ScheduleService.php 36 KB

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