StudentContractService.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. // Dispatch Asaas sync for the generated installments
  115. $installments = StudentContractInstallment::where('student_contract_id', $contract->id)
  116. ->where('status', 'pending')
  117. ->get();
  118. foreach ($installments as $installment) {
  119. \App\Jobs\SyncStudentChargeJob::dispatch($installment->id);
  120. }
  121. }
  122. }
  123. /**
  124. * Monta o array de datas para N parcelas.
  125. *
  126. * - 1ª parcela: usa exatamente $firstDate (data escolhida pelo usuário)
  127. * - 2ª em diante: dia $recurringDay avançando mês a mês a partir do mês da 1ª
  128. *
  129. * Exemplo: firstDate=25/05/2026, recurringDay=5, count=3
  130. * → [25/05/2026, 05/06/2026, 05/07/2026]
  131. */
  132. private function buildInstallmentDates(string $firstDate, int $recurringDay, int $count): array
  133. {
  134. $dates = [];
  135. $first = Carbon::createFromFormat('Y-m-d', $firstDate);
  136. $dates[] = $first->copy();
  137. $baseMonth = $first->copy()->startOfMonth();
  138. for ($i = 1; $i < $count; $i++) {
  139. $next = $baseMonth->copy()->addMonths($i);
  140. $day = min($recurringDay, $next->daysInMonth);
  141. $next->setDay($day);
  142. $dates[] = $next;
  143. }
  144. return $dates;
  145. }
  146. public function update(int $id, array $data): ?StudentContract
  147. {
  148. $model = $this->findById($id);
  149. if (!$model) {
  150. return null;
  151. }
  152. if (!empty($data['due_day'])) {
  153. $data['recurring_day'] = (int) $data['due_day'];
  154. }
  155. unset($data['due_day']);
  156. $model->update($data);
  157. return $model->fresh();
  158. }
  159. public function attachFile(int $id, $file): ?StudentContract
  160. {
  161. $model = $this->findById($id);
  162. if (!$model) {
  163. return null;
  164. }
  165. /** @var \Illuminate\Http\UploadedFile $file */
  166. $path = $file->store('student-media');
  167. StudentMedia::create([
  168. 'student_id' => $model->student_id,
  169. 'student_contract_id' => $model->id,
  170. 'url' => $path,
  171. 'file_type' => $file->getMimeType(),
  172. 'type' => 'contract',
  173. ]);
  174. $model->update(['file_url' => Storage::url($path), 'file_type' => $file->getMimeType()]);
  175. return $model->fresh();
  176. }
  177. public function getInstallments(int $contractId): Collection
  178. {
  179. return StudentContractInstallment::where('student_contract_id', $contractId)
  180. ->where('status', 'pending')
  181. ->orderBy('due_date')
  182. ->orderBy('installment_number')
  183. ->get();
  184. }
  185. public function freeze(int $id, int $months = 0): ?StudentContract
  186. {
  187. $model = $this->findById($id);
  188. if (!$model) {
  189. return null;
  190. }
  191. if ($months > 0) {
  192. StudentContractInstallment::where('student_contract_id', $id)
  193. ->where('status', 'pending')
  194. ->get()
  195. ->each(function ($installment) use ($months) {
  196. $newDate = Carbon::parse($installment->due_date)->addMonths($months);
  197. $installment->update(['due_date' => $newDate->format('Y-m-d')]);
  198. });
  199. }
  200. $model->update(['status' => 'frozen']);
  201. return $model->fresh();
  202. }
  203. public function cancel(int $id): ?StudentContract
  204. {
  205. $model = $this->findById($id);
  206. if (!$model) {
  207. return null;
  208. }
  209. $model->update(['status' => 'cancelled']);
  210. return $model->fresh();
  211. }
  212. public function reactivate(int $id): ?StudentContract
  213. {
  214. $model = $this->findById($id);
  215. if (!$model) {
  216. return null;
  217. }
  218. $model->update(['status' => 'active']);
  219. return $model->fresh();
  220. }
  221. public function delete(int $id): bool
  222. {
  223. $model = $this->findById($id);
  224. if (!$model) {
  225. return false;
  226. }
  227. if ($model->file_url) {
  228. Storage::delete($model->file_url);
  229. }
  230. return $model->delete();
  231. }
  232. }