ScheduleService.php 21 KB

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