ScheduleService.php 23 KB

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