CustomScheduleService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. $startTime = $schedule->start_time;
  315. $endTime = $schedule->end_time;
  316. $dayOfWeek = $date->dayOfWeek;
  317. ScheduleBusinessRules::validateWeeklyScheduleLimit(
  318. $schedule->client_id,
  319. $providerId,
  320. $schedule->date
  321. );
  322. $startHour = (int) substr($startTime, 0, 2);
  323. $endHour = (int) substr($endTime, 0, 2);
  324. $periods = [];
  325. if ($startHour < 13) {
  326. $periods[] = 'morning';
  327. }
  328. if ($endHour >= 13 || ($startHour < 13 && $endHour > 12)) {
  329. $periods[] = 'afternoon';
  330. }
  331. foreach ($periods as $period) {
  332. $workingDay = ProviderWorkingDay::where('provider_id', $providerId)
  333. ->where('day', $dayOfWeek)
  334. ->where('period', $period)
  335. ->first();
  336. if (!$workingDay) {
  337. throw new \Exception(__('validation.custom.opportunity.provider_not_working'));
  338. }
  339. }
  340. $blockedDay = ProviderBlockedDay::where('provider_id', $providerId)
  341. ->where('date', $date->format('Y-m-d'))
  342. ->where(function ($query) use ($startTime, $endTime) {
  343. $query->where('period', 'full')
  344. ->orWhere(function ($q) use ($startTime, $endTime) {
  345. $q->where('period', 'partial')
  346. ->where(function ($q2) use ($startTime, $endTime) {
  347. $q2->whereBetween('init_hour', [$startTime, $endTime])
  348. ->orWhereBetween('end_hour', [$startTime, $endTime])
  349. ->orWhere(function ($q3) use ($startTime, $endTime) {
  350. $q3->where('init_hour', '<=', $startTime)
  351. ->where('end_hour', '>=', $endTime);
  352. });
  353. });
  354. });
  355. })
  356. ->first();
  357. if ($blockedDay) {
  358. throw new \Exception(__('validation.custom.opportunity.provider_blocked'));
  359. }
  360. $excluded_status = ['cancelled', 'rejected'];
  361. $conflictingSchedule = Schedule::where('provider_id', $providerId)
  362. ->where('date', $date->format('Y-m-d'))
  363. ->whereNotIn('status', $excluded_status)
  364. ->where(function ($query) use ($startTime, $endTime) {
  365. $query->whereBetween('start_time', [$startTime, $endTime])
  366. ->orWhereBetween('end_time', [$startTime, $endTime])
  367. ->orWhere(function ($q) use ($startTime, $endTime) {
  368. $q->where('start_time', '<=', $startTime)
  369. ->where('end_time', '>=', $endTime);
  370. });
  371. })
  372. ->first();
  373. if ($conflictingSchedule) {
  374. throw new \Exception(__('validation.custom.opportunity.schedule_conflict'));
  375. }
  376. return true;
  377. }
  378. public function getProvidersProposalsAndOpportunities($providerId)
  379. {
  380. $proposals = $this->getProviderProposals($providerId);
  381. $opportunities = $this->formatCustomSchedules($this->getAvailableOpportunities($providerId));
  382. return [
  383. 'proposals' => $proposals,
  384. 'opportunities' => $opportunities,
  385. ];
  386. }
  387. public function formatCustomSchedules($schedules)
  388. {
  389. $grouped = $schedules->groupBy('client_id')->map(function ($clientSchedules) {
  390. $firstSchedule = $clientSchedules->first();
  391. return [
  392. 'client_id' => $firstSchedule->client_id,
  393. 'client_name' => $firstSchedule->client->user->name ?? 'N/A',
  394. 'schedules' => $clientSchedules->map(function ($schedule) {
  395. $customSchedule = $schedule->customSchedule;
  396. return [
  397. 'id' => $schedule->id,
  398. 'date' => $schedule->date ? Carbon::parse($schedule->date)->format('d/m/Y') : null,
  399. 'start_time' => $schedule->start_time,
  400. 'end_time' => $schedule->end_time,
  401. 'period_type' => $schedule->period_type,
  402. 'status' => $schedule->status,
  403. 'total_amount' => $schedule->total_amount,
  404. 'code' => $schedule->code,
  405. 'code_verified' => $schedule->code_verified,
  406. 'provider_id' => $schedule->provider_id,
  407. 'provider_name' => $schedule->provider?->user->name ?? 'N/A',
  408. 'address' => $schedule->address ? [
  409. 'id' => $schedule->address->id,
  410. 'address' => $schedule->address->address,
  411. 'complement' => $schedule->address->complement,
  412. 'zip_code' => $schedule->address->zip_code,
  413. 'city' => $schedule->address->city->name ?? '',
  414. 'state' => $schedule->address->city->state->name ?? '',
  415. ] : null,
  416. 'client_name' => $schedule->client->user->name ?? 'N/A',
  417. 'custom_schedule' => $customSchedule ? [
  418. 'id' => $customSchedule->id,
  419. 'address_type' => $customSchedule->address_type,
  420. 'service_type_id' => $customSchedule->service_type_id,
  421. 'service_type_name' => $customSchedule->serviceType?->description ?? 'N/A',
  422. 'description' => $customSchedule->description,
  423. 'min_price' => $customSchedule->min_price,
  424. 'max_price' => $customSchedule->max_price,
  425. 'offers_meal' => $customSchedule->offers_meal,
  426. 'specialities' => $customSchedule->specialities->map(function ($speciality) {
  427. return [
  428. 'id' => $speciality->id,
  429. 'description' => $speciality->description,
  430. ];
  431. })->values()
  432. ] : null,
  433. ];
  434. })->values()
  435. ];
  436. })->sortBy('id')->values();
  437. return $grouped;
  438. }
  439. public function verifyScheduleCode($scheduleId, $code)
  440. {
  441. $schedule = Schedule::findOrFail($scheduleId);
  442. if ($schedule->code_verified) {
  443. throw new \Exception(__('validation.custom.opportunity.code_already_verified'));
  444. }
  445. if ($schedule->code !== $code) {
  446. throw new \Exception(__('validation.custom.opportunity.invalid_code'));
  447. }
  448. $schedule->update([
  449. 'code_verified' => true,
  450. ]);
  451. return $schedule;
  452. }
  453. public function refuseOpportunity($scheduleId, $providerId)
  454. {
  455. $schedule_refuse = ScheduleRefuse::create([
  456. 'schedule_id' => $scheduleId,
  457. 'provider_id' => $providerId,
  458. ]);
  459. return $schedule_refuse;
  460. }
  461. }