ScheduleService.php 22 KB

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