StudentContractService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. if ($signed && $model->status === 'pending') {
  222. $model->update(['status' => 'active']);
  223. }
  224. return $model->fresh();
  225. }
  226. public function generateFile(int $id): ?StudentContract
  227. {
  228. return DB::transaction(function () use ($id): ?StudentContract {
  229. $model = StudentContract::query()->lockForUpdate()->find($id);
  230. if (! $model || $model->file_url) {
  231. return $model?->fresh();
  232. }
  233. $model->load([
  234. 'classPackageUnit.pavaoProposalUnit',
  235. 'classPackageUnit.irrecusableProposalUnit',
  236. 'student.city',
  237. 'student.state',
  238. 'student.responsibles.city',
  239. 'student.responsibles.state',
  240. 'unit.city',
  241. 'unit.state',
  242. ]);
  243. $path = sprintf(
  244. 'student-contracts/%d/contract-v%d.pdf',
  245. $model->id,
  246. $model->version,
  247. );
  248. $contents = Pdf::loadView('student-contracts.contract', [
  249. 'contract' => $model,
  250. ])->setPaper('a4')->output();
  251. Storage::put($path, $contents);
  252. StudentMedia::create([
  253. 'student_id' => $model->student_id,
  254. 'student_contract_id' => $model->id,
  255. 'url' => $path,
  256. 'file_type' => 'application/pdf',
  257. 'type' => 'contract',
  258. ]);
  259. $model->update([
  260. 'file_url' => $path,
  261. 'file_type' => 'application/pdf',
  262. ]);
  263. return $model->fresh();
  264. });
  265. }
  266. //
  267. public function cancel(int $id, ?int $createdByUserId = null): ?StudentContract
  268. {
  269. return $this->update($id, ['status' => 'cancelled'], $createdByUserId);
  270. }
  271. public function freeze(int $id, int $months = 0, ?int $createdByUserId = null): ?StudentContract
  272. {
  273. return DB::transaction(function () use ($id, $months, $createdByUserId): ?StudentContract {
  274. $contract = $this->update($id, ['status' => 'frozen'], $createdByUserId);
  275. if (! $contract) {
  276. return null;
  277. }
  278. if ($months > 0) {
  279. StudentContractInstallment::where('student_contract_id', $contract->id)
  280. ->where('status', 'pending')
  281. ->get()
  282. ->each(function ($installment) use ($months) {
  283. $newDate = Carbon::parse($installment->due_date)->addMonths($months);
  284. $installment->update(['due_date' => $newDate->format('Y-m-d')]);
  285. });
  286. }
  287. return $contract->fresh();
  288. });
  289. }
  290. public function reactivate(int $id, ?int $createdByUserId = null): ?StudentContract
  291. {
  292. return $this->update($id, ['status' => 'active'], $createdByUserId);
  293. }
  294. //
  295. // monta o array de datas para n parcelas
  296. // primeira parcela usa exatamente firstdate, data escolhida pelo usuario
  297. // segunda parcela em diante usa recurringday avancando mes a mes a partir do mes da primeira
  298. // exemplo: firstdate=25/05/2026, recurringday=5, count=3
  299. // resultado: [25/05/2026, 05/06/2026, 05/07/2026]
  300. private function buildInstallmentDates(string $firstDate, int $recurringDay, int $count): array
  301. {
  302. $dates = [];
  303. $first = Carbon::createFromFormat('Y-m-d', $firstDate);
  304. $dates[] = $first->copy();
  305. $baseMonth = $first->copy()->startOfMonth();
  306. for ($i = 1; $i < $count; $i++) {
  307. $next = $baseMonth->copy()->addMonths($i);
  308. $day = min($recurringDay, $next->daysInMonth);
  309. $next->setDay($day);
  310. $dates[] = $next;
  311. }
  312. return $dates;
  313. }
  314. /**
  315. * Cada bloco de valor do contrato (Matrícula, Pacote/Aulas, Materiais, Total
  316. * do Curso) gera seu próprio grupo de parcelas quando tem valor, quantidade
  317. * de parcelas e data de vencimento preenchidos. "Total do Curso" concentra
  318. * o que foi marcado como "incluso no valor do curso" na proposta; os
  319. * demais blocos só existem quando a modalidade escolhida marcou aquele
  320. * item como "permite parcelar" (parcela separada, fora do Total).
  321. */
  322. private const INSTALLMENT_BLOCKS = [
  323. ['value' => 'tax_register', 'installments' => 'installments', 'due_date' => 'enrollment_due_date', 'type' => 'enrollment', 'history' => 'REF. MATRÍCULA'],
  324. ['value' => 'package_value', 'installments' => 'package_installments', 'due_date' => 'package_due_date', 'type' => 'package', 'history' => 'REF. PACOTE'],
  325. ['value' => 'materials_value', 'installments' => 'materials_installments', 'due_date' => 'materials_due_date', 'type' => 'materials', 'history' => 'REF. MATERIAIS'],
  326. ['value' => 'total_value', 'installments' => 'total_installments', 'due_date' => 'total_due_date', 'type' => 'total', 'history' => 'REF. TOTAL DO CURSO'],
  327. ];
  328. private function generateInstallments(StudentContract $contract): void
  329. {
  330. $recurringDay = $contract->recurring_day ?? 1;
  331. $rows = [];
  332. $now = now();
  333. foreach (self::INSTALLMENT_BLOCKS as $block) {
  334. $value = $contract->{$block['value']};
  335. $installments = $contract->{$block['installments']};
  336. $dueDate = $contract->{$block['due_date']};
  337. if (! $value || ! $installments || ! $dueDate) continue;
  338. $installmentValue = round($value / $installments, 2);
  339. $dates = $this->buildInstallmentDates(
  340. $dueDate->format('Y-m-d'),
  341. $recurringDay,
  342. $installments,
  343. );
  344. foreach ($dates as $i => $date) {
  345. $rows[] = [
  346. 'student_contract_id' => $contract->id,
  347. 'unit_id' => $contract->unit_id,
  348. 'student_id' => $contract->student_id,
  349. 'type' => $block['type'],
  350. 'history' => $block['history'],
  351. 'installment_number' => $i + 1,
  352. 'total_installments' => $installments,
  353. 'value' => $installmentValue,
  354. 'paid_value' => 0,
  355. 'discount' => 0,
  356. 'fine' => 0,
  357. 'due_date' => $date->format('Y-m-d'),
  358. 'status' => 'pending',
  359. 'created_at' => $now,
  360. 'updated_at' => $now,
  361. ];
  362. }
  363. }
  364. if (! empty($rows)) {
  365. // As parcelas são registradas/calculadas normalmente. A cobrança no Asaas
  366. // da franquia será reintroduzida no módulo Franchisee (conta própria por unidade).
  367. StudentContractInstallment::insert($rows);
  368. }
  369. }
  370. private function loadVersionHistory(StudentContract $contract): void
  371. {
  372. $root = $contract;
  373. while ($root->derived_from_contract_id !== null) {
  374. $parent = StudentContract::with('createdBy')->find($root->derived_from_contract_id);
  375. if (! $parent) {
  376. break;
  377. }
  378. $root = $parent;
  379. }
  380. $history = new Collection;
  381. $current = StudentContract::with('createdBy')->find($root->id);
  382. while ($current) {
  383. $current->loadMissing('createdBy');
  384. $history->push($current);
  385. $current = $current->derivedVersions()->with('createdBy')->first();
  386. }
  387. $contract->setRelation('versionHistory', $history->sortByDesc('version')->values());
  388. }
  389. }