TbrCalculationService.php 24 KB

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