TbrCalculationRulesTest.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  1. <?php
  2. namespace Tests\Unit\Financeiro;
  3. use App\Models\City;
  4. use App\Models\Country;
  5. use App\Models\FranchiseeAccountReceive;
  6. use App\Models\FranchiseeContract;
  7. use App\Models\InhabitantClassification;
  8. use App\Models\MunicipalitySize;
  9. use App\Models\State;
  10. use App\Models\Student;
  11. use App\Models\StudentContract;
  12. use App\Models\StudentContractInstallment;
  13. use App\Models\Tbr;
  14. use App\Models\TbrCalculation;
  15. use App\Models\Unit;
  16. use App\Models\UnitAccountPayable;
  17. use App\Models\UnitAccountReceivable;
  18. use App\Models\UnitFinancial;
  19. use App\Services\TbrCalculationService;
  20. use Illuminate\Foundation\Testing\RefreshDatabase;
  21. use Illuminate\Support\Facades\Bus;
  22. use Illuminate\Validation\ValidationException;
  23. use Tests\TestCase;
  24. /**
  25. * Regras de cobrança do contrato da unidade (Royalties / FNM / Taxa de Manutenção).
  26. *
  27. * Documentação de apoio: docs/calculo-royalties.md
  28. *
  29. * Resumo das regras validadas aqui (ver o md para o texto original do cliente):
  30. * - Royalties: meses 1-3 isento; meses 4-60 = maior entre % fixo da faixa de
  31. * porte (Classificação de Habitantes) x TBR, ou 8% do faturamento da unidade.
  32. * - FNM: meses 1-3 isento; meses 4-60 = maior entre % fixo do FNM (tabela TBR
  33. * do ano) x TBR, ou 2% do faturamento da unidade.
  34. * - Taxa de Manutenção: meses 1-60, sempre 30% da TBR — nunca isenta, nunca
  35. * comparada com faturamento, sem flag de liga/desliga.
  36. * - A partir do mês 61 (fim do primeiro ciclo de 60 meses) o contrato entra em
  37. * renovação: a faixa de royalties passa a vir de is_renewal=true, com o mês
  38. * de contrato "enrolado" de volta para o intervalo 1-60.
  39. * - Critério aplicado (tbr_fixo | percentual_faturamento | nao_cobrado) é
  40. * sempre gravado, como pedido no md.
  41. *
  42. * Cenário base usado na maioria dos testes:
  43. * - TBR = R$ 1.000,00 configurada em `tbrs` para 2026
  44. * - Porte GP: meses 1-3 = 0%, meses 4-12 = 75%, meses 13-60 = 100%
  45. * - FNM fixo = 20% da TBR | Manutenção = 30% da TBR
  46. * - Royalties sobre faturamento = 8% | FNM sobre faturamento = 2%
  47. * - Contrato iniciado em 01/01/2026
  48. *
  49. * Cada teste tem em cima um bloco Regra / Cenário / Espera para conferir a
  50. * regra de negócio, não só se o teste passa.
  51. */
  52. class TbrCalculationRulesTest extends TestCase
  53. {
  54. use RefreshDatabase;
  55. private TbrCalculationService $service;
  56. private Unit $unit;
  57. private MunicipalitySize $sizeGp;
  58. /** @var array<int, array{student_id:int, contract_id:int}> aluno/contrato reaproveitado por unidade */
  59. private array $studentContracts = [];
  60. protected function setUp(): void
  61. {
  62. parent::setUp();
  63. Bus::fake();
  64. $this->service = new TbrCalculationService;
  65. $this->unit = $this->makeUnit();
  66. $this->sizeGp = $this->makeSize('GP', 'De 100 mil a 200 mil habitantes');
  67. $this->makeBrackets($this->sizeGp->id, [
  68. [1, 3, 0.0],
  69. [4, 12, 0.75],
  70. [13, 60, 1.00],
  71. ]);
  72. $this->makeTbrYear(2026, 1000.00);
  73. }
  74. // ---------------------------------------------------------------- helpers
  75. private function makeUnit(string $name = 'Unidade Teste'): Unit
  76. {
  77. $country = Country::create(['name' => 'Brasil', 'code' => 'BR']);
  78. $state = State::create(['name' => 'Paraná', 'code' => 'PR', 'country_id' => $country->id]);
  79. $city = City::create(['name' => 'Maringá', 'country_id' => $country->id, 'state_id' => $state->id]);
  80. return Unit::create([
  81. 'fantasy_name' => $name,
  82. 'social_reason' => $name.' LTDA',
  83. 'cnpj' => '00000000000191',
  84. 'street' => 'Rua Teste',
  85. 'neighborhood' => 'Centro',
  86. 'postal_code' => '87000000',
  87. 'city_id' => $city->id,
  88. 'state_id' => $state->id,
  89. 'email' => 'unidade@teste.com',
  90. 'name_responsible' => 'Responsável Teste',
  91. ]);
  92. }
  93. private function makeSize(string $acronym, string $description): MunicipalitySize
  94. {
  95. return MunicipalitySize::create(['acronym' => $acronym, 'description' => $description]);
  96. }
  97. /** @param array<int, array{0:int,1:?int,2:float}> $brackets [start, end, percentual] */
  98. private function makeBrackets(int $sizeId, array $brackets, bool $isRenewal = false): void
  99. {
  100. foreach ($brackets as [$start, $end, $percentage]) {
  101. InhabitantClassification::create([
  102. 'municipality_size_id' => $sizeId,
  103. 'description' => ($isRenewal ? 'Renovação ' : 'Faixa ')."{$start}-{$end}",
  104. 'start' => $start,
  105. 'end' => $end,
  106. 'tbr_percentage' => $percentage,
  107. 'is_renewal' => $isRenewal,
  108. ]);
  109. }
  110. }
  111. private function makeTbrYear(int $year, float $value, float $fnm = 0.20, float $maintenance = 0.30): Tbr
  112. {
  113. return Tbr::create([
  114. 'year' => $year,
  115. 'tbr_value' => $value,
  116. 'royalties_percentage' => 0.08,
  117. 'fnm_percentage' => $fnm,
  118. 'maintenance_percentage' => $maintenance,
  119. ]);
  120. }
  121. private function makeContract(array $overrides = []): FranchiseeContract
  122. {
  123. return FranchiseeContract::create(array_merge([
  124. 'unit_id' => $this->unit->id,
  125. 'protocol' => 1,
  126. 'name' => 'Contrato de Franquia',
  127. 'description' => 'Contrato de teste',
  128. 'start_date' => '2026-01-01',
  129. 'end_date' => '2031-01-01',
  130. 'signature_date' => '2026-01-01',
  131. 'validity_months' => 60,
  132. 'invoice_due_date' => 10,
  133. 'municipality_size_id' => $this->sizeGp->id,
  134. 'tbr_fixed_value' => 1000.00,
  135. ], $overrides));
  136. }
  137. /** Aluno + contrato mínimos para pendurar as parcelas que formam o faturamento. */
  138. private function studentContractFor(int $unitId): array
  139. {
  140. if (isset($this->studentContracts[$unitId])) {
  141. return $this->studentContracts[$unitId];
  142. }
  143. $student = Student::create([
  144. 'name' => 'Aluno Teste',
  145. 'unit_id' => $unitId,
  146. 'status' => 'active',
  147. ]);
  148. $contract = StudentContract::create([
  149. 'student_id' => $student->id,
  150. 'unit_id' => $unitId,
  151. 'status' => 'active',
  152. ]);
  153. return $this->studentContracts[$unitId] = [
  154. 'student_id' => $student->id,
  155. 'contract_id' => $contract->id,
  156. ];
  157. }
  158. private function makeInstallment(array $overrides = []): StudentContractInstallment
  159. {
  160. $unitId = $overrides['unit_id'] ?? $this->unit->id;
  161. $owner = $this->studentContractFor($unitId);
  162. return StudentContractInstallment::create(array_merge([
  163. 'student_contract_id' => $owner['contract_id'],
  164. 'unit_id' => $unitId,
  165. 'student_id' => $owner['student_id'],
  166. 'type' => 'monthly',
  167. 'history' => 'Mensalidade',
  168. 'installment_number' => 1,
  169. 'total_installments' => 12,
  170. 'value' => 100.00,
  171. 'due_date' => '2026-04-10',
  172. 'status' => 'pending',
  173. ], $overrides));
  174. }
  175. /** Atalho: preview do cenário base para uma competência, com faturamento informado. */
  176. private function preview(int $year, int $month, float $revenue = 0.0): array
  177. {
  178. return $this->service->preview([
  179. 'unit_id' => $this->unit->id,
  180. 'reference_year' => $year,
  181. 'reference_month' => $month,
  182. 'revenue_value' => $revenue,
  183. ]);
  184. }
  185. // ------------------------------------------------- mês de contrato / isenção
  186. /**
  187. * Regra: Como o sistema descobre em que "mês de contrato" a competência cai.
  188. *
  189. * Cenário: Contrato iniciado em 01/01/2026; consulta várias competências.
  190. *
  191. * Espera:
  192. * - 01/2026 -> mês 1
  193. * - 03/2026 -> mês 3
  194. * - 04/2026 -> mês 4
  195. * - 01/2027 -> mês 13
  196. */
  197. public function test_mes_de_contrato_conta_a_partir_do_start_date(): void
  198. {
  199. $this->makeContract();
  200. $this->assertSame(1, $this->preview(2026, 1, 1000)['contract_month_reference']);
  201. $this->assertSame(3, $this->preview(2026, 3, 1000)['contract_month_reference']);
  202. $this->assertSame(4, $this->preview(2026, 4, 1000)['contract_month_reference']);
  203. $this->assertSame(13, $this->preview(2027, 1, 1000)['contract_month_reference']);
  204. }
  205. /**
  206. * Regra: Competência anterior ao início do contrato não pode gerar mês zero ou negativo.
  207. *
  208. * Cenário: Contrato inicia 01/01/2026 e pede-se a competência 10/2025.
  209. *
  210. * Espera: mês de contrato = 1.
  211. */
  212. public function test_competencia_anterior_ao_inicio_do_contrato_e_tratada_como_mes_1(): void
  213. {
  214. $this->makeContract();
  215. $this->assertSame(1, $this->preview(2025, 10, 1000)['contract_month_reference']);
  216. }
  217. /**
  218. * Regra (md "Royalties" e "FNM"): meses 1 a 3 = isento.
  219. *
  220. * Cenário: Faturamento alto (R$ 40.000), que normalmente geraria R$ 3.200 de
  221. * royalties e R$ 800 de FNM.
  222. *
  223. * Espera:
  224. * - Royalties = R$ 0,00 nos três meses
  225. * - FNM = R$ 0,00 nos três meses
  226. * - critério registrado = 'tbr_fixo'
  227. */
  228. public function test_meses_1_a_3_isentam_royalties_e_fnm(): void
  229. {
  230. $this->makeContract();
  231. foreach ([1, 2, 3] as $month) {
  232. $result = $this->preview(2026, $month, 40000);
  233. $this->assertSame(0.0, $result['royalties_effective_value'], "mês {$month}");
  234. $this->assertSame(0.0, $result['fnm_effective_value'], "mês {$month}");
  235. $this->assertSame('tbr_fixo', $result['royalties_applied_criteria'], "mês {$month}");
  236. }
  237. }
  238. /**
  239. * Regra (md "Taxa de Manutenção"): meses 1 a 60 = 30% do fixo da TBR, sem exceção.
  240. * A isenção de Royalties/FNM dos meses 1-3 não se aplica à Manutenção.
  241. *
  242. * Cenário: Competência 02/2026 (mês 2), TBR de R$ 1.000,00.
  243. *
  244. * Espera: Manutenção = R$ 300,00; total do título = R$ 300,00.
  245. */
  246. public function test_taxa_de_manutencao_e_cobrada_mesmo_nos_meses_isentos(): void
  247. {
  248. $this->makeContract();
  249. $result = $this->preview(2026, 2, 40000);
  250. $this->assertSame(300.0, $result['maintenance_effective_value']);
  251. $this->assertSame(300.0, $result['final_value']);
  252. }
  253. /**
  254. * Regra: A isenção termina exatamente no fim do mês 3.
  255. *
  256. * Cenário: Competência 04/2026 (mês 4), faturamento baixo.
  257. *
  258. * Espera: Royalties > 0 e FNM > 0.
  259. */
  260. public function test_isencao_acaba_no_mes_4(): void
  261. {
  262. $this->makeContract();
  263. $result = $this->preview(2026, 4, 1000);
  264. $this->assertGreaterThan(0, $result['royalties_effective_value']);
  265. $this->assertGreaterThan(0, $result['fnm_effective_value']);
  266. }
  267. // ---------------------------------------------- Royalties: regra do maior valor
  268. /**
  269. * Regra (md "Royalties" meses 4-60): maior entre % fixo x TBR ou 8% do faturamento.
  270. * O % fixo é a taxa-base configurada em "Configurações do TBR"
  271. * (tbrs.royalties_percentage, 8% no cenário base) multiplicada pelo percentual
  272. * da faixa de porte (Classificação de Habitantes) — a faixa é um multiplicador,
  273. * não o percentual final.
  274. *
  275. * Cenário: Mês 4, faixa GP = 75% (multiplicador), taxa-base = 8% -> fixo efetivo
  276. * = 6% da TBR = R$ 60,00 (TBR R$ 1.000,00). Faturamento baixo (R$ 500,00, 8% = R$ 40,00).
  277. *
  278. * Espera: Royalties = R$ 60,00, critério = 'tbr_fixo'.
  279. */
  280. public function test_royalties_usa_valor_fixo_quando_faturamento_e_baixo(): void
  281. {
  282. $this->makeContract();
  283. $result = $this->preview(2026, 4, 500.00);
  284. $this->assertSame(60.0, $result['royalties_effective_value']);
  285. $this->assertSame(0.06, $result['royalties_effective_percentage']);
  286. $this->assertSame('tbr_fixo', $result['royalties_applied_criteria']);
  287. }
  288. /**
  289. * Regra (md "Royalties" meses 4-60): quando 8% do faturamento supera o fixo, vence o faturamento.
  290. *
  291. * Cenário: Mês 4, TBR R$ 1.000,00 (fixo R$ 750,00), faturamento R$ 40.000,00 (8% = R$ 3.200,00).
  292. *
  293. * Espera: Royalties = R$ 3.200,00, critério = 'percentual_faturamento'.
  294. */
  295. public function test_royalties_usa_percentual_do_faturamento_quando_faturamento_e_alto(): void
  296. {
  297. $this->makeContract();
  298. $result = $this->preview(2026, 4, 40000.00);
  299. $this->assertSame(3200.0, $result['royalties_effective_value']);
  300. $this->assertSame(0.08, $result['royalties_effective_percentage']);
  301. $this->assertSame('percentual_faturamento', $result['royalties_applied_criteria']);
  302. }
  303. /**
  304. * Regra: Critério de desempate — valor igual mantém o fixo da TBR (comparação é >=).
  305. *
  306. * Cenário: Fixo do mês 4 = 8% (base) x 75% (faixa GP) = 6% x TBR R$ 1.000 = R$ 60,00.
  307. * Faturamento R$ 750,00, em que 8% = R$ 60,00 = exatamente o valor fixo.
  308. *
  309. * Espera: Royalties = R$ 60,00, critério = 'tbr_fixo', percentual gravado = 0,06.
  310. */
  311. public function test_empate_entre_fixo_e_faturamento_mantem_o_fixo_da_tbr(): void
  312. {
  313. $this->makeContract();
  314. $result = $this->preview(2026, 4, 750.00);
  315. $this->assertSame(60.0, $result['royalties_effective_value']);
  316. $this->assertSame('tbr_fixo', $result['royalties_applied_criteria']);
  317. $this->assertSame(0.06, $result['royalties_effective_percentage']);
  318. }
  319. // --------------------------------------------------------- FNM: regra do maior valor
  320. /**
  321. * Regra (md "FNM" meses 4-60): maior entre % fixo do FNM (tabela TBR do ano) x TBR
  322. * ou 2% do faturamento. O percentual fixo vem de tbrs.fnm_percentage (20% no cenário base).
  323. *
  324. * Cenário: Mês 4, TBR R$ 1.000,00 (fixo 20% = R$ 200,00), faturamento R$ 1.000,00 (2% = R$ 20,00).
  325. *
  326. * Espera: FNM = R$ 200,00, percentual efetivo = 0,20.
  327. */
  328. public function test_fnm_usa_valor_fixo_quando_faturamento_e_baixo(): void
  329. {
  330. $this->makeContract();
  331. $result = $this->preview(2026, 4, 1000.00);
  332. $this->assertSame(200.0, $result['fnm_effective_value']);
  333. $this->assertSame(0.20, $result['fnm_effective_percentage']);
  334. }
  335. /**
  336. * Regra (md "FNM" meses 4-60): quando 2% do faturamento supera o fixo, vence o faturamento.
  337. *
  338. * Cenário: Mês 4, TBR R$ 1.000,00 (fixo R$ 200,00), faturamento R$ 40.000,00 (2% = R$ 800,00).
  339. *
  340. * Espera: FNM = R$ 800,00, percentual efetivo = 0,02.
  341. */
  342. public function test_fnm_usa_percentual_do_faturamento_quando_faturamento_e_alto(): void
  343. {
  344. $this->makeContract();
  345. $result = $this->preview(2026, 4, 40000.00);
  346. $this->assertSame(800.0, $result['fnm_effective_value']);
  347. $this->assertSame(0.02, $result['fnm_effective_percentage']);
  348. }
  349. /**
  350. * Regra: Royalties e FNM são comparados de forma independente — um pode cair no
  351. * fixo e o outro no percentual de faturamento no mesmo mês.
  352. *
  353. * Cenário: Faturamento R$ 9.500,00: 8% = R$ 760 (passa do fixo de royalties, R$ 750),
  354. * mas 2% = R$ 190 (fica abaixo do fixo de FNM, R$ 200).
  355. *
  356. * Espera:
  357. * - Royalties = R$ 760,00 por 'percentual_faturamento'
  358. * - FNM = R$ 200,00 pelo fixo (percentual 0,20)
  359. */
  360. public function test_royalties_e_fnm_podem_usar_criterios_diferentes_no_mesmo_mes(): void
  361. {
  362. $this->makeContract();
  363. $result = $this->preview(2026, 4, 9500.00);
  364. $this->assertSame(760.0, $result['royalties_effective_value']);
  365. $this->assertSame('percentual_faturamento', $result['royalties_applied_criteria']);
  366. $this->assertSame(200.0, $result['fnm_effective_value']);
  367. $this->assertSame(0.20, $result['fnm_effective_percentage']);
  368. }
  369. // ------------------------------------------------------------- Taxa de Manutenção
  370. /**
  371. * Regra (md "Taxa de Manutenção"): 30% do fixo da TBR, meses 1-60, nunca comparada
  372. * com o faturamento — não existe "maior valor" para a manutenção.
  373. *
  374. * Cenário: Mês 6, TBR R$ 1.000,00, faturamento altíssimo (R$ 1.000.000,00).
  375. *
  376. * Espera: Manutenção = R$ 300,00 de qualquer forma.
  377. */
  378. public function test_manutencao_nunca_e_comparada_com_o_faturamento(): void
  379. {
  380. $this->makeContract();
  381. $result = $this->preview(2026, 6, 1_000_000.00);
  382. $this->assertSame(300.0, $result['maintenance_effective_value']);
  383. $this->assertSame(0.30, $result['maintenance_effective_percentage']);
  384. }
  385. // --------------------------------------------- Classificação de Habitantes (porte)
  386. /**
  387. * Regra (md "Classificação de Habitantes"): a faixa de royalties muda conforme o
  388. * mês de contrato (4-12 x 13-60), dentro do mesmo porte.
  389. *
  390. * Cenário: Porte GP — mês 12 (75%) e mês 13 (100%).
  391. *
  392. * Espera: mês 12 -> R$ 750,00; mês 13 -> R$ 1.000,00.
  393. */
  394. public function test_faixa_de_royalties_muda_no_mes_13(): void
  395. {
  396. $this->makeContract();
  397. $this->makeTbrYear(2027, 1000.00);
  398. $mes12 = $this->preview(2026, 12, 1000);
  399. $mes13 = $this->preview(2027, 1, 1000);
  400. // 8% (base) x 75% (faixa 4-12) = 6%
  401. $this->assertSame(0.06, $mes12['royalties_bracket_percentage']);
  402. $this->assertSame(60.0, $mes12['royalties_bracket_value']);
  403. // 8% (base) x 100% (faixa 13-60) = 8%
  404. $this->assertSame(0.08, $mes13['royalties_bracket_percentage']);
  405. $this->assertSame(80.0, $mes13['royalties_bracket_value']);
  406. }
  407. /**
  408. * Regra (md "Classificação de Habitantes"): o porte do município do contrato
  409. * define qual faixa de royalties se aplica.
  410. *
  411. * Cenário: Contrato em porte MGP (multiplicador 100% no mês 4) no lugar de GP (75%).
  412. *
  413. * Espera: percentual efetivo da faixa = 8% (base) x 100% = 0,08; Royalties = R$ 80,00
  414. * em vez dos R$ 60,00 do porte GP.
  415. */
  416. public function test_porte_maior_do_municipio_cobra_percentual_maior(): void
  417. {
  418. $sizeMgp = $this->makeSize('MGP', 'Acima de 200 mil habitantes');
  419. $this->makeBrackets($sizeMgp->id, [[1, 3, 0.0], [4, 12, 1.00], [13, 60, 1.50]]);
  420. $this->makeContract(['municipality_size_id' => $sizeMgp->id]);
  421. $result = $this->preview(2026, 4, 1000);
  422. $this->assertSame(0.08, $result['royalties_bracket_percentage']);
  423. $this->assertSame(80.0, $result['royalties_effective_value']);
  424. }
  425. /**
  426. * Regra: Contrato sem faixa cadastrada para o porte/mês, e sem faixa de renovação
  427. * cobrindo o período, não calcula.
  428. *
  429. * Cenário: Faixas cadastradas só até o mês 60, sem nenhuma faixa de renovação;
  430. * competência cai no mês 61.
  431. *
  432. * Espera: ValidationException 'Não foi encontrada faixa de royalties'.
  433. */
  434. public function test_erro_quando_nao_existe_faixa_nem_de_renovacao_para_o_mes(): void
  435. {
  436. $this->makeContract();
  437. $this->makeTbrYear(2031, 1000.00);
  438. $this->expectException(ValidationException::class);
  439. $this->expectExceptionMessage('Não foi encontrada faixa de royalties');
  440. $this->preview(2031, 1, 1000); // mês 61, sem faixa de renovação cadastrada
  441. }
  442. // ---------------------------------------------------- Renovação (mês 61 em diante)
  443. /**
  444. * Regra: A partir do mês 61 (fim do primeiro ciclo de 60 meses), a faixa de
  445. * royalties passa a vir de is_renewal=true — o contrato "renova" e continua sendo
  446. * cobrado, em vez de estourar erro.
  447. *
  448. * Cenário: Faixa de renovação do porte GP cobrindo 1-60, com multiplicador 100%
  449. * (igual à última faixa normal). Competência cai no mês 61 do contrato.
  450. *
  451. * Espera: encontra a faixa de renovação; percentual efetivo = 8% (base) x 100% = 0,08;
  452. * Royalties = R$ 80,00 (empata com os 8% de faturamento de R$ 1.000,00, fica no fixo).
  453. */
  454. public function test_mes_61_usa_a_faixa_de_renovacao(): void
  455. {
  456. $this->makeBrackets($this->sizeGp->id, [[1, 60, 1.00]], true);
  457. $this->makeContract();
  458. $this->makeTbrYear(2031, 1000.00);
  459. $result = $this->preview(2031, 1, 1000); // mês de contrato 61
  460. $this->assertSame(0.08, $result['royalties_bracket_percentage']);
  461. $this->assertSame(80.0, $result['royalties_effective_value']);
  462. }
  463. /**
  464. * Regra: O mês de contrato dentro do ciclo de renovação é "enrolado" de volta para
  465. * o intervalo 1-60 (mês 61 = mês 1 da renovação, mês 120 = mês 60 da renovação).
  466. *
  467. * Cenário: Faixa de renovação com duas fatias (1-12 = 60%, 13-60 = 100%), simulando
  468. * uma nova isenção/escalonamento dentro do próprio ciclo de renovação.
  469. *
  470. * Espera (percentual efetivo = 8% base x multiplicador da faixa de renovação):
  471. * - mês 65 do contrato (5º mês da renovação, multiplicador 60%) -> 8% x 60% = 0,048
  472. * - mês 120 do contrato (60º mês da renovação, multiplicador 100%) -> 8% x 100% = 0,08
  473. */
  474. public function test_mes_de_renovacao_e_calculado_dentro_do_ciclo_de_60_meses(): void
  475. {
  476. $this->makeBrackets($this->sizeGp->id, [[1, 12, 0.60], [13, 60, 1.00]], true);
  477. $this->makeContract();
  478. $this->makeTbrYear(2031, 1000.00); // mês 61
  479. $this->makeTbrYear(2035, 1000.00); // mês 61 + 59 = mês 120
  480. $mes65 = $this->preview(2031, 5, 1000); // mês de contrato 65 -> renovação mês 5
  481. $mes120 = $this->preview(2035, 12, 1000); // mês de contrato 120 -> renovação mês 60
  482. $this->assertSame(0.048, $mes65['royalties_bracket_percentage']);
  483. $this->assertSame(0.08, $mes120['royalties_bracket_percentage']);
  484. }
  485. /**
  486. * Regra: Passado um segundo ciclo completo de 60 meses (mês 121 em diante), o
  487. * ciclo de renovação recomeça do zero.
  488. *
  489. * Cenário: Faixa de renovação única (1-60, multiplicador 100%); competência cai no mês 121.
  490. *
  491. * Espera: continua encontrando a faixa de renovação (não estoura erro); percentual
  492. * efetivo = 8% (base) x 100% = 0,08.
  493. */
  494. public function test_segundo_ciclo_de_renovacao_reinicia_a_contagem(): void
  495. {
  496. $this->makeBrackets($this->sizeGp->id, [[1, 60, 1.00]], true);
  497. $this->makeContract();
  498. $this->makeTbrYear(2036, 1000.00); // mês de contrato 121
  499. $result = $this->preview(2036, 1, 1000);
  500. $this->assertSame(0.08, $result['royalties_bracket_percentage']);
  501. }
  502. // --------------------------------------------------------------- valor da TBR
  503. /**
  504. * Regra (md): o percentual/valor fixo vem da "TBR Fixo do ano (Atribuído em
  505. * Configurações do TBR)". A tabela `tbrs` do ano cadastrada pelo admin manda
  506. * sobre o valor gravado no contrato.
  507. *
  508. * Cenário: tbrs/2026 = R$ 1.000,00 (setUp) e contrato com tbr_fixed_value = R$ 2.000,00.
  509. * Faturamento baixo (R$ 500,00) para o fixo (R$ 60,00) prevalecer sobre o percentual.
  510. *
  511. * Espera: TBR usada = R$ 1.000,00; Royalties = R$ 60,00; Manutenção = R$ 300,00.
  512. */
  513. public function test_tbr_do_ano_configurada_pelo_admin_tem_prioridade_sobre_o_contrato(): void
  514. {
  515. $this->makeContract(['tbr_fixed_value' => 2000.00]);
  516. $result = $this->preview(2026, 4, 500);
  517. $this->assertSame(1000.0, $result['tbr_value']);
  518. $this->assertSame(60.0, $result['royalties_effective_value']);
  519. $this->assertSame(300.0, $result['maintenance_effective_value']);
  520. }
  521. /**
  522. * Regra: Cada ano de referência usa sua própria configuração de TBR.
  523. *
  524. * Cenário: tbrs/2026 = R$ 1.000,00 (setUp), tbrs/2027 = R$ 2.000,00.
  525. *
  526. * Espera: mês em 2026 usa R$ 1.000,00; mês em 2027 usa R$ 2.000,00.
  527. */
  528. public function test_cada_ano_usa_a_sua_propria_configuracao_de_tbr(): void
  529. {
  530. $this->makeContract();
  531. $this->makeTbrYear(2027, 2000.00);
  532. $this->assertSame(1000.0, $this->preview(2026, 4, 1000)['tbr_value']);
  533. $this->assertSame(2000.0, $this->preview(2027, 1, 1000)['tbr_value']);
  534. }
  535. /**
  536. * Regra: Quando o ano de referência não está configurado em `tbrs`, usa-se o
  537. * valor gravado no contrato (tbr_fixed_value) como reserva.
  538. *
  539. * Cenário: Competência em 2030 (sem linha em `tbrs`), contrato com tbr_fixed_value = R$ 1.500,00.
  540. *
  541. * Espera: TBR usada = R$ 1.500,00.
  542. */
  543. public function test_usa_a_tbr_do_contrato_quando_o_ano_nao_esta_configurado(): void
  544. {
  545. $this->makeContract(['tbr_fixed_value' => 1500.00]);
  546. $result = $this->preview(2030, 1, 1000);
  547. $this->assertSame(1500.0, $result['tbr_value']);
  548. }
  549. /**
  550. * Regra: Sem TBR configurada nem no ano nem no contrato, o cálculo não pode seguir.
  551. *
  552. * Cenário: Ano sem `tbrs` e contrato com tbr_fixed_value = 0.
  553. *
  554. * Espera: ValidationException.
  555. */
  556. public function test_erro_quando_nao_ha_tbr_no_ano_nem_no_contrato(): void
  557. {
  558. $this->makeContract(['tbr_fixed_value' => 0]);
  559. $this->expectException(ValidationException::class);
  560. $this->preview(2030, 1, 1000);
  561. }
  562. /**
  563. * Regra: Os percentuais fixos de FNM e Manutenção vêm da tabela `tbrs` do ano.
  564. *
  565. * Cenário: tbrs/2027 com FNM = 25% e Manutenção = 35%.
  566. *
  567. * Espera: FNM fixo = R$ 250,00 (25% x 1000) e Manutenção = R$ 350,00 (35% x 1000).
  568. */
  569. public function test_percentuais_de_fnm_e_manutencao_vem_da_tabela_do_ano(): void
  570. {
  571. $this->makeContract();
  572. $this->makeTbrYear(2027, 1000.00, fnm: 0.25, maintenance: 0.35);
  573. $result = $this->preview(2027, 1, 1000); // mês 13, sem faturamento suficiente pra superar o fixo
  574. $this->assertSame(250.0, $result['fnm_bracket_value']);
  575. $this->assertSame(350.0, $result['maintenance_effective_value']);
  576. }
  577. // ------------------------------------------------ flags charge_roi / charge_fnm
  578. /**
  579. * Regra (md "UnitActionPage"): quando a cobrança de Royalties (ROI) está desativada
  580. * para a unidade, o valor efetivo de royalties é zerado.
  581. *
  582. * Cenário: `unit_financials.charge_roi = false`.
  583. *
  584. * Espera: royalties_effective_value = 0, critério = 'nao_cobrado'; Manutenção continua.
  585. */
  586. public function test_charge_roi_desligado_zera_os_royalties(): void
  587. {
  588. $this->makeContract();
  589. UnitFinancial::create(['unit_id' => $this->unit->id, 'charge_roi' => false, 'charge_fnm' => true]);
  590. $result = $this->preview(2026, 4, 40000);
  591. $this->assertSame(0.0, $result['royalties_effective_value']);
  592. $this->assertSame('nao_cobrado', $result['royalties_applied_criteria']);
  593. $this->assertGreaterThan(0, $result['maintenance_effective_value']);
  594. }
  595. /**
  596. * Regra: Com charge_roi desligado, o cálculo nem exige que exista faixa de
  597. * royalties cadastrada para o porte/mês (não busca a faixa).
  598. *
  599. * Cenário: Nenhuma faixa cadastrada para o porte MP; charge_roi = false.
  600. *
  601. * Espera: preview não lança exceção; royalties = 0.
  602. */
  603. public function test_charge_roi_desligado_dispensa_a_existencia_de_faixa(): void
  604. {
  605. $sizeMp = $this->makeSize('MP', 'Sem faixas cadastradas');
  606. $this->makeContract(['municipality_size_id' => $sizeMp->id]);
  607. UnitFinancial::create(['unit_id' => $this->unit->id, 'charge_roi' => false, 'charge_fnm' => true]);
  608. $result = $this->preview(2026, 4, 1000);
  609. $this->assertSame(0.0, $result['royalties_effective_value']);
  610. $this->assertNull($result['royalties_bracket_id']);
  611. }
  612. /**
  613. * Regra: charge_fnm desligado zera apenas o FNM.
  614. *
  615. * Cenário: `unit_financials.charge_fnm = false`.
  616. *
  617. * Espera: fnm_effective_value = 0; royalties e manutenção continuam normais.
  618. */
  619. public function test_charge_fnm_desligado_zera_o_fnm(): void
  620. {
  621. $this->makeContract();
  622. UnitFinancial::create(['unit_id' => $this->unit->id, 'charge_roi' => true, 'charge_fnm' => false]);
  623. $result = $this->preview(2026, 4, 1000);
  624. $this->assertSame(0.0, $result['fnm_effective_value']);
  625. $this->assertGreaterThan(0, $result['royalties_effective_value']);
  626. }
  627. /**
  628. * Regra: Unidade sem registro em `unit_financials` cobra normalmente (default seguro = cobrar).
  629. *
  630. * Cenário: Nenhum `UnitFinancial` criado para a unidade.
  631. *
  632. * Espera: royalties e FNM calculados normalmente (> 0).
  633. */
  634. public function test_unidade_sem_registro_financeiro_cobra_royalties_e_fnm(): void
  635. {
  636. $this->makeContract();
  637. $result = $this->preview(2026, 4, 1000);
  638. $this->assertGreaterThan(0, $result['royalties_effective_value']);
  639. $this->assertGreaterThan(0, $result['fnm_effective_value']);
  640. }
  641. /**
  642. * Regra (md "Taxa de Manutenção"): a manutenção não tem flag de liga/desliga —
  643. * é sempre cobrada, mesmo com charge_roi e charge_fnm desligados.
  644. *
  645. * Cenário: charge_roi = false e charge_fnm = false.
  646. *
  647. * Espera: Manutenção = R$ 300,00; total = R$ 300,00.
  648. */
  649. public function test_manutencao_e_cobrada_mesmo_com_as_duas_flags_desligadas(): void
  650. {
  651. $this->makeContract();
  652. UnitFinancial::create(['unit_id' => $this->unit->id, 'charge_roi' => false, 'charge_fnm' => false]);
  653. $result = $this->preview(2026, 4, 1000);
  654. $this->assertSame(300.0, $result['maintenance_effective_value']);
  655. $this->assertSame(300.0, $result['final_value']);
  656. }
  657. // ---------------------------------------------------------- composição do faturamento
  658. /**
  659. * Regra: O faturamento-base do TBR soma parcelas de aluno, recebíveis avulsos da
  660. * unidade e contas vinculadas pela franqueadora (origin=manual_unit).
  661. *
  662. * Cenário: 1 parcela de R$ 100, 1 recebível avulso de R$ 50, 1 conta da matriz
  663. * vinculada de R$ 30, todos com vencimento no mês de referência.
  664. *
  665. * Espera: faturamento resolvido = R$ 180,00.
  666. */
  667. public function test_faturamento_soma_parcelas_recebiveis_e_contas_da_matriz(): void
  668. {
  669. $this->makeInstallment(['value' => 100, 'due_date' => '2026-04-10']);
  670. UnitAccountReceivable::create([
  671. 'unit_id' => $this->unit->id,
  672. 'history' => 'Avulso',
  673. 'value' => 50,
  674. 'due_date' => '2026-04-15',
  675. 'status' => 'pending',
  676. ]);
  677. FranchiseeAccountReceive::create([
  678. 'unit_id' => $this->unit->id,
  679. 'origin' => 'manual_unit',
  680. 'history' => 'Conta vinculada',
  681. 'value' => 30,
  682. 'due_date' => '2026-04-20',
  683. 'status' => 'pending',
  684. ]);
  685. $revenue = $this->service->resolveRevenue($this->unit->id, 2026, 4);
  686. $this->assertSame(180.0, $revenue);
  687. }
  688. /**
  689. * Regra: Parcelas canceladas e de outros meses não entram no faturamento.
  690. */
  691. public function test_faturamento_ignora_parcelas_canceladas_e_de_outros_meses(): void
  692. {
  693. $this->makeInstallment(['value' => 100, 'due_date' => '2026-04-10', 'status' => 'cancelled']);
  694. $this->makeInstallment(['value' => 200, 'due_date' => '2026-05-10', 'installment_number' => 2]);
  695. $revenue = $this->service->resolveRevenue($this->unit->id, 2026, 4);
  696. $this->assertSame(0.0, $revenue);
  697. }
  698. /**
  699. * Regra: Parcelas com soft delete não entram no faturamento.
  700. */
  701. public function test_faturamento_ignora_parcelas_excluidas(): void
  702. {
  703. $installment = $this->makeInstallment(['value' => 100, 'due_date' => '2026-04-10']);
  704. $installment->delete();
  705. $revenue = $this->service->resolveRevenue($this->unit->id, 2026, 4);
  706. $this->assertSame(0.0, $revenue);
  707. }
  708. /**
  709. * Regra: Recebíveis originados do próprio TBR não realimentam a base de faturamento.
  710. */
  711. public function test_faturamento_ignora_recebiveis_de_tbr(): void
  712. {
  713. FranchiseeAccountReceive::create([
  714. 'unit_id' => $this->unit->id,
  715. 'origin' => 'tbr',
  716. 'history' => 'Royalties gerado',
  717. 'value' => 500,
  718. 'due_date' => '2026-04-20',
  719. 'status' => 'pending',
  720. ]);
  721. $revenue = $this->service->resolveRevenue($this->unit->id, 2026, 4);
  722. $this->assertSame(0.0, $revenue);
  723. }
  724. /**
  725. * Regra: Movimentos de outra unidade não entram no faturamento consultado.
  726. */
  727. public function test_faturamento_ignora_movimento_de_outra_unidade(): void
  728. {
  729. $outraUnidade = $this->makeUnit('Outra Unidade');
  730. $this->makeInstallment(['unit_id' => $outraUnidade->id, 'value' => 999, 'due_date' => '2026-04-10']);
  731. $revenue = $this->service->resolveRevenue($this->unit->id, 2026, 4);
  732. $this->assertSame(0.0, $revenue);
  733. }
  734. /**
  735. * Regra: Faturamento informado manualmente sobrepõe o cálculo automático (override).
  736. */
  737. public function test_faturamento_informado_manualmente_substitui_o_calculo_automatico(): void
  738. {
  739. $this->makeContract();
  740. $this->makeInstallment(['value' => 100, 'due_date' => '2026-04-10']);
  741. $result = $this->service->preview([
  742. 'unit_id' => $this->unit->id,
  743. 'reference_year' => 2026,
  744. 'reference_month' => 4,
  745. 'revenue_value' => 40000,
  746. ]);
  747. $this->assertSame(40000.0, $result['revenue_value']);
  748. $this->assertSame('percentual_faturamento', $result['royalties_applied_criteria']);
  749. }
  750. // -------------------------------------------------------------- contrato / erros
  751. /**
  752. * Regra: Unidade sem contrato cadastrado não calcula.
  753. */
  754. public function test_erro_quando_a_unidade_nao_tem_contrato(): void
  755. {
  756. $this->expectException(ValidationException::class);
  757. $this->expectExceptionMessage('Unidade não possui contrato cadastrado.');
  758. $this->preview(2026, 4, 1000);
  759. }
  760. /**
  761. * Regra: Contrato sem porte do município definido não calcula.
  762. */
  763. public function test_erro_quando_o_contrato_nao_tem_porte_do_municipio(): void
  764. {
  765. $this->makeContract(['municipality_size_id' => null]);
  766. $this->expectException(ValidationException::class);
  767. $this->expectExceptionMessage('faixa de habitantes definida');
  768. $this->preview(2026, 4, 1000);
  769. }
  770. /**
  771. * Regra: Havendo mais de um contrato para a unidade, usa-se sempre o mais recente
  772. * (maior start_date).
  773. */
  774. public function test_usa_sempre_o_contrato_mais_recente_da_unidade(): void
  775. {
  776. $this->makeContract(['start_date' => '2020-01-01', 'tbr_fixed_value' => 500]);
  777. $this->makeContract(['start_date' => '2026-01-01', 'tbr_fixed_value' => 1500]);
  778. $result = $this->preview(2026, 1, 1000);
  779. $this->assertSame(1, $result['contract_month_reference']);
  780. }
  781. // -------------------------------------------------------------- persistência
  782. /**
  783. * Regra: calculate() grava em `tbr_calculations` exatamente os valores do preview
  784. * (a tabela de auditoria pedida no md).
  785. */
  786. public function test_calculate_grava_o_calculo_com_os_valores_do_preview(): void
  787. {
  788. $this->makeContract();
  789. $calculation = $this->service->calculate([
  790. 'unit_id' => $this->unit->id,
  791. 'reference_year' => 2026,
  792. 'reference_month' => 4,
  793. 'revenue_value' => 40000,
  794. ]);
  795. $this->assertInstanceOf(TbrCalculation::class, $calculation);
  796. $this->assertSame(4, $calculation->contract_month_reference);
  797. $this->assertSame('percentual_faturamento', $calculation->royalties_applied_criteria);
  798. $this->assertEquals(3200.0, (float) $calculation->royalties_effective_value);
  799. $this->assertEquals(800.0, (float) $calculation->fnm_effective_value);
  800. $this->assertEquals(300.0, (float) $calculation->maintenance_effective_value);
  801. $this->assertEquals(4300.0, (float) $calculation->final_value);
  802. $this->assertFalse($calculation->receivable_generated);
  803. }
  804. // ---------------------------------------------------------- geração de título
  805. /**
  806. * Regra (md "Tabela de Auditoria" + contas a receber/pagar): gerar o título cria
  807. * o recebível da matriz, os 3 detalhes por componente e o espelho na unidade
  808. * (conta a pagar), além de disparar a sincronização com o Asaas.
  809. */
  810. public function test_gerar_titulo_cria_recebivel_detalhes_e_conta_a_pagar(): void
  811. {
  812. $this->makeContract();
  813. $calculation = $this->service->calculate([
  814. 'unit_id' => $this->unit->id,
  815. 'reference_year' => 2026,
  816. 'reference_month' => 4,
  817. 'revenue_value' => 40000,
  818. ]);
  819. $receive = $this->service->generateReceivable($calculation->id);
  820. $this->assertSame(4300.0, (float) $receive->value);
  821. $this->assertCount(3, $receive->details);
  822. $this->assertDatabaseHas('unit_account_payables', [
  823. 'unit_id' => $this->unit->id,
  824. 'franchisee_account_receive_id' => $receive->id,
  825. 'origin' => UnitAccountPayable::ORIGIN_TBR,
  826. ]);
  827. $this->assertTrue($calculation->fresh()->receivable_generated);
  828. Bus::assertDispatched(\App\Jobs\SyncFranchiseeChargeJob::class);
  829. }
  830. /**
  831. * Regra: Não é possível gerar título duas vezes para o mesmo cálculo.
  832. */
  833. public function test_gerar_titulo_duas_vezes_para_o_mesmo_calculo_e_bloqueado(): void
  834. {
  835. $this->makeContract();
  836. $calculation = $this->service->calculate([
  837. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 1000,
  838. ]);
  839. $this->service->generateReceivable($calculation->id);
  840. $this->expectException(ValidationException::class);
  841. $this->expectExceptionMessage('Já existe um título gerado para este cálculo.');
  842. $this->service->generateReceivable($calculation->id);
  843. }
  844. /**
  845. * Regra: Não é possível gerar dois títulos para o mesmo mês de contrato da mesma unidade.
  846. */
  847. public function test_gerar_titulo_para_o_mesmo_mes_de_contrato_e_bloqueado(): void
  848. {
  849. $this->makeContract();
  850. $primeiro = $this->service->calculate([
  851. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 1000,
  852. ]);
  853. $this->service->generateReceivable($primeiro->id);
  854. $segundo = $this->service->calculate([
  855. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 2000,
  856. ]);
  857. $this->expectException(ValidationException::class);
  858. $this->expectExceptionMessage('mês de contrato');
  859. $this->service->generateReceivable($segundo->id);
  860. }
  861. /**
  862. * Regra: O preview avisa (flag) quando já existe título gerado para o mês de contrato,
  863. * sem impedir a nova simulação.
  864. */
  865. public function test_preview_avisa_quando_ja_existe_titulo_no_mes_de_contrato(): void
  866. {
  867. $this->makeContract();
  868. $calculation = $this->service->calculate([
  869. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 1000,
  870. ]);
  871. $this->service->generateReceivable($calculation->id);
  872. $result = $this->preview(2026, 4, 1000);
  873. $this->assertTrue($result['receivable_already_generated']);
  874. }
  875. // ----------------------------------------------------------------- vencimento
  876. public function test_vencimento_usa_o_dia_do_contrato_no_mes_seguinte(): void
  877. {
  878. $this->makeContract(['invoice_due_date' => 15]);
  879. $calculation = $this->service->calculate([
  880. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 1000,
  881. ]);
  882. $receive = $this->service->generateReceivable($calculation->id);
  883. $this->assertSame('2026-05-15', $receive->due_date->toDateString());
  884. }
  885. public function test_vencimento_cai_no_dia_10_quando_o_contrato_nao_informa(): void
  886. {
  887. $this->makeContract(['invoice_due_date' => null]);
  888. $calculation = $this->service->calculate([
  889. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 1000,
  890. ]);
  891. $receive = $this->service->generateReceivable($calculation->id);
  892. $this->assertSame('2026-05-10', $receive->due_date->toDateString());
  893. }
  894. public function test_vencimento_e_limitado_ao_dia_28(): void
  895. {
  896. $this->makeContract(['invoice_due_date' => 31]);
  897. $calculation = $this->service->calculate([
  898. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 1000,
  899. ]);
  900. $receive = $this->service->generateReceivable($calculation->id);
  901. $this->assertSame(28, $receive->due_date->day);
  902. }
  903. // ---------------------------------------------------------------------- lote
  904. public function test_lote_gera_titulo_para_cada_contrato_ativo(): void
  905. {
  906. $unidade2 = $this->makeUnit('Unidade 2');
  907. $this->makeContract();
  908. $this->makeContract(['unit_id' => $unidade2->id]);
  909. $result = $this->service->generateBatch(2026, 4, null);
  910. $this->assertSame(2, $result['generated_count']);
  911. $this->assertSame(0, $result['error_count']);
  912. }
  913. public function test_lote_pula_unidade_que_ja_tem_titulo_no_mes_de_contrato(): void
  914. {
  915. $this->makeContract();
  916. $calculation = $this->service->calculate([
  917. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 1000,
  918. ]);
  919. $this->service->generateReceivable($calculation->id);
  920. $result = $this->service->generateBatch(2026, 4, null);
  921. $this->assertSame(0, $result['generated_count']);
  922. $this->assertSame(1, $result['skipped_count']);
  923. }
  924. public function test_lote_ignora_contrato_encerrado_antes_da_competencia(): void
  925. {
  926. $this->makeContract(['end_date' => '2026-02-28']);
  927. $result = $this->service->generateBatch(2026, 4, null);
  928. $this->assertSame(0, $result['generated_count']);
  929. $this->assertSame(0, $result['skipped_count']);
  930. $this->assertSame(0, $result['error_count']);
  931. }
  932. public function test_lote_ignora_contrato_que_ainda_nao_comecou(): void
  933. {
  934. $this->makeContract(['start_date' => '2026-08-01']);
  935. $result = $this->service->generateBatch(2026, 4, null);
  936. $this->assertSame(0, $result['generated_count']);
  937. }
  938. public function test_lote_ignora_contrato_sem_porte_definido(): void
  939. {
  940. $this->makeContract(['municipality_size_id' => null]);
  941. $result = $this->service->generateBatch(2026, 4, null);
  942. $this->assertSame(0, $result['generated_count']);
  943. $this->assertSame(0, $result['error_count']);
  944. }
  945. public function test_lote_pode_ser_filtrado_por_unidade(): void
  946. {
  947. $unidade2 = $this->makeUnit('Unidade 2');
  948. $this->makeContract();
  949. $this->makeContract(['unit_id' => $unidade2->id]);
  950. $result = $this->service->generateBatch(2026, 4, [$unidade2->id]);
  951. $this->assertSame(1, $result['generated_count']);
  952. $this->assertSame($unidade2->id, $result['generated'][0]['unit_id']);
  953. }
  954. public function test_lote_reporta_erro_sem_interromper_as_demais_unidades(): void
  955. {
  956. $unidadeComErro = $this->makeUnit('Unidade Sem TBR');
  957. $this->makeContract(['tbr_fixed_value' => 0]);
  958. $this->makeContract(['unit_id' => $unidadeComErro->id, 'tbr_fixed_value' => 0]);
  959. Tbr::query()->delete();
  960. $result = $this->service->generateBatch(2030, 1, null);
  961. $this->assertSame(0, $result['generated_count']);
  962. $this->assertSame(2, $result['error_count']);
  963. }
  964. }