CustomScheduleService.php 31 KB

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