ScheduleService.php 19 KB

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