DashboardService.php 39 KB

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