CustomScheduleService.php 27 KB

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