StudentContractService.php 8.6 KB

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