DashboardService.php 34 KB

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