CustomScheduleService.php 21 KB

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