DashboardService.php 38 KB

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