ScheduleService.php 33 KB

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