ScheduleService.php 33 KB

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