DashboardService.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  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\Review;
  13. use App\Models\Schedule;
  14. use App\Models\ScheduleProposal;
  15. use App\Models\ServicePackage;
  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. $pendingServicePackages = ServicePackage::query()
  526. ->where('client_id', $cliente->id)
  527. ->where('status', ServicePackageStatusEnum::OPEN->value)
  528. ->whereDoesntHave('items.schedule', fn ($q) => $q->where('status', '!=', 'accepted'))
  529. ->with(['items.schedule' => function ($query) {
  530. $query->with(['provider.user', 'address']);
  531. }])
  532. ->with('provider.user')
  533. ->get();
  534. return [
  535. 'headerBar' => $headerBar,
  536. 'summaryInfos' => $summaryInfos,
  537. 'pendingSchedules' => $pendingSchedules,
  538. 'nextSchedules' => $nextSchedules,
  539. 'lastDoneSchedules' => $lastDoneSchedules,
  540. 'favoriteProviders' => $favoriteProviders,
  541. 'providersClose' => $providersClose,
  542. 'todaySchedules' => $todaySchedules,
  543. 'schedulesProposals' => $schedulesProposals,
  544. 'customSchedulesNoProposals' => $custom_schedules_with_no_proposals,
  545. 'notifications' => $notifications,
  546. 'has_payment_methods' => $hasPaymentMethods,
  547. 'pendingServicePackages' => $pendingServicePackages,
  548. ];
  549. }
  550. public function dadosDashboardPrestador(): array
  551. {
  552. $user = Auth::user();
  553. if ($user->type !== UserTypeEnum::PROVIDER) {
  554. throw new AuthorizationException(__('messages.only_providers_allowed'));
  555. }
  556. $provider = Provider::with('profileMedia')->where('user_id', $user->id)->first();
  557. $headerBar = [
  558. 'rating' => $provider->average_rating,
  559. 'total_ratings' => Review::where('reviews.origin', 'client')->leftJoin('schedules', 'schedules.id', '=', 'reviews.schedule_id')->where('schedules.provider_id', $provider->id)->count(),
  560. 'total_services' => $provider->total_services,
  561. ];
  562. $address = Address::where('source', 'provider')->where('source_id', $provider->id)->with(['city', 'state'])->first();
  563. $summaryInfos = [
  564. 'name' => $user->name,
  565. 'address' => $address,
  566. 'pending_services' => Schedule::where('provider_id', $provider->id)->where('status', 'pending')->count(),
  567. 'profile_photo' => $provider->profileMedia?->path
  568. ? Storage::temporaryUrl($provider->profileMedia->path, now()->addMinutes(60))
  569. : null,
  570. ];
  571. $priceSuggestedAvg = Provider::where('user_id', '!=', $user->id)
  572. ->whereNotNull('daily_price_8h')
  573. ->pluck('daily_price_8h')
  574. ->avg();
  575. $priceActual = $provider->daily_price_8h;
  576. $priceSuggested = [
  577. 'average_price' => $priceSuggestedAvg,
  578. 'your_price' => $priceActual,
  579. ];
  580. $solicitations = Schedule::with([
  581. 'address:district,source_id,source,id,zip_code,latitude,longitude',
  582. 'customSchedule.specialities',
  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. ->append('specialities')
  640. ->makeHidden('customSchedule');
  641. $solicitations->each(function ($solicitation) use ($address) {
  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('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  660. ->select(
  661. 'schedules.id',
  662. 'schedules.client_id',
  663. 'client_user.name as client_name',
  664. 'schedules.date',
  665. 'schedules.start_time',
  666. 'schedules.end_time',
  667. 'schedules.total_amount',
  668. 'schedules.period_type',
  669. 'schedules.address_id',
  670. 'schedules.schedule_type',
  671. 'schedules.status',
  672. 'schedules.code_verified',
  673. 'schedules.code',
  674. 'custom_schedules.offers_meal',
  675. DB::raw("
  676. EXISTS (
  677. SELECT 1
  678. FROM reviews
  679. WHERE reviews.schedule_id = schedules.id
  680. AND reviews.origin = 'provider'
  681. AND reviews.origin_id = {$provider->id}
  682. AND reviews.deleted_at IS NULL
  683. ) AS provider_reviewed
  684. "),
  685. DB::raw("
  686. (
  687. SELECT service_package_items.service_package_id
  688. FROM service_package_items
  689. WHERE service_package_items.schedule_id = schedules.id
  690. LIMIT 1
  691. ) AS service_package_id
  692. "),
  693. )
  694. ->orderBy('schedules.start_time', 'asc')
  695. ->get();
  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('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  703. ->select(
  704. 'schedules.id',
  705. 'schedules.client_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. DB::raw("
  717. (
  718. SELECT service_package_items.service_package_id
  719. FROM service_package_items
  720. WHERE service_package_items.schedule_id = schedules.id
  721. LIMIT 1
  722. ) AS service_package_id
  723. "),
  724. )
  725. ->orderBy('schedules.date', 'asc')
  726. ->get();
  727. $nextSchedules->each(function ($schedule) use ($address) {
  728. $schedule->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
  729. $address?->latitude !== null ? (float) $address->latitude : null,
  730. $address?->longitude !== null ? (float) $address->longitude : null,
  731. $address?->zip_code,
  732. $schedule->address?->latitude !== null ? (float) $schedule->address->latitude : null,
  733. $schedule->address?->longitude !== null ? (float) $schedule->address->longitude : null,
  734. $schedule->address?->zip_code,
  735. );
  736. });
  737. $clientCollections = collect([
  738. $solicitations,
  739. $todayServices,
  740. $nextSchedules,
  741. ]);
  742. $clientPhotoUrls = $this->clientPhotoUrls(
  743. $clientCollections->flatMap(
  744. fn (Collection $items) => $items->pluck('client_id'),
  745. ),
  746. );
  747. $clientCollections->each(function (Collection $items) use ($clientPhotoUrls) {
  748. $items->each(function ($item) use ($clientPhotoUrls) {
  749. $item->customer_photo = $clientPhotoUrls->get($item->client_id);
  750. });
  751. });
  752. $notifications = Notification::where('user_id', $user->id)
  753. ->orderBy('read', 'asc')
  754. ->orderBy('created_at', 'desc')
  755. ->limit(10)
  756. ->get()
  757. ->map(function ($notification) {
  758. return [
  759. 'id' => $notification->id,
  760. 'title' => $notification->title,
  761. 'description' => $notification->description,
  762. 'time' => $notification->created_at->diffForHumans(),
  763. 'read' => $notification->read,
  764. 'avatar' => '/icons/avatar.svg',
  765. ];
  766. });
  767. $opportunities = $this->customScheduleService->getAvailableOpportunities($provider->id);
  768. $opportunities->each(function ($o) {
  769. $o->customer_photo = $o->client?->profileMedia?->path
  770. ? Storage::temporaryUrl($o->client->profileMedia->path, now()->addMinutes(60))
  771. : null;
  772. });
  773. return [
  774. 'headerBar' => $headerBar,
  775. 'summaryInfos' => $summaryInfos,
  776. 'priceSuggested' => $priceSuggested,
  777. 'solicitations' => $solicitations,
  778. 'todayServices' => $todayServices,
  779. 'nextSchedules' => $nextSchedules,
  780. 'opportunities' => $opportunities,
  781. 'notifications' => $notifications,
  782. ];
  783. }
  784. public function getScheduleClienteDetails(int $scheduleId): array
  785. {
  786. $user = Auth::user();
  787. $cliente = Client::where('user_id', $user->id)->firstOrFail();
  788. $schedule = Schedule::with('customSchedule.specialities')
  789. ->where('schedules.id', $scheduleId)
  790. ->where('schedules.client_id', $cliente->id)
  791. ->leftJoin('providers', 'providers.id', '=', 'schedules.provider_id')
  792. ->leftJoin('users as provider_user', 'provider_user.id', '=', 'providers.user_id')
  793. ->leftJoin('custom_schedules', 'custom_schedules.schedule_id', '=', 'schedules.id')
  794. ->select(
  795. 'schedules.id',
  796. 'schedules.provider_id',
  797. 'schedules.schedule_type',
  798. 'provider_user.name as provider_name',
  799. 'providers.birth_date as provider_birth_date',
  800. 'providers.gender',
  801. 'custom_schedules.offers_meal',
  802. )
  803. ->firstOrFail();
  804. $providerPhoto = $this->providerPhotoUrls([$schedule->provider_id])
  805. ->get($schedule->provider_id);
  806. return [
  807. 'schedule_type' => $schedule->schedule_type,
  808. 'provider_name' => $schedule->provider_name,
  809. 'provider_birth_date' => $schedule->provider_birth_date,
  810. 'gender' => $schedule->gender,
  811. 'gender_label' => GenderEnum::labelFor($schedule->gender),
  812. 'offers_meal' => $schedule->offers_meal,
  813. 'specialities' => $schedule->specialities,
  814. 'provider_photo' => $providerPhoto,
  815. ];
  816. }
  817. // gera urls apenas para fotos verificadas ou visiveis ao proprio prestador.
  818. private function providerPhotoUrls(iterable $providerIds): Collection
  819. {
  820. return Provider::query()
  821. ->select('id', 'profile_media_id')
  822. ->with('profileMedia')
  823. ->whereIn('id', collect($providerIds)->filter()->unique())
  824. ->get()
  825. ->mapWithKeys(function (Provider $provider) {
  826. $path = $provider->profileMedia?->path;
  827. return [
  828. $provider->id => $path ? Storage::temporaryUrl($path, now()->addMinutes(60)) : null,
  829. ];
  830. });
  831. }
  832. // Gera URLs apenas para fotos verificadas ou visíveis ao próprio cliente.
  833. private function clientPhotoUrls(iterable $clientIds): Collection
  834. {
  835. return Client::query()
  836. ->select('id', 'profile_media_id')
  837. ->with('profileMedia')
  838. ->whereIn('id', collect($clientIds)->filter()->unique())
  839. ->get()
  840. ->mapWithKeys(function (Client $client) {
  841. $path = $client->profileMedia?->path;
  842. return [
  843. $client->id => $path ? Storage::temporaryUrl($path, now()->addMinutes(60)) : null,
  844. ];
  845. });
  846. }
  847. //
  848. private function applyCreditCardFee(?float $price): ?float
  849. {
  850. if ($price === null) {
  851. return null;
  852. }
  853. $rate = $this->platformCreditCardFeeRate();
  854. return round($price * (1 + $rate), 2);
  855. }
  856. private function platformCreditCardFeeRate(): float
  857. {
  858. $rate = config('services.pagarme.platform_credit_card_fee_rate', 0.16);
  859. if (is_string($rate)) {
  860. $rate = str_replace(',', '.', trim($rate));
  861. }
  862. $rate = (float) $rate;
  863. return $rate > 1 ? $rate / 100 : $rate;
  864. }
  865. //
  866. private function addressForDistance(int $clientId, ?Address $primaryAddress): ?Address
  867. {
  868. if ($primaryAddress?->latitude !== null && $primaryAddress?->longitude !== null) {
  869. return $primaryAddress;
  870. }
  871. return Address::where('source', 'client')
  872. ->where('source_id', $clientId)
  873. ->whereNotNull('latitude')
  874. ->whereNotNull('longitude')
  875. ->orderByDesc('is_primary')
  876. ->orderByDesc('id')
  877. ->first() ?? $primaryAddress;
  878. }
  879. private function distanceSelect(?float $clientLatitude, ?float $clientLongitude): \Illuminate\Contracts\Database\Query\Expression
  880. {
  881. return DistanceService::sqlExpression($clientLatitude, $clientLongitude);
  882. }
  883. }