CustomScheduleService.php 21 KB

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