ScheduleService.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. <?php
  2. namespace App\Services;
  3. use App\Exceptions\ScheduleStatusTransitionException;
  4. use App\Enums\ServicePackageStatusEnum;
  5. use App\Enums\UserTypeEnum;
  6. use App\Enums\NotificationTypeEnum;
  7. use App\Jobs\StartScheduleJob;
  8. use App\Models\Provider;
  9. use App\Models\Schedule;
  10. use App\Models\ServicePackage;
  11. use App\Rules\ScheduleBusinessRules;
  12. use App\Services\NotificationService;
  13. use App\Services\PushNotificationService;
  14. use App\Notifications\Push\Cliente\Agendamento\PrestadorAceitouPush;
  15. use App\Notifications\Push\Cliente\Agendamento\PrestadorRecusouPush;
  16. use App\Notifications\Push\Prestador\Agendamento\ClienteAceitouPush;
  17. use App\Notifications\Push\Prestador\Pagamento\ClienteEfetuouPagamentoPush;
  18. use App\Notifications\Push\Cliente\Agendamento\PrestadorCancelouPush;
  19. use App\Notifications\Push\Prestador\Agendamento\ClienteCancelouPush;
  20. use App\Notifications\Push\Prestador\Agendamento\NewPushRequest;
  21. use Carbon\Carbon;
  22. use Illuminate\Support\Facades\Auth;
  23. use Illuminate\Support\Facades\DB;
  24. use Illuminate\Support\Facades\Log;
  25. class ScheduleService
  26. {
  27. private const EXCLUDED_STATUSES = ['cancelled', 'rejected'];
  28. public function getAll()
  29. {
  30. return Schedule::with(['client.user', 'provider.user', 'address'])
  31. ->where('schedule_type', 'default')
  32. ->orderBy('date', 'desc')
  33. ->orderBy('start_time', 'desc')
  34. ->get();
  35. }
  36. public function getById($id)
  37. {
  38. return Schedule::with(['client.user', 'provider.user', 'address'])->findOrFail($id);
  39. }
  40. public function create(array $data): Schedule
  41. {
  42. return data_get($this->createSingleOrMultiple([], [$data]), 0);
  43. }
  44. public function createSingleOrMultiple(array $baseData, array $schedules)
  45. {
  46. try {
  47. DB::beginTransaction();
  48. $createdSchedules = [];
  49. foreach ($schedules as $schedule) {
  50. $datasMerged = array_merge($baseData, $schedule);
  51. if (data_get($datasMerged, 'schedule_type', 'default') === 'default') {
  52. $provider = Provider::findOrFail(data_get($datasMerged, 'provider_id'));
  53. $datasMerged['total_amount'] = $this->calculateAmount(
  54. $provider,
  55. (string) data_get($datasMerged, 'period_type'),
  56. );
  57. }
  58. $this->validateProviderAvailability($datasMerged, null);
  59. $scheduleData = array_merge($datasMerged, [
  60. 'code' => str_pad(random_int(0, 9999), 4, '0', STR_PAD_LEFT),
  61. ]);
  62. $newSchedule = Schedule::create($scheduleData);
  63. // NOTIFICAÇÃO PRESTADOR
  64. if ($newSchedule->provider_id) {
  65. $notificationService = app(NotificationService::class);
  66. $notificationService->create([
  67. 'title' => __('notifications.new_schedule_request_title'),
  68. 'description' => __('notifications.new_schedule_request_description'),
  69. 'origin' => 'schedule',
  70. 'origin_id' => $newSchedule->id,
  71. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_NEW_SOLICITATION->value,
  72. 'user_id' => $newSchedule->provider->user_id,
  73. ]);
  74. // Push Notification
  75. $pushNotificationService = app(PushNotificationService::class);
  76. $pushNotificationService->sendToUser(
  77. $newSchedule->provider->user,
  78. new NewPushRequest($newSchedule->client->user->name)
  79. );
  80. }
  81. $createdSchedules[] = $newSchedule;
  82. }
  83. DB::commit();
  84. } catch (\Exception $e) {
  85. DB::rollBack();
  86. throw $e;
  87. }
  88. return $createdSchedules;
  89. }
  90. public function update($id, array $data)
  91. {
  92. unset($data['status']);
  93. $schedule = Schedule::with(['provider.user', 'client.user', 'address'])->findOrFail($id);
  94. if (data_get($data, 'provider_id') !== null || data_get($data, 'period_type') !== null) {
  95. $providerId = data_get($data, 'provider_id', $schedule->provider_id);
  96. $periodType = data_get($data, 'period_type', $schedule->period_type);
  97. $provider = Provider::findOrFail($providerId);
  98. $data['total_amount'] = $this->calculateAmount($provider, $periodType);
  99. }
  100. if (data_get($data, 'date') !== null || data_get($data, 'start_time') !== null || data_get($data, 'provider_id') !== null) {
  101. $validationData = array_merge($schedule->toArray(), $data);
  102. $this->validateProviderAvailability($validationData, $id);
  103. }
  104. $schedule->update($data);
  105. return $schedule->fresh(['client.user', 'provider.user', 'address']);
  106. }
  107. public function delete($id)
  108. {
  109. $schedule = Schedule::findOrFail($id);
  110. $schedule->delete();
  111. return $schedule;
  112. }
  113. //
  114. public function updateStatus($id, string $status, bool $fromPackage = false)
  115. {
  116. try {
  117. DB::beginTransaction();
  118. $schedule = Schedule::with(['provider.user', 'client.user', 'address'])->findOrFail($id);
  119. if (! $fromPackage && in_array($status, ['accepted', 'rejected']) && Auth::user()?->type === UserTypeEnum::PROVIDER) {
  120. $belongsToServicePackage = DB::table('service_package_items')
  121. ->where('schedule_id', $schedule->id)
  122. ->exists();
  123. if ($belongsToServicePackage) {
  124. throw new \DomainException(__('messages.schedule_belongs_to_package_use_package_endpoint'));
  125. }
  126. }
  127. $allowedTransitions = [
  128. 'pending' => ['accepted', 'rejected', 'paid', 'cancelled'],
  129. 'accepted' => ['paid', 'cancelled'],
  130. 'paid' => ['cancelled', 'started'],
  131. 'started' => ['finished'],
  132. 'rejected' => [],
  133. 'cancelled' => [],
  134. 'finished' => [],
  135. ];
  136. $currentStatus = $schedule->status;
  137. if (data_get($allowedTransitions, $currentStatus) === null) {
  138. throw new ScheduleStatusTransitionException;
  139. }
  140. if (! in_array($status, data_get($allowedTransitions, $currentStatus))) {
  141. log::info("Transição de status inválida: {$currentStatus} para {$status}");
  142. throw new ScheduleStatusTransitionException;
  143. }
  144. $schedule->update(['status' => $status]);
  145. $schedule->refresh();
  146. $currentStatus = $schedule->status;
  147. switch ($status) {
  148. case 'pending':
  149. break;
  150. case 'accepted':
  151. $notificationService = app(NotificationService::class);
  152. switch (Auth::user()?->type) {
  153. case UserTypeEnum::PROVIDER:
  154. $notificationService->create([
  155. 'title' => __('notifications.schedule_accepted_title'),
  156. 'description' => __('notifications.provider_accepted_schedule_description', ['provider' => $schedule->provider->user->name]),
  157. 'origin' => 'schedule',
  158. 'origin_id' => $schedule->id,
  159. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_ACCEPTED->value,
  160. 'user_id' => $schedule->client->user_id,
  161. ]);
  162. $this->sendProviderAcceptedPush($schedule);
  163. break;
  164. case UserTypeEnum::CLIENT:
  165. if ($schedule->provider_id) {
  166. $notificationService->create([
  167. 'title' => __('notifications.proposal_accepted_title'),
  168. 'description' => __('notifications.proposal_accepted_description'),
  169. 'origin' => 'schedule',
  170. 'origin_id' => $schedule->id,
  171. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_PROPOSAL_ACCEPTED->value,
  172. 'user_id' => $schedule->provider->user_id,
  173. ]);
  174. }
  175. $this->sendClientAcceptedPush($schedule);
  176. break;
  177. default:
  178. break;
  179. }
  180. break;
  181. case 'cancelled':
  182. $notificationService = app(NotificationService::class);
  183. switch (Auth::user()?->type) {
  184. case UserTypeEnum::CLIENT:
  185. $notificationService->create([
  186. 'title' => __('notifications.schedule_cancelled_title'),
  187. 'description' => __('notifications.client_cancelled_schedule_description'),
  188. 'origin' => 'schedule',
  189. 'origin_id' => $schedule->id,
  190. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_CANCELLED->value,
  191. 'user_id' => $schedule->provider->user_id,
  192. ]);
  193. $this->sendProviderCancelledPush($schedule);
  194. break;
  195. case UserTypeEnum::PROVIDER:
  196. $notificationService->create([
  197. 'title' => __('notifications.schedule_cancelled_title'),
  198. 'description' => __('notifications.provider_cancelled_schedule_description', ['provider' => $schedule->provider->user->name]),
  199. 'origin' => 'schedule',
  200. 'origin_id' => $schedule->id,
  201. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_CANCELLED->value,
  202. 'user_id' => $schedule->client->user_id,
  203. ]);
  204. $this->sendClientCancelledPush($schedule);
  205. break;
  206. default:
  207. break;
  208. }
  209. break;
  210. case 'started':
  211. $notificationService = app(NotificationService::class);
  212. // CLIENTE
  213. $notificationService->create([
  214. 'title' => __('notifications.provider_on_the_way_title'),
  215. 'description' => __('notifications.provider_on_the_way_description', ['code' => $schedule->code]),
  216. 'origin' => 'schedule',
  217. 'origin_id' => $schedule->id,
  218. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_COMING->value,
  219. 'user_id' => $schedule->client->user_id,
  220. ]);
  221. // PRESTADOR
  222. $notificationService->create([
  223. 'title' => __('notifications.service_start_title'),
  224. 'description' => __('notifications.service_start_description'),
  225. 'origin' => 'schedule',
  226. 'origin_id' => $schedule->id,
  227. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_START->value,
  228. 'user_id' => $schedule->provider->user_id,
  229. ]);
  230. break;
  231. case 'finished':
  232. $notificationService = app(NotificationService::class);
  233. // CLIENTE
  234. $notificationService->create([
  235. 'title' => __('notifications.service_finished_title'),
  236. 'description' => __('notifications.service_finished_description'),
  237. 'origin' => 'schedule',
  238. 'origin_id' => $schedule->id,
  239. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_FINISHED->value,
  240. 'user_id' => $schedule->client->user_id,
  241. ]);
  242. break;
  243. case 'paid':
  244. $notificationService = app(NotificationService::class);
  245. if ($schedule->provider_id) {
  246. $notificationService->create([
  247. 'title' => __('notifications.payment_confirmed_title'),
  248. 'description' => __('notifications.payment_confirmed_description'),
  249. 'origin' => 'schedule',
  250. 'origin_id' => $schedule->id,
  251. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_START->value,
  252. 'user_id' => $schedule->provider->user_id,
  253. ]);
  254. }
  255. $this->sendClientPaymentPush($schedule);
  256. $date_cleaned = Carbon::parse($schedule->date)
  257. ->format('Y-m-d');
  258. $date_time_dispatch = Carbon::parse(
  259. $date_cleaned . ' ' . $schedule->start_time
  260. )->subHour();
  261. StartScheduleJob::dispatch($schedule->id)
  262. ->delay($date_time_dispatch);
  263. break;
  264. case 'rejected':
  265. $notificationService = app(NotificationService::class);
  266. $notificationService->create([
  267. 'title' => __('notifications.schedule_refused_title'),
  268. 'description' => __('notifications.schedule_refused_description'),
  269. 'origin' => 'schedule',
  270. 'origin_id' => $schedule->id,
  271. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_REFUSED->value,
  272. 'user_id' => $schedule->client->user_id,
  273. ]);
  274. $this->sendProviderRefusedPush($schedule);
  275. break;
  276. }
  277. DB::commit();
  278. return $schedule->fresh(['client.user', 'provider.user', 'address']);
  279. } catch (ScheduleStatusTransitionException $e) {
  280. DB::rollBack();
  281. throw $e;
  282. } catch (\Exception $e) {
  283. DB::rollBack();
  284. Log::error('Erro ao atualizar status do agendamento: ' . $e->getMessage());
  285. throw $e;
  286. }
  287. }
  288. //
  289. public function getClientProviderBlocks(int $clientId, int $providerId): array
  290. {
  291. $today = Carbon::today()->format('Y-m-d');
  292. $schedules = Schedule::where('client_id', $clientId)
  293. ->where('provider_id', $providerId)
  294. ->whereNotIn('status', self::EXCLUDED_STATUSES)
  295. ->whereDate('date', '>=', $today)
  296. ->orderBy('date')
  297. ->orderBy('start_time')
  298. ->get(['id', 'date', 'start_time', 'end_time', 'status']);
  299. $existingSchedules = $schedules->map(function ($schedule) {
  300. return [
  301. 'id' => $schedule->id,
  302. 'date' => Carbon::parse($schedule->date)->format('Y-m-d'),
  303. 'start_time' => $schedule->start_time,
  304. 'end_time' => $schedule->end_time,
  305. 'status' => $schedule->status,
  306. ];
  307. })->values();
  308. $fullyBlockedWeeks = $schedules
  309. ->groupBy(function ($schedule) {
  310. return Carbon::parse($schedule->date)
  311. ->startOfWeek(Carbon::SUNDAY)
  312. ->format('Y-m-d');
  313. })
  314. ->filter(function ($weekSchedules) {
  315. return $weekSchedules->count() >= 2;
  316. })
  317. ->keys()
  318. ->values();
  319. return [
  320. 'existing_schedules' => $existingSchedules,
  321. 'fully_blocked_weeks' => $fullyBlockedWeeks,
  322. ];
  323. }
  324. public function getFinished()
  325. {
  326. return Schedule::with(['client.user', 'provider.user'])
  327. ->where('status', 'finished')
  328. ->orderBy('date', 'desc')
  329. ->orderBy('start_time', 'desc')
  330. ->get();
  331. }
  332. public function getSchedulesDefaultGroupedByClient()
  333. {
  334. $schedules = Schedule::with(['client.user', 'provider.user', 'address', 'reviews.reviewsImprovements.improvementType'])
  335. ->orderBy('id', 'desc')
  336. ->where('schedule_type', 'default')
  337. ->select(
  338. 'schedules.*'
  339. )
  340. ->get();
  341. $grouped = $schedules->groupBy('client_id')->map(function ($clientSchedules) {
  342. $firstSchedule = $clientSchedules->first();
  343. return [
  344. 'client_id' => $firstSchedule->client_id,
  345. 'client_name' => $firstSchedule->client->user->name ?? 'N/A',
  346. 'schedules' => $clientSchedules->map(function ($schedule) {
  347. return [
  348. 'id' => $schedule->id,
  349. 'date' => $schedule->date ? Carbon::parse($schedule->date)->format('d/m/Y') : null,
  350. 'start_time' => $schedule->start_time,
  351. 'end_time' => $schedule->end_time,
  352. 'period_type' => $schedule->period_type,
  353. 'status' => $schedule->status,
  354. 'total_amount' => $schedule->total_amount,
  355. 'code' => $schedule->code,
  356. 'code_verified' => $schedule->code_verified,
  357. 'client_id' => $schedule->client_id,
  358. 'provider_id' => $schedule->provider_id,
  359. 'provider_name' => $schedule->provider->user->name ?? 'N/A',
  360. 'address' => $schedule->address ? [
  361. 'id' => $schedule->address->id,
  362. 'address' => $schedule->address->address,
  363. 'complement' => $schedule->address->complement,
  364. 'zip_code' => $schedule->address->zip_code,
  365. 'city' => $schedule->address->city->name ?? '',
  366. 'state' => $schedule->address->city->state->name ?? '',
  367. ] : null,
  368. 'client_name' => $schedule->client->user->name ?? 'N/A',
  369. 'reviews' => $schedule->reviews->map(function ($review) {
  370. return [
  371. 'id' => $review->id,
  372. 'stars' => $review->stars,
  373. 'comment' => $review->comment,
  374. 'origin' => $review->origin,
  375. 'origin_id' => $review->origin_id,
  376. 'created_at' => Carbon::parse($review->created_at)->format('Y-m-d H:i'),
  377. 'updated_at' => Carbon::parse($review->updated_at)->format('Y-m-d H:i'),
  378. 'improvements' => $review->reviewsImprovements->map(function ($ri) {
  379. return [
  380. 'id' => $ri->id,
  381. 'improvement_type_id' => $ri->improvement_type_id,
  382. 'improvement_type_name' => $ri->improvementType ? $ri->improvementType->description : null,
  383. ];
  384. })->values(),
  385. ];
  386. }),
  387. ];
  388. })->values(),
  389. ];
  390. })->sortBy('id')->values();
  391. return $grouped;
  392. }
  393. //
  394. public function cancelWithReason(int $id, string $cancelText)
  395. {
  396. try {
  397. DB::beginTransaction();
  398. $schedule = Schedule::findOrFail($id);
  399. $allowedStatuses = ['accepted', 'paid', 'pending'];
  400. if (! in_array($schedule->status, $allowedStatuses)) {
  401. throw new ScheduleStatusTransitionException;
  402. }
  403. $cancelled_by = Auth::user()->type;
  404. $schedule->update([
  405. 'status' => 'cancelled',
  406. 'cancel_text' => $cancelText,
  407. 'cancelled_by' => $cancelled_by,
  408. ]);
  409. $this->cascadeCancelServicePackages($schedule, $cancelText, $cancelled_by);
  410. DB::commit();
  411. return $schedule->fresh(['client.user', 'provider.user', 'address']);
  412. } catch (ScheduleStatusTransitionException $e) {
  413. DB::rollBack();
  414. throw $e;
  415. } catch (\Exception $e) {
  416. DB::rollBack();
  417. Log::error('Erro ao cancelar agendamento: ' . $e->getMessage());
  418. throw $e;
  419. }
  420. }
  421. private function cascadeCancelServicePackages(Schedule $schedule, string $cancelText, $cancelledBy): void
  422. {
  423. $packageIds = DB::table('service_package_items')
  424. ->where('schedule_id', $schedule->id)
  425. ->pluck('service_package_id');
  426. if ($packageIds->isEmpty()) {
  427. return;
  428. }
  429. $packages = ServicePackage::query()
  430. ->with('items.schedule')
  431. ->whereIn('id', $packageIds)
  432. ->get();
  433. foreach ($packages as $package) {
  434. $siblingSchedules = $package->items->pluck('schedule')->filter();
  435. $siblingSchedules
  436. ->filter(fn(Schedule $sibling) => $sibling->id !== $schedule->id
  437. && in_array($sibling->status, ['pending', 'accepted', 'paid'], true))
  438. ->each(fn(Schedule $sibling) => $sibling->update([
  439. 'status' => 'cancelled',
  440. 'cancel_text' => $cancelText,
  441. 'cancelled_by' => $cancelledBy,
  442. ]));
  443. $hasRealizedSchedule = $siblingSchedules->contains(
  444. fn(Schedule $sibling) => in_array($sibling->status, ['started', 'finished'], true),
  445. );
  446. if (
  447. $package->status === ServicePackageStatusEnum::OPEN
  448. || ($package->status === ServicePackageStatusEnum::PAID && ! $hasRealizedSchedule)
  449. ) {
  450. $package->update(['status' => ServicePackageStatusEnum::CANCELLED->value]);
  451. }
  452. }
  453. }
  454. //Notificações por push do sistema
  455. private function sendProviderAcceptedPush(Schedule $schedule): void
  456. {
  457. $user = $schedule->client->user;
  458. if (! $user) {
  459. Log::warning('Push de aceite ignorada: cliente sem usuário', [
  460. 'schedule_id' => $schedule->id,
  461. ]);
  462. return;
  463. }
  464. try {
  465. app(PushNotificationService::class)->sendToUser(
  466. $user,
  467. new PrestadorAceitouPush($schedule->provider->user->name)
  468. );
  469. } catch (\Throwable $exception) {
  470. Log::error('Falha ao enviar push de aceite do prestador', [
  471. 'schedule_id' => $schedule->id,
  472. 'user_id' => $user->id,
  473. 'error' => $exception->getMessage(),
  474. ]);
  475. }
  476. }
  477. private function sendProviderRefusedPush(Schedule $schedule): void
  478. {
  479. $user = $schedule->client->user;
  480. if (! $user) {
  481. Log::warning('Push de recusa ignorada: cliente sem usuário', [
  482. 'schedule_id' => $schedule->id,
  483. ]);
  484. return;
  485. }
  486. try {
  487. app(PushNotificationService::class)->sendToUser(
  488. $user,
  489. new PrestadorRecusouPush(
  490. $schedule->provider->user->name
  491. )
  492. );
  493. } catch (\Throwable $exception) {
  494. Log::error('Falha ao enviar push de recusa do prestador', [
  495. 'schedule_id' => $schedule->id,
  496. 'user_id' => $user->id,
  497. 'error' => $exception->getMessage(),
  498. ]);
  499. }
  500. }
  501. private function sendClientAcceptedPush(Schedule $schedule): void
  502. {
  503. $user = $schedule->provider?->user;
  504. if (! $user) {
  505. Log::warning('Push de aceite do cliente ignorado: prestador sem usuário', [
  506. 'schedule_id' => $schedule->id,
  507. ]);
  508. return;
  509. }
  510. try {
  511. app(PushNotificationService::class)->sendToUser(
  512. $user,
  513. new ClienteAceitouPush(
  514. $schedule->client->user->name
  515. )
  516. );
  517. } catch (\Throwable $exception) {
  518. Log::error('Falha ao enviar push de aceite do cliente', [
  519. 'schedule_id' => $schedule->id,
  520. 'user_id' => $user->id,
  521. 'error' => $exception->getMessage(),
  522. ]);
  523. }
  524. }
  525. private function sendClientPaymentPush(Schedule $schedule): void
  526. {
  527. $user = $schedule->provider?->user;
  528. if (! $user) {
  529. Log::warning('Push de pagamento ignorado: prestador sem usuário', [
  530. 'schedule_id' => $schedule->id,
  531. ]);
  532. return;
  533. }
  534. try {
  535. app(PushNotificationService::class)->sendToUser(
  536. $user,
  537. new ClienteEfetuouPagamentoPush(
  538. $schedule->client?->user?->name ?? 'Cliente'
  539. )
  540. );
  541. } catch (\Throwable $exception) {
  542. Log::error('Falha ao enviar push de pagamento ao prestador', [
  543. 'schedule_id' => $schedule->id,
  544. 'provider_id' => $schedule->provider_id,
  545. 'user_id' => $user->id,
  546. 'error' => $exception->getMessage(),
  547. ]);
  548. }
  549. }
  550. private function sendClientCancelledPush(Schedule $schedule): void
  551. {
  552. $user = $schedule->provider->user;
  553. if (! $user) {
  554. Log::warning('Push de cancelamento ignorado: prestador sem usuário', [
  555. 'schedule_id' => $schedule->id,
  556. ]);
  557. return;
  558. }
  559. try {
  560. app(PushNotificationService::class)->sendToUser(
  561. $user,
  562. new ClienteCancelouPush(
  563. $schedule->client->user->name
  564. )
  565. );
  566. } catch (\Throwable $exception) {
  567. Log::error('Falha ao enviar push de cancelamento pelo cliente', [
  568. 'schedule_id' => $schedule->id,
  569. 'user_id' => $user->id,
  570. 'error' => $exception->getMessage(),
  571. ]);
  572. }
  573. }
  574. private function sendProviderCancelledPush(Schedule $schedule): void
  575. {
  576. $user = $schedule->client->user;
  577. if (! $user) {
  578. Log::warning('Push de cancelamento ignorado: cliente sem usuário', [
  579. 'schedule_id' => $schedule->id,
  580. ]);
  581. return;
  582. }
  583. try {
  584. app(PushNotificationService::class)->sendToUser(
  585. $user,
  586. new PrestadorCancelouPush(
  587. $schedule->provider->user->name
  588. )
  589. );
  590. } catch (\Throwable $exception) {
  591. Log::error('Falha ao enviar push de cancelamento pelo prestador', [
  592. 'schedule_id' => $schedule->id,
  593. 'user_id' => $user->id,
  594. 'error' => $exception->getMessage(),
  595. ]);
  596. }
  597. }
  598. private function calculateAmount(Provider $provider, string $periodType): float
  599. {
  600. $hourlyRates = [
  601. '2' => $provider->daily_price_2h ?? 0,
  602. '4' => $provider->daily_price_4h ?? 0,
  603. '6' => $provider->daily_price_6h ?? 0,
  604. '8' => $provider->daily_price_8h ?? 0,
  605. ];
  606. return data_get($hourlyRates, $periodType, 0);
  607. }
  608. private function validateProviderAvailability(array $data, $excludeScheduleId = null)
  609. {
  610. $provider_id = data_get($data, 'provider_id');
  611. $client_id = data_get($data, 'client_id');
  612. $date = Carbon::parse(data_get($data, 'date'));
  613. $dayOfWeek = $date->dayOfWeek;
  614. $startTime = data_get($data, 'start_time');
  615. $endTime = data_get($data, 'end_time');
  616. $date_ymd = $date->format('Y-m-d');
  617. $period = $startTime < '13:00:00' ? 'morning' : 'afternoon';
  618. ScheduleBusinessRules::validateProviderVisibleToCustomers($provider_id);
  619. // bloqueio 2 schedules por semana para o mesmo client e provider
  620. ScheduleBusinessRules::validateWeeklyScheduleLimit(
  621. $client_id,
  622. $provider_id,
  623. data_get($data, 'date'),
  624. $excludeScheduleId
  625. );
  626. // bloqueio provider trabalha no dia/periodo
  627. ScheduleBusinessRules::validateWorkingDay(
  628. $provider_id,
  629. $dayOfWeek,
  630. $period
  631. );
  632. // bloqueio provider tem blockedday para dia/hora
  633. ScheduleBusinessRules::validateBlockedDay(
  634. $provider_id,
  635. $date->format('Y-m-d'),
  636. $startTime,
  637. $endTime
  638. );
  639. // bloqueio provider tem outro agendamento para dia/hora
  640. ScheduleBusinessRules::validateConflictingSchedule(
  641. $provider_id,
  642. $date->format('Y-m-d'),
  643. $startTime,
  644. $endTime,
  645. $excludeScheduleId
  646. );
  647. // bloqueio provider tem outra proposta na mesma data
  648. ScheduleBusinessRules::validateConflictingProposalSameDate(
  649. $provider_id,
  650. $date_ymd,
  651. $startTime,
  652. $endTime,
  653. null
  654. );
  655. // bloqueio caso o client tenha bloqueado o provider
  656. ScheduleBusinessRules::validateClientNotBlockedByProvider(
  657. $client_id,
  658. $provider_id
  659. );
  660. // bloqueio caso o provider tenha bloqueado o client
  661. ScheduleBusinessRules::validateProviderNotBlockedByClient(
  662. $client_id,
  663. $provider_id
  664. );
  665. return true;
  666. }
  667. }