CustomScheduleService.php 17 KB

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