DashboardService.php 44 KB

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