feat: adiciona simulação de prefixado para CDB e LCI/LCA#532
Conversation
Adiciona a simulação de taxa prefixada ao lado dos produtos pós-fixados (% do CDI) que já existem. Um prefixado muda apenas o fator de capitalização diário (uma taxa anual fixa em vez de um percentual do CDI); a tributação continua a mesma, então o CDB reutiliza o IR regressivo e o IOF do finance.ts e a LCI/LCA permanece isenta. Inclui dois cards de resultado e seus inputs, com um novo módulo app/src/prefixado.ts e testes unitários. Parte da rendafixa#17
📝 WalkthroughWalkthroughAdds prefixado (fixed-rate) investment calculation support: a new ChangesPrefixado Investment Feature
Estimated code review effort: 2 (Simple) | ~15 minutes Sequence Diagram(s)sequenceDiagram
participant InvestmentInput
participant InvestmentStore
participant InvestmentSimulation
participant PrefixadoModule
InvestmentInput->>InvestmentStore: setCdbPre / setLcxPre
InvestmentSimulation->>InvestmentStore: read cdbPre, lcxPre, amount
InvestmentSimulation->>PrefixadoModule: getPrefixadoCdbResult(amount, cdbPre, days)
InvestmentSimulation->>PrefixadoModule: getPrefixadoLcxResult(amount, lcxPre, days)
PrefixadoModule-->>InvestmentSimulation: interestAmount, taxAmount, taxPercentage, iofAmount
InvestmentSimulation-->>InvestmentSimulation: render InvestmentResult blocks
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
test/unit/src/prefixado.spec.ts (2)
16-30: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winConsider testing exact IR tier boundaries.
Cases use 181/400/900 days (mid-tier) but not the exact boundary values (180, 360, 720) where off-by-one errors are most likely. If
finance.tsdoesn't already cover these boundaries elsewhere, adding them here would harden coverage.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/unit/src/prefixado.spec.ts` around lines 16 - 30, Add boundary coverage to getPrefixadoCdbResult in prefixado.spec.ts by extending the tierCases in the tax percentage suite to include the exact IR cutoff values (180, 360, and 720 days) alongside the existing mid-tier cases; verify each boundary returns the expected taxPercentage so off-by-one behavior in finance.ts is caught. Use getPrefixadoCdbResult and the taxPercentage assertions in the existing describe block to place the new cases.
5-14: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winTests mirror the production formula instead of using independent expected values.
expectedPrefixado()duplicates the exact same math ascompoundInterest/getIndexPrefixado/the CDB tax formula. Most assertions (e.g. Lines 42-46, 60-63, 77-78, 100) compareresultagainst this mirror, so they mainly verify wiring, not that the arithmetic itself is correct - a shared bug in both places wouldn't be caught. Consider adding at least one or two hardcoded/golden-value assertions (e.g. precompute expectedinterestAmount/taxAmountfor a knownamount/yearlyRate/dayscombo) to validate the actual math independently.Also applies to: 32-46
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/unit/src/prefixado.spec.ts` around lines 5 - 14, The tests rely on expectedPrefixado to mirror the same arithmetic used by compoundInterest, getIndexPrefixado, and the tax/IOF helpers, so they only validate wiring rather than the math itself. Update the assertions in prefixado.spec.ts to include at least one or two hardcoded golden-value cases for a known amount/yearlyRate/days combination, with expected interestAmount, taxAmount, taxPercentage, and iofAmount computed independently of expectedPrefixado. Keep the existing helper if useful for broad coverage, but add independent checks so a shared bug in the production formula is caught.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@test/unit/src/prefixado.spec.ts`:
- Around line 16-30: Add boundary coverage to getPrefixadoCdbResult in
prefixado.spec.ts by extending the tierCases in the tax percentage suite to
include the exact IR cutoff values (180, 360, and 720 days) alongside the
existing mid-tier cases; verify each boundary returns the expected taxPercentage
so off-by-one behavior in finance.ts is caught. Use getPrefixadoCdbResult and
the taxPercentage assertions in the existing describe block to place the new
cases.
- Around line 5-14: The tests rely on expectedPrefixado to mirror the same
arithmetic used by compoundInterest, getIndexPrefixado, and the tax/IOF helpers,
so they only validate wiring rather than the math itself. Update the assertions
in prefixado.spec.ts to include at least one or two hardcoded golden-value cases
for a known amount/yearlyRate/days combination, with expected interestAmount,
taxAmount, taxPercentage, and iofAmount computed independently of
expectedPrefixado. Keep the existing helper if useful for broad coverage, but
add independent checks so a shared bug in the production formula is caught.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: bae30e6b-8352-4b9d-9dfd-9a34392be599
📒 Files selected for processing (7)
app/components/InvestmentInput.vueapp/components/InvestmentSimulation.vueapp/components/investment/IndexCdbPreInput.vueapp/components/investment/IndexLcxPreInput.vueapp/src/prefixado.tsapp/store/investment.tstest/unit/src/prefixado.spec.ts
|
|
Olá, @ReddyyZ! Antes de tudo, obrigado pela intenção e pela iniciativa de ajudar o projeto. A simulação de investimentos prefixados é uma solicitação antiga da comunidade, e sua contribuição avança bastante a implementação da issue #17. Revisei as alterações e executei as validações locais: o lint passou, os 95 testes passaram e a geração do site foi concluída com sucesso. Antes de aprovar, encontrei dois pontos relacionados à precisão da simulação: 1. Base de dias utilizada no cálculo do prefixadoAtualmente, Math.pow(yearlyRate / 100 + 1, 1 / 365)Essa base não representa necessariamente o critério contratual desses produtos. As fórmulas da B3 utilizam critérios como 252 dias úteis para CDB/RDB/LC e LCI; CDBs também podem utilizar o critério de 360 dias corridos, dependendo das condições da emissão. Referências: Isso pode fazer com que o resultado calculado seja diferente da rentabilidade contratada. Minha sugestão é modelar o critério de contagem aplicável — por exemplo, 252 dias úteis ou 360 dias corridos — e converter o prazo de acordo com ele. Caso a intenção seja oferecer uma aproximação, seria importante deixar essa limitação explícita na interface. O helper 2. Simulações de LCI/LCA com prazos que não existem no produtoO novo resultado de LCI/LCA prefixado é calculado para qualquer prazo positivo, inclusive períodos inferiores a 90 dias. Segundo a documentação da B3 sobre LCI, uma LCI sem índice de preços possui vencimento mínimo de 90 dias e não pode ser resgatada durante esse período. Sugiro validar o prazo mínimo antes de apresentar o resultado, exibindo uma mensagem explicativa quando a combinação escolhida não representar um investimento disponível. Como o card agrupa LCI e LCA, também vale considerar as regras específicas aplicáveis a cada produto. Com esses ajustes, acredito que a funcionalidade ficará mais segura para comparação financeira e mais alinhada às condições reais dos investimentos. Obrigado novamente pela contribuição e pelo cuidado em incluir testes para a nova lógica. |



Adiciona a simulação de investimentos prefixados (taxa fixa anual), ao lado dos pós-fixados (% do CDI) que já existem. Cobre a parte mais pedida da #17.
O que muda
app/src/prefixado.ts: um prefixado altera só o fator de capitalização diário (taxa nominal fixa em vez de % do CDI). A tributação é a mesma que já existe, CDB reutiliza o IR regressivo e o IOF dofinance.ts, e LCI/LCA continua isenta.% a.a.).Escopo
Deixei de fora, de propósito, o IPCA+x% (precisa de um índice novo em
indicadores.json) e o Tesouro prefixado (produto novo, com taxa de custódia).Parte da #17
Summary by CodeRabbit
New Features
Bug Fixes