StudentContractService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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\Http\UploadedFile;
  9. use Illuminate\Support\Arr;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\Storage;
  12. use Illuminate\Validation\ValidationException;
  13. class StudentContractService
  14. {
  15. private const FILE_ATTRIBUTES = [
  16. 'file_url',
  17. 'file_type',
  18. 'signed_file_url',
  19. 'signed_file_type',
  20. ];
  21. private const VERSION_ATTRIBUTES = [
  22. 'id',
  23. 'version',
  24. 'derived_from_contract_id',
  25. 'created_by_user_id',
  26. 'created_at',
  27. 'updated_at',
  28. 'deleted_at',
  29. ];
  30. public function getAll(int $unitId, ?int $studentId = null): Collection
  31. {
  32. return StudentContract::with([
  33. 'student' => fn ($query) => $query
  34. ->withTrashed()
  35. ->with(['city', 'state']),
  36. 'classPackageUnit',
  37. 'createdBy',
  38. ])
  39. ->latestVersion()
  40. ->where('unit_id', $unitId)
  41. ->when($studentId, fn ($q) => $q->where('student_id', $studentId))
  42. ->orderBy('created_at', 'desc')
  43. ->get();
  44. }
  45. public function findById(int $id): ?StudentContract
  46. {
  47. $contract = StudentContract::with(['student', 'classPackageUnit', 'createdBy'])->find($id);
  48. if (! $contract) {
  49. return null;
  50. }
  51. $this->loadVersionHistory($contract);
  52. return $contract;
  53. }
  54. public function create(array $data): StudentContract
  55. {
  56. if (! empty($data['due_day'])) {
  57. $data['recurring_day'] = (int) $data['due_day'];
  58. }
  59. unset($data['due_day']);
  60. $contract = StudentContract::create($data);
  61. $this->generateInstallments($contract);
  62. return $contract;
  63. }
  64. public function update(int $id, array $data, ?int $createdByUserId = null): ?StudentContract
  65. {
  66. if (! empty($data['due_day'])) {
  67. $data['recurring_day'] = (int) $data['due_day'];
  68. }
  69. unset($data['due_day']);
  70. return DB::transaction(function () use ($id, $data, $createdByUserId): ?StudentContract {
  71. $contract = StudentContract::query()->lockForUpdate()->find($id);
  72. if (! $contract) {
  73. return null;
  74. }
  75. $originalAttributes = $contract->getAttributes();
  76. $contract->fill($data);
  77. $dirty = Arr::except(
  78. $contract->getDirty(),
  79. array_merge(self::FILE_ATTRIBUTES, self::VERSION_ATTRIBUTES),
  80. );
  81. if ($dirty === []) {
  82. return $contract->refresh();
  83. }
  84. if ($contract->derivedVersions()->withTrashed()->lockForUpdate()->first()) {
  85. throw ValidationException::withMessages([
  86. 'contract' => __('validation.student_contract_old_version'),
  87. ]);
  88. }
  89. $submittedAttributes = array_keys($data);
  90. $copiedAttributes = Arr::except(
  91. $originalAttributes,
  92. array_merge(self::FILE_ATTRIBUTES, self::VERSION_ATTRIBUTES, $submittedAttributes),
  93. );
  94. $editedAttributes = Arr::only($contract->getAttributes(), $submittedAttributes);
  95. $newVersion = StudentContract::create(array_merge(
  96. $copiedAttributes,
  97. $editedAttributes,
  98. [
  99. 'version' => $contract->version + 1,
  100. 'derived_from_contract_id' => $contract->id,
  101. 'created_by_user_id' => $createdByUserId,
  102. ],
  103. ));
  104. StudentContractInstallment::where('student_contract_id', $contract->id)
  105. ->update(['student_contract_id' => $newVersion->id]);
  106. return $newVersion->fresh();
  107. });
  108. }
  109. public function delete(int $id): bool
  110. {
  111. $model = $this->findById($id);
  112. if (! $model) {
  113. return false;
  114. }
  115. if ($model->file_url) {
  116. Storage::delete($model->file_url);
  117. }
  118. if ($model->signed_file_url) {
  119. Storage::delete($model->signed_file_url);
  120. }
  121. return $model->delete();
  122. }
  123. //
  124. public function getFranchisorSummary(array $unitIds = []): array
  125. {
  126. $base = StudentContract::query()->latestVersion()
  127. ->when(! empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds));
  128. return [
  129. 'active' => (clone $base)->where('status', 'active')->count(),
  130. 'frozen' => (clone $base)->where('status', 'frozen')->count(),
  131. 'cancelled' => (clone $base)->where('status', 'cancelled')->count(),
  132. ];
  133. }
  134. public function getFranchisorByStatus(string $status, array $unitIds = []): Collection
  135. {
  136. return StudentContract::with(['student', 'unit', 'createdBy'])->latestVersion()
  137. ->where('status', $status)
  138. ->when(! empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds))
  139. ->orderBy('created_at', 'desc')
  140. ->get();
  141. }
  142. public function getInstallments(int $contractId): Collection
  143. {
  144. return StudentContractInstallment::where('student_contract_id', $contractId)
  145. ->where('status', 'pending')
  146. ->orderBy('due_date')
  147. ->orderBy('installment_number')
  148. ->get();
  149. }
  150. //
  151. public function attachFile(int $id, UploadedFile $file, bool $signed = false): ?StudentContract
  152. {
  153. $model = StudentContract::find($id);
  154. if (! $model) {
  155. return null;
  156. }
  157. $path = $file->store('student-media');
  158. StudentMedia::create([
  159. 'student_id' => $model->student_id,
  160. 'student_contract_id' => $model->id,
  161. 'url' => $path,
  162. 'file_type' => $file->getMimeType(),
  163. 'type' => $signed ? 'signed_contract' : 'contract',
  164. ]);
  165. $urlAttribute = $signed ? 'signed_file_url' : 'file_url';
  166. $typeAttribute = $signed ? 'signed_file_type' : 'file_type';
  167. $model->update([
  168. $urlAttribute => $path,
  169. $typeAttribute => $file->getMimeType(),
  170. ]);
  171. return $model->fresh();
  172. }
  173. //
  174. public function cancel(int $id, ?int $createdByUserId = null): ?StudentContract
  175. {
  176. return $this->update($id, ['status' => 'cancelled'], $createdByUserId);
  177. }
  178. public function freeze(int $id, int $months = 0, ?int $createdByUserId = null): ?StudentContract
  179. {
  180. return DB::transaction(function () use ($id, $months, $createdByUserId): ?StudentContract {
  181. $contract = $this->update($id, ['status' => 'frozen'], $createdByUserId);
  182. if (! $contract) {
  183. return null;
  184. }
  185. if ($months > 0) {
  186. StudentContractInstallment::where('student_contract_id', $contract->id)
  187. ->where('status', 'pending')
  188. ->get()
  189. ->each(function ($installment) use ($months) {
  190. $newDate = Carbon::parse($installment->due_date)->addMonths($months);
  191. $installment->update(['due_date' => $newDate->format('Y-m-d')]);
  192. });
  193. }
  194. return $contract->fresh();
  195. });
  196. }
  197. public function reactivate(int $id, ?int $createdByUserId = null): ?StudentContract
  198. {
  199. return $this->update($id, ['status' => 'active'], $createdByUserId);
  200. }
  201. //
  202. // monta o array de datas para n parcelas
  203. // primeira parcela usa exatamente firstdate, data escolhida pelo usuario
  204. // segunda parcela em diante usa recurringday avancando mes a mes a partir do mes da primeira
  205. // exemplo: firstdate=25/05/2026, recurringday=5, count=3
  206. // resultado: [25/05/2026, 05/06/2026, 05/07/2026]
  207. private function buildInstallmentDates(string $firstDate, int $recurringDay, int $count): array
  208. {
  209. $dates = [];
  210. $first = Carbon::createFromFormat('Y-m-d', $firstDate);
  211. $dates[] = $first->copy();
  212. $baseMonth = $first->copy()->startOfMonth();
  213. for ($i = 1; $i < $count; $i++) {
  214. $next = $baseMonth->copy()->addMonths($i);
  215. $day = min($recurringDay, $next->daysInMonth);
  216. $next->setDay($day);
  217. $dates[] = $next;
  218. }
  219. return $dates;
  220. }
  221. private function generateInstallments(StudentContract $contract): void
  222. {
  223. $recurringDay = $contract->recurring_day ?? 1;
  224. $rows = [];
  225. $now = now();
  226. // Matrícula
  227. if ($contract->tax_register && $contract->installments && $contract->enrollment_due_date) {
  228. $value = round($contract->tax_register / $contract->installments, 2);
  229. $dates = $this->buildInstallmentDates(
  230. $contract->enrollment_due_date->format('Y-m-d'),
  231. $recurringDay,
  232. $contract->installments,
  233. );
  234. foreach ($dates as $i => $date) {
  235. $rows[] = [
  236. 'student_contract_id' => $contract->id,
  237. 'unit_id' => $contract->unit_id,
  238. 'student_id' => $contract->student_id,
  239. 'type' => 'enrollment',
  240. 'history' => 'REF. MATRÍCULA',
  241. 'installment_number' => $i + 1,
  242. 'total_installments' => $contract->installments,
  243. 'value' => $value,
  244. 'paid_value' => 0,
  245. 'discount' => 0,
  246. 'fine' => 0,
  247. 'due_date' => $date->format('Y-m-d'),
  248. 'status' => 'pending',
  249. 'created_at' => $now,
  250. 'updated_at' => $now,
  251. ];
  252. }
  253. }
  254. // Pacote
  255. if ($contract->package_value && $contract->package_installments && $contract->package_due_date) {
  256. $value = round($contract->package_value / $contract->package_installments, 2);
  257. $dates = $this->buildInstallmentDates(
  258. $contract->package_due_date->format('Y-m-d'),
  259. $recurringDay,
  260. $contract->package_installments,
  261. );
  262. foreach ($dates as $i => $date) {
  263. $rows[] = [
  264. 'student_contract_id' => $contract->id,
  265. 'unit_id' => $contract->unit_id,
  266. 'student_id' => $contract->student_id,
  267. 'type' => 'package',
  268. 'history' => 'REF. PACOTE',
  269. 'installment_number' => $i + 1,
  270. 'total_installments' => $contract->package_installments,
  271. 'value' => $value,
  272. 'paid_value' => 0,
  273. 'discount' => 0,
  274. 'fine' => 0,
  275. 'due_date' => $date->format('Y-m-d'),
  276. 'status' => 'pending',
  277. 'created_at' => $now,
  278. 'updated_at' => $now,
  279. ];
  280. }
  281. }
  282. if (! empty($rows)) {
  283. // As parcelas são registradas/calculadas normalmente. A cobrança no Asaas
  284. // da franquia será reintroduzida no módulo Franchisee (conta própria por unidade).
  285. StudentContractInstallment::insert($rows);
  286. }
  287. }
  288. private function loadVersionHistory(StudentContract $contract): void
  289. {
  290. $root = $contract;
  291. while ($root->derived_from_contract_id !== null) {
  292. $parent = StudentContract::with('createdBy')->find($root->derived_from_contract_id);
  293. if (! $parent) {
  294. break;
  295. }
  296. $root = $parent;
  297. }
  298. $history = new Collection;
  299. $current = StudentContract::with('createdBy')->find($root->id);
  300. while ($current) {
  301. $current->loadMissing('createdBy');
  302. $history->push($current);
  303. $current = $current->derivedVersions()->with('createdBy')->first();
  304. }
  305. $contract->setRelation('versionHistory', $history->sortByDesc('version')->values());
  306. }
  307. }