CustomScheduleService.php 16 KB

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