CustomScheduleService.php 39 KB

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