| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186 |
- <?php
- namespace App\Services;
- use App\Broadcasting\RealtimeEvent;
- use App\Broadcasting\RealtimeRoom;
- use App\Broadcasting\RealtimeService;
- use App\Exceptions\ScheduleStatusTransitionException;
- use App\Enums\ServicePackageStatusEnum;
- use App\Enums\UserTypeEnum;
- use App\Enums\NotificationTypeEnum;
- use App\Jobs\StartScheduleJob;
- use App\Jobs\ScheduleStartingSoonJob;
- use App\Models\Provider;
- use App\Models\Schedule;
- use App\Models\ServicePackage;
- use App\Rules\ScheduleBusinessRules;
- use App\Services\NotificationService;
- use App\Services\PushNotificationService;
- use App\Notifications\Push\Cliente\Agendamento\PrestadorAceitouPush;
- use App\Notifications\Push\Cliente\Agendamento\PrestadorRecusouPush;
- use App\Notifications\Push\Prestador\Agendamento\ClienteAceitouPush;
- use App\Notifications\Push\Prestador\Pagamento\ClienteEfetuouPagamentoPush;
- use App\Notifications\Push\Cliente\Agendamento\AgendamentoProximoPrestadorPush;
- use App\Notifications\Push\Prestador\Agendamento\AgendamentoProximoClientePush;
- use App\Notifications\Push\Cliente\Agendamento\PrestadorCancelouPush;
- use App\Notifications\Push\Prestador\Agendamento\ClienteCancelouPush;
- use App\Notifications\Push\Prestador\Agendamento\PrestadorFaltouPush;
- use App\Notifications\Push\Prestador\Agendamento\NewPushRequest;
- use App\Enums\BlockedPeriodEnum;
- use App\Models\ProviderBlockedDay;
- use App\Models\ProviderWorkingDay;
- use App\Services\ProviderBlockedDayService;
- use Carbon\Carbon;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- class ScheduleService
- {
- private const EXCLUDED_STATUSES = ['cancelled', 'rejected'];
- public function __construct(
- private readonly RealtimeService $realtime,
- private readonly ProviderBlockedDayService $providerBlockedDayService
- ) {}
- public function getAll()
- {
- return Schedule::with(['client.user', 'provider.user', 'address'])
- ->where('schedule_type', 'default')
- ->orderBy('date', 'desc')
- ->orderBy('start_time', 'desc')
- ->get();
- }
- public function getById($id)
- {
- return Schedule::with(['client.user', 'provider.user', 'address'])->findOrFail($id);
- }
- public function create(array $data): Schedule
- {
- return data_get($this->createSingleOrMultiple([], [$data]), 0);
- }
- public function createSingleOrMultiple(array $baseData, array $schedules)
- {
- try {
- DB::beginTransaction();
- $createdSchedules = [];
- foreach ($schedules as $schedule) {
- $datasMerged = array_merge($baseData, $schedule);
- if (data_get($datasMerged, 'schedule_type', 'default') === 'default') {
- $provider = Provider::findOrFail(data_get($datasMerged, 'provider_id'));
- $datasMerged['total_amount'] = $this->calculateAmount(
- $provider,
- (string) data_get($datasMerged, 'period_type'),
- );
- }
- $this->validateProviderAvailability($datasMerged, null);
- $scheduleData = array_merge($datasMerged, [
- 'code' => str_pad(random_int(0, 9999), 4, '0', STR_PAD_LEFT),
- ]);
- $newSchedule = Schedule::create($scheduleData);
- // NOTIFICAÇÃO PRESTADOR
- if ($newSchedule->provider_id) {
- $notificationService = app(NotificationService::class);
- $notificationService->create([
- 'title' => __('notifications.new_schedule_request_title'),
- 'description' => __('notifications.new_schedule_request_description'),
- 'origin' => 'schedule',
- 'origin_id' => $newSchedule->id,
- 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_NEW_SOLICITATION->value,
- 'user_id' => $newSchedule->provider->user_id,
- ]);
- // Push Notification
- $pushNotificationService = app(PushNotificationService::class);
- $pushNotificationService->sendToUser(
- $newSchedule->provider->user,
- new NewPushRequest($newSchedule->client->user->name)
- );
- }
- $this->realtime->emit(
- RealtimeEvent::SCHEDULE_CREATED,
- $this->scheduleRooms($newSchedule),
- [
- 'entity' => 'schedule',
- 'id' => $newSchedule->id,
- 'status' => $newSchedule->status,
- 'schedule_type' => $newSchedule->schedule_type,
- ],
- );
- $createdSchedules[] = $newSchedule;
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- throw $e;
- }
- return $createdSchedules;
- }
- public function update($id, array $data)
- {
- unset($data['status']);
- $schedule = Schedule::with(['provider.user', 'client.user', 'address'])->findOrFail($id);
- if (data_get($data, 'provider_id') !== null || data_get($data, 'period_type') !== null) {
- $providerId = data_get($data, 'provider_id', $schedule->provider_id);
- $periodType = data_get($data, 'period_type', $schedule->period_type);
- $provider = Provider::findOrFail($providerId);
- $data['total_amount'] = $this->calculateAmount($provider, $periodType);
- }
- if (data_get($data, 'date') !== null || data_get($data, 'start_time') !== null || data_get($data, 'provider_id') !== null) {
- $validationData = array_merge($schedule->toArray(), $data);
- $this->validateProviderAvailability($validationData, $id);
- }
- $schedule->update($data);
- return $schedule->fresh(['client.user', 'provider.user', 'address']);
- }
- public function delete($id)
- {
- $schedule = Schedule::findOrFail($id);
- $schedule->delete();
- return $schedule;
- }
- //
- //
- public function updateStatus($id, string $status, bool $fromPackage = false, bool $isProviderAbsence = false)
- {
- try {
- DB::beginTransaction();
- $schedule = Schedule::with(['provider.user', 'client.user', 'address'])->findOrFail($id);
- if (! $fromPackage && in_array($status, ['accepted', 'rejected']) && Auth::user()?->type === UserTypeEnum::PROVIDER) {
- $belongsToServicePackage = DB::table('service_package_items')
- ->where('schedule_id', $schedule->id)
- ->exists();
- if ($belongsToServicePackage) {
- throw new \DomainException(__('messages.schedule_belongs_to_package_use_package_endpoint'));
- }
- }
- $allowedTransitions = [
- 'pending' => ['accepted', 'rejected', 'paid', 'cancelled'],
- 'accepted' => ['paid', 'cancelled'],
- 'paid' => ['cancelled', 'started'],
- 'started' => ['finished'],
- 'rejected' => [],
- 'cancelled' => [],
- 'finished' => [],
- ];
- $currentStatus = $schedule->status;
- if (
- $isProviderAbsence &&
- $currentStatus === 'started' &&
- $status === 'cancelled'
- ) {
- $allowedTransitions['started'][] = 'cancelled';
- }
- if (data_get($allowedTransitions, $currentStatus) === null) {
- throw new ScheduleStatusTransitionException;
- }
- if (! in_array($status, data_get($allowedTransitions, $currentStatus))) {
- log::info("Transição de status inválida: {$currentStatus} para {$status}");
- throw new ScheduleStatusTransitionException;
- }
- $schedule->update(['status' => $status]);
- $schedule->refresh();
- $currentStatus = $schedule->status;
- switch ($status) {
- case 'pending':
- break;
- case 'accepted':
- $notificationService = app(NotificationService::class);
- switch (Auth::user()?->type) {
- case UserTypeEnum::PROVIDER:
- $notificationService->create([
- 'title' => __('notifications.schedule_accepted_title'),
- 'description' => __('notifications.provider_accepted_schedule_description', ['provider' => $schedule->provider->user->name]),
- 'origin' => 'schedule',
- 'origin_id' => $schedule->id,
- 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_ACCEPTED->value,
- 'user_id' => $schedule->client->user_id,
- ]);
- $this->sendProviderAcceptedPush($schedule);
- break;
- case UserTypeEnum::CLIENT:
- if ($schedule->provider_id) {
- $notificationService->create([
- 'title' => __('notifications.proposal_accepted_title'),
- 'description' => __('notifications.proposal_accepted_description'),
- 'origin' => 'schedule',
- 'origin_id' => $schedule->id,
- 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_PROPOSAL_ACCEPTED->value,
- 'user_id' => $schedule->provider->user_id,
- ]);
- }
- $this->sendClientAcceptedPush($schedule);
- break;
- default:
- break;
- }
- break;
- //tem que chamar o status cancel por causa da regra de push
- case 'cancelled':
- $notificationService = app(NotificationService::class);
- if ($schedule->cancelled_due_to_provider_absence) {
- // Cancelamento por falta do prestador.
- // Aqui enviamos a notificação específica para o prestador.
- $this->sendProviderAbsencePush($schedule);
- break;
- }
- switch (Auth::user()?->type) {
- case UserTypeEnum::CLIENT:
- $user = $schedule->provider?->user;
- if (!$user) {
- break;
- }
- $notificationService->create([
- 'title' => __('notifications.schedule_cancelled_title'),
- 'description' => __('notifications.client_cancelled_schedule_description'),
- 'origin' => 'schedule',
- 'origin_id' => $schedule->id,
- 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_CANCELLED->value,
- 'user_id' => $user->id,
- ]);
- $this->sendClientCancelledPush($schedule);
- break;
- case UserTypeEnum::PROVIDER:
- $notificationService->create([
- 'title' => __('notifications.schedule_cancelled_title'),
- 'description' => __('notifications.provider_cancelled_schedule_description', [
- 'provider' => $schedule->provider->user->name
- ]),
- 'origin' => 'schedule',
- 'origin_id' => $schedule->id,
- 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_CANCELLED->value,
- 'user_id' => $schedule->client->user_id,
- ]);
- $this->sendProviderCancelledPush($schedule);
- break;
- default:
- break;
- }
- break;
- case 'started':
- $notificationService = app(NotificationService::class);
- // CLIENTE
- $notificationService->create([
- 'title' => __('notifications.provider_on_the_way_title'),
- 'description' => __('notifications.provider_on_the_way_description', ['code' => $schedule->code]),
- 'origin' => 'schedule',
- 'origin_id' => $schedule->id,
- 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_COMING->value,
- 'user_id' => $schedule->client->user_id,
- ]);
- // PRESTADOR
- $notificationService->create([
- 'title' => __('notifications.service_start_title'),
- 'description' => __('notifications.service_start_description'),
- 'origin' => 'schedule',
- 'origin_id' => $schedule->id,
- 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_START->value,
- 'user_id' => $schedule->provider->user_id,
- ]);
- break;
- case 'finished':
- $notificationService = app(NotificationService::class);
- // CLIENTE
- $notificationService->create([
- 'title' => __('notifications.service_finished_title'),
- 'description' => __('notifications.service_finished_description'),
- 'origin' => 'schedule',
- 'origin_id' => $schedule->id,
- 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_FINISHED->value,
- 'user_id' => $schedule->client->user_id,
- ]);
- break;
- case 'paid':
- $notificationService = app(NotificationService::class);
- if ($schedule->provider_id) {
- $notificationService->create([
- 'title' => __('notifications.payment_confirmed_title'),
- 'description' => __('notifications.payment_confirmed_description'),
- 'origin' => 'schedule',
- 'origin_id' => $schedule->id,
- 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_START->value,
- 'user_id' => $schedule->provider->user_id,
- ]);
- }
- $this->sendClientPaymentPush($schedule);
- $date_cleaned = Carbon::parse($schedule->date)
- ->format('Y-m-d');
- $start_date_time = Carbon::parse(
- $date_cleaned . ' ' . $schedule->start_time
- );
- // =====================================================
- // ScheduleStartingSoonJob
- // =====================================================
- // TESTE LOCAL: dispara 15 segundos depois do pagamento
- // ScheduleStartingSoonJob::dispatch($schedule->id)
- // ->delay(now()->addSeconds(15));
- // PRODUÇÃO: dispara 1 hora antes do início
- $notification_date_time = $start_date_time->copy()->subHour();
- ScheduleStartingSoonJob::dispatch($schedule->id)
- ->delay($notification_date_time);
- // =====================================================
- // StartScheduleJob
- // =====================================================
- // Aqui continua sendo o horário REAL de início
- StartScheduleJob::dispatch($schedule->id)
- ->delay($start_date_time);
- break;
- case 'rejected':
- $notificationService = app(NotificationService::class);
- $notificationService->create([
- 'title' => __('notifications.schedule_refused_title'),
- 'description' => __('notifications.schedule_refused_description'),
- 'origin' => 'schedule',
- 'origin_id' => $schedule->id,
- 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_REFUSED->value,
- 'user_id' => $schedule->client->user_id,
- ]);
- $this->sendProviderRefusedPush($schedule);
- break;
- }
- $actor = Auth::user()?->type;
- $this->realtime->emit(
- RealtimeEvent::SCHEDULE_STATUS_CHANGED,
- $this->scheduleRooms($schedule),
- [
- 'entity' => 'schedule',
- 'id' => $schedule->id,
- 'status' => $status,
- 'schedule_type' => $schedule->schedule_type,
- 'actor' => $actor instanceof UserTypeEnum ? strtolower($actor->value) : 'system',
- ],
- );
- DB::commit();
- return $schedule->fresh(['client.user', 'provider.user', 'address']);
- } catch (ScheduleStatusTransitionException $e) {
- DB::rollBack();
- throw $e;
- } catch (\Exception $e) {
- DB::rollBack();
- Log::error('Erro ao atualizar status do agendamento: ' . $e->getMessage());
- throw $e;
- }
- }
- /**
- * @return RealtimeRoom[]
- */
- private function scheduleRooms(Schedule $schedule): array
- {
- $rooms = [
- RealtimeRoom::schedule($schedule->id),
- ];
- if ($schedule->client?->user_id) {
- $rooms[] = RealtimeRoom::user($schedule->client->user_id);
- }
- if ($schedule->provider?->user_id) {
- $rooms[] = RealtimeRoom::user($schedule->provider->user_id);
- }
- return $rooms;
- }
- //
- public function getClientProviderBlocks(int $clientId, int $providerId): array
- {
- $weekStart = Carbon::today()->startOfWeek(Carbon::SUNDAY)->format('Y-m-d');
- $schedules = Schedule::where('client_id', $clientId)
- ->where('provider_id', $providerId)
- ->whereNotIn('status', self::EXCLUDED_STATUSES)
- ->whereDate('date', '>=', $weekStart)
- ->orderBy('date')
- ->orderBy('start_time')
- ->get(['id', 'date', 'start_time', 'end_time', 'status']);
- $existingSchedules = $schedules->map(function ($schedule) {
- return [
- 'id' => $schedule->id,
- 'date' => Carbon::parse($schedule->date)->format('Y-m-d'),
- 'start_time' => $schedule->start_time,
- 'end_time' => $schedule->end_time,
- 'status' => $schedule->status,
- ];
- })->values();
- $fullyBlockedWeeks = $schedules
- ->groupBy(function ($schedule) {
- return Carbon::parse($schedule->date)
- ->startOfWeek(Carbon::SUNDAY)
- ->format('Y-m-d');
- })
- ->filter(function ($weekSchedules) {
- return $weekSchedules->count() >= 2;
- })
- ->keys()
- ->values();
- return [
- 'existing_schedules' => $existingSchedules,
- 'fully_blocked_weeks' => $fullyBlockedWeeks,
- ];
- }
- public function getFinished()
- {
- return Schedule::with(['client.user', 'provider.user'])
- ->where('status', 'finished')
- ->orderBy('date', 'desc')
- ->orderBy('start_time', 'desc')
- ->get();
- }
- public function getSchedulesDefaultGroupedByClient()
- {
- $schedules = Schedule::with(['client.user', 'provider.user', 'address', 'reviews.reviewsImprovements.improvementType'])
- ->orderBy('id', 'desc')
- ->where('schedule_type', 'default')
- ->select(
- 'schedules.*'
- )
- ->get();
- $grouped = $schedules->groupBy('client_id')->map(function ($clientSchedules) {
- $firstSchedule = $clientSchedules->first();
- return [
- 'client_id' => $firstSchedule->client_id,
- 'client_name' => $firstSchedule->client->user->name ?? 'N/A',
- 'schedules' => $clientSchedules->map(function ($schedule) {
- return [
- 'id' => $schedule->id,
- 'date' => $schedule->date ? Carbon::parse($schedule->date)->format('d/m/Y') : null,
- 'start_time' => $schedule->start_time,
- 'end_time' => $schedule->end_time,
- 'period_type' => $schedule->period_type,
- 'status' => $schedule->status,
- 'total_amount' => $schedule->total_amount,
- 'code' => $schedule->code,
- 'code_verified' => $schedule->code_verified,
- 'client_id' => $schedule->client_id,
- 'provider_id' => $schedule->provider_id,
- 'provider_name' => $schedule->provider->user->name ?? 'N/A',
- 'address' => $schedule->address ? [
- 'id' => $schedule->address->id,
- 'address' => $schedule->address->address,
- 'complement' => $schedule->address->complement,
- 'zip_code' => $schedule->address->zip_code,
- 'city' => $schedule->address->city->name ?? '',
- 'state' => $schedule->address->city->state->name ?? '',
- ] : null,
- 'client_name' => $schedule->client->user->name ?? 'N/A',
- 'reviews' => $schedule->reviews->map(function ($review) {
- return [
- 'id' => $review->id,
- 'stars' => $review->stars,
- 'comment' => $review->comment,
- 'origin' => $review->origin,
- 'origin_id' => $review->origin_id,
- 'created_at' => Carbon::parse($review->created_at)->format('Y-m-d H:i'),
- 'updated_at' => Carbon::parse($review->updated_at)->format('Y-m-d H:i'),
- 'improvements' => $review->reviewsImprovements->map(function ($ri) {
- return [
- 'id' => $ri->id,
- 'improvement_type_id' => $ri->improvement_type_id,
- 'improvement_type_name' => $ri->improvementType ? $ri->improvementType->description : null,
- ];
- })->values(),
- ];
- }),
- ];
- })->values(),
- ];
- })->sortBy('id')->values();
- return $grouped;
- }
- //
- public function cancelWithReason(int $id, string $cancelText)
- {
- try {
- DB::beginTransaction();
- $schedule = Schedule::findOrFail($id);
- $allowedStatuses = ['accepted', 'paid', 'pending'];
- if (! in_array($schedule->status, $allowedStatuses)) {
- throw new ScheduleStatusTransitionException;
- }
- $cancelled_by = Auth::user()->type;
- $schedule->update([
- 'cancel_text' => $cancelText,
- 'cancelled_by' => $cancelled_by,
- ]);
- $this->cascadeCancelServicePackages($schedule, $cancelText, $cancelled_by);
- $this->updateStatus($id, 'cancelled');
- $actor = Auth::user()?->type;
- $this->realtime->emit(
- RealtimeEvent::SCHEDULE_STATUS_CHANGED,
- $this->scheduleRooms($schedule),
- [
- 'entity' => 'schedule',
- 'id' => $schedule->id,
- 'status' => 'cancelled',
- 'schedule_type' => $schedule->schedule_type,
- 'actor' => $actor instanceof UserTypeEnum ? strtolower($actor->value) : 'system',
- ],
- );
- DB::commit();
- return $schedule->fresh(['client.user', 'provider.user', 'address']);
- } catch (ScheduleStatusTransitionException $e) {
- DB::rollBack();
- throw $e;
- } catch (\Exception $e) {
- DB::rollBack();
- Log::error('Erro ao cancelar agendamento: ' . $e->getMessage());
- throw $e;
- }
- }
- //reporta por falta
- public function reportProviderAbsence(
- int $scheduleId,
- string $cancelText
- ): Schedule {
- return DB::transaction(function () use ($scheduleId, $cancelText) {
- $schedule = Schedule::findOrFail($scheduleId);
- // O agendamento precisa ter um prestador vinculado
- if (! $schedule->provider_id) {
- throw new \Exception(
- __('messages.provider_absence_provider_not_assigned')
- );
- }
- // O cliente precisa ser o dono do agendamento
- if (Auth::user()->type !== UserTypeEnum::CLIENT) {
- throw new \Exception(
- __('messages.provider_absence_only_client')
- );
- }
- if (Auth::user()->client?->id !== $schedule->client_id) {
- throw new \Exception(
- __('messages.provider_absence_not_authorized')
- );
- }
- // O código já foi confirmado: o prestador compareceu
- if ($schedule->code_verified) {
- throw new \Exception(
- __('messages.provider_absence_code_already_verified')
- );
- }
- // O agendamento não pode estar encerrado/cancelado/rejeitado
- if (
- in_array(
- $schedule->status,
- ['cancelled', 'rejected', 'finished'],
- true
- )
- ) {
- throw new \Exception(
- __('messages.provider_absence_invalid_status')
- );
- }
- // Valida se o cliente pode informar a falta neste momento
- ScheduleBusinessRules::validateProviderAbsenceWindow($schedule);
- // Registra o motivo informado pelo cliente
- $schedule->update([
- 'cancel_text' => $cancelText,
- 'cancelled_by' => Auth::user()->type,
- 'cancelled_due_to_provider_absence' => true,
- ]);
- // Cancela o agendamento
- $this->updateStatus(
- $schedule->id,
- 'cancelled',
- false,
- true
- );
- // Aplica a penalidade de bloqueio de 3 dias úteis do prestador.
- $this->blockProviderPenaltyDays($schedule);
- // TODO: Implementar estorno integral do pagamento.
- // Esta etapa será implementada posteriormente por outro responsável.
- return $schedule->fresh([
- 'client.user',
- 'provider.user',
- 'address',
- ]);
- });
- }
- //penalidade por falta bloqueio de 3 dias validos
- // penalidade por falta - bloqueio de 3 dias válidos
- private function blockProviderPenaltyDays(Schedule $schedule): void
- {
- $providerId = $schedule->provider_id;
- $date = Carbon::parse($schedule->date)->startOfDay();
- $blockedDaysCount = 0;
- while ($blockedDaysCount < 3) {
- $date->addDay();
- $dayOfWeek = $date->dayOfWeek;
- // 1. O prestador precisa trabalhar nesse dia da semana.
- $worksOnDay = ProviderWorkingDay::query()
- ->where('provider_id', $providerId)
- ->where('day', $dayOfWeek)
- ->exists();
- if (! $worksOnDay) {
- continue;
- }
- // 2. Se já existe qualquer ProviderBlockedDay nessa data,
- // a data não pode ser utilizada como penalidade.
- $alreadyBlocked = ProviderBlockedDay::query()
- ->where('provider_id', $providerId)
- ->whereDate('date', $date->format('Y-m-d'))
- ->exists();
- if ($alreadyBlocked) {
- continue;
- }
- // 3. Se existe qualquer agendamento ativo nessa data,
- // não podemos bloquear o dia inteiro.
- $hasSchedule = Schedule::query()
- ->where('provider_id', $providerId)
- ->whereDate('date', $date->format('Y-m-d'))
- ->whereNotIn('status', self::EXCLUDED_STATUSES)
- ->exists();
- if ($hasSchedule) {
- continue;
- }
- // 4. Encontramos um dia de trabalho completamente livre.
- $this->providerBlockedDayService->create([
- 'provider_id' => $providerId,
- 'date' => $date->format('Y-m-d'),
- 'period' => BlockedPeriodEnum::ALL->value,
- 'reason' => 'Bloqueio de 3 dias por falta do prestador.',
- 'type' => 'auto_cancel',
- 'init_hour' => '07:00',
- 'end_hour' => '20:00',
- // Identifica que este bloqueio é uma penalidade
- // e não pode ser alterado/desbloqueado manualmente.
- 'blocked_due_to_provider_absence' => true,
- ]);
- $blockedDaysCount++;
- }
- }
- private function cascadeCancelServicePackages(Schedule $schedule, string $cancelText, $cancelledBy): void
- {
- $packageIds = DB::table('service_package_items')
- ->where('schedule_id', $schedule->id)
- ->pluck('service_package_id');
- if ($packageIds->isEmpty()) {
- return;
- }
- $packages = ServicePackage::query()
- ->with('items.schedule')
- ->whereIn('id', $packageIds)
- ->get();
- foreach ($packages as $package) {
- $siblingSchedules = $package->items->pluck('schedule')->filter();
- $siblingSchedules
- ->filter(fn(Schedule $sibling) => $sibling->id !== $schedule->id
- && in_array($sibling->status, ['pending', 'accepted', 'paid'], true))
- ->each(fn(Schedule $sibling) => $sibling->update([
- 'status' => 'cancelled',
- 'cancel_text' => $cancelText,
- 'cancelled_by' => $cancelledBy,
- ]));
- $hasRealizedSchedule = $siblingSchedules->contains(
- fn(Schedule $sibling) => in_array($sibling->status, ['started', 'finished'], true),
- );
- if (
- $package->status === ServicePackageStatusEnum::OPEN
- || ($package->status === ServicePackageStatusEnum::PAID && ! $hasRealizedSchedule)
- ) {
- $package->update(['status' => ServicePackageStatusEnum::CANCELLED->value]);
- }
- }
- }
- //Notificações por push do sistema
- private function sendProviderAcceptedPush(Schedule $schedule): void
- {
- $user = $schedule->client->user;
- if (! $user) {
- Log::warning('Push de aceite ignorada: cliente sem usuário', [
- 'schedule_id' => $schedule->id,
- ]);
- return;
- }
- try {
- app(PushNotificationService::class)->sendToUser(
- $user,
- new PrestadorAceitouPush($schedule->provider->user->name)
- );
- } catch (\Throwable $exception) {
- Log::error('Falha ao enviar push de aceite do prestador', [
- 'schedule_id' => $schedule->id,
- 'user_id' => $user->id,
- 'error' => $exception->getMessage(),
- ]);
- }
- }
- private function sendProviderRefusedPush(Schedule $schedule): void
- {
- $user = $schedule->client->user;
- if (! $user) {
- Log::warning('Push de recusa ignorada: cliente sem usuário', [
- 'schedule_id' => $schedule->id,
- ]);
- return;
- }
- try {
- app(PushNotificationService::class)->sendToUser(
- $user,
- new PrestadorRecusouPush(
- $schedule->provider->user->name
- )
- );
- } catch (\Throwable $exception) {
- Log::error('Falha ao enviar push de recusa do prestador', [
- 'schedule_id' => $schedule->id,
- 'user_id' => $user->id,
- 'error' => $exception->getMessage(),
- ]);
- }
- }
- private function sendClientAcceptedPush(Schedule $schedule): void
- {
- $user = $schedule->provider?->user;
- if (! $user) {
- Log::warning('Push de aceite do cliente ignorado: prestador sem usuário', [
- 'schedule_id' => $schedule->id,
- ]);
- return;
- }
- try {
- app(PushNotificationService::class)->sendToUser(
- $user,
- new ClienteAceitouPush(
- $schedule->client->user->name
- )
- );
- } catch (\Throwable $exception) {
- Log::error('Falha ao enviar push de aceite do cliente', [
- 'schedule_id' => $schedule->id,
- 'user_id' => $user->id,
- 'error' => $exception->getMessage(),
- ]);
- }
- }
- private function sendClientPaymentPush(Schedule $schedule): void
- {
- $user = $schedule->provider?->user;
- if (! $user) {
- Log::warning('Push de pagamento ignorado: prestador sem usuário', [
- 'schedule_id' => $schedule->id,
- ]);
- return;
- }
- try {
- app(PushNotificationService::class)->sendToUser(
- $user,
- new ClienteEfetuouPagamentoPush(
- $schedule->client?->user?->name ?? 'Cliente'
- )
- );
- } catch (\Throwable $exception) {
- Log::error('Falha ao enviar push de pagamento ao prestador', [
- 'schedule_id' => $schedule->id,
- 'provider_id' => $schedule->provider_id,
- 'user_id' => $user->id,
- 'error' => $exception->getMessage(),
- ]);
- }
- }
- private function sendClientCancelledPush(Schedule $schedule): void
- {
- $user = $schedule->provider->user;
- if (! $user) {
- Log::warning('Push de cancelamento ignorado: prestador sem usuário', [
- 'schedule_id' => $schedule->id,
- ]);
- return;
- }
- try {
- app(PushNotificationService::class)->sendToUser(
- $user,
- new ClienteCancelouPush(
- $schedule->client->user->name
- )
- );
- } catch (\Throwable $exception) {
- Log::error('Falha ao enviar push de cancelamento pelo cliente', [
- 'schedule_id' => $schedule->id,
- 'user_id' => $user->id,
- 'error' => $exception->getMessage(),
- ]);
- }
- }
- private function sendProviderCancelledPush(Schedule $schedule): void
- {
- $user = $schedule->client->user;
- if (! $user) {
- Log::warning('Push de cancelamento ignorado: cliente sem usuário', [
- 'schedule_id' => $schedule->id,
- ]);
- return;
- }
- try {
- app(PushNotificationService::class)->sendToUser(
- $user,
- new PrestadorCancelouPush(
- $schedule->provider->user->name
- )
- );
- } catch (\Throwable $exception) {
- Log::error('Falha ao enviar push de cancelamento pelo prestador', [
- 'schedule_id' => $schedule->id,
- 'user_id' => $user->id,
- 'error' => $exception->getMessage(),
- ]);
- }
- }
- // cancelou por falta
- private function sendProviderAbsencePush(Schedule $schedule): void
- {
- $user = $schedule->provider?->user;
- if (! $user) {
- Log::warning('Push de falta ignorada: prestador sem usuário', [
- 'schedule_id' => $schedule->id,
- ]);
- return;
- }
- try {
- app(PushNotificationService::class)->sendToUser(
- $user,
- new PrestadorFaltouPush()
- );
- } catch (\Throwable $exception) {
- Log::error('Falha ao enviar push de falta do prestador', [
- 'schedule_id' => $schedule->id,
- 'user_id' => $user->id,
- 'error' => $exception->getMessage(),
- ]);
- }
- }
- public function sendScheduleStartingSoonPushes(Schedule $schedule): void
- {
- $pushNotificationService = app(PushNotificationService::class);
- $clientUser = $schedule->client?->user;
- $providerUser = $schedule->provider?->user;
- if ($clientUser) {
- try {
- $pushNotificationService->sendToUser(
- $clientUser,
- new AgendamentoProximoPrestadorPush(
- $providerUser?->name ?? 'Prestador'
- )
- );
- } catch (\Throwable $exception) {
- Log::error('Falha ao enviar push de agendamento próximo para o cliente', [
- 'schedule_id' => $schedule->id,
- 'user_id' => $clientUser->id,
- 'error' => $exception->getMessage(),
- ]);
- }
- }
- // PUSH PARA O PRESTADOR
- if ($providerUser) {
- try {
- $pushNotificationService->sendToUser(
- $providerUser,
- new AgendamentoProximoClientePush(
- $clientUser?->name ?? 'Cliente'
- )
- );
- } catch (\Throwable $exception) {
- Log::error('Falha ao enviar push de agendamento próximo para o prestador', [
- 'schedule_id' => $schedule->id,
- 'user_id' => $providerUser->id,
- 'error' => $exception->getMessage(),
- ]);
- }
- }
- }
- //dq pra cima e as notificações
- private function calculateAmount(Provider $provider, string $periodType): float
- {
- $hourlyRates = [
- '2' => $provider->daily_price_2h ?? 0,
- '4' => $provider->daily_price_4h ?? 0,
- '6' => $provider->daily_price_6h ?? 0,
- '8' => $provider->daily_price_8h ?? 0,
- ];
- return data_get($hourlyRates, $periodType, 0);
- }
- private function validateProviderAvailability(array $data, $excludeScheduleId = null)
- {
- $provider_id = data_get($data, 'provider_id');
- $client_id = data_get($data, 'client_id');
- $date = Carbon::parse(data_get($data, 'date'));
- $dayOfWeek = $date->dayOfWeek;
- $startTime = data_get($data, 'start_time');
- $endTime = data_get($data, 'end_time');
- $date_ymd = $date->format('Y-m-d');
- $period = $startTime < '13:00:00' ? 'morning' : 'afternoon';
- ScheduleBusinessRules::validateProviderVisibleToCustomers($provider_id);
- // bloqueio 2 schedules por semana para o mesmo client e provider
- ScheduleBusinessRules::validateWeeklyScheduleLimit(
- $client_id,
- $provider_id,
- data_get($data, 'date'),
- $excludeScheduleId
- );
- // bloqueio provider trabalha no dia/periodo
- ScheduleBusinessRules::validateWorkingDay(
- $provider_id,
- $dayOfWeek,
- $period
- );
- // bloqueio provider tem blockedday para dia/hora
- ScheduleBusinessRules::validateBlockedDay(
- $provider_id,
- $date->format('Y-m-d'),
- $startTime,
- $endTime
- );
- // bloqueio provider tem outro agendamento para dia/hora
- ScheduleBusinessRules::validateConflictingSchedule(
- $provider_id,
- $date->format('Y-m-d'),
- $startTime,
- $endTime,
- $excludeScheduleId
- );
- // bloqueio provider tem outra proposta na mesma data
- ScheduleBusinessRules::validateConflictingProposalSameDate(
- $provider_id,
- $date_ymd,
- $startTime,
- $endTime,
- null
- );
- // bloqueio caso o client tenha bloqueado o provider
- ScheduleBusinessRules::validateClientNotBlockedByProvider(
- $client_id,
- $provider_id
- );
- // bloqueio caso o provider tenha bloqueado o client
- ScheduleBusinessRules::validateProviderNotBlockedByClient(
- $client_id,
- $provider_id
- );
- return true;
- }
- }
|