ScheduleService.php 32 KB

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