DashboardService.php 32 KB

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