ScheduleService.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. <?php
  2. namespace App\Services;
  3. use App\Exceptions\ScheduleStatusTransitionException;
  4. use App\Enums\UserTypeEnum;
  5. use App\Enums\NotificationTypeEnum;
  6. use App\Jobs\StartScheduleJob;
  7. use App\Models\Provider;
  8. use App\Models\Schedule;
  9. use App\Rules\ScheduleBusinessRules;
  10. use App\Services\NotificationService;
  11. use Carbon\Carbon;
  12. use Illuminate\Support\Facades\Auth;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. class ScheduleService
  16. {
  17. private const EXCLUDED_STATUSES = ['cancelled', 'rejected'];
  18. public function getAll()
  19. {
  20. return Schedule::with(['client.user', 'provider.user', 'address'])
  21. ->where('schedule_type', 'default')
  22. ->orderBy('date', 'desc')
  23. ->orderBy('start_time', 'desc')
  24. ->get();
  25. }
  26. public function getById($id)
  27. {
  28. return Schedule::with(['client.user', 'provider.user', 'address'])->findOrFail($id);
  29. }
  30. public function create(array $data): Schedule
  31. {
  32. return data_get($this->createSingleOrMultiple([], [$data]), 0);
  33. }
  34. public function createSingleOrMultiple(array $baseData, array $schedules)
  35. {
  36. try {
  37. DB::beginTransaction();
  38. $createdSchedules = [];
  39. foreach ($schedules as $schedule) {
  40. $datasMerged = array_merge($baseData, $schedule);
  41. if (data_get($datasMerged, 'schedule_type', 'default') === 'default') {
  42. $provider = Provider::findOrFail(data_get($datasMerged, 'provider_id'));
  43. $datasMerged['total_amount'] = $this->calculateAmount(
  44. $provider,
  45. (string) data_get($datasMerged, 'period_type'),
  46. );
  47. }
  48. $this->validateProviderAvailability($datasMerged, null);
  49. $scheduleData = array_merge($datasMerged, [
  50. 'code' => str_pad(random_int(0, 9999), 4, '0', STR_PAD_LEFT),
  51. ]);
  52. $newSchedule = Schedule::create($scheduleData);
  53. // NOTIFICAÇÃO PRESTADOR
  54. if ($newSchedule->provider_id) {
  55. $notificationService = app(NotificationService::class);
  56. $notificationService->create([
  57. 'title' => __('notifications.new_schedule_request_title'),
  58. 'description' => __('notifications.new_schedule_request_description'),
  59. 'origin' => 'schedule',
  60. 'origin_id' => $newSchedule->id,
  61. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_NEW_SOLICITATION->value,
  62. 'user_id' => $newSchedule->provider->user_id,
  63. ]);
  64. }
  65. $createdSchedules[] = $newSchedule;
  66. }
  67. DB::commit();
  68. } catch (\Exception $e) {
  69. DB::rollBack();
  70. throw $e;
  71. }
  72. return $createdSchedules;
  73. }
  74. public function update($id, array $data)
  75. {
  76. unset($data['status']);
  77. $schedule = Schedule::with(['provider.user', 'client.user', 'address'])->findOrFail($id);
  78. if (data_get($data, 'provider_id') !== null || data_get($data, 'period_type') !== null) {
  79. $providerId = data_get($data, 'provider_id', $schedule->provider_id);
  80. $periodType = data_get($data, 'period_type', $schedule->period_type);
  81. $provider = Provider::findOrFail($providerId);
  82. $data['total_amount'] = $this->calculateAmount($provider, $periodType);
  83. }
  84. if (data_get($data, 'date') !== null || data_get($data, 'start_time') !== null || data_get($data, 'provider_id') !== null) {
  85. $validationData = array_merge($schedule->toArray(), $data);
  86. $this->validateProviderAvailability($validationData, $id);
  87. }
  88. $schedule->update($data);
  89. return $schedule->fresh(['client.user', 'provider.user', 'address']);
  90. }
  91. public function delete($id)
  92. {
  93. $schedule = Schedule::findOrFail($id);
  94. $schedule->delete();
  95. return $schedule;
  96. }
  97. //
  98. public function updateStatus($id, string $status, bool $fromPackage = false)
  99. {
  100. try {
  101. DB::beginTransaction();
  102. $schedule = Schedule::with(['provider.user', 'client.user', 'address'])->findOrFail($id);
  103. if (! $fromPackage && in_array($status, ['accepted', 'rejected']) && Auth::user()->type === UserTypeEnum::PROVIDER) {
  104. $belongsToServicePackage = DB::table('service_package_items')
  105. ->where('schedule_id', $schedule->id)
  106. ->exists();
  107. if ($belongsToServicePackage) {
  108. throw new \DomainException(__('messages.schedule_belongs_to_package_use_package_endpoint'));
  109. }
  110. }
  111. $allowedTransitions = [
  112. 'pending' => ['accepted', 'rejected', 'cancelled'],
  113. 'accepted' => ['paid', 'cancelled'],
  114. 'paid' => ['cancelled', 'started'],
  115. 'started' => ['finished'],
  116. 'rejected' => [],
  117. 'cancelled' => [],
  118. 'finished' => [],
  119. ];
  120. $currentStatus = $schedule->status;
  121. if (data_get($allowedTransitions, $currentStatus) === null) {
  122. throw new ScheduleStatusTransitionException;
  123. }
  124. if (! in_array($status, data_get($allowedTransitions, $currentStatus))) {
  125. throw new ScheduleStatusTransitionException;
  126. }
  127. $schedule->update(['status' => $status]);
  128. $schedule->refresh();
  129. $currentStatus = $schedule->status;
  130. switch ($status) {
  131. case 'pending':
  132. break;
  133. case 'accepted':
  134. $notificationService = app(NotificationService::class);
  135. switch (Auth::user()->type) {
  136. case UserTypeEnum::PROVIDER:
  137. $notificationService->create([
  138. 'title' => __('notifications.schedule_accepted_title'),
  139. 'description' => __('notifications.provider_accepted_schedule_description', ['provider' => $schedule->provider->user->name]),
  140. 'origin' => 'schedule',
  141. 'origin_id' => $schedule->id,
  142. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_ACCEPTED->value,
  143. 'user_id' => $schedule->client->user_id,
  144. ]);
  145. break;
  146. case UserTypeEnum::CLIENT:
  147. if ($schedule->provider_id) {
  148. $notificationService->create([
  149. 'title' => __('notifications.proposal_accepted_title'),
  150. 'description' => __('notifications.proposal_accepted_description'),
  151. 'origin' => 'schedule',
  152. 'origin_id' => $schedule->id,
  153. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_PROPOSAL_ACCEPTED->value,
  154. 'user_id' => $schedule->provider->user_id,
  155. ]);
  156. }
  157. break;
  158. default:
  159. break;
  160. }
  161. break;
  162. case 'cancelled':
  163. $notificationService = app(NotificationService::class);
  164. switch (Auth::user()->type) {
  165. case UserTypeEnum::CLIENT:
  166. $notificationService->create([
  167. 'title' => __('notifications.schedule_cancelled_title'),
  168. 'description' => __('notifications.client_cancelled_schedule_description'),
  169. 'origin' => 'schedule',
  170. 'origin_id' => $schedule->id,
  171. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_CANCELLED->value,
  172. 'user_id' => $schedule->provider->user_id,
  173. ]);
  174. break;
  175. case UserTypeEnum::PROVIDER:
  176. $notificationService->create([
  177. 'title' => __('notifications.schedule_cancelled_title'),
  178. 'description' => __('notifications.provider_cancelled_schedule_description', ['provider' => $schedule->provider->user->name]),
  179. 'origin' => 'schedule',
  180. 'origin_id' => $schedule->id,
  181. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_CANCELLED->value,
  182. 'user_id' => $schedule->client->user_id,
  183. ]);
  184. break;
  185. default:
  186. break;
  187. }
  188. break;
  189. case 'started':
  190. $notificationService = app(NotificationService::class);
  191. // CLIENTE
  192. $notificationService->create([
  193. 'title' => __('notifications.provider_on_the_way_title'),
  194. 'description' => __('notifications.provider_on_the_way_description', ['code' => $schedule->code]),
  195. 'origin' => 'schedule',
  196. 'origin_id' => $schedule->id,
  197. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_COMING->value,
  198. 'user_id' => $schedule->client->user_id,
  199. ]);
  200. // PRESTADOR
  201. $notificationService->create([
  202. 'title' => __('notifications.service_start_title'),
  203. 'description' => __('notifications.service_start_description'),
  204. 'origin' => 'schedule',
  205. 'origin_id' => $schedule->id,
  206. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_START->value,
  207. 'user_id' => $schedule->provider->user_id,
  208. ]);
  209. break;
  210. case 'finished':
  211. $notificationService = app(NotificationService::class);
  212. // CLIENTE
  213. $notificationService->create([
  214. 'title' => __('notifications.service_finished_title'),
  215. 'description' => __('notifications.service_finished_description'),
  216. 'origin' => 'schedule',
  217. 'origin_id' => $schedule->id,
  218. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_FINISHED->value,
  219. 'user_id' => $schedule->client->user_id,
  220. ]);
  221. break;
  222. case 'paid':
  223. $notificationService = app(NotificationService::class);
  224. switch (Auth::user()->type) {
  225. case UserTypeEnum::CLIENT:
  226. if ($schedule->provider_id) {
  227. $notificationService->create([
  228. 'title' => __('notifications.payment_confirmed_title'),
  229. 'description' => __('notifications.payment_confirmed_description'),
  230. 'origin' => 'schedule',
  231. 'origin_id' => $schedule->id,
  232. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_START->value,
  233. 'user_id' => $schedule->provider->user_id,
  234. ]);
  235. }
  236. break;
  237. default:
  238. break;
  239. }
  240. $date_cleaned = Carbon::parse($schedule->date)
  241. ->format('Y-m-d');
  242. $date_time_dispatch = Carbon::parse(
  243. $date_cleaned . ' ' . $schedule->start_time
  244. )->subHour();
  245. StartScheduleJob::dispatch($schedule->id)
  246. ->delay($date_time_dispatch);
  247. break;
  248. case 'rejected':
  249. $notificationService = app(NotificationService::class);
  250. $notificationService->create([
  251. 'title' => __('notifications.schedule_refused_title'),
  252. 'description' => __('notifications.schedule_refused_description'),
  253. 'origin' => 'schedule',
  254. 'origin_id' => $schedule->id,
  255. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_REFUSED->value,
  256. 'user_id' => $schedule->client->user_id,
  257. ]);
  258. break;
  259. }
  260. DB::commit();
  261. return $schedule->fresh(['client.user', 'provider.user', 'address']);
  262. } catch (ScheduleStatusTransitionException $e) {
  263. DB::rollBack();
  264. throw $e;
  265. } catch (\Exception $e) {
  266. DB::rollBack();
  267. Log::error('Erro ao atualizar status do agendamento: ' . $e->getMessage());
  268. throw $e;
  269. }
  270. }
  271. //
  272. public function getClientProviderBlocks(int $clientId, int $providerId): array
  273. {
  274. $today = Carbon::today()->format('Y-m-d');
  275. $schedules = Schedule::where('client_id', $clientId)
  276. ->where('provider_id', $providerId)
  277. ->whereNotIn('status', self::EXCLUDED_STATUSES)
  278. ->whereDate('date', '>=', $today)
  279. ->orderBy('date')
  280. ->orderBy('start_time')
  281. ->get(['id', 'date', 'start_time', 'end_time', 'status']);
  282. $existingSchedules = $schedules->map(function ($schedule) {
  283. return [
  284. 'id' => $schedule->id,
  285. 'date' => Carbon::parse($schedule->date)->format('Y-m-d'),
  286. 'start_time' => $schedule->start_time,
  287. 'end_time' => $schedule->end_time,
  288. 'status' => $schedule->status,
  289. ];
  290. })->values();
  291. $fullyBlockedWeeks = $schedules
  292. ->groupBy(function ($schedule) {
  293. return Carbon::parse($schedule->date)
  294. ->startOfWeek(Carbon::SUNDAY)
  295. ->format('Y-m-d');
  296. })
  297. ->filter(function ($weekSchedules) {
  298. return $weekSchedules->count() >= 2;
  299. })
  300. ->keys()
  301. ->values();
  302. return [
  303. 'existing_schedules' => $existingSchedules,
  304. 'fully_blocked_weeks' => $fullyBlockedWeeks,
  305. ];
  306. }
  307. public function getFinished()
  308. {
  309. return Schedule::with(['client.user', 'provider.user'])
  310. ->where('status', 'finished')
  311. ->orderBy('date', 'desc')
  312. ->orderBy('start_time', 'desc')
  313. ->get();
  314. }
  315. public function getSchedulesDefaultGroupedByClient()
  316. {
  317. $schedules = Schedule::with(['client.user', 'provider.user', 'address', 'reviews.reviewsImprovements.improvementType'])
  318. ->orderBy('id', 'desc')
  319. ->where('schedule_type', 'default')
  320. ->select(
  321. 'schedules.*'
  322. )
  323. ->get();
  324. $grouped = $schedules->groupBy('client_id')->map(function ($clientSchedules) {
  325. $firstSchedule = $clientSchedules->first();
  326. return [
  327. 'client_id' => $firstSchedule->client_id,
  328. 'client_name' => $firstSchedule->client->user->name ?? 'N/A',
  329. 'schedules' => $clientSchedules->map(function ($schedule) {
  330. return [
  331. 'id' => $schedule->id,
  332. 'date' => $schedule->date ? Carbon::parse($schedule->date)->format('d/m/Y') : null,
  333. 'start_time' => $schedule->start_time,
  334. 'end_time' => $schedule->end_time,
  335. 'period_type' => $schedule->period_type,
  336. 'status' => $schedule->status,
  337. 'total_amount' => $schedule->total_amount,
  338. 'code' => $schedule->code,
  339. 'code_verified' => $schedule->code_verified,
  340. 'client_id' => $schedule->client_id,
  341. 'provider_id' => $schedule->provider_id,
  342. 'provider_name' => $schedule->provider->user->name ?? 'N/A',
  343. 'address' => $schedule->address ? [
  344. 'id' => $schedule->address->id,
  345. 'address' => $schedule->address->address,
  346. 'complement' => $schedule->address->complement,
  347. 'zip_code' => $schedule->address->zip_code,
  348. 'city' => $schedule->address->city->name ?? '',
  349. 'state' => $schedule->address->city->state->name ?? '',
  350. ] : null,
  351. 'client_name' => $schedule->client->user->name ?? 'N/A',
  352. 'reviews' => $schedule->reviews->map(function ($review) {
  353. return [
  354. 'id' => $review->id,
  355. 'stars' => $review->stars,
  356. 'comment' => $review->comment,
  357. 'origin' => $review->origin,
  358. 'origin_id' => $review->origin_id,
  359. 'created_at' => Carbon::parse($review->created_at)->format('Y-m-d H:i'),
  360. 'updated_at' => Carbon::parse($review->updated_at)->format('Y-m-d H:i'),
  361. 'improvements' => $review->reviewsImprovements->map(function ($ri) {
  362. return [
  363. 'id' => $ri->id,
  364. 'improvement_type_id' => $ri->improvement_type_id,
  365. 'improvement_type_name' => $ri->improvementType ? $ri->improvementType->description : null,
  366. ];
  367. })->values(),
  368. ];
  369. }),
  370. ];
  371. })->values(),
  372. ];
  373. })->sortBy('id')->values();
  374. return $grouped;
  375. }
  376. //
  377. public function cancelWithReason(int $id, string $cancelText)
  378. {
  379. try {
  380. DB::beginTransaction();
  381. $schedule = Schedule::findOrFail($id);
  382. $allowedStatuses = ['accepted', 'paid', 'pending'];
  383. if (! in_array($schedule->status, $allowedStatuses)) {
  384. throw new ScheduleStatusTransitionException;
  385. }
  386. $cancelled_by = Auth::user()->type;
  387. $schedule->update([
  388. 'status' => 'cancelled',
  389. 'cancel_text' => $cancelText,
  390. 'cancelled_by' => $cancelled_by,
  391. ]);
  392. DB::commit();
  393. return $schedule->fresh(['client.user', 'provider.user', 'address']);
  394. } catch (ScheduleStatusTransitionException $e) {
  395. DB::rollBack();
  396. throw $e;
  397. } catch (\Exception $e) {
  398. DB::rollBack();
  399. Log::error('Erro ao cancelar agendamento: '.$e->getMessage());
  400. throw $e;
  401. }
  402. }
  403. //
  404. private function calculateAmount(Provider $provider, string $periodType): float
  405. {
  406. $hourlyRates = [
  407. '2' => $provider->daily_price_2h ?? 0,
  408. '4' => $provider->daily_price_4h ?? 0,
  409. '6' => $provider->daily_price_6h ?? 0,
  410. '8' => $provider->daily_price_8h ?? 0,
  411. ];
  412. return data_get($hourlyRates, $periodType, 0);
  413. }
  414. private function validateProviderAvailability(array $data, $excludeScheduleId = null)
  415. {
  416. $provider_id = data_get($data, 'provider_id');
  417. $client_id = data_get($data, 'client_id');
  418. $date = Carbon::parse(data_get($data, 'date'));
  419. $dayOfWeek = $date->dayOfWeek;
  420. $startTime = data_get($data, 'start_time');
  421. $endTime = data_get($data, 'end_time');
  422. $date_ymd = $date->format('Y-m-d');
  423. $period = $startTime < '13:00:00' ? 'morning' : 'afternoon';
  424. ScheduleBusinessRules::validateProviderVisibleToCustomers($provider_id);
  425. // bloqueio 2 schedules por semana para o mesmo client e provider
  426. ScheduleBusinessRules::validateWeeklyScheduleLimit(
  427. $client_id,
  428. $provider_id,
  429. data_get($data, 'date'),
  430. $excludeScheduleId
  431. );
  432. // bloqueio provider trabalha no dia/periodo
  433. ScheduleBusinessRules::validateWorkingDay(
  434. $provider_id,
  435. $dayOfWeek,
  436. $period
  437. );
  438. // bloqueio provider tem blockedday para dia/hora
  439. ScheduleBusinessRules::validateBlockedDay(
  440. $provider_id,
  441. $date->format('Y-m-d'),
  442. $startTime,
  443. $endTime
  444. );
  445. // bloqueio provider tem outro agendamento para dia/hora
  446. ScheduleBusinessRules::validateConflictingSchedule(
  447. $provider_id,
  448. $date->format('Y-m-d'),
  449. $startTime,
  450. $endTime,
  451. $excludeScheduleId
  452. );
  453. // bloqueio provider tem outra proposta na mesma data
  454. ScheduleBusinessRules::validateConflictingProposalSameDate(
  455. $provider_id,
  456. $date_ymd,
  457. $startTime,
  458. $endTime,
  459. null
  460. );
  461. // bloqueio caso o client tenha bloqueado o provider
  462. ScheduleBusinessRules::validateClientNotBlockedByProvider(
  463. $client_id,
  464. $provider_id
  465. );
  466. // bloqueio caso o provider tenha bloqueado o client
  467. ScheduleBusinessRules::validateProviderNotBlockedByClient(
  468. $client_id,
  469. $provider_id
  470. );
  471. return true;
  472. }
  473. }