CustomScheduleService.php 29 KB

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