CustomScheduleService.php 29 KB

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