ScheduleService.php 35 KB

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