CustomScheduleService.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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\Rules\ScheduleBusinessRules;
  13. use App\Services\NotificationService;
  14. use App\Services\DistanceService;
  15. use Carbon\Carbon;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Log;
  18. use Illuminate\Support\Facades\Storage;
  19. class CustomScheduleService
  20. {
  21. private const NEARBY_RADIUS_KM = 20.0;
  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. $providerCityId = $providerAddress?->city_id;
  200. $providerLat = $providerAddress?->latitude !== null ? (float) $providerAddress->latitude : null;
  201. $providerLng = $providerAddress?->longitude !== null ? (float) $providerAddress->longitude : null;
  202. $opportunities = Schedule::with([
  203. 'client.user',
  204. 'client.profileMedia',
  205. 'address:id,district,zip_code,latitude,longitude',
  206. 'customSchedule.serviceType',
  207. 'customSchedule.specialities',
  208. ])
  209. ->leftJoin('schedule_refuses', function ($join) use ($providerId) {
  210. $join->on('schedules.id', '=', 'schedule_refuses.schedule_id')
  211. ->where('schedule_refuses.provider_id', $providerId);
  212. })
  213. ->leftJoin('addresses as opportunity_address', 'opportunity_address.id', '=', 'schedules.address_id')
  214. ->whereNull('schedule_refuses.id')
  215. ->where('schedules.schedule_type', 'custom')
  216. ->where('schedules.status', 'pending')
  217. ->whereNull('schedules.provider_id')
  218. ->whereDate('schedules.date', '>=', now()->toDateString())
  219. ->where(function ($query) use ($providerCityId, $providerLat, $providerLng) {
  220. if ($providerCityId !== null) {
  221. $query->where('opportunity_address.city_id', $providerCityId);
  222. }
  223. if ($providerLat !== null && $providerLng !== null) {
  224. $method = $providerCityId !== null ? 'orWhereRaw' : 'whereRaw';
  225. $query->{$method}(
  226. DistanceService::withinRadiusSqlCondition(
  227. $providerLat,
  228. $providerLng,
  229. self::NEARBY_RADIUS_KM,
  230. 'opportunity_address.latitude',
  231. 'opportunity_address.longitude',
  232. )
  233. );
  234. return;
  235. }
  236. if ($providerCityId === null) {
  237. $query->whereRaw('1 = 0');
  238. }
  239. })
  240. ->select(
  241. 'schedules.id',
  242. 'schedules.client_id',
  243. 'schedules.address_id',
  244. 'schedules.date',
  245. 'schedules.period_type',
  246. 'schedules.start_time',
  247. 'schedules.end_time',
  248. 'schedules.total_amount',
  249. DB::raw("
  250. CASE
  251. WHEN schedules.period_type = '2' THEN {$provider->daily_price_2h}
  252. WHEN schedules.period_type = '4' THEN {$provider->daily_price_4h}
  253. WHEN schedules.period_type = '6' THEN {$provider->daily_price_6h}
  254. WHEN schedules.period_type = '8' THEN {$provider->daily_price_8h}
  255. ELSE 0
  256. END AS total_amount
  257. "),
  258. )
  259. ->get();
  260. $availableOpportunities = $opportunities->filter(function ($opportunity) use ($providerId) {
  261. try {
  262. return $this->checkProviderAvailability($providerId, $opportunity);
  263. } catch (\Exception $e) {
  264. return false;
  265. }
  266. });
  267. $availableOpportunities->each(function ($opportunity) use ($providerAddress) {
  268. $opportunity->distance_km = $this->zipCodeCoordinatesService->calculateDistance(
  269. $providerAddress?->latitude !== null ? (float) $providerAddress->latitude : null,
  270. $providerAddress?->longitude !== null ? (float) $providerAddress->longitude : null,
  271. $providerAddress?->zip_code,
  272. $opportunity->address?->latitude !== null ? (float) $opportunity->address->latitude : null,
  273. $opportunity->address?->longitude !== null ? (float) $opportunity->address->longitude : null,
  274. $opportunity->address?->zip_code,
  275. );
  276. $photoPath = $opportunity->client->profileMedia?->path;
  277. $opportunity->customer_photo = $photoPath
  278. ? Storage::temporaryUrl($photoPath, now()->addMinutes(60))
  279. : null;
  280. });
  281. return $availableOpportunities->values();
  282. }
  283. public function getOpportunityProposals($scheduleId)
  284. {
  285. return ScheduleProposal::with(['provider.user'])
  286. ->where('schedule_id', $scheduleId)
  287. ->orderBy('created_at', 'desc')
  288. ->get();
  289. }
  290. public function getProvidersProposalsAndOpportunities($providerId)
  291. {
  292. $proposals = $this->getProviderProposals($providerId);
  293. $opportunities = $this->formatCustomSchedules($this->getAvailableOpportunities($providerId));
  294. return [
  295. 'proposals' => $proposals,
  296. 'opportunities' => $opportunities,
  297. ];
  298. }
  299. public function getProviderProposals($providerId)
  300. {
  301. return ScheduleProposal::with([
  302. 'schedule.client.user',
  303. 'schedule.address',
  304. 'schedule.address.city',
  305. 'schedule.address.state',
  306. 'schedule.customSchedule.serviceType',
  307. 'schedule.customSchedule.specialities',
  308. 'schedule.provider.user',
  309. ])
  310. ->where('provider_id', $providerId)
  311. ->orderBy('created_at', 'desc')
  312. ->get();
  313. }
  314. public function getSchedulesCustomGroupedByClient()
  315. {
  316. $schedules = Schedule::with(['client.user', 'provider.user', 'address', 'customSchedule.serviceType', 'customSchedule.specialities', 'reviews.reviewsImprovements.improvementType'])
  317. ->orderBy('id', 'desc')
  318. ->where('schedule_type', 'custom')
  319. ->get();
  320. $grouped = $this->formatCustomSchedules($schedules);
  321. return $grouped;
  322. }
  323. //
  324. public function proposeOpportunity($scheduleId, $providerId)
  325. {
  326. $schedule = Schedule::findOrFail($scheduleId);
  327. if ($schedule->provider_id) {
  328. throw new \Exception(__('validation.custom.opportunity.already_assigned'));
  329. }
  330. $existingProposal = ScheduleProposal::where('schedule_id', $scheduleId)
  331. ->where('provider_id', $providerId)
  332. ->first();
  333. if ($existingProposal) {
  334. throw new \Exception(__('validation.custom.opportunity.proposal_already_sent'));
  335. }
  336. $wasRefused = ScheduleRefuse::where('schedule_id', $scheduleId)
  337. ->where('provider_id', $providerId)
  338. ->exists();
  339. if ($wasRefused) {
  340. throw new \Exception(__('validation.custom.opportunity.provider_refused'));
  341. }
  342. $this->checkProviderAvailability($providerId, $schedule);
  343. $provider = Provider::with([
  344. 'user'
  345. ])->findOrFail($providerId);
  346. $schedule->load([
  347. 'client.user'
  348. ]);
  349. $notificationService = app(NotificationService::class);
  350. $notificationService->create([
  351. 'title' => __('notifications.new_proposal_title'),
  352. 'description' => __('notifications.new_proposal_description', ['provider' => $provider->user->name]),
  353. 'origin' => 'schedule',
  354. 'origin_id' => $schedule->id,
  355. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_NEW_SOLICITATION->value,
  356. 'user_id' => $schedule->client->user_id,
  357. ]);
  358. return ScheduleProposal::create([
  359. 'schedule_id' => $scheduleId,
  360. 'provider_id' => $providerId,
  361. ]);
  362. }
  363. public function refuseOpportunity($scheduleId, $providerId)
  364. {
  365. $schedule = Schedule::with(['client.user'])->findOrFail($scheduleId);
  366. $provider = Provider::with(['user'])->findOrFail($providerId);
  367. $schedule_refuse = ScheduleRefuse::create([
  368. 'schedule_id' => $scheduleId,
  369. 'provider_id' => $providerId,
  370. ]);
  371. $notificationService = app(NotificationService::class);
  372. $notificationService->create([
  373. 'title' => __('notifications.opportunity_refused_title'),
  374. 'description' => __('notifications.opportunity_refused_description', ['provider' => $provider->user->name]),
  375. 'origin' => 'schedule',
  376. 'origin_id' => $scheduleId,
  377. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_REFUSED->value,
  378. 'user_id' => $schedule->client->user_id,
  379. ]);
  380. return $schedule_refuse;
  381. }
  382. //
  383. public function acceptProposal($proposalId)
  384. {
  385. return DB::transaction(function () use ($proposalId) {
  386. $proposal = ScheduleProposal::findOrFail($proposalId);
  387. $schedule = $proposal->schedule;
  388. if ($schedule->provider_id) {
  389. throw new \Exception(__('validation.custom.opportunity.already_assigned'));
  390. }
  391. $provider = Provider::find($proposal->provider_id);
  392. $schedule->total_amount = $this->resolveProposalAmount($schedule, $provider);
  393. $schedule->save();
  394. $schedule->update([
  395. 'provider_id' => $proposal->provider_id,
  396. ]);
  397. $schedule->refresh();
  398. $schedule->load(['provider.user', 'client.user']);
  399. $notificationService = app(NotificationService::class);
  400. $notificationService->create([
  401. 'title' => __('notifications.proposal_accepted_title'),
  402. 'description' => __('notifications.proposal_accepted_description'),
  403. 'origin' => 'schedule',
  404. 'origin_id' => $schedule->id,
  405. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_PROPOSAL_ACCEPTED->value,
  406. 'user_id' => $provider->user_id,
  407. ]);
  408. app(ScheduleService::class)->updateStatus($schedule->id, 'accepted');
  409. ScheduleProposal::where('schedule_id', $schedule->id)
  410. ->where('id', '!=', $proposalId)
  411. ->delete();
  412. $servicePackage = ServicePackage::create([
  413. 'client_id' => $schedule->client_id,
  414. 'provider_id' => $schedule->provider_id,
  415. ]);
  416. $servicePackage->items()->create([
  417. 'schedule_id' => $schedule->id,
  418. ]);
  419. return $servicePackage->fresh([
  420. 'items.schedule.client.user',
  421. 'items.schedule.provider.user',
  422. 'items.schedule.address',
  423. 'provider.user',
  424. ]);
  425. });
  426. }
  427. public function resolveProposalAmount(Schedule $schedule, Provider $provider): float
  428. {
  429. switch ($schedule->period_type) {
  430. case '8':
  431. return (float) $provider->daily_price_8h;
  432. case '6':
  433. return (float) $provider->daily_price_6h;
  434. case '4':
  435. return (float) $provider->daily_price_4h;
  436. case '2':
  437. return (float) $provider->daily_price_2h;
  438. default:
  439. throw new \Exception(__('messages.invalid_schedule_period'));
  440. }
  441. }
  442. public function refuseProposal($proposalId)
  443. {
  444. return DB::transaction(function () use ($proposalId) {
  445. $proposal = ScheduleProposal::findOrFail($proposalId);
  446. ScheduleRefuse::create([
  447. 'schedule_id' => $proposal->schedule_id,
  448. 'provider_id' => $proposal->provider_id,
  449. ]);
  450. $notificationService = app(NotificationService::class);
  451. $notificationService->create([
  452. 'title' => __('notifications.proposal_refused_title'),
  453. 'description' => __('notifications.proposal_refused_description'),
  454. 'origin' => 'schedule',
  455. 'origin_id' => $proposal->schedule_id,
  456. 'type' => NotificationTypeEnum::SCHEDULE_CLIENT_PROVIDER_REFUSED->value,
  457. 'user_id' => $proposal->provider->user_id,
  458. ]);
  459. $proposal->delete();
  460. return true;
  461. });
  462. }
  463. //
  464. public function formatCustomSchedules($schedules)
  465. {
  466. $grouped = $schedules->groupBy('client_id')->map(function ($clientSchedules) {
  467. $firstSchedule = $clientSchedules->first();
  468. $clientPhotoPath = $firstSchedule->client->profileMedia?->path;
  469. return [
  470. 'client_id' => $firstSchedule->client_id,
  471. 'client_name' => $firstSchedule->client->user->name ?? 'N/A',
  472. 'customer_photo' => $clientPhotoPath
  473. ? Storage::temporaryUrl($clientPhotoPath, now()->addMinutes(60))
  474. : null,
  475. 'schedules' => $clientSchedules->map(function ($schedule) {
  476. $customSchedule = $schedule->customSchedule;
  477. return [
  478. 'id' => $schedule->id,
  479. 'date' => $schedule->date ? Carbon::parse($schedule->date)->format('d/m/Y') : null,
  480. 'start_time' => $schedule->start_time,
  481. 'end_time' => $schedule->end_time,
  482. 'period_type' => $schedule->period_type,
  483. 'status' => $schedule->status,
  484. 'total_amount' => $schedule->total_amount,
  485. 'code' => $schedule->code,
  486. 'code_verified' => $schedule->code_verified,
  487. 'provider_id' => $schedule->provider_id,
  488. 'client_id' => $schedule->client_id,
  489. 'provider_name' => $schedule->provider?->user->name ?? 'N/A',
  490. 'address' => $schedule->address ? [
  491. 'id' => $schedule->address->id,
  492. 'address' => $schedule->address->address,
  493. 'complement' => $schedule->address->complement,
  494. 'zip_code' => $schedule->address->zip_code,
  495. 'city' => $schedule->address->city->name ?? '',
  496. 'state' => $schedule->address->city->state->name ?? '',
  497. ] : null,
  498. 'client_name' => $schedule->client->user->name ?? 'N/A',
  499. 'custom_schedule' => $customSchedule ? [
  500. 'id' => $customSchedule->id,
  501. 'address_type' => $customSchedule->address_type,
  502. 'service_type_id' => $customSchedule->service_type_id,
  503. 'service_type_name' => $customSchedule->serviceType?->description ?? 'N/A',
  504. 'description' => $customSchedule->description,
  505. 'min_price' => $customSchedule->min_price,
  506. 'max_price' => $customSchedule->max_price,
  507. 'offers_meal' => $customSchedule->offers_meal,
  508. 'specialities' => $customSchedule->specialities->map(function ($speciality) {
  509. return [
  510. 'id' => $speciality->id,
  511. 'description' => $speciality->description,
  512. ];
  513. })->values(),
  514. ] : null,
  515. 'reviews' => $schedule->reviews->map(function ($review) {
  516. return [
  517. 'id' => $review->id,
  518. 'stars' => $review->stars,
  519. 'comment' => $review->comment,
  520. 'origin' => $review->origin,
  521. 'origin_id' => $review->origin_id,
  522. 'created_at' => Carbon::parse($review->created_at)->format('Y-m-d H:i'),
  523. 'updated_at' => Carbon::parse($review->updated_at)->format('Y-m-d H:i'),
  524. 'improvements' => $review->reviewsImprovements->map(function ($ri) {
  525. return [
  526. 'id' => $ri->id,
  527. 'improvement_type_id' => $ri->improvement_type_id,
  528. 'improvement_type_name' => $ri->improvementType ? $ri->improvementType->description : null,
  529. ];
  530. })->values(),
  531. ];
  532. }),
  533. ];
  534. })->values(),
  535. ];
  536. })->sortBy('id')->values();
  537. return $grouped;
  538. }
  539. public function verifyScheduleCode($scheduleId, $code)
  540. {
  541. $schedule = Schedule::findOrFail($scheduleId);
  542. if ($schedule->code_verified) {
  543. throw new \Exception(__('validation.custom.opportunity.code_already_verified'));
  544. }
  545. if ($schedule->code !== $code) {
  546. throw new \Exception(__('validation.custom.opportunity.invalid_code'));
  547. }
  548. $schedule->update([
  549. 'code_verified' => true,
  550. ]);
  551. return $schedule;
  552. }
  553. //
  554. private function checkProviderAvailability($providerId, $schedule)
  555. {
  556. $client_id = $schedule->client_id;
  557. $provider_id = $providerId;
  558. $date = Carbon::parse($schedule->date);
  559. $dayOfWeek = $date->dayOfWeek; // 0-6
  560. $startTime = $schedule->start_time;
  561. $endTime = $schedule->end_time;
  562. $date_ymd = $date->format('Y-m-d');
  563. $period = $startTime < '13:00:00' ? 'morning' : 'afternoon';
  564. $period_type = $schedule->period_type; // 2,4,6,8
  565. // bloqueio 2 schedules por semana para o mesmo client e provider
  566. ScheduleBusinessRules::validateWeeklyScheduleLimit(
  567. $client_id,
  568. $provider_id,
  569. $date_ymd
  570. );
  571. // bloqueio provider trabalha no dia/periodo
  572. ScheduleBusinessRules::validateWorkingDay(
  573. $provider_id,
  574. $dayOfWeek,
  575. $period
  576. );
  577. // bloqueio provider tem blockedday para dia/hora
  578. ScheduleBusinessRules::validateBlockedDay(
  579. $provider_id,
  580. $date_ymd,
  581. $startTime,
  582. $endTime
  583. );
  584. // bloqueio daily_price do provider esta fora do range min_price e max_price
  585. ScheduleBusinessRules::validatePricePeriod(
  586. $provider_id,
  587. $schedule->customSchedule->min_price,
  588. $schedule->customSchedule->max_price,
  589. $period_type
  590. );
  591. // bloqueio provider tem outro agendamento para dia/hora
  592. ScheduleBusinessRules::validateConflictingSchedule(
  593. $provider_id,
  594. $date_ymd,
  595. $startTime,
  596. $endTime
  597. );
  598. // bloqueio provider tem outra proposta para o mesmo agendamento
  599. ScheduleBusinessRules::validateConflictingSameProposal(
  600. $provider_id,
  601. $schedule->id
  602. );
  603. // bloqueio provider tem outra proposta na mesma data
  604. ScheduleBusinessRules::validateConflictingProposalSameDate(
  605. $provider_id,
  606. $date_ymd,
  607. $startTime,
  608. $endTime,
  609. $schedule->id
  610. );
  611. // bloqueio caso o client tenha bloqueado o provider
  612. ScheduleBusinessRules::validateClientNotBlockedByProvider(
  613. $client_id,
  614. $provider_id
  615. );
  616. // bloqueio caso o provider tenha bloqueado o client
  617. ScheduleBusinessRules::validateProviderNotBlockedByClient(
  618. $client_id,
  619. $provider_id
  620. );
  621. return true;
  622. }
  623. }