Files
Investidor-V2/tests/frontend/financial-ratios-report.test.mjs
T
Claude a3f2d2d7ca Plano de negócio como resultado da simulação
O relatório do investidor segue o modelo: resumo executivo (com objectivos,
missão e chaves para o sucesso), startup, mercado, vendas e marcos, pessoal
e plano financeiro, com as tabelas anuais nos capítulos e o detalhe mensal
do primeiro ano em anexo, sem colunas técnicas. Antes de exportar aparece
«Falta preencher» com ligação aos campos.

O cenário fiscal calcula o IRPC de cada ano à taxa geral de 32% sobre o
lucro antes de impostos, em vez de 72 campos mensais. Os rácios passam a
ser calculados a partir do balanço quando o investidor não classifica o
activo e o passivo correntes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
2026-12-04 21:11:45 +02:00

189 lines
8.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import test from 'node:test';
import assert from 'node:assert/strict';
import JSZip from 'jszip';
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
import { buildFinancialRatiosTable } from '../../resources/js/lib/financial-ratios-report.ts';
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
import {
serializeBusinessPlanSnapshot,
restoreBusinessPlanSnapshot,
} from '../../resources/js/lib/business-financial-plan.ts';
import { calculateDecisionRatios } from '../../resources/js/lib/business-plan-guidance.ts';
import {
createProjectDossierReport,
createProjectDossierPrintHtml,
generateProjectDossierDocx,
} from '../../resources/js/lib/project-dossier-report.ts';
const fixture = () => {
const plan = financialReportFixture(13),
source = buildIntegralFinancialTables(plan),
b = source.find((t) => t.id === 'balance');
plan.ratioCurrentBalances = {
assetsByMonth: b.rows
.find((r) => r[0] === 'Caixa líquida')
.slice(1, 14),
liabilitiesByMonth: b.rows
.find((r) => r[0] === 'Total do passivo')
.slice(1, 14),
};
return { plan, source };
};
const get = (t, label) => t.rows.find((r) => r[0] === label);
void test('a missing classification in later months does not erase an available earlier liquidity ratio', () => {
const { plan, source } = fixture();
plan.ratioCurrentBalances = {
assetsByMonth: ['1180'],
liabilitiesByMonth: ['10'],
};
const table = buildFinancialRatiosTable(plan, source);
assert.equal(get(table, 'Liquidez corrente')[1], '118,00×');
assert.equal(get(table, 'Liquidez corrente')[2], 'Por determinar');
assert.equal(table.issues.length, 24);
assert.equal(new Set(table.issues).size, 24);
assert.ok(
table.issues.every((issue) =>
/corrente — mês (?:[2-9]|1[0-3]):/.test(issue),
),
);
});
void test('annual comparison uses two complete years and permits growth above 100 percent', () => {
const plan = financialReportFixture(24);
plan.products[0].monthlyUnitsByPeriod = [
...Array(12).fill('10'),
...Array(12).fill('25'),
];
const table = buildFinancialRatiosTable(plan);
assert.equal(get(table, 'Crescimento das vendas').at(-1), '150,00%');
assert.equal(get(table, 'Crescimento das vendas')[13], '150,00%');
});
void test('approved formulas are presented from the same monthly and annual statements, without summing ratios', () => {
const { plan, source } = fixture();
const t = buildFinancialRatiosTable(plan, source);
assert.equal(t.issues.length, 0);
const approved = calculateDecisionRatios(
{
cash: '1180',
receivables: '0',
inventory: '0',
otherCurrentAssets: '0',
longTermAssets: '590',
accumulatedDepreciation: '0',
currentLiabilities: '10',
longTermLiabilities: '0',
paidCapital: '1600',
retainedResults: '-100',
periodResult: '260',
},
'1000',
);
assert.equal(
get(t, 'Liquidez corrente')[1],
approved.currentLiquidity.toFixed(2).replace('.', ',') + '×',
);
assert.equal(
get(t, 'Endividamento (passivo/activo)')[1],
(approved.debtAssets * 100).toFixed(2).replace('.', ',') + '%',
);
assert.equal(get(t, 'Margem líquida')[1], '26,00%');
assert.equal(get(t, 'Retorno do capital')[1], '14,77%');
assert.equal(get(t, 'Margem líquida')[14], '26,00%');
assert.equal(get(t, 'Retorno do capital')[14], '67,53%');
assert.equal(get(t, 'Liquidez corrente')[14], '35,50×');
assert.equal(get(t, 'Crescimento das vendas')[1], 'Por determinar');
assert.equal(get(t, 'Crescimento das vendas')[2], '0,00%');
assert.equal(get(t, 'Crescimento das vendas').at(-1), 'Por determinar');
});
void test('inconsistent balance blocks only dependent indicators; without classification liquidity comes from the balance', () => {
const { plan, source } = fixture();
delete plan.ratioCurrentBalances;
let t = buildFinancialRatiosTable(plan, source);
// Mapa de erros, plano de negócio: ratios are calculated from the balance;
// loans are read as long-term and the rule is stated in the notes.
const balance = source.find((b) => b.id === 'balance');
const value = (label) =>
Number(balance.rows.find((r) => r[0] === label)[1]);
const expected =
(value('Total do activo') - value('Activos fixos líquidos')) /
(value('Total do passivo') -
value('Empréstimos e suprimentos por reembolsar'));
assert.equal(
get(t, 'Liquidez corrente')[1],
expected.toFixed(2).replace('.', ',') + '×',
);
assert.ok(
t.notes.some((n) =>
n.startsWith('Activo e passivo correntes calculados a partir do balanço'),
),
);
assert.ok(!t.issues.some((i) => i.includes('Activo corrente — mês')));
assert.equal(get(t, 'Margem líquida')[1], '26,00%');
assert.equal(get(t, 'Retorno do capital')[1], '14,77%');
source
.find((t) => t.id === 'balance')
.rows.find((r) => r[0] === 'Diferença do balanço')[1] = '0.01';
t = buildFinancialRatiosTable(plan, source);
assert.equal(get(t, 'Retorno do capital')[1], 'Por determinar');
assert.equal(get(t, 'Endividamento (passivo/activo)')[1], 'Por determinar');
assert.equal(get(t, 'Margem líquida')[1], '26,00%');
assert.equal(get(t, 'Crescimento das vendas')[2], '0,00%');
source
.find((t) => t.id === 'profit-loss')
.issues.push('Imposto indeterminado');
assert.equal(
get(buildFinancialRatiosTable(plan, source), 'Margem líquida')[1],
'Por determinar',
);
});
void test('zero denominators, invalid classification and malformed snapshots remain indeterminate; inputs unchanged', () => {
const { plan, source } = fixture();
const before = JSON.stringify(source);
plan.ratioCurrentBalances.assetsByMonth[0] = '999999';
let t = buildFinancialRatiosTable(plan, source);
assert.equal(get(t, 'Liquidez corrente')[1], 'Por determinar');
assert.equal(JSON.stringify(source), before);
plan.ratioCurrentBalances.assetsByMonth[0] = '1180';
plan.ratioCurrentBalances.liabilitiesByMonth[0] = '0';
assert.equal(
get(buildFinancialRatiosTable(plan, source), 'Liquidez corrente')[1],
'Por determinar',
);
plan.ratioCurrentBalances.assetsByMonth[0] = { bad: true };
assert.doesNotThrow(() => buildFinancialRatiosTable(plan, source));
source
.find((t) => t.id === 'sales')
.rows.find((r) => r[0] === 'Vendas totais')[1] = '0.00';
t = buildFinancialRatiosTable(plan, source);
assert.equal(get(t, 'Margem líquida')[1], 'Por determinar');
assert.equal(get(t, 'Crescimento das vendas')[2], 'Por determinar');
});
void test('ratio classifications persist in the existing snapshot and export as the final financial table', async () => {
const { plan } = fixture(),
snapshot = serializeBusinessPlanSnapshot(plan),
recovered = restoreBusinessPlanSnapshot(snapshot);
assert.deepEqual(recovered.ratioCurrentBalances, plan.ratioCurrentBalances);
assert.deepEqual(
buildFinancialRatiosTable(recovered),
buildFinancialRatiosTable(plan),
);
const report = createProjectDossierReport(
{ business_plan_snapshot: snapshot },
{ selectedSections: new Set(['finance']) },
);
assert.equal(report.sections[0].tables.length, 8);
assert.equal(report.sections[0].tables.at(-1).id, 'ratios');
assert.match(
await createProjectDossierPrintHtml(report, []),
/Rácios financeiros/,
);
const doc = await generateProjectDossierDocx(report, []),
zip = await JSZip.loadAsync(
doc instanceof Blob ? await doc.arrayBuffer() : doc,
);
assert.match(
await zip.file('word/document.xml').async('string'),
/Rácios financeiros/,
);
});