DashboardService.php 45 KB

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