CustomScheduleService.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  1. <?php
  2. namespace App\Services;
  3. use App\Broadcasting\RealtimeEvent;
  4. use App\Broadcasting\RealtimeRoom;
  5. use App\Broadcasting\RealtimeService;
  6. use App\Enums\ApprovalStatusEnum;
  7. use App\Enums\NotificationTypeEnum;
  8. use App\Jobs\NotifyProvidersOfNewOpportunityJob;
  9. use App\Models\Address;
  10. use App\Models\CustomSchedule;
  11. use App\Models\CustomScheduleSpeciality;
  12. use App\Models\Provider;
  13. use App\Models\Schedule;
  14. use App\Models\ScheduleProposal;
  15. use App\Models\ScheduleRefuse;
  16. use App\Models\ServicePackage;
  17. use App\Notifications\Push\Cliente\Agendamento\PrestadorAceitouPush;
  18. use App\Notifications\Push\Cliente\Agendamento\PrestadorRecusouPush;
  19. use App\Notifications\Push\Prestador\Agendamento\ClienteRecusouPush;
  20. use App\Notifications\Push\Prestador\Agendamento\ClienteAceitouPush;
  21. use App\Services\PushNotificationService;
  22. use App\Rules\ScheduleBusinessRules;
  23. use App\Services\NotificationService;
  24. use App\Services\DistanceService;
  25. use Carbon\Carbon;
  26. use Illuminate\Support\Collection;
  27. use Illuminate\Support\Facades\DB;
  28. use Illuminate\Support\Facades\Log;
  29. use Illuminate\Support\Facades\Storage;
  30. class CustomScheduleService
  31. {
  32. private const NEARBY_RADIUS_KM = 20.0;
  33. public function __construct(
  34. private readonly ZipCodeCoordinatesService $zipCodeCoordinatesService,
  35. private readonly RealtimeService $realtime,
  36. ) {}
  37. public function getAll()
  38. {
  39. $custom_schedules = CustomSchedule::with([
  40. 'schedule.client.user',
  41. 'schedule.address',
  42. 'serviceType',
  43. 'specialities.speciality',
  44. ])
  45. ->orderBy('id', 'desc')
  46. ->get();
  47. return $custom_schedules;
  48. }
  49. public function getById($id)
  50. {
  51. $customSchedule = CustomSchedule::with([
  52. 'schedule.client.user',
  53. 'schedule.client.profileMedia',
  54. 'schedule.address',
  55. 'serviceType',
  56. 'specialities.speciality',
  57. ])->find($id);
  58. return $customSchedule;
  59. }
  60. public function create(array $data)
  61. {
  62. $address = Address::find(data_get($data, 'address_id'));
  63. if (! $address || $address->latitude === null || $address->longitude === null) {
  64. throw new \Exception(__('messages.client_address_location_required'));
  65. }
  66. DB::beginTransaction();
  67. try {
  68. $quantity = data_get($data, 'quantity', 1);
  69. $specialityIds = data_get($data, 'speciality_ids', []);
  70. $createdCustomSchedules = [];
  71. for ($i = 0; $i < $quantity; $i++) {
  72. $scheduleData = [
  73. 'client_id' => data_get($data, 'client_id'),
  74. 'provider_id' => null,
  75. 'address_id' => data_get($data, 'address_id'),
  76. 'date' => data_get($data, 'date'),
  77. 'period_type' => data_get($data, 'period_type'),
  78. 'schedule_type' => 'custom',
  79. 'start_time' => data_get($data, 'start_time'),
  80. 'end_time' => data_get($data, 'end_time'),
  81. 'status' => 'pending',
  82. 'total_amount' => 0,
  83. 'code' => str_pad(random_int(0, 9999), 4, '0', STR_PAD_LEFT),
  84. 'code_verified' => false,
  85. ];
  86. $schedule = Schedule::create($scheduleData);
  87. $customScheduleData = [
  88. 'schedule_id' => $schedule->id,
  89. 'address_type' => data_get($data, 'address_type'),
  90. 'service_type_id' => data_get($data, 'service_type_id'),
  91. 'description' => data_get($data, 'description'),
  92. 'min_price' => data_get($data, 'min_price'),
  93. 'max_price' => data_get($data, 'max_price'),
  94. 'offers_meal' => data_get($data, 'offers_meal', false),
  95. ];
  96. $customSchedule = CustomSchedule::create($customScheduleData);
  97. if (! empty($specialityIds)) {
  98. foreach ($specialityIds as $specialityId) {
  99. CustomScheduleSpeciality::create([
  100. 'custom_schedule_id' => $customSchedule->id,
  101. 'speciality_id' => $specialityId,
  102. ]);
  103. }
  104. }
  105. $createdCustomSchedules[] = $customSchedule->load([
  106. 'schedule.client.user',
  107. 'schedule.address',
  108. 'serviceType',
  109. 'specialities.speciality',
  110. ]);
  111. }
  112. DB::commit();
  113. $this->dispatchOpportunityNotification($createdCustomSchedules);
  114. return $createdCustomSchedules;
  115. } catch (\Exception $e) {
  116. DB::rollBack();
  117. Log::error('Erro ao criar agendamento personalizado: ' . $e->getMessage());
  118. throw $e;
  119. }
  120. }
  121. public function update($id, array $data)
  122. {
  123. DB::beginTransaction();
  124. try {
  125. $customSchedule = CustomSchedule::findOrFail($id);
  126. $schedule = $customSchedule->schedule;
  127. $scheduleUpdateData = [];
  128. if (data_get($data, 'address_id') !== null) {
  129. $scheduleUpdateData['address_id'] = data_get($data, 'address_id');
  130. }
  131. if (data_get($data, 'date') !== null) {
  132. $scheduleUpdateData['date'] = data_get($data, 'date');
  133. }
  134. if (data_get($data, 'period_type') !== null) {
  135. $scheduleUpdateData['period_type'] = data_get($data, 'period_type');
  136. }
  137. if (data_get($data, 'start_time') !== null) {
  138. $scheduleUpdateData['start_time'] = data_get($data, 'start_time');
  139. }
  140. if (data_get($data, 'end_time') !== null) {
  141. $scheduleUpdateData['end_time'] = data_get($data, 'end_time');
  142. }
  143. if (! empty($scheduleUpdateData)) {
  144. $schedule->update($scheduleUpdateData);
  145. }
  146. $customScheduleUpdateData = [];
  147. if (data_get($data, 'address_type') !== null) {
  148. $customScheduleUpdateData['address_type'] = data_get($data, 'address_type');
  149. }
  150. if (data_get($data, 'service_type_id') !== null) {
  151. $customScheduleUpdateData['service_type_id'] = data_get($data, 'service_type_id');
  152. }
  153. if (data_get($data, 'description') !== null) {
  154. $customScheduleUpdateData['description'] = data_get($data, 'description');
  155. }
  156. if (data_get($data, 'min_price') !== null) {
  157. $customScheduleUpdateData['min_price'] = data_get($data, 'min_price');
  158. }
  159. if (data_get($data, 'max_price') !== null) {
  160. $customScheduleUpdateData['max_price'] = data_get($data, 'max_price');
  161. }
  162. if (data_get($data, 'offers_meal') !== null) {
  163. $customScheduleUpdateData['offers_meal'] = data_get($data, 'offers_meal');
  164. }
  165. if (! empty($customScheduleUpdateData)) {
  166. $customSchedule->update($customScheduleUpdateData);
  167. }
  168. if (data_get($data, 'speciality_ids') !== null) {
  169. $custom_schedule = CustomScheduleSpeciality::where('custom_schedule_id', $customSchedule->id);
  170. $custom_schedule->delete();
  171. foreach (data_get($data, 'speciality_ids') as $specialityId) {
  172. CustomScheduleSpeciality::create([
  173. 'custom_schedule_id' => $customSchedule->id,
  174. 'speciality_id' => $specialityId,
  175. ]);
  176. }
  177. }
  178. DB::commit();
  179. return $customSchedule->fresh([
  180. 'schedule.client.user',
  181. 'schedule.address',
  182. 'serviceType',
  183. 'specialities.speciality',
  184. ]);
  185. } catch (\Exception $e) {
  186. DB::rollBack();
  187. Log::error('Erro ao atualizar agendamento personalizado: ' . $e->getMessage());
  188. throw $e;
  189. }
  190. }
  191. public function delete($id)
  192. {
  193. DB::beginTransaction();
  194. try {
  195. $customSchedule = CustomSchedule::findOrFail($id);
  196. $schedule = $customSchedule->schedule;
  197. CustomScheduleSpeciality::where('custom_schedule_id', $customSchedule->id)->delete();
  198. $customSchedule->delete();
  199. $schedule->delete();
  200. DB::commit();
  201. return $customSchedule;
  202. } catch (\Exception $e) {
  203. DB::rollBack();
  204. Log::error('Erro ao excluir agendamento personalizado: ' . $e->getMessage());
  205. throw $e;
  206. }
  207. }
  208. //
  209. public function getAvailableOpportunities($providerId)
  210. {
  211. $provider = Provider::find($providerId);
  212. $providerAddress = Address::where('source', 'provider')
  213. ->where('source_id', $providerId)
  214. ->orderBy('is_primary', 'desc')
  215. ->first();
  216. $providerCityId = $providerAddress?->city_id;
  217. $providerLat = $providerAddress?->latitude !== null ? (float) $providerAddress->latitude : null;
  218. $providerLng = $providerAddress?->longitude !== null ? (float) $providerAddress->longitude : null;
  219. $opportunities = Schedule::with([
  220. 'client.user',
  221. 'client.profileMedia',
  222. 'address:id,district,zip_code,latitude,longitude',
  223. 'customSchedule.serviceType',
  224. 'customSchedule.specialities',
  225. ])
  226. ->leftJoin('schedule_refuses', function ($join) use ($providerId) {
  227. $join->on('schedules.id', '=', 'schedule_refuses.schedule_id')
  228. ->where('schedule_refuses.provider_id', $providerId);
  229. })
  230. ->leftJoin('addresses as opportunity_address', 'opportunity_address.id', '=', 'schedules.address_id')
  231. ->whereNull('schedule_refuses.id')
  232. ->where('schedules.schedule_type', 'custom')
  233. ->where('schedules.status', 'pending')
  234. ->whereNull('schedules.provider_id')
  235. ->whereDate('schedules.date', '>=', now()->toDateString())
  236. ->where(function ($query) use ($providerCityId, $providerLat, $providerLng) {
  237. if ($providerCityId !== null) {
  238. $query->where('opportunity_address.city_id', $providerCityId);
  239. }
  240. if ($providerLat !== null && $providerLng !== null) {
  241. $method = $providerCityId !== null ? 'orWhereRaw' : 'whereRaw';
  242. $query->{$method}(
  243. DistanceService::withinRadiusSqlCondition(
  244. $providerLat,
  245. $providerLng,
  246. self::NEARBY_RADIUS_KM,
  247. 'opportunity_address.latitude',
  248. 'opportunity_address.longitude',
  249. )
  250. );
  251. return;
  252. }
  253. if ($providerCityId === null) {
  254. $query->whereRaw('1 = 0');
  255. }
  256. })
  257. ->select(
  258. 'schedules.id',
  259. 'schedules.client_id',
  260. 'schedules.address_id',
  261. 'schedules.date',
  262. 'schedules.period_type',
  263. 'schedules.start_time',
  264. 'schedules.end_time',
  265. 'schedules.total_amount',
  266. DB::raw("
  267. CASE
  268. WHEN schedules.period_type = '2' THEN {$provider->daily_price_2h}
  269. WHEN schedules.period_type = '4' THEN {$provider->daily_price_4h}
  270. WHEN schedules.period_type = '6' THEN {$provider->daily_price_6h}
  271. WHEN schedules.period_type = '8' THEN {$provider->daily_price_8h}
  272. ELSE 0
  273. END AS total_amount
  274. "),
  275. )
  276. ->get();
  277. $proposedScheduleIds = ScheduleProposal::where('provider_id', $providerId)
  278. ->pluck('schedule_id')
  279. ->flip();
  280. $availableOpportunities = $opportunities->filter(function ($opportunity) use ($providerId, $proposedScheduleIds) {
  281. if ($proposedScheduleIds->has($opportunity->id)) {
  282. return true;
  283. }
  284. try {
  285. return $this->checkProviderAvailability($providerId, $opportunity);
  286. } catch (\Exception $e) {
  287. return false;
  288. }
  289. });
  290. $availableOpportunities->each(function ($opportunity) use ($providerAddress, $proposedScheduleIds) {
  291. $opportunity->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
  292. $providerAddress?->latitude !== null ? (float) $providerAddress->latitude : null,
  293. $providerAddress?->longitude !== null ? (float) $providerAddress->longitude : null,
  294. $providerAddress?->zip_code,
  295. $opportunity->address?->latitude !== null ? (float) $opportunity->address->latitude : null,
  296. $opportunity->address?->longitude !== null ? (float) $opportunity->address->longitude : null,
  297. $opportunity->address?->zip_code,
  298. );
  299. $photoPath = $opportunity->client->profileMedia?->path;
  300. $opportunity->customer_photo = $photoPath
  301. ? Storage::temporaryUrl($photoPath, now()->addMinutes(60))
  302. : null;
  303. $opportunity->proposal_sent = $proposedScheduleIds->has($opportunity->id);
  304. });
  305. return $availableOpportunities->values();
  306. }
  307. /**
  308. * @return Collection<int, int>
  309. */
  310. public function getAvailableProvidersForOpportunity(Schedule $schedule): Collection
  311. {
  312. $schedule->loadMissing(['customSchedule', 'address']);
  313. $candidateIds = $this->getCandidateProviderIdsForOpportunity($schedule);
  314. if ($candidateIds->isEmpty()) {
  315. return $candidateIds;
  316. }
  317. return $candidateIds->filter(function ($providerId) use ($schedule) {
  318. try {
  319. return $this->checkProviderAvailability($providerId, $schedule);
  320. } catch (\Exception $e) {
  321. return false;
  322. }
  323. })->values();
  324. }
  325. public function getOpportunityProposals($scheduleId)
  326. {
  327. return ScheduleProposal::with(['provider.user'])
  328. ->where('schedule_id', $scheduleId)
  329. ->orderBy('created_at', 'desc')
  330. ->get();
  331. }
  332. public function getProvidersProposalsAndOpportunities($providerId)
  333. {
  334. $proposals = $this->getProviderProposals($providerId);
  335. $opportunities = $this->formatCustomSchedules($this->getAvailableOpportunities($providerId));
  336. return [
  337. 'proposals' => $proposals,
  338. 'opportunities' => $opportunities,
  339. ];
  340. }
  341. public function getProviderProposals($providerId)
  342. {
  343. return ScheduleProposal::with([
  344. 'schedule.client.user',
  345. 'schedule.address',
  346. 'schedule.address.city',
  347. 'schedule.address.state',
  348. 'schedule.customSchedule.serviceType',
  349. 'schedule.customSchedule.specialities',
  350. 'schedule.provider.user',
  351. ])
  352. ->where('provider_id', $providerId)
  353. ->orderBy('created_at', 'desc')
  354. ->get();
  355. }
  356. public function getSchedulesCustomGroupedByClient()
  357. {
  358. $schedules = Schedule::with(['client.user', 'provider.user', 'address', 'customSchedule.serviceType', 'customSchedule.specialities', 'reviews.reviewsImprovements.improvementType'])
  359. ->orderBy('id', 'desc')
  360. ->where('schedule_type', 'custom')
  361. ->get();
  362. $grouped = $this->formatCustomSchedules($schedules);
  363. return $grouped;
  364. }
  365. //
  366. public function proposeOpportunity($scheduleId, $providerId)
  367. {
  368. $schedule = Schedule::findOrFail($scheduleId);
  369. if ($schedule->provider_id) {
  370. throw new \Exception(__('validation.custom.opportunity.already_assigned'));
  371. }
  372. $existingProposal = ScheduleProposal::where('schedule_id', $scheduleId)
  373. ->where('provider_id', $providerId)
  374. ->first();
  375. if ($existingProposal) {
  376. throw new \Exception(__('validation.custom.opportunity.proposal_already_sent'));
  377. }
  378. $wasRefused = ScheduleRefuse::where('schedule_id', $scheduleId)
  379. ->where('provider_id', $providerId)
  380. ->exists();
  381. if ($wasRefused) {
  382. throw new \Exception(__('validation.custom.opportunity.provider_refused'));
  383. }
  384. $this->checkProviderAvailability($providerId, $schedule);
  385. $provider = Provider::with([
  386. 'user'
  387. ])->findOrFail($providerId);
  388. $schedule->load([
  389. 'client.user'
  390. ]);
  391. $notificationService = app(NotificationService::class);
  392. $notificationService->create([
  393. 'title' => __('notifications.new_proposal_title'),
  394. 'description' => __('notifications.new_proposal_description', ['provider' => $provider->user->name]),
  395. 'origin' => 'schedule',
  396. 'origin_id' => $schedule->id,
  397. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_NEW_SOLICITATION->value,
  398. 'user_id' => $schedule->client->user_id,
  399. ]);
  400. $this->sendProposalReceivedPush($schedule, $provider->user->name);
  401. $proposal = ScheduleProposal::create([
  402. 'schedule_id' => $scheduleId,
  403. 'provider_id' => $providerId,
  404. ]);
  405. $this->realtime->emit(
  406. RealtimeEvent::PROPOSAL_CREATED,
  407. $this->proposalRooms($schedule, $provider),
  408. [
  409. 'entity' => 'schedule_proposal',
  410. 'id' => $proposal->id,
  411. 'schedule_id' => $schedule->id,
  412. ],
  413. );
  414. return $proposal;
  415. }
  416. private function sendProposalReceivedPush(Schedule $schedule, string $providerName): void
  417. {
  418. $user = $schedule->client->user;
  419. if (! $user) {
  420. Log::warning('Push de proposta ignorada: cliente sem usuário', [
  421. 'schedule_id' => $schedule->id,
  422. ]);
  423. return;
  424. }
  425. try {
  426. app(PushNotificationService::class)->sendToUser(
  427. $user,
  428. new PrestadorAceitouPush($providerName, isProposal: true)
  429. );
  430. } catch (\Throwable $exception) {
  431. Log::error('Falha ao enviar push de nova proposta sob medida', [
  432. 'schedule_id' => $schedule->id,
  433. 'user_id' => $user->id,
  434. 'error' => $exception->getMessage(),
  435. ]);
  436. }
  437. }
  438. public function refuseOpportunity($scheduleId, $providerId)
  439. {
  440. $schedule = Schedule::with(['client.user'])->findOrFail($scheduleId);
  441. $provider = Provider::with(['user'])->findOrFail($providerId);
  442. $schedule_refuse = ScheduleRefuse::create([
  443. 'schedule_id' => $scheduleId,
  444. 'provider_id' => $providerId,
  445. ]);
  446. $notificationService = app(NotificationService::class);
  447. $notificationService->create([
  448. 'title' => __('notifications.opportunity_refused_title'),
  449. 'description' => __('notifications.opportunity_refused_description', [
  450. 'provider' => $provider->user->name,
  451. ]),
  452. 'origin' => 'schedule',
  453. 'origin_id' => $scheduleId,
  454. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_REFUSED->value,
  455. 'user_id' => $schedule->client->user_id,
  456. ]);
  457. // Push notification
  458. if ($schedule->client?->user) {
  459. try {
  460. app(PushNotificationService::class)->sendToUser(
  461. $schedule->client->user,
  462. new PrestadorRecusouPush(
  463. $provider->user->name
  464. )
  465. );
  466. } catch (\Throwable $exception) {
  467. Log::error('Falha ao enviar push de recusa da oportunidade', [
  468. 'schedule_id' => $schedule->id,
  469. 'provider_id' => $providerId,
  470. 'user_id' => $schedule->client->user->id,
  471. 'error' => $exception->getMessage(),
  472. ]);
  473. }
  474. }
  475. $this->realtime->emit(
  476. RealtimeEvent::PROPOSAL_REFUSED,
  477. $this->proposalRooms($schedule, $provider),
  478. [
  479. 'entity' => 'schedule_refuse',
  480. 'id' => $schedule_refuse->id,
  481. 'schedule_id' => $schedule->id,
  482. 'actor' => 'provider',
  483. ],
  484. );
  485. return $schedule_refuse;
  486. }
  487. /**
  488. * Salas dos dois lados de uma proposta, mais quem estiver com o
  489. * agendamento aberto.
  490. *
  491. * @return RealtimeRoom[]
  492. */
  493. private function proposalRooms(Schedule $schedule, Provider $provider): array
  494. {
  495. $rooms = [
  496. RealtimeRoom::schedule($schedule->id),
  497. ];
  498. if ($schedule->client?->user_id) {
  499. $rooms[] = RealtimeRoom::user($schedule->client->user_id);
  500. }
  501. if ($provider->user_id) {
  502. $rooms[] = RealtimeRoom::user($provider->user_id);
  503. }
  504. return $rooms;
  505. }
  506. //
  507. public function acceptProposal($proposalId)
  508. {
  509. return DB::transaction(function () use ($proposalId) {
  510. $proposal = ScheduleProposal::findOrFail($proposalId);
  511. $schedule = $proposal->schedule;
  512. if ($schedule->provider_id) {
  513. throw new \Exception(__('validation.custom.opportunity.already_assigned'));
  514. }
  515. $provider = Provider::find($proposal->provider_id);
  516. $schedule->total_amount = $this->resolveProposalAmount($schedule, $provider);
  517. $schedule->save();
  518. $schedule->update([
  519. 'provider_id' => $proposal->provider_id,
  520. ]);
  521. $schedule->refresh();
  522. $schedule->load(['provider.user', 'client.user']);
  523. $notificationService = app(NotificationService::class);
  524. $notificationService->create([
  525. 'title' => __('notifications.proposal_accepted_title'),
  526. 'description' => __('notifications.proposal_accepted_description'),
  527. 'origin' => 'schedule',
  528. 'origin_id' => $schedule->id,
  529. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_PROPOSAL_ACCEPTED->value,
  530. 'user_id' => $provider->user_id,
  531. ]);
  532. app(ScheduleService::class)->updateStatus($schedule->id, 'paid');
  533. ScheduleProposal::where('schedule_id', $schedule->id)
  534. ->where('id', '!=', $proposalId)
  535. ->delete();
  536. $servicePackage = ServicePackage::create([
  537. 'client_id' => $schedule->client_id,
  538. 'provider_id' => $schedule->provider_id,
  539. ]);
  540. $servicePackage->items()->create([
  541. 'schedule_id' => $schedule->id,
  542. ]);
  543. $this->realtime->emit(
  544. RealtimeEvent::PROPOSAL_ACCEPTED,
  545. $this->proposalRooms($schedule, $provider),
  546. [
  547. 'entity' => 'schedule_proposal',
  548. 'id' => $proposalId,
  549. 'schedule_id' => $schedule->id,
  550. 'service_package_id' => $servicePackage->id,
  551. ],
  552. );
  553. return $servicePackage->fresh([
  554. 'items.schedule.client.user',
  555. 'items.schedule.provider.user',
  556. 'items.schedule.address',
  557. 'provider.user',
  558. ]);
  559. });
  560. }
  561. public function resolveProposalAmount(Schedule $schedule, Provider $provider): float
  562. {
  563. switch ($schedule->period_type) {
  564. case '8':
  565. return (float) $provider->daily_price_8h;
  566. case '6':
  567. return (float) $provider->daily_price_6h;
  568. case '4':
  569. return (float) $provider->daily_price_4h;
  570. case '2':
  571. return (float) $provider->daily_price_2h;
  572. default:
  573. throw new \Exception(__('messages.invalid_schedule_period'));
  574. }
  575. }
  576. public function refuseProposal($proposalId)
  577. {
  578. return DB::transaction(function () use ($proposalId) {
  579. $proposal = ScheduleProposal::findOrFail($proposalId);
  580. ScheduleRefuse::create([
  581. 'schedule_id' => $proposal->schedule_id,
  582. 'provider_id' => $proposal->provider_id,
  583. ]);
  584. $notificationService = app(NotificationService::class);
  585. $notificationService->create([
  586. 'title' => __('notifications.proposal_refused_title'),
  587. 'description' => __('notifications.proposal_refused_description'),
  588. 'origin' => 'schedule',
  589. 'origin_id' => $proposal->schedule_id,
  590. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_REFUSED->value,
  591. 'user_id' => $proposal->provider->user_id,
  592. ]);
  593. // Push notification
  594. if ($proposal->provider?->user) {
  595. try {
  596. app(PushNotificationService::class)->sendToUser(
  597. $proposal->provider->user,
  598. new ClienteRecusouPush(
  599. $proposal->schedule?->client?->user?->name
  600. )
  601. );
  602. } catch (\Throwable $exception) {
  603. Log::error('Falha ao enviar push de recusa da proposta', [
  604. 'proposal_id' => $proposal->id,
  605. 'schedule_id' => $proposal->schedule_id,
  606. 'provider_id' => $proposal->provider_id,
  607. 'user_id' => $proposal->provider->user->id,
  608. 'error' => $exception->getMessage(),
  609. ]);
  610. }
  611. }
  612. $scheduleId = $proposal->schedule_id;
  613. $rooms = [
  614. RealtimeRoom::schedule($scheduleId),
  615. ];
  616. if ($proposal->schedule?->client?->user_id) {
  617. $rooms[] = RealtimeRoom::user($proposal->schedule->client->user_id);
  618. }
  619. if ($proposal->provider?->user_id) {
  620. $rooms[] = RealtimeRoom::user($proposal->provider->user_id);
  621. }
  622. $proposal->delete();
  623. $this->realtime->emit(
  624. RealtimeEvent::PROPOSAL_REFUSED,
  625. $rooms,
  626. [
  627. 'entity' => 'schedule_proposal',
  628. 'id' => $proposalId,
  629. 'schedule_id' => $scheduleId,
  630. 'actor' => 'client',
  631. ],
  632. );
  633. return true;
  634. });
  635. }
  636. //
  637. public function formatCustomSchedules($schedules)
  638. {
  639. $grouped = $schedules->groupBy('client_id')->map(function ($clientSchedules) {
  640. $firstSchedule = $clientSchedules->first();
  641. $clientPhotoPath = $firstSchedule->client->profileMedia?->path;
  642. return [
  643. 'client_id' => $firstSchedule->client_id,
  644. 'client_name' => $firstSchedule->client->user->name ?? 'N/A',
  645. 'customer_photo' => $clientPhotoPath
  646. ? Storage::temporaryUrl($clientPhotoPath, now()->addMinutes(60))
  647. : null,
  648. 'schedules' => $clientSchedules->map(function ($schedule) {
  649. $customSchedule = $schedule->customSchedule;
  650. return [
  651. 'id' => $schedule->id,
  652. 'date' => $schedule->date ? Carbon::parse($schedule->date)->format('d/m/Y') : null,
  653. 'start_time' => $schedule->start_time,
  654. 'end_time' => $schedule->end_time,
  655. 'period_type' => $schedule->period_type,
  656. 'status' => $schedule->status,
  657. 'total_amount' => $schedule->total_amount,
  658. 'code' => $schedule->code,
  659. 'code_verified' => $schedule->code_verified,
  660. 'provider_id' => $schedule->provider_id,
  661. 'client_id' => $schedule->client_id,
  662. 'provider_name' => $schedule->provider?->user->name ?? 'N/A',
  663. 'address' => $schedule->address ? [
  664. 'id' => $schedule->address->id,
  665. 'address' => $schedule->address->address,
  666. 'complement' => $schedule->address->complement,
  667. 'zip_code' => $schedule->address->zip_code,
  668. 'city' => $schedule->address->city->name ?? '',
  669. 'state' => $schedule->address->city->state->name ?? '',
  670. ] : null,
  671. 'client_name' => $schedule->client->user->name ?? 'N/A',
  672. 'custom_schedule' => $customSchedule ? [
  673. 'id' => $customSchedule->id,
  674. 'address_type' => $customSchedule->address_type,
  675. 'service_type_id' => $customSchedule->service_type_id,
  676. 'service_type_name' => $customSchedule->serviceType?->description ?? 'N/A',
  677. 'description' => $customSchedule->description,
  678. 'min_price' => $customSchedule->min_price,
  679. 'max_price' => $customSchedule->max_price,
  680. 'offers_meal' => $customSchedule->offers_meal,
  681. 'specialities' => $customSchedule->specialities->map(function ($speciality) {
  682. return [
  683. 'id' => $speciality->id,
  684. 'description' => $speciality->description,
  685. ];
  686. })->values(),
  687. ] : null,
  688. 'reviews' => $schedule->reviews->map(function ($review) {
  689. return [
  690. 'id' => $review->id,
  691. 'stars' => $review->stars,
  692. 'comment' => $review->comment,
  693. 'origin' => $review->origin,
  694. 'origin_id' => $review->origin_id,
  695. 'created_at' => Carbon::parse($review->created_at)->format('Y-m-d H:i'),
  696. 'updated_at' => Carbon::parse($review->updated_at)->format('Y-m-d H:i'),
  697. 'improvements' => $review->reviewsImprovements->map(function ($ri) {
  698. return [
  699. 'id' => $ri->id,
  700. 'improvement_type_id' => $ri->improvement_type_id,
  701. 'improvement_type_name' => $ri->improvementType ? $ri->improvementType->description : null,
  702. ];
  703. })->values(),
  704. ];
  705. }),
  706. ];
  707. })->values(),
  708. ];
  709. })->sortBy('id')->values();
  710. return $grouped;
  711. }
  712. public function verifyScheduleCode($scheduleId, $code)
  713. {
  714. $schedule = Schedule::findOrFail($scheduleId);
  715. if ($schedule->code_verified) {
  716. throw new \Exception(__('validation.custom.opportunity.code_already_verified'));
  717. }
  718. if ($schedule->code !== $code) {
  719. throw new \Exception(__('validation.custom.opportunity.invalid_code'));
  720. }
  721. $schedule->update([
  722. 'code_verified' => true,
  723. ]);
  724. return $schedule;
  725. }
  726. //
  727. /**
  728. * @return Collection<int, int>
  729. */
  730. private function getCandidateProviderIdsForOpportunity(Schedule $schedule): Collection
  731. {
  732. $address = Address::find($schedule->address_id);
  733. $cityId = $address?->city_id;
  734. $lat = $address?->latitude !== null ? (float) $address->latitude : null;
  735. $lng = $address?->longitude !== null ? (float) $address->longitude : null;
  736. if ($cityId === null && ($lat === null || $lng === null)) {
  737. Log::warning('Oportunidade sem geolocalizacao; nenhum prestador elegivel', [
  738. 'schedule_id' => $schedule->id,
  739. 'address_id' => $schedule->address_id,
  740. ]);
  741. return collect();
  742. }
  743. $periodType = (string) $schedule->period_type;
  744. $factor = match ($periodType) {
  745. '2' => 0.30,
  746. '4' => 0.55,
  747. '6' => 0.85,
  748. '8' => 1.00,
  749. default => null,
  750. };
  751. if ($factor === null) {
  752. return collect();
  753. }
  754. $priceColumn = "providers.daily_price_{$periodType}h";
  755. $date = Carbon::parse($schedule->date);
  756. $dayOfWeek = $date->dayOfWeek;
  757. $period = $schedule->start_time < '13:00:00' ? 'morning' : 'afternoon';
  758. $minProportional = (float) $schedule->customSchedule->min_price * $factor;
  759. $maxProportional = (float) $schedule->customSchedule->max_price * $factor;
  760. $providerAddressSubquery = DB::raw("
  761. (
  762. SELECT DISTINCT ON (source_id)
  763. *
  764. FROM addresses
  765. WHERE
  766. source = 'provider'
  767. AND deleted_at IS NULL
  768. ORDER BY
  769. source_id,
  770. (latitude IS NOT NULL AND longitude IS NOT NULL) DESC,
  771. is_primary DESC,
  772. id DESC
  773. ) AS provider_address
  774. ");
  775. return Provider::query()
  776. ->join($providerAddressSubquery, 'provider_address.source_id', '=', 'providers.id')
  777. ->where('providers.approval_status', ApprovalStatusEnum::ACCEPTED->value)
  778. ->where(function ($query) use ($cityId, $lat, $lng) {
  779. if ($cityId !== null) {
  780. $query->orWhere('provider_address.city_id', $cityId);
  781. }
  782. if ($lat !== null && $lng !== null) {
  783. $query->orWhereRaw(
  784. DistanceService::withinRadiusSqlCondition(
  785. $lat,
  786. $lng,
  787. self::NEARBY_RADIUS_KM,
  788. 'provider_address.latitude',
  789. 'provider_address.longitude',
  790. )
  791. );
  792. }
  793. })
  794. ->whereExists(function ($query) use ($dayOfWeek, $period) {
  795. $query->select(DB::raw(1))
  796. ->from('provider_working_days')
  797. ->whereColumn('provider_working_days.provider_id', 'providers.id')
  798. ->where('provider_working_days.day', $dayOfWeek)
  799. ->where('provider_working_days.period', $period)
  800. ->whereNull('provider_working_days.deleted_at');
  801. })
  802. ->whereNotNull($priceColumn)
  803. ->whereBetween($priceColumn, [$minProportional, $maxProportional])
  804. ->whereNotIn(
  805. 'providers.id',
  806. ScheduleBusinessRules::getBlockedProviderIdsForClient($schedule->client_id)
  807. )
  808. ->pluck('providers.id');
  809. }
  810. private function dispatchOpportunityNotification(array $customSchedules): void
  811. {
  812. $scheduleIds = [];
  813. try {
  814. $scheduleIds = collect($customSchedules)
  815. ->pluck('schedule_id')
  816. ->filter()
  817. ->values()
  818. ->all();
  819. if (empty($scheduleIds)) {
  820. return;
  821. }
  822. NotifyProvidersOfNewOpportunityJob::dispatch($scheduleIds);
  823. } catch (\Throwable $exception) {
  824. Log::error('Falha ao enfileirar notificacao de nova oportunidade', [
  825. 'schedule_ids' => $scheduleIds,
  826. 'error' => $exception->getMessage(),
  827. ]);
  828. }
  829. }
  830. private function checkProviderAvailability($providerId, $schedule)
  831. {
  832. $client_id = $schedule->client_id;
  833. $provider_id = $providerId;
  834. $date = Carbon::parse($schedule->date);
  835. $dayOfWeek = $date->dayOfWeek; // 0-6
  836. $startTime = $schedule->start_time;
  837. $endTime = $schedule->end_time;
  838. $date_ymd = $date->format('Y-m-d');
  839. $period = $startTime < '13:00:00' ? 'morning' : 'afternoon';
  840. $period_type = $schedule->period_type; // 2,4,6,8
  841. // bloqueio 2 schedules por semana para o mesmo client e provider
  842. ScheduleBusinessRules::validateWeeklyScheduleLimit(
  843. $client_id,
  844. $provider_id,
  845. $date_ymd
  846. );
  847. // bloqueio provider trabalha no dia/periodo
  848. ScheduleBusinessRules::validateWorkingDay(
  849. $provider_id,
  850. $dayOfWeek,
  851. $period
  852. );
  853. // bloqueio provider tem blockedday para dia/hora
  854. ScheduleBusinessRules::validateBlockedDay(
  855. $provider_id,
  856. $date_ymd,
  857. $startTime,
  858. $endTime
  859. );
  860. // bloqueio daily_price do provider esta fora do range min_price e max_price
  861. ScheduleBusinessRules::validatePricePeriod(
  862. $provider_id,
  863. $schedule->customSchedule->min_price,
  864. $schedule->customSchedule->max_price,
  865. $period_type
  866. );
  867. // bloqueio provider tem outro agendamento para dia/hora
  868. ScheduleBusinessRules::validateConflictingSchedule(
  869. $provider_id,
  870. $date_ymd,
  871. $startTime,
  872. $endTime
  873. );
  874. // bloqueio provider tem outra proposta para o mesmo agendamento
  875. ScheduleBusinessRules::validateConflictingSameProposal(
  876. $provider_id,
  877. $schedule->id
  878. );
  879. // bloqueio provider tem outra proposta na mesma data
  880. ScheduleBusinessRules::validateConflictingProposalSameDate(
  881. $provider_id,
  882. $date_ymd,
  883. $startTime,
  884. $endTime,
  885. $schedule->id
  886. );
  887. // bloqueio caso o client tenha bloqueado o provider
  888. ScheduleBusinessRules::validateClientNotBlockedByProvider(
  889. $client_id,
  890. $provider_id
  891. );
  892. // bloqueio caso o provider tenha bloqueado o client
  893. ScheduleBusinessRules::validateProviderNotBlockedByClient(
  894. $client_id,
  895. $provider_id
  896. );
  897. return true;
  898. }
  899. }