DashboardService.php 44 KB

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