| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121 |
- <?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)
- {
- 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);
- $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 ($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,
- ]);
- try {
- app(PushNotificationService::class)->sendToUser(
- $provider->user,
- new ClienteAceitouPush($schedule->client->user->name)
- );
- } catch (\Throwable $exception) {
- Log::error('Falha ao enviar push de cliente aceitou proposta', [
- 'schedule_id' => $schedule->id,
- 'provider_id' => $provider->id,
- 'error' => $exception->getMessage(),
- ]);
- }
- app(ScheduleService::class)->updateStatus($schedule->id, 'accepted');
- 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 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)
- ->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;
- }
- }
|