| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124 |
- <?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\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);
- 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): Schedule
- {
- return DB::transaction(function () use ($scheduleId) {
- $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);
- // Motivo utilizado para o cancelamento por falta
- $cancelText = 'Prestador não compareceu ao serviço.';
- // Registra que o cancelamento ocorreu por falta do prestador
- $schedule->update([
- 'cancel_text' => $cancelText,
- 'cancelled_by' => Auth::user()->type,
- 'cancelled_due_to_provider_absence' => true,
- ]);
- $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
- 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.',
- 'init_hour' => '07:00',
- 'end_hour' => '20:00',
- ]);
- $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(),
- ]);
- }
- }
- 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;
- }
- }
|