DashboardService.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\ApprovalStatusEnum;
  4. use App\Enums\GenderEnum;
  5. use App\Enums\ServicePackageStatusEnum;
  6. use App\Enums\UserTypeEnum;
  7. use App\Models\Address;
  8. use App\Models\Client;
  9. use App\Models\ClientFavoriteProvider;
  10. use App\Models\ClientPaymentMethod;
  11. use App\Models\Notification;
  12. use App\Models\Provider;
  13. use App\Models\ProviderSpeciality;
  14. use App\Models\Review;
  15. use App\Models\Schedule;
  16. use App\Models\ScheduleProposal;
  17. use App\Models\ServicePackage;
  18. use App\Rules\ScheduleBusinessRules;
  19. use Illuminate\Auth\Access\AuthorizationException;
  20. use Illuminate\Support\Collection;
  21. use Illuminate\Support\Facades\Auth;
  22. use Illuminate\Support\Facades\DB;
  23. use Illuminate\Support\Facades\Storage;
  24. class DashboardService
  25. {
  26. public function __construct(
  27. private readonly CustomScheduleService $customScheduleService,
  28. private readonly ZipCodeCoordinatesService $zipCodeCoordinatesService,
  29. ) {}
  30. public function dadosDashboardCliente(): array
  31. {
  32. $user = Auth::user();
  33. if ($user->type !== UserTypeEnum::CLIENT) {
  34. throw new AuthorizationException(__('messages.only_clients_allowed'));
  35. }
  36. $cliente = Client::with('profileMedia')->where('user_id', $user->id)->first();
  37. $headerBar = [
  38. 'rating' => $cliente->average_rating,
  39. 'total_services' => $cliente->total_services,
  40. 'total_ratings' => Review::where('reviews.origin', 'provider')
  41. ->leftJoin('schedules', 'schedules.id', '=', 'reviews.schedule_id')
  42. ->where('schedules.client_id', $cliente->id)
  43. ->count(),
  44. ];
  45. $address = Address::where('source', 'client')
  46. ->where('source_id', $cliente->id)
  47. ->with(['city', 'state'])
  48. ->select('id', 'source', 'source_id', 'address', 'number', 'district', 'nickname', 'address_type', 'city_id', 'state_id', 'is_primary')
  49. ->first();
  50. $summaryInfos = [
  51. 'name' => $user->name,
  52. 'address' => $address,
  53. 'profile_photo' => $cliente->profileMedia?->path
  54. ? Storage::temporaryUrl($cliente->profileMedia->path, now()->addMinutes(60))
  55. : null,
  56. 'pending_services' => Schedule::where('client_id', $cliente->id)
  57. ->whereIn('status', ['pending', 'paid', 'accepted'])
  58. ->whereDate('date', '>=', now()->toDateString())
  59. ->count(),
  60. ];
  61. $nextSchedules = Schedule::with([
  62. 'address:district,address,source_id,source,id,address_type',
  63. ])
  64. ->where('schedules.client_id', $cliente->id)
  65. ->whereIn('schedules.status', ['accepted', 'paid'])
  66. ->whereDate('schedules.date', '>=', now()->toDateString())
  67. ->where('schedules.date', '>=', now()->toDateString())
  68. ->leftJoin('providers', 'providers.id', '=', 'schedules.provider_id')
  69. ->leftJoin('users as provider_user', 'provider_user.id', '=', 'providers.user_id')
  70. ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  71. ->select(
  72. 'schedules.id',
  73. 'schedules.provider_id',
  74. 'provider_user.name as provider_name',
  75. 'providers.gender',
  76. 'schedules.date',
  77. 'schedules.start_time',
  78. 'schedules.end_time',
  79. 'schedules.total_amount',
  80. 'schedules.period_type',
  81. 'schedules.schedule_type',
  82. 'schedules.address_id',
  83. 'custom_schedules.address_type as custom_address_type',
  84. DB::raw("
  85. (
  86. SELECT spi.service_package_id
  87. FROM service_package_items spi
  88. WHERE spi.schedule_id = schedules.id
  89. LIMIT 1
  90. ) AS service_package_id
  91. "),
  92. DB::raw("
  93. (
  94. SELECT COUNT(*)
  95. FROM service_package_items spi_count
  96. WHERE spi_count.service_package_id = (
  97. SELECT spi.service_package_id
  98. FROM service_package_items spi
  99. WHERE spi.schedule_id = schedules.id
  100. LIMIT 1
  101. )
  102. ) AS service_package_items_count
  103. "),
  104. )
  105. ->orderBy('schedules.date', 'asc')
  106. ->limit(5)
  107. ->get();
  108. $nextSchedules->each(function ($item) {
  109. $item->gender_label = GenderEnum::labelFor($item->gender);
  110. });
  111. $latestPerProvider = Schedule::where('client_id', $cliente->id)
  112. ->where('status', 'finished')
  113. ->select('provider_id', DB::raw('MAX(id) as max_id'))
  114. ->groupBy('provider_id');
  115. $lastDoneSchedules = Schedule::joinSub($latestPerProvider, 'latest', function ($join) {
  116. $join->on('schedules.id', '=', 'latest.max_id');
  117. })
  118. ->leftJoin('providers', 'providers.id', '=', 'schedules.provider_id')
  119. ->leftJoin('users as provider_user', 'provider_user.id', '=', 'providers.user_id')
  120. ->leftJoinSub(
  121. Address::preferredForProvider(),
  122. 'provider_address',
  123. fn($join) =>
  124. $join->on('provider_address.source_id', '=', 'providers.id')
  125. ->where('provider_address.rn', 1)
  126. )
  127. ->select(
  128. 'schedules.id',
  129. 'schedules.provider_id',
  130. 'provider_user.name as provider_name',
  131. 'providers.gender',
  132. 'provider_address.district as provider_district',
  133. )
  134. ->orderBy('schedules.date', 'desc')
  135. ->limit(5)
  136. ->get();
  137. $lastDoneSchedules->each(function ($item) {
  138. $item->gender_label = GenderEnum::labelFor($item->gender);
  139. });
  140. $favoriteProviders = ClientFavoriteProvider::where('client_favorite_providers.client_id', $cliente->id)
  141. ->leftJoin('providers', 'providers.id', '=', 'client_favorite_providers.provider_id')
  142. ->whereNotNull('providers.recipient_default_bank_account')
  143. ->whereRaw("providers.recipient_default_bank_account::text <> '{}'")
  144. ->whereRaw("providers.recipient_default_bank_account::text <> '[]'")
  145. ->leftJoin('users as provider_user', 'provider_user.id', '=', 'providers.user_id')
  146. ->leftJoinSub(
  147. Address::preferredForProvider(),
  148. 'provider_address',
  149. fn($join) =>
  150. $join->on('provider_address.source_id', '=', 'providers.id')
  151. ->where('provider_address.rn', 1)
  152. )
  153. ->select(
  154. 'providers.id as provider_id',
  155. 'provider_user.name as provider_name',
  156. 'providers.gender',
  157. 'providers.average_rating',
  158. 'provider_address.district as provider_district',
  159. )
  160. ->orderBy('client_favorite_providers.created_at', 'desc')
  161. ->limit(5)
  162. ->get();
  163. $favoriteProviders->each(function ($item) {
  164. $item->gender_label = GenderEnum::labelFor($item->gender);
  165. });
  166. $blockedProviderIds = ScheduleBusinessRules::getBlockedProviderIdsForClient($cliente->id);
  167. $providersWithWorkingDays = ScheduleBusinessRules::getProviderIdsWithWorkingDays();
  168. $clientPrimaryAddress = Address::where('source', 'client')
  169. ->where('source_id', $cliente->id)
  170. ->orderByDesc('is_primary')
  171. ->orderByDesc('id')
  172. ->first();
  173. $clientDistanceAddress = $this->addressForDistance($cliente->id, $clientPrimaryAddress);
  174. $clientCoordinates = $this->zipCodeCoordinatesService->resolve(
  175. $clientDistanceAddress?->latitude !== null ? (float) $clientDistanceAddress->latitude : null,
  176. $clientDistanceAddress?->longitude !== null ? (float) $clientDistanceAddress->longitude : null,
  177. $clientDistanceAddress?->zip_code,
  178. );
  179. $providersCloseDistanceSelect = $this->distanceSelect(
  180. data_get($clientCoordinates, 'latitude'),
  181. data_get($clientCoordinates, 'longitude'),
  182. );
  183. $providerAddressLatestSubquery = DB::raw("
  184. (
  185. SELECT DISTINCT ON (source_id)
  186. *
  187. FROM addresses
  188. WHERE
  189. source = 'provider'
  190. AND deleted_at IS NULL
  191. ORDER BY
  192. source_id,
  193. (latitude IS NOT NULL AND longitude IS NOT NULL) DESC,
  194. is_primary DESC,
  195. id DESC
  196. ) AS provider_address
  197. ");
  198. $providersClose = Provider::leftJoin(
  199. 'users as provider_user',
  200. 'provider_user.id',
  201. '=',
  202. 'providers.user_id'
  203. )
  204. ->visibleToCustomers()
  205. ->leftJoin(
  206. $providerAddressLatestSubquery,
  207. 'provider_address.source_id',
  208. '=',
  209. 'providers.id'
  210. )
  211. ->whereNotNull('provider_address.id')
  212. ->when(
  213. $clientPrimaryAddress?->city_id,
  214. fn($query, int $cityId) => $query->where('provider_address.city_id', $cityId)
  215. )
  216. ->whereNotIn('providers.id', $blockedProviderIds)
  217. ->whereIn('providers.id', $providersWithWorkingDays)
  218. ->whereNull('providers.deleted_at')
  219. ->select(
  220. 'providers.id as provider_id',
  221. 'provider_user.name as provider_name',
  222. 'providers.gender',
  223. 'provider_address.id as address_id',
  224. 'provider_address.zip_code as provider_zip_code',
  225. 'provider_address.district',
  226. 'provider_address.latitude as provider_latitude',
  227. 'provider_address.longitude as provider_longitude',
  228. 'providers.average_rating',
  229. 'providers.total_services',
  230. 'providers.daily_price_8h',
  231. 'providers.daily_price_6h',
  232. 'providers.daily_price_4h',
  233. 'providers.daily_price_2h',
  234. DB::raw("
  235. (
  236. SELECT COUNT(*)
  237. FROM reviews
  238. LEFT JOIN schedules
  239. ON schedules.id = reviews.schedule_id
  240. WHERE reviews.origin = 'provider'
  241. AND schedules.provider_id = providers.id
  242. ) AS total_reviews
  243. "),
  244. $providersCloseDistanceSelect,
  245. )
  246. ->orderByRaw('distance_km ASC NULLS LAST')
  247. ->get();
  248. $this->zipCodeCoordinatesService->preload(
  249. $providersClose->whereNull('distance_km')->pluck('provider_zip_code')
  250. );
  251. $providersClose->each(function ($item) use ($clientDistanceAddress) {
  252. $item->gender_label = GenderEnum::labelFor($item->gender);
  253. if ($item->distance_km === null) {
  254. $item->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
  255. $clientDistanceAddress?->latitude !== null ? (float) $clientDistanceAddress->latitude : null,
  256. $clientDistanceAddress?->longitude !== null ? (float) $clientDistanceAddress->longitude : null,
  257. $clientDistanceAddress?->zip_code,
  258. $item->provider_latitude !== null ? (float) $item->provider_latitude : null,
  259. $item->provider_longitude !== null ? (float) $item->provider_longitude : null,
  260. $item->provider_zip_code,
  261. );
  262. }
  263. $item->specialities = ProviderSpeciality::query()
  264. ->join('specialities', 'specialities.id', '=', 'provider_specialities.speciality_id')
  265. ->where('provider_specialities.provider_id', $item->provider_id)
  266. ->where('specialities.active', true)
  267. ->orderBy('specialities.description')
  268. ->get([
  269. 'specialities.id',
  270. 'specialities.description',
  271. ]);
  272. $item->age = Provider::query()
  273. ->where('id', $item->provider_id)
  274. ->value(DB::raw("DATE_PART('year', AGE(birth_date))"));
  275. unset($item->provider_zip_code);
  276. $item->daily_price_8h_base = $item->daily_price_8h;
  277. $item->daily_price_6h_base = $item->daily_price_6h;
  278. $item->daily_price_4h_base = $item->daily_price_4h;
  279. $item->daily_price_2h_base = $item->daily_price_2h;
  280. $item->daily_price_8h = $this->applyCreditCardFee($item->daily_price_8h);
  281. $item->daily_price_6h = $this->applyCreditCardFee($item->daily_price_6h);
  282. $item->daily_price_4h = $this->applyCreditCardFee($item->daily_price_4h);
  283. $item->daily_price_2h = $this->applyCreditCardFee($item->daily_price_2h);
  284. });
  285. $providersClose = $providersClose
  286. ->sortBy(fn($provider) => $provider->distance_km ?? PHP_FLOAT_MAX)
  287. ->sortBy(fn($provider) => $provider->distance_km ?? PHP_FLOAT_MAX)
  288. ->values();
  289. $pendingSchedules = Schedule::with([
  290. 'address:district,address,number,source_id,source,id,address_type',
  291. ])
  292. ->where('schedules.client_id', $cliente->id)
  293. ->whereIn('schedules.status', ['pending', 'accepted'])
  294. ->where('schedules.schedule_type', 'default')
  295. ->leftJoin('providers', 'providers.id', '=', 'schedules.provider_id')
  296. ->leftJoin('users as provider_user', 'provider_user.id', '=', 'providers.user_id')
  297. ->select(
  298. 'schedules.id',
  299. 'schedules.provider_id',
  300. 'provider_user.name as provider_name',
  301. 'providers.gender',
  302. 'schedules.date',
  303. 'schedules.address_id',
  304. 'schedules.status',
  305. 'schedules.total_amount',
  306. 'schedules.start_time',
  307. 'schedules.end_time',
  308. DB::raw("
  309. CASE
  310. WHEN (NOW() - schedules.created_at) < INTERVAL '1 hour' THEN
  311. CONCAT(
  312. ROUND(EXTRACT(EPOCH FROM (NOW() - schedules.created_at)) / 60),
  313. 'min'
  314. )
  315. WHEN (NOW() - schedules.created_at) < INTERVAL '1 day' THEN
  316. CONCAT(
  317. ROUND(EXTRACT(EPOCH FROM (NOW() - schedules.created_at)) / 3600),
  318. 'h'
  319. )
  320. ELSE
  321. CONCAT(
  322. ROUND(EXTRACT(EPOCH FROM (NOW() - schedules.created_at)) / 86400),
  323. 'd'
  324. )
  325. END AS time_since_request
  326. "),
  327. DB::raw("
  328. (
  329. SELECT spi.service_package_id
  330. FROM service_package_items spi
  331. WHERE spi.schedule_id = schedules.id
  332. LIMIT 1
  333. ) AS service_package_id
  334. "),
  335. DB::raw("
  336. (
  337. SELECT COUNT(*)
  338. FROM service_package_items spi_count
  339. WHERE spi_count.service_package_id = (
  340. SELECT spi.service_package_id
  341. FROM service_package_items spi
  342. WHERE spi.schedule_id = schedules.id
  343. LIMIT 1
  344. )
  345. ) AS service_package_items_count
  346. "),
  347. )
  348. ->orderBy('schedules.date', 'asc')
  349. ->get();
  350. $pendingSchedules->each(function ($item) {
  351. $item->gender_label = GenderEnum::labelFor($item->gender);
  352. });
  353. $proposalsDistanceSelect = DistanceService::sqlExpression(
  354. data_get($clientCoordinates, 'latitude'),
  355. data_get($clientCoordinates, 'longitude'),
  356. );
  357. $schedulesProposals = ScheduleProposal::query()
  358. ->leftJoin(
  359. 'schedules',
  360. 'schedule_proposals.schedule_id',
  361. '=',
  362. 'schedules.id'
  363. )
  364. ->leftJoin(
  365. 'providers',
  366. 'schedule_proposals.provider_id',
  367. '=',
  368. 'providers.id'
  369. )
  370. ->whereNotNull('providers.recipient_default_bank_account')
  371. ->whereRaw("providers.recipient_default_bank_account::text <> '{}'")
  372. ->whereRaw("providers.recipient_default_bank_account::text <> '[]'")
  373. ->leftJoin('users', 'providers.user_id', '=', 'users.id')
  374. ->leftJoin(
  375. DB::raw("
  376. (
  377. SELECT DISTINCT ON (source_id)
  378. *
  379. FROM addresses
  380. WHERE source = 'provider'
  381. AND deleted_at IS NULL
  382. ORDER BY source_id, is_primary DESC
  383. ) AS provider_address
  384. "),
  385. 'provider_address.source_id',
  386. '=',
  387. 'providers.id'
  388. )
  389. ->where('schedules.client_id', $cliente->id)
  390. ->where('schedules.schedule_type', 'custom')
  391. ->where('schedules.status', 'pending')
  392. ->whereNull('schedules.deleted_at')
  393. ->whereDate('schedules.date', '>=', now()->toDateString())
  394. ->orderBy('schedule_proposals.created_at', 'desc')
  395. ->select([
  396. 'schedule_proposals.id',
  397. DB::raw("
  398. DATE_PART('year', AGE(providers.birth_date)) AS idade
  399. "),
  400. 'providers.id as provider_id',
  401. 'providers.gender',
  402. 'schedules.id as schedule_id',
  403. 'schedules.date',
  404. 'schedules.start_time',
  405. 'schedules.end_time',
  406. 'schedules.period_type',
  407. 'schedules.total_amount',
  408. 'providers.daily_price_8h',
  409. 'providers.average_rating',
  410. 'providers.total_services',
  411. 'users.name as provider_name',
  412. 'provider_address.latitude as provider_latitude',
  413. 'provider_address.longitude as provider_longitude',
  414. 'provider_address.zip_code as provider_zip_code',
  415. $proposalsDistanceSelect,
  416. ])
  417. ->get();
  418. $this->zipCodeCoordinatesService->preload(
  419. $schedulesProposals->whereNull('distance_km')->pluck('provider_zip_code')
  420. );
  421. $custom_schedules_with_no_proposals = Schedule::where('client_id', $cliente->id)
  422. ->where('schedule_type', 'custom')
  423. ->where('status', 'pending')
  424. ->whereDate('date', '>=', now()->toDateString())
  425. ->doesntHave('proposals')
  426. ->get();
  427. $schedulesProposals->each(function ($item) use ($clientDistanceAddress) {
  428. $item->gender_label = GenderEnum::labelFor($item->gender);
  429. if ($item->distance_km === null) {
  430. $item->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
  431. $clientDistanceAddress?->latitude !== null ? (float) $clientDistanceAddress->latitude : null,
  432. $clientDistanceAddress?->longitude !== null ? (float) $clientDistanceAddress->longitude : null,
  433. $clientDistanceAddress?->zip_code,
  434. $item->provider_latitude !== null ? (float) $item->provider_latitude : null,
  435. $item->provider_longitude !== null ? (float) $item->provider_longitude : null,
  436. $item->provider_zip_code,
  437. );
  438. }
  439. unset(
  440. $item->provider_latitude,
  441. $item->provider_longitude,
  442. $item->provider_zip_code,
  443. );
  444. });
  445. $todaySchedules = Schedule::with([
  446. 'address:district,address,number,source_id,source,id,address_type',
  447. ])
  448. ->where('schedules.client_id', $cliente->id)
  449. ->whereIn('schedules.status', ['accepted', 'paid', 'started', 'cancelled', 'finished'])
  450. ->whereDate('schedules.date', now()->toDateString())
  451. ->leftJoin('providers', 'providers.id', '=', 'schedules.provider_id')
  452. ->leftJoin('users as provider_user', 'provider_user.id', '=', 'providers.user_id')
  453. ->select(
  454. 'schedules.id',
  455. 'schedules.provider_id',
  456. 'provider_user.name as provider_name',
  457. 'providers.gender',
  458. 'schedules.date',
  459. 'schedules.start_time',
  460. 'schedules.end_time',
  461. 'schedules.total_amount',
  462. 'schedules.period_type',
  463. 'schedules.schedule_type',
  464. 'schedules.address_id',
  465. 'schedules.status',
  466. 'schedules.code_verified',
  467. 'schedules.code',
  468. DB::raw("
  469. (
  470. SELECT spi.service_package_id
  471. FROM service_package_items spi
  472. WHERE spi.schedule_id = schedules.id
  473. LIMIT 1
  474. ) AS service_package_id
  475. "),
  476. DB::raw("
  477. (
  478. SELECT COUNT(*)
  479. FROM service_package_items spi_count
  480. WHERE spi_count.service_package_id = (
  481. SELECT spi.service_package_id
  482. FROM service_package_items spi
  483. WHERE spi.schedule_id = schedules.id
  484. LIMIT 1
  485. )
  486. ) AS service_package_items_count
  487. "),
  488. DB::raw("
  489. EXISTS (
  490. SELECT 1
  491. FROM reviews
  492. WHERE reviews.schedule_id = schedules.id
  493. AND reviews.origin = 'client'
  494. AND reviews.origin_id = {$cliente->id}
  495. AND reviews.deleted_at IS NULL
  496. ) AS client_reviewed
  497. "),
  498. )
  499. ->orderBy('schedules.start_time', 'asc')
  500. ->get()
  501. ->map(function ($item) {
  502. $item->gender_label = GenderEnum::labelFor($item->gender);
  503. return $item;
  504. });
  505. $providerCollections = collect([
  506. $nextSchedules,
  507. $lastDoneSchedules,
  508. $favoriteProviders,
  509. $providersClose,
  510. $pendingSchedules,
  511. $schedulesProposals,
  512. $todaySchedules,
  513. ]);
  514. $providerPhotoUrls = $this->providerPhotoUrls(
  515. $providerCollections->flatMap(
  516. fn(Collection $items) => $items->pluck('provider_id'),
  517. ),
  518. );
  519. $providerCollections->each(function (Collection $items) use ($providerPhotoUrls) {
  520. $items->each(function ($item) use ($providerPhotoUrls) {
  521. $item->provider_photo = $providerPhotoUrls->get($item->provider_id);
  522. });
  523. });
  524. $notifications = Notification::where('user_id', $user->id)
  525. ->orderBy('read', 'asc')
  526. ->orderBy('created_at', 'desc')
  527. ->limit(10)
  528. ->get()
  529. ->map(function ($notification) {
  530. return [
  531. 'id' => $notification->id,
  532. 'title' => $notification->title,
  533. 'description' => $notification->description,
  534. 'time' => $notification->created_at->diffForHumans(),
  535. 'read' => $notification->read,
  536. 'avatar' => '/icons/avatar.svg',
  537. ];
  538. });
  539. $hasPaymentMethods = ClientPaymentMethod::where('client_id', $cliente->id)->exists();
  540. $pendingServicePackages = ServicePackage::query()
  541. ->where('client_id', $cliente->id)
  542. ->where('status', ServicePackageStatusEnum::OPEN->value)
  543. ->whereDoesntHave('items.schedule', fn($q) => $q->where('status', '!=', 'accepted'))
  544. ->with(['items.schedule' => function ($query) {
  545. $query->with(['provider.user', 'address']);
  546. }])
  547. ->with('provider.user')
  548. ->get();
  549. return [
  550. 'headerBar' => $headerBar,
  551. 'summaryInfos' => $summaryInfos,
  552. 'pendingSchedules' => $pendingSchedules,
  553. 'nextSchedules' => $nextSchedules,
  554. 'lastDoneSchedules' => $lastDoneSchedules,
  555. 'favoriteProviders' => $favoriteProviders,
  556. 'providersClose' => $providersClose,
  557. 'todaySchedules' => $todaySchedules,
  558. 'schedulesProposals' => $schedulesProposals,
  559. 'customSchedulesNoProposals' => $custom_schedules_with_no_proposals,
  560. 'notifications' => $notifications,
  561. 'has_payment_methods' => $hasPaymentMethods,
  562. 'pendingServicePackages' => $pendingServicePackages,
  563. ];
  564. }
  565. public function dadosDashboardPrestador(): array
  566. {
  567. $user = Auth::user();
  568. if ($user->type !== UserTypeEnum::PROVIDER) {
  569. throw new AuthorizationException(__('messages.only_providers_allowed'));
  570. }
  571. $provider = Provider::with('profileMedia')->where('user_id', $user->id)->first();
  572. $headerBar = [
  573. 'rating' => $provider->average_rating,
  574. 'total_ratings' => Review::where('reviews.origin', 'client')->leftJoin('schedules', 'schedules.id', '=', 'reviews.schedule_id')->where('schedules.provider_id', $provider->id)->count(),
  575. 'total_services' => $provider->total_services,
  576. ];
  577. $address = Address::where('source', 'provider')->where('source_id', $provider->id)->with(['city', 'state'])->first();
  578. $summaryInfos = [
  579. 'name' => $user->name,
  580. 'address' => $address,
  581. 'pending_services' => Schedule::where('provider_id', $provider->id)->where('status', 'pending')->count(),
  582. 'profile_photo' => $provider->profileMedia?->path
  583. ? Storage::temporaryUrl($provider->profileMedia->path, now()->addMinutes(60))
  584. : null,
  585. ];
  586. if ($provider->approval_status === ApprovalStatusEnum::PENDING) {
  587. return [
  588. 'headerBar' => $headerBar,
  589. 'summaryInfos' => $summaryInfos,
  590. 'priceSuggested' => null,
  591. 'todayServices' => [],
  592. 'solicitations' => [],
  593. 'nextSchedules' => [],
  594. 'opportunities' => [],
  595. 'notifications' => [],
  596. 'pendingConfirmation' => [],
  597. ];
  598. }
  599. $priceSuggestedAvg = Provider::where('user_id', '!=', $user->id)
  600. ->whereNotNull('daily_price_8h')
  601. ->pluck('daily_price_8h')
  602. ->avg();
  603. $priceActual = $provider->daily_price_8h;
  604. $priceSuggested = [
  605. 'average_price' => $priceSuggestedAvg,
  606. 'your_price' => $priceActual,
  607. ];
  608. $solicitations = Schedule::with([
  609. 'address:district,source_id,source,id,zip_code,latitude,longitude',
  610. 'customSchedule.specialities',
  611. ])
  612. ->where('schedules.provider_id', $provider->id)
  613. ->where('schedules.status', 'pending')
  614. ->leftJoin('clients', 'clients.id', '=', 'schedules.client_id')
  615. ->leftJoin('users as client_user', 'client_user.id', '=', 'clients.user_id')
  616. ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  617. ->select(
  618. 'schedules.id',
  619. 'schedules.client_id',
  620. 'client_user.name as client_name',
  621. 'clients.average_rating',
  622. 'schedules.date',
  623. DB::raw("
  624. TO_CHAR(schedules.date, 'DD/MM/YYYY') AS formatted_date
  625. "),
  626. 'schedules.start_time',
  627. 'schedules.end_time',
  628. 'schedules.total_amount',
  629. 'schedules.period_type',
  630. 'schedules.schedule_type',
  631. 'schedules.address_id',
  632. 'schedules.status',
  633. 'custom_schedules.offers_meal',
  634. DB::raw("
  635. CASE
  636. WHEN (NOW() - schedules.created_at) < INTERVAL '1 day' THEN
  637. CONCAT(
  638. ROUND(
  639. EXTRACT(
  640. EPOCH FROM (NOW() - schedules.created_at)
  641. ) / 3600
  642. ),
  643. ' hours ago'
  644. )
  645. ELSE
  646. CONCAT(
  647. ROUND(
  648. EXTRACT(
  649. EPOCH FROM (NOW() - schedules.created_at)
  650. ) / 86400
  651. ),
  652. ' days ago'
  653. )
  654. END AS time_since_request
  655. "),
  656. DB::raw("
  657. (
  658. SELECT service_package_items.service_package_id
  659. FROM service_package_items
  660. WHERE service_package_items.schedule_id = schedules.id
  661. LIMIT 1
  662. ) AS service_package_id
  663. "),
  664. )
  665. ->orderBy('schedules.date', 'asc')
  666. ->get()
  667. ->append('specialities')
  668. ->makeHidden('customSchedule');
  669. $solicitations->each(function ($solicitation) use ($address) {
  670. $solicitation->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
  671. $address?->latitude !== null ? (float) $address->latitude : null,
  672. $address?->longitude !== null ? (float) $address->longitude : null,
  673. $address?->zip_code,
  674. $solicitation->address?->latitude !== null ? (float) $solicitation->address->latitude : null,
  675. $solicitation->address?->longitude !== null ? (float) $solicitation->address->longitude : null,
  676. $solicitation->address?->zip_code,
  677. );
  678. });
  679. $todayServices = Schedule::with([
  680. 'address:district,address,number,source_id,source,id',
  681. ])
  682. ->where('schedules.provider_id', $provider->id)
  683. ->whereIn('schedules.status', ['accepted', 'paid', 'started', 'finished'])
  684. ->whereDate('schedules.date', now()->toDateString())
  685. ->leftJoin('clients', 'clients.id', '=', 'schedules.client_id')
  686. ->leftJoin('users as client_user', 'client_user.id', '=', 'clients.user_id')
  687. ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  688. ->select(
  689. 'schedules.id',
  690. 'schedules.client_id',
  691. 'client_user.name as client_name',
  692. 'schedules.date',
  693. 'schedules.start_time',
  694. 'schedules.end_time',
  695. 'schedules.total_amount',
  696. 'schedules.period_type',
  697. 'schedules.address_id',
  698. 'schedules.schedule_type',
  699. 'schedules.status',
  700. 'schedules.code_verified',
  701. 'schedules.code',
  702. 'custom_schedules.offers_meal',
  703. DB::raw("
  704. EXISTS (
  705. SELECT 1
  706. FROM reviews
  707. WHERE reviews.schedule_id = schedules.id
  708. AND reviews.origin = 'provider'
  709. AND reviews.origin_id = {$provider->id}
  710. AND reviews.deleted_at IS NULL
  711. ) AS provider_reviewed
  712. "),
  713. DB::raw("
  714. (
  715. SELECT service_package_items.service_package_id
  716. FROM service_package_items
  717. WHERE service_package_items.schedule_id = schedules.id
  718. LIMIT 1
  719. ) AS service_package_id
  720. "),
  721. )
  722. ->orderBy('schedules.start_time', 'asc')
  723. ->get();
  724. $pendingConfirmation = Schedule::with(
  725. 'address:district,address,number,source_id,source,id,zip_code,latitude,longitude'
  726. )
  727. ->where('schedules.provider_id', $provider->id)
  728. ->where('schedules.status', 'accepted')
  729. ->whereDate('schedules.date', '>=', now()->toDateString())
  730. ->leftJoin('clients', 'clients.id', '=', 'schedules.client_id')
  731. ->leftJoin('users as client_user', 'client_user.id', '=', 'clients.user_id')
  732. ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  733. ->select(
  734. 'schedules.id',
  735. 'schedules.client_id',
  736. 'client_user.name as client_name',
  737. 'schedules.date',
  738. 'schedules.start_time',
  739. 'schedules.end_time',
  740. 'schedules.total_amount',
  741. 'schedules.period_type',
  742. 'schedules.address_id',
  743. 'schedules.schedule_type',
  744. 'schedules.status',
  745. 'custom_schedules.offers_meal',
  746. DB::raw("
  747. (
  748. SELECT service_package_items.service_package_id
  749. FROM service_package_items
  750. WHERE service_package_items.schedule_id = schedules.id
  751. LIMIT 1
  752. ) AS service_package_id
  753. "),
  754. )
  755. ->orderBy('schedules.date', 'asc')
  756. ->get();
  757. $pendingConfirmation->each(function ($schedule) use ($address) {
  758. $schedule->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
  759. $address?->latitude !== null ? (float) $address->latitude : null,
  760. $address?->longitude !== null ? (float) $address->longitude : null,
  761. $address?->zip_code,
  762. $schedule->address?->latitude !== null ? (float) $schedule->address->latitude : null,
  763. $schedule->address?->longitude !== null ? (float) $schedule->address->longitude : null,
  764. $schedule->address?->zip_code,
  765. );
  766. });
  767. $nextSchedules = Schedule::with('address:district,address,number,source_id,source,id,zip_code,latitude,longitude')
  768. ->where('schedules.provider_id', $provider->id)
  769. ->where('schedules.status', 'paid')
  770. ->whereDate('schedules.date', '>=', now()->toDateString())
  771. ->leftJoin('clients', 'clients.id', '=', 'schedules.client_id')
  772. ->leftJoin('users as client_user', 'client_user.id', '=', 'clients.user_id')
  773. ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  774. ->select(
  775. 'schedules.id',
  776. 'schedules.client_id',
  777. 'client_user.name as client_name',
  778. 'schedules.date',
  779. 'schedules.start_time',
  780. 'schedules.end_time',
  781. 'schedules.total_amount',
  782. 'schedules.period_type',
  783. 'schedules.address_id',
  784. 'schedules.schedule_type',
  785. 'schedules.status',
  786. 'custom_schedules.offers_meal',
  787. DB::raw("
  788. (
  789. SELECT service_package_items.service_package_id
  790. FROM service_package_items
  791. WHERE service_package_items.schedule_id = schedules.id
  792. LIMIT 1
  793. ) AS service_package_id
  794. "),
  795. )
  796. ->orderBy('schedules.date', 'asc')
  797. ->get();
  798. $nextSchedules->each(function ($schedule) use ($address) {
  799. $schedule->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
  800. $address?->latitude !== null ? (float) $address->latitude : null,
  801. $address?->longitude !== null ? (float) $address->longitude : null,
  802. $address?->zip_code,
  803. $schedule->address?->latitude !== null ? (float) $schedule->address->latitude : null,
  804. $schedule->address?->longitude !== null ? (float) $schedule->address->longitude : null,
  805. $schedule->address?->zip_code,
  806. );
  807. });
  808. $clientCollections = collect([
  809. $solicitations,
  810. $todayServices,
  811. $pendingConfirmation,
  812. $nextSchedules
  813. ]);
  814. $clientPhotoUrls = $this->clientPhotoUrls(
  815. $clientCollections->flatMap(
  816. fn(Collection $items) => $items->pluck('client_id'),
  817. ),
  818. );
  819. $clientCollections->each(function (Collection $items) use ($clientPhotoUrls) {
  820. $items->each(function ($item) use ($clientPhotoUrls) {
  821. $item->customer_photo = $clientPhotoUrls->get($item->client_id);
  822. });
  823. });
  824. $notifications = Notification::where('user_id', $user->id)
  825. ->orderBy('read', 'asc')
  826. ->orderBy('created_at', 'desc')
  827. ->limit(10)
  828. ->get()
  829. ->map(function ($notification) {
  830. return [
  831. 'id' => $notification->id,
  832. 'title' => $notification->title,
  833. 'description' => $notification->description,
  834. 'time' => $notification->created_at->diffForHumans(),
  835. 'read' => $notification->read,
  836. 'avatar' => '/icons/avatar.svg',
  837. ];
  838. });
  839. $opportunities = $this->customScheduleService->getAvailableOpportunities($provider->id);
  840. $opportunities->each(function ($o) {
  841. $o->customer_photo = $o->client?->profileMedia?->path
  842. ? Storage::temporaryUrl($o->client->profileMedia->path, now()->addMinutes(60))
  843. : null;
  844. });
  845. return [
  846. 'headerBar' => $headerBar,
  847. 'summaryInfos' => $summaryInfos,
  848. 'priceSuggested' => $priceSuggested,
  849. 'solicitations' => $solicitations,
  850. 'todayServices' => $todayServices,
  851. 'pendingConfirmation' => $pendingConfirmation,
  852. 'nextSchedules' => $nextSchedules,
  853. 'opportunities' => $opportunities,
  854. 'notifications' => $notifications,
  855. ];
  856. }
  857. public function getScheduleClienteDetails(int $scheduleId): array
  858. {
  859. $user = Auth::user();
  860. $cliente = Client::where('user_id', $user->id)->firstOrFail();
  861. $schedule = Schedule::with('customSchedule.specialities')
  862. ->where('schedules.id', $scheduleId)
  863. ->where('schedules.client_id', $cliente->id)
  864. ->leftJoin('providers', 'providers.id', '=', 'schedules.provider_id')
  865. ->leftJoin('users as provider_user', 'provider_user.id', '=', 'providers.user_id')
  866. ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  867. ->select(
  868. 'schedules.id',
  869. 'schedules.provider_id',
  870. 'schedules.schedule_type',
  871. 'provider_user.name as provider_name',
  872. 'providers.birth_date as provider_birth_date',
  873. 'providers.gender',
  874. 'custom_schedules.offers_meal',
  875. )
  876. ->firstOrFail();
  877. $providerPhoto = $this->providerPhotoUrls([$schedule->provider_id])
  878. ->get($schedule->provider_id);
  879. return [
  880. 'schedule_type' => $schedule->schedule_type,
  881. 'provider_name' => $schedule->provider_name,
  882. 'provider_birth_date' => $schedule->provider_birth_date,
  883. 'gender' => $schedule->gender,
  884. 'gender_label' => GenderEnum::labelFor($schedule->gender),
  885. 'offers_meal' => $schedule->offers_meal,
  886. 'specialities' => $schedule->specialities,
  887. 'provider_photo' => $providerPhoto,
  888. ];
  889. }
  890. // gera urls apenas para fotos verificadas ou visiveis ao proprio prestador.
  891. private function providerPhotoUrls(iterable $providerIds): Collection
  892. {
  893. return Provider::query()
  894. ->select('id', 'profile_media_id')
  895. ->with('profileMedia')
  896. ->whereIn('id', collect($providerIds)->filter()->unique())
  897. ->get()
  898. ->mapWithKeys(function (Provider $provider) {
  899. $path = $provider->profileMedia?->path;
  900. return [
  901. $provider->id => $path ? Storage::temporaryUrl($path, now()->addMinutes(60)) : null,
  902. ];
  903. });
  904. }
  905. // Gera URLs apenas para fotos verificadas ou visíveis ao próprio cliente.
  906. private function clientPhotoUrls(iterable $clientIds): Collection
  907. {
  908. return Client::query()
  909. ->select('id', 'profile_media_id')
  910. ->with('profileMedia')
  911. ->whereIn('id', collect($clientIds)->filter()->unique())
  912. ->get()
  913. ->mapWithKeys(function (Client $client) {
  914. $path = $client->profileMedia?->path;
  915. return [
  916. $client->id => $path ? Storage::temporaryUrl($path, now()->addMinutes(60)) : null,
  917. ];
  918. });
  919. }
  920. //
  921. private function applyCreditCardFee(?float $price): ?float
  922. {
  923. if ($price === null) {
  924. return null;
  925. }
  926. $rate = $this->platformCreditCardFeeRate();
  927. return round($price * (1 + $rate), 2);
  928. }
  929. private function platformCreditCardFeeRate(): float
  930. {
  931. $rate = config('services.pagarme.platform_credit_card_fee_rate', 0.16);
  932. if (is_string($rate)) {
  933. $rate = str_replace(',', '.', trim($rate));
  934. }
  935. $rate = (float) $rate;
  936. return $rate > 1 ? $rate / 100 : $rate;
  937. }
  938. //
  939. private function addressForDistance(int $clientId, ?Address $primaryAddress): ?Address
  940. {
  941. if ($primaryAddress?->latitude !== null && $primaryAddress?->longitude !== null) {
  942. return $primaryAddress;
  943. }
  944. return Address::where('source', 'client')
  945. ->where('source_id', $clientId)
  946. ->whereNotNull('latitude')
  947. ->whereNotNull('longitude')
  948. ->orderByDesc('is_primary')
  949. ->orderByDesc('id')
  950. ->first() ?? $primaryAddress;
  951. }
  952. private function distanceSelect(?float $clientLatitude, ?float $clientLongitude): \Illuminate\Contracts\Database\Query\Expression
  953. {
  954. return DistanceService::sqlExpression($clientLatitude, $clientLongitude);
  955. }
  956. }