TbrCalculationService.php 26 KB

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