DashboardService.php 39 KB

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