DashboardService.php 40 KB

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