CustomScheduleService.php 34 KB

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