DashboardService.php 44 KB

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