ScheduleService.php 19 KB

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