CustomScheduleService.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  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. $availableOpportunities = $opportunities->filter(function ($opportunity) use ($providerId) {
  266. try {
  267. return $this->checkProviderAvailability($providerId, $opportunity);
  268. } catch (\Exception $e) {
  269. return false;
  270. }
  271. });
  272. $availableOpportunities->each(function ($opportunity) use ($providerAddress) {
  273. $opportunity->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
  274. $providerAddress?->latitude !== null ? (float) $providerAddress->latitude : null,
  275. $providerAddress?->longitude !== null ? (float) $providerAddress->longitude : null,
  276. $providerAddress?->zip_code,
  277. $opportunity->address?->latitude !== null ? (float) $opportunity->address->latitude : null,
  278. $opportunity->address?->longitude !== null ? (float) $opportunity->address->longitude : null,
  279. $opportunity->address?->zip_code,
  280. );
  281. $photoPath = $opportunity->client->profileMedia?->path;
  282. $opportunity->customer_photo = $photoPath
  283. ? Storage::temporaryUrl($photoPath, now()->addMinutes(60))
  284. : null;
  285. });
  286. return $availableOpportunities->values();
  287. }
  288. public function getOpportunityProposals($scheduleId)
  289. {
  290. return ScheduleProposal::with(['provider.user'])
  291. ->where('schedule_id', $scheduleId)
  292. ->orderBy('created_at', 'desc')
  293. ->get();
  294. }
  295. public function getProvidersProposalsAndOpportunities($providerId)
  296. {
  297. $proposals = $this->getProviderProposals($providerId);
  298. $opportunities = $this->formatCustomSchedules($this->getAvailableOpportunities($providerId));
  299. return [
  300. 'proposals' => $proposals,
  301. 'opportunities' => $opportunities,
  302. ];
  303. }
  304. public function getProviderProposals($providerId)
  305. {
  306. return ScheduleProposal::with([
  307. 'schedule.client.user',
  308. 'schedule.address',
  309. 'schedule.address.city',
  310. 'schedule.address.state',
  311. 'schedule.customSchedule.serviceType',
  312. 'schedule.customSchedule.specialities',
  313. 'schedule.provider.user',
  314. ])
  315. ->where('provider_id', $providerId)
  316. ->orderBy('created_at', 'desc')
  317. ->get();
  318. }
  319. public function getSchedulesCustomGroupedByClient()
  320. {
  321. $schedules = Schedule::with(['client.user', 'provider.user', 'address', 'customSchedule.serviceType', 'customSchedule.specialities', 'reviews.reviewsImprovements.improvementType'])
  322. ->orderBy('id', 'desc')
  323. ->where('schedule_type', 'custom')
  324. ->get();
  325. $grouped = $this->formatCustomSchedules($schedules);
  326. return $grouped;
  327. }
  328. //
  329. public function proposeOpportunity($scheduleId, $providerId)
  330. {
  331. $schedule = Schedule::findOrFail($scheduleId);
  332. if ($schedule->provider_id) {
  333. throw new \Exception(__('validation.custom.opportunity.already_assigned'));
  334. }
  335. $existingProposal = ScheduleProposal::where('schedule_id', $scheduleId)
  336. ->where('provider_id', $providerId)
  337. ->first();
  338. if ($existingProposal) {
  339. throw new \Exception(__('validation.custom.opportunity.proposal_already_sent'));
  340. }
  341. $wasRefused = ScheduleRefuse::where('schedule_id', $scheduleId)
  342. ->where('provider_id', $providerId)
  343. ->exists();
  344. if ($wasRefused) {
  345. throw new \Exception(__('validation.custom.opportunity.provider_refused'));
  346. }
  347. $this->checkProviderAvailability($providerId, $schedule);
  348. $provider = Provider::with([
  349. 'user'
  350. ])->findOrFail($providerId);
  351. $schedule->load([
  352. 'client.user'
  353. ]);
  354. $notificationService = app(NotificationService::class);
  355. $notificationService->create([
  356. 'title' => __('notifications.new_proposal_title'),
  357. 'description' => __('notifications.new_proposal_description', ['provider' => $provider->user->name]),
  358. 'origin' => 'schedule',
  359. 'origin_id' => $schedule->id,
  360. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_NEW_SOLICITATION->value,
  361. 'user_id' => $schedule->client->user_id,
  362. ]);
  363. $this->sendProposalReceivedPush($schedule, $provider->user->name);
  364. return ScheduleProposal::create([
  365. 'schedule_id' => $scheduleId,
  366. 'provider_id' => $providerId,
  367. ]);
  368. }
  369. private function sendProposalReceivedPush(Schedule $schedule, string $providerName): void
  370. {
  371. $user = $schedule->client->user;
  372. if (! $user) {
  373. Log::warning('Push de proposta ignorada: cliente sem usuário', [
  374. 'schedule_id' => $schedule->id,
  375. ]);
  376. return;
  377. }
  378. try {
  379. app(PushNotificationService::class)->sendToUser(
  380. $user,
  381. new PrestadorAceitouPush($providerName, isProposal: true)
  382. );
  383. } catch (\Throwable $exception) {
  384. Log::error('Falha ao enviar push de nova proposta sob medida', [
  385. 'schedule_id' => $schedule->id,
  386. 'user_id' => $user->id,
  387. 'error' => $exception->getMessage(),
  388. ]);
  389. }
  390. }
  391. public function refuseOpportunity($scheduleId, $providerId)
  392. {
  393. $schedule = Schedule::with(['client.user'])->findOrFail($scheduleId);
  394. $provider = Provider::with(['user'])->findOrFail($providerId);
  395. $schedule_refuse = ScheduleRefuse::create([
  396. 'schedule_id' => $scheduleId,
  397. 'provider_id' => $providerId,
  398. ]);
  399. $notificationService = app(NotificationService::class);
  400. $notificationService->create([
  401. 'title' => __('notifications.opportunity_refused_title'),
  402. 'description' => __('notifications.opportunity_refused_description', [
  403. 'provider' => $provider->user->name,
  404. ]),
  405. 'origin' => 'schedule',
  406. 'origin_id' => $scheduleId,
  407. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_REFUSED->value,
  408. 'user_id' => $schedule->client->user_id,
  409. ]);
  410. // Push notification
  411. if ($schedule->client?->user) {
  412. try {
  413. app(PushNotificationService::class)->sendToUser(
  414. $schedule->client->user,
  415. new PrestadorRecusouPush(
  416. $provider->user->name
  417. )
  418. );
  419. } catch (\Throwable $exception) {
  420. Log::error('Falha ao enviar push de recusa da oportunidade', [
  421. 'schedule_id' => $schedule->id,
  422. 'provider_id' => $providerId,
  423. 'user_id' => $schedule->client->user->id,
  424. 'error' => $exception->getMessage(),
  425. ]);
  426. }
  427. }
  428. return $schedule_refuse;
  429. }
  430. //
  431. public function acceptProposal($proposalId)
  432. {
  433. return DB::transaction(function () use ($proposalId) {
  434. $proposal = ScheduleProposal::findOrFail($proposalId);
  435. $schedule = $proposal->schedule;
  436. if ($schedule->provider_id) {
  437. throw new \Exception(__('validation.custom.opportunity.already_assigned'));
  438. }
  439. $provider = Provider::find($proposal->provider_id);
  440. $schedule->total_amount = $this->resolveProposalAmount($schedule, $provider);
  441. $schedule->save();
  442. $schedule->update([
  443. 'provider_id' => $proposal->provider_id,
  444. ]);
  445. $schedule->refresh();
  446. $schedule->load(['provider.user', 'client.user']);
  447. $notificationService = app(NotificationService::class);
  448. $notificationService->create([
  449. 'title' => __('notifications.proposal_accepted_title'),
  450. 'description' => __('notifications.proposal_accepted_description'),
  451. 'origin' => 'schedule',
  452. 'origin_id' => $schedule->id,
  453. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_PROPOSAL_ACCEPTED->value,
  454. 'user_id' => $provider->user_id,
  455. ]);
  456. try {
  457. app(PushNotificationService::class)->sendToUser(
  458. $provider->user,
  459. new ClienteAceitouPush($schedule->client->user->name)
  460. );
  461. } catch (\Throwable $exception) {
  462. Log::error('Falha ao enviar push de cliente aceitou proposta', [
  463. 'schedule_id' => $schedule->id,
  464. 'provider_id' => $provider->id,
  465. 'error' => $exception->getMessage(),
  466. ]);
  467. }
  468. app(ScheduleService::class)->updateStatus($schedule->id, 'accepted');
  469. ScheduleProposal::where('schedule_id', $schedule->id)
  470. ->where('id', '!=', $proposalId)
  471. ->delete();
  472. $servicePackage = ServicePackage::create([
  473. 'client_id' => $schedule->client_id,
  474. 'provider_id' => $schedule->provider_id,
  475. ]);
  476. $servicePackage->items()->create([
  477. 'schedule_id' => $schedule->id,
  478. ]);
  479. return $servicePackage->fresh([
  480. 'items.schedule.client.user',
  481. 'items.schedule.provider.user',
  482. 'items.schedule.address',
  483. 'provider.user',
  484. ]);
  485. });
  486. }
  487. public function resolveProposalAmount(Schedule $schedule, Provider $provider): float
  488. {
  489. switch ($schedule->period_type) {
  490. case '8':
  491. return (float) $provider->daily_price_8h;
  492. case '6':
  493. return (float) $provider->daily_price_6h;
  494. case '4':
  495. return (float) $provider->daily_price_4h;
  496. case '2':
  497. return (float) $provider->daily_price_2h;
  498. default:
  499. throw new \Exception(__('messages.invalid_schedule_period'));
  500. }
  501. }
  502. public function refuseProposal($proposalId)
  503. {
  504. return DB::transaction(function () use ($proposalId) {
  505. $proposal = ScheduleProposal::findOrFail($proposalId);
  506. ScheduleRefuse::create([
  507. 'schedule_id' => $proposal->schedule_id,
  508. 'provider_id' => $proposal->provider_id,
  509. ]);
  510. $notificationService = app(NotificationService::class);
  511. $notificationService->create([
  512. 'title' => __('notifications.proposal_refused_title'),
  513. 'description' => __('notifications.proposal_refused_description'),
  514. 'origin' => 'schedule',
  515. 'origin_id' => $proposal->schedule_id,
  516. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_REFUSED->value,
  517. 'user_id' => $proposal->provider->user_id,
  518. ]);
  519. // Push notification
  520. if ($proposal->provider?->user) {
  521. try {
  522. app(PushNotificationService::class)->sendToUser(
  523. $proposal->provider->user,
  524. new ClienteRecusouPush(
  525. $proposal->schedule?->client?->user?->name
  526. )
  527. );
  528. } catch (\Throwable $exception) {
  529. Log::error('Falha ao enviar push de recusa da proposta', [
  530. 'proposal_id' => $proposal->id,
  531. 'schedule_id' => $proposal->schedule_id,
  532. 'provider_id' => $proposal->provider_id,
  533. 'user_id' => $proposal->provider->user->id,
  534. 'error' => $exception->getMessage(),
  535. ]);
  536. }
  537. }
  538. $proposal->delete();
  539. return true;
  540. });
  541. }
  542. //
  543. public function formatCustomSchedules($schedules)
  544. {
  545. $grouped = $schedules->groupBy('client_id')->map(function ($clientSchedules) {
  546. $firstSchedule = $clientSchedules->first();
  547. $clientPhotoPath = $firstSchedule->client->profileMedia?->path;
  548. return [
  549. 'client_id' => $firstSchedule->client_id,
  550. 'client_name' => $firstSchedule->client->user->name ?? 'N/A',
  551. 'customer_photo' => $clientPhotoPath
  552. ? Storage::temporaryUrl($clientPhotoPath, now()->addMinutes(60))
  553. : null,
  554. 'schedules' => $clientSchedules->map(function ($schedule) {
  555. $customSchedule = $schedule->customSchedule;
  556. return [
  557. 'id' => $schedule->id,
  558. 'date' => $schedule->date ? Carbon::parse($schedule->date)->format('d/m/Y') : null,
  559. 'start_time' => $schedule->start_time,
  560. 'end_time' => $schedule->end_time,
  561. 'period_type' => $schedule->period_type,
  562. 'status' => $schedule->status,
  563. 'total_amount' => $schedule->total_amount,
  564. 'code' => $schedule->code,
  565. 'code_verified' => $schedule->code_verified,
  566. 'provider_id' => $schedule->provider_id,
  567. 'client_id' => $schedule->client_id,
  568. 'provider_name' => $schedule->provider?->user->name ?? 'N/A',
  569. 'address' => $schedule->address ? [
  570. 'id' => $schedule->address->id,
  571. 'address' => $schedule->address->address,
  572. 'complement' => $schedule->address->complement,
  573. 'zip_code' => $schedule->address->zip_code,
  574. 'city' => $schedule->address->city->name ?? '',
  575. 'state' => $schedule->address->city->state->name ?? '',
  576. ] : null,
  577. 'client_name' => $schedule->client->user->name ?? 'N/A',
  578. 'custom_schedule' => $customSchedule ? [
  579. 'id' => $customSchedule->id,
  580. 'address_type' => $customSchedule->address_type,
  581. 'service_type_id' => $customSchedule->service_type_id,
  582. 'service_type_name' => $customSchedule->serviceType?->description ?? 'N/A',
  583. 'description' => $customSchedule->description,
  584. 'min_price' => $customSchedule->min_price,
  585. 'max_price' => $customSchedule->max_price,
  586. 'offers_meal' => $customSchedule->offers_meal,
  587. 'specialities' => $customSchedule->specialities->map(function ($speciality) {
  588. return [
  589. 'id' => $speciality->id,
  590. 'description' => $speciality->description,
  591. ];
  592. })->values(),
  593. ] : null,
  594. 'reviews' => $schedule->reviews->map(function ($review) {
  595. return [
  596. 'id' => $review->id,
  597. 'stars' => $review->stars,
  598. 'comment' => $review->comment,
  599. 'origin' => $review->origin,
  600. 'origin_id' => $review->origin_id,
  601. 'created_at' => Carbon::parse($review->created_at)->format('Y-m-d H:i'),
  602. 'updated_at' => Carbon::parse($review->updated_at)->format('Y-m-d H:i'),
  603. 'improvements' => $review->reviewsImprovements->map(function ($ri) {
  604. return [
  605. 'id' => $ri->id,
  606. 'improvement_type_id' => $ri->improvement_type_id,
  607. 'improvement_type_name' => $ri->improvementType ? $ri->improvementType->description : null,
  608. ];
  609. })->values(),
  610. ];
  611. }),
  612. ];
  613. })->values(),
  614. ];
  615. })->sortBy('id')->values();
  616. return $grouped;
  617. }
  618. public function verifyScheduleCode($scheduleId, $code)
  619. {
  620. $schedule = Schedule::findOrFail($scheduleId);
  621. if ($schedule->code_verified) {
  622. throw new \Exception(__('validation.custom.opportunity.code_already_verified'));
  623. }
  624. if ($schedule->code !== $code) {
  625. throw new \Exception(__('validation.custom.opportunity.invalid_code'));
  626. }
  627. $schedule->update([
  628. 'code_verified' => true,
  629. ]);
  630. return $schedule;
  631. }
  632. //
  633. private function checkProviderAvailability($providerId, $schedule)
  634. {
  635. $client_id = $schedule->client_id;
  636. $provider_id = $providerId;
  637. $date = Carbon::parse($schedule->date);
  638. $dayOfWeek = $date->dayOfWeek; // 0-6
  639. $startTime = $schedule->start_time;
  640. $endTime = $schedule->end_time;
  641. $date_ymd = $date->format('Y-m-d');
  642. $period = $startTime < '13:00:00' ? 'morning' : 'afternoon';
  643. $period_type = $schedule->period_type; // 2,4,6,8
  644. // bloqueio 2 schedules por semana para o mesmo client e provider
  645. ScheduleBusinessRules::validateWeeklyScheduleLimit(
  646. $client_id,
  647. $provider_id,
  648. $date_ymd
  649. );
  650. // bloqueio provider trabalha no dia/periodo
  651. ScheduleBusinessRules::validateWorkingDay(
  652. $provider_id,
  653. $dayOfWeek,
  654. $period
  655. );
  656. // bloqueio provider tem blockedday para dia/hora
  657. ScheduleBusinessRules::validateBlockedDay(
  658. $provider_id,
  659. $date_ymd,
  660. $startTime,
  661. $endTime
  662. );
  663. // bloqueio daily_price do provider esta fora do range min_price e max_price
  664. ScheduleBusinessRules::validatePricePeriod(
  665. $provider_id,
  666. $schedule->customSchedule->min_price,
  667. $schedule->customSchedule->max_price,
  668. $period_type
  669. );
  670. // bloqueio provider tem outro agendamento para dia/hora
  671. ScheduleBusinessRules::validateConflictingSchedule(
  672. $provider_id,
  673. $date_ymd,
  674. $startTime,
  675. $endTime
  676. );
  677. // bloqueio provider tem outra proposta para o mesmo agendamento
  678. ScheduleBusinessRules::validateConflictingSameProposal(
  679. $provider_id,
  680. $schedule->id
  681. );
  682. // bloqueio provider tem outra proposta na mesma data
  683. ScheduleBusinessRules::validateConflictingProposalSameDate(
  684. $provider_id,
  685. $date_ymd,
  686. $startTime,
  687. $endTime,
  688. $schedule->id
  689. );
  690. // bloqueio caso o client tenha bloqueado o provider
  691. ScheduleBusinessRules::validateClientNotBlockedByProvider(
  692. $client_id,
  693. $provider_id
  694. );
  695. // bloqueio caso o provider tenha bloqueado o client
  696. ScheduleBusinessRules::validateProviderNotBlockedByClient(
  697. $client_id,
  698. $provider_id
  699. );
  700. return true;
  701. }
  702. }