StudentContractService.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. <?php
  2. namespace App\Services;
  3. use App\Models\StudentContract;
  4. use App\Models\StudentContractInstallment;
  5. use App\Models\StudentMedia;
  6. use Carbon\Carbon;
  7. use Illuminate\Database\Eloquent\Collection;
  8. use Illuminate\Support\Facades\Storage;
  9. class StudentContractService
  10. {
  11. public function getFranchisorSummary(array $unitIds = []): array
  12. {
  13. $base = StudentContract::query()
  14. ->when(!empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds));
  15. return [
  16. 'frozen' => (clone $base)->where('status', 'frozen')->count(),
  17. 'cancelled' => (clone $base)->where('status', 'cancelled')->count(),
  18. ];
  19. }
  20. public function getFranchisorByStatus(string $status, array $unitIds = []): Collection
  21. {
  22. return StudentContract::with(['student', 'unit'])
  23. ->where('status', $status)
  24. ->when(!empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds))
  25. ->orderBy('created_at', 'desc')
  26. ->get();
  27. }
  28. public function getAll(int $unitId, ?int $studentId = null): Collection
  29. {
  30. return StudentContract::with(['student.city', 'student.state', 'classPackageUnit'])
  31. ->where('unit_id', $unitId)
  32. ->when($studentId, fn ($q) => $q->where('student_id', $studentId))
  33. ->orderBy('created_at', 'desc')
  34. ->get();
  35. }
  36. public function findById(int $id): ?StudentContract
  37. {
  38. return StudentContract::with(['student', 'classPackageUnit'])->find($id);
  39. }
  40. public function create(array $data): StudentContract
  41. {
  42. if (!empty($data['due_day'])) {
  43. $data['recurring_day'] = (int) $data['due_day'];
  44. }
  45. unset($data['due_day']);
  46. $contract = StudentContract::create($data);
  47. $this->generateInstallments($contract);
  48. return $contract;
  49. }
  50. private function generateInstallments(StudentContract $contract): void
  51. {
  52. $recurringDay = $contract->recurring_day ?? 1;
  53. $rows = [];
  54. $now = now();
  55. // --- Matrícula ---
  56. if ($contract->tax_register && $contract->installments && $contract->enrollment_due_date) {
  57. $value = round($contract->tax_register / $contract->installments, 2);
  58. $dates = $this->buildInstallmentDates(
  59. $contract->enrollment_due_date->format('Y-m-d'),
  60. $recurringDay,
  61. $contract->installments,
  62. );
  63. foreach ($dates as $i => $date) {
  64. $rows[] = [
  65. 'student_contract_id' => $contract->id,
  66. 'unit_id' => $contract->unit_id,
  67. 'student_id' => $contract->student_id,
  68. 'type' => 'enrollment',
  69. 'history' => 'REF. MATRÍCULA',
  70. 'installment_number' => $i + 1,
  71. 'total_installments' => $contract->installments,
  72. 'value' => $value,
  73. 'paid_value' => 0,
  74. 'discount' => 0,
  75. 'fine' => 0,
  76. 'due_date' => $date->format('Y-m-d'),
  77. 'status' => 'pending',
  78. 'created_at' => $now,
  79. 'updated_at' => $now,
  80. ];
  81. }
  82. }
  83. // --- Pacote ---
  84. if ($contract->package_value && $contract->package_installments && $contract->package_due_date) {
  85. $value = round($contract->package_value / $contract->package_installments, 2);
  86. $dates = $this->buildInstallmentDates(
  87. $contract->package_due_date->format('Y-m-d'),
  88. $recurringDay,
  89. $contract->package_installments,
  90. );
  91. foreach ($dates as $i => $date) {
  92. $rows[] = [
  93. 'student_contract_id' => $contract->id,
  94. 'unit_id' => $contract->unit_id,
  95. 'student_id' => $contract->student_id,
  96. 'type' => 'package',
  97. 'history' => 'REF. PACOTE',
  98. 'installment_number' => $i + 1,
  99. 'total_installments' => $contract->package_installments,
  100. 'value' => $value,
  101. 'paid_value' => 0,
  102. 'discount' => 0,
  103. 'fine' => 0,
  104. 'due_date' => $date->format('Y-m-d'),
  105. 'status' => 'pending',
  106. 'created_at' => $now,
  107. 'updated_at' => $now,
  108. ];
  109. }
  110. }
  111. if (!empty($rows)) {
  112. StudentContractInstallment::insert($rows);
  113. }
  114. }
  115. /**
  116. * Monta o array de datas para N parcelas.
  117. *
  118. * - 1ª parcela: usa exatamente $firstDate (data escolhida pelo usuário)
  119. * - 2ª em diante: dia $recurringDay avançando mês a mês a partir do mês da 1ª
  120. *
  121. * Exemplo: firstDate=25/05/2026, recurringDay=5, count=3
  122. * → [25/05/2026, 05/06/2026, 05/07/2026]
  123. */
  124. private function buildInstallmentDates(string $firstDate, int $recurringDay, int $count): array
  125. {
  126. $dates = [];
  127. $first = Carbon::createFromFormat('Y-m-d', $firstDate);
  128. $dates[] = $first->copy();
  129. $baseMonth = $first->copy()->startOfMonth();
  130. for ($i = 1; $i < $count; $i++) {
  131. $next = $baseMonth->copy()->addMonths($i);
  132. $day = min($recurringDay, $next->daysInMonth);
  133. $next->setDay($day);
  134. $dates[] = $next;
  135. }
  136. return $dates;
  137. }
  138. public function update(int $id, array $data): ?StudentContract
  139. {
  140. $model = $this->findById($id);
  141. if (!$model) {
  142. return null;
  143. }
  144. if (!empty($data['due_day'])) {
  145. $data['recurring_day'] = (int) $data['due_day'];
  146. }
  147. unset($data['due_day']);
  148. $model->update($data);
  149. return $model->fresh();
  150. }
  151. public function attachFile(int $id, $file): ?StudentContract
  152. {
  153. $model = $this->findById($id);
  154. if (!$model) {
  155. return null;
  156. }
  157. /** @var \Illuminate\Http\UploadedFile $file */
  158. $path = $file->store('student-media');
  159. StudentMedia::create([
  160. 'student_id' => $model->student_id,
  161. 'student_contract_id' => $model->id,
  162. 'url' => $path,
  163. 'file_type' => $file->getMimeType(),
  164. 'type' => 'contract',
  165. ]);
  166. $model->update(['file_url' => Storage::url($path), 'file_type' => $file->getMimeType()]);
  167. return $model->fresh();
  168. }
  169. public function getInstallments(int $contractId): Collection
  170. {
  171. return StudentContractInstallment::where('student_contract_id', $contractId)
  172. ->where('status', 'pending')
  173. ->orderBy('due_date')
  174. ->orderBy('installment_number')
  175. ->get();
  176. }
  177. public function freeze(int $id, int $months = 0): ?StudentContract
  178. {
  179. $model = $this->findById($id);
  180. if (!$model) {
  181. return null;
  182. }
  183. if ($months > 0) {
  184. StudentContractInstallment::where('student_contract_id', $id)
  185. ->where('status', 'pending')
  186. ->get()
  187. ->each(function ($installment) use ($months) {
  188. $newDate = Carbon::parse($installment->due_date)->addMonths($months);
  189. $installment->update(['due_date' => $newDate->format('Y-m-d')]);
  190. });
  191. }
  192. $model->update(['status' => 'frozen']);
  193. return $model->fresh();
  194. }
  195. public function cancel(int $id): ?StudentContract
  196. {
  197. $model = $this->findById($id);
  198. if (!$model) {
  199. return null;
  200. }
  201. $model->update(['status' => 'cancelled']);
  202. return $model->fresh();
  203. }
  204. public function reactivate(int $id): ?StudentContract
  205. {
  206. $model = $this->findById($id);
  207. if (!$model) {
  208. return null;
  209. }
  210. $model->update(['status' => 'active']);
  211. return $model->fresh();
  212. }
  213. public function delete(int $id): bool
  214. {
  215. $model = $this->findById($id);
  216. if (!$model) {
  217. return false;
  218. }
  219. if ($model->file_url) {
  220. Storage::delete($model->file_url);
  221. }
  222. return $model->delete();
  223. }
  224. }