ScheduleService.php 22 KB

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