TbrCalculationService.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. <?php
  2. namespace App\Services;
  3. use App\Models\FranchiseeAccountReceive;
  4. use App\Models\FranchiseeAccountReceiveDetail;
  5. use App\Models\FranchiseeContract;
  6. use App\Models\InhabitantClassification;
  7. use App\Models\StudentContractInstallment;
  8. use App\Models\Tbr;
  9. use App\Models\TbrCalculation;
  10. use App\Models\UnitAccountReceivable;
  11. use App\Models\UnitFinancial;
  12. use Carbon\Carbon;
  13. use Illuminate\Pagination\LengthAwarePaginator;
  14. use Illuminate\Support\Facades\Auth;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Validation\ValidationException;
  17. class TbrCalculationService
  18. {
  19. private const ROYALTIES_REVENUE_RATE = 0.08;
  20. private const FNM_REVENUE_RATE = 0.02;
  21. private const FNM_BRACKET_PERCENTAGE = 0.20;
  22. private const MAINTENANCE_RATE = 0.30;
  23. private const EXEMPT_THRESHOLD_MONTH = 3;
  24. // Faturamento (competência): por padrão usa o próprio mês de referência
  25. // (Opção A — assume-se o mês já fechado ao gerar). Ligue para usar o mês
  26. // anterior fechado (Opção B) quando a geração ocorrer dentro do mês corrente.
  27. private const REVENUE_FROM_PREVIOUS_MONTH = false;
  28. /**
  29. * Faturamento da unidade no mês (competência): soma das parcelas de aluno com
  30. * vencimento no mês, de contratos não cancelados. Alimenta a regra "maior entre
  31. * valor fixo e % do faturamento".
  32. */
  33. public function resolveRevenue(int $unitId, int $referenceYear, int $referenceMonth): float
  34. {
  35. $base = Carbon::createFromDate($referenceYear, $referenceMonth, 1);
  36. if (self::REVENUE_FROM_PREVIOUS_MONTH) {
  37. $base = $base->subMonthNoOverflow();
  38. }
  39. return $this->resolveRevenueBetween(
  40. [$unitId],
  41. $base->copy()->startOfMonth(),
  42. $base->copy()->endOfMonth(),
  43. );
  44. }
  45. /**
  46. * Faturamento-base do TBR em um intervalo. Mantém dashboard e geração do TBR
  47. * usando a mesma composição: parcelas de alunos + recebíveis avulsos.
  48. * Um array vazio de unidades representa toda a rede.
  49. */
  50. public function resolveRevenueBetween(array $unitIds, Carbon $startDate, Carbon $endDate): float
  51. {
  52. $start = $startDate->toDateString();
  53. $end = $endDate->toDateString();
  54. // Base de faturamento = parcelas de aluno + recebíveis avulsos (manuais)
  55. // do mês de referência (decisão da franqueadora: avulsos compõem o royalty).
  56. $installments = (float) StudentContractInstallment::whereNull('deleted_at')
  57. ->when(!empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds))
  58. ->where('status', '!=', 'cancelled')
  59. ->whereBetween('due_date', [$start, $end])
  60. ->sum('value');
  61. $manual = (float) UnitAccountReceivable::whereNull('deleted_at')
  62. ->when(!empty($unitIds), fn ($q) => $q->whereIn('unit_id', $unitIds))
  63. ->where('status', '!=', 'cancelled')
  64. ->whereBetween('due_date', [$start, $end])
  65. ->sum('value');
  66. return $installments + $manual;
  67. }
  68. /**
  69. * Faturamento do cálculo individual: usa o valor informado manualmente
  70. * (override) quando > 0; senão calcula automaticamente pelas parcelas do mês.
  71. */
  72. private function pickRevenue(array $data, int $unitId, int $year, int $month): float
  73. {
  74. $manual = (float) ($data['revenue_value'] ?? 0);
  75. return $manual > 0 ? $manual : $this->resolveRevenue($unitId, $year, $month);
  76. }
  77. public function paginate(int $perPage = 15): LengthAwarePaginator
  78. {
  79. return TbrCalculation::with(['unit', 'user'])
  80. ->orderBy('created_at', 'desc')
  81. ->paginate($perPage);
  82. }
  83. public function listAll(int $limit = 100): \Illuminate\Database\Eloquent\Collection
  84. {
  85. return TbrCalculation::with(['unit', 'user'])
  86. ->orderBy('created_at', 'desc')
  87. ->limit($limit)
  88. ->get();
  89. }
  90. public function findById(int $id): ?TbrCalculation
  91. {
  92. return TbrCalculation::with([
  93. 'unit',
  94. 'user',
  95. 'royaltiesBracket',
  96. ])->find($id);
  97. }
  98. public function preview(array $data): array
  99. {
  100. $contract = $this->resolveContract($data['unit_id']);
  101. $year = (int) $data['reference_year'];
  102. $month = (int) $data['reference_month'];
  103. return $this->buildPreview($contract, $year, $month, $this->pickRevenue($data, $contract->unit_id, $year, $month));
  104. }
  105. public function previewBatch(int $referenceYear, int $referenceMonth): array
  106. {
  107. $contracts = $this->loadActiveContracts($referenceYear, $referenceMonth);
  108. return $contracts->map(function (FranchiseeContract $contract) use ($referenceYear, $referenceMonth) {
  109. try {
  110. $revenue = $this->resolveRevenue($contract->unit_id, $referenceYear, $referenceMonth);
  111. return $this->buildPreview($contract, $referenceYear, $referenceMonth, $revenue);
  112. } catch (ValidationException $e) {
  113. return [
  114. 'unit_id' => $contract->unit_id,
  115. 'unit_name' => $contract->unit?->fantasy_name,
  116. 'error' => collect($e->errors())->flatten()->first(),
  117. ];
  118. }
  119. })->values()->toArray();
  120. }
  121. public function calculate(array $data): TbrCalculation
  122. {
  123. return DB::transaction(function () use ($data) {
  124. $contract = $this->resolveContract($data['unit_id']);
  125. $year = (int) $data['reference_year'];
  126. $month = (int) $data['reference_month'];
  127. $payload = $this->buildPreview($contract, $year, $month, $this->pickRevenue($data, $contract->unit_id, $year, $month));
  128. return $this->persistCalculation($payload);
  129. });
  130. }
  131. public function generateReceivable(int $calculationId): FranchiseeAccountReceive
  132. {
  133. return DB::transaction(function () use ($calculationId) {
  134. $calculation = TbrCalculation::lockForUpdate()->findOrFail($calculationId);
  135. if ($calculation->receivable_generated) {
  136. throw ValidationException::withMessages([
  137. 'tbr_calculation_id' => 'Já existe um título gerado para este cálculo.',
  138. ]);
  139. }
  140. $duplicate = TbrCalculation::where('unit_id', $calculation->unit_id)
  141. ->where('contract_month_reference', $calculation->contract_month_reference)
  142. ->where('receivable_generated', true)
  143. ->where('id', '!=', $calculation->id)
  144. ->exists();
  145. if ($duplicate) {
  146. throw ValidationException::withMessages([
  147. 'tbr_calculation_id' => 'Já existe um título gerado para esta unidade no mês de contrato '
  148. . $calculation->contract_month_reference . '.',
  149. ]);
  150. }
  151. $contract = FranchiseeContract::where('unit_id', $calculation->unit_id)
  152. ->orderByDesc('start_date')
  153. ->first();
  154. return $this->buildReceivable($calculation, $contract);
  155. });
  156. }
  157. public function generateBatch(int $referenceYear, int $referenceMonth, ?array $unitIds = null): array
  158. {
  159. $contracts = $this->loadActiveContracts($referenceYear, $referenceMonth);
  160. if ($unitIds !== null) {
  161. $contracts = $contracts->filter(fn ($c) => in_array($c->unit_id, $unitIds, true))->values();
  162. }
  163. $generated = [];
  164. $skipped = [];
  165. $errors = [];
  166. foreach ($contracts as $contract) {
  167. try {
  168. DB::transaction(function () use ($contract, $referenceYear, $referenceMonth, &$generated, &$skipped) {
  169. $revenue = $this->resolveRevenue($contract->unit_id, $referenceYear, $referenceMonth);
  170. $payload = $this->buildPreview($contract, $referenceYear, $referenceMonth, $revenue);
  171. if ($payload['receivable_already_generated']) {
  172. $skipped[] = [
  173. 'unit_id' => $contract->unit_id,
  174. 'unit_name' => $payload['unit_name'],
  175. 'reason' => 'Já gerado para este mês de contrato.',
  176. ];
  177. return;
  178. }
  179. $calculation = $this->persistCalculation($payload);
  180. $receive = $this->buildReceivable($calculation, $contract);
  181. $generated[] = [
  182. 'unit_id' => $contract->unit_id,
  183. 'unit_name' => $payload['unit_name'],
  184. 'tbr_calculation_id' => $calculation->id,
  185. 'receivable_id' => $receive->id,
  186. 'total' => $payload['final_value'],
  187. ];
  188. });
  189. } catch (ValidationException $e) {
  190. $errors[] = [
  191. 'unit_id' => $contract->unit_id,
  192. 'unit_name' => $contract->unit?->fantasy_name,
  193. 'reason' => collect($e->errors())->flatten()->first(),
  194. ];
  195. } catch (\Throwable $e) {
  196. $errors[] = [
  197. 'unit_id' => $contract->unit_id,
  198. 'unit_name' => $contract->unit?->fantasy_name,
  199. 'reason' => $e->getMessage(),
  200. ];
  201. }
  202. }
  203. return [
  204. 'generated_count' => count($generated),
  205. 'skipped_count' => count($skipped),
  206. 'error_count' => count($errors),
  207. 'generated' => $generated,
  208. 'skipped' => $skipped,
  209. 'errors' => $errors,
  210. ];
  211. }
  212. private function loadActiveContracts(int $referenceYear, int $referenceMonth): \Illuminate\Support\Collection
  213. {
  214. $referenceLastDay = Carbon::createFromDate($referenceYear, $referenceMonth, 1)->endOfMonth()->toDateString();
  215. $referenceFirstDay = Carbon::createFromDate($referenceYear, $referenceMonth, 1)->startOfMonth()->toDateString();
  216. return FranchiseeContract::with(['unit', 'municipalitySize'])
  217. ->whereNotNull('start_date')
  218. ->whereNotNull('municipality_size_id')
  219. ->where('start_date', '<=', $referenceLastDay)
  220. ->where(function ($q) use ($referenceFirstDay) {
  221. $q->whereNull('end_date')->orWhere('end_date', '>=', $referenceFirstDay);
  222. })
  223. ->orderByDesc('start_date')
  224. ->orderByDesc('id')
  225. ->get()
  226. ->unique('unit_id')
  227. ->values();
  228. }
  229. private function resolveContract(int $unitId): FranchiseeContract
  230. {
  231. $contract = FranchiseeContract::with(['unit', 'municipalitySize'])
  232. ->where('unit_id', $unitId)
  233. ->whereNotNull('start_date')
  234. ->orderByDesc('start_date')
  235. ->orderByDesc('id')
  236. ->first();
  237. if (!$contract) {
  238. throw ValidationException::withMessages([
  239. 'unit_id' => 'Unidade não possui contrato cadastrado.',
  240. ]);
  241. }
  242. if (!$contract->municipality_size_id) {
  243. throw ValidationException::withMessages([
  244. 'unit_id' => 'O contrato da unidade não tem a faixa de habitantes definida. Edite o contrato para informá-la.',
  245. ]);
  246. }
  247. return $contract;
  248. }
  249. private function buildPreview(FranchiseeContract $contract, int $referenceYear, int $referenceMonth, float $revenueValue): array
  250. {
  251. $tbrValue = (float) ($contract->tbr_fixed_value ?? 0);
  252. if ($tbrValue <= 0) {
  253. $tbrValue = (float) (Tbr::where('year', $referenceYear)->orderByDesc('id')->value('tbr_value') ?? 0);
  254. }
  255. if ($tbrValue <= 0) {
  256. throw ValidationException::withMessages([
  257. 'unit_id' => 'TBR não definida para o contrato nem para o ano de referência.',
  258. ]);
  259. }
  260. $contractMonth = $this->resolveContractMonth($contract->start_date, $referenceYear, $referenceMonth);
  261. $municipalitySizeId = (int) $contract->municipality_size_id;
  262. // Flags de cobrança da unidade (sem registro financeiro => cobra, padrão).
  263. $financial = UnitFinancial::where('unit_id', $contract->unit_id)->first();
  264. $chargeRoi = $financial ? (bool) $financial->charge_roi : true;
  265. $chargeFnm = $financial ? (bool) $financial->charge_fnm : true;
  266. // Royalties só busca a faixa quando há cobrança; desligado não exige faixa.
  267. $royaltiesBracket = $chargeRoi
  268. ? $this->findRoyaltiesBracket($municipalitySizeId, $contractMonth)
  269. : null;
  270. $royaltiesBracketPercentage = $royaltiesBracket ? (float) $royaltiesBracket->tbr_percentage : 0.0;
  271. $fnmPercentage = $chargeFnm ? $this->resolveFnmPercentage($contractMonth) : 0.0;
  272. $maintenancePercentage = self::MAINTENANCE_RATE;
  273. $royaltiesBracketValue = round($royaltiesBracketPercentage * $tbrValue, 2);
  274. $fnmBracketValue = round($fnmPercentage * $tbrValue, 2);
  275. $maintenanceBracketValue = round($maintenancePercentage * $tbrValue, 2);
  276. [$royaltiesEffectiveValue, $royaltiesEffectivePercentage, $royaltiesAppliedCriteria,
  277. $fnmEffectiveValue, $fnmEffectivePercentage] = $this->resolveEffectiveValues(
  278. $contractMonth,
  279. $revenueValue,
  280. $royaltiesBracketPercentage,
  281. $royaltiesBracketValue,
  282. $fnmPercentage,
  283. $fnmBracketValue,
  284. );
  285. // Cobrança desligada: zera o respectivo componente (fora do total).
  286. if (!$chargeRoi) {
  287. $royaltiesEffectiveValue = 0.0;
  288. $royaltiesEffectivePercentage = 0.0;
  289. $royaltiesAppliedCriteria = 'nao_cobrado';
  290. }
  291. if (!$chargeFnm) {
  292. $fnmEffectiveValue = 0.0;
  293. $fnmEffectivePercentage = 0.0;
  294. }
  295. $maintenanceEffectiveValue = $maintenanceBracketValue;
  296. $maintenanceEffectivePercentage = $maintenancePercentage;
  297. $bracketSubtotal = round($royaltiesBracketValue + $fnmBracketValue + $maintenanceBracketValue, 2);
  298. $subtotal = round($royaltiesEffectiveValue + $fnmEffectiveValue + $maintenanceEffectiveValue, 2);
  299. return [
  300. 'unit_id' => $contract->unit_id,
  301. 'unit_name' => $contract->unit?->fantasy_name,
  302. 'contract_id' => $contract->id,
  303. 'reference_year' => $referenceYear,
  304. 'reference_month' => $referenceMonth,
  305. 'contract_month_reference' => $contractMonth,
  306. 'revenue_value' => $revenueValue,
  307. 'tbr_value' => $tbrValue,
  308. 'municipality_size_id' => $municipalitySizeId,
  309. 'municipality_size_name' => $contract->municipalitySize?->description,
  310. 'royalties_bracket_id' => $royaltiesBracket?->id,
  311. 'royalties_bracket_percentage' => $royaltiesBracketPercentage,
  312. 'royalties_bracket_value' => $royaltiesBracketValue,
  313. 'fnm_bracket_percentage' => $fnmPercentage,
  314. 'fnm_bracket_value' => $fnmBracketValue,
  315. 'maintenance_bracket_percentage' => $maintenancePercentage,
  316. 'maintenance_bracket_value' => $maintenanceBracketValue,
  317. 'royalties_effective_percentage' => $royaltiesEffectivePercentage,
  318. 'royalties_effective_value' => $royaltiesEffectiveValue,
  319. 'fnm_effective_percentage' => $fnmEffectivePercentage,
  320. 'fnm_effective_value' => $fnmEffectiveValue,
  321. 'maintenance_effective_percentage' => $maintenanceEffectivePercentage,
  322. 'maintenance_effective_value' => $maintenanceEffectiveValue,
  323. 'bracket_subtotal' => $bracketSubtotal,
  324. 'subtotal' => $subtotal,
  325. 'final_value' => $subtotal,
  326. 'royalties_applied_criteria' => $royaltiesAppliedCriteria,
  327. 'receivable_already_generated' => $this->existingReceivable($contract->unit_id, $contractMonth),
  328. ];
  329. }
  330. private function persistCalculation(array $payload): TbrCalculation
  331. {
  332. return TbrCalculation::create([
  333. 'unit_id' => $payload['unit_id'],
  334. 'reference_year' => $payload['reference_year'],
  335. 'reference_month' => $payload['reference_month'],
  336. 'revenue_value' => $payload['revenue_value'],
  337. 'contract_month_reference' => $payload['contract_month_reference'],
  338. 'tbr_value' => $payload['tbr_value'],
  339. 'royalties_bracket_id' => $payload['royalties_bracket_id'],
  340. 'royalties_bracket_percentage' => $payload['royalties_bracket_percentage'],
  341. 'royalties_bracket_value' => $payload['royalties_bracket_value'],
  342. 'fnm_bracket_percentage' => $payload['fnm_bracket_percentage'],
  343. 'fnm_bracket_value' => $payload['fnm_bracket_value'],
  344. 'maintenance_bracket_percentage' => $payload['maintenance_bracket_percentage'],
  345. 'maintenance_bracket_value' => $payload['maintenance_bracket_value'],
  346. 'royalties_effective_percentage' => $payload['royalties_effective_percentage'],
  347. 'royalties_effective_value' => $payload['royalties_effective_value'],
  348. 'fnm_effective_percentage' => $payload['fnm_effective_percentage'],
  349. 'fnm_effective_value' => $payload['fnm_effective_value'],
  350. 'maintenance_effective_percentage' => $payload['maintenance_effective_percentage'],
  351. 'maintenance_effective_value' => $payload['maintenance_effective_value'],
  352. 'bracket_subtotal' => $payload['bracket_subtotal'],
  353. 'subtotal' => $payload['subtotal'],
  354. 'final_value' => $payload['final_value'],
  355. 'user_id' => Auth::id(),
  356. 'royalties_applied_criteria' => $payload['royalties_applied_criteria'],
  357. 'receivable_generated' => false,
  358. ]);
  359. }
  360. private function buildReceivable(TbrCalculation $calculation, ?FranchiseeContract $contract): FranchiseeAccountReceive
  361. {
  362. // Mês de competência = o que a pessoa escolheu ao gerar (não a data de geração).
  363. $referenceDate = $calculation->reference_year && $calculation->reference_month
  364. ? Carbon::create($calculation->reference_year, $calculation->reference_month, 1)
  365. : Carbon::parse($calculation->created_at);
  366. $referenceLabel = $referenceDate->format('m/Y');
  367. $dueDate = $this->resolveDueDate($contract, $referenceDate);
  368. $receive = FranchiseeAccountReceive::create([
  369. 'unit_id' => $calculation->unit_id,
  370. 'tbr_calculation_id' => $calculation->id,
  371. 'order' => $calculation->contract_month_reference,
  372. 'history' => 'Royalties / FNM / Manutenção — ' . $referenceLabel,
  373. 'value' => $calculation->final_value,
  374. 'paid_value' => 0,
  375. 'due_date' => $dueDate,
  376. 'discount' => 0,
  377. 'fees' => 0,
  378. 'obs' => null,
  379. 'asaas_id' => null,
  380. 'status' => 'pending',
  381. ]);
  382. FranchiseeAccountReceiveDetail::create([
  383. 'franchisee_account_receive_id' => $receive->id,
  384. 'value' => $calculation->royalties_effective_value,
  385. 'history' => 'Royalties ' . $referenceLabel,
  386. ]);
  387. FranchiseeAccountReceiveDetail::create([
  388. 'franchisee_account_receive_id' => $receive->id,
  389. 'value' => $calculation->fnm_effective_value,
  390. 'history' => 'FNM ' . $referenceLabel,
  391. ]);
  392. FranchiseeAccountReceiveDetail::create([
  393. 'franchisee_account_receive_id' => $receive->id,
  394. 'value' => $calculation->maintenance_effective_value,
  395. 'history' => 'Taxa Manutenção ' . $referenceLabel,
  396. ]);
  397. $calculation->update(['receivable_generated' => true]);
  398. // Espelho na unidade: o TBR que a matriz cobra vira uma Conta a Pagar da
  399. // franquia (ciclo próprio, com ou sem Asaas). A dívida é registrada sempre.
  400. \App\Models\UnitAccountPayable::create([
  401. 'unit_id' => $receive->unit_id,
  402. 'franchisee_account_receive_id' => $receive->id,
  403. 'origin' => \App\Models\UnitAccountPayable::ORIGIN_TBR,
  404. 'history' => $receive->history,
  405. 'value' => $receive->value,
  406. 'paid_value' => 0,
  407. 'discount' => 0,
  408. 'fine' => 0,
  409. 'due_date' => $receive->due_date,
  410. 'status' => 'pending',
  411. ]);
  412. \App\Jobs\SyncFranchiseeChargeJob::dispatch($receive);
  413. return $receive->load('details');
  414. }
  415. private function resolveEffectiveValues(
  416. int $contractMonth,
  417. float $revenueValue,
  418. float $royaltiesBracketPercentage,
  419. float $royaltiesBracketValue,
  420. float $fnmBracketPercentage,
  421. float $fnmBracketValue,
  422. ): array {
  423. if ($contractMonth <= self::EXEMPT_THRESHOLD_MONTH) {
  424. return [0.0, 0.0, 'tbr_fixo', 0.0, 0.0];
  425. }
  426. $royaltiesFromRevenue = round(self::ROYALTIES_REVENUE_RATE * $revenueValue, 2);
  427. $fnmFromRevenue = round(self::FNM_REVENUE_RATE * $revenueValue, 2);
  428. if ($royaltiesBracketValue >= $royaltiesFromRevenue) {
  429. $royaltiesEffectiveValue = $royaltiesBracketValue;
  430. $royaltiesEffectivePercentage = $royaltiesBracketPercentage;
  431. $royaltiesAppliedCriteria = 'tbr_fixo';
  432. } else {
  433. $royaltiesEffectiveValue = $royaltiesFromRevenue;
  434. $royaltiesEffectivePercentage = self::ROYALTIES_REVENUE_RATE;
  435. $royaltiesAppliedCriteria = 'percentual_faturamento';
  436. }
  437. if ($fnmBracketValue >= $fnmFromRevenue) {
  438. $fnmEffectiveValue = $fnmBracketValue;
  439. $fnmEffectivePercentage = $fnmBracketPercentage;
  440. } else {
  441. $fnmEffectiveValue = $fnmFromRevenue;
  442. $fnmEffectivePercentage = self::FNM_REVENUE_RATE;
  443. }
  444. return [$royaltiesEffectiveValue, $royaltiesEffectivePercentage, $royaltiesAppliedCriteria, $fnmEffectiveValue, $fnmEffectivePercentage];
  445. }
  446. private function resolveContractMonth(?Carbon $startDate, int $year, int $month): int
  447. {
  448. if (!$startDate) {
  449. return 1;
  450. }
  451. $start = $startDate->copy()->startOfMonth();
  452. $reference = Carbon::createFromDate($year, $month, 1)->startOfMonth();
  453. $diff = (int) $start->diffInMonths($reference);
  454. return max(1, $diff + 1);
  455. }
  456. private function findRoyaltiesBracket(int $municipalitySizeId, int $contractMonth): InhabitantClassification
  457. {
  458. $bracket = InhabitantClassification::where('municipality_size_id', $municipalitySizeId)
  459. ->where('is_renewal', false)
  460. ->where('start', '<=', $contractMonth)
  461. ->where(function ($q) use ($contractMonth) {
  462. $q->whereNull('end')->orWhere('end', '>=', $contractMonth);
  463. })
  464. ->orderBy('start')
  465. ->first();
  466. if (!$bracket) {
  467. throw ValidationException::withMessages([
  468. 'municipality_size_id' => 'Não foi encontrada faixa de royalties para o porte e mês de contrato informados.',
  469. ]);
  470. }
  471. return $bracket;
  472. }
  473. private function resolveFnmPercentage(int $contractMonth): float
  474. {
  475. return $contractMonth <= self::EXEMPT_THRESHOLD_MONTH ? 0.0 : self::FNM_BRACKET_PERCENTAGE;
  476. }
  477. private function resolveDueDate(?FranchiseeContract $contract, Carbon $referenceDate): Carbon
  478. {
  479. $dueDay = (int) ($contract?->invoice_due_date ?? 10);
  480. $dueDay = max(1, min(28, $dueDay));
  481. return $referenceDate->copy()->addMonthNoOverflow()->day($dueDay);
  482. }
  483. private function existingReceivable(int $unitId, int $contractMonth): bool
  484. {
  485. return TbrCalculation::where('unit_id', $unitId)
  486. ->where('contract_month_reference', $contractMonth)
  487. ->where('receivable_generated', true)
  488. ->exists();
  489. }
  490. }