ScheduleService.php 23 KB

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