feat(finance): validate opt-in day terms without supplier advances
@@ -1173,7 +1173,7 @@ Nomes de ficheiros na coluna de implementação referem-se a `resources/js/lib/`
|
|||||||
| F17 | PN P0052 | Relatório financeiro | Calcular automaticamente vendas dos anos seguintes a partir do crescimento esperado | INTEGRADO E VALIDADO | business-financial-plan.ts; financial-plan-details.tsx; simulation-business-plan.tsx | 9c34af04 | Opt-in explícito de crescimento composto das quantidades após cada 12 meses; agendas mensais explícitas prevalecem, preços/custos unitários mantêm-se. Nove regressões novas e integrações afectadas: 37 testes aprovados; E8. Sem activação automática nos planos anteriores. |
|
| F17 | PN P0052 | Relatório financeiro | Calcular automaticamente vendas dos anos seguintes a partir do crescimento esperado | INTEGRADO E VALIDADO | business-financial-plan.ts; financial-plan-details.tsx; simulation-business-plan.tsx | 9c34af04 | Opt-in explícito de crescimento composto das quantidades após cada 12 meses; agendas mensais explícitas prevalecem, preços/custos unitários mantêm-se. Nove regressões novas e integrações afectadas: 37 testes aprovados; E8. Sem activação automática nos planos anteriores. |
|
||||||
| F18 | PN P0055 | Relatório financeiro | Separar capital do proprietário, do investidor e dinheiro adicional angariado no plano geral | INTEGRADO E VALIDADO | financial-plan-details.tsx; business-financial-plan.ts; integral-financial-report.ts | 9c34af04 | Proprietário, investidor e capital adicional discriminados; soma exacta ao centavo actualiza equity e divergências são recusadas no cálculo. Empréstimos/suprimentos/subvenções conservam tipos próprios. Capital adicional é contribuição de capital expressamente indicada, não receita ou dívida inferida. E8: UI real, roundtrip, HTTP e exportações. |
|
| F18 | PN P0055 | Relatório financeiro | Separar capital do proprietário, do investidor e dinheiro adicional angariado no plano geral | INTEGRADO E VALIDADO | financial-plan-details.tsx; business-financial-plan.ts; integral-financial-report.ts | 9c34af04 | Proprietário, investidor e capital adicional discriminados; soma exacta ao centavo actualiza equity e divergências são recusadas no cálculo. Empréstimos/suprimentos/subvenções conservam tipos próprios. Capital adicional é contribuição de capital expressamente indicada, não receita ou dívida inferida. E8: UI real, roundtrip, HTTP e exportações. |
|
||||||
| F19 | PN P0057 | Relatório financeiro | Recolher rendas, seguros, utilidades e marketing separadamente nas despesas correntes | INTEGRADO E VALIDADO | financial-plan-details.tsx; business-financial-plan.ts; integral-financial-report.ts | 9c34af04 | Rendas, seguros, utilidades, marketing e outras despesas discriminadas substituem o agregado reconhecido, sem dupla contagem ou alteração dos pagamentos. Juros e depreciação conservam campos próprios. Agregado/agenda anteriores preservados e ocultados enquanto as linhas são usadas. E8: totais mensais/anuais, cenários e saldos reconciliados. |
|
| F19 | PN P0057 | Relatório financeiro | Recolher rendas, seguros, utilidades e marketing separadamente nas despesas correntes | INTEGRADO E VALIDADO | financial-plan-details.tsx; business-financial-plan.ts; integral-financial-report.ts | 9c34af04 | Rendas, seguros, utilidades, marketing e outras despesas discriminadas substituem o agregado reconhecido, sem dupla contagem ou alteração dos pagamentos. Juros e depreciação conservam campos próprios. Agregado/agenda anteriores preservados e ocultados enquanto as linhas são usadas. E8: totais mensais/anuais, cenários e saldos reconciliados. |
|
||||||
| F20 | PN P0058; ME P0143/P0163 | Relatório financeiro | Prazos de recebimento/pagamento: cobrança e compras diferidas | PARCIALMENTE DEMONSTRADO | business-financial-plan.ts; simulation-business-plan.tsx | E15/E23/E24; verificacao-f20-f22-v11-v12-20261120.json; referência 8a35dd0e | E24 valida por leitura a compatibilidade das convenções propostas: data económica distinta da caixa, dias de calendário, prazo zero no próprio dia, caixa no mês do vencimento e modos sem duplicação por operação. O modelo actual usa índices mensais, sem data diária de origem; creditTermDays 0–365 apenas valida/avisa. Antes de implementar, fechar granularidade/datas das coortes, aquisição versus recepção/adiantamentos, abrangência/parcelas e aplicação dos 36 meses sem truncar horizontes existentes de 1–60. Proposta técnica, impactos e aceitação futura registados; estado parcial mantido. Sem código, dados, fórmulas ou testes alterados/executados. F22 e aprovações V11/V12 preservados. |
|
| F20 | PN P0058; ME P0143/P0163 | Relatório financeiro | Prazos de recebimento/pagamento: cobrança e compras diferidas | PARCIALMENTE DEMONSTRADO | business-financial-plan.ts; financial-day-terms.ts; financial-day-terms.tsx; simulation-business-plan.tsx | E15/E23/E24/E25; e25-f20-a-20261121/functional-receipt.json; e25-f20-a-20261121/verification.json | F20-A integrado e validado em QA no recorte sem adiantamentos, proposto para aceitação do proprietário. Adesão explícita por agenda; dias de calendário, datas individuais ou coortes no último dia identificadas como aproximação; caixa no vencimento; exclusão de antecipações/datas insuficientes; parcelas sem duplicação; horizonte 1–60 e vencimentos posteriores identificados. Snapshot 20 opcional; planos anteriores e agendas manuais conservados, outras receitas independentes preservadas. Provas reais de activação, gravação e recuperação exacta em computador/emulação móvel. 15 testes anteriores reutilizados, seis cenários antigos preservados e regressão adicional aprovada. F20 global mantém-se parcial: F20-B suspenso para validação contabilística; F22 separado; V11/V12 e restantes 87 linhas preservados. Sem instalação, publicação ou migrações. |
|
||||||
| F21 | PN P0058 | Relatório financeiro | Dividendos como entrada própria e movimento derivado de caixa/capital | INTEGRADO E VALIDADO | financial-plan-details.tsx; business-financial-plan.ts; integral-financial-report.ts; project-dossier-report.ts | 9c34af04 | Dividendos mensais declarados reduzem caixa e capital, sem reduzir o lucro; não são execução de pagamentos ou autorização jurídica. Reconciliação em 13 meses e dois anos, validação de negativos/agendas incompletas, recuperação, CSV e Word/impressão. E8. |
|
| F21 | PN P0058 | Relatório financeiro | Dividendos como entrada própria e movimento derivado de caixa/capital | INTEGRADO E VALIDADO | financial-plan-details.tsx; business-financial-plan.ts; integral-financial-report.ts; project-dossier-report.ts | 9c34af04 | Dividendos mensais declarados reduzem caixa e capital, sem reduzir o lucro; não são execução de pagamentos ou autorização jurídica. Reconciliação em 13 meses e dois anos, validação de negativos/agendas incompletas, recuperação, CSV e Word/impressão. E8. |
|
||||||
| F22 | PN P0058 | Relatório financeiro | Novos empréstimos e compras de activos ao longo dos períodos | PENDENTE COM CAUSA IDENTIFICADA | business-financial-plan.ts; integral-financial-report.ts | E15/E23; verificacao-f20-f22-v11-v12-20261120.json; referência 50b95936 | E23 confirma a ausência de novos desembolsos/aquisições por período no contrato/editor/relatório inspeccionados. Financiamento e activos iniciais preservados; reembolsos e mercadorias não substituem estes movimentos. Antes de implementar, fechar reconhecimento/pagamento dos activos, início/base/vida útil da depreciação e efeitos na dívida/juros/reembolso, sem inferir condições bancárias. Documentos Revisão 1 conferidos; sem alteração funcional ou novos testes. Pendente com causa identificada. |
|
| F22 | PN P0058 | Relatório financeiro | Novos empréstimos e compras de activos ao longo dos períodos | PENDENTE COM CAUSA IDENTIFICADA | business-financial-plan.ts; integral-financial-report.ts | E15/E23; verificacao-f20-f22-v11-v12-20261120.json; referência 50b95936 | E23 confirma a ausência de novos desembolsos/aquisições por período no contrato/editor/relatório inspeccionados. Financiamento e activos iniciais preservados; reembolsos e mercadorias não substituem estes movimentos. Antes de implementar, fechar reconhecimento/pagamento dos activos, início/base/vida útil da depreciação e efeitos na dívida/juros/reembolso, sem inferir condições bancárias. Documentos Revisão 1 conferidos; sem alteração funcional ou novos testes. Pendente com causa identificada. |
|
||||||
| F23 | PN P0043/P0117–0150 | Relatório financeiro | Resumo executivo com objectivos, missão e chaves para o sucesso | IMPLEMENTADO MAS NÃO VALIDADO | project-dossier-report.ts:223–245 | 93fc837a (consolidação) | Resumo existente usa project_summary, problema, proposta de valor e clientes. Não demonstra os três conteúdos expressamente pedidos; não confundir título Resumo executivo com cumprimento integral. |
|
| F23 | PN P0043/P0117–0150 | Relatório financeiro | Resumo executivo com objectivos, missão e chaves para o sucesso | IMPLEMENTADO MAS NÃO VALIDADO | project-dossier-report.ts:223–245 | 93fc837a (consolidação) | Resumo existente usa project_summary, problema, proposta de valor e clientes. Não demonstra os três conteúdos expressamente pedidos; não confundir título Resumo executivo com cumprimento integral. |
|
||||||
@@ -2205,3 +2205,38 @@ A validação contabilística aqui referida é **específica destes tratamentos
|
|||||||
| Preservação e utilização real | Planos antigos sem optar por dias conservam resultados; relatório/exportações e computador/móvel correspondem às mesmas agendas; avisos V11 reflectem apenas os novos saldos calculados |
|
| Preservação e utilização real | Planos antigos sem optar por dias conservam resultados; relatório/exportações e computador/móvel correspondem às mesmas agendas; avisos V11 reflectem apenas os novos saldos calculados |
|
||||||
|
|
||||||
**Versão consolidada para decisão:** nove convenções propostas, com último dia do mês explicitamente classificado como aproximação ainda por confirmar. F20 permanece **PARCIALMENTE DEMONSTRADO**; implementação suspensa até confirmação da convenção e do tratamento das operações/parcelas. Próxima acção recomendada: decisão expressa sobre os três pontos da secção 4 e posterior autorização delimitada de implementação. Nenhum código, dado, cálculo ou teste foi alterado/executado, nem houve instalação, publicação, migração ou avanço para F22. Nesta consolidação apenas a proposta E24 foi revista; todas as 88 linhas da matriz, incluindo F20, F22, V11 e V12, permanecem exactamente iguais.
|
**Versão consolidada para decisão:** nove convenções propostas, com último dia do mês explicitamente classificado como aproximação ainda por confirmar. F20 permanece **PARCIALMENTE DEMONSTRADO**; implementação suspensa até confirmação da convenção e do tratamento das operações/parcelas. Próxima acção recomendada: decisão expressa sobre os três pontos da secção 4 e posterior autorização delimitada de implementação. Nenhum código, dado, cálculo ou teste foi alterado/executado, nem houve instalação, publicação, migração ou avanço para F22. Nesta consolidação apenas a proposta E24 foi revista; todas as 88 linhas da matriz, incluindo F20, F22, V11 e V12, permanecem exactamente iguais.
|
||||||
|
|
||||||
|
|
||||||
|
## E25 — F20-A: implementação delimitada e prova funcional em QA — 21/11/2026
|
||||||
|
|
||||||
|
Referências E23/E24 versão 2, Revisão 1 e autorização expressa de F20-A sem adiantamentos. Retomadas as alterações locais existentes no worktree QA, sem reiniciar o desenvolvimento. **F20-A: INTEGRADO E VALIDADO EM QA, PROPOSTO PARA ACEITAÇÃO DO PROPRIETÁRIO. F20 global: PARCIALMENTE DEMONSTRADO**, enquanto F20-B aguarda validação contabilística. Esta entrega não encerra F20 nem altera F22, V11/V12 ou as restantes 87 linhas.
|
||||||
|
|
||||||
|
### Âmbito implementado e preservação
|
||||||
|
|
||||||
|
Contrato opcional `dayTerms`, snapshot 20, com adesão explícita por agenda: vendas/prestações, mercadorias efectivamente recebidas e serviços adquiridos reconhecidos. O modo substitui a agenda de caixa correspondente, sem apagar os valores manuais; saldos de abertura, salários, impostos, juros, empréstimos e novos activos mantêm contratos próprios. O modo de serviços abrange o total operacional e só deve ser escolhido se todo esse total corresponder a serviços elegíveis. Outras receitas manuais explicitamente classificadas mantêm-se activas e separadas das cobranças das vendas.
|
||||||
|
|
||||||
|
Cada parcela identifica origem, tipo, mês económico, montante, reconhecimento e evento de origem do prazo. Datas individuais prevalecem quando escolhidas; a escolha mensal usa o último dia do mês e identifica o vencimento como aproximação. Contagem civil em dias de calendário, prazo inteiro 0–365, zero no próprio dia; vazio não é zero. Parcelas duplicadas e distribuições que não reconciliam com o valor reconhecido são rejeitadas. Uma data insuficiente ou vencimento anterior ao reconhecimento bloqueia o cálculo automático da agenda, com diagnóstico explícito; não converte a operação em pagamento normal. Datas de factura/contrato não são confundidas com recepção. Vencimentos posteriores ao horizonte 1–60 não entram artificialmente no último mês; mantêm data, montante e saldo por liquidar.
|
||||||
|
|
||||||
|
Sem `dayTerms` activo conserva-se o percurso de cálculo anterior. Snapshots antigos não são migrados nem activados automaticamente. Reutilizadas as provas aceites dos seis cenários D1/D2/D3/depreciação/reembolso/ambos: resultados e campos não diagnósticos das tabelas idênticos às referências. O novo modo apenas altera as agendas optadas; não altera fórmulas de reconhecimento económico, depreciação, juros, impostos ou financiamento.
|
||||||
|
|
||||||
|
### Conferência na aplicação real
|
||||||
|
|
||||||
|
Playwright e Chromium já instalados no runtime, conforme os precedentes locais em `tools/investmoz-v2-draft-save-browser.cjs`. Não foi repetido o controlo interactivo que bloqueou. Navegação/pedidos de página limitados à origem `http://127.0.0.3:18724`; autenticação normal de conta sintética, sem atalhos. Router existente confere a base QA `main_reference_20261104_test:55441`. Rascunho isolado `9a53831b-c54d-4fa4-a399-848b29000cfa`, recuperado sem recriação; rascunho de V12 e planos antigos não alterados.
|
||||||
|
|
||||||
|
| Critério | Evidência individual |
|
||||||
|
| --- | --- |
|
||||||
|
| Adesão explícita | Três agendas inicialmente manuais; uma confirmação recusada conservou o modo manual; três confirmações aceites activaram vendas, compras e serviços. Mensagens dos diálogos em `functional-receipt.json`; pressupostos anteriores à activação em `before-activation.json` |
|
||||||
|
| Prazos e caixa | Coortes de Janeiro de 2027, 30 dias: reconhecimento/origem aproximados em 31/01 e vencimento 02/03. Recebimentos 1.000, compras 400 e serviços 100 apenas em Março. Prazo zero de vendas demonstrado no editor: vencimento 31/01, caixa no mês 1; depois reposto 30 dias |
|
||||||
|
| Antecipações e datas insuficientes | Evento contratual em 01/01 com prazo zero, reconhecimento em 31/01: rejeitado, mesmo sendo o mesmo mês. Origem por confirmar: diagnóstico específico, sem agenda automática. Após correcção, mensagens desapareceram e os vencimentos regressaram |
|
||||||
|
| Reconciliação e ausência de duplicação | Tabelas reais em `desktop-tables.json`: recebíveis 1.000/1.000/0; obrigações 500/500/0; diferença de balanço zero em cada mês e no agregado. Cobrança manual de vendas 777 conservada no snapshot, inactiva no modo automático |
|
||||||
|
| Gravação e recuperação | Snapshot do servidor na versão 5 exactamente igual ao JSON exportado. Novos contextos autenticados sem armazenamento local recuperaram o mesmo contrato por GET HTTP 200, em computador e emulação móvel. Os restantes pressupostos financeiros e manuais são idênticos aos anteriores à activação |
|
||||||
|
| Apresentação | Capturas revistas em 1440×1000 e 390×844; editor dentro da largura disponível e parcelas/vencimentos legíveis. Painel de ajuda fechado pelo controlo normal quando sobrepunha a zona de trabalho. Emulação móvel, não ensaio num aparelho físico |
|
||||||
|
| Correcção delimitada na revisão final | Reproduzida a supressão indevida de outras receitas independentes pelo novo modo. Corrigida apenas a selecção da agenda activa, restaurando o reconhecimento já existente dessas receitas. Novo teste falhou antes e passou depois; editor confirmou 100 por mês de outras receitas, cobranças totais 100/100/1.100 e balanço reconciliado. Repuseram-se os dados sintéticos originais após esta prova |
|
||||||
|
|
||||||
|
### Verificações e limites
|
||||||
|
|
||||||
|
Reutilizados os 15 testes aprovados na implementação anterior: seis específicos de F20-A e nove dos contratos financeiros afectados. Não repetida a auditoria nem a bateria geral. Nesta retoma, executado um teste focado após a conclusão do CSV e, por causa da falha concreta identificada, o novo teste de receitas independentes e o teste directamente afectado de substituição/reconciliação/exportação: ambos aprovados. Total de casos distintos com prova: 16. Limites de calendário, transição anual/bissexto, duplicação e horizontes 1/60 conservam as provas específicas anteriores. Tipos já aprovados, lint final dos ficheiros afectados e compilação final isolada de QA aprovados. Avisos de fontaine opcional, tamanho de chunks e tempos de plugins permanecem avisos de compilação; não houve instalação para os eliminar.
|
||||||
|
|
||||||
|
As primeiras tentativas Playwright expuseram problemas do ensaio, não falhas financeiras: a página pública não redirecciona para login, selectores inadequados, espera por uma nova escrita quando o estado já estava guardado e sobreposição do painel de ajuda. Corrigido o mecanismo de prova com autenticação explícita, selectores semânticos, comparação do snapshot persistido e fecho normal da ajuda. Sem contornar autenticação, RLS ou restrições de segurança.
|
||||||
|
|
||||||
|
Recibos e imagens: [pasta E25](e25-f20-a-20261121/verification.json), com hashes individuais; [prova funcional](e25-f20-a-20261121/functional-receipt.json). Sessões, cookies e credenciais não versionados. Scripts internos recuperáveis em `outputs/v12-d1-d2-d3-20261120/f20-{browser,recovery,optin}.cjs`; não requerem instalar Playwright. Limites: máximo 240 parcelas e limite existente de 60 KB por snapshot; selecção manual/automática por agenda completa. F20-B e F22 continuam suspensos; nenhuma aprovação anterior reaberta. Sem instalação, publicação, migração ou alteração de dados activos.
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
{"version":20,"plan":{"currency":"MZN","openingCash":"1000","assetInvestment":"600","equity":"600","products":[{"label":"Serviço sintético F20-A","monthlyUnits":"0","unitPrice":"1000","unitVariableCost":"0","monthlyUnitsByPeriod":["1","0","0"]}],"depreciationLifeMonths":60,"periods":3,"monthlyCollections":"777","monthlyVariableCostPayments":"400","monthlyInventoryPurchases":"400","monthlyOperatingExpenses":"100","monthlyOperatingPayments":"100","monthlyPayrollExpense":"0","monthlyPayrollPayments":"0","inventory":"0","receivables":"0","payables":"0","shareholderLoans":"0","bankLoanProceeds":"0","grants":"0","assetDepreciation":"600","monthlyInterestExpense":"0","monthlyInterestPayment":"0","monthlyPrincipalRepayment":"0","salesCollectionLagMonths":0,"salesCollectionPercent":"100","openingReceivablesCollectionPercent":"0","reportAssumptions":{"startYear":"2027","openingFixedAssets":"0","openingOtherAssets":"0","openingEquity":"1000","startupExpenses":[{"label":"Constituição","amount":"100"}],"taxExpenseByMonth":["30","30","30"],"taxPaymentByMonth":["20","20","20"],"taxSource":"Hipótese sintética de teste; não é taxa legal","grantsTreatment":"","manualCollectionsKind":"sales"},"useInventoryPurchaseSchedule":true,"inventoryPurchaseSchedule":[{"amount":"400","leadMonths":0},{"amount":"0","leadMonths":0},{"amount":"0","leadMonths":0}],"monthlyOperatingExpensesByPeriod":["100","0","0"],"dayTerms":{"sales":false,"purchases":false,"services":false,"operations":[{"kind":"sales","month":1,"originId":"sales-1","parcelId":"1","amount":"1000","termDays":"30","recognitionBasis":"monthly","recognitionDate":"","originBasis":"recognition","originDate":""},{"kind":"purchases","month":1,"originId":"purchases-1","parcelId":"1","amount":"400","termDays":"30","recognitionBasis":"monthly","recognitionDate":"","originBasis":"recognition","originDate":""},{"kind":"services","month":1,"originId":"services-1","parcelId":"1","amount":"100","termDays":"30","recognitionBasis":"monthly","recognitionDate":"","originBasis":"recognition","originDate":""}]},"inventoryPurchaseLeadMonths":0,"useProductInventorySchedule":false,"useSupplierPaymentTerms":false,"monthlyVariableCostPaymentsByPeriod":null,"openingReceivablesCollectionMonth":null,"openingReceivablesInstallments":[],"openingPayablesInstallments":[],"salesRecoverySchedule":[]}}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"name": "Start-up / arranque",
|
||||||
|
"text": "Start-up / arranque\nRubrica\tValor\nConstituição\t100,00\nDespesas de arranque\t100,00\nInvestimento em activos\t600,00\nExistências iniciais\t0,00\nRecebíveis iniciais\t0,00\nObrigações iniciais\t0,00\nUsos líquidos iniciais\t700,00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Previsão de Vendas",
|
||||||
|
"text": "Previsão de Vendas\nRubrica\t2027-01\t2027-02\t2027-03\t2027 (parcial)\nServiço sintético F20-A\t1 000,00\t0,00\t0,00\t1 000,00\nVendas totais\t1 000,00\t0,00\t0,00\t1 000,00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Financiamento",
|
||||||
|
"text": "Financiamento\nRubrica\tValor\nCapital introduzido\t600,00\nSuprimentos\t0,00\nEmpréstimos\t0,00\nSubvenções declaradas\t0,00\nTotal de fontes\t600,00\nUsos líquidos com arranque\t700,00\nDiferença por financiar\t100,00\nCaixa após financiamento e arranque\t900,00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Ponto de Equilíbrio",
|
||||||
|
"text": "Ponto de Equilíbrio\nRubrica\t2027-01\t2027-02\t2027-03\t2027 (parcial)\nVendas de equilíbrio\t110,00\tIndeterminado — margem sem contribuição positiva\tIndeterminado — margem sem contribuição positiva\t130,00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lucros e Perdas",
|
||||||
|
"text": "Lucros e Perdas\nRubrica\t2027-01\t2027-02\t2027-03\t2027 (parcial)\nVendas\t1 000,00\t0,00\t0,00\t1 000,00\nOutras receitas de caixa declaradas\t0,00\t0,00\t0,00\t0,00\nCusto directo\t0,00\t0,00\t0,00\t0,00\nDespesas operacionais\t100,00\t0,00\t0,00\t100,00\nPessoal\t0,00\t0,00\t0,00\t0,00\nDepreciação\t10,00\t10,00\t10,00\t30,00\nJuros\t0,00\t0,00\t0,00\t0,00\nImposto estimado\t30,00\t30,00\t30,00\t90,00\nLucro líquido\t860,00\t-40,00\t-40,00\t780,00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Fluxo de Caixa",
|
||||||
|
"text": "Fluxo de Caixa\nRubrica\t2027-01\t2027-02\t2027-03\t2027 (parcial)\nCaixa inicial\t900,00\t880,00\t860,00\t900,00\nRecebimentos\t0,00\t0,00\t1 000,00\t1 000,00\nPagamentos de compras\t0,00\t0,00\t400,00\t400,00\nPagamentos operacionais\t0,00\t0,00\t100,00\t100,00\nPagamentos de pessoal\t0,00\t0,00\t0,00\t0,00\nJuros pagos\t0,00\t0,00\t0,00\t0,00\nCapital reembolsado\t0,00\t0,00\t0,00\t0,00\nPagamento de obrigações iniciais\t0,00\t0,00\t0,00\t0,00\nPagamento fiscal estimado\t20,00\t20,00\t20,00\t60,00\nFluxo líquido\t-20,00\t-20,00\t480,00\t440,00\nCaixa final\t880,00\t860,00\t1 340,00\t1 340,00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Balanço Projectado",
|
||||||
|
"text": "Balanço Projectado\nRubrica\t2027-01\t2027-02\t2027-03\t2027 (parcial)\nCaixa líquida\t880,00\t860,00\t1 340,00\t1 340,00\nRecebíveis líquidos\t1 000,00\t1 000,00\t0,00\t0,00\nObrigações operacionais líquidas\t500,00\t500,00\t0,00\t0,00\nSaldo fiscal estimado\t10,00\t20,00\t30,00\t30,00\nActivos fixos líquidos\t590,00\t580,00\t570,00\t570,00\nEmpréstimos e suprimentos por reembolsar\t0,00\t0,00\t0,00\t0,00\nCapital declarado e anterior\t1 600,00\t1 600,00\t1 600,00\t1 600,00\nResultados acumulados, incluindo arranque\t760,00\t720,00\t680,00\t680,00\nTotal do activo\t2 870,00\t2 840,00\t2 310,00\t2 310,00\nTotal do passivo\t510,00\t520,00\t30,00\t30,00\nCapital e resultados\t2 360,00\t2 320,00\t2 280,00\t2 280,00\nExistências\t400,00\t400,00\t400,00\t400,00\nDiferença do balanço\t0,00\t0,00\t0,00\t0,00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Linhas contabilísticas propostas para classificação fiscal",
|
||||||
|
"text": "Linhas contabilísticas propostas para classificação fiscal\nOrigem\tEfeito contabilístico\tTotal no período\tTratamento fiscal\nProdutos/serviços facturados\tRendimento; por mês: 1: 1000.00 · 2: 0.00 · 3: 0.00\t1000.00 MZN\tPor classificar\nCusto variável dos produtos\tDespesa; por mês: 1: 0.00 · 2: 0.00 · 3: 0.00\t0.00 MZN\tPor classificar\nDespesas operacionais reconhecidas\tDespesa; por mês: 1: 100.00 · 2: 0.00 · 3: 0.00\t100.00 MZN\tPor classificar\nDespesas com pessoal reconhecidas\tDespesa; por mês: 1: 0.00 · 2: 0.00 · 3: 0.00\t0.00 MZN\tPor classificar\nDepreciação contabilística\tDespesa; por mês: 1: 10.00 · 2: 10.00 · 3: 10.00\t30.00 MZN\tPor classificar\nJuros reconhecidos\tDespesa; por mês: 1: 0.00 · 2: 0.00 · 3: 0.00\t0.00 MZN\tPor classificar"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Encomendas, recepções, mercadoria em trânsito, consumo, falta e saldo de existências por mês",
|
||||||
|
"text": "Encomendas, recepções, mercadoria em trânsito, consumo, falta e saldo de existências por mês\nMês\tSaldo inicial\tEncomendas\tPrazo (meses)\tRecepções\tEm trânsito\tConsumo\tFalta de stock\tSaldo final\n1\t0.00\t400.00\t0\t400.00\t0.00\t0.00\t0.00\t400.00\n2\t400.00\t0.00\t0\t0.00\t0.00\t0.00\t0.00\t400.00\n3\t400.00\t0.00\t0\t0.00\t0.00\t0.00\t0.00\t400.00"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Resultados financeiros mensais antes de impostos",
|
||||||
|
"text": "Resultados financeiros mensais antes de impostos\nMês\tFacturação\tCobranças\tCobranças das vendas\tCobranças iniciais\tRecuperações vencidas\tCobrança de valores de abertura\tValores de abertura por receber\tOutras cobranças\tCustos variáveis\tDespesas/pessoal\tDepreciação\tJuros\tResultado antes de impostos\tPagamento de capital\tCaixa final\n1\t1000.00\t0.00\t0.00\t0.00\t0.00\t0.00\t0.00\t0.00\t0.00\t100.00 / 0.00\t10.00\t0.00\t890.00\t0.00\t1000.00\n2\t0.00\t0.00\t0.00\t0.00\t0.00\t0.00\t0.00\t0.00\t0.00\t0.00 / 0.00\t10.00\t0.00\t-10.00\t0.00\t1000.00\n3\t0.00\t1000.00\t1000.00\t1000.00\t0.00\t0.00\t0.00\t0.00\t0.00\t0.00 / 0.00\t10.00\t0.00\t-10.00\t0.00\t1500.00"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
After Width: | Height: | Size: 163 KiB |
@@ -0,0 +1,9 @@
|
|||||||
|
✔ F20-A replaces only opted-in cash agendas, preserves recognition and reconciles every monthly balance (48.401209ms)
|
||||||
|
ℹ tests 1
|
||||||
|
ℹ suites 0
|
||||||
|
ℹ pass 1
|
||||||
|
ℹ fail 0
|
||||||
|
ℹ cancelled 0
|
||||||
|
ℹ skipped 0
|
||||||
|
ℹ todo 0
|
||||||
|
ℹ duration_ms 362.476
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
{
|
||||||
|
"url": "http://127.0.0.3:18724/simulador-fiscal?draft=9a53831b-c54d-4fa4-a399-848b29000cfa",
|
||||||
|
"account": "synthetic-f20-a",
|
||||||
|
"draft": "9a53831b-c54d-4fa4-a399-848b29000cfa",
|
||||||
|
"viewports": [
|
||||||
|
{
|
||||||
|
"mobile": false,
|
||||||
|
"url": "http://127.0.0.3:18724/simulador-fiscal?draft=9a53831b-c54d-4fa4-a399-848b29000cfa",
|
||||||
|
"reads": [
|
||||||
|
{
|
||||||
|
"url": "http://127.0.0.3:18724/api/v1/simulation-drafts/9a53831b-c54d-4fa4-a399-848b29000cfa",
|
||||||
|
"status": 200
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "http://127.0.0.3:18724/api/v1/simulation-drafts/9a53831b-c54d-4fa4-a399-848b29000cfa/business-link",
|
||||||
|
"status": 200
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"bounds": {
|
||||||
|
"left": 206,
|
||||||
|
"right": 1234,
|
||||||
|
"width": 1440
|
||||||
|
},
|
||||||
|
"recoveredExactly": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"mobile": true,
|
||||||
|
"url": "http://127.0.0.3:18724/simulador-fiscal?draft=9a53831b-c54d-4fa4-a399-848b29000cfa",
|
||||||
|
"reads": [
|
||||||
|
{
|
||||||
|
"url": "http://127.0.0.3:18724/api/v1/simulation-drafts/9a53831b-c54d-4fa4-a399-848b29000cfa",
|
||||||
|
"status": 200
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"url": "http://127.0.0.3:18724/api/v1/simulation-drafts/9a53831b-c54d-4fa4-a399-848b29000cfa/business-link",
|
||||||
|
"status": 200
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"bounds": {
|
||||||
|
"left": 54,
|
||||||
|
"right": 336,
|
||||||
|
"width": 390
|
||||||
|
},
|
||||||
|
"recoveredExactly": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"dialogs": [
|
||||||
|
{
|
||||||
|
"action": "dismiss",
|
||||||
|
"message": "Activar prazos em dias para Vendas e prestações? A agenda em dias substitui toda a agenda de caixa desta categoria. Os valores anteriores ficam guardados e não serão somados. Confira primeiro as parcelas e as datas."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"action": "accept",
|
||||||
|
"message": "Activar prazos em dias para Vendas e prestações? A agenda em dias substitui toda a agenda de caixa desta categoria. Os valores anteriores ficam guardados e não serão somados. Confira primeiro as parcelas e as datas."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"action": "accept",
|
||||||
|
"message": "Activar prazos em dias para Mercadorias recebidas? A agenda em dias substitui toda a agenda de caixa desta categoria. Os valores anteriores ficam guardados e não serão somados. Confira primeiro as parcelas e as datas."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"action": "accept",
|
||||||
|
"message": "Activar prazos em dias para Serviços adquiridos reconhecidos? A agenda em dias substitui toda a agenda de caixa desta categoria. Os valores anteriores ficam guardados e não serão somados. Confira primeiro as parcelas e as datas."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"saves": [
|
||||||
|
{
|
||||||
|
"label": "recovered-desktop",
|
||||||
|
"status": 200,
|
||||||
|
"version": 5,
|
||||||
|
"persistedSnapshotMatchesEditor": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "recovered-mobile",
|
||||||
|
"status": 200,
|
||||||
|
"version": 5,
|
||||||
|
"persistedSnapshotMatchesEditor": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"errors": [],
|
||||||
|
"blocked": [],
|
||||||
|
"activationRecoveredFromPriorSuccessfulSave": true,
|
||||||
|
"events": "Vencimentos previstos\n\nVendas e prestações — sales-1/1: reconhecimento 2027-01-31; origem 2027-01-31; vencimento 2027-03-02; 1000.00 MZN. Aproximação mensal explícita. Caixa no mês 3.\n\nMercadorias recebidas — purchases-1/1: reconhecimento 2027-01-31; origem 2027-01-31; vencimento 2027-03-02; 400.00 MZN. Aproximação mensal explícita. Caixa no mês 3.\n\nServiços adquiridos reconhecidos — services-1/1: reconhecimento 2027-01-31; origem 2027-01-31; vencimento 2027-03-02; 100.00 MZN. Aproximação mensal explícita. Caixa no mês 3.",
|
||||||
|
"earlyMessage": "Prazos em dias — Mercadorias recebidas, origem purchases-1, parcela 1: vencimento anterior ao reconhecimento: antecipação excluída de F20-A. Use a agenda manual existente; adiantamentos identificados dependem de F20-B.",
|
||||||
|
"unknownMessage": "Prazos em dias — Mercadorias recebidas, origem purchases-1, parcela 1: data de origem do prazo insuficiente ou inválida; indique o evento contratual ou escolha reconhecimento. Operação excluída do cálculo automático.",
|
||||||
|
"zeroDays": "Vencimentos previstos\n\nVendas e prestações — sales-1/1: reconhecimento 2027-01-31; origem 2027-01-31; vencimento 2027-01-31; 1000.00 MZN. Aproximação mensal explícita. Caixa no mês 1.\n\nMercadorias recebidas — purchases-1/1: reconhecimento 2027-01-31; origem 2027-01-31; vencimento 2027-03-02; 400.00 MZN. Aproximação mensal explícita. Caixa no mês 3.\n\nServiços adquiridos reconhecidos — services-1/1: reconhecimento 2027-01-31; origem 2027-01-31; vencimento 2027-03-02; 100.00 MZN. Aproximação mensal explícita. Caixa no mês 3.",
|
||||||
|
"independentIncome": {
|
||||||
|
"profitRow": "Outras receitas de caixa declaradas\t100,00\t100,00\t100,00\t300,00",
|
||||||
|
"cashRow": "Recebimentos\t100,00\t100,00\t1 100,00\t1 300,00",
|
||||||
|
"balanceRow": "Diferença do balanço\t0,00\t0,00\t0,00\t0,00"
|
||||||
|
},
|
||||||
|
"realTablesVerified": true
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
✔ F20-A preserves explicitly classified independent other income when replacing sales collections (25.203542ms)
|
||||||
|
✔ F20-A replaces only opted-in cash agendas, preserves recognition and reconciles every monthly balance (4.100125ms)
|
||||||
|
ℹ tests 2
|
||||||
|
ℹ suites 0
|
||||||
|
ℹ pass 2
|
||||||
|
ℹ fail 0
|
||||||
|
ℹ cancelled 0
|
||||||
|
ℹ skipped 0
|
||||||
|
ℹ todo 0
|
||||||
|
ℹ duration_ms 309.050083
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
✖ F20-A preserves explicitly classified independent other income when replacing sales collections (56.082667ms)
|
||||||
|
ℹ tests 1
|
||||||
|
ℹ suites 0
|
||||||
|
ℹ pass 0
|
||||||
|
ℹ fail 1
|
||||||
|
ℹ cancelled 0
|
||||||
|
ℹ skipped 0
|
||||||
|
ℹ todo 0
|
||||||
|
ℹ duration_ms 460.2845
|
||||||
|
|
||||||
|
✖ failing tests:
|
||||||
|
|
||||||
|
test at tests\frontend\financial-day-terms.test.mjs:12:1
|
||||||
|
✖ F20-A preserves explicitly classified independent other income when replacing sales collections (56.082667ms)
|
||||||
|
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
|
||||||
|
+ actual - expected
|
||||||
|
|
||||||
|
[
|
||||||
|
+ '0.00',
|
||||||
|
+ '0.00',
|
||||||
|
+ '0.00'
|
||||||
|
- '100.00',
|
||||||
|
- '100.00',
|
||||||
|
- '100.00'
|
||||||
|
]
|
||||||
|
|
||||||
|
at TestContext.<anonymous> (file:///C:/laragon/www/portal-investidor-continuity-qa-20261120/tests/frontend/financial-day-terms.test.mjs:17:12)
|
||||||
|
at Test.runInAsyncScope (node:async_hooks:227:14)
|
||||||
|
at Test.run (node:internal/test_runner/test:1397:25)
|
||||||
|
at Test.start (node:internal/test_runner/test:1257:17)
|
||||||
|
at startSubtestAfterBootstrap (node:internal/test_runner/harness:387:17) {
|
||||||
|
generatedMessage: true,
|
||||||
|
code: 'ERR_ASSERTION',
|
||||||
|
actual: [ '0.00', '0.00', '0.00' ],
|
||||||
|
expected: [ '100.00', '100.00', '100.00' ],
|
||||||
|
operator: 'deepStrictEqual',
|
||||||
|
diff: 'simple'
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 132 KiB |
|
After Width: | Height: | Size: 188 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 136 KiB |
@@ -0,0 +1 @@
|
|||||||
|
{"version":20,"plan":{"currency":"MZN","openingCash":"1000","assetInvestment":"600","equity":"600","products":[{"label":"Serviço sintético F20-A","monthlyUnits":"0","unitPrice":"1000","unitVariableCost":"0","monthlyUnitsByPeriod":["1","0","0"]}],"depreciationLifeMonths":60,"periods":3,"monthlyCollections":"777","monthlyVariableCostPayments":"400","monthlyInventoryPurchases":"400","monthlyOperatingExpenses":"100","monthlyOperatingPayments":"100","monthlyPayrollExpense":"0","monthlyPayrollPayments":"0","inventory":"0","receivables":"0","payables":"0","shareholderLoans":"0","bankLoanProceeds":"0","grants":"0","assetDepreciation":"600","monthlyInterestExpense":"0","monthlyInterestPayment":"0","monthlyPrincipalRepayment":"0","salesCollectionLagMonths":0,"salesCollectionPercent":"100","openingReceivablesCollectionPercent":"0","reportAssumptions":{"startYear":"2027","openingFixedAssets":"0","openingOtherAssets":"0","openingEquity":"1000","startupExpenses":[{"label":"Constituição","amount":"100"}],"taxExpenseByMonth":["30","30","30"],"taxPaymentByMonth":["20","20","20"],"taxSource":"Hipótese sintética de teste; não é taxa legal","grantsTreatment":"","manualCollectionsKind":"sales"},"useInventoryPurchaseSchedule":true,"inventoryPurchaseSchedule":[{"amount":"400","leadMonths":0},{"amount":"0","leadMonths":0},{"amount":"0","leadMonths":0}],"monthlyOperatingExpensesByPeriod":["100","0","0"],"dayTerms":{"sales":true,"purchases":true,"services":true,"operations":[{"kind":"sales","month":1,"originId":"sales-1","parcelId":"1","amount":"1000","termDays":"30","recognitionBasis":"monthly","recognitionDate":"","originBasis":"recognition","originDate":""},{"kind":"purchases","month":1,"originId":"purchases-1","parcelId":"1","amount":"400","termDays":"30","recognitionBasis":"monthly","recognitionDate":"","originBasis":"recognition","originDate":"2027-01-01"},{"kind":"services","month":1,"originId":"services-1","parcelId":"1","amount":"100","termDays":"30","recognitionBasis":"monthly","recognitionDate":"","originBasis":"recognition","originDate":""}]},"inventoryPurchaseLeadMonths":0,"useProductInventorySchedule":false,"useSupplierPaymentTerms":false,"monthlyVariableCostPaymentsByPeriod":null,"openingReceivablesCollectionMonth":null,"openingReceivablesInstallments":[],"openingPayablesInstallments":[],"salesRecoverySchedule":[]}}
|
||||||
|
After Width: | Height: | Size: 177 KiB |
|
After Width: | Height: | Size: 69 KiB |
@@ -0,0 +1,45 @@
|
|||||||
|
{
|
||||||
|
"date": "2026-11-21",
|
||||||
|
"scope": "F20-A only; F20 global partial; awaiting owner acceptance",
|
||||||
|
"qa": {
|
||||||
|
"url": "http://127.0.0.3:18724",
|
||||||
|
"database": "main_reference_20261104_test",
|
||||||
|
"port": 55441,
|
||||||
|
"syntheticDraft": "9a53831b-c54d-4fa4-a399-848b29000cfa"
|
||||||
|
},
|
||||||
|
"checks": {
|
||||||
|
"priorFocusedTestsReused": 15,
|
||||||
|
"priorFinancialScenariosPreserved": 6,
|
||||||
|
"additionalRegression": "independent other income: reproduced failure, corrected, passed",
|
||||||
|
"affectedReconciliationAndExportTest": "passed after correction",
|
||||||
|
"types": "prior applicable check passed; no type contract changed in final correction",
|
||||||
|
"lint": "final affected files passed",
|
||||||
|
"build": "final isolated QA build passed",
|
||||||
|
"desktop": "1440x1000, new authenticated storage, exact server recovery",
|
||||||
|
"mobile": "390x844 emulation, new authenticated storage, exact server recovery",
|
||||||
|
"matrixRows": 88,
|
||||||
|
"unchangedOtherRows": 87
|
||||||
|
},
|
||||||
|
"limits": [
|
||||||
|
"not production or physical handset certification",
|
||||||
|
"manual mode is selected for the entire corresponding agenda; independent other income remains active",
|
||||||
|
"F20-B advances and F22 not implemented",
|
||||||
|
"existing 60 KB snapshot limit; at most 240 day-term parcels"
|
||||||
|
],
|
||||||
|
"hashes": {
|
||||||
|
"before-activation.json": "d781e1ac27512ea925d23788dfd49a47808230e91bdafb7f91272d77ea3fc0dc",
|
||||||
|
"desktop-tables.json": "94e862a89b32078f4f2a27fb94a9c5be1b708b3a95841a0a3a751202b07b58b3",
|
||||||
|
"early-payment-desktop.png": "71474f0ba2ea5fdc3db4e20cb70bab6a4a73139d0ba311def7dc93cdba92c2c2",
|
||||||
|
"export-focused-test.log": "de6250f35cdcfd3f8362539252380828fa811965a431c5dedcfd112c2b8f9027",
|
||||||
|
"functional-receipt.json": "fdb2e9ea4896ec515382fce4c6686ca79312c7631276c22e2ddf3b16b9d86aae",
|
||||||
|
"independent-income-after.log": "b396e819d642f83519c28ae2872436b42ae1eb65e7aee2a05199ec7539a645de",
|
||||||
|
"independent-income-before.log": "4961533883853af13f631984dffe8edc8c0fad8b8b6d6f69f9747f1fd665e1a5",
|
||||||
|
"independent-income-desktop.png": "aa4e3d17f07ff3b9a0f097462a5366aaea2d212ccc39e28e2af1470a6d4d9c52",
|
||||||
|
"initial-desktop.png": "8290d563c29a904ffd1b4799a5b520d9dfe6a909bae4fb8998dcd1c944303709",
|
||||||
|
"parcelas-mobile.png": "f0104f4c54275d8a763235604cdd7400f9ec6558f06570656c59e383330609c5",
|
||||||
|
"recovered-desktop.png": "0cbcb0cdde746bd3dda01d29db15cc9c463c58279faa9dd548bc21db2a21362f",
|
||||||
|
"saved.json": "7921afdfabf89c0c54545ad6521c97b97c150ef94e9d0f0772d06131da8c0c83",
|
||||||
|
"vencimentos-desktop.png": "e309b203af1bce606e3ec2f49178f16ad0ca95047b1db45bc364278a065d1a78",
|
||||||
|
"vencimentos-mobile.png": "ee85b453b0a137790ce8b07da051d9263bbf53546a645d15b2329b2ca857891a"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,364 @@
|
|||||||
|
import {
|
||||||
|
forecastBusinessPlan,
|
||||||
|
type BusinessFinancialPlanInput,
|
||||||
|
} from '@/lib/business-financial-plan';
|
||||||
|
import {
|
||||||
|
dayTermLabels,
|
||||||
|
type DayTermKind,
|
||||||
|
type DayTermOperation,
|
||||||
|
type DayTerms,
|
||||||
|
} from '@/lib/financial-day-terms';
|
||||||
|
|
||||||
|
const kinds = Object.keys(dayTermLabels) as DayTermKind[];
|
||||||
|
const empty = (): DayTerms => ({
|
||||||
|
sales: false,
|
||||||
|
purchases: false,
|
||||||
|
services: false,
|
||||||
|
operations: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
export function FinancialDayTerms({
|
||||||
|
plan,
|
||||||
|
onChange,
|
||||||
|
}: {
|
||||||
|
plan: BusinessFinancialPlanInput;
|
||||||
|
onChange: (plan: BusinessFinancialPlanInput) => void;
|
||||||
|
}) {
|
||||||
|
const config = plan.dayTerms ?? empty();
|
||||||
|
const save = (next: DayTerms) => onChange({ ...plan, dayTerms: next });
|
||||||
|
const update = (index: number, patch: Partial<DayTermOperation>) =>
|
||||||
|
save({
|
||||||
|
...config,
|
||||||
|
operations: config.operations.map((o, i) =>
|
||||||
|
i === index ? { ...o, ...patch } : o,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
let economic: ReturnType<typeof forecastBusinessPlan> | undefined;
|
||||||
|
let calculated: ReturnType<typeof forecastBusinessPlan> | undefined;
|
||||||
|
try {
|
||||||
|
economic = forecastBusinessPlan({ ...plan, dayTerms: undefined });
|
||||||
|
} catch {
|
||||||
|
/* Existing diagnostics remain in the report. */
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
calculated = forecastBusinessPlan(plan);
|
||||||
|
} catch {
|
||||||
|
/* One existing report diagnostic, no duplicate here. */
|
||||||
|
}
|
||||||
|
const prepare = (kind: DayTermKind) => {
|
||||||
|
if (
|
||||||
|
!economic ||
|
||||||
|
config[kind] ||
|
||||||
|
config.operations.some((o) => o.kind === kind)
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
const operations: DayTermOperation[] = [];
|
||||||
|
for (const row of economic.rows) {
|
||||||
|
const amount =
|
||||||
|
kind === 'sales'
|
||||||
|
? row.revenue
|
||||||
|
: kind === 'purchases'
|
||||||
|
? row.inventoryReceipts
|
||||||
|
: row.operatingExpenses;
|
||||||
|
if (amount === null || Number(amount) === 0) continue;
|
||||||
|
operations.push({
|
||||||
|
kind,
|
||||||
|
month: row.month,
|
||||||
|
amount,
|
||||||
|
originId: `${kind}-${row.month}`,
|
||||||
|
parcelId: '1',
|
||||||
|
recognitionBasis: 'monthly',
|
||||||
|
recognitionDate: '',
|
||||||
|
originBasis: 'recognition',
|
||||||
|
originDate: '',
|
||||||
|
termDays: '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
save({ ...config, operations: [...config.operations, ...operations] });
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<details className="my-3 min-w-0 space-y-3 rounded border p-3">
|
||||||
|
<summary className="font-semibold">
|
||||||
|
Prazos em dias — operações sem adiantamentos
|
||||||
|
</summary>
|
||||||
|
<p>
|
||||||
|
Adesão opcional por agenda. A agenda em dias substitui
|
||||||
|
integralmente a agenda de caixa correspondente, incluindo
|
||||||
|
cobranças mensais e recuperações de vendas do período. Os
|
||||||
|
valores manuais correspondentes ficam guardados, inactivos;
|
||||||
|
outras receitas explicitamente classificadas mantêm-se activas.
|
||||||
|
Os saldos de abertura mantêm as agendas próprias. Para misturar
|
||||||
|
operações datadas e coortes, distribua o total reconhecido entre
|
||||||
|
parcelas sem repetir montantes.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Mercadorias: só após recepção reconhecida. Serviços adquiridos:
|
||||||
|
este modo abrange a totalidade das despesas operacionais
|
||||||
|
declaradas; use-o apenas se todas corresponderem a serviços
|
||||||
|
elegíveis. Não inclui salários, impostos, juros, empréstimos ou
|
||||||
|
novos activos. Antecipações e datas insuficientes bloqueiam o
|
||||||
|
cálculo automático, sem conversão para pagamentos normais.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Sem data individual, escolha explicitamente «Último dia do mês
|
||||||
|
(aproximação)». O vencimento também será aproximado. A origem
|
||||||
|
dos pagamentos é o evento contratual indicado; não se presume
|
||||||
|
que factura e recepção coincidam. O prazo em dias deste editor é
|
||||||
|
independente do campo histórico usado nos avisos de crédito.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Ano inicial:{' '}
|
||||||
|
{plan.reportAssumptions?.startYear ||
|
||||||
|
'preencha o ano no relatório financeiro integral'}
|
||||||
|
. Horizonte: {plan.periods} meses. Os vencimentos posteriores
|
||||||
|
ficam identificados fora do horizonte.
|
||||||
|
</p>
|
||||||
|
{kinds.map((kind) => (
|
||||||
|
<fieldset
|
||||||
|
key={kind}
|
||||||
|
className="min-w-0 space-y-2 rounded border p-3"
|
||||||
|
>
|
||||||
|
<legend className="font-medium">
|
||||||
|
{dayTermLabels[kind]}
|
||||||
|
</legend>
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Modo de {dayTermLabels[kind]}
|
||||||
|
<select
|
||||||
|
className="w-full rounded border p-2"
|
||||||
|
value={config[kind] ? 'days' : 'manual'}
|
||||||
|
onChange={(e) => {
|
||||||
|
if (
|
||||||
|
e.target.value === 'days' &&
|
||||||
|
!window.confirm(
|
||||||
|
`Activar prazos em dias para ${dayTermLabels[kind]}? A agenda em dias substitui toda a agenda de caixa desta categoria. Os valores anteriores ficam guardados e não serão somados. Confira primeiro as parcelas e as datas.`,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
save({
|
||||||
|
...config,
|
||||||
|
[kind]: e.target.value === 'days',
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="manual">
|
||||||
|
Agenda anterior/manual preservada
|
||||||
|
</option>
|
||||||
|
<option value="days">
|
||||||
|
Prazos em dias (adesão explícita)
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="rounded border px-3 py-2"
|
||||||
|
disabled={
|
||||||
|
!economic ||
|
||||||
|
config[kind] ||
|
||||||
|
config.operations.some((o) => o.kind === kind)
|
||||||
|
}
|
||||||
|
onClick={() => prepare(kind)}
|
||||||
|
>
|
||||||
|
Preparar coortes mensais de {dayTermLabels[kind]}
|
||||||
|
</button>
|
||||||
|
<p className="text-sm">
|
||||||
|
Preparar coortes não activa o modo. Revise os valores,
|
||||||
|
indique o prazo de cada parcela e só depois escolha o
|
||||||
|
modo em dias.
|
||||||
|
</p>
|
||||||
|
{config.operations.map((o, index) =>
|
||||||
|
o.kind !== kind ? null : (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="grid min-w-0 gap-2 rounded border p-3 sm:grid-cols-2 lg:grid-cols-3"
|
||||||
|
aria-label={`Parcela ${index + 1} de ${dayTermLabels[kind]}`}
|
||||||
|
>
|
||||||
|
{(
|
||||||
|
[
|
||||||
|
['Origem', 'originId'],
|
||||||
|
['Parcela', 'parcelId'],
|
||||||
|
['Montante', 'amount'],
|
||||||
|
['Prazo (dias)', 'termDays'],
|
||||||
|
] as const
|
||||||
|
).map(([label, key]) => (
|
||||||
|
<label
|
||||||
|
key={key}
|
||||||
|
className="grid min-w-0 gap-1"
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
<input
|
||||||
|
className="w-full min-w-0 rounded border p-2"
|
||||||
|
value={o[key]}
|
||||||
|
onChange={(e) =>
|
||||||
|
update(index, {
|
||||||
|
[key]: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Mês económico
|
||||||
|
<input
|
||||||
|
className="w-full min-w-0 rounded border p-2"
|
||||||
|
type="number"
|
||||||
|
min="1"
|
||||||
|
max={plan.periods}
|
||||||
|
value={o.month}
|
||||||
|
onChange={(e) =>
|
||||||
|
update(index, {
|
||||||
|
month: Number(e.target.value),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Reconhecimento
|
||||||
|
<select
|
||||||
|
className="w-full min-w-0 rounded border p-2"
|
||||||
|
value={o.recognitionBasis}
|
||||||
|
onChange={(e) =>
|
||||||
|
update(index, {
|
||||||
|
recognitionBasis: e.target
|
||||||
|
.value as DayTermOperation['recognitionBasis'],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="unknown">
|
||||||
|
Data por confirmar (excluída)
|
||||||
|
</option>
|
||||||
|
<option value="monthly">
|
||||||
|
Último dia do mês (aproximação)
|
||||||
|
</option>
|
||||||
|
<option value="date">
|
||||||
|
Data individual
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
{o.recognitionBasis === 'date' && (
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Data de reconhecimento
|
||||||
|
<input
|
||||||
|
className="w-full min-w-0 rounded border p-2"
|
||||||
|
type="date"
|
||||||
|
value={o.recognitionDate}
|
||||||
|
onChange={(e) =>
|
||||||
|
update(index, {
|
||||||
|
recognitionDate:
|
||||||
|
e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Origem do prazo
|
||||||
|
<select
|
||||||
|
className="w-full min-w-0 rounded border p-2"
|
||||||
|
value={o.originBasis}
|
||||||
|
onChange={(e) =>
|
||||||
|
update(index, {
|
||||||
|
originBasis: e.target
|
||||||
|
.value as DayTermOperation['originBasis'],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="unknown">
|
||||||
|
Evento por confirmar (excluído)
|
||||||
|
</option>
|
||||||
|
<option value="recognition">
|
||||||
|
Na data do reconhecimento
|
||||||
|
</option>
|
||||||
|
<option value="date">
|
||||||
|
Data do evento contratual
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
{o.originBasis === 'date' && (
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Data de origem do prazo
|
||||||
|
<input
|
||||||
|
className="w-full min-w-0 rounded border p-2"
|
||||||
|
type="date"
|
||||||
|
value={o.originDate}
|
||||||
|
onChange={(e) =>
|
||||||
|
update(index, {
|
||||||
|
originDate: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="rounded border px-3 py-2"
|
||||||
|
onClick={() =>
|
||||||
|
save({
|
||||||
|
...config,
|
||||||
|
operations:
|
||||||
|
config.operations.filter(
|
||||||
|
(_, i) => i !== index,
|
||||||
|
),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Remover parcela {index + 1}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="rounded border px-3 py-2"
|
||||||
|
disabled={config.operations.length >= 240}
|
||||||
|
onClick={() =>
|
||||||
|
save({
|
||||||
|
...config,
|
||||||
|
operations: [
|
||||||
|
...config.operations,
|
||||||
|
{
|
||||||
|
kind,
|
||||||
|
originId: '',
|
||||||
|
parcelId: '',
|
||||||
|
month: 1,
|
||||||
|
amount: '',
|
||||||
|
termDays: '',
|
||||||
|
recognitionBasis: 'unknown',
|
||||||
|
recognitionDate: '',
|
||||||
|
originBasis: 'unknown',
|
||||||
|
originDate: '',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Adicionar parcela de {dayTermLabels[kind]}
|
||||||
|
</button>
|
||||||
|
</fieldset>
|
||||||
|
))}
|
||||||
|
{calculated?.dayTermEvents && (
|
||||||
|
<section aria-label="Vencimentos em dias" className="space-y-2">
|
||||||
|
<h4 className="font-semibold">Vencimentos previstos</h4>
|
||||||
|
{calculated.dayTermEvents.map((e) => (
|
||||||
|
<p
|
||||||
|
key={JSON.stringify([
|
||||||
|
e.kind,
|
||||||
|
e.originId,
|
||||||
|
e.parcelId,
|
||||||
|
])}
|
||||||
|
>
|
||||||
|
{dayTermLabels[e.kind]} — {e.originId}/{e.parcelId}:
|
||||||
|
reconhecimento {e.recognition}; origem {e.origin};
|
||||||
|
vencimento {e.due}; {e.amount} {plan.currency}.{' '}
|
||||||
|
{e.approximate
|
||||||
|
? 'Aproximação mensal explícita.'
|
||||||
|
: 'Datas individuais.'}{' '}
|
||||||
|
{e.outsideHorizon
|
||||||
|
? 'Fora do horizonte; não incluído na caixa do plano.'
|
||||||
|
: `Caixa no mês ${e.dueMonth}.`}
|
||||||
|
</p>
|
||||||
|
))}
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</details>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -26,6 +26,7 @@ import { MarketAnalysisPlan } from '@/components/market-analysis-plan';
|
|||||||
import { FinancialRatiosPlan } from '@/components/financial-ratios-plan';
|
import { FinancialRatiosPlan } from '@/components/financial-ratios-plan';
|
||||||
import { PlanEconomicClassification } from '@/components/plan-economic-classification';
|
import { PlanEconomicClassification } from '@/components/plan-economic-classification';
|
||||||
import { FinancialPlanDetails } from '@/components/financial-plan-details';
|
import { FinancialPlanDetails } from '@/components/financial-plan-details';
|
||||||
|
import { FinancialDayTerms } from '@/components/financial-day-terms';
|
||||||
import { StartupAssetRequirements } from '@/components/startup-asset-requirements';
|
import { StartupAssetRequirements } from '@/components/startup-asset-requirements';
|
||||||
import {
|
import {
|
||||||
forecastErrorShownInReport,
|
forecastErrorShownInReport,
|
||||||
@@ -948,6 +949,7 @@ export function SimulationBusinessPlan({
|
|||||||
)}
|
)}
|
||||||
<PlanEconomicClassification plan={plan} onChange={savePlan} />
|
<PlanEconomicClassification plan={plan} onChange={savePlan} />
|
||||||
<FinancialPlanDetails plan={plan} onChange={savePlan} />
|
<FinancialPlanDetails plan={plan} onChange={savePlan} />
|
||||||
|
<FinancialDayTerms plan={plan} onChange={savePlan} />
|
||||||
<StartupAssetRequirements
|
<StartupAssetRequirements
|
||||||
plan={plan}
|
plan={plan}
|
||||||
onChange={savePlan}
|
onChange={savePlan}
|
||||||
|
|||||||
@@ -1,3 +1,8 @@
|
|||||||
|
import {
|
||||||
|
buildDayTermSchedule,
|
||||||
|
isDayTerms,
|
||||||
|
type DayTerms,
|
||||||
|
} from './financial-day-terms.ts';
|
||||||
import { csvCell } from './csv.js';
|
import { csvCell } from './csv.js';
|
||||||
import { calculateStartupAssetRequirements } from './startup-asset-requirements.ts';
|
import { calculateStartupAssetRequirements } from './startup-asset-requirements.ts';
|
||||||
|
|
||||||
@@ -83,6 +88,8 @@ function validCurrency(value: string): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type BusinessFinancialPlanInput = {
|
export type BusinessFinancialPlanInput = {
|
||||||
|
/** Explicit opt-in. Missing keeps all historical calculations unchanged. */
|
||||||
|
dayTerms?: DayTerms;
|
||||||
economicClassification?: {
|
economicClassification?: {
|
||||||
code: string;
|
code: string;
|
||||||
revision: string;
|
revision: string;
|
||||||
@@ -202,22 +209,25 @@ export function serializeBusinessPlanSnapshot(
|
|||||||
plan: BusinessFinancialPlanInput,
|
plan: BusinessFinancialPlanInput,
|
||||||
): string {
|
): string {
|
||||||
const snapshot = JSON.stringify({
|
const snapshot = JSON.stringify({
|
||||||
version: plan.startupAssetRequirements
|
version:
|
||||||
? 19
|
plan.dayTerms !== undefined
|
||||||
: [
|
? 20
|
||||||
'applyAnnualGrowth',
|
: plan.startupAssetRequirements
|
||||||
'creditTermDays',
|
? 19
|
||||||
'dividendsByPeriod',
|
: [
|
||||||
'operatingExpenseLines',
|
'applyAnnualGrowth',
|
||||||
'fundingBreakdown',
|
'creditTermDays',
|
||||||
'reportSource',
|
'dividendsByPeriod',
|
||||||
].some(
|
'operatingExpenseLines',
|
||||||
(key) =>
|
'fundingBreakdown',
|
||||||
plan[key as keyof BusinessFinancialPlanInput] !==
|
'reportSource',
|
||||||
undefined,
|
].some(
|
||||||
)
|
(key) =>
|
||||||
? 18
|
plan[key as keyof BusinessFinancialPlanInput] !==
|
||||||
: 17,
|
undefined,
|
||||||
|
)
|
||||||
|
? 18
|
||||||
|
: 17,
|
||||||
plan: {
|
plan: {
|
||||||
...plan,
|
...plan,
|
||||||
...(plan.useSupplierPaymentTerms === true
|
...(plan.useSupplierPaymentTerms === true
|
||||||
@@ -301,12 +311,18 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
decoded.version !== 16 &&
|
decoded.version !== 16 &&
|
||||||
decoded.version !== 17 &&
|
decoded.version !== 17 &&
|
||||||
decoded.version !== 18 &&
|
decoded.version !== 18 &&
|
||||||
decoded.version !== 19) ||
|
decoded.version !== 19 &&
|
||||||
|
decoded.version !== 20) ||
|
||||||
!decoded.plan ||
|
!decoded.plan ||
|
||||||
typeof decoded.plan !== 'object'
|
typeof decoded.plan !== 'object'
|
||||||
)
|
)
|
||||||
return null;
|
return null;
|
||||||
const plan = decoded.plan as Record<string, unknown>;
|
const plan = decoded.plan as Record<string, unknown>;
|
||||||
|
if (
|
||||||
|
plan.dayTerms !== undefined &&
|
||||||
|
(decoded.version !== 20 || !isDayTerms(plan.dayTerms))
|
||||||
|
)
|
||||||
|
return null;
|
||||||
if (
|
if (
|
||||||
decoded.version < 18 &&
|
decoded.version < 18 &&
|
||||||
[
|
[
|
||||||
@@ -439,7 +455,7 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
)
|
)
|
||||||
return null;
|
return null;
|
||||||
if (
|
if (
|
||||||
[12, 13, 14, 15, 16, 17].includes(Number(decoded.version)) &&
|
[12, 13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) &&
|
||||||
(!Object.hasOwn(plan, 'inventoryPurchaseSchedule') ||
|
(!Object.hasOwn(plan, 'inventoryPurchaseSchedule') ||
|
||||||
!Object.hasOwn(plan, 'useInventoryPurchaseSchedule') ||
|
!Object.hasOwn(plan, 'useInventoryPurchaseSchedule') ||
|
||||||
typeof plan.useInventoryPurchaseSchedule !== 'boolean')
|
typeof plan.useInventoryPurchaseSchedule !== 'boolean')
|
||||||
@@ -450,7 +466,9 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
plan.inventoryPurchaseSchedule !== null
|
plan.inventoryPurchaseSchedule !== null
|
||||||
) {
|
) {
|
||||||
if (
|
if (
|
||||||
![12, 13, 14, 15, 16, 17].includes(Number(decoded.version)) ||
|
![12, 13, 14, 15, 16, 17, 20].includes(
|
||||||
|
Number(decoded.version),
|
||||||
|
) ||
|
||||||
!Array.isArray(plan.inventoryPurchaseSchedule) ||
|
!Array.isArray(plan.inventoryPurchaseSchedule) ||
|
||||||
plan.inventoryPurchaseSchedule.length < Number(plan.periods) ||
|
plan.inventoryPurchaseSchedule.length < Number(plan.periods) ||
|
||||||
plan.inventoryPurchaseSchedule.length > 60 ||
|
plan.inventoryPurchaseSchedule.length > 60 ||
|
||||||
@@ -473,14 +491,14 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
)
|
)
|
||||||
return null;
|
return null;
|
||||||
if (
|
if (
|
||||||
[13, 14, 15, 16, 17].includes(Number(decoded.version)) &&
|
[13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) &&
|
||||||
!Object.hasOwn(plan, 'monthlyVariableCostPaymentsByPeriod')
|
!Object.hasOwn(plan, 'monthlyVariableCostPaymentsByPeriod')
|
||||||
)
|
)
|
||||||
return null;
|
return null;
|
||||||
if (
|
if (
|
||||||
plan.monthlyVariableCostPaymentsByPeriod !== undefined &&
|
plan.monthlyVariableCostPaymentsByPeriod !== undefined &&
|
||||||
plan.monthlyVariableCostPaymentsByPeriod !== null &&
|
plan.monthlyVariableCostPaymentsByPeriod !== null &&
|
||||||
(![13, 14, 15, 16, 17].includes(Number(decoded.version)) ||
|
(![13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) ||
|
||||||
!Array.isArray(plan.monthlyVariableCostPaymentsByPeriod) ||
|
!Array.isArray(plan.monthlyVariableCostPaymentsByPeriod) ||
|
||||||
plan.monthlyVariableCostPaymentsByPeriod.length <
|
plan.monthlyVariableCostPaymentsByPeriod.length <
|
||||||
Number(plan.periods) ||
|
Number(plan.periods) ||
|
||||||
@@ -545,7 +563,7 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
if (openingCollectionRate < 0n || openingCollectionRate > 100_000_000n)
|
if (openingCollectionRate < 0n || openingCollectionRate > 100_000_000n)
|
||||||
return null;
|
return null;
|
||||||
if (
|
if (
|
||||||
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17].includes(
|
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
|
||||||
Number(decoded.version),
|
Number(decoded.version),
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
@@ -618,7 +636,7 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
)
|
)
|
||||||
return null;
|
return null;
|
||||||
if (
|
if (
|
||||||
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17].includes(
|
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
|
||||||
Number(decoded.version),
|
Number(decoded.version),
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
@@ -657,7 +675,7 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
const schedule = plan[field];
|
const schedule = plan[field];
|
||||||
if (
|
if (
|
||||||
schedule !== undefined &&
|
schedule !== undefined &&
|
||||||
(![11, 12, 13, 14, 15, 16, 17].includes(
|
(![11, 12, 13, 14, 15, 16, 17, 20].includes(
|
||||||
Number(decoded.version),
|
Number(decoded.version),
|
||||||
) ||
|
) ||
|
||||||
!Array.isArray(schedule) ||
|
!Array.isArray(schedule) ||
|
||||||
@@ -747,7 +765,7 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
const costSchedule = productData.unitVariableCostByPeriod;
|
const costSchedule = productData.unitVariableCostByPeriod;
|
||||||
const validMoneySchedule = (values: unknown) =>
|
const validMoneySchedule = (values: unknown) =>
|
||||||
values === undefined ||
|
values === undefined ||
|
||||||
([10, 11, 12, 13, 14, 15, 16, 17].includes(
|
([10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
|
||||||
Number(decoded.version),
|
Number(decoded.version),
|
||||||
) &&
|
) &&
|
||||||
Array.isArray(values) &&
|
Array.isArray(values) &&
|
||||||
@@ -756,7 +774,7 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
values.every((value) => typeof value === 'string'));
|
values.every((value) => typeof value === 'string'));
|
||||||
return (
|
return (
|
||||||
(schedule !== undefined &&
|
(schedule !== undefined &&
|
||||||
(![9, 10, 11, 12, 13, 14, 15, 16, 17].includes(
|
(![9, 10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
|
||||||
Number(decoded.version),
|
Number(decoded.version),
|
||||||
) ||
|
) ||
|
||||||
!Array.isArray(schedule) ||
|
!Array.isArray(schedule) ||
|
||||||
@@ -795,7 +813,7 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
entry.paymentLagMonths < 0 ||
|
entry.paymentLagMonths < 0 ||
|
||||||
entry.paymentLagMonths > 12)) ||
|
entry.paymentLagMonths > 12)) ||
|
||||||
(entry.paymentInstallments !== undefined &&
|
(entry.paymentInstallments !== undefined &&
|
||||||
(![16, 17].includes(
|
(![16, 17, 20].includes(
|
||||||
Number(decoded.version),
|
Number(decoded.version),
|
||||||
) ||
|
) ||
|
||||||
!Array.isArray(
|
!Array.isArray(
|
||||||
@@ -853,7 +871,7 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
})
|
})
|
||||||
)
|
)
|
||||||
return null;
|
return null;
|
||||||
return {
|
const restored = {
|
||||||
...plan,
|
...plan,
|
||||||
inventoryPurchaseLeadMonths: Number(
|
inventoryPurchaseLeadMonths: Number(
|
||||||
plan.inventoryPurchaseLeadMonths ?? 0,
|
plan.inventoryPurchaseLeadMonths ?? 0,
|
||||||
@@ -915,6 +933,9 @@ export function restoreBusinessPlanSnapshot(
|
|||||||
? plan.monthlyVariableCostPaymentsByPeriod.map(String)
|
? plan.monthlyVariableCostPaymentsByPeriod.map(String)
|
||||||
: null,
|
: null,
|
||||||
} as unknown as BusinessFinancialPlanInput;
|
} as unknown as BusinessFinancialPlanInput;
|
||||||
|
if (restored.dayTerms && !options.editable)
|
||||||
|
forecastBusinessPlan(restored);
|
||||||
|
return restored;
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -1439,7 +1460,47 @@ export function compareBusinessScenarios(input: BusinessFinancialPlanInput) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Forecast separates invoiced sales, collections, accounting expenses and cash payments. */
|
/** Forecast separates invoiced sales, collections, accounting expenses and cash payments. */
|
||||||
|
type ActiveDayTerms = ReturnType<typeof buildDayTermSchedule> & {
|
||||||
|
config: DayTerms;
|
||||||
|
};
|
||||||
|
|
||||||
export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||||
|
const config = input.dayTerms;
|
||||||
|
if (config !== undefined && !isDayTerms(config))
|
||||||
|
throw new Error('Prazos em dias: estrutura inválida.');
|
||||||
|
if (!config || !(config.sales || config.purchases || config.services))
|
||||||
|
return forecastBusinessPlanBase(input);
|
||||||
|
// First pass obtains economic recognition from the unchanged calculator. The second
|
||||||
|
// replaces only opted-in cash schedules. Neither pass mutates stored/manual inputs.
|
||||||
|
const economic = forecastBusinessPlanBase(input);
|
||||||
|
if (!input.reportAssumptions?.startYear?.trim())
|
||||||
|
throw new Error(
|
||||||
|
'Prazos em dias — Ano inicial: preencha o ano do relatório.',
|
||||||
|
);
|
||||||
|
const day = buildDayTermSchedule(
|
||||||
|
config,
|
||||||
|
Number(input.reportAssumptions.startYear),
|
||||||
|
economic.rows.length,
|
||||||
|
{
|
||||||
|
sales: economic.rows.map((r) => cents(r.revenue, 'Vendas')),
|
||||||
|
purchases: economic.rows.map((r) =>
|
||||||
|
r.inventoryReceipts === null
|
||||||
|
? null
|
||||||
|
: cents(r.inventoryReceipts, 'Recepções'),
|
||||||
|
),
|
||||||
|
services: economic.rows.map((r) =>
|
||||||
|
cents(r.operatingExpenses, 'Serviços reconhecidos'),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
cents,
|
||||||
|
);
|
||||||
|
return forecastBusinessPlanBase(input, { ...day, config });
|
||||||
|
}
|
||||||
|
|
||||||
|
function forecastBusinessPlanBase(
|
||||||
|
input: BusinessFinancialPlanInput,
|
||||||
|
day?: ActiveDayTerms,
|
||||||
|
) {
|
||||||
if (input.startupAssetRequirements) {
|
if (input.startupAssetRequirements) {
|
||||||
const needs = calculateStartupAssetRequirements(input);
|
const needs = calculateStartupAssetRequirements(input);
|
||||||
if (
|
if (
|
||||||
@@ -2243,10 +2304,13 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
|||||||
const rows = [];
|
const rows = [];
|
||||||
|
|
||||||
for (let month = 1; month <= periods; month++) {
|
for (let month = 1; month <= periods; month++) {
|
||||||
const periodVariableCostPayment =
|
const periodVariableCostPayment = day?.config.purchases
|
||||||
variableCostPaymentsByPeriod[month - 1];
|
? day.schedules.purchases[month - 1]
|
||||||
|
: variableCostPaymentsByPeriod[month - 1];
|
||||||
const periodOperatingExpense = operatingExpenseByPeriod[month - 1];
|
const periodOperatingExpense = operatingExpenseByPeriod[month - 1];
|
||||||
const periodOperatingPayment = operatingPaymentsByPeriod[month - 1];
|
const periodOperatingPayment = day?.config.services
|
||||||
|
? day.schedules.services[month - 1]
|
||||||
|
: operatingPaymentsByPeriod[month - 1];
|
||||||
const periodPayrollExpense = payrollExpenseByPeriod[month - 1];
|
const periodPayrollExpense = payrollExpenseByPeriod[month - 1];
|
||||||
const periodPayrollPayment = payrollPaymentsByPeriod[month - 1];
|
const periodPayrollPayment = payrollPaymentsByPeriod[month - 1];
|
||||||
const revenue = revenueByPeriod[month - 1];
|
const revenue = revenueByPeriod[month - 1];
|
||||||
@@ -2368,7 +2432,14 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
|||||||
let salesCollections: bigint | null = null;
|
let salesCollections: bigint | null = null;
|
||||||
let salesScheduledCollections: bigint | null = null;
|
let salesScheduledCollections: bigint | null = null;
|
||||||
let salesRecoveryCollections: bigint | null = null;
|
let salesRecoveryCollections: bigint | null = null;
|
||||||
if (salesCollectionLagMonths !== null) {
|
if (day?.config.sales) {
|
||||||
|
salesCollections = day.schedules.sales[month - 1];
|
||||||
|
salesScheduledCollections = salesCollections;
|
||||||
|
salesRecoveryCollections = 0n;
|
||||||
|
salesReceivables += revenue - salesCollections;
|
||||||
|
totalSalesCollections += salesCollections;
|
||||||
|
totalScheduledSalesCollections += salesCollections;
|
||||||
|
} else if (salesCollectionLagMonths !== null) {
|
||||||
const collectionMonth = month + salesCollectionLagMonths;
|
const collectionMonth = month + salesCollectionLagMonths;
|
||||||
const scheduledCollection =
|
const scheduledCollection =
|
||||||
(revenue * salesCollectionRate + 50_000_000n) / 100_000_000n;
|
(revenue * salesCollectionRate + 50_000_000n) / 100_000_000n;
|
||||||
@@ -2415,7 +2486,13 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
|||||||
totalSalesRecoveryCollections += salesRecoveryCollections;
|
totalSalesRecoveryCollections += salesRecoveryCollections;
|
||||||
totalSalesCollections += salesCollections;
|
totalSalesCollections += salesCollections;
|
||||||
}
|
}
|
||||||
const totalCollections = monthlyCollections + (salesCollections ?? 0n);
|
const activeManualCollections =
|
||||||
|
day?.config.sales &&
|
||||||
|
input.reportAssumptions?.manualCollectionsKind !== 'other_income'
|
||||||
|
? 0n
|
||||||
|
: monthlyCollections;
|
||||||
|
const totalCollections =
|
||||||
|
activeManualCollections + (salesCollections ?? 0n);
|
||||||
const legacyOpeningReceivablesCollections =
|
const legacyOpeningReceivablesCollections =
|
||||||
month === openingReceivablesCollectionMonth
|
month === openingReceivablesCollectionMonth
|
||||||
? openingReceivablesCollectionAmount
|
? openingReceivablesCollectionAmount
|
||||||
@@ -2463,7 +2540,9 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
|||||||
? null
|
? null
|
||||||
: format(salesRecoveryCollections),
|
: format(salesRecoveryCollections),
|
||||||
otherCollections:
|
otherCollections:
|
||||||
salesCollections === null ? null : format(monthlyCollections),
|
salesCollections === null
|
||||||
|
? null
|
||||||
|
: format(activeManualCollections),
|
||||||
salesReceivablesClosing:
|
salesReceivablesClosing:
|
||||||
salesCollections === null ? null : format(salesReceivables),
|
salesCollections === null ? null : format(salesReceivables),
|
||||||
variableCost: format(costOfSales),
|
variableCost: format(costOfSales),
|
||||||
@@ -2572,8 +2651,9 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
|||||||
paymentLagMonths: order.paymentLagMonths,
|
paymentLagMonths: order.paymentLagMonths,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
paymentSchedule:
|
paymentSchedule: day?.config.purchases
|
||||||
supplierPaymentSchedules?.[index] ?? null,
|
? null
|
||||||
|
: (supplierPaymentSchedules?.[index] ?? null),
|
||||||
totalPurchases: format(
|
totalPurchases: format(
|
||||||
productStockInputs[index].orders!.reduce(
|
productStockInputs[index].orders!.reduce(
|
||||||
(sum, order) => sum + order.amount,
|
(sum, order) => sum + order.amount,
|
||||||
@@ -2651,26 +2731,36 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
|||||||
amount: format(installment.amount),
|
amount: format(installment.amount),
|
||||||
})),
|
})),
|
||||||
totalSalesCollections:
|
totalSalesCollections:
|
||||||
salesCollectionLagMonths === null
|
salesCollectionLagMonths === null && !day?.config.sales
|
||||||
? null
|
? null
|
||||||
: format(totalSalesCollections),
|
: format(totalSalesCollections),
|
||||||
totalScheduledSalesCollections:
|
totalScheduledSalesCollections:
|
||||||
salesCollectionLagMonths === null
|
salesCollectionLagMonths === null && !day?.config.sales
|
||||||
? null
|
? null
|
||||||
: format(totalScheduledSalesCollections),
|
: format(totalScheduledSalesCollections),
|
||||||
totalSalesRecoveryCollections:
|
totalSalesRecoveryCollections:
|
||||||
salesCollectionLagMonths === null
|
salesCollectionLagMonths === null && !day?.config.sales
|
||||||
? null
|
? null
|
||||||
: format(totalSalesRecoveryCollections),
|
: format(totalSalesRecoveryCollections),
|
||||||
salesReceivablesAtEnd:
|
salesReceivablesAtEnd:
|
||||||
salesCollectionLagMonths === null ? null : format(salesReceivables),
|
salesCollectionLagMonths === null && !day?.config.sales
|
||||||
|
? null
|
||||||
|
: format(salesReceivables),
|
||||||
salesCollectionLagMonths,
|
salesCollectionLagMonths,
|
||||||
salesCollectionPercent:
|
salesCollectionPercent:
|
||||||
salesCollectionLagMonths === null ? null : salesCollectionPercent,
|
salesCollectionLagMonths === null && !day?.config.sales
|
||||||
|
? null
|
||||||
|
: salesCollectionPercent,
|
||||||
totalPayments: format(totalOperatingPayments),
|
totalPayments: format(totalOperatingPayments),
|
||||||
supplierPaymentsOutstandingAtEnd: useSupplierPaymentTerms
|
supplierPaymentsOutstandingAtEnd: day?.config.purchases
|
||||||
? format(supplierPaymentsOutstanding)
|
? format(
|
||||||
: null,
|
day.events
|
||||||
|
.filter((e) => e.kind === 'purchases' && e.outsideHorizon)
|
||||||
|
.reduce((sum, e) => sum + BigInt(e.amount), 0n),
|
||||||
|
)
|
||||||
|
: useSupplierPaymentTerms
|
||||||
|
? format(supplierPaymentsOutstanding)
|
||||||
|
: null,
|
||||||
totalProfitBeforeTax: format(totalProfitBeforeTax),
|
totalProfitBeforeTax: format(totalProfitBeforeTax),
|
||||||
endingCash: format(cash),
|
endingCash: format(cash),
|
||||||
inventoryProjection,
|
inventoryProjection,
|
||||||
@@ -2940,7 +3030,19 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
return { ...output, presentationCurrency, conversion };
|
return {
|
||||||
|
...output,
|
||||||
|
presentationCurrency,
|
||||||
|
conversion,
|
||||||
|
...(day
|
||||||
|
? {
|
||||||
|
dayTermEvents: day.events.map((e) => ({
|
||||||
|
...e,
|
||||||
|
amount: format(BigInt(e.amount)),
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Reproducible local report: original assumptions, declared FX basis, and the same forecast totals. */
|
/** Reproducible local report: original assumptions, declared FX basis, and the same forecast totals. */
|
||||||
@@ -3495,6 +3597,38 @@ export function exportBusinessPlanCsv(
|
|||||||
'Estimativa sem aconselhamento fiscal, parâmetros legais, sazonalidade, inflação ou validação contabilística. Moeda original preservada.',
|
'Estimativa sem aconselhamento fiscal, parâmetros legais, sazonalidade, inflação ou validação contabilística. Moeda original preservada.',
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
|
if (result.dayTermEvents) {
|
||||||
|
rows.push(
|
||||||
|
[],
|
||||||
|
[
|
||||||
|
'Prazos em dias — agendas anteriores das categorias seleccionadas conservadas inactivas',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'Categoria',
|
||||||
|
'Origem',
|
||||||
|
'Parcela',
|
||||||
|
'Reconhecimento',
|
||||||
|
'Origem do prazo',
|
||||||
|
'Vencimento',
|
||||||
|
'Montante',
|
||||||
|
'Precisão',
|
||||||
|
'Horizonte',
|
||||||
|
],
|
||||||
|
...result.dayTermEvents.map((e) => [
|
||||||
|
e.kind,
|
||||||
|
e.originId,
|
||||||
|
e.parcelId,
|
||||||
|
e.recognition,
|
||||||
|
e.origin,
|
||||||
|
e.due,
|
||||||
|
e.amount,
|
||||||
|
e.approximate ? 'aproximação mensal' : 'datas individuais',
|
||||||
|
e.outsideHorizon
|
||||||
|
? 'fora do horizonte, sem caixa neste plano'
|
||||||
|
: `mês ${e.dueMonth}`,
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
}
|
||||||
return `\uFEFF${rows
|
return `\uFEFF${rows
|
||||||
.map((row) => row.map(csvCell).join(','))
|
.map((row) => row.map(csvCell).join(','))
|
||||||
.join('\r\n')}`;
|
.join('\r\n')}`;
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
export type DayTermKind = 'sales' | 'purchases' | 'services';
|
||||||
|
export type DayTermOperation = {
|
||||||
|
originId: string;
|
||||||
|
parcelId: string;
|
||||||
|
kind: DayTermKind;
|
||||||
|
month: number;
|
||||||
|
amount: string;
|
||||||
|
recognitionBasis: 'monthly' | 'date' | 'unknown';
|
||||||
|
recognitionDate: string;
|
||||||
|
originBasis: 'recognition' | 'date' | 'unknown';
|
||||||
|
originDate: string;
|
||||||
|
termDays: string;
|
||||||
|
};
|
||||||
|
export type DayTerms = {
|
||||||
|
sales: boolean;
|
||||||
|
purchases: boolean;
|
||||||
|
services: boolean;
|
||||||
|
operations: DayTermOperation[];
|
||||||
|
};
|
||||||
|
export const dayTermLabels: Record<DayTermKind, string> = {
|
||||||
|
sales: 'Vendas e prestações',
|
||||||
|
purchases: 'Mercadorias recebidas',
|
||||||
|
services: 'Serviços adquiridos reconhecidos',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function isDayTerms(value: unknown): value is DayTerms {
|
||||||
|
if (!value || typeof value !== 'object') return false;
|
||||||
|
const c = value as DayTerms;
|
||||||
|
return (
|
||||||
|
['sales', 'purchases', 'services'].every(
|
||||||
|
(k) => typeof c[k as DayTermKind] === 'boolean',
|
||||||
|
) &&
|
||||||
|
Array.isArray(c.operations) &&
|
||||||
|
c.operations.length <= 240 &&
|
||||||
|
c.operations.every(
|
||||||
|
(o) =>
|
||||||
|
o &&
|
||||||
|
Object.hasOwn(dayTermLabels, o.kind) &&
|
||||||
|
Number.isSafeInteger(o.month) &&
|
||||||
|
o.month >= 1 &&
|
||||||
|
o.month <= 60 &&
|
||||||
|
[
|
||||||
|
'originId',
|
||||||
|
'parcelId',
|
||||||
|
'amount',
|
||||||
|
'recognitionDate',
|
||||||
|
'originDate',
|
||||||
|
'termDays',
|
||||||
|
].every(
|
||||||
|
(k) =>
|
||||||
|
typeof o[k as keyof DayTermOperation] === 'string' &&
|
||||||
|
String(o[k as keyof DayTermOperation]).length <= 160,
|
||||||
|
) &&
|
||||||
|
['monthly', 'date', 'unknown'].includes(o.recognitionBasis) &&
|
||||||
|
['recognition', 'date', 'unknown'].includes(o.originBasis),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function civilDate(value: string): Date | null {
|
||||||
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
|
||||||
|
const d = new Date(value + 'T00:00:00.000Z');
|
||||||
|
return Number.isFinite(d.getTime()) &&
|
||||||
|
d.toISOString().slice(0, 10) === value
|
||||||
|
? d
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
const iso = (d: Date) => d.toISOString().slice(0, 10);
|
||||||
|
|
||||||
|
/** Only opted-in channels replace their complete cash agenda. No legacy input is mutated. */
|
||||||
|
export function buildDayTermSchedule(
|
||||||
|
config: DayTerms,
|
||||||
|
year: number,
|
||||||
|
periods: number,
|
||||||
|
recognized: Record<DayTermKind, (bigint | null)[]>,
|
||||||
|
parseAmount: (value: string, label: string) => bigint,
|
||||||
|
) {
|
||||||
|
if (!isDayTerms(config))
|
||||||
|
throw new Error(
|
||||||
|
'Prazos em dias: estrutura inválida. Reveja operações e parcelas.',
|
||||||
|
);
|
||||||
|
if (!Number.isSafeInteger(year) || year < 1900 || year > 9993)
|
||||||
|
throw new Error(
|
||||||
|
'Prazos em dias — Ano inicial: indique o ano do relatório entre 1900 e 9993.',
|
||||||
|
);
|
||||||
|
const schedules: Record<DayTermKind, bigint[]> = {
|
||||||
|
sales: Array(periods).fill(0n),
|
||||||
|
purchases: Array(periods).fill(0n),
|
||||||
|
services: Array(periods).fill(0n),
|
||||||
|
};
|
||||||
|
const amounts: Record<DayTermKind, bigint[]> = {
|
||||||
|
sales: Array(periods).fill(0n),
|
||||||
|
purchases: Array(periods).fill(0n),
|
||||||
|
services: Array(periods).fill(0n),
|
||||||
|
};
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const origins = new Map<string, string>();
|
||||||
|
const events = config.operations
|
||||||
|
.filter((o) => config[o.kind])
|
||||||
|
.map((o) => {
|
||||||
|
const label = `Prazos em dias — ${dayTermLabels[o.kind]}, origem ${o.originId || 'por preencher'}, parcela ${o.parcelId || 'por preencher'}`;
|
||||||
|
const fail = (message: string): never => {
|
||||||
|
throw new Error(`${label}: ${message}`);
|
||||||
|
};
|
||||||
|
if (!o.originId.trim() || !o.parcelId.trim())
|
||||||
|
fail('preencha a origem e a parcela para impedir duplicações.');
|
||||||
|
const key = JSON.stringify([
|
||||||
|
o.kind,
|
||||||
|
o.originId.trim(),
|
||||||
|
o.parcelId.trim(),
|
||||||
|
]);
|
||||||
|
if (seen.has(key))
|
||||||
|
fail(
|
||||||
|
'parcela duplicada; conserve apenas um movimento da mesma origem/parcela.',
|
||||||
|
);
|
||||||
|
seen.add(key);
|
||||||
|
if (o.month > periods)
|
||||||
|
fail(
|
||||||
|
'mês de reconhecimento fora do horizonte; reveja o mês ou use a agenda manual.',
|
||||||
|
);
|
||||||
|
const start = new Date(Date.UTC(year, o.month - 1, 1));
|
||||||
|
const recognition =
|
||||||
|
o.recognitionBasis === 'monthly'
|
||||||
|
? new Date(Date.UTC(year, o.month, 0))
|
||||||
|
: o.recognitionBasis === 'date'
|
||||||
|
? civilDate(o.recognitionDate)
|
||||||
|
: null;
|
||||||
|
if (!recognition)
|
||||||
|
fail(
|
||||||
|
'data de reconhecimento insuficiente ou inválida; indique uma data ou escolha explicitamente a aproximação mensal. Operação excluída do cálculo automático.',
|
||||||
|
);
|
||||||
|
const r = recognition!;
|
||||||
|
if (
|
||||||
|
r.getUTCFullYear() !== start.getUTCFullYear() ||
|
||||||
|
r.getUTCMonth() !== start.getUTCMonth()
|
||||||
|
)
|
||||||
|
fail(
|
||||||
|
'data de reconhecimento não pertence ao mês económico indicado; corrija a data ou o mês.',
|
||||||
|
);
|
||||||
|
const origin =
|
||||||
|
o.originBasis === 'recognition'
|
||||||
|
? r
|
||||||
|
: o.originBasis === 'date'
|
||||||
|
? civilDate(o.originDate)
|
||||||
|
: null;
|
||||||
|
if (!origin)
|
||||||
|
fail(
|
||||||
|
'data de origem do prazo insuficiente ou inválida; indique o evento contratual ou escolha reconhecimento. Operação excluída do cálculo automático.',
|
||||||
|
);
|
||||||
|
if (o.kind === 'sales' && iso(origin!) !== iso(r))
|
||||||
|
fail(
|
||||||
|
'origem do recebimento deve ser a venda/prestação reconhecida; corrija a origem.',
|
||||||
|
);
|
||||||
|
if (!/^\d+$/.test(o.termDays) || Number(o.termDays) > 365)
|
||||||
|
fail(
|
||||||
|
'Prazo (dias): indique um inteiro entre 0 e 365; vazio não significa zero.',
|
||||||
|
);
|
||||||
|
const due = new Date(origin!.getTime());
|
||||||
|
due.setUTCDate(due.getUTCDate() + Number(o.termDays));
|
||||||
|
if (due < r)
|
||||||
|
fail(
|
||||||
|
'vencimento anterior ao reconhecimento: antecipação excluída de F20-A. Use a agenda manual existente; adiantamentos identificados dependem de F20-B.',
|
||||||
|
);
|
||||||
|
const amount = parseAmount(o.amount, `${label} — Montante`);
|
||||||
|
const originKey = JSON.stringify([o.kind, o.originId.trim()]);
|
||||||
|
const identity = JSON.stringify([
|
||||||
|
o.month,
|
||||||
|
iso(r),
|
||||||
|
o.recognitionBasis,
|
||||||
|
]);
|
||||||
|
if (origins.has(originKey) && origins.get(originKey) !== identity)
|
||||||
|
fail(
|
||||||
|
'parcelas da mesma origem têm reconhecimentos diferentes; confira origem, mês e data.',
|
||||||
|
);
|
||||||
|
origins.set(originKey, identity);
|
||||||
|
amounts[o.kind][o.month - 1] += amount;
|
||||||
|
const dueMonth =
|
||||||
|
(due.getUTCFullYear() - year) * 12 + due.getUTCMonth() + 1;
|
||||||
|
if (dueMonth <= periods) schedules[o.kind][dueMonth - 1] += amount;
|
||||||
|
return {
|
||||||
|
...o,
|
||||||
|
amount: amount.toString(),
|
||||||
|
recognition: iso(r),
|
||||||
|
origin: iso(origin!),
|
||||||
|
due: iso(due),
|
||||||
|
dueMonth,
|
||||||
|
approximate: o.recognitionBasis === 'monthly',
|
||||||
|
outsideHorizon: dueMonth > periods,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
for (const kind of Object.keys(dayTermLabels) as DayTermKind[]) {
|
||||||
|
if (!config[kind]) continue;
|
||||||
|
for (let i = 0; i < periods; i++) {
|
||||||
|
if (recognized[kind][i] === null)
|
||||||
|
throw new Error(
|
||||||
|
`Prazos em dias — ${dayTermLabels[kind]}, mês ${i + 1}: reconhecimento indeterminado; preencha a agenda económica antes de activar este modo.`,
|
||||||
|
);
|
||||||
|
if (amounts[kind][i] !== recognized[kind][i])
|
||||||
|
throw new Error(
|
||||||
|
`Prazos em dias — ${dayTermLabels[kind]}, mês ${i + 1}: a soma dos montantes das origens/parcelas deve coincidir com o valor reconhecido. Corrija a distribuição; não some uma coorte às operações já individualizadas.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { schedules, events };
|
||||||
|
}
|
||||||
@@ -224,6 +224,7 @@ export function buildIntegralFinancialTables(
|
|||||||
'Escolha o tratamento das subvenções: capital ou passivo diferido.',
|
'Escolha o tratamento das subvenções: capital ou passivo diferido.',
|
||||||
);
|
);
|
||||||
if (
|
if (
|
||||||
|
!plan.dayTerms?.sales &&
|
||||||
cents(plan.monthlyCollections) > 0n &&
|
cents(plan.monthlyCollections) > 0n &&
|
||||||
!['sales', 'other_income'].includes(a.manualCollectionsKind)
|
!['sales', 'other_income'].includes(a.manualCollectionsKind)
|
||||||
)
|
)
|
||||||
@@ -784,6 +785,15 @@ export function buildIntegralFinancialTables(
|
|||||||
table('break-even').notes.push(
|
table('break-even').notes.push(
|
||||||
'Vendas de equilíbrio = custos fixos operacionais, pessoal e depreciação ÷ margem de contribuição ponderada. Juros e impostos excluídos. Arredondamento apenas no resultado final, ao centavo.',
|
'Vendas de equilíbrio = custos fixos operacionais, pessoal e depreciação ÷ margem de contribuição ponderada. Juros e impostos excluídos. Arredondamento apenas no resultado final, ao centavo.',
|
||||||
);
|
);
|
||||||
|
if (result.dayTermEvents) {
|
||||||
|
table('cashflow').notes.push(
|
||||||
|
'Prazos em dias: as agendas seleccionadas substituem as agendas anteriores de caixa, conservadas inactivas. Saldos de abertura mantêm as agendas próprias. Não inclui adiantamentos.',
|
||||||
|
...result.dayTermEvents.map(
|
||||||
|
(e) =>
|
||||||
|
`${e.kind === 'sales' ? 'Vendas/prestações' : e.kind === 'purchases' ? 'Mercadorias recebidas' : 'Serviços adquiridos'} — ${e.originId}/${e.parcelId}: ${e.amount} ${plan.currency}; reconhecimento ${e.recognition}; origem ${e.origin}; vencimento ${e.due}${e.approximate ? ' (aproximação mensal)' : ''}; ${e.outsideHorizon ? 'fora do horizonte, sem movimento de caixa neste plano' : `mês de caixa ${e.dueMonth}`}.`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
for (const entry of tables)
|
for (const entry of tables)
|
||||||
entry.issues.push(
|
entry.issues.push(
|
||||||
|
|||||||
@@ -0,0 +1,211 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {
|
||||||
|
forecastBusinessPlan,
|
||||||
|
serializeBusinessPlanSnapshot,
|
||||||
|
restoreBusinessPlanSnapshot,
|
||||||
|
exportBusinessPlanCsv,
|
||||||
|
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||||
|
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
|
||||||
|
import { dayTermsFixture, operation } from './fixtures/financial-day-terms.mjs';
|
||||||
|
|
||||||
|
test('F20-A preserves explicitly classified independent other income when replacing sales collections', () => {
|
||||||
|
const p = dayTermsFixture();
|
||||||
|
p.monthlyCollections = '100';
|
||||||
|
p.reportAssumptions.manualCollectionsKind = 'other_income';
|
||||||
|
const r = forecastBusinessPlan(p);
|
||||||
|
assert.deepEqual(
|
||||||
|
r.rows.map((row) => row.otherCollections),
|
||||||
|
['100.00', '100.00', '100.00'],
|
||||||
|
);
|
||||||
|
assert.equal(r.totalCashCollections, '1300.00');
|
||||||
|
const tables = buildIntegralFinancialTables(p);
|
||||||
|
assert.deepEqual(
|
||||||
|
tables
|
||||||
|
.find((t) => t.id === 'profit-loss')
|
||||||
|
.rows.find((r) => r[0] === 'Outras receitas de caixa declaradas')
|
||||||
|
.slice(1),
|
||||||
|
['100.00', '100.00', '100.00', '300.00'],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
tables
|
||||||
|
.find((t) => t.id === 'balance')
|
||||||
|
.rows.find((r) => r[0] === 'Diferença do balanço')
|
||||||
|
.slice(1),
|
||||||
|
['0.00', '0.00', '0.00', '0.00'],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F20-A replaces only opted-in cash agendas, preserves recognition and reconciles every monthly balance', () => {
|
||||||
|
const p = dayTermsFixture();
|
||||||
|
const before = structuredClone(p);
|
||||||
|
const r = forecastBusinessPlan(p);
|
||||||
|
assert.deepEqual(p, before);
|
||||||
|
assert.deepEqual(
|
||||||
|
r.rows.map((r) => r.salesCollections),
|
||||||
|
['0.00', '0.00', '1000.00'],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
r.rows.map((r) => r.variableCostPayments),
|
||||||
|
['0.00', '0.00', '400.00'],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
r.rows.map((r) => r.operatingPayments),
|
||||||
|
['0.00', '0.00', '100.00'],
|
||||||
|
);
|
||||||
|
assert.equal(r.totalCashCollections, '1000.00');
|
||||||
|
assert.equal(r.rows[0].revenue, '1000.00');
|
||||||
|
assert.equal(r.rows[0].inventoryReceipts, '400.00');
|
||||||
|
assert.equal(r.rows[0].operatingExpenses, '100.00');
|
||||||
|
assert.equal(r.salesReceivablesAtEnd, '0.00');
|
||||||
|
const tables = buildIntegralFinancialTables(p);
|
||||||
|
const balance = tables.find((t) => t.id === 'balance');
|
||||||
|
assert.deepEqual(
|
||||||
|
balance.rows.find((r) => r[0] === 'Diferença do balanço').slice(1),
|
||||||
|
['0.00', '0.00', '0.00', '0.00'],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
balance.rows
|
||||||
|
.find((r) => r[0] === 'Obrigações operacionais líquidas')
|
||||||
|
.slice(1, 4),
|
||||||
|
['500.00', '500.00', '0.00'],
|
||||||
|
);
|
||||||
|
assert.ok(
|
||||||
|
tables.every((t) => t.issues.length === 0),
|
||||||
|
JSON.stringify(tables.map((t) => t.issues)),
|
||||||
|
);
|
||||||
|
assert.match(
|
||||||
|
tables.find((t) => t.id === 'cashflow').notes.join(' '),
|
||||||
|
/2027-03-02.*aproximação/,
|
||||||
|
);
|
||||||
|
assert.match(exportBusinessPlanCsv(p), /2027-03-02/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F20-A calendar days cover zero, individual dates, leap February and year transition', () => {
|
||||||
|
const p = dayTermsFixture();
|
||||||
|
p.dayTerms.operations.forEach((o) => (o.termDays = '0'));
|
||||||
|
assert.equal(forecastBusinessPlan(p).rows[0].salesCollections, '1000.00');
|
||||||
|
const sale = p.dayTerms.operations[0];
|
||||||
|
Object.assign(sale, {
|
||||||
|
recognitionBasis: 'date',
|
||||||
|
recognitionDate: '2027-01-20',
|
||||||
|
termDays: '30',
|
||||||
|
});
|
||||||
|
let r = forecastBusinessPlan(p);
|
||||||
|
assert.equal(r.dayTermEvents[0].due, '2027-02-19');
|
||||||
|
assert.equal(r.dayTermEvents[0].approximate, false);
|
||||||
|
sale.recognitionBasis = 'monthly';
|
||||||
|
p.reportAssumptions.startYear = '2028';
|
||||||
|
assert.equal(forecastBusinessPlan(p).dayTermEvents[0].due, '2028-03-01');
|
||||||
|
p.reportAssumptions.startYear = '2027';
|
||||||
|
sale.termDays = '365';
|
||||||
|
assert.equal(forecastBusinessPlan(p).dayTermEvents[0].due, '2028-01-31');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F20-A excludes early and unknown payments including within the same month, never silently normalizes them', () => {
|
||||||
|
const p = dayTermsFixture();
|
||||||
|
const o = p.dayTerms.operations[1];
|
||||||
|
Object.assign(o, {
|
||||||
|
recognitionBasis: 'date',
|
||||||
|
recognitionDate: '2027-01-25',
|
||||||
|
originBasis: 'date',
|
||||||
|
originDate: '2027-01-01',
|
||||||
|
termDays: '0',
|
||||||
|
});
|
||||||
|
assert.throws(() => forecastBusinessPlan(p), /antecipação excluída/);
|
||||||
|
assert.equal(
|
||||||
|
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p)),
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
assert.ok(
|
||||||
|
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p), {
|
||||||
|
editable: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
o.termDays = '30';
|
||||||
|
assert.equal(forecastBusinessPlan(p).dayTermEvents[1].due, '2027-01-31');
|
||||||
|
o.originBasis = 'unknown';
|
||||||
|
assert.throws(() => forecastBusinessPlan(p), /origem.*insuficiente/);
|
||||||
|
o.originBasis = 'recognition';
|
||||||
|
o.recognitionBasis = 'unknown';
|
||||||
|
assert.throws(() => forecastBusinessPlan(p), /reconhecimento insuficiente/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F20-A parcels reconcile to recognition and reject duplicates without merging distinct equal payments', () => {
|
||||||
|
const p = dayTermsFixture();
|
||||||
|
const original = p.dayTerms.operations[1];
|
||||||
|
original.amount = '200';
|
||||||
|
const second = { ...original, parcelId: '2' };
|
||||||
|
p.dayTerms.operations.push(second);
|
||||||
|
assert.equal(
|
||||||
|
forecastBusinessPlan(p).rows[2].variableCostPayments,
|
||||||
|
'400.00',
|
||||||
|
);
|
||||||
|
second.parcelId = '1';
|
||||||
|
assert.throws(() => forecastBusinessPlan(p), /duplicada/);
|
||||||
|
second.originId = 'another';
|
||||||
|
assert.equal(
|
||||||
|
forecastBusinessPlan(p).rows[2].variableCostPayments,
|
||||||
|
'400.00',
|
||||||
|
);
|
||||||
|
second.amount = '201';
|
||||||
|
assert.throws(() => forecastBusinessPlan(p), /soma dos montantes/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F20-A retains future receivables and payables at horizons 1 and 60 and restores manual schedules explicitly', () => {
|
||||||
|
for (const periods of [1, 60]) {
|
||||||
|
const p = dayTermsFixture(periods);
|
||||||
|
p.dayTerms.operations.forEach((o) => {
|
||||||
|
o.month = periods;
|
||||||
|
o.originId += '-last';
|
||||||
|
o.termDays = '365';
|
||||||
|
});
|
||||||
|
p.products[0].monthlyUnitsByPeriod = Array(periods).fill('0');
|
||||||
|
p.products[0].monthlyUnitsByPeriod[periods - 1] = '1';
|
||||||
|
p.inventoryPurchaseSchedule.forEach(
|
||||||
|
(o, i) => (o.amount = i === periods - 1 ? '400' : '0'),
|
||||||
|
);
|
||||||
|
p.monthlyOperatingExpensesByPeriod = Array(periods).fill('0');
|
||||||
|
p.monthlyOperatingExpensesByPeriod[periods - 1] = '100';
|
||||||
|
const r = forecastBusinessPlan(p);
|
||||||
|
assert.equal(r.totalCashCollections, '0.00');
|
||||||
|
assert.equal(r.supplierPaymentsOutstandingAtEnd, '400.00');
|
||||||
|
assert.equal(r.salesReceivablesAtEnd, '1000.00');
|
||||||
|
assert.ok(r.dayTermEvents.every((e) => e.outsideHorizon));
|
||||||
|
assert.equal(r.rows.at(-1).variableCostPayments, '0.00');
|
||||||
|
}
|
||||||
|
const p = dayTermsFixture();
|
||||||
|
const legacy = { ...p, dayTerms: undefined };
|
||||||
|
p.dayTerms.sales = p.dayTerms.purchases = p.dayTerms.services = false;
|
||||||
|
assert.deepEqual(forecastBusinessPlan(p), forecastBusinessPlan(legacy));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F20-A version 20 recovers dates, inactive manual inputs and outcomes; invalid terms and foreign versions are rejected', () => {
|
||||||
|
const p = dayTermsFixture();
|
||||||
|
const snapshot = serializeBusinessPlanSnapshot(p);
|
||||||
|
assert.equal(JSON.parse(snapshot).version, 20);
|
||||||
|
const recovered = restoreBusinessPlanSnapshot(snapshot);
|
||||||
|
assert.ok(recovered);
|
||||||
|
assert.deepEqual(recovered.dayTerms, p.dayTerms);
|
||||||
|
assert.equal(recovered.monthlyCollections, '777');
|
||||||
|
assert.deepEqual(forecastBusinessPlan(recovered), forecastBusinessPlan(p));
|
||||||
|
assert.equal(
|
||||||
|
restoreBusinessPlanSnapshot(
|
||||||
|
snapshot.replace('"version":20', '"version":19'),
|
||||||
|
),
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
for (const termDays of ['', '-1', '366', '1.5', 'abc']) {
|
||||||
|
p.dayTerms.operations[0].termDays = termDays;
|
||||||
|
assert.throws(() => forecastBusinessPlan(p), /Prazo \(dias\)/);
|
||||||
|
}
|
||||||
|
p.dayTerms.operations[0] = operation('sales', '1000');
|
||||||
|
Object.assign(p.dayTerms.operations[0], {
|
||||||
|
recognitionBasis: 'date',
|
||||||
|
recognitionDate: '2027-02-30',
|
||||||
|
});
|
||||||
|
assert.throws(
|
||||||
|
() => forecastBusinessPlan(p),
|
||||||
|
/reconhecimento insuficiente ou inválida/,
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { financialReportFixture } from './integral-financial-plan.mjs';
|
||||||
|
|
||||||
|
export function dayTermsFixture(periods = 3) {
|
||||||
|
const p = financialReportFixture(periods);
|
||||||
|
const schedule = amount => Array.from({ length: periods }, (_, i) => i === 0 ? amount : '0');
|
||||||
|
p.products = [{ label: 'Serviço sintético F20-A', monthlyUnits: '0', unitPrice: '1000', unitVariableCost: '0', monthlyUnitsByPeriod: schedule('1') }];
|
||||||
|
p.useInventoryPurchaseSchedule = true;
|
||||||
|
p.inventoryPurchaseSchedule = schedule('400').map(amount => ({ amount, leadMonths: 0 }));
|
||||||
|
p.monthlyOperatingExpensesByPeriod = schedule('100');
|
||||||
|
p.monthlyPayrollExpense = '0';
|
||||||
|
p.monthlyPayrollPayments = '0';
|
||||||
|
p.monthlyCollections = '777'; // Kept, never added to the opted-in sales agenda.
|
||||||
|
p.reportAssumptions.manualCollectionsKind = 'sales';
|
||||||
|
p.dayTerms = { sales: true, purchases: true, services: true, operations: [
|
||||||
|
operation('sales', '1000'), operation('purchases', '400'), operation('services', '100'),
|
||||||
|
] };
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function operation(kind, amount) {
|
||||||
|
return { kind, month: 1, originId: kind + '-1', parcelId: '1', amount, termDays: '30',
|
||||||
|
recognitionBasis: 'monthly', recognitionDate: '', originBasis: 'recognition', originDate: '' };
|
||||||
|
}
|
||||||