TbrCalculationService.php 24 KB

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