CustomScheduleService.php 22 KB

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