Files
Investidor-V2/tests/frontend/integral-financial-report.test.mjs
T

257 lines
9.7 KiB
JavaScript

import { financialReportFixture as plan } from './fixtures/integral-financial-plan.mjs';
import assert from 'node:assert/strict';
import test from 'node:test';
import JSZip from 'jszip';
import {
buildIntegralFinancialTables,
displayReportMoney,
} from '../../resources/js/lib/integral-financial-report.ts';
import {
forecastBusinessPlan,
serializeBusinessPlanSnapshot,
restoreBusinessPlanSnapshot,
} from '../../resources/js/lib/business-financial-plan.ts';
import {
createProjectDossierReport,
createProjectDossierPrintHtml,
generateProjectDossierDocx,
} from '../../resources/js/lib/project-dossier-report.ts';
import {
partitionSimulationDraft,
restoreSimulationDraft,
} from '../../resources/js/lib/simulation-form.ts';
void test('acceptance regression: summary uses the same cash, tax payments and startup funding gap as its seven tables', () => {
const input = plan(13);
const make = () =>
createProjectDossierReport(
{
project_title: 'QA',
business_plan_snapshot: serializeBusinessPlanSnapshot(input),
},
{ selectedSections: new Set(['finance']) },
).sections[0];
const finance = make();
const value = (field) =>
finance.rows.find((row) => row.field === field)?.value;
assert.equal(value('Caixa final projectada'), '4 540,00 MZN');
assert.equal(value('Pagamentos no horizonte'), '9 360,00 MZN');
assert.equal(value('Resultado antes de impostos'), '3 770,00 MZN');
assert.equal(value('Resultado líquido no horizonte'), '3 380,00 MZN');
assert.equal(value('Diferença entre usos e fontes'), '100,00 MZN');
assert.match(
value('Reconciliação do financiamento'),
/insuficiente.*não bloqueante/,
);
assert.equal(get(finance.tables, 'cashflow', 'Caixa final')[13], '4540.00');
input.reportAssumptions.taxExpenseByMonth[0] = '';
assert.match(
make().rows.find((row) => row.field === 'Caixa final projectada').value,
/Por determinar/,
);
});
void test('review regression: cash deficit does not create an undeclared loan or inflate projected liabilities', () => {
const input = plan(12);
input.reportAssumptions.startupExpenses[0].amount = '10000';
const tables = buildIntegralFinancialTables(input);
assert.equal(get(tables, 'cashflow', 'Caixa inicial')[1], '-9000.00');
assert.equal(get(tables, 'balance', 'Caixa líquida')[1], '-8720.00');
assert.equal(
get(tables, 'balance', 'Total do passivo')[1],
'10.00',
'only the declared accrued tax, without a fabricated overdraft',
);
assert.equal(
get(tables, 'balance', 'Empréstimos e suprimentos por reembolsar')[1],
'0.00',
);
assert.equal(get(tables, 'balance', 'Total do activo')[1], '-8130.00');
assert.equal(get(tables, 'balance', 'Diferença do balanço')[1], '0.00');
assert.match(
tables.find((table) => table.id === 'balance').notes.join(' '),
/não cria dívida/,
);
});
void test('review regression: print export repeats rubrics in readable slices without losing any of sixty months or five annual periods', async () => {
const input = plan(60);
const report = createProjectDossierReport(
{
project_title: 'QA 60 meses',
business_plan_snapshot: serializeBusinessPlanSnapshot(input),
},
{
selectedSections: new Set(['finance']),
generatedAt: '2026-11-20T12:00:00Z',
},
);
const html = await createProjectDossierPrintHtml(report, []);
const heads = [...html.matchAll(/<thead>([\s\S]*?)<\/thead>/g)];
assert.ok(heads.length > 7);
for (const [, head] of heads)
assert.ok(
(head.match(/<th>/g) ?? []).length <= 5,
'four periods plus rubric maximum',
);
for (const table of report.sections[0].tables)
for (const header of table.headers)
assert.ok(html.includes(header), header);
assert.match(html, /2031-12/);
assert.doesNotMatch(html, /overflow-x:auto/);
});
const get = (tables, id, label) =>
tables
.find((table) => table.id === id)
.rows.find((row) => row[0] === label);
void test('seven integrated statements reconcile monthly flows, annual totals and closing stocks without changing the existing engine', () => {
const input = plan(),
before = JSON.stringify(input),
forecast = forecastBusinessPlan(input),
tables = buildIntegralFinancialTables(input);
assert.equal(tables.length, 7);
assert.ok(
tables.every((table) => table.issues.length === 0),
JSON.stringify(tables.map((t) => [t.id, t.issues])),
);
assert.equal(get(tables, 'startup', 'Despesas de arranque')[1], '100.00');
assert.equal(
get(tables, 'funding', 'Caixa após financiamento e arranque')[1],
'900.00',
);
assert.deepEqual(get(tables, 'sales', 'Vendas totais').slice(-2), [
'12000.00',
'12000.00',
]);
assert.deepEqual(get(tables, 'profit-loss', 'Lucro líquido').slice(-2), [
'3120.00',
'3120.00',
]);
assert.deepEqual(get(tables, 'cashflow', 'Caixa inicial').slice(-2), [
'900.00',
'4260.00',
]);
assert.deepEqual(get(tables, 'cashflow', 'Caixa final').slice(-2), [
'4260.00',
'7620.00',
]);
assert.deepEqual(get(tables, 'balance', 'Total do activo').slice(-2), [
'4740.00',
'7980.00',
]);
assert.ok(
get(tables, 'balance', 'Diferença do balanço')
.slice(1)
.every((value) => value === '0.00'),
);
assert.equal(
get(tables, 'break-even', 'Vendas de equilíbrio')[1],
'516.67',
);
assert.equal(JSON.stringify(input), before);
const withoutSupplement = { ...input };
delete withoutSupplement.reportAssumptions;
assert.deepEqual(
forecastBusinessPlan(withoutSupplement),
forecast,
'no changes to approved base forecast',
);
const draft = {
purpose: 'own_investment',
business_plan_snapshot: serializeBusinessPlanSnapshot(input),
};
const stored = JSON.parse(
JSON.stringify(partitionSimulationDraft(draft, false)),
);
const recovered = restoreBusinessPlanSnapshot(
restoreSimulationDraft(stored.economic_snapshot, {})
.business_plan_snapshot,
);
assert.deepEqual(buildIntegralFinancialTables(recovered), tables);
});
void test('missing inputs, insufficient inventory and inconsistent opening capital remain explicit, never balancing plugs', () => {
const input = plan(12);
input.reportAssumptions.openingEquity = '999.99';
let tables = buildIntegralFinancialTables(input);
assert.match(
tables.find((t) => t.id === 'balance').issues.join(' '),
/abertura/,
);
assert.equal(get(tables, 'balance', 'Diferença do balanço')[1], '0.01');
input.reportAssumptions.openingEquity = '1000';
input.monthlyInventoryPurchases = '';
tables = buildIntegralFinancialTables(input);
assert.match(
tables.find((t) => t.id === 'balance').issues.join(' '),
/agenda/,
);
assert.equal(
get(tables, 'balance', 'Diferença do balanço')[1],
'Por determinar',
);
input.monthlyInventoryPurchases = '0';
assert.match(
buildIntegralFinancialTables(input)
.find((t) => t.id === 'balance')
.issues.join(' '),
/insuficientes/,
);
input.reportAssumptions.taxExpenseByMonth[0] = '';
assert.ok(
buildIntegralFinancialTables(input).every((t) => t.issues.length > 0),
);
});
void test('partial years, changing product schedules and negative cash keep exact amounts and disclosed assumptions', () => {
const input = plan(13);
input.products[0].unitPriceByPeriod = Array(13).fill('100.01');
input.reportAssumptions.startupExpenses[0].amount = '10000.01';
const tables = buildIntegralFinancialTables(input);
assert.ok(
tables
.find((t) => t.id === 'sales')
.headers.at(-1)
.endsWith('(parcial)'),
);
assert.equal(get(tables, 'sales', 'Vendas totais').at(-1), '1000.10');
assert.equal(get(tables, 'cashflow', 'Caixa inicial')[1], '-9000.01');
assert.ok(
get(tables, 'balance', 'Diferença do balanço')
.slice(1)
.every((value) => value === '0.00'),
);
assert.equal(displayReportMoney('-1234567.89'), '-1 234 567,89');
});
void test('dossier print and Word exports include the same seven statements, escape labels and split wide tables', async () => {
const input = plan(13);
input.products[0].label = '<script>não executar</script>';
const report = createProjectDossierReport(
{
project_title: 'Teste QA',
business_plan_snapshot: serializeBusinessPlanSnapshot(input),
},
{
selectedSections: new Set(['finance']),
generatedAt: '2026-11-20T12:00:00Z',
},
);
assert.equal(report.sections[0].tables.length, 7);
const html = await createProjectDossierPrintHtml(report, []);
assert.match(html, /Balanço Projectado/);
assert.match(html, /&lt;script&gt;/);
assert.doesNotMatch(html, /<script>não executar/);
const output = await generateProjectDossierDocx(report, []);
const zip = await JSZip.loadAsync(
output instanceof Blob ? await output.arrayBuffer() : output,
);
const xml = await zip.file('word/document.xml').async('string');
assert.match(xml, /Balanço Projectado/);
assert.match(xml, /Lucros e Perdas/);
assert.doesNotMatch(xml, /<\/w:tbl>\s*<w:tbl>/);
assert.match(xml, /7 620,00|7620,00|4 540,00|4540,00/);
});