CustomScheduleService.php 23 KB

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