StudentContractService.php 16 KB

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