DashboardService.php 39 KB

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