ScheduleService.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. <?php
  2. namespace App\Services;
  3. use App\Exceptions\ScheduleStatusTransitionException;
  4. use App\Enums\ServicePackageStatusEnum;
  5. use App\Enums\UserTypeEnum;
  6. use App\Enums\NotificationTypeEnum;
  7. use App\Jobs\StartScheduleJob;
  8. use App\Models\Provider;
  9. use App\Models\Schedule;
  10. use App\Models\ServicePackage;
  11. use App\Rules\ScheduleBusinessRules;
  12. use App\Services\NotificationService;
  13. use App\Services\PushNotificationService;
  14. use App\Notifications\Push\Cliente\Agendamento\PrestadorAceitouPush;
  15. use App\Notifications\Push\Prestador\Agendamento\NewPushRequest;
  16. use Carbon\Carbon;
  17. use Illuminate\Support\Facades\Auth;
  18. use Illuminate\Support\Facades\DB;
  19. use Illuminate\Support\Facades\Log;
  20. class ScheduleService
  21. {
  22. private const EXCLUDED_STATUSES = ['cancelled', 'rejected'];
  23. public function getAll()
  24. {
  25. return Schedule::with(['client.user', 'provider.user', 'address'])
  26. ->where('schedule_type', 'default')
  27. ->orderBy('date', 'desc')
  28. ->orderBy('start_time', 'desc')
  29. ->get();
  30. }
  31. public function getById($id)
  32. {
  33. return Schedule::with(['client.user', 'provider.user', 'address'])->findOrFail($id);
  34. }
  35. public function create(array $data): Schedule
  36. {
  37. return data_get($this->createSingleOrMultiple([], [$data]), 0);
  38. }
  39. public function createSingleOrMultiple(array $baseData, array $schedules)
  40. {
  41. try {
  42. DB::beginTransaction();
  43. $createdSchedules = [];
  44. foreach ($schedules as $schedule) {
  45. $datasMerged = array_merge($baseData, $schedule);
  46. if (data_get($datasMerged, 'schedule_type', 'default') === 'default') {
  47. $provider = Provider::findOrFail(data_get($datasMerged, 'provider_id'));
  48. $datasMerged['total_amount'] = $this->calculateAmount(
  49. $provider,
  50. (string) data_get($datasMerged, 'period_type'),
  51. );
  52. }
  53. $this->validateProviderAvailability($datasMerged, null);
  54. $scheduleData = array_merge($datasMerged, [
  55. 'code' => str_pad(random_int(0, 9999), 4, '0', STR_PAD_LEFT),
  56. ]);
  57. $newSchedule = Schedule::create($scheduleData);
  58. // NOTIFICAÇÃO PRESTADOR
  59. if ($newSchedule->provider_id) {
  60. $notificationService = app(NotificationService::class);
  61. $notificationService->create([
  62. 'title' => __('notifications.new_schedule_request_title'),
  63. 'description' => __('notifications.new_schedule_request_description'),
  64. 'origin' => 'schedule',
  65. 'origin_id' => $newSchedule->id,
  66. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_NEW_SOLICITATION->value,
  67. 'user_id' => $newSchedule->provider->user_id,
  68. ]);
  69. // Push Notification
  70. $pushNotificationService = app(PushNotificationService::class);
  71. $pushNotificationService->sendToUser(
  72. $newSchedule->provider->user,
  73. new NewPushRequest($newSchedule->client->user->name)
  74. );
  75. }
  76. $createdSchedules[] = $newSchedule;
  77. }
  78. DB::commit();
  79. } catch (\Exception $e) {
  80. DB::rollBack();
  81. throw $e;
  82. }
  83. return $createdSchedules;
  84. }
  85. public function update($id, array $data)
  86. {
  87. unset($data['status']);
  88. $schedule = Schedule::with(['provider.user', 'client.user', 'address'])->findOrFail($id);
  89. if (data_get($data, 'provider_id') !== null || data_get($data, 'period_type') !== null) {
  90. $providerId = data_get($data, 'provider_id', $schedule->provider_id);
  91. $periodType = data_get($data, 'period_type', $schedule->period_type);
  92. $provider = Provider::findOrFail($providerId);
  93. $data['total_amount'] = $this->calculateAmount($provider, $periodType);
  94. }
  95. if (data_get($data, 'date') !== null || data_get($data, 'start_time') !== null || data_get($data, 'provider_id') !== null) {
  96. $validationData = array_merge($schedule->toArray(), $data);
  97. $this->validateProviderAvailability($validationData, $id);
  98. }
  99. $schedule->update($data);
  100. return $schedule->fresh(['client.user', 'provider.user', 'address']);
  101. }
  102. public function delete($id)
  103. {
  104. $schedule = Schedule::findOrFail($id);
  105. $schedule->delete();
  106. return $schedule;
  107. }
  108. //
  109. public function updateStatus($id, string $status, bool $fromPackage = false)
  110. {
  111. try {
  112. DB::beginTransaction();
  113. $schedule = Schedule::with(['provider.user', 'client.user', 'address'])->findOrFail($id);
  114. if (! $fromPackage && in_array($status, ['accepted', 'rejected']) && Auth::user()?->type === UserTypeEnum::PROVIDER) {
  115. $belongsToServicePackage = DB::table('service_package_items')
  116. ->where('schedule_id', $schedule->id)
  117. ->exists();
  118. if ($belongsToServicePackage) {
  119. throw new \DomainException(__('messages.schedule_belongs_to_package_use_package_endpoint'));
  120. }
  121. }
  122. $allowedTransitions = [
  123. 'pending' => ['accepted', 'rejected', 'cancelled'],
  124. 'accepted' => ['paid', 'cancelled'],
  125. 'paid' => ['cancelled', 'started'],
  126. 'started' => ['finished'],
  127. 'rejected' => [],
  128. 'cancelled' => [],
  129. 'finished' => [],
  130. ];
  131. $currentStatus = $schedule->status;
  132. if (data_get($allowedTransitions, $currentStatus) === null) {
  133. throw new ScheduleStatusTransitionException;
  134. }
  135. if (! in_array($status, data_get($allowedTransitions, $currentStatus))) {
  136. throw new ScheduleStatusTransitionException;
  137. }
  138. $schedule->update(['status' => $status]);
  139. $schedule->refresh();
  140. $currentStatus = $schedule->status;
  141. switch ($status) {
  142. case 'pending':
  143. break;
  144. case 'accepted':
  145. $notificationService = app(NotificationService::class);
  146. switch (Auth::user()?->type) {
  147. case UserTypeEnum::PROVIDER:
  148. $notificationService->create([
  149. 'title' => __('notifications.schedule_accepted_title'),
  150. 'description' => __('notifications.provider_accepted_schedule_description', ['provider' => $schedule->provider->user->name]),
  151. 'origin' => 'schedule',
  152. 'origin_id' => $schedule->id,
  153. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_ACCEPTED->value,
  154. 'user_id' => $schedule->client->user_id,
  155. ]);
  156. $this->sendProviderAcceptedPush($schedule);
  157. break;
  158. case UserTypeEnum::CLIENT:
  159. if ($schedule->provider_id) {
  160. $notificationService->create([
  161. 'title' => __('notifications.proposal_accepted_title'),
  162. 'description' => __('notifications.proposal_accepted_description'),
  163. 'origin' => 'schedule',
  164. 'origin_id' => $schedule->id,
  165. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_PROPOSAL_ACCEPTED->value,
  166. 'user_id' => $schedule->provider->user_id,
  167. ]);
  168. }
  169. break;
  170. default:
  171. break;
  172. }
  173. break;
  174. case 'cancelled':
  175. $notificationService = app(NotificationService::class);
  176. switch (Auth::user()?->type) {
  177. case UserTypeEnum::CLIENT:
  178. $notificationService->create([
  179. 'title' => __('notifications.schedule_cancelled_title'),
  180. 'description' => __('notifications.client_cancelled_schedule_description'),
  181. 'origin' => 'schedule',
  182. 'origin_id' => $schedule->id,
  183. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_CANCELLED->value,
  184. 'user_id' => $schedule->provider->user_id,
  185. ]);
  186. break;
  187. case UserTypeEnum::PROVIDER:
  188. $notificationService->create([
  189. 'title' => __('notifications.schedule_cancelled_title'),
  190. 'description' => __('notifications.provider_cancelled_schedule_description', ['provider' => $schedule->provider->user->name]),
  191. 'origin' => 'schedule',
  192. 'origin_id' => $schedule->id,
  193. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_CANCELLED->value,
  194. 'user_id' => $schedule->client->user_id,
  195. ]);
  196. break;
  197. default:
  198. break;
  199. }
  200. break;
  201. case 'started':
  202. $notificationService = app(NotificationService::class);
  203. // CLIENTE
  204. $notificationService->create([
  205. 'title' => __('notifications.provider_on_the_way_title'),
  206. 'description' => __('notifications.provider_on_the_way_description', ['code' => $schedule->code]),
  207. 'origin' => 'schedule',
  208. 'origin_id' => $schedule->id,
  209. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_COMING->value,
  210. 'user_id' => $schedule->client->user_id,
  211. ]);
  212. // PRESTADOR
  213. $notificationService->create([
  214. 'title' => __('notifications.service_start_title'),
  215. 'description' => __('notifications.service_start_description'),
  216. 'origin' => 'schedule',
  217. 'origin_id' => $schedule->id,
  218. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_START->value,
  219. 'user_id' => $schedule->provider->user_id,
  220. ]);
  221. break;
  222. case 'finished':
  223. $notificationService = app(NotificationService::class);
  224. // CLIENTE
  225. $notificationService->create([
  226. 'title' => __('notifications.service_finished_title'),
  227. 'description' => __('notifications.service_finished_description'),
  228. 'origin' => 'schedule',
  229. 'origin_id' => $schedule->id,
  230. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_FINISHED->value,
  231. 'user_id' => $schedule->client->user_id,
  232. ]);
  233. break;
  234. case 'paid':
  235. $notificationService = app(NotificationService::class);
  236. switch (Auth::user()?->type) {
  237. case UserTypeEnum::CLIENT:
  238. if ($schedule->provider_id) {
  239. $notificationService->create([
  240. 'title' => __('notifications.payment_confirmed_title'),
  241. 'description' => __('notifications.payment_confirmed_description'),
  242. 'origin' => 'schedule',
  243. 'origin_id' => $schedule->id,
  244. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_START->value,
  245. 'user_id' => $schedule->provider->user_id,
  246. ]);
  247. }
  248. break;
  249. default:
  250. break;
  251. }
  252. $date_cleaned = Carbon::parse($schedule->date)
  253. ->format('Y-m-d');
  254. $date_time_dispatch = Carbon::parse(
  255. $date_cleaned . ' ' . $schedule->start_time
  256. )->subHour();
  257. StartScheduleJob::dispatch($schedule->id)
  258. ->delay($date_time_dispatch);
  259. break;
  260. case 'rejected':
  261. $notificationService = app(NotificationService::class);
  262. $notificationService->create([
  263. 'title' => __('notifications.schedule_refused_title'),
  264. 'description' => __('notifications.schedule_refused_description'),
  265. 'origin' => 'schedule',
  266. 'origin_id' => $schedule->id,
  267. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_REFUSED->value,
  268. 'user_id' => $schedule->client->user_id,
  269. ]);
  270. break;
  271. }
  272. DB::commit();
  273. return $schedule->fresh(['client.user', 'provider.user', 'address']);
  274. } catch (ScheduleStatusTransitionException $e) {
  275. DB::rollBack();
  276. throw $e;
  277. } catch (\Exception $e) {
  278. DB::rollBack();
  279. Log::error('Erro ao atualizar status do agendamento: ' . $e->getMessage());
  280. throw $e;
  281. }
  282. }
  283. //
  284. public function getClientProviderBlocks(int $clientId, int $providerId): array
  285. {
  286. $today = Carbon::today()->format('Y-m-d');
  287. $schedules = Schedule::where('client_id', $clientId)
  288. ->where('provider_id', $providerId)
  289. ->whereNotIn('status', self::EXCLUDED_STATUSES)
  290. ->whereDate('date', '>=', $today)
  291. ->orderBy('date')
  292. ->orderBy('start_time')
  293. ->get(['id', 'date', 'start_time', 'end_time', 'status']);
  294. $existingSchedules = $schedules->map(function ($schedule) {
  295. return [
  296. 'id' => $schedule->id,
  297. 'date' => Carbon::parse($schedule->date)->format('Y-m-d'),
  298. 'start_time' => $schedule->start_time,
  299. 'end_time' => $schedule->end_time,
  300. 'status' => $schedule->status,
  301. ];
  302. })->values();
  303. $fullyBlockedWeeks = $schedules
  304. ->groupBy(function ($schedule) {
  305. return Carbon::parse($schedule->date)
  306. ->startOfWeek(Carbon::SUNDAY)
  307. ->format('Y-m-d');
  308. })
  309. ->filter(function ($weekSchedules) {
  310. return $weekSchedules->count() >= 2;
  311. })
  312. ->keys()
  313. ->values();
  314. return [
  315. 'existing_schedules' => $existingSchedules,
  316. 'fully_blocked_weeks' => $fullyBlockedWeeks,
  317. ];
  318. }
  319. public function getFinished()
  320. {
  321. return Schedule::with(['client.user', 'provider.user'])
  322. ->where('status', 'finished')
  323. ->orderBy('date', 'desc')
  324. ->orderBy('start_time', 'desc')
  325. ->get();
  326. }
  327. public function getSchedulesDefaultGroupedByClient()
  328. {
  329. $schedules = Schedule::with(['client.user', 'provider.user', 'address', 'reviews.reviewsImprovements.improvementType'])
  330. ->orderBy('id', 'desc')
  331. ->where('schedule_type', 'default')
  332. ->select(
  333. 'schedules.*'
  334. )
  335. ->get();
  336. $grouped = $schedules->groupBy('client_id')->map(function ($clientSchedules) {
  337. $firstSchedule = $clientSchedules->first();
  338. return [
  339. 'client_id' => $firstSchedule->client_id,
  340. 'client_name' => $firstSchedule->client->user->name ?? 'N/A',
  341. 'schedules' => $clientSchedules->map(function ($schedule) {
  342. return [
  343. 'id' => $schedule->id,
  344. 'date' => $schedule->date ? Carbon::parse($schedule->date)->format('d/m/Y') : null,
  345. 'start_time' => $schedule->start_time,
  346. 'end_time' => $schedule->end_time,
  347. 'period_type' => $schedule->period_type,
  348. 'status' => $schedule->status,
  349. 'total_amount' => $schedule->total_amount,
  350. 'code' => $schedule->code,
  351. 'code_verified' => $schedule->code_verified,
  352. 'client_id' => $schedule->client_id,
  353. 'provider_id' => $schedule->provider_id,
  354. 'provider_name' => $schedule->provider->user->name ?? 'N/A',
  355. 'address' => $schedule->address ? [
  356. 'id' => $schedule->address->id,
  357. 'address' => $schedule->address->address,
  358. 'complement' => $schedule->address->complement,
  359. 'zip_code' => $schedule->address->zip_code,
  360. 'city' => $schedule->address->city->name ?? '',
  361. 'state' => $schedule->address->city->state->name ?? '',
  362. ] : null,
  363. 'client_name' => $schedule->client->user->name ?? 'N/A',
  364. 'reviews' => $schedule->reviews->map(function ($review) {
  365. return [
  366. 'id' => $review->id,
  367. 'stars' => $review->stars,
  368. 'comment' => $review->comment,
  369. 'origin' => $review->origin,
  370. 'origin_id' => $review->origin_id,
  371. 'created_at' => Carbon::parse($review->created_at)->format('Y-m-d H:i'),
  372. 'updated_at' => Carbon::parse($review->updated_at)->format('Y-m-d H:i'),
  373. 'improvements' => $review->reviewsImprovements->map(function ($ri) {
  374. return [
  375. 'id' => $ri->id,
  376. 'improvement_type_id' => $ri->improvement_type_id,
  377. 'improvement_type_name' => $ri->improvementType ? $ri->improvementType->description : null,
  378. ];
  379. })->values(),
  380. ];
  381. }),
  382. ];
  383. })->values(),
  384. ];
  385. })->sortBy('id')->values();
  386. return $grouped;
  387. }
  388. //
  389. public function cancelWithReason(int $id, string $cancelText)
  390. {
  391. try {
  392. DB::beginTransaction();
  393. $schedule = Schedule::findOrFail($id);
  394. $allowedStatuses = ['accepted', 'paid', 'pending'];
  395. if (! in_array($schedule->status, $allowedStatuses)) {
  396. throw new ScheduleStatusTransitionException;
  397. }
  398. $cancelled_by = Auth::user()->type;
  399. $schedule->update([
  400. 'status' => 'cancelled',
  401. 'cancel_text' => $cancelText,
  402. 'cancelled_by' => $cancelled_by,
  403. ]);
  404. $this->cascadeCancelServicePackages($schedule, $cancelText, $cancelled_by);
  405. DB::commit();
  406. return $schedule->fresh(['client.user', 'provider.user', 'address']);
  407. } catch (ScheduleStatusTransitionException $e) {
  408. DB::rollBack();
  409. throw $e;
  410. } catch (\Exception $e) {
  411. DB::rollBack();
  412. Log::error('Erro ao cancelar agendamento: ' . $e->getMessage());
  413. throw $e;
  414. }
  415. }
  416. private function cascadeCancelServicePackages(Schedule $schedule, string $cancelText, $cancelledBy): void
  417. {
  418. $packageIds = DB::table('service_package_items')
  419. ->where('schedule_id', $schedule->id)
  420. ->pluck('service_package_id');
  421. if ($packageIds->isEmpty()) {
  422. return;
  423. }
  424. $packages = ServicePackage::query()
  425. ->with('items.schedule')
  426. ->whereIn('id', $packageIds)
  427. ->get();
  428. foreach ($packages as $package) {
  429. $siblingSchedules = $package->items->pluck('schedule')->filter();
  430. $siblingSchedules
  431. ->filter(fn (Schedule $sibling) => $sibling->id !== $schedule->id
  432. && in_array($sibling->status, ['pending', 'accepted', 'paid'], true))
  433. ->each(fn (Schedule $sibling) => $sibling->update([
  434. 'status' => 'cancelled',
  435. 'cancel_text' => $cancelText,
  436. 'cancelled_by' => $cancelledBy,
  437. ]));
  438. $hasRealizedSchedule = $siblingSchedules->contains(
  439. fn (Schedule $sibling) => in_array($sibling->status, ['started', 'finished'], true),
  440. );
  441. if ($package->status === ServicePackageStatusEnum::OPEN
  442. || ($package->status === ServicePackageStatusEnum::PAID && ! $hasRealizedSchedule)) {
  443. $package->update(['status' => ServicePackageStatusEnum::CANCELLED->value]);
  444. }
  445. }
  446. }
  447. //
  448. private function sendProviderAcceptedPush(Schedule $schedule): void
  449. {
  450. $user = $schedule->client->user;
  451. if (! $user) {
  452. Log::warning('Push de aceite ignorada: cliente sem usuário', [
  453. 'schedule_id' => $schedule->id,
  454. ]);
  455. return;
  456. }
  457. try {
  458. app(PushNotificationService::class)->sendToUser(
  459. $user,
  460. new PrestadorAceitouPush($schedule->provider->user->name)
  461. );
  462. } catch (\Throwable $exception) {
  463. Log::error('Falha ao enviar push de aceite do prestador', [
  464. 'schedule_id' => $schedule->id,
  465. 'user_id' => $user->id,
  466. 'error' => $exception->getMessage(),
  467. ]);
  468. }
  469. }
  470. private function calculateAmount(Provider $provider, string $periodType): float
  471. {
  472. $hourlyRates = [
  473. '2' => $provider->daily_price_2h ?? 0,
  474. '4' => $provider->daily_price_4h ?? 0,
  475. '6' => $provider->daily_price_6h ?? 0,
  476. '8' => $provider->daily_price_8h ?? 0,
  477. ];
  478. return data_get($hourlyRates, $periodType, 0);
  479. }
  480. private function validateProviderAvailability(array $data, $excludeScheduleId = null)
  481. {
  482. $provider_id = data_get($data, 'provider_id');
  483. $client_id = data_get($data, 'client_id');
  484. $date = Carbon::parse(data_get($data, 'date'));
  485. $dayOfWeek = $date->dayOfWeek;
  486. $startTime = data_get($data, 'start_time');
  487. $endTime = data_get($data, 'end_time');
  488. $date_ymd = $date->format('Y-m-d');
  489. $period = $startTime < '13:00:00' ? 'morning' : 'afternoon';
  490. ScheduleBusinessRules::validateProviderVisibleToCustomers($provider_id);
  491. // bloqueio 2 schedules por semana para o mesmo client e provider
  492. ScheduleBusinessRules::validateWeeklyScheduleLimit(
  493. $client_id,
  494. $provider_id,
  495. data_get($data, 'date'),
  496. $excludeScheduleId
  497. );
  498. // bloqueio provider trabalha no dia/periodo
  499. ScheduleBusinessRules::validateWorkingDay(
  500. $provider_id,
  501. $dayOfWeek,
  502. $period
  503. );
  504. // bloqueio provider tem blockedday para dia/hora
  505. ScheduleBusinessRules::validateBlockedDay(
  506. $provider_id,
  507. $date->format('Y-m-d'),
  508. $startTime,
  509. $endTime
  510. );
  511. // bloqueio provider tem outro agendamento para dia/hora
  512. ScheduleBusinessRules::validateConflictingSchedule(
  513. $provider_id,
  514. $date->format('Y-m-d'),
  515. $startTime,
  516. $endTime,
  517. $excludeScheduleId
  518. );
  519. // bloqueio provider tem outra proposta na mesma data
  520. ScheduleBusinessRules::validateConflictingProposalSameDate(
  521. $provider_id,
  522. $date_ymd,
  523. $startTime,
  524. $endTime,
  525. null
  526. );
  527. // bloqueio caso o client tenha bloqueado o provider
  528. ScheduleBusinessRules::validateClientNotBlockedByProvider(
  529. $client_id,
  530. $provider_id
  531. );
  532. // bloqueio caso o provider tenha bloqueado o client
  533. ScheduleBusinessRules::validateProviderNotBlockedByClient(
  534. $client_id,
  535. $provider_id
  536. );
  537. return true;
  538. }
  539. }