StudentContractService.php 14 KB

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