StudentContractService.php 16 KB

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