ScheduleService.php 21 KB

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