CustomScheduleService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. return CustomSchedule::with([
  32. 'schedule.client.user',
  33. 'schedule.address',
  34. 'serviceType',
  35. 'specialities.speciality'
  36. ])->findOrFail($id);
  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. $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('schedules.*')
  208. ->get();
  209. $availableOpportunities = $opportunities->filter(function ($opportunity) use ($providerId) {
  210. try {
  211. return $this->checkProviderAvailability($providerId, $opportunity);
  212. } catch (\Exception $e) {
  213. return false;
  214. }
  215. });
  216. return $availableOpportunities->values();
  217. }
  218. public function getProviderProposals($providerId)
  219. {
  220. return ScheduleProposal::with([
  221. 'schedule.client.user',
  222. 'schedule.address',
  223. 'schedule.address.city',
  224. 'schedule.address.state',
  225. 'schedule.customSchedule.serviceType',
  226. 'schedule.customSchedule.specialities',
  227. 'schedule.provider.user'
  228. ])
  229. ->where('provider_id', $providerId)
  230. ->orderBy('created_at', 'desc')
  231. ->get();
  232. }
  233. public function getOpportunityProposals($scheduleId)
  234. {
  235. return ScheduleProposal::with(['provider.user'])
  236. ->where('schedule_id', $scheduleId)
  237. ->orderBy('created_at', 'desc')
  238. ->get();
  239. }
  240. public function proposeOpportunity($scheduleId, $providerId)
  241. {
  242. $schedule = Schedule::findOrFail($scheduleId);
  243. if ($schedule->provider_id) {
  244. throw new \Exception(__('validation.custom.opportunity.already_assigned'));
  245. }
  246. $existingProposal = ScheduleProposal::where('schedule_id', $scheduleId)
  247. ->where('provider_id', $providerId)
  248. ->first();
  249. if ($existingProposal) {
  250. throw new \Exception(__('validation.custom.opportunity.proposal_already_sent'));
  251. }
  252. $wasRefused = ScheduleRefuse::where('schedule_id', $scheduleId)
  253. ->where('provider_id', $providerId)
  254. ->exists();
  255. if ($wasRefused) {
  256. throw new \Exception(__('validation.custom.opportunity.provider_refused'));
  257. }
  258. $this->checkProviderAvailability($providerId, $schedule);
  259. return ScheduleProposal::create([
  260. 'schedule_id' => $scheduleId,
  261. 'provider_id' => $providerId,
  262. ]);
  263. }
  264. public function acceptProposal($proposalId)
  265. {
  266. return DB::transaction(function () use ($proposalId) {
  267. $proposal = ScheduleProposal::findOrFail($proposalId);
  268. $schedule = $proposal->schedule;
  269. Log::info($schedule);
  270. if ($schedule->provider_id) {
  271. throw new \Exception(__('validation.custom.opportunity.already_assigned'));
  272. }
  273. Log::info('vrauu2');
  274. $provider = Provider::find($proposal->provider_id);
  275. switch ($schedule->period_type) {
  276. case '8':
  277. $baseAmount = $provider->daily_price_8h;
  278. break;
  279. case '6':
  280. $baseAmount = $provider->daily_price_6h;
  281. break;
  282. case '4':
  283. $baseAmount = $provider->daily_price_4h;
  284. break;
  285. case '2':
  286. $baseAmount = $provider->daily_price_2h;
  287. break;
  288. default:
  289. }
  290. $schedule->total_amount = $baseAmount;
  291. $schedule->save();
  292. $schedule->update([
  293. 'provider_id' => $proposal->provider_id,
  294. 'status' => 'accepted',
  295. ]);
  296. ScheduleProposal::where('schedule_id', $schedule->id)
  297. ->where('id', '!=', $proposalId)
  298. ->delete();
  299. return $schedule->fresh(['provider.user']);
  300. });
  301. }
  302. public function refuseProposal($proposalId)
  303. {
  304. return DB::transaction(function () use ($proposalId) {
  305. $proposal = ScheduleProposal::findOrFail($proposalId);
  306. ScheduleRefuse::create([
  307. 'schedule_id' => $proposal->schedule_id,
  308. 'provider_id' => $proposal->provider_id,
  309. ]);
  310. $proposal->delete();
  311. return true;
  312. });
  313. }
  314. private function checkProviderAvailability($providerId, $schedule)
  315. {
  316. $client_id = $schedule->client_id;
  317. $provider_id = $providerId;
  318. $date = Carbon::parse($schedule->date);
  319. $dayOfWeek = $date->dayOfWeek;//0-6
  320. $startTime = $schedule->start_time;
  321. $endTime = $schedule->end_time;
  322. $date_ymd = $date->format('Y-m-d');
  323. $period = $startTime < '13:00:00' ? 'morning' : 'afternoon';
  324. $period_type = $schedule->period_type;//2,4,6,8
  325. // bloqueio 2 schedules por semana para o mesmo client e provider
  326. ScheduleBusinessRules::validateWeeklyScheduleLimit(
  327. $client_id,
  328. $provider_id,
  329. $date_ymd
  330. );
  331. // bloqueio provider trabalha no dia/periodo
  332. ScheduleBusinessRules::validateWorkingDay(
  333. $provider_id,
  334. $dayOfWeek,
  335. $period
  336. );
  337. // bloqueio provider tem blockedday para dia/hora
  338. ScheduleBusinessRules::validateBlockedDay(
  339. $provider_id,
  340. $date_ymd,
  341. $startTime,
  342. $endTime
  343. );
  344. // bloqueio daily_price do provider esta fora do range min_price e max_price
  345. ScheduleBusinessRules::validatePricePeriod(
  346. $provider_id,
  347. $schedule->customSchedule->min_price,
  348. $schedule->customSchedule->max_price,
  349. $period_type
  350. );
  351. // bloqueio provider tem outro agendamento para dia/hora
  352. ScheduleBusinessRules::validateConflictingSchedule(
  353. $provider_id,
  354. $date_ymd,
  355. $startTime,
  356. $endTime
  357. );
  358. // bloqueio provider tem outra proposta para o mesmo agendamento
  359. ScheduleBusinessRules::validateConflictingSameProposal(
  360. $provider_id,
  361. $schedule->id
  362. );
  363. // bloqueio provider tem outra proposta na mesma data
  364. ScheduleBusinessRules::validateConflictingProposalSameDate(
  365. $provider_id,
  366. $date_ymd,
  367. $startTime,
  368. $endTime,
  369. $schedule->id
  370. );
  371. // bloqueio caso o client tenha bloqueado o provider
  372. ScheduleBusinessRules::validateClientNotBlockedByProvider(
  373. $client_id,
  374. $provider_id
  375. );
  376. // bloqueio caso o provider tenha bloqueado o client
  377. ScheduleBusinessRules::validateProviderNotBlockedByClient(
  378. $client_id,
  379. $provider_id
  380. );
  381. return true;
  382. }
  383. public function getProvidersProposalsAndOpportunities($providerId)
  384. {
  385. $proposals = $this->getProviderProposals($providerId);
  386. $opportunities = $this->formatCustomSchedules($this->getAvailableOpportunities($providerId));
  387. return [
  388. 'proposals' => $proposals,
  389. 'opportunities' => $opportunities,
  390. ];
  391. }
  392. public function formatCustomSchedules($schedules)
  393. {
  394. $grouped = $schedules->groupBy('client_id')->map(function ($clientSchedules) {
  395. $firstSchedule = $clientSchedules->first();
  396. return [
  397. 'client_id' => $firstSchedule->client_id,
  398. 'client_name' => $firstSchedule->client->user->name ?? 'N/A',
  399. 'schedules' => $clientSchedules->map(function ($schedule) {
  400. $customSchedule = $schedule->customSchedule;
  401. return [
  402. 'id' => $schedule->id,
  403. 'date' => $schedule->date ? Carbon::parse($schedule->date)->format('d/m/Y') : null,
  404. 'start_time' => $schedule->start_time,
  405. 'end_time' => $schedule->end_time,
  406. 'period_type' => $schedule->period_type,
  407. 'status' => $schedule->status,
  408. 'total_amount' => $schedule->total_amount,
  409. 'code' => $schedule->code,
  410. 'code_verified' => $schedule->code_verified,
  411. 'provider_id' => $schedule->provider_id,
  412. 'client_id' => $schedule->client_id,
  413. 'provider_name' => $schedule->provider?->user->name ?? 'N/A',
  414. 'address' => $schedule->address ? [
  415. 'id' => $schedule->address->id,
  416. 'address' => $schedule->address->address,
  417. 'complement' => $schedule->address->complement,
  418. 'zip_code' => $schedule->address->zip_code,
  419. 'city' => $schedule->address->city->name ?? '',
  420. 'state' => $schedule->address->city->state->name ?? '',
  421. ] : null,
  422. 'client_name' => $schedule->client->user->name ?? 'N/A',
  423. 'custom_schedule' => $customSchedule ? [
  424. 'id' => $customSchedule->id,
  425. 'address_type' => $customSchedule->address_type,
  426. 'service_type_id' => $customSchedule->service_type_id,
  427. 'service_type_name' => $customSchedule->serviceType?->description ?? 'N/A',
  428. 'description' => $customSchedule->description,
  429. 'min_price' => $customSchedule->min_price,
  430. 'max_price' => $customSchedule->max_price,
  431. 'offers_meal' => $customSchedule->offers_meal,
  432. 'specialities' => $customSchedule->specialities->map(function ($speciality) {
  433. return [
  434. 'id' => $speciality->id,
  435. 'description' => $speciality->description,
  436. ];
  437. })->values()
  438. ] : null,
  439. 'reviews' => $schedule->reviews->map(function ($review) {
  440. return [
  441. 'id' => $review->id,
  442. 'stars' => $review->stars,
  443. 'comment' => $review->comment,
  444. 'origin' => $review->origin,
  445. 'origin_id' => $review->origin_id,
  446. 'created_at' => Carbon::parse($review->created_at)->format('Y-m-d H:i'),
  447. 'updated_at' => Carbon::parse($review->updated_at)->format('Y-m-d H:i'),
  448. 'improvements' => $review->reviewsImprovements->map(function ($ri) {
  449. return [
  450. 'id' => $ri->id,
  451. 'improvement_type_id' => $ri->improvement_type_id,
  452. 'improvement_type_name' => $ri->improvementType ? $ri->improvementType->description : null,
  453. ];
  454. })->values(),
  455. ];
  456. })
  457. ];
  458. })->values()
  459. ];
  460. })->sortBy('id')->values();
  461. return $grouped;
  462. }
  463. public function verifyScheduleCode($scheduleId, $code)
  464. {
  465. $schedule = Schedule::findOrFail($scheduleId);
  466. if ($schedule->code_verified) {
  467. throw new \Exception(__('validation.custom.opportunity.code_already_verified'));
  468. }
  469. if ($schedule->code !== $code) {
  470. throw new \Exception(__('validation.custom.opportunity.invalid_code'));
  471. }
  472. $schedule->update([
  473. 'code_verified' => true,
  474. ]);
  475. return $schedule;
  476. }
  477. public function refuseOpportunity($scheduleId, $providerId)
  478. {
  479. $schedule_refuse = ScheduleRefuse::create([
  480. 'schedule_id' => $scheduleId,
  481. 'provider_id' => $providerId,
  482. ]);
  483. return $schedule_refuse;
  484. }
  485. }