ScheduleBusinessRules.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace App\Rules;
  3. use App\Models\Schedule;
  4. use Carbon\Carbon;
  5. class ScheduleBusinessRules
  6. {
  7. // Status que devem ser ignorados na validação de limite por semana
  8. private const EXCLUDED_STATUSES = ['cancelled', 'rejected'];
  9. /**
  10. * Valida se o prestador pode ter mais um agendamento com o cliente na semana
  11. * Limite: 2 agendamentos por semana (domingo a sábado)
  12. *
  13. * @param int $clientId
  14. * @param int $providerId
  15. * @param string $date (Y-m-d)
  16. * @param int|null $excludeScheduleId
  17. * @return bool
  18. * @throws \Exception
  19. */
  20. public static function validateWeeklyScheduleLimit($clientId, $providerId, $date, $excludeScheduleId = null)
  21. {
  22. $date = Carbon::parse($date);
  23. $weekStart = $date->copy()->startOfWeek(Carbon::SUNDAY);
  24. $weekEnd = $date->copy()->endOfWeek(Carbon::SATURDAY);
  25. $weeklySchedulesCount = Schedule::where('client_id', $clientId)
  26. ->where('provider_id', $providerId)
  27. ->whereNotIn('status', self::EXCLUDED_STATUSES)
  28. ->whereBetween('date', [$weekStart->format('Y-m-d'), $weekEnd->format('Y-m-d')])
  29. ->when($excludeScheduleId, function ($query) use ($excludeScheduleId) {
  30. $query->where('id', '!=', $excludeScheduleId);
  31. })
  32. ->count();
  33. if ($weeklySchedulesCount >= 2) {
  34. throw new \Exception(__('validation.custom.schedule.weekly_limit_exceeded'));
  35. }
  36. return true;
  37. }
  38. }