CustomScheduleService.php 23 KB

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