ScheduleService.php 24 KB

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