ScheduleService.php 21 KB

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