TbrCalculationService.php 26 KB

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