CustomScheduleService.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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. use App\Enums\NotificationTypeEnum;
  14. use App\Services\NotificationService;
  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. return ScheduleProposal::create([
  278. 'schedule_id' => $scheduleId,
  279. 'provider_id' => $providerId,
  280. ]);
  281. }
  282. public function acceptProposal($proposalId)
  283. {
  284. return DB::transaction(function () use ($proposalId) {
  285. $proposal = ScheduleProposal::findOrFail($proposalId);
  286. $schedule = $proposal->schedule;
  287. Log::info($schedule);
  288. if ($schedule->provider_id) {
  289. throw new \Exception(__('validation.custom.opportunity.already_assigned'));
  290. }
  291. Log::info('vrauu2');
  292. $provider = Provider::find($proposal->provider_id);
  293. switch ($schedule->period_type) {
  294. case '8':
  295. $baseAmount = $provider->daily_price_8h;
  296. break;
  297. case '6':
  298. $baseAmount = $provider->daily_price_6h;
  299. break;
  300. case '4':
  301. $baseAmount = $provider->daily_price_4h;
  302. break;
  303. case '2':
  304. $baseAmount = $provider->daily_price_2h;
  305. break;
  306. default:
  307. }
  308. $schedule->total_amount = $baseAmount;
  309. $schedule->save();
  310. $schedule->update([
  311. 'provider_id' => $proposal->provider_id,
  312. 'status' => 'accepted',
  313. ]);
  314. $notificationService = app(NotificationService::class);
  315. $notificationService->create([
  316. 'title' => 'Proposta aceita!',
  317. 'description' =>
  318. 'O cliente aceitou sua proposta de diária.',
  319. 'origin' => 'schedule',
  320. 'origin_id' => $schedule->id,
  321. 'type' => NotificationTypeEnum::SCHEDULE_PROVIDER_CLIENT_PROPOSAL_ACCEPTED->value,
  322. 'user_id' => $provider->user_id,
  323. ]);
  324. ScheduleProposal::where('schedule_id', $schedule->id)
  325. ->where('id', '!=', $proposalId)
  326. ->delete();
  327. return $schedule->fresh(['provider.user']);
  328. });
  329. }
  330. public function refuseProposal($proposalId)
  331. {
  332. return DB::transaction(function () use ($proposalId) {
  333. $proposal = ScheduleProposal::findOrFail($proposalId);
  334. ScheduleRefuse::create([
  335. 'schedule_id' => $proposal->schedule_id,
  336. 'provider_id' => $proposal->provider_id,
  337. ]);
  338. $proposal->delete();
  339. return true;
  340. });
  341. }
  342. private function checkProviderAvailability($providerId, $schedule)
  343. {
  344. $client_id = $schedule->client_id;
  345. $provider_id = $providerId;
  346. $date = Carbon::parse($schedule->date);
  347. $dayOfWeek = $date->dayOfWeek; // 0-6
  348. $startTime = $schedule->start_time;
  349. $endTime = $schedule->end_time;
  350. $date_ymd = $date->format('Y-m-d');
  351. $period = $startTime < '13:00:00' ? 'morning' : 'afternoon';
  352. $period_type = $schedule->period_type; // 2,4,6,8
  353. // bloqueio 2 schedules por semana para o mesmo client e provider
  354. ScheduleBusinessRules::validateWeeklyScheduleLimit(
  355. $client_id,
  356. $provider_id,
  357. $date_ymd
  358. );
  359. // bloqueio provider trabalha no dia/periodo
  360. ScheduleBusinessRules::validateWorkingDay(
  361. $provider_id,
  362. $dayOfWeek,
  363. $period
  364. );
  365. // bloqueio provider tem blockedday para dia/hora
  366. ScheduleBusinessRules::validateBlockedDay(
  367. $provider_id,
  368. $date_ymd,
  369. $startTime,
  370. $endTime
  371. );
  372. // bloqueio daily_price do provider esta fora do range min_price e max_price
  373. ScheduleBusinessRules::validatePricePeriod(
  374. $provider_id,
  375. $schedule->customSchedule->min_price,
  376. $schedule->customSchedule->max_price,
  377. $period_type
  378. );
  379. // bloqueio provider tem outro agendamento para dia/hora
  380. ScheduleBusinessRules::validateConflictingSchedule(
  381. $provider_id,
  382. $date_ymd,
  383. $startTime,
  384. $endTime
  385. );
  386. // bloqueio provider tem outra proposta para o mesmo agendamento
  387. ScheduleBusinessRules::validateConflictingSameProposal(
  388. $provider_id,
  389. $schedule->id
  390. );
  391. // bloqueio provider tem outra proposta na mesma data
  392. ScheduleBusinessRules::validateConflictingProposalSameDate(
  393. $provider_id,
  394. $date_ymd,
  395. $startTime,
  396. $endTime,
  397. $schedule->id
  398. );
  399. // bloqueio caso o client tenha bloqueado o provider
  400. ScheduleBusinessRules::validateClientNotBlockedByProvider(
  401. $client_id,
  402. $provider_id
  403. );
  404. // bloqueio caso o provider tenha bloqueado o client
  405. ScheduleBusinessRules::validateProviderNotBlockedByClient(
  406. $client_id,
  407. $provider_id
  408. );
  409. return true;
  410. }
  411. public function getProvidersProposalsAndOpportunities($providerId)
  412. {
  413. $proposals = $this->getProviderProposals($providerId);
  414. $opportunities = $this->formatCustomSchedules($this->getAvailableOpportunities($providerId));
  415. return [
  416. 'proposals' => $proposals,
  417. 'opportunities' => $opportunities,
  418. ];
  419. }
  420. public function formatCustomSchedules($schedules)
  421. {
  422. $grouped = $schedules->groupBy('client_id')->map(function ($clientSchedules) {
  423. $firstSchedule = $clientSchedules->first();
  424. return [
  425. 'client_id' => $firstSchedule->client_id,
  426. 'client_name' => $firstSchedule->client->user->name ?? 'N/A',
  427. 'schedules' => $clientSchedules->map(function ($schedule) {
  428. $customSchedule = $schedule->customSchedule;
  429. return [
  430. 'id' => $schedule->id,
  431. 'date' => $schedule->date ? Carbon::parse($schedule->date)->format('d/m/Y') : null,
  432. 'start_time' => $schedule->start_time,
  433. 'end_time' => $schedule->end_time,
  434. 'period_type' => $schedule->period_type,
  435. 'status' => $schedule->status,
  436. 'total_amount' => $schedule->total_amount,
  437. 'code' => $schedule->code,
  438. 'code_verified' => $schedule->code_verified,
  439. 'provider_id' => $schedule->provider_id,
  440. 'client_id' => $schedule->client_id,
  441. 'provider_name' => $schedule->provider?->user->name ?? 'N/A',
  442. 'address' => $schedule->address ? [
  443. 'id' => $schedule->address->id,
  444. 'address' => $schedule->address->address,
  445. 'complement' => $schedule->address->complement,
  446. 'zip_code' => $schedule->address->zip_code,
  447. 'city' => $schedule->address->city->name ?? '',
  448. 'state' => $schedule->address->city->state->name ?? '',
  449. ] : null,
  450. 'client_name' => $schedule->client->user->name ?? 'N/A',
  451. 'custom_schedule' => $customSchedule ? [
  452. 'id' => $customSchedule->id,
  453. 'address_type' => $customSchedule->address_type,
  454. 'service_type_id' => $customSchedule->service_type_id,
  455. 'service_type_name' => $customSchedule->serviceType?->description ?? 'N/A',
  456. 'description' => $customSchedule->description,
  457. 'min_price' => $customSchedule->min_price,
  458. 'max_price' => $customSchedule->max_price,
  459. 'offers_meal' => $customSchedule->offers_meal,
  460. 'specialities' => $customSchedule->specialities->map(function ($speciality) {
  461. return [
  462. 'id' => $speciality->id,
  463. 'description' => $speciality->description,
  464. ];
  465. })->values(),
  466. ] : null,
  467. 'reviews' => $schedule->reviews->map(function ($review) {
  468. return [
  469. 'id' => $review->id,
  470. 'stars' => $review->stars,
  471. 'comment' => $review->comment,
  472. 'origin' => $review->origin,
  473. 'origin_id' => $review->origin_id,
  474. 'created_at' => Carbon::parse($review->created_at)->format('Y-m-d H:i'),
  475. 'updated_at' => Carbon::parse($review->updated_at)->format('Y-m-d H:i'),
  476. 'improvements' => $review->reviewsImprovements->map(function ($ri) {
  477. return [
  478. 'id' => $ri->id,
  479. 'improvement_type_id' => $ri->improvement_type_id,
  480. 'improvement_type_name' => $ri->improvementType ? $ri->improvementType->description : null,
  481. ];
  482. })->values(),
  483. ];
  484. }),
  485. ];
  486. })->values(),
  487. ];
  488. })->sortBy('id')->values();
  489. return $grouped;
  490. }
  491. public function verifyScheduleCode($scheduleId, $code)
  492. {
  493. $schedule = Schedule::findOrFail($scheduleId);
  494. if ($schedule->code_verified) {
  495. throw new \Exception(__('validation.custom.opportunity.code_already_verified'));
  496. }
  497. if ($schedule->code !== $code) {
  498. throw new \Exception(__('validation.custom.opportunity.invalid_code'));
  499. }
  500. $schedule->update([
  501. 'code_verified' => true,
  502. ]);
  503. return $schedule;
  504. }
  505. public function refuseOpportunity($scheduleId, $providerId)
  506. {
  507. $schedule_refuse = ScheduleRefuse::create([
  508. 'schedule_id' => $scheduleId,
  509. 'provider_id' => $providerId,
  510. ]);
  511. return $schedule_refuse;
  512. }
  513. }