StudentContractService.php 14 KB

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