TbrCalculationRulesTest.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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 da faixa de porte x TBR
  270. * ou 8% do faturamento.
  271. *
  272. * Cenário: Mês 4, TBR R$ 1.000,00 (75% da faixa = R$ 750,00), faturamento
  273. * R$ 1.000,00 (8% = R$ 80,00).
  274. *
  275. * Espera: Royalties = R$ 750,00, critério = 'tbr_fixo'.
  276. */
  277. public function test_royalties_usa_valor_fixo_quando_faturamento_e_baixo(): void
  278. {
  279. $this->makeContract();
  280. $result = $this->preview(2026, 4, 1000.00);
  281. $this->assertSame(750.0, $result['royalties_effective_value']);
  282. $this->assertSame(0.75, $result['royalties_effective_percentage']);
  283. $this->assertSame('tbr_fixo', $result['royalties_applied_criteria']);
  284. }
  285. /**
  286. * Regra (md "Royalties" meses 4-60): quando 8% do faturamento supera o fixo, vence o faturamento.
  287. *
  288. * Cenário: Mês 4, TBR R$ 1.000,00 (fixo R$ 750,00), faturamento R$ 40.000,00 (8% = R$ 3.200,00).
  289. *
  290. * Espera: Royalties = R$ 3.200,00, critério = 'percentual_faturamento'.
  291. */
  292. public function test_royalties_usa_percentual_do_faturamento_quando_faturamento_e_alto(): void
  293. {
  294. $this->makeContract();
  295. $result = $this->preview(2026, 4, 40000.00);
  296. $this->assertSame(3200.0, $result['royalties_effective_value']);
  297. $this->assertSame(0.08, $result['royalties_effective_percentage']);
  298. $this->assertSame('percentual_faturamento', $result['royalties_applied_criteria']);
  299. }
  300. /**
  301. * Regra: Critério de desempate — valor igual mantém o fixo da TBR (comparação é >=).
  302. *
  303. * Cenário: Faturamento R$ 9.375,00, em que 8% = R$ 750,00 = exatamente o valor fixo.
  304. *
  305. * Espera: Royalties = R$ 750,00, critério = 'tbr_fixo', percentual gravado = 0,75 (o da faixa).
  306. */
  307. public function test_empate_entre_fixo_e_faturamento_mantem_o_fixo_da_tbr(): void
  308. {
  309. $this->makeContract();
  310. $result = $this->preview(2026, 4, 9375.00);
  311. $this->assertSame(750.0, $result['royalties_effective_value']);
  312. $this->assertSame('tbr_fixo', $result['royalties_applied_criteria']);
  313. $this->assertSame(0.75, $result['royalties_effective_percentage']);
  314. }
  315. // --------------------------------------------------------- FNM: regra do maior valor
  316. /**
  317. * Regra (md "FNM" meses 4-60): maior entre % fixo do FNM (tabela TBR do ano) x TBR
  318. * ou 2% do faturamento. O percentual fixo vem de tbrs.fnm_percentage (20% no cenário base).
  319. *
  320. * Cenário: Mês 4, TBR R$ 1.000,00 (fixo 20% = R$ 200,00), faturamento R$ 1.000,00 (2% = R$ 20,00).
  321. *
  322. * Espera: FNM = R$ 200,00, percentual efetivo = 0,20.
  323. */
  324. public function test_fnm_usa_valor_fixo_quando_faturamento_e_baixo(): void
  325. {
  326. $this->makeContract();
  327. $result = $this->preview(2026, 4, 1000.00);
  328. $this->assertSame(200.0, $result['fnm_effective_value']);
  329. $this->assertSame(0.20, $result['fnm_effective_percentage']);
  330. }
  331. /**
  332. * Regra (md "FNM" meses 4-60): quando 2% do faturamento supera o fixo, vence o faturamento.
  333. *
  334. * Cenário: Mês 4, TBR R$ 1.000,00 (fixo R$ 200,00), faturamento R$ 40.000,00 (2% = R$ 800,00).
  335. *
  336. * Espera: FNM = R$ 800,00, percentual efetivo = 0,02.
  337. */
  338. public function test_fnm_usa_percentual_do_faturamento_quando_faturamento_e_alto(): void
  339. {
  340. $this->makeContract();
  341. $result = $this->preview(2026, 4, 40000.00);
  342. $this->assertSame(800.0, $result['fnm_effective_value']);
  343. $this->assertSame(0.02, $result['fnm_effective_percentage']);
  344. }
  345. /**
  346. * Regra: Royalties e FNM são comparados de forma independente — um pode cair no
  347. * fixo e o outro no percentual de faturamento no mesmo mês.
  348. *
  349. * Cenário: Faturamento R$ 9.500,00: 8% = R$ 760 (passa do fixo de royalties, R$ 750),
  350. * mas 2% = R$ 190 (fica abaixo do fixo de FNM, R$ 200).
  351. *
  352. * Espera:
  353. * - Royalties = R$ 760,00 por 'percentual_faturamento'
  354. * - FNM = R$ 200,00 pelo fixo (percentual 0,20)
  355. */
  356. public function test_royalties_e_fnm_podem_usar_criterios_diferentes_no_mesmo_mes(): void
  357. {
  358. $this->makeContract();
  359. $result = $this->preview(2026, 4, 9500.00);
  360. $this->assertSame(760.0, $result['royalties_effective_value']);
  361. $this->assertSame('percentual_faturamento', $result['royalties_applied_criteria']);
  362. $this->assertSame(200.0, $result['fnm_effective_value']);
  363. $this->assertSame(0.20, $result['fnm_effective_percentage']);
  364. }
  365. // ------------------------------------------------------------- Taxa de Manutenção
  366. /**
  367. * Regra (md "Taxa de Manutenção"): 30% do fixo da TBR, meses 1-60, nunca comparada
  368. * com o faturamento — não existe "maior valor" para a manutenção.
  369. *
  370. * Cenário: Mês 6, TBR R$ 1.000,00, faturamento altíssimo (R$ 1.000.000,00).
  371. *
  372. * Espera: Manutenção = R$ 300,00 de qualquer forma.
  373. */
  374. public function test_manutencao_nunca_e_comparada_com_o_faturamento(): void
  375. {
  376. $this->makeContract();
  377. $result = $this->preview(2026, 6, 1_000_000.00);
  378. $this->assertSame(300.0, $result['maintenance_effective_value']);
  379. $this->assertSame(0.30, $result['maintenance_effective_percentage']);
  380. }
  381. // --------------------------------------------- Classificação de Habitantes (porte)
  382. /**
  383. * Regra (md "Classificação de Habitantes"): a faixa de royalties muda conforme o
  384. * mês de contrato (4-12 x 13-60), dentro do mesmo porte.
  385. *
  386. * Cenário: Porte GP — mês 12 (75%) e mês 13 (100%).
  387. *
  388. * Espera: mês 12 -> R$ 750,00; mês 13 -> R$ 1.000,00.
  389. */
  390. public function test_faixa_de_royalties_muda_no_mes_13(): void
  391. {
  392. $this->makeContract();
  393. $this->makeTbrYear(2027, 1000.00);
  394. $mes12 = $this->preview(2026, 12, 1000);
  395. $mes13 = $this->preview(2027, 1, 1000);
  396. $this->assertSame(0.75, $mes12['royalties_bracket_percentage']);
  397. $this->assertSame(750.0, $mes12['royalties_bracket_value']);
  398. $this->assertSame(1.0, $mes13['royalties_bracket_percentage']);
  399. $this->assertSame(1000.0, $mes13['royalties_bracket_value']);
  400. }
  401. /**
  402. * Regra (md "Classificação de Habitantes"): o porte do município do contrato
  403. * define qual faixa de royalties se aplica.
  404. *
  405. * Cenário: Contrato em porte MGP (100% no mês 4) no lugar de GP (75%).
  406. *
  407. * Espera: percentual da faixa = 1,00; Royalties = R$ 1.000,00 em vez de R$ 750,00.
  408. */
  409. public function test_porte_maior_do_municipio_cobra_percentual_maior(): void
  410. {
  411. $sizeMgp = $this->makeSize('MGP', 'Acima de 200 mil habitantes');
  412. $this->makeBrackets($sizeMgp->id, [[1, 3, 0.0], [4, 12, 1.00], [13, 60, 1.50]]);
  413. $this->makeContract(['municipality_size_id' => $sizeMgp->id]);
  414. $result = $this->preview(2026, 4, 1000);
  415. $this->assertSame(1.0, $result['royalties_bracket_percentage']);
  416. $this->assertSame(1000.0, $result['royalties_effective_value']);
  417. }
  418. /**
  419. * Regra: Contrato sem faixa cadastrada para o porte/mês, e sem faixa de renovação
  420. * cobrindo o período, não calcula.
  421. *
  422. * Cenário: Faixas cadastradas só até o mês 60, sem nenhuma faixa de renovação;
  423. * competência cai no mês 61.
  424. *
  425. * Espera: ValidationException 'Não foi encontrada faixa de royalties'.
  426. */
  427. public function test_erro_quando_nao_existe_faixa_nem_de_renovacao_para_o_mes(): void
  428. {
  429. $this->makeContract();
  430. $this->makeTbrYear(2031, 1000.00);
  431. $this->expectException(ValidationException::class);
  432. $this->expectExceptionMessage('Não foi encontrada faixa de royalties');
  433. $this->preview(2031, 1, 1000); // mês 61, sem faixa de renovação cadastrada
  434. }
  435. // ---------------------------------------------------- Renovação (mês 61 em diante)
  436. /**
  437. * Regra: A partir do mês 61 (fim do primeiro ciclo de 60 meses), a faixa de
  438. * royalties passa a vir de is_renewal=true — o contrato "renova" e continua sendo
  439. * cobrado, em vez de estourar erro.
  440. *
  441. * Cenário: Faixa de renovação do porte GP cobrindo 1-60, com 100% (igual à última
  442. * faixa normal). Competência cai no mês 61 do contrato.
  443. *
  444. * Espera: encontra a faixa de renovação, percentual = 1,00, Royalties = R$ 1.000,00.
  445. */
  446. public function test_mes_61_usa_a_faixa_de_renovacao(): void
  447. {
  448. $this->makeBrackets($this->sizeGp->id, [[1, 60, 1.00]], true);
  449. $this->makeContract();
  450. $this->makeTbrYear(2031, 1000.00);
  451. $result = $this->preview(2031, 1, 1000); // mês de contrato 61
  452. $this->assertSame(1.0, $result['royalties_bracket_percentage']);
  453. $this->assertSame(1000.0, $result['royalties_effective_value']);
  454. }
  455. /**
  456. * Regra: O mês de contrato dentro do ciclo de renovação é "enrolado" de volta para
  457. * o intervalo 1-60 (mês 61 = mês 1 da renovação, mês 120 = mês 60 da renovação).
  458. *
  459. * Cenário: Faixa de renovação com duas fatias (1-12 = 60%, 13-60 = 100%), simulando
  460. * uma nova isenção/escalonamento dentro do próprio ciclo de renovação.
  461. *
  462. * Espera:
  463. * - mês 65 do contrato (5º mês da renovação) -> 60%
  464. * - mês 120 do contrato (60º mês da renovação) -> 100%
  465. */
  466. public function test_mes_de_renovacao_e_calculado_dentro_do_ciclo_de_60_meses(): void
  467. {
  468. $this->makeBrackets($this->sizeGp->id, [[1, 12, 0.60], [13, 60, 1.00]], true);
  469. $this->makeContract();
  470. $this->makeTbrYear(2031, 1000.00); // mês 61
  471. $this->makeTbrYear(2035, 1000.00); // mês 61 + 59 = mês 120
  472. $mes65 = $this->preview(2031, 5, 1000); // mês de contrato 65 -> renovação mês 5
  473. $mes120 = $this->preview(2035, 12, 1000); // mês de contrato 120 -> renovação mês 60
  474. $this->assertSame(0.60, $mes65['royalties_bracket_percentage']);
  475. $this->assertSame(1.00, $mes120['royalties_bracket_percentage']);
  476. }
  477. /**
  478. * Regra: Passado um segundo ciclo completo de 60 meses (mês 121 em diante), o
  479. * ciclo de renovação recomeça do zero.
  480. *
  481. * Cenário: Faixa de renovação única (1-60 = 100%); competência cai no mês 121.
  482. *
  483. * Espera: continua encontrando a faixa de renovação (não estoura erro), 100%.
  484. */
  485. public function test_segundo_ciclo_de_renovacao_reinicia_a_contagem(): void
  486. {
  487. $this->makeBrackets($this->sizeGp->id, [[1, 60, 1.00]], true);
  488. $this->makeContract();
  489. $this->makeTbrYear(2036, 1000.00); // mês de contrato 121
  490. $result = $this->preview(2036, 1, 1000);
  491. $this->assertSame(1.0, $result['royalties_bracket_percentage']);
  492. }
  493. // --------------------------------------------------------------- valor da TBR
  494. /**
  495. * Regra (md): o percentual/valor fixo vem da "TBR Fixo do ano (Atribuído em
  496. * Configurações do TBR)". A tabela `tbrs` do ano cadastrada pelo admin manda
  497. * sobre o valor gravado no contrato.
  498. *
  499. * Cenário: tbrs/2026 = R$ 1.000,00 (setUp) e contrato com tbr_fixed_value = R$ 2.000,00.
  500. *
  501. * Espera: TBR usada = R$ 1.000,00; Royalties = R$ 750,00; Manutenção = R$ 300,00.
  502. */
  503. public function test_tbr_do_ano_configurada_pelo_admin_tem_prioridade_sobre_o_contrato(): void
  504. {
  505. $this->makeContract(['tbr_fixed_value' => 2000.00]);
  506. $result = $this->preview(2026, 4, 1000);
  507. $this->assertSame(1000.0, $result['tbr_value']);
  508. $this->assertSame(750.0, $result['royalties_effective_value']);
  509. $this->assertSame(300.0, $result['maintenance_effective_value']);
  510. }
  511. /**
  512. * Regra: Cada ano de referência usa sua própria configuração de TBR.
  513. *
  514. * Cenário: tbrs/2026 = R$ 1.000,00 (setUp), tbrs/2027 = R$ 2.000,00.
  515. *
  516. * Espera: mês em 2026 usa R$ 1.000,00; mês em 2027 usa R$ 2.000,00.
  517. */
  518. public function test_cada_ano_usa_a_sua_propria_configuracao_de_tbr(): void
  519. {
  520. $this->makeContract();
  521. $this->makeTbrYear(2027, 2000.00);
  522. $this->assertSame(1000.0, $this->preview(2026, 4, 1000)['tbr_value']);
  523. $this->assertSame(2000.0, $this->preview(2027, 1, 1000)['tbr_value']);
  524. }
  525. /**
  526. * Regra: Quando o ano de referência não está configurado em `tbrs`, usa-se o
  527. * valor gravado no contrato (tbr_fixed_value) como reserva.
  528. *
  529. * Cenário: Competência em 2030 (sem linha em `tbrs`), contrato com tbr_fixed_value = R$ 1.500,00.
  530. *
  531. * Espera: TBR usada = R$ 1.500,00.
  532. */
  533. public function test_usa_a_tbr_do_contrato_quando_o_ano_nao_esta_configurado(): void
  534. {
  535. $this->makeContract(['tbr_fixed_value' => 1500.00]);
  536. $result = $this->preview(2030, 1, 1000);
  537. $this->assertSame(1500.0, $result['tbr_value']);
  538. }
  539. /**
  540. * Regra: Sem TBR configurada nem no ano nem no contrato, o cálculo não pode seguir.
  541. *
  542. * Cenário: Ano sem `tbrs` e contrato com tbr_fixed_value = 0.
  543. *
  544. * Espera: ValidationException.
  545. */
  546. public function test_erro_quando_nao_ha_tbr_no_ano_nem_no_contrato(): void
  547. {
  548. $this->makeContract(['tbr_fixed_value' => 0]);
  549. $this->expectException(ValidationException::class);
  550. $this->preview(2030, 1, 1000);
  551. }
  552. /**
  553. * Regra: Os percentuais fixos de FNM e Manutenção vêm da tabela `tbrs` do ano.
  554. *
  555. * Cenário: tbrs/2027 com FNM = 25% e Manutenção = 35%.
  556. *
  557. * Espera: FNM fixo = R$ 250,00 (25% x 1000) e Manutenção = R$ 350,00 (35% x 1000).
  558. */
  559. public function test_percentuais_de_fnm_e_manutencao_vem_da_tabela_do_ano(): void
  560. {
  561. $this->makeContract();
  562. $this->makeTbrYear(2027, 1000.00, fnm: 0.25, maintenance: 0.35);
  563. $result = $this->preview(2027, 1, 1000); // mês 13, sem faturamento suficiente pra superar o fixo
  564. $this->assertSame(250.0, $result['fnm_bracket_value']);
  565. $this->assertSame(350.0, $result['maintenance_effective_value']);
  566. }
  567. // ------------------------------------------------ flags charge_roi / charge_fnm
  568. /**
  569. * Regra (md "UnitActionPage"): quando a cobrança de Royalties (ROI) está desativada
  570. * para a unidade, o valor efetivo de royalties é zerado.
  571. *
  572. * Cenário: `unit_financials.charge_roi = false`.
  573. *
  574. * Espera: royalties_effective_value = 0, critério = 'nao_cobrado'; Manutenção continua.
  575. */
  576. public function test_charge_roi_desligado_zera_os_royalties(): void
  577. {
  578. $this->makeContract();
  579. UnitFinancial::create(['unit_id' => $this->unit->id, 'charge_roi' => false, 'charge_fnm' => true]);
  580. $result = $this->preview(2026, 4, 40000);
  581. $this->assertSame(0.0, $result['royalties_effective_value']);
  582. $this->assertSame('nao_cobrado', $result['royalties_applied_criteria']);
  583. $this->assertGreaterThan(0, $result['maintenance_effective_value']);
  584. }
  585. /**
  586. * Regra: Com charge_roi desligado, o cálculo nem exige que exista faixa de
  587. * royalties cadastrada para o porte/mês (não busca a faixa).
  588. *
  589. * Cenário: Nenhuma faixa cadastrada para o porte MP; charge_roi = false.
  590. *
  591. * Espera: preview não lança exceção; royalties = 0.
  592. */
  593. public function test_charge_roi_desligado_dispensa_a_existencia_de_faixa(): void
  594. {
  595. $sizeMp = $this->makeSize('MP', 'Sem faixas cadastradas');
  596. $this->makeContract(['municipality_size_id' => $sizeMp->id]);
  597. UnitFinancial::create(['unit_id' => $this->unit->id, 'charge_roi' => false, 'charge_fnm' => true]);
  598. $result = $this->preview(2026, 4, 1000);
  599. $this->assertSame(0.0, $result['royalties_effective_value']);
  600. $this->assertNull($result['royalties_bracket_id']);
  601. }
  602. /**
  603. * Regra: charge_fnm desligado zera apenas o FNM.
  604. *
  605. * Cenário: `unit_financials.charge_fnm = false`.
  606. *
  607. * Espera: fnm_effective_value = 0; royalties e manutenção continuam normais.
  608. */
  609. public function test_charge_fnm_desligado_zera_o_fnm(): void
  610. {
  611. $this->makeContract();
  612. UnitFinancial::create(['unit_id' => $this->unit->id, 'charge_roi' => true, 'charge_fnm' => false]);
  613. $result = $this->preview(2026, 4, 1000);
  614. $this->assertSame(0.0, $result['fnm_effective_value']);
  615. $this->assertGreaterThan(0, $result['royalties_effective_value']);
  616. }
  617. /**
  618. * Regra: Unidade sem registro em `unit_financials` cobra normalmente (default seguro = cobrar).
  619. *
  620. * Cenário: Nenhum `UnitFinancial` criado para a unidade.
  621. *
  622. * Espera: royalties e FNM calculados normalmente (> 0).
  623. */
  624. public function test_unidade_sem_registro_financeiro_cobra_royalties_e_fnm(): void
  625. {
  626. $this->makeContract();
  627. $result = $this->preview(2026, 4, 1000);
  628. $this->assertGreaterThan(0, $result['royalties_effective_value']);
  629. $this->assertGreaterThan(0, $result['fnm_effective_value']);
  630. }
  631. /**
  632. * Regra (md "Taxa de Manutenção"): a manutenção não tem flag de liga/desliga —
  633. * é sempre cobrada, mesmo com charge_roi e charge_fnm desligados.
  634. *
  635. * Cenário: charge_roi = false e charge_fnm = false.
  636. *
  637. * Espera: Manutenção = R$ 300,00; total = R$ 300,00.
  638. */
  639. public function test_manutencao_e_cobrada_mesmo_com_as_duas_flags_desligadas(): void
  640. {
  641. $this->makeContract();
  642. UnitFinancial::create(['unit_id' => $this->unit->id, 'charge_roi' => false, 'charge_fnm' => false]);
  643. $result = $this->preview(2026, 4, 1000);
  644. $this->assertSame(300.0, $result['maintenance_effective_value']);
  645. $this->assertSame(300.0, $result['final_value']);
  646. }
  647. // ---------------------------------------------------------- composição do faturamento
  648. /**
  649. * Regra: O faturamento-base do TBR soma parcelas de aluno, recebíveis avulsos da
  650. * unidade e contas vinculadas pela franqueadora (origin=manual_unit).
  651. *
  652. * Cenário: 1 parcela de R$ 100, 1 recebível avulso de R$ 50, 1 conta da matriz
  653. * vinculada de R$ 30, todos com vencimento no mês de referência.
  654. *
  655. * Espera: faturamento resolvido = R$ 180,00.
  656. */
  657. public function test_faturamento_soma_parcelas_recebiveis_e_contas_da_matriz(): void
  658. {
  659. $this->makeInstallment(['value' => 100, 'due_date' => '2026-04-10']);
  660. UnitAccountReceivable::create([
  661. 'unit_id' => $this->unit->id,
  662. 'history' => 'Avulso',
  663. 'value' => 50,
  664. 'due_date' => '2026-04-15',
  665. 'status' => 'pending',
  666. ]);
  667. FranchiseeAccountReceive::create([
  668. 'unit_id' => $this->unit->id,
  669. 'origin' => 'manual_unit',
  670. 'history' => 'Conta vinculada',
  671. 'value' => 30,
  672. 'due_date' => '2026-04-20',
  673. 'status' => 'pending',
  674. ]);
  675. $revenue = $this->service->resolveRevenue($this->unit->id, 2026, 4);
  676. $this->assertSame(180.0, $revenue);
  677. }
  678. /**
  679. * Regra: Parcelas canceladas e de outros meses não entram no faturamento.
  680. */
  681. public function test_faturamento_ignora_parcelas_canceladas_e_de_outros_meses(): void
  682. {
  683. $this->makeInstallment(['value' => 100, 'due_date' => '2026-04-10', 'status' => 'cancelled']);
  684. $this->makeInstallment(['value' => 200, 'due_date' => '2026-05-10', 'installment_number' => 2]);
  685. $revenue = $this->service->resolveRevenue($this->unit->id, 2026, 4);
  686. $this->assertSame(0.0, $revenue);
  687. }
  688. /**
  689. * Regra: Parcelas com soft delete não entram no faturamento.
  690. */
  691. public function test_faturamento_ignora_parcelas_excluidas(): void
  692. {
  693. $installment = $this->makeInstallment(['value' => 100, 'due_date' => '2026-04-10']);
  694. $installment->delete();
  695. $revenue = $this->service->resolveRevenue($this->unit->id, 2026, 4);
  696. $this->assertSame(0.0, $revenue);
  697. }
  698. /**
  699. * Regra: Recebíveis originados do próprio TBR não realimentam a base de faturamento.
  700. */
  701. public function test_faturamento_ignora_recebiveis_de_tbr(): void
  702. {
  703. FranchiseeAccountReceive::create([
  704. 'unit_id' => $this->unit->id,
  705. 'origin' => 'tbr',
  706. 'history' => 'Royalties gerado',
  707. 'value' => 500,
  708. 'due_date' => '2026-04-20',
  709. 'status' => 'pending',
  710. ]);
  711. $revenue = $this->service->resolveRevenue($this->unit->id, 2026, 4);
  712. $this->assertSame(0.0, $revenue);
  713. }
  714. /**
  715. * Regra: Movimentos de outra unidade não entram no faturamento consultado.
  716. */
  717. public function test_faturamento_ignora_movimento_de_outra_unidade(): void
  718. {
  719. $outraUnidade = $this->makeUnit('Outra Unidade');
  720. $this->makeInstallment(['unit_id' => $outraUnidade->id, 'value' => 999, 'due_date' => '2026-04-10']);
  721. $revenue = $this->service->resolveRevenue($this->unit->id, 2026, 4);
  722. $this->assertSame(0.0, $revenue);
  723. }
  724. /**
  725. * Regra: Faturamento informado manualmente sobrepõe o cálculo automático (override).
  726. */
  727. public function test_faturamento_informado_manualmente_substitui_o_calculo_automatico(): void
  728. {
  729. $this->makeContract();
  730. $this->makeInstallment(['value' => 100, 'due_date' => '2026-04-10']);
  731. $result = $this->service->preview([
  732. 'unit_id' => $this->unit->id,
  733. 'reference_year' => 2026,
  734. 'reference_month' => 4,
  735. 'revenue_value' => 40000,
  736. ]);
  737. $this->assertSame(40000.0, $result['revenue_value']);
  738. $this->assertSame('percentual_faturamento', $result['royalties_applied_criteria']);
  739. }
  740. // -------------------------------------------------------------- contrato / erros
  741. /**
  742. * Regra: Unidade sem contrato cadastrado não calcula.
  743. */
  744. public function test_erro_quando_a_unidade_nao_tem_contrato(): void
  745. {
  746. $this->expectException(ValidationException::class);
  747. $this->expectExceptionMessage('Unidade não possui contrato cadastrado.');
  748. $this->preview(2026, 4, 1000);
  749. }
  750. /**
  751. * Regra: Contrato sem porte do município definido não calcula.
  752. */
  753. public function test_erro_quando_o_contrato_nao_tem_porte_do_municipio(): void
  754. {
  755. $this->makeContract(['municipality_size_id' => null]);
  756. $this->expectException(ValidationException::class);
  757. $this->expectExceptionMessage('faixa de habitantes definida');
  758. $this->preview(2026, 4, 1000);
  759. }
  760. /**
  761. * Regra: Havendo mais de um contrato para a unidade, usa-se sempre o mais recente
  762. * (maior start_date).
  763. */
  764. public function test_usa_sempre_o_contrato_mais_recente_da_unidade(): void
  765. {
  766. $this->makeContract(['start_date' => '2020-01-01', 'tbr_fixed_value' => 500]);
  767. $this->makeContract(['start_date' => '2026-01-01', 'tbr_fixed_value' => 1500]);
  768. $result = $this->preview(2026, 1, 1000);
  769. $this->assertSame(1, $result['contract_month_reference']);
  770. }
  771. // -------------------------------------------------------------- persistência
  772. /**
  773. * Regra: calculate() grava em `tbr_calculations` exatamente os valores do preview
  774. * (a tabela de auditoria pedida no md).
  775. */
  776. public function test_calculate_grava_o_calculo_com_os_valores_do_preview(): void
  777. {
  778. $this->makeContract();
  779. $calculation = $this->service->calculate([
  780. 'unit_id' => $this->unit->id,
  781. 'reference_year' => 2026,
  782. 'reference_month' => 4,
  783. 'revenue_value' => 40000,
  784. ]);
  785. $this->assertInstanceOf(TbrCalculation::class, $calculation);
  786. $this->assertSame(4, $calculation->contract_month_reference);
  787. $this->assertSame('percentual_faturamento', $calculation->royalties_applied_criteria);
  788. $this->assertEquals(3200.0, (float) $calculation->royalties_effective_value);
  789. $this->assertEquals(800.0, (float) $calculation->fnm_effective_value);
  790. $this->assertEquals(300.0, (float) $calculation->maintenance_effective_value);
  791. $this->assertEquals(4300.0, (float) $calculation->final_value);
  792. $this->assertFalse($calculation->receivable_generated);
  793. }
  794. // ---------------------------------------------------------- geração de título
  795. /**
  796. * Regra (md "Tabela de Auditoria" + contas a receber/pagar): gerar o título cria
  797. * o recebível da matriz, os 3 detalhes por componente e o espelho na unidade
  798. * (conta a pagar), além de disparar a sincronização com o Asaas.
  799. */
  800. public function test_gerar_titulo_cria_recebivel_detalhes_e_conta_a_pagar(): void
  801. {
  802. $this->makeContract();
  803. $calculation = $this->service->calculate([
  804. 'unit_id' => $this->unit->id,
  805. 'reference_year' => 2026,
  806. 'reference_month' => 4,
  807. 'revenue_value' => 40000,
  808. ]);
  809. $receive = $this->service->generateReceivable($calculation->id);
  810. $this->assertSame(4300.0, (float) $receive->value);
  811. $this->assertCount(3, $receive->details);
  812. $this->assertDatabaseHas('unit_account_payables', [
  813. 'unit_id' => $this->unit->id,
  814. 'franchisee_account_receive_id' => $receive->id,
  815. 'origin' => UnitAccountPayable::ORIGIN_TBR,
  816. ]);
  817. $this->assertTrue($calculation->fresh()->receivable_generated);
  818. Bus::assertDispatched(\App\Jobs\SyncFranchiseeChargeJob::class);
  819. }
  820. /**
  821. * Regra: Não é possível gerar título duas vezes para o mesmo cálculo.
  822. */
  823. public function test_gerar_titulo_duas_vezes_para_o_mesmo_calculo_e_bloqueado(): void
  824. {
  825. $this->makeContract();
  826. $calculation = $this->service->calculate([
  827. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 1000,
  828. ]);
  829. $this->service->generateReceivable($calculation->id);
  830. $this->expectException(ValidationException::class);
  831. $this->expectExceptionMessage('Já existe um título gerado para este cálculo.');
  832. $this->service->generateReceivable($calculation->id);
  833. }
  834. /**
  835. * Regra: Não é possível gerar dois títulos para o mesmo mês de contrato da mesma unidade.
  836. */
  837. public function test_gerar_titulo_para_o_mesmo_mes_de_contrato_e_bloqueado(): void
  838. {
  839. $this->makeContract();
  840. $primeiro = $this->service->calculate([
  841. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 1000,
  842. ]);
  843. $this->service->generateReceivable($primeiro->id);
  844. $segundo = $this->service->calculate([
  845. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 2000,
  846. ]);
  847. $this->expectException(ValidationException::class);
  848. $this->expectExceptionMessage('mês de contrato');
  849. $this->service->generateReceivable($segundo->id);
  850. }
  851. /**
  852. * Regra: O preview avisa (flag) quando já existe título gerado para o mês de contrato,
  853. * sem impedir a nova simulação.
  854. */
  855. public function test_preview_avisa_quando_ja_existe_titulo_no_mes_de_contrato(): void
  856. {
  857. $this->makeContract();
  858. $calculation = $this->service->calculate([
  859. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 1000,
  860. ]);
  861. $this->service->generateReceivable($calculation->id);
  862. $result = $this->preview(2026, 4, 1000);
  863. $this->assertTrue($result['receivable_already_generated']);
  864. }
  865. // ----------------------------------------------------------------- vencimento
  866. public function test_vencimento_usa_o_dia_do_contrato_no_mes_seguinte(): void
  867. {
  868. $this->makeContract(['invoice_due_date' => 15]);
  869. $calculation = $this->service->calculate([
  870. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 1000,
  871. ]);
  872. $receive = $this->service->generateReceivable($calculation->id);
  873. $this->assertSame('2026-05-15', $receive->due_date->toDateString());
  874. }
  875. public function test_vencimento_cai_no_dia_10_quando_o_contrato_nao_informa(): void
  876. {
  877. $this->makeContract(['invoice_due_date' => null]);
  878. $calculation = $this->service->calculate([
  879. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 1000,
  880. ]);
  881. $receive = $this->service->generateReceivable($calculation->id);
  882. $this->assertSame('2026-05-10', $receive->due_date->toDateString());
  883. }
  884. public function test_vencimento_e_limitado_ao_dia_28(): void
  885. {
  886. $this->makeContract(['invoice_due_date' => 31]);
  887. $calculation = $this->service->calculate([
  888. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 1000,
  889. ]);
  890. $receive = $this->service->generateReceivable($calculation->id);
  891. $this->assertSame(28, $receive->due_date->day);
  892. }
  893. // ---------------------------------------------------------------------- lote
  894. public function test_lote_gera_titulo_para_cada_contrato_ativo(): void
  895. {
  896. $unidade2 = $this->makeUnit('Unidade 2');
  897. $this->makeContract();
  898. $this->makeContract(['unit_id' => $unidade2->id]);
  899. $result = $this->service->generateBatch(2026, 4, null);
  900. $this->assertSame(2, $result['generated_count']);
  901. $this->assertSame(0, $result['error_count']);
  902. }
  903. public function test_lote_pula_unidade_que_ja_tem_titulo_no_mes_de_contrato(): void
  904. {
  905. $this->makeContract();
  906. $calculation = $this->service->calculate([
  907. 'unit_id' => $this->unit->id, 'reference_year' => 2026, 'reference_month' => 4, 'revenue_value' => 1000,
  908. ]);
  909. $this->service->generateReceivable($calculation->id);
  910. $result = $this->service->generateBatch(2026, 4, null);
  911. $this->assertSame(0, $result['generated_count']);
  912. $this->assertSame(1, $result['skipped_count']);
  913. }
  914. public function test_lote_ignora_contrato_encerrado_antes_da_competencia(): void
  915. {
  916. $this->makeContract(['end_date' => '2026-02-28']);
  917. $result = $this->service->generateBatch(2026, 4, null);
  918. $this->assertSame(0, $result['generated_count']);
  919. $this->assertSame(0, $result['skipped_count']);
  920. $this->assertSame(0, $result['error_count']);
  921. }
  922. public function test_lote_ignora_contrato_que_ainda_nao_comecou(): void
  923. {
  924. $this->makeContract(['start_date' => '2026-08-01']);
  925. $result = $this->service->generateBatch(2026, 4, null);
  926. $this->assertSame(0, $result['generated_count']);
  927. }
  928. public function test_lote_ignora_contrato_sem_porte_definido(): void
  929. {
  930. $this->makeContract(['municipality_size_id' => null]);
  931. $result = $this->service->generateBatch(2026, 4, null);
  932. $this->assertSame(0, $result['generated_count']);
  933. $this->assertSame(0, $result['error_count']);
  934. }
  935. public function test_lote_pode_ser_filtrado_por_unidade(): void
  936. {
  937. $unidade2 = $this->makeUnit('Unidade 2');
  938. $this->makeContract();
  939. $this->makeContract(['unit_id' => $unidade2->id]);
  940. $result = $this->service->generateBatch(2026, 4, [$unidade2->id]);
  941. $this->assertSame(1, $result['generated_count']);
  942. $this->assertSame($unidade2->id, $result['generated'][0]['unit_id']);
  943. }
  944. public function test_lote_reporta_erro_sem_interromper_as_demais_unidades(): void
  945. {
  946. $unidadeComErro = $this->makeUnit('Unidade Sem TBR');
  947. $this->makeContract(['tbr_fixed_value' => 0]);
  948. $this->makeContract(['unit_id' => $unidadeComErro->id, 'tbr_fixed_value' => 0]);
  949. Tbr::query()->delete();
  950. $result = $this->service->generateBatch(2030, 1, null);
  951. $this->assertSame(0, $result['generated_count']);
  952. $this->assertSame(2, $result['error_count']);
  953. }
  954. }