CustomScheduleService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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 getAll()
  16. {
  17. $custom_schedules = CustomSchedule::with([
  18. 'schedule.client.user',
  19. 'schedule.address',
  20. 'serviceType',
  21. 'specialities.speciality',
  22. ])
  23. ->orderBy('id', 'desc')
  24. ->get();
  25. return $custom_schedules;
  26. }
  27. public function getById($id)
  28. {
  29. $customSchedule = CustomSchedule::with([
  30. 'schedule.client.user',
  31. 'schedule.address',
  32. 'serviceType',
  33. 'specialities.speciality',
  34. ])->find($id);
  35. return $customSchedule;
  36. }
  37. public function create(array $data)
  38. {
  39. DB::beginTransaction();
  40. try {
  41. $quantity = $data['quantity'] ?? 1;
  42. $specialityIds = $data['speciality_ids'] ?? [];
  43. $createdCustomSchedules = [];
  44. for ($i = 0; $i < $quantity; $i++) {
  45. $scheduleData = [
  46. 'client_id' => $data['client_id'],
  47. 'provider_id' => null,
  48. 'address_id' => $data['address_id'],
  49. 'date' => $data['date'],
  50. 'period_type' => $data['period_type'],
  51. 'schedule_type' => 'custom',
  52. 'start_time' => $data['start_time'],
  53. 'end_time' => $data['end_time'],
  54. 'status' => 'pending',
  55. 'total_amount' => 0,
  56. 'code' => str_pad(random_int(0, 9999), 4, '0', STR_PAD_LEFT),
  57. 'code_verified' => false,
  58. ];
  59. $schedule = Schedule::create($scheduleData);
  60. $customScheduleData = [
  61. 'schedule_id' => $schedule->id,
  62. 'address_type' => $data['address_type'],
  63. 'service_type_id' => $data['service_type_id'],
  64. 'description' => $data['description'] ?? null,
  65. 'min_price' => $data['min_price'],
  66. 'max_price' => $data['max_price'],
  67. 'offers_meal' => $data['offers_meal'] ?? false,
  68. ];
  69. $customSchedule = CustomSchedule::create($customScheduleData);
  70. if (! empty($specialityIds)) {
  71. foreach ($specialityIds as $specialityId) {
  72. CustomScheduleSpeciality::create([
  73. 'custom_schedule_id' => $customSchedule->id,
  74. 'speciality_id' => $specialityId,
  75. ]);
  76. }
  77. }
  78. $createdCustomSchedules[] = $customSchedule->load([
  79. 'schedule.client.user',
  80. 'schedule.address',
  81. 'serviceType',
  82. 'specialities.speciality',
  83. ]);
  84. }
  85. DB::commit();
  86. return $createdCustomSchedules;
  87. } catch (\Exception $e) {
  88. DB::rollBack();
  89. Log::error('Error creating custom schedule: '.$e->getMessage());
  90. throw $e;
  91. }
  92. }
  93. public function update($id, array $data)
  94. {
  95. DB::beginTransaction();
  96. try {
  97. $customSchedule = CustomSchedule::findOrFail($id);
  98. $schedule = $customSchedule->schedule;
  99. $scheduleUpdateData = [];
  100. if (isset($data['address_id'])) {
  101. $scheduleUpdateData['address_id'] = $data['address_id'];
  102. }
  103. if (isset($data['date'])) {
  104. $scheduleUpdateData['date'] = $data['date'];
  105. }
  106. if (isset($data['period_type'])) {
  107. $scheduleUpdateData['period_type'] = $data['period_type'];
  108. }
  109. if (isset($data['start_time'])) {
  110. $scheduleUpdateData['start_time'] = $data['start_time'];
  111. }
  112. if (isset($data['end_time'])) {
  113. $scheduleUpdateData['end_time'] = $data['end_time'];
  114. }
  115. if (! empty($scheduleUpdateData)) {
  116. $schedule->update($scheduleUpdateData);
  117. }
  118. $customScheduleUpdateData = [];
  119. if (isset($data['address_type'])) {
  120. $customScheduleUpdateData['address_type'] = $data['address_type'];
  121. }
  122. if (isset($data['service_type_id'])) {
  123. $customScheduleUpdateData['service_type_id'] = $data['service_type_id'];
  124. }
  125. if (isset($data['description'])) {
  126. $customScheduleUpdateData['description'] = $data['description'];
  127. }
  128. if (isset($data['min_price'])) {
  129. $customScheduleUpdateData['min_price'] = $data['min_price'];
  130. }
  131. if (isset($data['max_price'])) {
  132. $customScheduleUpdateData['max_price'] = $data['max_price'];
  133. }
  134. if (isset($data['offers_meal'])) {
  135. $customScheduleUpdateData['offers_meal'] = $data['offers_meal'];
  136. }
  137. if (! empty($customScheduleUpdateData)) {
  138. $customSchedule->update($customScheduleUpdateData);
  139. }
  140. if (isset($data['speciality_ids'])) {
  141. $custom_schedule = CustomScheduleSpeciality::where('custom_schedule_id', $customSchedule->id);
  142. $custom_schedule->delete();
  143. foreach ($data['speciality_ids'] as $specialityId) {
  144. CustomScheduleSpeciality::create([
  145. 'custom_schedule_id' => $customSchedule->id,
  146. 'speciality_id' => $specialityId,
  147. ]);
  148. }
  149. }
  150. DB::commit();
  151. return $customSchedule->fresh([
  152. 'schedule.client.user',
  153. 'schedule.address',
  154. 'serviceType',
  155. 'specialities.speciality',
  156. ]);
  157. } catch (\Exception $e) {
  158. DB::rollBack();
  159. Log::error('Error updating custom schedule: '.$e->getMessage());
  160. throw $e;
  161. }
  162. }
  163. public function delete($id)
  164. {
  165. DB::beginTransaction();
  166. try {
  167. $customSchedule = CustomSchedule::findOrFail($id);
  168. $schedule = $customSchedule->schedule;
  169. CustomScheduleSpeciality::where('custom_schedule_id', $customSchedule->id)->delete();
  170. $customSchedule->delete();
  171. $schedule->delete();
  172. DB::commit();
  173. return $customSchedule;
  174. } catch (\Exception $e) {
  175. DB::rollBack();
  176. Log::error('Error deleting custom schedule: '.$e->getMessage());
  177. throw $e;
  178. }
  179. }
  180. public function getSchedulesCustomGroupedByClient()
  181. {
  182. $schedules = Schedule::with(['client.user', 'provider.user', 'address', 'customSchedule.serviceType', 'customSchedule.specialities', 'reviews.reviewsImprovements.improvementType'])
  183. ->orderBy('id', 'desc')
  184. ->where('schedule_type', 'custom')
  185. ->get();
  186. $grouped = $this->formatCustomSchedules($schedules);
  187. return $grouped;
  188. }
  189. public function getAvailableOpportunities($providerId)
  190. {
  191. $provider = Provider::find($providerId);
  192. $opportunities = Schedule::with([
  193. 'client.user',
  194. 'address',
  195. 'customSchedule.serviceType',
  196. 'customSchedule.specialities',
  197. ])
  198. ->leftJoin('schedule_refuses', function ($join) use ($providerId) {
  199. $join->on('schedules.id', '=', 'schedule_refuses.schedule_id')
  200. ->where('schedule_refuses.provider_id', $providerId);
  201. })
  202. ->whereNull('schedule_refuses.id')
  203. ->where('schedules.schedule_type', 'custom')
  204. ->where('schedules.status', 'pending')
  205. ->whereNull('schedules.provider_id')
  206. ->whereDate('schedules.date', '>=', now()->toDateString())
  207. ->select(
  208. 'schedules.id',
  209. 'schedules.client_id',
  210. 'schedules.address_id',
  211. 'schedules.date',
  212. 'schedules.period_type',
  213. 'schedules.start_time',
  214. 'schedules.end_time',
  215. 'schedules.total_amount',
  216. DB::raw("CASE
  217. WHEN schedules.period_type = '2' THEN {$provider->daily_price_2h}
  218. WHEN schedules.period_type = '4' THEN {$provider->daily_price_4h}
  219. WHEN schedules.period_type = '6' THEN {$provider->daily_price_6h}
  220. WHEN schedules.period_type = '8' THEN {$provider->daily_price_8h}
  221. ELSE 0
  222. END as total_amount"),
  223. )
  224. ->get();
  225. $availableOpportunities = $opportunities->filter(function ($opportunity) use ($providerId) {
  226. try {
  227. return $this->checkProviderAvailability($providerId, $opportunity);
  228. } catch (\Exception $e) {
  229. return false;
  230. }
  231. });
  232. return $availableOpportunities->values();
  233. }
  234. public function getProviderProposals($providerId)
  235. {
  236. return ScheduleProposal::with([
  237. 'schedule.client.user',
  238. 'schedule.address',
  239. 'schedule.address.city',
  240. 'schedule.address.state',
  241. 'schedule.customSchedule.serviceType',
  242. 'schedule.customSchedule.specialities',
  243. 'schedule.provider.user',
  244. ])
  245. ->where('provider_id', $providerId)
  246. ->orderBy('created_at', 'desc')
  247. ->get();
  248. }
  249. public function getOpportunityProposals($scheduleId)
  250. {
  251. return ScheduleProposal::with(['provider.user'])
  252. ->where('schedule_id', $scheduleId)
  253. ->orderBy('created_at', 'desc')
  254. ->get();
  255. }
  256. public function proposeOpportunity($scheduleId, $providerId)
  257. {
  258. $schedule = Schedule::findOrFail($scheduleId);
  259. if ($schedule->provider_id) {
  260. throw new \Exception(__('validation.custom.opportunity.already_assigned'));
  261. }
  262. $existingProposal = ScheduleProposal::where('schedule_id', $scheduleId)
  263. ->where('provider_id', $providerId)
  264. ->first();
  265. if ($existingProposal) {
  266. throw new \Exception(__('validation.custom.opportunity.proposal_already_sent'));
  267. }
  268. $wasRefused = ScheduleRefuse::where('schedule_id', $scheduleId)
  269. ->where('provider_id', $providerId)
  270. ->exists();
  271. if ($wasRefused) {
  272. throw new \Exception(__('validation.custom.opportunity.provider_refused'));
  273. }
  274. $this->checkProviderAvailability($providerId, $schedule);
  275. return ScheduleProposal::create([
  276. 'schedule_id' => $scheduleId,
  277. 'provider_id' => $providerId,
  278. ]);
  279. }
  280. public function acceptProposal($proposalId)
  281. {
  282. return DB::transaction(function () use ($proposalId) {
  283. $proposal = ScheduleProposal::findOrFail($proposalId);
  284. $schedule = $proposal->schedule;
  285. Log::info($schedule);
  286. if ($schedule->provider_id) {
  287. throw new \Exception(__('validation.custom.opportunity.already_assigned'));
  288. }
  289. Log::info('vrauu2');
  290. $provider = Provider::find($proposal->provider_id);
  291. switch ($schedule->period_type) {
  292. case '8':
  293. $baseAmount = $provider->daily_price_8h;
  294. break;
  295. case '6':
  296. $baseAmount = $provider->daily_price_6h;
  297. break;
  298. case '4':
  299. $baseAmount = $provider->daily_price_4h;
  300. break;
  301. case '2':
  302. $baseAmount = $provider->daily_price_2h;
  303. break;
  304. default:
  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. }