DashboardService.php 52 KB

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