CustomScheduleService.php 23 KB

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