| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132 |
- <?php
- namespace App\Services;
- use App\Broadcasting\RealtimeEvent;
- use App\Broadcasting\RealtimeRoom;
- use App\Broadcasting\RealtimeService;
- use App\Enums\ApprovalStatusEnum;
- use App\Enums\NotificationTypeEnum;
- use App\Jobs\NotifyProvidersOfNewOpportunityJob;
- use App\Models\Address;
- use App\Models\CustomSchedule;
- use App\Models\CustomScheduleSpeciality;
- use App\Models\Provider;
- use App\Models\Schedule;
- use App\Models\ScheduleProposal;
- use App\Models\ScheduleRefuse;
- use App\Models\ServicePackage;
- use App\Notifications\Push\Cliente\Agendamento\PrestadorAceitouPush;
- use App\Notifications\Push\Cliente\Agendamento\PrestadorRecusouPush;
- use App\Notifications\Push\Prestador\Agendamento\ClienteRecusouPush;
- use App\Notifications\Push\Prestador\Agendamento\ClienteAceitouPush;
- use App\Services\PushNotificationService;
- use App\Rules\ScheduleBusinessRules;
- use App\Services\NotificationService;
- use App\Services\DistanceService;
- use Carbon\Carbon;
- use Illuminate\Support\Collection;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Storage;
- class CustomScheduleService
- {
- private const NEARBY_RADIUS_KM = 20.0;
- public function __construct(
- private readonly ZipCodeCoordinatesService $zipCodeCoordinatesService,
- private readonly RealtimeService $realtime,
- ) {}
- public function getAll()
- {
- $custom_schedules = CustomSchedule::with([
- 'schedule.client.user',
- 'schedule.address',
- 'serviceType',
- 'specialities.speciality',
- ])
- ->orderBy('id', 'desc')
- ->get();
- return $custom_schedules;
- }
- public function getById($id)
- {
- $customSchedule = CustomSchedule::with([
- 'schedule.client.user',
- 'schedule.client.profileMedia',
- 'schedule.address',
- 'serviceType',
- 'specialities.speciality',
- ])->find($id);
- return $customSchedule;
- }
- public function create(array $data)
- {
- $address = Address::find(data_get($data, 'address_id'));
- if (! $address || $address->latitude === null || $address->longitude === null) {
- throw new \Exception(__('messages.client_address_location_required'));
- }
- DB::beginTransaction();
- try {
- $quantity = data_get($data, 'quantity', 1);
- $specialityIds = data_get($data, 'speciality_ids', []);
- $createdCustomSchedules = [];
- for ($i = 0; $i < $quantity; $i++) {
- $scheduleData = [
- 'client_id' => data_get($data, 'client_id'),
- 'provider_id' => null,
- 'address_id' => data_get($data, 'address_id'),
- 'date' => data_get($data, 'date'),
- 'period_type' => data_get($data, 'period_type'),
- 'schedule_type' => 'custom',
- 'start_time' => data_get($data, 'start_time'),
- 'end_time' => data_get($data, 'end_time'),
- 'status' => 'pending',
- 'total_amount' => 0,
- 'code' => str_pad(random_int(0, 9999), 4, '0', STR_PAD_LEFT),
- 'code_verified' => false,
- ];
- $schedule = Schedule::create($scheduleData);
- $customScheduleData = [
- 'schedule_id' => $schedule->id,
- 'address_type' => data_get($data, 'address_type'),
- 'service_type_id' => data_get($data, 'service_type_id'),
- 'description' => data_get($data, 'description'),
- 'min_price' => data_get($data, 'min_price'),
- 'max_price' => data_get($data, 'max_price'),
- 'offers_meal' => data_get($data, 'offers_meal', false),
- ];
- $customSchedule = CustomSchedule::create($customScheduleData);
- if (! empty($specialityIds)) {
- foreach ($specialityIds as $specialityId) {
- CustomScheduleSpeciality::create([
- 'custom_schedule_id' => $customSchedule->id,
- 'speciality_id' => $specialityId,
- ]);
- }
- }
- $createdCustomSchedules[] = $customSchedule->load([
- 'schedule.client.user',
- 'schedule.address',
- 'serviceType',
- 'specialities.speciality',
- ]);
- }
- DB::commit();
- $this->dispatchOpportunityNotification($createdCustomSchedules);
- return $createdCustomSchedules;
- } catch (\Exception $e) {
- DB::rollBack();
- Log::error('Erro ao criar agendamento personalizado: ' . $e->getMessage());
- throw $e;
- }
- }
- public function update($id, array $data)
- {
- DB::beginTransaction();
- try {
- $customSchedule = CustomSchedule::findOrFail($id);
- $schedule = $customSchedule->schedule;
- $scheduleUpdateData = [];
- if (data_get($data, 'address_id') !== null) {
- $scheduleUpdateData['address_id'] = data_get($data, 'address_id');
- }
- if (data_get($data, 'date') !== null) {
- $scheduleUpdateData['date'] = data_get($data, 'date');
- }
- if (data_get($data, 'period_type') !== null) {
- $scheduleUpdateData['period_type'] = data_get($data, 'period_type');
- }
- if (data_get($data, 'start_time') !== null) {
- $scheduleUpdateData['start_time'] = data_get($data, 'start_time');
- }
- if (data_get($data, 'end_time') !== null) {
- $scheduleUpdateData['end_time'] = data_get($data, 'end_time');
- }
- if (! empty($scheduleUpdateData)) {
- $schedule->update($scheduleUpdateData);
- }
- $customScheduleUpdateData = [];
- if (data_get($data, 'address_type') !== null) {
- $customScheduleUpdateData['address_type'] = data_get($data, 'address_type');
- }
- if (data_get($data, 'service_type_id') !== null) {
- $customScheduleUpdateData['service_type_id'] = data_get($data, 'service_type_id');
- }
- if (data_get($data, 'description') !== null) {
- $customScheduleUpdateData['description'] = data_get($data, 'description');
- }
- if (data_get($data, 'min_price') !== null) {
- $customScheduleUpdateData['min_price'] = data_get($data, 'min_price');
- }
- if (data_get($data, 'max_price') !== null) {
- $customScheduleUpdateData['max_price'] = data_get($data, 'max_price');
- }
- if (data_get($data, 'offers_meal') !== null) {
- $customScheduleUpdateData['offers_meal'] = data_get($data, 'offers_meal');
- }
- if (! empty($customScheduleUpdateData)) {
- $customSchedule->update($customScheduleUpdateData);
- }
- if (data_get($data, 'speciality_ids') !== null) {
- $custom_schedule = CustomScheduleSpeciality::where('custom_schedule_id', $customSchedule->id);
- $custom_schedule->delete();
- foreach (data_get($data, 'speciality_ids') as $specialityId) {
- CustomScheduleSpeciality::create([
- 'custom_schedule_id' => $customSchedule->id,
- 'speciality_id' => $specialityId,
- ]);
- }
- }
- DB::commit();
- return $customSchedule->fresh([
- 'schedule.client.user',
- 'schedule.address',
- 'serviceType',
- 'specialities.speciality',
- ]);
- } catch (\Exception $e) {
- DB::rollBack();
- Log::error('Erro ao atualizar agendamento personalizado: ' . $e->getMessage());
- throw $e;
- }
- }
- public function delete($id)
- {
- DB::beginTransaction();
- try {
- $customSchedule = CustomSchedule::findOrFail($id);
- $schedule = $customSchedule->schedule;
- CustomScheduleSpeciality::where('custom_schedule_id', $customSchedule->id)->delete();
- $customSchedule->delete();
- $schedule->delete();
- DB::commit();
- return $customSchedule;
- } catch (\Exception $e) {
- DB::rollBack();
- Log::error('Erro ao excluir agendamento personalizado: ' . $e->getMessage());
- throw $e;
- }
- }
- //
- public function getAvailableOpportunities($providerId)
- {
- $provider = Provider::find($providerId);
- if (! $provider || ! self::providerHasActivePrimaryBankAccount($providerId)) {
- return collect();
- }
- $providerAddress = Address::where('source', 'provider')
- ->where('source_id', $providerId)
- ->orderBy('is_primary', 'desc')
- ->first();
- $providerCityId = $providerAddress?->city_id;
- $providerLat = $providerAddress?->latitude !== null ? (float) $providerAddress->latitude : null;
- $providerLng = $providerAddress?->longitude !== null ? (float) $providerAddress->longitude : null;
- $opportunities = Schedule::with([
- 'client.user',
- 'client.profileMedia',
- 'address:id,district,zip_code,latitude,longitude',
- 'customSchedule.serviceType',
- 'customSchedule.specialities',
- ])
- ->leftJoin('schedule_refuses', function ($join) use ($providerId) {
- $join->on('schedules.id', '=', 'schedule_refuses.schedule_id')
- ->where('schedule_refuses.provider_id', $providerId);
- })
- ->leftJoin('addresses as opportunity_address', 'opportunity_address.id', '=', 'schedules.address_id')
- ->whereNull('schedule_refuses.id')
- ->where('schedules.schedule_type', 'custom')
- ->where('schedules.status', 'pending')
- ->whereNull('schedules.provider_id')
- ->whereDate('schedules.date', '>=', now()->toDateString())
- ->where(function ($query) use ($providerCityId, $providerLat, $providerLng) {
- if ($providerCityId !== null) {
- $query->where('opportunity_address.city_id', $providerCityId);
- }
- if ($providerLat !== null && $providerLng !== null) {
- $method = $providerCityId !== null ? 'orWhereRaw' : 'whereRaw';
- $query->{$method}(
- DistanceService::withinRadiusSqlCondition(
- $providerLat,
- $providerLng,
- self::NEARBY_RADIUS_KM,
- 'opportunity_address.latitude',
- 'opportunity_address.longitude',
- )
- );
- return;
- }
- if ($providerCityId === null) {
- $query->whereRaw('1 = 0');
- }
- })
- ->select(
- 'schedules.id',
- 'schedules.client_id',
- 'schedules.address_id',
- 'schedules.date',
- 'schedules.period_type',
- 'schedules.start_time',
- 'schedules.end_time',
- 'schedules.total_amount',
- DB::raw("
- CASE
- WHEN schedules.period_type = '2' THEN {$provider->daily_price_2h}
- WHEN schedules.period_type = '4' THEN {$provider->daily_price_4h}
- WHEN schedules.period_type = '6' THEN {$provider->daily_price_6h}
- WHEN schedules.period_type = '8' THEN {$provider->daily_price_8h}
- ELSE 0
- END AS total_amount
- "),
- )
- ->get();
- $proposedScheduleIds = ScheduleProposal::where('provider_id', $providerId)
- ->pluck('schedule_id')
- ->flip();
- $availableOpportunities = $opportunities->filter(function ($opportunity) use ($providerId, $proposedScheduleIds) {
- if ($proposedScheduleIds->has($opportunity->id)) {
- return true;
- }
- try {
- return $this->checkProviderAvailability($providerId, $opportunity);
- } catch (\Exception $e) {
- return false;
- }
- });
- $availableOpportunities->each(function ($opportunity) use ($providerAddress, $proposedScheduleIds) {
- $opportunity->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
- $providerAddress?->latitude !== null ? (float) $providerAddress->latitude : null,
- $providerAddress?->longitude !== null ? (float) $providerAddress->longitude : null,
- $providerAddress?->zip_code,
- $opportunity->address?->latitude !== null ? (float) $opportunity->address->latitude : null,
- $opportunity->address?->longitude !== null ? (float) $opportunity->address->longitude : null,
- $opportunity->address?->zip_code,
- );
- $photoPath = $opportunity->client->profileMedia?->path;
- $opportunity->customer_photo = $photoPath
- ? Storage::temporaryUrl($photoPath, now()->addMinutes(60))
- : null;
- $opportunity->proposal_sent = $proposedScheduleIds->has($opportunity->id);
- });
- return $availableOpportunities->values();
- }
- /**
- * @return Collection<int, int>
- */
- public function getAvailableProvidersForOpportunity(Schedule $schedule): Collection
- {
- $schedule->loadMissing(['customSchedule', 'address']);
- $candidateIds = $this->getCandidateProviderIdsForOpportunity($schedule);
- if ($candidateIds->isEmpty()) {
- return $candidateIds;
- }
- return $candidateIds->filter(function ($providerId) use ($schedule) {
- try {
- return $this->checkProviderAvailability($providerId, $schedule);
- } catch (\Exception $e) {
- return false;
- }
- })->values();
- }
- public function getOpportunityProposals($scheduleId)
- {
- return ScheduleProposal::with(['provider.user'])
- ->where('schedule_id', $scheduleId)
- ->orderBy('created_at', 'desc')
- ->get();
- }
- public function getProvidersProposalsAndOpportunities($providerId)
- {
- $proposals = $this->getProviderProposals($providerId);
- $opportunities = $this->formatCustomSchedules($this->getAvailableOpportunities($providerId));
- return [
- 'proposals' => $proposals,
- 'opportunities' => $opportunities,
- ];
- }
- public function getProviderProposals($providerId)
- {
- return ScheduleProposal::with([
- 'schedule.client.user',
- 'schedule.address',
- 'schedule.address.city',
- 'schedule.address.state',
- 'schedule.customSchedule.serviceType',
- 'schedule.customSchedule.specialities',
- 'schedule.provider.user',
- ])
- ->where('provider_id', $providerId)
- ->orderBy('created_at', 'desc')
- ->get();
- }
- public function getSchedulesCustomGroupedByClient()
- {
- $schedules = Schedule::with(['client.user', 'provider.user', 'address', 'customSchedule.serviceType', 'customSchedule.specialities', 'reviews.reviewsImprovements.improvementType'])
- ->orderBy('id', 'desc')
- ->where('schedule_type', 'custom')
- ->get();
- $grouped = $this->formatCustomSchedules($schedules);
- return $grouped;
- }
- //
- public function proposeOpportunity($scheduleId, $providerId)
- {
- $schedule = Schedule::findOrFail($scheduleId);
- if (! self::providerHasActivePrimaryBankAccount($providerId)) {
- throw new \Exception(__('messages.provider_missing_bank_account'));
- }
- if ($schedule->provider_id) {
- throw new \Exception(__('validation.custom.opportunity.already_assigned'));
- }
- $existingProposal = ScheduleProposal::where('schedule_id', $scheduleId)
- ->where('provider_id', $providerId)
- ->first();
- if ($existingProposal) {
- throw new \Exception(__('validation.custom.opportunity.proposal_already_sent'));
- }
- $wasRefused = ScheduleRefuse::where('schedule_id', $scheduleId)
- ->where('provider_id', $providerId)
- ->exists();
- if ($wasRefused) {
- throw new \Exception(__('validation.custom.opportunity.provider_refused'));
- }
- $this->checkProviderAvailability($providerId, $schedule);
- $provider = Provider::with([
- 'user'
- ])->findOrFail($providerId);
- $schedule->load([
- 'client.user'
- ]);
- $notificationService = app(NotificationService::class);
- $notificationService->create([
- 'title' => __('notifications.new_proposal_title'),
- 'description' => __('notifications.new_proposal_description', ['provider' => $provider->user->name]),
- 'origin' => 'schedule',
- 'origin_id' => $schedule->id,
- 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_NEW_SOLICITATION->value,
- 'user_id' => $schedule->client->user_id,
- ]);
- $this->sendProposalReceivedPush($schedule, $provider->user->name);
- $proposal = ScheduleProposal::create([
- 'schedule_id' => $scheduleId,
- 'provider_id' => $providerId,
- ]);
- $this->realtime->emit(
- RealtimeEvent::PROPOSAL_CREATED,
- $this->proposalRooms($schedule, $provider),
- [
- 'entity' => 'schedule_proposal',
- 'id' => $proposal->id,
- 'schedule_id' => $schedule->id,
- ],
- );
- return $proposal;
- }
- private function sendProposalReceivedPush(Schedule $schedule, string $providerName): void
- {
- $user = $schedule->client->user;
- if (! $user) {
- Log::warning('Push de proposta ignorada: cliente sem usuário', [
- 'schedule_id' => $schedule->id,
- ]);
- return;
- }
- try {
- app(PushNotificationService::class)->sendToUser(
- $user,
- new PrestadorAceitouPush($providerName, isProposal: true)
- );
- } catch (\Throwable $exception) {
- Log::error('Falha ao enviar push de nova proposta sob medida', [
- 'schedule_id' => $schedule->id,
- 'user_id' => $user->id,
- 'error' => $exception->getMessage(),
- ]);
- }
- }
- public function refuseOpportunity($scheduleId, $providerId)
- {
- $schedule = Schedule::with(['client.user'])->findOrFail($scheduleId);
- $provider = Provider::with(['user'])->findOrFail($providerId);
- $schedule_refuse = ScheduleRefuse::create([
- 'schedule_id' => $scheduleId,
- 'provider_id' => $providerId,
- ]);
- $notificationService = app(NotificationService::class);
- $notificationService->create([
- 'title' => __('notifications.opportunity_refused_title'),
- 'description' => __('notifications.opportunity_refused_description', [
- 'provider' => $provider->user->name,
- ]),
- 'origin' => 'schedule',
- 'origin_id' => $scheduleId,
- 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_REFUSED->value,
- 'user_id' => $schedule->client->user_id,
- ]);
- // Push notification
- if ($schedule->client?->user) {
- try {
- app(PushNotificationService::class)->sendToUser(
- $schedule->client->user,
- new PrestadorRecusouPush(
- $provider->user->name
- )
- );
- } catch (\Throwable $exception) {
- Log::error('Falha ao enviar push de recusa da oportunidade', [
- 'schedule_id' => $schedule->id,
- 'provider_id' => $providerId,
- 'user_id' => $schedule->client->user->id,
- 'error' => $exception->getMessage(),
- ]);
- }
- }
- $this->realtime->emit(
- RealtimeEvent::PROPOSAL_REFUSED,
- $this->proposalRooms($schedule, $provider),
- [
- 'entity' => 'schedule_refuse',
- 'id' => $schedule_refuse->id,
- 'schedule_id' => $schedule->id,
- 'actor' => 'provider',
- ],
- );
- return $schedule_refuse;
- }
- /**
- * Salas dos dois lados de uma proposta, mais quem estiver com o
- * agendamento aberto.
- *
- * @return RealtimeRoom[]
- */
- private function proposalRooms(Schedule $schedule, Provider $provider): array
- {
- $rooms = [
- RealtimeRoom::schedule($schedule->id),
- ];
- if ($schedule->client?->user_id) {
- $rooms[] = RealtimeRoom::user($schedule->client->user_id);
- }
- if ($provider->user_id) {
- $rooms[] = RealtimeRoom::user($provider->user_id);
- }
- return $rooms;
- }
- //
- public function acceptProposal($proposalId)
- {
- return DB::transaction(function () use ($proposalId) {
- $proposal = ScheduleProposal::findOrFail($proposalId);
- $schedule = $proposal->schedule;
- if ($schedule->provider_id) {
- throw new \Exception(__('validation.custom.opportunity.already_assigned'));
- }
- $provider = Provider::find($proposal->provider_id);
- $schedule->total_amount = $this->resolveProposalAmount($schedule, $provider);
- $schedule->save();
- $schedule->update([
- 'provider_id' => $proposal->provider_id,
- ]);
- $schedule->refresh();
- $schedule->load(['provider.user', 'client.user']);
- $notificationService = app(NotificationService::class);
- $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' => $provider->user_id,
- ]);
- app(ScheduleService::class)->updateStatus($schedule->id, 'paid');
- ScheduleProposal::where('schedule_id', $schedule->id)
- ->where('id', '!=', $proposalId)
- ->delete();
- $servicePackage = ServicePackage::create([
- 'client_id' => $schedule->client_id,
- 'provider_id' => $schedule->provider_id,
- ]);
- $servicePackage->items()->create([
- 'schedule_id' => $schedule->id,
- ]);
- $this->realtime->emit(
- RealtimeEvent::PROPOSAL_ACCEPTED,
- $this->proposalRooms($schedule, $provider),
- [
- 'entity' => 'schedule_proposal',
- 'id' => $proposalId,
- 'schedule_id' => $schedule->id,
- 'service_package_id' => $servicePackage->id,
- ],
- );
- return $servicePackage->fresh([
- 'items.schedule.client.user',
- 'items.schedule.provider.user',
- 'items.schedule.address',
- 'provider.user',
- ]);
- });
- }
- public function resolveProposalAmount(Schedule $schedule, Provider $provider): float
- {
- switch ($schedule->period_type) {
- case '8':
- return (float) $provider->daily_price_8h;
- case '6':
- return (float) $provider->daily_price_6h;
- case '4':
- return (float) $provider->daily_price_4h;
- case '2':
- return (float) $provider->daily_price_2h;
- default:
- throw new \Exception(__('messages.invalid_schedule_period'));
- }
- }
- public function refuseProposal($proposalId)
- {
- return DB::transaction(function () use ($proposalId) {
- $proposal = ScheduleProposal::findOrFail($proposalId);
- ScheduleRefuse::create([
- 'schedule_id' => $proposal->schedule_id,
- 'provider_id' => $proposal->provider_id,
- ]);
- $notificationService = app(NotificationService::class);
- $notificationService->create([
- 'title' => __('notifications.proposal_refused_title'),
- 'description' => __('notifications.proposal_refused_description'),
- 'origin' => 'schedule',
- 'origin_id' => $proposal->schedule_id,
- 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_REFUSED->value,
- 'user_id' => $proposal->provider->user_id,
- ]);
- // Push notification
- if ($proposal->provider?->user) {
- try {
- app(PushNotificationService::class)->sendToUser(
- $proposal->provider->user,
- new ClienteRecusouPush(
- $proposal->schedule?->client?->user?->name
- )
- );
- } catch (\Throwable $exception) {
- Log::error('Falha ao enviar push de recusa da proposta', [
- 'proposal_id' => $proposal->id,
- 'schedule_id' => $proposal->schedule_id,
- 'provider_id' => $proposal->provider_id,
- 'user_id' => $proposal->provider->user->id,
- 'error' => $exception->getMessage(),
- ]);
- }
- }
- $scheduleId = $proposal->schedule_id;
- $rooms = [
- RealtimeRoom::schedule($scheduleId),
- ];
- if ($proposal->schedule?->client?->user_id) {
- $rooms[] = RealtimeRoom::user($proposal->schedule->client->user_id);
- }
- if ($proposal->provider?->user_id) {
- $rooms[] = RealtimeRoom::user($proposal->provider->user_id);
- }
- $proposal->delete();
- $this->realtime->emit(
- RealtimeEvent::PROPOSAL_REFUSED,
- $rooms,
- [
- 'entity' => 'schedule_proposal',
- 'id' => $proposalId,
- 'schedule_id' => $scheduleId,
- 'actor' => 'client',
- ],
- );
- return true;
- });
- }
- //
- public function formatCustomSchedules($schedules)
- {
- $grouped = $schedules->groupBy('client_id')->map(function ($clientSchedules) {
- $firstSchedule = $clientSchedules->first();
- $clientPhotoPath = $firstSchedule->client->profileMedia?->path;
- return [
- 'client_id' => $firstSchedule->client_id,
- 'client_name' => $firstSchedule->client->user->name ?? 'N/A',
- 'customer_photo' => $clientPhotoPath
- ? Storage::temporaryUrl($clientPhotoPath, now()->addMinutes(60))
- : null,
- 'schedules' => $clientSchedules->map(function ($schedule) {
- $customSchedule = $schedule->customSchedule;
- 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,
- 'provider_id' => $schedule->provider_id,
- 'client_id' => $schedule->client_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',
- 'custom_schedule' => $customSchedule ? [
- 'id' => $customSchedule->id,
- 'address_type' => $customSchedule->address_type,
- 'service_type_id' => $customSchedule->service_type_id,
- 'service_type_name' => $customSchedule->serviceType?->description ?? 'N/A',
- 'description' => $customSchedule->description,
- 'min_price' => $customSchedule->min_price,
- 'max_price' => $customSchedule->max_price,
- 'offers_meal' => $customSchedule->offers_meal,
- 'specialities' => $customSchedule->specialities->map(function ($speciality) {
- return [
- 'id' => $speciality->id,
- 'description' => $speciality->description,
- ];
- })->values(),
- ] : null,
- '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 verifyScheduleCode($scheduleId, $code)
- {
- $schedule = Schedule::findOrFail($scheduleId);
- if ($schedule->code_verified) {
- throw new \Exception(__('validation.custom.opportunity.code_already_verified'));
- }
- if ($schedule->code !== $code) {
- throw new \Exception(__('validation.custom.opportunity.invalid_code'));
- }
- $schedule->update([
- 'code_verified' => true,
- ]);
- return $schedule;
- }
- //
- /**
- * @return Collection<int, int>
- */
- private static function providerHasActivePrimaryBankAccount($providerId): bool
- {
- return Provider::query()
- ->where('providers.id', $providerId)
- ->whereExists(Provider::hasActivePrimaryBankAccount())
- ->exists();
- }
- private function getCandidateProviderIdsForOpportunity(Schedule $schedule): Collection
- {
- $address = Address::find($schedule->address_id);
- $cityId = $address?->city_id;
- $lat = $address?->latitude !== null ? (float) $address->latitude : null;
- $lng = $address?->longitude !== null ? (float) $address->longitude : null;
- if ($cityId === null && ($lat === null || $lng === null)) {
- Log::warning('Oportunidade sem geolocalizacao; nenhum prestador elegivel', [
- 'schedule_id' => $schedule->id,
- 'address_id' => $schedule->address_id,
- ]);
- return collect();
- }
- $periodType = (string) $schedule->period_type;
- $factor = match ($periodType) {
- '2' => 0.30,
- '4' => 0.55,
- '6' => 0.85,
- '8' => 1.00,
- default => null,
- };
- if ($factor === null) {
- return collect();
- }
- $priceColumn = "providers.daily_price_{$periodType}h";
- $date = Carbon::parse($schedule->date);
- $dayOfWeek = $date->dayOfWeek;
- $period = $schedule->start_time < '13:00:00' ? 'morning' : 'afternoon';
- $minProportional = (float) $schedule->customSchedule->min_price * $factor;
- $maxProportional = (float) $schedule->customSchedule->max_price * $factor;
- $providerAddressSubquery = DB::raw("
- (
- SELECT DISTINCT ON (source_id)
- *
- FROM addresses
- WHERE
- source = 'provider'
- AND deleted_at IS NULL
- ORDER BY
- source_id,
- (latitude IS NOT NULL AND longitude IS NOT NULL) DESC,
- is_primary DESC,
- id DESC
- ) AS provider_address
- ");
- return Provider::query()
- ->join($providerAddressSubquery, 'provider_address.source_id', '=', 'providers.id')
- ->where('providers.approval_status', ApprovalStatusEnum::ACCEPTED->value)
- ->whereExists(Provider::hasActivePrimaryBankAccount())
- ->where(function ($query) use ($cityId, $lat, $lng) {
- if ($cityId !== null) {
- $query->orWhere('provider_address.city_id', $cityId);
- }
- if ($lat !== null && $lng !== null) {
- $query->orWhereRaw(
- DistanceService::withinRadiusSqlCondition(
- $lat,
- $lng,
- self::NEARBY_RADIUS_KM,
- 'provider_address.latitude',
- 'provider_address.longitude',
- )
- );
- }
- })
- ->whereExists(function ($query) use ($dayOfWeek, $period) {
- $query->select(DB::raw(1))
- ->from('provider_working_days')
- ->whereColumn('provider_working_days.provider_id', 'providers.id')
- ->where('provider_working_days.day', $dayOfWeek)
- ->where('provider_working_days.period', $period)
- ->whereNull('provider_working_days.deleted_at');
- })
- ->whereNotNull($priceColumn)
- ->whereBetween($priceColumn, [$minProportional, $maxProportional])
- ->whereNotIn(
- 'providers.id',
- ScheduleBusinessRules::getBlockedProviderIdsForClient($schedule->client_id)
- )
- ->pluck('providers.id');
- }
- private function dispatchOpportunityNotification(array $customSchedules): void
- {
- $scheduleIds = [];
- try {
- $scheduleIds = collect($customSchedules)
- ->pluck('schedule_id')
- ->filter()
- ->values()
- ->all();
- if (empty($scheduleIds)) {
- return;
- }
- NotifyProvidersOfNewOpportunityJob::dispatch($scheduleIds);
- } catch (\Throwable $exception) {
- Log::error('Falha ao enfileirar notificacao de nova oportunidade', [
- 'schedule_ids' => $scheduleIds,
- 'error' => $exception->getMessage(),
- ]);
- }
- }
- private function checkProviderAvailability($providerId, $schedule)
- {
- $client_id = $schedule->client_id;
- $provider_id = $providerId;
- $date = Carbon::parse($schedule->date);
- $dayOfWeek = $date->dayOfWeek; // 0-6
- $startTime = $schedule->start_time;
- $endTime = $schedule->end_time;
- $date_ymd = $date->format('Y-m-d');
- $period = $startTime < '13:00:00' ? 'morning' : 'afternoon';
- $period_type = $schedule->period_type; // 2,4,6,8
- // bloqueio 2 schedules por semana para o mesmo client e provider
- ScheduleBusinessRules::validateWeeklyScheduleLimit(
- $client_id,
- $provider_id,
- $date_ymd
- );
- // bloqueio provider trabalha no dia/periodo
- ScheduleBusinessRules::validateWorkingDay(
- $provider_id,
- $dayOfWeek,
- $period
- );
- // bloqueio provider tem blockedday para dia/hora
- ScheduleBusinessRules::validateBlockedDay(
- $provider_id,
- $date_ymd,
- $startTime,
- $endTime
- );
- // bloqueio daily_price do provider esta fora do range min_price e max_price
- ScheduleBusinessRules::validatePricePeriod(
- $provider_id,
- $schedule->customSchedule->min_price,
- $schedule->customSchedule->max_price,
- $period_type
- );
- // bloqueio provider tem outro agendamento para dia/hora
- ScheduleBusinessRules::validateConflictingSchedule(
- $provider_id,
- $date_ymd,
- $startTime,
- $endTime
- );
- // bloqueio provider tem outra proposta para o mesmo agendamento
- ScheduleBusinessRules::validateConflictingSameProposal(
- $provider_id,
- $schedule->id
- );
- // bloqueio provider tem outra proposta na mesma data
- ScheduleBusinessRules::validateConflictingProposalSameDate(
- $provider_id,
- $date_ymd,
- $startTime,
- $endTime,
- $schedule->id
- );
- // 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;
- }
- }
|