DashboardService.php 30 KB

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