DashboardService.php 42 KB

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