ScheduleBusinessRules.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. <?php
  2. namespace App\Rules;
  3. use App\Models\ClientProviderBlock;
  4. use App\Models\Provider;
  5. use App\Models\ProviderBlockedDay;
  6. use App\Models\ProviderClientBlock;
  7. use App\Models\ProviderWorkingDay;
  8. use App\Models\Schedule;
  9. use App\Models\ScheduleProposal;
  10. use Carbon\Carbon;
  11. use Illuminate\Support\Facades\Log;
  12. use Illuminate\Support\Collection;
  13. class ScheduleBusinessRules
  14. {
  15. // Status que devem ser ignorados na validação de limite por semana
  16. private const EXCLUDED_STATUSES = ['cancelled', 'rejected'];
  17. /**
  18. * Valida se o prestador pode ter mais um agendamento com o cliente na semana
  19. * Limite: 2 agendamentos por semana (domingo a sábado)
  20. * @param int $clientId
  21. * @param int $providerId
  22. * @param string $date (Y-m-d)
  23. * @param int|null $excludeScheduleId
  24. * @return bool
  25. * @throws \Exception
  26. */
  27. public static function validateWeeklyScheduleLimit($clientId, $providerId, $date, $excludeScheduleId = null)
  28. {
  29. $date = Carbon::parse($date);
  30. $weekStart = $date->copy()->startOfWeek(Carbon::SUNDAY);
  31. $weekEnd = $date->copy()->endOfWeek(Carbon::SATURDAY);
  32. $weeklySchedulesCount = Schedule::where('client_id', $clientId)
  33. ->where('provider_id', $providerId)
  34. ->whereNotIn('status', self::EXCLUDED_STATUSES)
  35. ->whereBetween('date', [$weekStart->format('Y-m-d'), $weekEnd->format('Y-m-d')])
  36. ->when($excludeScheduleId, function ($query) use ($excludeScheduleId) {
  37. $query->where('id', '!=', $excludeScheduleId);
  38. })
  39. ->count();
  40. if ($weeklySchedulesCount >= 2) {
  41. throw new \Exception(__('validation.custom.schedule.weekly_limit_exceeded'));
  42. }
  43. return true;
  44. }
  45. /**
  46. * Valida se o prestador tem horário de trabalho cadastrado para o dia da semana e período
  47. * @param int $provider_id
  48. * @param int $day_of_week (0 - domingo, 6 - sábado)
  49. * @param string $period ('morning' ou 'afternoon')
  50. * @return bool
  51. * @throws \Exception
  52. */
  53. public static function validateWorkingDay($provider_id, $day_of_week, $period)
  54. {
  55. $workingDay = ProviderWorkingDay::where('provider_id', $provider_id)
  56. ->where('day', $day_of_week)
  57. ->where('period', $period)
  58. ->first();
  59. if(!$workingDay) {
  60. throw new \Exception(__('validation.custom.schedule.provider_not_working'));
  61. }
  62. return true;
  63. }
  64. /**
  65. * Valida se o prestador tem bloqueio cadastrado para o dia e horário
  66. * @param int $provider_id
  67. * @param string $date_ymd (Y-m-d)
  68. * @param string $start_time (H:i:s)
  69. * @param string $end_time (H:i:s)
  70. * @return bool
  71. * @throws \Exception
  72. */
  73. public static function validateBlockedDay($provider_id, $date_ymd, $start_time, $end_time)
  74. {
  75. $blockedDay = ProviderBlockedDay::where('provider_id', $provider_id)
  76. ->where('date', $date_ymd)
  77. ->where(function ($query) use ($start_time, $end_time) {
  78. $query->where('period', 'full')
  79. ->orWhere(function ($q) use ($start_time, $end_time) {
  80. $q->where('period', 'partial')
  81. ->where(function ($q2) use ($start_time, $end_time) {
  82. $q2->whereBetween('init_hour', [$start_time, $end_time])
  83. ->orWhereBetween('end_hour', [$start_time, $end_time])
  84. ->orWhere(function ($q3) use ($start_time, $end_time) {
  85. $q3->where('init_hour', '<=', $start_time)
  86. ->where('end_hour', '>=', $end_time);
  87. });
  88. });
  89. });
  90. })
  91. ->first();
  92. if ($blockedDay) {
  93. throw new \Exception(__('validation.custom.schedule.provider_blocked'));
  94. }
  95. return true;
  96. }
  97. public static function validatePricePeriod($provider_id, $min_price, $max_price, $period_type)
  98. {
  99. if ($min_price < 0 || $max_price < 0) {
  100. throw new \Exception(__('validation.custom.schedule.invalid_price'));
  101. }
  102. if ($min_price > $max_price) {
  103. throw new \Exception(__('validation.custom.schedule.invalid_price_range'));
  104. }
  105. $provider = Provider::find($provider_id);
  106. $provider_price_period = 0;
  107. switch ($period_type):
  108. case '2': //2 horas
  109. $provider_price_period = $provider->daily_price_2h;
  110. break;
  111. case '4': //4 horas
  112. $provider_price_period = $provider->daily_price_4h;
  113. break;
  114. case '6': //6 horas
  115. $provider_price_period = $provider->daily_price_6h;
  116. break;
  117. case '8': //8 horas
  118. $provider_price_period = $provider->daily_price_8h;
  119. break;
  120. default:
  121. throw new \Exception(__('validation.custom.schedule.invalid_period_type'));
  122. endswitch;
  123. if ($provider_price_period < $min_price || $provider_price_period > $max_price) {
  124. throw new \Exception(__('validation.custom.schedule.price_not_in_range'));
  125. }
  126. return true;
  127. }
  128. /**
  129. * Valida se o prestador tem outro agendamento no mesmo dia e horário
  130. * @param int $provider_id
  131. * @param string $date_ymd (Y-m-d)
  132. * @param string $start_time (H:i:s)
  133. * @param string $end_time (H:i:s)
  134. * @param int|null $exclude_schedule_id (id do agendamento a ser excluído da validação, usado para edição de agendamento)
  135. * @return bool
  136. * @throws \Exception
  137. */
  138. public static function validateConflictingSchedule($provider_id, $date_ymd, $start_time, $end_time, $exclude_schedule_id = null)
  139. {
  140. $conflictingSchedule = Schedule::where('provider_id', $provider_id)
  141. ->where('date', $date_ymd)
  142. ->whereIn('status', ['pending', 'accepted', 'paid', 'started'])
  143. ->where(function ($query) use ($start_time, $end_time) {
  144. $query->whereBetween('start_time', [$start_time, $end_time])
  145. ->orWhereBetween('end_time', [$start_time, $end_time])
  146. ->orWhere(function ($q) use ($start_time, $end_time) {
  147. $q->where('start_time', '<=', $start_time)
  148. ->where('end_time', '>=', $end_time);
  149. });
  150. })
  151. ->when($exclude_schedule_id, function ($query) use ($exclude_schedule_id) {
  152. $query->where('id', '!=', $exclude_schedule_id);
  153. })
  154. ->first();
  155. if ($conflictingSchedule) {
  156. throw new \Exception(__('validation.custom.schedule.provider_conflicting_schedule'));
  157. }
  158. return true;
  159. }
  160. /**
  161. * Valida se o prestador tem outro agendamento com o mesmo cliente no mesmo dia e horário
  162. * @param int $provider_id
  163. * @param string $date_ymd (Y-m-d)
  164. * @param string $start_time (H:i:s)
  165. * @param string $end_time (H:i:s)
  166. * @param int|null $exclude_schedule_id (id do agendamento a ser excluído da validação, usado para edição de agendamento)
  167. * @return bool
  168. * @throws \Exception
  169. */
  170. public static function validateConflictingSameProposal($provider_id, $schedule_id)
  171. {
  172. $conflictingSameProposal = ScheduleProposal::where('schedule_proposals.provider_id', $provider_id)
  173. ->where('schedule_proposals.schedule_id', $schedule_id)
  174. ->leftJoin('schedules', 'schedule_proposals.schedule_id', '=', 'schedules.id')
  175. ->whereNotIn('schedules.status', self::EXCLUDED_STATUSES)
  176. ->first();
  177. if ($conflictingSameProposal) {
  178. throw new \Exception(__('validation.custom.schedule.provider_conflicting_same_proposal'));
  179. }
  180. return true;
  181. }
  182. /**
  183. * Valida se o prestador tem outro agendamento com o mesmo cliente no mesmo dia e horário, ignorando o horário
  184. * @param int $provider_id
  185. * @param string $date_ymd (Y-m-d)
  186. * @param string $start_time (H:i:s)
  187. * @param string $end_time (H:i:s)
  188. * @param int|null $exclude_schedule_id (id do agendamento a ser excluído da validação, usado para edição de agendamento)
  189. * @return bool
  190. * @throws \Exception
  191. */
  192. public static function validateConflictingProposalSameDate($provider_id, $date_ymd, $start_time, $end_time, $exclude_schedule_id = null)
  193. {
  194. $conflictingProposalSameDate = ScheduleProposal::where('schedule_proposals.provider_id', $provider_id)
  195. ->leftJoin('schedules', 'schedule_proposals.schedule_id', '=', 'schedules.id')
  196. ->where('schedules.date', $date_ymd)
  197. ->where(function ($query) use ($start_time, $end_time) {
  198. $query->whereBetween('schedules.start_time', [$start_time, $end_time])
  199. ->orWhereBetween('schedules.end_time', [$start_time, $end_time])
  200. ->orWhere(function ($q) use ($start_time, $end_time) {
  201. $q->where('schedules.start_time', '<=', $start_time)
  202. ->where('schedules.end_time', '>=', $end_time);
  203. });
  204. })
  205. ->whereNotIn('status', self::EXCLUDED_STATUSES)
  206. ->when($exclude_schedule_id, function ($query) use ($exclude_schedule_id) {
  207. $query->where('schedules.id', '!=', $exclude_schedule_id);
  208. })
  209. ->first();
  210. if ($conflictingProposalSameDate) {
  211. throw new \Exception(__('validation.custom.schedule.provider_conflicting_proposal_same_date'));
  212. }
  213. return true;
  214. }
  215. /**
  216. * Valida se o cliente tem bloqueio cadastrado para o prestador
  217. * @param int $client_id
  218. * @param int $provider_id
  219. * @return bool
  220. * @throws \Exception
  221. */
  222. public static function validateClientNotBlockedByProvider($client_id, $provider_id)
  223. {
  224. $provider_client_block = ProviderClientBlock::where('provider_id', $provider_id)
  225. ->where('client_id', $client_id)
  226. ->first();
  227. if ($provider_client_block) {
  228. throw new \Exception(__('validation.custom.schedule.client_blocked_by_provider'));
  229. }
  230. return true;
  231. }
  232. /**
  233. * Valida se o prestador tem bloqueio cadastrado para o cliente
  234. * @param int $client_id
  235. * @param int $provider_id
  236. * @return bool
  237. * @throws \Exception
  238. */
  239. public static function validateProviderNotBlockedByClient($client_id, $provider_id)
  240. {
  241. $client_provider_block = ClientProviderBlock::where('provider_id', $provider_id)
  242. ->where('client_id', $client_id)
  243. ->first();
  244. if ($client_provider_block) {
  245. throw new \Exception(__('validation.custom.schedule.provider_blocked_by_client'));
  246. }
  247. return true;
  248. }
  249. // -------------------------------------------------------------------------
  250. // Métodos de consulta em batch — usados para filtragem em listagens.
  251. // Não lançam exceção: retornam coleções de IDs para uso em whereIn/whereNotIn.
  252. // -------------------------------------------------------------------------
  253. /**
  254. * Retorna os IDs de prestadores que bloquearam o cliente OU foram bloqueados por ele.
  255. * Centraliza ambas as direções de bloqueio em um único método para uso em listagens.
  256. *
  257. * @param int $client_id
  258. * @return Collection
  259. */
  260. public static function getBlockedProviderIdsForClient(int $client_id): Collection
  261. {
  262. // Prestadores que bloquearam este cliente (ProviderClientBlock)
  263. $blockedByProvider = ProviderClientBlock::where('client_id', $client_id)
  264. ->pluck('provider_id');
  265. // Prestadores que este cliente bloqueou (ClientProviderBlock)
  266. $blockedByClient = ClientProviderBlock::where('client_id', $client_id)
  267. ->pluck('provider_id');
  268. return $blockedByProvider->merge($blockedByClient)->unique()->values();
  269. }
  270. /**
  271. * Retorna os IDs de prestadores que possuem pelo menos um dia de trabalho cadastrado.
  272. * Garante que apenas prestadores ativos na plataforma apareçam em listagens.
  273. *
  274. * @return Collection
  275. */
  276. public static function getProviderIdsWithWorkingDays(): Collection
  277. {
  278. return ProviderWorkingDay::select('provider_id')
  279. ->distinct()
  280. ->pluck('provider_id');
  281. }
  282. /**
  283. * Retorna os IDs de prestadores disponíveis em uma data específica,
  284. * dentro de um conjunto pré-filtrado de IDs.
  285. *
  286. * Regras (em batch, sem iteração PHP):
  287. * 1. Prestador tem pelo menos um ProviderWorkingDay para o day_of_week da data.
  288. * 2. Prestador NÃO tem ProviderBlockedDay com period = 'all' nessa data.
  289. * (period = 'morning' ou 'afternoon' = bloqueio parcial → ainda disponível)
  290. *
  291. * @param string $date_ymd Y-m-d
  292. * @param Collection $providerIds conjunto de IDs a filtrar
  293. * @return Collection
  294. */
  295. public static function getAvailableProviderIdsForDate(string $date_ymd, Collection $providerIds): Collection
  296. {
  297. $dayOfWeek = Carbon::parse($date_ymd)->dayOfWeek;
  298. $withWorkingDay = ProviderWorkingDay::whereIn('provider_id', $providerIds)
  299. ->where('day', $dayOfWeek)
  300. ->pluck('provider_id')
  301. ->unique();
  302. $fullyBlockedIds = ProviderBlockedDay::whereIn('provider_id', $withWorkingDay)
  303. ->where('date', $date_ymd)
  304. ->where('period', 'all')
  305. ->pluck('provider_id')
  306. ->unique();
  307. return $withWorkingDay->diff($fullyBlockedIds)->values();
  308. }
  309. }