StudentContractService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. <?php
  2. namespace App\Services;
  3. use App\Models\StudentContract;
  4. use App\Models\StudentContractInstallment;
  5. use App\Models\StudentMedia;
  6. use App\Models\Unit;
  7. use Barryvdh\DomPDF\Facade\Pdf;
  8. use Carbon\Carbon;
  9. use Illuminate\Database\Eloquent\Collection;
  10. use Illuminate\Http\UploadedFile;
  11. use Illuminate\Support\Arr;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Storage;
  14. use Illuminate\Validation\ValidationException;
  15. class StudentContractService
  16. {
  17. private const FILE_ATTRIBUTES = [
  18. 'file_url',
  19. 'file_type',
  20. 'signed_file_url',
  21. 'signed_file_type',
  22. ];
  23. private const VERSION_ATTRIBUTES = [
  24. 'id',
  25. 'version',
  26. 'derived_from_contract_id',
  27. 'created_by_user_id',
  28. 'created_at',
  29. 'updated_at',
  30. 'deleted_at',
  31. ];
  32. public function getAll(int $unitId, ?int $studentId = null): Collection
  33. {
  34. return StudentContract::with([
  35. 'student' => fn ($query) => $query
  36. ->withTrashed()
  37. ->with(['city', 'state']),
  38. 'classPackageUnit',
  39. 'createdBy',
  40. ])
  41. ->latestVersion()
  42. ->where('unit_id', $unitId)
  43. ->when($studentId, fn ($q) => $q->where('student_id', $studentId))
  44. ->orderBy('created_at', 'desc')
  45. ->get();
  46. }
  47. public function findById(int $id): ?StudentContract
  48. {
  49. $contract = StudentContract::with(['student', 'classPackageUnit', 'createdBy'])->find($id);
  50. if (! $contract) {
  51. return null;
  52. }
  53. $this->loadVersionHistory($contract);
  54. return $contract;
  55. }
  56. public function generateNextProtocol(): string
  57. {
  58. $nextNumber = $this->getMaxProtocolNumber() + 1;
  59. return str_pad((string) $nextNumber, 6, '0', STR_PAD_LEFT);
  60. }
  61. public function getMaxProtocolNumber(): int
  62. {
  63. $driver = DB::connection()->getDriverName();
  64. if ($driver === 'pgsql') {
  65. $max = StudentContract::withTrashed()
  66. ->whereNotNull('protocol')
  67. ->whereRaw("protocol ~ '^[0-9]+$'")
  68. ->selectRaw("COALESCE(MAX(CAST(protocol AS BIGINT)), 0) as max_protocol")
  69. ->value('max_protocol');
  70. return (int) $max;
  71. }
  72. if ($driver === 'mysql') {
  73. $max = StudentContract::withTrashed()
  74. ->whereNotNull('protocol')
  75. ->whereRaw("protocol REGEXP '^[0-9]+$'")
  76. ->selectRaw("COALESCE(MAX(CAST(protocol AS UNSIGNED)), 0) as max_protocol")
  77. ->value('max_protocol');
  78. return (int) $max;
  79. }
  80. $max = StudentContract::withTrashed()
  81. ->whereNotNull('protocol')
  82. ->get(['protocol'])
  83. ->filter(fn ($contract) => ctype_digit((string) $contract->protocol))
  84. ->map(fn ($contract) => (int) $contract->protocol)
  85. ->max();
  86. return (int) ($max ?? 0);
  87. }
  88. public function create(array $data): StudentContract
  89. {
  90. if (! empty($data['due_day'])) {
  91. $data['recurring_day'] = (int) $data['due_day'];
  92. }
  93. unset($data['due_day']);
  94. $unitId = $data['unit_id'] ?? null;
  95. $isAutomatic = true;
  96. if ($unitId) {
  97. $unit = $this->findUnit($unitId);
  98. if ($unit && $unit->automatic_protocol === false) {
  99. $isAutomatic = false;
  100. }
  101. }
  102. if ($isAutomatic) {
  103. $data['protocol'] = $this->generateNextProtocol();
  104. }
  105. $data['status'] = 'pending';
  106. $contract = StudentContract::create($data);
  107. $this->generateInstallments($contract);
  108. return $contract;
  109. }
  110. protected function findUnit(int $unitId): ?Unit
  111. {
  112. return Unit::find($unitId);
  113. }
  114. public function update(int $id, array $data, ?int $createdByUserId = null): ?StudentContract
  115. {
  116. if (! empty($data['due_day'])) {
  117. $data['recurring_day'] = (int) $data['due_day'];
  118. }
  119. unset($data['due_day']);
  120. return DB::transaction(function () use ($id, $data, $createdByUserId): ?StudentContract {
  121. $contract = StudentContract::query()->lockForUpdate()->find($id);
  122. if (! $contract) {
  123. return null;
  124. }
  125. $originalAttributes = $contract->getAttributes();
  126. $contract->fill($data);
  127. $dirty = Arr::except(
  128. $contract->getDirty(),
  129. array_merge(self::FILE_ATTRIBUTES, self::VERSION_ATTRIBUTES),
  130. );
  131. if ($dirty === []) {
  132. return $contract->refresh();
  133. }
  134. if ($contract->derivedVersions()->withTrashed()->lockForUpdate()->first()) {
  135. throw ValidationException::withMessages([
  136. 'contract' => __('validation.student_contract_old_version'),
  137. ]);
  138. }
  139. $submittedAttributes = array_keys($data);
  140. $copiedAttributes = Arr::except(
  141. $originalAttributes,
  142. array_merge(self::FILE_ATTRIBUTES, self::VERSION_ATTRIBUTES, $submittedAttributes),
  143. );
  144. $editedAttributes = Arr::only($contract->getAttributes(), $submittedAttributes);
  145. $newVersion = StudentContract::create(array_merge(
  146. $copiedAttributes,
  147. $editedAttributes,
  148. [
  149. 'version' => $contract->version + 1,
  150. 'derived_from_contract_id' => $contract->id,
  151. 'created_by_user_id' => $createdByUserId,
  152. ],
  153. ));
  154. StudentContractInstallment::where('student_contract_id', $contract->id)
  155. ->update(['student_contract_id' => $newVersion->id]);
  156. return $newVersion->fresh();
  157. });
  158. }
  159. public function delete(int $id): bool
  160. {
  161. $model = $this->findById($id);
  162. if (! $model) {
  163. return false;
  164. }
  165. if ($model->file_url) {
  166. Storage::delete($model->file_url);
  167. }
  168. if ($model->signed_file_url) {
  169. Storage::delete($model->signed_file_url);
  170. }
  171. return $model->delete();
  172. }
  173. //
  174. public function getFranchisorSummary(array $unitIds = []): array
  175. {
  176. $base = StudentContract::query()->latestVersion()
  177. ->when(! empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds));
  178. return [
  179. 'active' => (clone $base)->where('status', 'active')->count(),
  180. 'frozen' => (clone $base)->where('status', 'frozen')->count(),
  181. 'cancelled' => (clone $base)->where('status', 'cancelled')->count(),
  182. ];
  183. }
  184. public function getFranchisorByStatus(string $status, array $unitIds = []): Collection
  185. {
  186. return StudentContract::with(['student', 'unit', 'createdBy'])->latestVersion()
  187. ->where('status', $status)
  188. ->when(! empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds))
  189. ->orderBy('created_at', 'desc')
  190. ->get();
  191. }
  192. public function getInstallments(int $contractId): Collection
  193. {
  194. return StudentContractInstallment::where('student_contract_id', $contractId)
  195. ->where('status', 'pending')
  196. ->orderBy('due_date')
  197. ->orderBy('installment_number')
  198. ->get();
  199. }
  200. //
  201. public function attachFile(int $id, UploadedFile $file, bool $signed = false): ?StudentContract
  202. {
  203. $model = StudentContract::find($id);
  204. if (! $model) {
  205. return null;
  206. }
  207. $path = $file->store('student-media');
  208. StudentMedia::create([
  209. 'student_id' => $model->student_id,
  210. 'student_contract_id' => $model->id,
  211. 'url' => $path,
  212. 'file_type' => $file->getMimeType(),
  213. 'type' => $signed ? 'signed_contract' : 'contract',
  214. ]);
  215. $urlAttribute = $signed ? 'signed_file_url' : 'file_url';
  216. $typeAttribute = $signed ? 'signed_file_type' : 'file_type';
  217. $model->update([
  218. $urlAttribute => $path,
  219. $typeAttribute => $file->getMimeType(),
  220. ]);
  221. return $model->fresh();
  222. }
  223. public function generateFile(int $id): ?StudentContract
  224. {
  225. return DB::transaction(function () use ($id): ?StudentContract {
  226. $model = StudentContract::query()->lockForUpdate()->find($id);
  227. if (! $model || $model->file_url) {
  228. return $model?->fresh();
  229. }
  230. $model->load([
  231. 'classPackageUnit.pavaoProposalUnit',
  232. 'classPackageUnit.irrecusableProposalUnit',
  233. 'student.city',
  234. 'student.state',
  235. 'student.responsibles.city',
  236. 'student.responsibles.state',
  237. 'unit.city',
  238. 'unit.state',
  239. ]);
  240. $path = sprintf(
  241. 'student-contracts/%d/contract-v%d.pdf',
  242. $model->id,
  243. $model->version,
  244. );
  245. $contents = Pdf::loadView('student-contracts.contract', [
  246. 'contract' => $model,
  247. ])->setPaper('a4')->output();
  248. Storage::put($path, $contents);
  249. StudentMedia::create([
  250. 'student_id' => $model->student_id,
  251. 'student_contract_id' => $model->id,
  252. 'url' => $path,
  253. 'file_type' => 'application/pdf',
  254. 'type' => 'contract',
  255. ]);
  256. $model->update([
  257. 'file_url' => $path,
  258. 'file_type' => 'application/pdf',
  259. ]);
  260. return $model->fresh();
  261. });
  262. }
  263. //
  264. public function cancel(int $id, ?int $createdByUserId = null): ?StudentContract
  265. {
  266. return $this->update($id, ['status' => 'cancelled'], $createdByUserId);
  267. }
  268. public function freeze(int $id, int $months = 0, ?int $createdByUserId = null): ?StudentContract
  269. {
  270. return DB::transaction(function () use ($id, $months, $createdByUserId): ?StudentContract {
  271. $contract = $this->update($id, ['status' => 'frozen'], $createdByUserId);
  272. if (! $contract) {
  273. return null;
  274. }
  275. if ($months > 0) {
  276. StudentContractInstallment::where('student_contract_id', $contract->id)
  277. ->where('status', 'pending')
  278. ->get()
  279. ->each(function ($installment) use ($months) {
  280. $newDate = Carbon::parse($installment->due_date)->addMonths($months);
  281. $installment->update(['due_date' => $newDate->format('Y-m-d')]);
  282. });
  283. }
  284. return $contract->fresh();
  285. });
  286. }
  287. public function reactivate(int $id, ?int $createdByUserId = null): ?StudentContract
  288. {
  289. return $this->update($id, ['status' => 'active'], $createdByUserId);
  290. }
  291. //
  292. // monta o array de datas para n parcelas
  293. // primeira parcela usa exatamente firstdate, data escolhida pelo usuario
  294. // segunda parcela em diante usa recurringday avancando mes a mes a partir do mes da primeira
  295. // exemplo: firstdate=25/05/2026, recurringday=5, count=3
  296. // resultado: [25/05/2026, 05/06/2026, 05/07/2026]
  297. private function buildInstallmentDates(string $firstDate, int $recurringDay, int $count): array
  298. {
  299. $dates = [];
  300. $first = Carbon::createFromFormat('Y-m-d', $firstDate);
  301. $dates[] = $first->copy();
  302. $baseMonth = $first->copy()->startOfMonth();
  303. for ($i = 1; $i < $count; $i++) {
  304. $next = $baseMonth->copy()->addMonths($i);
  305. $day = min($recurringDay, $next->daysInMonth);
  306. $next->setDay($day);
  307. $dates[] = $next;
  308. }
  309. return $dates;
  310. }
  311. /**
  312. * Cada bloco de valor do contrato (Matrícula, Pacote/Aulas, Materiais, Total
  313. * do Curso) gera seu próprio grupo de parcelas quando tem valor, quantidade
  314. * de parcelas e data de vencimento preenchidos. "Total do Curso" concentra
  315. * o que foi marcado como "incluso no valor do curso" na proposta; os
  316. * demais blocos só existem quando a modalidade escolhida marcou aquele
  317. * item como "permite parcelar" (parcela separada, fora do Total).
  318. */
  319. private const INSTALLMENT_BLOCKS = [
  320. ['value' => 'tax_register', 'installments' => 'installments', 'due_date' => 'enrollment_due_date', 'type' => 'enrollment', 'history' => 'REF. MATRÍCULA'],
  321. ['value' => 'package_value', 'installments' => 'package_installments', 'due_date' => 'package_due_date', 'type' => 'package', 'history' => 'REF. PACOTE'],
  322. ['value' => 'materials_value', 'installments' => 'materials_installments', 'due_date' => 'materials_due_date', 'type' => 'materials', 'history' => 'REF. MATERIAIS'],
  323. ['value' => 'total_value', 'installments' => 'total_installments', 'due_date' => 'total_due_date', 'type' => 'total', 'history' => 'REF. TOTAL DO CURSO'],
  324. ];
  325. private function generateInstallments(StudentContract $contract): void
  326. {
  327. $recurringDay = $contract->recurring_day ?? 1;
  328. $rows = [];
  329. $now = now();
  330. foreach (self::INSTALLMENT_BLOCKS as $block) {
  331. $value = $contract->{$block['value']};
  332. $installments = $contract->{$block['installments']};
  333. $dueDate = $contract->{$block['due_date']};
  334. if (! $value || ! $installments || ! $dueDate) continue;
  335. $installmentValue = round($value / $installments, 2);
  336. $dates = $this->buildInstallmentDates(
  337. $dueDate->format('Y-m-d'),
  338. $recurringDay,
  339. $installments,
  340. );
  341. foreach ($dates as $i => $date) {
  342. $rows[] = [
  343. 'student_contract_id' => $contract->id,
  344. 'unit_id' => $contract->unit_id,
  345. 'student_id' => $contract->student_id,
  346. 'type' => $block['type'],
  347. 'history' => $block['history'],
  348. 'installment_number' => $i + 1,
  349. 'total_installments' => $installments,
  350. 'value' => $installmentValue,
  351. 'paid_value' => 0,
  352. 'discount' => 0,
  353. 'fine' => 0,
  354. 'due_date' => $date->format('Y-m-d'),
  355. 'status' => 'pending',
  356. 'created_at' => $now,
  357. 'updated_at' => $now,
  358. ];
  359. }
  360. }
  361. if (! empty($rows)) {
  362. // As parcelas são registradas/calculadas normalmente. A cobrança no Asaas
  363. // da franquia será reintroduzida no módulo Franchisee (conta própria por unidade).
  364. StudentContractInstallment::insert($rows);
  365. }
  366. }
  367. private function loadVersionHistory(StudentContract $contract): void
  368. {
  369. $root = $contract;
  370. while ($root->derived_from_contract_id !== null) {
  371. $parent = StudentContract::with('createdBy')->find($root->derived_from_contract_id);
  372. if (! $parent) {
  373. break;
  374. }
  375. $root = $parent;
  376. }
  377. $history = new Collection;
  378. $current = StudentContract::with('createdBy')->find($root->id);
  379. while ($current) {
  380. $current->loadMissing('createdBy');
  381. $history->push($current);
  382. $current = $current->derivedVersions()->with('createdBy')->first();
  383. }
  384. $contract->setRelation('versionHistory', $history->sortByDesc('version')->values());
  385. }
  386. }