CustomScheduleService.php 23 KB

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