TbrCalculationService.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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. $tbrConfig = Tbr::where('year', $referenceYear)->orderByDesc('id')->first();
  260. $tbrValue = (float) ($contract->tbr_fixed_value ?? 0);
  261. if ($tbrValue <= 0) {
  262. $tbrValue = (float) ($tbrConfig->tbr_value ?? 0);
  263. }
  264. if ($tbrValue <= 0) {
  265. throw ValidationException::withMessages([
  266. 'unit_id' => 'TBR não definida para o contrato nem para o ano de referência.',
  267. ]);
  268. }
  269. $fnmPercentageConfig = $tbrConfig ? (float) $tbrConfig->fnm_percentage : self::FNM_BRACKET_PERCENTAGE;
  270. $maintenancePercentageConfig = $tbrConfig ? (float) $tbrConfig->maintenance_percentage : self::MAINTENANCE_RATE;
  271. $contractMonth = $this->resolveContractMonth($contract->start_date, $referenceYear, $referenceMonth);
  272. $municipalitySizeId = (int) $contract->municipality_size_id;
  273. // Flags de cobrança da unidade (sem registro financeiro => cobra, padrão).
  274. $financial = UnitFinancial::where('unit_id', $contract->unit_id)->first();
  275. $chargeRoi = $financial ? (bool) $financial->charge_roi : true;
  276. $chargeFnm = $financial ? (bool) $financial->charge_fnm : true;
  277. // Royalties só busca a faixa quando há cobrança; desligado não exige faixa.
  278. $royaltiesBracket = $chargeRoi
  279. ? $this->findRoyaltiesBracket($municipalitySizeId, $contractMonth)
  280. : null;
  281. $royaltiesBracketPercentage = $royaltiesBracket ? (float) $royaltiesBracket->tbr_percentage : 0.0;
  282. $fnmPercentage = $chargeFnm ? $this->resolveFnmPercentage($contractMonth, $fnmPercentageConfig) : 0.0;
  283. $maintenancePercentage = $maintenancePercentageConfig;
  284. $royaltiesBracketValue = round($royaltiesBracketPercentage * $tbrValue, 2);
  285. $fnmBracketValue = round($fnmPercentage * $tbrValue, 2);
  286. $maintenanceBracketValue = round($maintenancePercentage * $tbrValue, 2);
  287. [$royaltiesEffectiveValue, $royaltiesEffectivePercentage, $royaltiesAppliedCriteria,
  288. $fnmEffectiveValue, $fnmEffectivePercentage] = $this->resolveEffectiveValues(
  289. $contractMonth,
  290. $revenueValue,
  291. $royaltiesBracketPercentage,
  292. $royaltiesBracketValue,
  293. $fnmPercentage,
  294. $fnmBracketValue,
  295. );
  296. // Cobrança desligada: zera o respectivo componente (fora do total).
  297. if (! $chargeRoi) {
  298. $royaltiesEffectiveValue = 0.0;
  299. $royaltiesEffectivePercentage = 0.0;
  300. $royaltiesAppliedCriteria = 'nao_cobrado';
  301. }
  302. if (! $chargeFnm) {
  303. $fnmEffectiveValue = 0.0;
  304. $fnmEffectivePercentage = 0.0;
  305. }
  306. $maintenanceEffectiveValue = $maintenanceBracketValue;
  307. $maintenanceEffectivePercentage = $maintenancePercentage;
  308. $bracketSubtotal = round($royaltiesBracketValue + $fnmBracketValue + $maintenanceBracketValue, 2);
  309. $subtotal = round($royaltiesEffectiveValue + $fnmEffectiveValue + $maintenanceEffectiveValue, 2);
  310. return [
  311. 'unit_id' => $contract->unit_id,
  312. 'unit_name' => $contract->unit?->fantasy_name,
  313. 'contract_id' => $contract->id,
  314. 'reference_year' => $referenceYear,
  315. 'reference_month' => $referenceMonth,
  316. 'contract_month_reference' => $contractMonth,
  317. 'revenue_value' => $revenueValue,
  318. 'tbr_value' => $tbrValue,
  319. 'municipality_size_id' => $municipalitySizeId,
  320. 'municipality_size_name' => $contract->municipalitySize?->description,
  321. 'royalties_bracket_id' => $royaltiesBracket?->id,
  322. 'royalties_bracket_percentage' => $royaltiesBracketPercentage,
  323. 'royalties_bracket_value' => $royaltiesBracketValue,
  324. 'fnm_bracket_percentage' => $fnmPercentage,
  325. 'fnm_bracket_value' => $fnmBracketValue,
  326. 'maintenance_bracket_percentage' => $maintenancePercentage,
  327. 'maintenance_bracket_value' => $maintenanceBracketValue,
  328. 'royalties_effective_percentage' => $royaltiesEffectivePercentage,
  329. 'royalties_effective_value' => $royaltiesEffectiveValue,
  330. 'fnm_effective_percentage' => $fnmEffectivePercentage,
  331. 'fnm_effective_value' => $fnmEffectiveValue,
  332. 'maintenance_effective_percentage' => $maintenanceEffectivePercentage,
  333. 'maintenance_effective_value' => $maintenanceEffectiveValue,
  334. 'bracket_subtotal' => $bracketSubtotal,
  335. 'subtotal' => $subtotal,
  336. 'final_value' => $subtotal,
  337. 'royalties_applied_criteria' => $royaltiesAppliedCriteria,
  338. 'receivable_already_generated' => $this->existingReceivable($contract->unit_id, $contractMonth),
  339. ];
  340. }
  341. private function persistCalculation(array $payload): TbrCalculation
  342. {
  343. return TbrCalculation::create([
  344. 'unit_id' => $payload['unit_id'],
  345. 'reference_year' => $payload['reference_year'],
  346. 'reference_month' => $payload['reference_month'],
  347. 'revenue_value' => $payload['revenue_value'],
  348. 'contract_month_reference' => $payload['contract_month_reference'],
  349. 'tbr_value' => $payload['tbr_value'],
  350. 'royalties_bracket_id' => $payload['royalties_bracket_id'],
  351. 'royalties_bracket_percentage' => $payload['royalties_bracket_percentage'],
  352. 'royalties_bracket_value' => $payload['royalties_bracket_value'],
  353. 'fnm_bracket_percentage' => $payload['fnm_bracket_percentage'],
  354. 'fnm_bracket_value' => $payload['fnm_bracket_value'],
  355. 'maintenance_bracket_percentage' => $payload['maintenance_bracket_percentage'],
  356. 'maintenance_bracket_value' => $payload['maintenance_bracket_value'],
  357. 'royalties_effective_percentage' => $payload['royalties_effective_percentage'],
  358. 'royalties_effective_value' => $payload['royalties_effective_value'],
  359. 'fnm_effective_percentage' => $payload['fnm_effective_percentage'],
  360. 'fnm_effective_value' => $payload['fnm_effective_value'],
  361. 'maintenance_effective_percentage' => $payload['maintenance_effective_percentage'],
  362. 'maintenance_effective_value' => $payload['maintenance_effective_value'],
  363. 'bracket_subtotal' => $payload['bracket_subtotal'],
  364. 'subtotal' => $payload['subtotal'],
  365. 'final_value' => $payload['final_value'],
  366. 'user_id' => Auth::id(),
  367. 'royalties_applied_criteria' => $payload['royalties_applied_criteria'],
  368. 'receivable_generated' => false,
  369. ]);
  370. }
  371. private function buildReceivable(TbrCalculation $calculation, ?FranchiseeContract $contract): FranchiseeAccountReceive
  372. {
  373. // Mês de competência = o que a pessoa escolheu ao gerar (não a data de geração).
  374. $referenceDate = $calculation->reference_year && $calculation->reference_month
  375. ? Carbon::create($calculation->reference_year, $calculation->reference_month, 1)
  376. : Carbon::parse($calculation->created_at);
  377. $referenceLabel = $referenceDate->format('m/Y');
  378. $dueDate = $this->resolveDueDate($contract, $referenceDate);
  379. $receive = FranchiseeAccountReceive::create([
  380. 'unit_id' => $calculation->unit_id,
  381. 'tbr_calculation_id' => $calculation->id,
  382. 'order' => $calculation->contract_month_reference,
  383. 'history' => 'Royalties / FNM / Manutenção — '.$referenceLabel,
  384. 'value' => $calculation->final_value,
  385. 'paid_value' => 0,
  386. 'due_date' => $dueDate,
  387. 'discount' => 0,
  388. 'fees' => 0,
  389. 'obs' => null,
  390. 'asaas_id' => null,
  391. 'status' => 'pending',
  392. ]);
  393. FranchiseeAccountReceiveDetail::create([
  394. 'franchisee_account_receive_id' => $receive->id,
  395. 'value' => $calculation->royalties_effective_value,
  396. 'history' => 'Royalties '.$referenceLabel,
  397. ]);
  398. FranchiseeAccountReceiveDetail::create([
  399. 'franchisee_account_receive_id' => $receive->id,
  400. 'value' => $calculation->fnm_effective_value,
  401. 'history' => 'FNM '.$referenceLabel,
  402. ]);
  403. FranchiseeAccountReceiveDetail::create([
  404. 'franchisee_account_receive_id' => $receive->id,
  405. 'value' => $calculation->maintenance_effective_value,
  406. 'history' => 'Taxa Manutenção '.$referenceLabel,
  407. ]);
  408. $calculation->update(['receivable_generated' => true]);
  409. // Espelho na unidade: o TBR que a matriz cobra vira uma Conta a Pagar da
  410. // franquia (ciclo próprio, com ou sem Asaas). A dívida é registrada sempre.
  411. \App\Models\UnitAccountPayable::create([
  412. 'unit_id' => $receive->unit_id,
  413. 'franchisee_account_receive_id' => $receive->id,
  414. 'origin' => \App\Models\UnitAccountPayable::ORIGIN_TBR,
  415. 'history' => $receive->history,
  416. 'value' => $receive->value,
  417. 'paid_value' => 0,
  418. 'discount' => 0,
  419. 'fine' => 0,
  420. 'due_date' => $receive->due_date,
  421. 'status' => 'pending',
  422. ]);
  423. \App\Jobs\SyncFranchiseeChargeJob::dispatch($receive);
  424. return $receive->load('details');
  425. }
  426. private function resolveEffectiveValues(
  427. int $contractMonth,
  428. float $revenueValue,
  429. float $royaltiesBracketPercentage,
  430. float $royaltiesBracketValue,
  431. float $fnmBracketPercentage,
  432. float $fnmBracketValue,
  433. ): array {
  434. if ($contractMonth <= self::EXEMPT_THRESHOLD_MONTH) {
  435. return [0.0, 0.0, 'tbr_fixo', 0.0, 0.0];
  436. }
  437. $royaltiesFromRevenue = round(self::ROYALTIES_REVENUE_RATE * $revenueValue, 2);
  438. $fnmFromRevenue = round(self::FNM_REVENUE_RATE * $revenueValue, 2);
  439. if ($royaltiesBracketValue >= $royaltiesFromRevenue) {
  440. $royaltiesEffectiveValue = $royaltiesBracketValue;
  441. $royaltiesEffectivePercentage = $royaltiesBracketPercentage;
  442. $royaltiesAppliedCriteria = 'tbr_fixo';
  443. } else {
  444. $royaltiesEffectiveValue = $royaltiesFromRevenue;
  445. $royaltiesEffectivePercentage = self::ROYALTIES_REVENUE_RATE;
  446. $royaltiesAppliedCriteria = 'percentual_faturamento';
  447. }
  448. if ($fnmBracketValue >= $fnmFromRevenue) {
  449. $fnmEffectiveValue = $fnmBracketValue;
  450. $fnmEffectivePercentage = $fnmBracketPercentage;
  451. } else {
  452. $fnmEffectiveValue = $fnmFromRevenue;
  453. $fnmEffectivePercentage = self::FNM_REVENUE_RATE;
  454. }
  455. return [$royaltiesEffectiveValue, $royaltiesEffectivePercentage, $royaltiesAppliedCriteria, $fnmEffectiveValue, $fnmEffectivePercentage];
  456. }
  457. private function resolveContractMonth(?Carbon $startDate, int $year, int $month): int
  458. {
  459. if (! $startDate) {
  460. return 1;
  461. }
  462. $start = $startDate->copy()->startOfMonth();
  463. $reference = Carbon::createFromDate($year, $month, 1)->startOfMonth();
  464. $diff = (int) $start->diffInMonths($reference);
  465. return max(1, $diff + 1);
  466. }
  467. private function findRoyaltiesBracket(int $municipalitySizeId, int $contractMonth): InhabitantClassification
  468. {
  469. $bracket = InhabitantClassification::where('municipality_size_id', $municipalitySizeId)
  470. ->where('is_renewal', false)
  471. ->where('start', '<=', $contractMonth)
  472. ->where(function ($q) use ($contractMonth) {
  473. $q->whereNull('end')->orWhere('end', '>=', $contractMonth);
  474. })
  475. ->orderBy('start')
  476. ->first();
  477. if (! $bracket) {
  478. throw ValidationException::withMessages([
  479. 'municipality_size_id' => 'Não foi encontrada faixa de royalties para o porte e mês de contrato informados.',
  480. ]);
  481. }
  482. return $bracket;
  483. }
  484. private function resolveFnmPercentage(int $contractMonth, float $fnmPercentage): float
  485. {
  486. return $contractMonth <= self::EXEMPT_THRESHOLD_MONTH ? 0.0 : $fnmPercentage;
  487. }
  488. private function resolveDueDate(?FranchiseeContract $contract, Carbon $referenceDate): Carbon
  489. {
  490. $dueDay = (int) ($contract?->invoice_due_date ?? 10);
  491. $dueDay = max(1, min(28, $dueDay));
  492. return $referenceDate->copy()->addMonthNoOverflow()->day($dueDay);
  493. }
  494. private function existingReceivable(int $unitId, int $contractMonth): bool
  495. {
  496. return TbrCalculation::where('unit_id', $unitId)
  497. ->where('contract_month_reference', $contractMonth)
  498. ->where('receivable_generated', true)
  499. ->exists();
  500. }
  501. }