ScheduleService.php 25 KB

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