ScheduleService.php 19 KB

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