TbrCalculationService.php 25 KB

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