DashboardService.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  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. ->where('schedules.status', 'paid')
  66. ->whereDate('schedules.date', '>=', now()->toDateString())
  67. ->leftJoin('providers', 'providers.id', '=', 'schedules.provider_id')
  68. ->leftJoin('users as provider_user', 'provider_user.id', '=', 'providers.user_id')
  69. ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  70. ->select(
  71. 'schedules.id',
  72. 'schedules.provider_id',
  73. 'provider_user.name as provider_name',
  74. 'providers.gender',
  75. 'schedules.date',
  76. 'schedules.start_time',
  77. 'schedules.end_time',
  78. 'schedules.total_amount',
  79. 'schedules.period_type',
  80. 'schedules.schedule_type',
  81. 'schedules.address_id',
  82. 'custom_schedules.address_type as custom_address_type',
  83. DB::raw("
  84. (
  85. SELECT spi.service_package_id
  86. FROM service_package_items spi
  87. WHERE spi.schedule_id = schedules.id
  88. LIMIT 1
  89. ) AS service_package_id
  90. "),
  91. DB::raw("
  92. (
  93. SELECT COUNT(*)
  94. FROM service_package_items spi_count
  95. JOIN schedules s_count ON s_count.id = spi_count.schedule_id
  96. AND s_count.status NOT IN ('cancelled', 'rejected')
  97. AND s_count.schedule_type = 'default'
  98. WHERE spi_count.service_package_id = (
  99. SELECT spi.service_package_id
  100. FROM service_package_items spi
  101. WHERE spi.schedule_id = schedules.id
  102. LIMIT 1
  103. )
  104. ) AS service_package_items_count
  105. "),
  106. )
  107. ->orderBy('schedules.date', 'asc')
  108. ->limit(5)
  109. ->get();
  110. $nextSchedules->each(function ($item) {
  111. $item->gender_label = GenderEnum::labelFor($item->gender);
  112. });
  113. $latestPerProvider = Schedule::where('client_id', $cliente->id)
  114. ->where('status', 'finished')
  115. ->select('provider_id', DB::raw('MAX(id) as max_id'))
  116. ->groupBy('provider_id');
  117. $lastDoneSchedules = Schedule::joinSub($latestPerProvider, 'latest', function ($join) {
  118. $join->on('schedules.id', '=', 'latest.max_id');
  119. })
  120. ->leftJoin('providers', 'providers.id', '=', 'schedules.provider_id')
  121. ->leftJoin('users as provider_user', 'provider_user.id', '=', 'providers.user_id')
  122. ->leftJoinSub(
  123. Address::preferredForProvider(),
  124. 'provider_address',
  125. fn($join) =>
  126. $join->on('provider_address.source_id', '=', 'providers.id')
  127. ->where('provider_address.rn', 1)
  128. )
  129. ->select(
  130. 'schedules.id',
  131. 'schedules.provider_id',
  132. 'provider_user.name as provider_name',
  133. 'providers.gender',
  134. 'provider_address.district as provider_district',
  135. )
  136. ->orderBy('schedules.date', 'desc')
  137. ->limit(5)
  138. ->get();
  139. $lastDoneSchedules->each(function ($item) {
  140. $item->gender_label = GenderEnum::labelFor($item->gender);
  141. });
  142. $favoriteProviders = ClientFavoriteProvider::where('client_favorite_providers.client_id', $cliente->id)
  143. ->leftJoin('providers', 'providers.id', '=', 'client_favorite_providers.provider_id')
  144. ->whereExists(Provider::hasActivePrimaryBankAccount())
  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. ->whereDate('schedules.date', '>=', now()->toDateString())
  296. ->leftJoin('providers', 'providers.id', '=', 'schedules.provider_id')
  297. ->leftJoin('users as provider_user', 'provider_user.id', '=', 'providers.user_id')
  298. ->select(
  299. 'schedules.id',
  300. 'schedules.provider_id',
  301. 'provider_user.name as provider_name',
  302. 'providers.gender',
  303. 'schedules.date',
  304. 'schedules.address_id',
  305. 'schedules.status',
  306. 'schedules.total_amount',
  307. 'schedules.start_time',
  308. 'schedules.end_time',
  309. DB::raw("
  310. CASE
  311. WHEN (NOW() - schedules.created_at) < INTERVAL '1 hour' THEN
  312. CONCAT(
  313. ROUND(EXTRACT(EPOCH FROM (NOW() - schedules.created_at)) / 60),
  314. 'min'
  315. )
  316. WHEN (NOW() - schedules.created_at) < INTERVAL '1 day' THEN
  317. CONCAT(
  318. ROUND(EXTRACT(EPOCH FROM (NOW() - schedules.created_at)) / 3600),
  319. 'h'
  320. )
  321. ELSE
  322. CONCAT(
  323. ROUND(EXTRACT(EPOCH FROM (NOW() - schedules.created_at)) / 86400),
  324. 'd'
  325. )
  326. END AS time_since_request
  327. "),
  328. DB::raw("
  329. (
  330. SELECT spi.service_package_id
  331. FROM service_package_items spi
  332. WHERE spi.schedule_id = schedules.id
  333. LIMIT 1
  334. ) AS service_package_id
  335. "),
  336. DB::raw("
  337. (
  338. SELECT COUNT(*)
  339. FROM service_package_items spi_count
  340. JOIN schedules s_count ON s_count.id = spi_count.schedule_id
  341. AND s_count.status NOT IN ('cancelled', 'rejected')
  342. AND s_count.schedule_type = 'default'
  343. WHERE spi_count.service_package_id = (
  344. SELECT spi.service_package_id
  345. FROM service_package_items spi
  346. WHERE spi.schedule_id = schedules.id
  347. LIMIT 1
  348. )
  349. ) AS service_package_items_count
  350. "),
  351. )
  352. ->orderBy('schedules.date', 'asc')
  353. ->get();
  354. $pendingSchedules->each(function ($item) {
  355. $item->gender_label = GenderEnum::labelFor($item->gender);
  356. });
  357. $proposalsDistanceSelect = DistanceService::sqlExpression(
  358. data_get($clientCoordinates, 'latitude'),
  359. data_get($clientCoordinates, 'longitude'),
  360. );
  361. $schedulesProposals = ScheduleProposal::query()
  362. ->leftJoin(
  363. 'schedules',
  364. 'schedule_proposals.schedule_id',
  365. '=',
  366. 'schedules.id'
  367. )
  368. ->leftJoin(
  369. 'providers',
  370. 'schedule_proposals.provider_id',
  371. '=',
  372. 'providers.id'
  373. )
  374. ->whereExists(Provider::hasActivePrimaryBankAccount())
  375. ->leftJoin('users', 'providers.user_id', '=', 'users.id')
  376. ->leftJoin(
  377. DB::raw("
  378. (
  379. SELECT DISTINCT ON (source_id)
  380. *
  381. FROM addresses
  382. WHERE source = 'provider'
  383. AND deleted_at IS NULL
  384. ORDER BY source_id, is_primary DESC
  385. ) AS provider_address
  386. "),
  387. 'provider_address.source_id',
  388. '=',
  389. 'providers.id'
  390. )
  391. ->where('schedules.client_id', $cliente->id)
  392. ->where('schedules.schedule_type', 'custom')
  393. ->where('schedules.status', 'pending')
  394. ->whereNull('schedules.deleted_at')
  395. ->whereDate('schedules.date', '>=', now()->toDateString())
  396. ->orderBy('schedule_proposals.created_at', 'desc')
  397. ->select([
  398. 'schedule_proposals.id',
  399. DB::raw("
  400. DATE_PART('year', AGE(providers.birth_date)) AS idade
  401. "),
  402. 'providers.id as provider_id',
  403. 'providers.gender',
  404. 'schedules.id as schedule_id',
  405. 'schedules.date',
  406. 'schedules.start_time',
  407. 'schedules.end_time',
  408. 'schedules.period_type',
  409. 'schedules.total_amount',
  410. 'providers.daily_price_8h',
  411. 'providers.average_rating',
  412. 'providers.total_services',
  413. 'users.name as provider_name',
  414. 'provider_address.latitude as provider_latitude',
  415. 'provider_address.longitude as provider_longitude',
  416. 'provider_address.zip_code as provider_zip_code',
  417. $proposalsDistanceSelect,
  418. ])
  419. ->get();
  420. $this->zipCodeCoordinatesService->preload(
  421. $schedulesProposals->whereNull('distance_km')->pluck('provider_zip_code')
  422. );
  423. $custom_schedules_with_no_proposals = Schedule::where('client_id', $cliente->id)
  424. ->where('schedule_type', 'custom')
  425. ->where('status', 'pending')
  426. ->whereDate('date', '>=', now()->toDateString())
  427. ->doesntHave('proposals')
  428. ->get();
  429. $schedulesProposals->each(function ($item) use ($clientDistanceAddress) {
  430. $item->gender_label = GenderEnum::labelFor($item->gender);
  431. if ($item->distance_km === null) {
  432. $item->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
  433. $clientDistanceAddress?->latitude !== null ? (float) $clientDistanceAddress->latitude : null,
  434. $clientDistanceAddress?->longitude !== null ? (float) $clientDistanceAddress->longitude : null,
  435. $clientDistanceAddress?->zip_code,
  436. $item->provider_latitude !== null ? (float) $item->provider_latitude : null,
  437. $item->provider_longitude !== null ? (float) $item->provider_longitude : null,
  438. $item->provider_zip_code,
  439. );
  440. }
  441. unset(
  442. $item->provider_latitude,
  443. $item->provider_longitude,
  444. $item->provider_zip_code,
  445. );
  446. });
  447. $todaySchedules = Schedule::with([
  448. 'address:district,address,number,source_id,source,id,address_type',
  449. ])
  450. ->where('schedules.client_id', $cliente->id)
  451. ->whereIn('schedules.status', ['accepted', 'paid', 'started', 'cancelled', 'finished'])
  452. ->whereDate('schedules.date', now()->toDateString())
  453. ->leftJoin('providers', 'providers.id', '=', 'schedules.provider_id')
  454. ->leftJoin('users as provider_user', 'provider_user.id', '=', 'providers.user_id')
  455. ->select(
  456. 'schedules.id',
  457. 'schedules.provider_id',
  458. 'provider_user.name as provider_name',
  459. 'providers.gender',
  460. 'schedules.date',
  461. 'schedules.start_time',
  462. 'schedules.end_time',
  463. 'schedules.total_amount',
  464. 'schedules.period_type',
  465. 'schedules.schedule_type',
  466. 'schedules.address_id',
  467. 'schedules.status',
  468. 'schedules.code_verified',
  469. 'schedules.code',
  470. DB::raw("
  471. (
  472. SELECT spi.service_package_id
  473. FROM service_package_items spi
  474. WHERE spi.schedule_id = schedules.id
  475. LIMIT 1
  476. ) AS service_package_id
  477. "),
  478. DB::raw("
  479. (
  480. SELECT COUNT(*)
  481. FROM service_package_items spi_count
  482. JOIN schedules s_count ON s_count.id = spi_count.schedule_id
  483. AND s_count.status NOT IN ('cancelled', 'rejected')
  484. AND s_count.schedule_type = 'default'
  485. WHERE spi_count.service_package_id = (
  486. SELECT spi.service_package_id
  487. FROM service_package_items spi
  488. WHERE spi.schedule_id = schedules.id
  489. LIMIT 1
  490. )
  491. ) AS service_package_items_count
  492. "),
  493. DB::raw("
  494. EXISTS (
  495. SELECT 1
  496. FROM reviews
  497. WHERE reviews.schedule_id = schedules.id
  498. AND reviews.origin = 'client'
  499. AND reviews.origin_id = {$cliente->id}
  500. AND reviews.deleted_at IS NULL
  501. ) AS client_reviewed
  502. "),
  503. )
  504. ->orderBy('schedules.start_time', 'asc')
  505. ->get()
  506. ->map(function ($item) {
  507. $item->gender_label = GenderEnum::labelFor($item->gender);
  508. return $item;
  509. });
  510. $providerCollections = collect([
  511. $nextSchedules,
  512. $lastDoneSchedules,
  513. $favoriteProviders,
  514. $providersClose,
  515. $pendingSchedules,
  516. $schedulesProposals,
  517. $todaySchedules,
  518. ]);
  519. $providerPhotoUrls = $this->providerPhotoUrls(
  520. $providerCollections->flatMap(
  521. fn(Collection $items) => $items->pluck('provider_id'),
  522. ),
  523. );
  524. $providerCollections->each(function (Collection $items) use ($providerPhotoUrls) {
  525. $items->each(function ($item) use ($providerPhotoUrls) {
  526. $item->provider_photo = $providerPhotoUrls->get($item->provider_id);
  527. });
  528. });
  529. $notifications = Notification::where('user_id', $user->id)
  530. ->orderBy('read', 'asc')
  531. ->orderBy('created_at', 'desc')
  532. ->limit(10)
  533. ->get()
  534. ->map(function ($notification) {
  535. return [
  536. 'id' => $notification->id,
  537. 'title' => $notification->title,
  538. 'description' => $notification->description,
  539. 'time' => $notification->created_at->diffForHumans(),
  540. 'read' => $notification->read,
  541. 'avatar' => '/icons/avatar.svg',
  542. ];
  543. });
  544. $hasPaymentMethods = ClientPaymentMethod::where('client_id', $cliente->id)->exists();
  545. $pendingServicePackages = ServicePackage::query()
  546. ->where('client_id', $cliente->id)
  547. ->where('status', ServicePackageStatusEnum::OPEN->value)
  548. ->whereHas('items.schedule', fn($q) => $q->where('status', 'accepted'))
  549. ->whereDoesntHave('items.schedule', fn($q) => $q->where('status', 'pending'))
  550. ->with(['items.schedule' => function ($query) {
  551. $query->with(['provider.user', 'address']);
  552. }])
  553. ->with('provider.user')
  554. ->get();
  555. return [
  556. 'headerBar' => $headerBar,
  557. 'summaryInfos' => $summaryInfos,
  558. 'pendingSchedules' => $pendingSchedules,
  559. 'nextSchedules' => $nextSchedules,
  560. 'lastDoneSchedules' => $lastDoneSchedules,
  561. 'favoriteProviders' => $favoriteProviders,
  562. 'providersClose' => $providersClose,
  563. 'todaySchedules' => $todaySchedules,
  564. 'schedulesProposals' => $schedulesProposals,
  565. 'customSchedulesNoProposals' => $custom_schedules_with_no_proposals,
  566. 'notifications' => $notifications,
  567. 'has_payment_methods' => $hasPaymentMethods,
  568. 'pendingServicePackages' => $pendingServicePackages,
  569. ];
  570. }
  571. public function dadosDashboardPrestador(): array
  572. {
  573. $user = Auth::user();
  574. if ($user->type !== UserTypeEnum::PROVIDER) {
  575. throw new AuthorizationException(__('messages.only_providers_allowed'));
  576. }
  577. $provider = Provider::with('profileMedia')->where('user_id', $user->id)->first();
  578. $headerBar = [
  579. 'rating' => $provider->average_rating,
  580. 'total_ratings' => Review::where('reviews.origin', 'client')->leftJoin('schedules', 'schedules.id', '=', 'reviews.schedule_id')->where('schedules.provider_id', $provider->id)->count(),
  581. 'total_services' => $provider->total_services,
  582. ];
  583. $address = Address::where('source', 'provider')->where('source_id', $provider->id)->with(['city', 'state'])->first();
  584. $summaryInfos = [
  585. 'name' => $user->name,
  586. 'address' => $address,
  587. 'pending_services' => Schedule::where('provider_id', $provider->id)->where('status', 'pending')->count(),
  588. 'profile_photo' => $provider->profileMedia?->path
  589. ? Storage::temporaryUrl($provider->profileMedia->path, now()->addMinutes(60))
  590. : null,
  591. ];
  592. if ($provider->approval_status === ApprovalStatusEnum::PENDING) {
  593. return [
  594. 'headerBar' => $headerBar,
  595. 'summaryInfos' => $summaryInfos,
  596. 'priceSuggested' => null,
  597. 'todayServices' => [],
  598. 'solicitations' => [],
  599. 'nextSchedules' => [],
  600. 'opportunities' => [],
  601. 'notifications' => [],
  602. 'pendingConfirmation' => [],
  603. ];
  604. }
  605. $priceSuggestedAvg = Provider::where('user_id', '!=', $user->id)
  606. ->whereNotNull('daily_price_8h')
  607. ->pluck('daily_price_8h')
  608. ->avg();
  609. $priceActual = $provider->daily_price_8h;
  610. $priceSuggested = [
  611. 'average_price' => $priceSuggestedAvg,
  612. 'your_price' => $priceActual,
  613. ];
  614. $solicitations = Schedule::with([
  615. 'address:district,source_id,source,id,zip_code,latitude,longitude',
  616. 'customSchedule.specialities',
  617. ])
  618. ->where('schedules.provider_id', $provider->id)
  619. ->where('schedules.status', 'pending')
  620. ->leftJoin('clients', 'clients.id', '=', 'schedules.client_id')
  621. ->leftJoin('users as client_user', 'client_user.id', '=', 'clients.user_id')
  622. ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  623. ->select(
  624. 'schedules.id',
  625. 'schedules.client_id',
  626. 'client_user.name as client_name',
  627. 'clients.average_rating',
  628. 'schedules.date',
  629. DB::raw("
  630. TO_CHAR(schedules.date, 'DD/MM/YYYY') AS formatted_date
  631. "),
  632. 'schedules.start_time',
  633. 'schedules.end_time',
  634. 'schedules.total_amount',
  635. 'schedules.period_type',
  636. 'schedules.schedule_type',
  637. 'schedules.address_id',
  638. 'schedules.status',
  639. 'custom_schedules.offers_meal',
  640. DB::raw("
  641. CASE
  642. WHEN (NOW() - schedules.created_at) < INTERVAL '1 day' THEN
  643. CONCAT(
  644. ROUND(
  645. EXTRACT(
  646. EPOCH FROM (NOW() - schedules.created_at)
  647. ) / 3600
  648. ),
  649. ' hours ago'
  650. )
  651. ELSE
  652. CONCAT(
  653. ROUND(
  654. EXTRACT(
  655. EPOCH FROM (NOW() - schedules.created_at)
  656. ) / 86400
  657. ),
  658. ' days ago'
  659. )
  660. END AS time_since_request
  661. "),
  662. DB::raw("
  663. (
  664. SELECT service_package_items.service_package_id
  665. FROM service_package_items
  666. WHERE service_package_items.schedule_id = schedules.id
  667. LIMIT 1
  668. ) AS service_package_id
  669. "),
  670. )
  671. ->orderBy('schedules.date', 'asc')
  672. ->get()
  673. ->append('specialities')
  674. ->makeHidden('customSchedule');
  675. $solicitations->each(function ($solicitation) use ($address) {
  676. $solicitation->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
  677. $address?->latitude !== null ? (float) $address->latitude : null,
  678. $address?->longitude !== null ? (float) $address->longitude : null,
  679. $address?->zip_code,
  680. $solicitation->address?->latitude !== null ? (float) $solicitation->address->latitude : null,
  681. $solicitation->address?->longitude !== null ? (float) $solicitation->address->longitude : null,
  682. $solicitation->address?->zip_code,
  683. );
  684. });
  685. $todayServices = Schedule::with([
  686. 'address:district,address,number,source_id,source,id',
  687. ])
  688. ->where('schedules.provider_id', $provider->id)
  689. ->whereIn('schedules.status', ['accepted', 'paid', 'started', 'finished'])
  690. ->whereDate('schedules.date', now()->toDateString())
  691. ->leftJoin('clients', 'clients.id', '=', 'schedules.client_id')
  692. ->leftJoin('users as client_user', 'client_user.id', '=', 'clients.user_id')
  693. ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  694. ->select(
  695. 'schedules.id',
  696. 'schedules.client_id',
  697. 'client_user.name as client_name',
  698. 'schedules.date',
  699. 'schedules.start_time',
  700. 'schedules.end_time',
  701. 'schedules.total_amount',
  702. 'schedules.period_type',
  703. 'schedules.address_id',
  704. 'schedules.schedule_type',
  705. 'schedules.status',
  706. 'schedules.code_verified',
  707. 'schedules.code',
  708. 'custom_schedules.offers_meal',
  709. DB::raw("
  710. EXISTS (
  711. SELECT 1
  712. FROM reviews
  713. WHERE reviews.schedule_id = schedules.id
  714. AND reviews.origin = 'provider'
  715. AND reviews.origin_id = {$provider->id}
  716. AND reviews.deleted_at IS NULL
  717. ) AS provider_reviewed
  718. "),
  719. DB::raw("
  720. (
  721. SELECT service_package_items.service_package_id
  722. FROM service_package_items
  723. WHERE service_package_items.schedule_id = schedules.id
  724. LIMIT 1
  725. ) AS service_package_id
  726. "),
  727. )
  728. ->orderBy('schedules.start_time', 'asc')
  729. ->get();
  730. $pendingConfirmation = Schedule::with(
  731. 'address:district,address,number,source_id,source,id,zip_code,latitude,longitude'
  732. )
  733. ->where('schedules.provider_id', $provider->id)
  734. ->where('schedules.status', 'accepted')
  735. ->whereDate('schedules.date', '>=', now()->toDateString())
  736. ->leftJoin('clients', 'clients.id', '=', 'schedules.client_id')
  737. ->leftJoin('users as client_user', 'client_user.id', '=', 'clients.user_id')
  738. ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  739. ->select(
  740. 'schedules.id',
  741. 'schedules.client_id',
  742. 'client_user.name as client_name',
  743. 'schedules.date',
  744. 'schedules.start_time',
  745. 'schedules.end_time',
  746. 'schedules.total_amount',
  747. 'schedules.period_type',
  748. 'schedules.address_id',
  749. 'schedules.schedule_type',
  750. 'schedules.status',
  751. 'custom_schedules.offers_meal',
  752. DB::raw("
  753. (
  754. SELECT service_package_items.service_package_id
  755. FROM service_package_items
  756. WHERE service_package_items.schedule_id = schedules.id
  757. LIMIT 1
  758. ) AS service_package_id
  759. "),
  760. )
  761. ->orderBy('schedules.date', 'asc')
  762. ->get();
  763. $pendingConfirmation->each(function ($schedule) use ($address) {
  764. $schedule->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
  765. $address?->latitude !== null ? (float) $address->latitude : null,
  766. $address?->longitude !== null ? (float) $address->longitude : null,
  767. $address?->zip_code,
  768. $schedule->address?->latitude !== null ? (float) $schedule->address->latitude : null,
  769. $schedule->address?->longitude !== null ? (float) $schedule->address->longitude : null,
  770. $schedule->address?->zip_code,
  771. );
  772. });
  773. $nextSchedules = Schedule::with('address:district,address,number,source_id,source,id,zip_code,latitude,longitude')
  774. ->where('schedules.provider_id', $provider->id)
  775. ->where('schedules.status', 'paid')
  776. ->whereDate('schedules.date', '>=', now()->toDateString())
  777. ->leftJoin('clients', 'clients.id', '=', 'schedules.client_id')
  778. ->leftJoin('users as client_user', 'client_user.id', '=', 'clients.user_id')
  779. ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  780. ->select(
  781. 'schedules.id',
  782. 'schedules.client_id',
  783. 'client_user.name as client_name',
  784. 'schedules.date',
  785. 'schedules.start_time',
  786. 'schedules.end_time',
  787. 'schedules.total_amount',
  788. 'schedules.period_type',
  789. 'schedules.address_id',
  790. 'schedules.schedule_type',
  791. 'schedules.status',
  792. 'custom_schedules.offers_meal',
  793. DB::raw("
  794. (
  795. SELECT service_package_items.service_package_id
  796. FROM service_package_items
  797. WHERE service_package_items.schedule_id = schedules.id
  798. LIMIT 1
  799. ) AS service_package_id
  800. "),
  801. )
  802. ->orderBy('schedules.date', 'asc')
  803. ->get();
  804. $nextSchedules->each(function ($schedule) use ($address) {
  805. $schedule->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
  806. $address?->latitude !== null ? (float) $address->latitude : null,
  807. $address?->longitude !== null ? (float) $address->longitude : null,
  808. $address?->zip_code,
  809. $schedule->address?->latitude !== null ? (float) $schedule->address->latitude : null,
  810. $schedule->address?->longitude !== null ? (float) $schedule->address->longitude : null,
  811. $schedule->address?->zip_code,
  812. );
  813. });
  814. $clientCollections = collect([
  815. $solicitations,
  816. $todayServices,
  817. $pendingConfirmation,
  818. $nextSchedules
  819. ]);
  820. $clientPhotoUrls = $this->clientPhotoUrls(
  821. $clientCollections->flatMap(
  822. fn(Collection $items) => $items->pluck('client_id'),
  823. ),
  824. );
  825. $clientCollections->each(function (Collection $items) use ($clientPhotoUrls) {
  826. $items->each(function ($item) use ($clientPhotoUrls) {
  827. $item->customer_photo = $clientPhotoUrls->get($item->client_id);
  828. });
  829. });
  830. $notifications = Notification::where('user_id', $user->id)
  831. ->orderBy('read', 'asc')
  832. ->orderBy('created_at', 'desc')
  833. ->limit(10)
  834. ->get()
  835. ->map(function ($notification) {
  836. return [
  837. 'id' => $notification->id,
  838. 'title' => $notification->title,
  839. 'description' => $notification->description,
  840. 'time' => $notification->created_at->diffForHumans(),
  841. 'read' => $notification->read,
  842. 'avatar' => '/icons/avatar.svg',
  843. ];
  844. });
  845. $opportunities = $this->customScheduleService->getAvailableOpportunities($provider->id);
  846. $opportunities->each(function ($o) {
  847. $o->customer_photo = $o->client?->profileMedia?->path
  848. ? Storage::temporaryUrl($o->client->profileMedia->path, now()->addMinutes(60))
  849. : null;
  850. });
  851. return [
  852. 'headerBar' => $headerBar,
  853. 'summaryInfos' => $summaryInfos,
  854. 'priceSuggested' => $priceSuggested,
  855. 'solicitations' => $solicitations,
  856. 'todayServices' => $todayServices,
  857. 'pendingConfirmation' => $pendingConfirmation,
  858. 'nextSchedules' => $nextSchedules,
  859. 'opportunities' => $opportunities,
  860. 'notifications' => $notifications,
  861. ];
  862. }
  863. public function getScheduleClienteDetails(int $scheduleId): array
  864. {
  865. $user = Auth::user();
  866. $cliente = Client::where('user_id', $user->id)->firstOrFail();
  867. $schedule = Schedule::with('customSchedule.specialities')
  868. ->where('schedules.id', $scheduleId)
  869. ->where('schedules.client_id', $cliente->id)
  870. ->leftJoin('providers', 'providers.id', '=', 'schedules.provider_id')
  871. ->leftJoin('users as provider_user', 'provider_user.id', '=', 'providers.user_id')
  872. ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  873. ->select(
  874. 'schedules.id',
  875. 'schedules.provider_id',
  876. 'schedules.schedule_type',
  877. 'provider_user.name as provider_name',
  878. 'providers.birth_date as provider_birth_date',
  879. 'providers.gender',
  880. 'custom_schedules.offers_meal',
  881. )
  882. ->firstOrFail();
  883. $providerPhoto = $this->providerPhotoUrls([$schedule->provider_id])
  884. ->get($schedule->provider_id);
  885. return [
  886. 'schedule_type' => $schedule->schedule_type,
  887. 'provider_name' => $schedule->provider_name,
  888. 'provider_birth_date' => $schedule->provider_birth_date,
  889. 'gender' => $schedule->gender,
  890. 'gender_label' => GenderEnum::labelFor($schedule->gender),
  891. 'offers_meal' => $schedule->offers_meal,
  892. 'specialities' => $schedule->specialities,
  893. 'provider_photo' => $providerPhoto,
  894. ];
  895. }
  896. // gera urls apenas para fotos verificadas ou visiveis ao proprio prestador.
  897. private function providerPhotoUrls(iterable $providerIds): Collection
  898. {
  899. return Provider::query()
  900. ->select('id', 'profile_media_id')
  901. ->with('profileMedia')
  902. ->whereIn('id', collect($providerIds)->filter()->unique())
  903. ->get()
  904. ->mapWithKeys(function (Provider $provider) {
  905. $path = $provider->profileMedia?->path;
  906. return [
  907. $provider->id => $path ? Storage::temporaryUrl($path, now()->addMinutes(60)) : null,
  908. ];
  909. });
  910. }
  911. // Gera URLs apenas para fotos verificadas ou visíveis ao próprio cliente.
  912. private function clientPhotoUrls(iterable $clientIds): Collection
  913. {
  914. return Client::query()
  915. ->select('id', 'profile_media_id')
  916. ->with('profileMedia')
  917. ->whereIn('id', collect($clientIds)->filter()->unique())
  918. ->get()
  919. ->mapWithKeys(function (Client $client) {
  920. $path = $client->profileMedia?->path;
  921. return [
  922. $client->id => $path ? Storage::temporaryUrl($path, now()->addMinutes(60)) : null,
  923. ];
  924. });
  925. }
  926. //
  927. private function applyCreditCardFee(?float $price): ?float
  928. {
  929. if ($price === null) {
  930. return null;
  931. }
  932. $rate = $this->platformCreditCardFeeRate();
  933. return round($price * (1 + $rate), 2);
  934. }
  935. private function platformCreditCardFeeRate(): float
  936. {
  937. $rate = config('services.pagarme.platform_credit_card_fee_rate', 0.16);
  938. if (is_string($rate)) {
  939. $rate = str_replace(',', '.', trim($rate));
  940. }
  941. $rate = (float) $rate;
  942. return $rate > 1 ? $rate / 100 : $rate;
  943. }
  944. //
  945. private function addressForDistance(int $clientId, ?Address $primaryAddress): ?Address
  946. {
  947. if ($primaryAddress?->latitude !== null && $primaryAddress?->longitude !== null) {
  948. return $primaryAddress;
  949. }
  950. return Address::where('source', 'client')
  951. ->where('source_id', $clientId)
  952. ->whereNotNull('latitude')
  953. ->whereNotNull('longitude')
  954. ->orderByDesc('is_primary')
  955. ->orderByDesc('id')
  956. ->first() ?? $primaryAddress;
  957. }
  958. private function distanceSelect(?float $clientLatitude, ?float $clientLongitude): \Illuminate\Contracts\Database\Query\Expression
  959. {
  960. return DistanceService::sqlExpression($clientLatitude, $clientLongitude);
  961. }
  962. }