DashboardService.php 51 KB

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