DashboardService.php 33 KB

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