StudentContractRequest.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. <?php
  2. namespace App\Http\Requests;
  3. use App\Models\StudentContract;
  4. use App\Rules\StudentContractVariationConsistency;
  5. use Carbon\CarbonImmutable;
  6. use Illuminate\Foundation\Http\FormRequest;
  7. use Illuminate\Validation\Validator;
  8. class StudentContractRequest extends FormRequest
  9. {
  10. public function rules(): array
  11. {
  12. // aluno e pacote sao obrigatorios apenas no cadastro
  13. $required = $this->isMethod('POST') ? 'required' : 'sometimes';
  14. return [
  15. 'student_id' => "$required|exists:students,id",
  16. 'protocol' => 'sometimes|nullable|string|max:255',
  17. 'signature_date' => 'sometimes|nullable|date_format:Y-m-d',
  18. 'end_date' => 'sometimes|nullable|date_format:Y-m-d',
  19. 'class_package_unit_id' => "$required|exists:class_package_units,id",
  20. 'class_package_unit_variation_id' => 'sometimes|nullable|integer|min:1',
  21. 'class_quantity' => 'sometimes|nullable|integer|min:1',
  22. 'weekday' => 'sometimes|nullable|integer|min:0|max:6',
  23. 'start_time' => 'sometimes|nullable|date_format:H:i',
  24. 'end_time' => 'sometimes|nullable|date_format:H:i',
  25. 'second_weekday' => 'sometimes|nullable|integer|min:0|max:6',
  26. 'second_start_time' => 'sometimes|nullable|date_format:H:i',
  27. 'second_end_time' => 'sometimes|nullable|date_format:H:i',
  28. 'due_day' => 'sometimes|nullable|integer|min:1|max:31',
  29. 'tax_register' => 'sometimes|nullable|numeric|min:0',
  30. 'installments' => 'sometimes|nullable|integer|min:1|max:60',
  31. 'enrollment_due_date' => 'sometimes|nullable|date_format:Y-m-d',
  32. 'package_value' => 'sometimes|nullable|numeric|min:0',
  33. 'package_installments' => 'sometimes|nullable|integer|min:1|max:60',
  34. 'package_due_date' => 'sometimes|nullable|date_format:Y-m-d',
  35. 'material_value' => 'sometimes|nullable|numeric|min:0',
  36. 'material_installments' => 'sometimes|nullable|integer|min:1|max:60',
  37. 'material_due_date' => 'sometimes|nullable|date_format:Y-m-d',
  38. 'early_payment_discount' => 'sometimes|nullable|numeric|min:0|max:100',
  39. 'interest_rate' => 'sometimes|nullable|numeric|min:0',
  40. 'payment_method' => 'sometimes|nullable|string|in:pix,credit_card,debit_card',
  41. 'fine_cancelled' => 'sometimes|nullable|numeric|min:0|max:100',
  42. ];
  43. }
  44. public function after(): array
  45. {
  46. return [
  47. function (Validator $validator): void {
  48. // o cadastro e a renovacao possuem limites de periodo diferentes
  49. if ($this->isMethod('POST')) {
  50. $this->validateCreationPeriod($validator);
  51. } else {
  52. $this->validateRenewalPeriod($validator);
  53. }
  54. $this->validateVariation($validator);
  55. },
  56. ];
  57. }
  58. private function validateCreationPeriod(Validator $validator): void
  59. {
  60. // na criacao o contrato pode durar no maximo um ano desde a assinatura
  61. if (
  62. ! $this->filled(['signature_date', 'end_date'])
  63. || $validator->errors()->hasAny(['signature_date', 'end_date'])
  64. ) {
  65. return;
  66. }
  67. $signatureDate = CarbonImmutable::createFromFormat('!Y-m-d', $this->string('signature_date')->toString());
  68. $endDate = CarbonImmutable::createFromFormat('!Y-m-d', $this->string('end_date')->toString());
  69. if ($endDate->greaterThan($signatureDate->addYearNoOverflow())) {
  70. $validator->errors()->add(
  71. 'end_date',
  72. __('validation.student_contract_max_duration'),
  73. );
  74. }
  75. }
  76. private function validateRenewalPeriod(Validator $validator): void
  77. {
  78. // a renovacao sempre considera os dados da versao atual do contrato
  79. $contract = $this->contractBeingUpdated();
  80. if (!$contract) {
  81. return;
  82. }
  83. // a data inicial fica imutavel depois que o contrato e criado
  84. if (
  85. $this->exists('signature_date')
  86. && !$validator->errors()->has('signature_date')
  87. && $this->input('signature_date') !== $contract->signature_date?->format('Y-m-d')
  88. ) {
  89. $validator->errors()->add(
  90. 'signature_date',
  91. __('validation.student_contract_signature_date_immutable'),
  92. );
  93. }
  94. // sem uma nova data final valida nao existe periodo para conferir
  95. if (!$this->exists('end_date') || $validator->errors()->has('end_date')) {
  96. return;
  97. }
  98. $currentEndDate = $contract->end_date?->toImmutable();
  99. $newEndDate = $this->filled('end_date')
  100. ? CarbonImmutable::createFromFormat('!Y-m-d', $this->string('end_date')->toString())
  101. : null;
  102. // a data final nunca pode diminuir nem ser removida
  103. if ($currentEndDate && (!$newEndDate || $newEndDate->lessThan($currentEndDate))) {
  104. $validator->errors()->add(
  105. 'end_date',
  106. __('validation.student_contract_end_date_cannot_decrease'),
  107. );
  108. return;
  109. }
  110. // reenviar a mesma data nao caracteriza uma renovacao
  111. if (
  112. (!$currentEndDate && !$newEndDate)
  113. || ($currentEndDate && $newEndDate && $newEndDate->equalTo($currentEndDate))
  114. ) {
  115. return;
  116. }
  117. // a renovacao pode avancar no maximo um ano a partir da data atual
  118. $maximumEndDate = CarbonImmutable::today()->addYearNoOverflow();
  119. if ($newEndDate?->greaterThan($maximumEndDate)) {
  120. $validator->errors()->add(
  121. 'end_date',
  122. __('validation.student_contract_renewal_max_end_date', [
  123. 'date' => $maximumEndDate->format('d/m/Y'),
  124. ]),
  125. );
  126. }
  127. }
  128. private function validateVariation(Validator $validator): void
  129. {
  130. // campos reprovados nas regras basicas nao entram na validacao cruzada
  131. $fields = [
  132. 'class_package_unit_id', 'class_package_unit_variation_id',
  133. 'tax_register', 'installments',
  134. 'package_value', 'package_installments',
  135. 'material_value', 'material_installments',
  136. ];
  137. if ($validator->errors()->hasAny($fields)) {
  138. return;
  139. }
  140. // na edicao os campos ausentes mantem o valor da versao atual
  141. $contract = $this->isMethod('POST') ? null : $this->contractBeingUpdated();
  142. $data = array_merge($contract?->getAttributes() ?? [], $this->all());
  143. $errors = $this->variationConsistencyRule()->errors($data);
  144. foreach ($errors as $field => $messages) {
  145. foreach ($messages as $message) {
  146. $validator->errors()->add($field, $message);
  147. }
  148. }
  149. }
  150. protected function variationConsistencyRule(): StudentContractVariationConsistency
  151. {
  152. return new StudentContractVariationConsistency;
  153. }
  154. protected function contractBeingUpdated(): ?StudentContract
  155. {
  156. // o id da rota identifica a versao usada como base para a edicao
  157. $contractId = $this->route('id');
  158. return is_numeric($contractId) ? StudentContract::find((int) $contractId) : null;
  159. }
  160. }