import assert from 'node:assert/strict'; import test from 'node:test'; import JSZip from 'jszip'; import fs from 'node:fs'; import { createRequire } from 'node:module'; import { compileFunction } from 'node:vm'; import ts from 'typescript'; import * as guidance from '../../resources/js/lib/business-plan-guidance.ts'; import { selectPlanCae } from '../../resources/js/lib/cae-mozambique.ts'; import { financialReportFixture } from './fixtures/integral-financial-plan.mjs'; import { forecastBusinessPlan, monthlyProjectedSales, serializeBusinessPlanSnapshot, restoreBusinessPlanSnapshot, compareBusinessScenarios, exportBusinessPlanCsv, } from '../../resources/js/lib/business-financial-plan.ts'; import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts'; import { financialPlanWarnings } from '../../resources/js/lib/financial-plan-warnings.ts'; import { buildAnnualExampleTables } from '../../resources/js/lib/annual-example-report.ts'; import { newAnnualReferencePlan, serializeAnnualExampleSnapshot, } from '../../resources/js/lib/business-plan-guidance.ts'; import { createProjectDossierReport, createIntegralFinancialReport, createProjectDossierPrintHtml, generateProjectDossierDocx, } from '../../resources/js/lib/project-dossier-report.ts'; const cell = (tables, id, label, index) => tables.find((t) => t.id === id).rows.find((r) => r[0] === label)[index]; const reload = (p) => restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p)); void test('annual growth is explicit, reaches all dependent forecasts and preserves declared monthly overrides', () => { const p = financialReportFixture(36); p.annualGrowthPercent = '150'; const unchanged = forecastBusinessPlan(p); assert.equal(unchanged.rows[12].revenue, '1000.00'); p.applyAnnualGrowth = true; const result = forecastBusinessPlan(reload(p)); assert.equal(result.rows[12].revenue, '2500.00'); assert.equal(result.rows[24].revenue, '6250.00'); assert.equal(result.rows[12].variableCost, '1000.00'); assert.deepEqual( monthlyProjectedSales(p), result.rows.map((r) => r.revenue), ); p.products[0].monthlyUnitsByPeriod = Array(36).fill('7'); assert.equal(forecastBusinessPlan(p).rows[24].revenue, '700.00'); const tables = buildIntegralFinancialTables({ ...p, products: [{ ...p.products[0], monthlyUnitsByPeriod: undefined }], }); assert.equal(cell(tables, 'sales', 'Vendas totais', 37), '12000.00'); assert.equal(cell(tables, 'sales', 'Vendas totais', 38), '30000.00'); assert.equal(cell(tables, 'sales', 'Vendas totais', 39), '75000.00'); }); void test('dividends reduce cash and capital equally, never profit; monthly and annual balances stay exact', () => { const p = financialReportFixture(13), base = buildIntegralFinancialTables(p); p.dividendsByPeriod = Array(13).fill('25.25'); const updated = reload(p), tables = buildIntegralFinancialTables(updated); assert.equal(forecastBusinessPlan(updated).rows[0].dividends, '25.25'); for (let col = 1; col <= 13; col++) { assert.equal( cell(tables, 'profit-loss', 'Lucro líquido', col), cell(base, 'profit-loss', 'Lucro líquido', col), ); const cents = (s) => BigInt(s.replace('.', '')); assert.equal( cents(cell(base, 'balance', 'Capital e resultados', col)) - cents(cell(tables, 'balance', 'Capital e resultados', col)), 2525n * BigInt(col), ); assert.equal( cents(cell(base, 'cashflow', 'Caixa final', col)) - cents(cell(tables, 'cashflow', 'Caixa final', col)), 2525n * BigInt(col), ); assert.equal( cell(tables, 'balance', 'Diferença do balanço', col), '0.00', ); } assert.equal( cell(tables, 'cashflow', 'Dividendos distribuídos', 14), '303.00', ); assert.equal( cell(tables, 'cashflow', 'Dividendos distribuídos', 15), '25.25', ); p.dividendsByPeriod[0] = '-1'; assert.throws(() => forecastBusinessPlan(p)); p.dividendsByPeriod = ['25']; assert.throws(() => forecastBusinessPlan(p)); }); void test('operating components replace rather than add the old aggregate; capital splits reconcile and survive recovery', () => { const p = financialReportFixture(13); p.operatingExpenseLines = [ { label: 'Rendas', monthlyAmount: '10.25' }, { label: 'Seguros', monthlyAmount: '20.75' }, ]; p.fundingBreakdown = { ownerCapital: '200.25', investorCapital: '300.25', additionalCapital: '99.50', }; const recovered = reload(p); assert.deepEqual(recovered.operatingExpenseLines, p.operatingExpenseLines); assert.deepEqual(recovered.fundingBreakdown, p.fundingBreakdown); const tables = buildIntegralFinancialTables(recovered); assert.equal( forecastBusinessPlan(recovered).rows[0].operatingExpenses, '31.00', ); assert.equal( cell(tables, 'profit-loss', 'Despesas operacionais', 14), '372.00', ); assert.equal(cell(tables, 'profit-loss', 'Despesa: Rendas', 14), '123.00'); assert.equal(cell(tables, 'funding', 'Capital do investidor', 1), '300.25'); assert.equal(cell(tables, 'balance', 'Diferença do balanço', 13), '0.00'); recovered.monthlyOperatingExpenses = ''; recovered.monthlyOperatingExpensesByPeriod = ['']; assert.equal( forecastBusinessPlan(recovered).rows[0].operatingExpenses, '31.00', ); p.equity = '601'; assert.throws(() => forecastBusinessPlan(p), /capital discriminado/); p.equity = '600'; p.operatingExpenseLines[0].monthlyAmount = ''; assert.throws(() => forecastBusinessPlan(p)); assert.equal(reload({ ...p, dividendsByPeriod: [5] }), null); }); void test('the full example shares the saved snapshot and its eleven tables and exports change together, leaving investor inputs untouched', async () => { const p = financialReportFixture(13), annual = newAnnualReferencePlan(); annual.years[0].sales = '14537.25'; p.annualExampleSnapshot = serializeAnnualExampleSnapshot(annual); p.reportSource = 'annual_example'; const before = forecastBusinessPlan(p), recovered = reload(p); const tables = buildAnnualExampleTables(recovered); assert.equal(tables.length, 11); assert.equal(cell(tables, 'sales', 'Vendas totais', 37), '14537.25'); assert.equal(cell(tables, 'balance', 'Diferença do balanço', 1), '0.00'); assert.equal( cell(tables, 'personnel', 'Folha de pagamento agregada', 37), '2100.00', ); assert.deepEqual(forecastBusinessPlan(recovered), before); const report = createProjectDossierReport( { project_title: 'QA sintético', business_plan_snapshot: serializeBusinessPlanSnapshot(recovered), }, { selectedSections: new Set([ 'finance', 'market', 'execution', 'team', ]), generatedAt: '2026-11-20T12:00:00Z', }, ); const all = report.sections.flatMap((s) => s.tables ?? []); assert.equal(all.length, 11); assert.deepEqual( all.find((t) => t.id === 'sales'), tables.find((t) => t.id === 'sales'), ); const html = await createProjectDossierPrintHtml(report, []); assert.match(html, /14 537,25/); assert.match(html, /Exemplo sintético/); const blob = await generateProjectDossierDocx(report, []), zip = await JSZip.loadAsync( blob instanceof Blob ? await blob.arrayBuffer() : blob, ), xml = await zip.file('word/document.xml').async('string'); assert.match(xml, /14 537,25/); assert.match(xml, /Capital por mobilizar/); recovered.reportSource = 'investor'; assert.equal( buildIntegralFinancialTables(recovered) .find((t) => t.id === 'sales') .rows.find((r) => r[0] === 'Vendas totais')[1], '1000.00', ); }); void test('financial warnings use the actual report metrics, remain non-blocking and reach print exports', async () => { const p = financialReportFixture(12); p.products[0].unitVariableCost = '90'; p.bankLoanProceeds = '30000'; p.equity = '0'; p.salesCollectionLagMonths = 4; p.applyAnnualGrowth = false; p.annualGrowthPercent = '150'; p.monthlyInventoryPurchases = '900'; p.monthlyVariableCostPayments = '900'; const tables = buildIntegralFinancialTables(p); assert.ok( tables.every((t) => !t.issues.length), JSON.stringify(tables.flatMap((t) => t.issues)), ); const warnings = financialPlanWarnings(p, tables), ids = warnings.map((w) => w.id); for (const id of [ 'loss', 'margin', 'break-even', 'cash', 'growth', 'credit', 'debt', 'capital', ]) { // Cash may be abundant because the declared loan is large; test that condition separately. if (id !== 'cash') assert.ok( ids.some((s) => s.endsWith('-' + id)), id, ); } const low = structuredClone(tables); low .find((t) => t.id === 'cashflow') .rows.find((r) => r[0] === 'Caixa final')[13] = '0.00'; assert.ok( financialPlanWarnings(p, low).some((w) => w.id.endsWith('-cash')), ); const report = createProjectDossierReport( { business_plan_snapshot: serializeBusinessPlanSnapshot(p) }, { selectedSections: new Set(['finance']), generatedAt: '2026-11-20T12:00:00Z', }, ); const html = await createProjectDossierPrintHtml(report, []); assert.match(html, /Aviso não bloqueante/); assert.match(html, /margem bruta é baixa/); const integral = createIntegralFinancialReport({ business_plan_snapshot: serializeBusinessPlanSnapshot(p), }); assert.match( await createProjectDossierPrintHtml(integral, []), /margem bruta é baixa/, ); }); void test('new declarations retain strict recovery boundaries and scenario adjustments reach operating components', () => { const p = financialReportFixture(12); p.operatingExpenseLines = [{ label: 'Renda', monthlyAmount: '10.25' }]; p.dividendsByPeriod = Array(12).fill('2.25'); const adjustment = { unitVolumePercent: '0', unitPricePercent: '0', unitCostPercent: '0', operatingCostsPercent: '100', cashCollectionsPercent: '0', }; p.scenarioAdjustments = { favorable: adjustment, unfavorable: { ...adjustment, operatingCostsPercent: '-50' }, }; const scenarios = compareBusinessScenarios(p); assert.equal(scenarios.favorable.result.rows[0].operatingExpenses, '20.50'); assert.equal( scenarios.unfavorable.result.rows[0].operatingExpenses, '5.13', ); assert.match(exportBusinessPlanCsv(p), /Dividendos distribuídos/); assert.equal( restoreBusinessPlanSnapshot( serializeBusinessPlanSnapshot({ ...p, dividendsByPeriod: ['0', null], }), ), null, ); assert.equal( restoreBusinessPlanSnapshot( serializeBusinessPlanSnapshot({ ...p, fundingBreakdown: { ownerCapital: 0 }, }), ), null, ); assert.equal( restoreBusinessPlanSnapshot( serializeBusinessPlanSnapshot({ ...p, reportSource: 'foreign' }), ), null, ); p.fundingBreakdown = { ownerCapital: '1', investorCapital: '0', additionalCapital: '0', }; assert.throws(() => forecastBusinessPlan(p), /capital discriminado/); }); void test('version 18 protects the added financial semantics and preserves prior payables, CAE and the legacy version 17 inputs', () => { const legacy = financialReportFixture(12); legacy.economicClassification = selectPlanCae('55111'); legacy.openingPayablesInstallments = [{ month: 2, percent: '50' }]; assert.equal(JSON.parse(serializeBusinessPlanSnapshot(legacy)).version, 17); const p = { ...legacy, dividendsByPeriod: Array(12).fill('0') }; const snapshot = serializeBusinessPlanSnapshot(p); assert.equal(JSON.parse(snapshot).version, 18); const recovered = restoreBusinessPlanSnapshot(snapshot); assert.deepEqual( recovered.economicClassification, legacy.economicClassification, ); assert.deepEqual( recovered.openingPayablesInstallments, legacy.openingPayablesInstallments, ); const downgraded = JSON.parse(snapshot); downgraded.version = 17; assert.equal(restoreBusinessPlanSnapshot(JSON.stringify(downgraded)), null); assert.deepEqual( forecastBusinessPlan(recovered), forecastBusinessPlan({ ...legacy, dividendsByPeriod: undefined }), ); }); void test('actual editor controls preserve declarations through snapshot reload and an explicit return from example to investor report', () => { const source = fs.readFileSync( new URL( '../../resources/js/components/financial-plan-details.tsx', import.meta.url, ), 'utf8', ); const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.ReactJSX, }, }).outputText; const module = { exports: {} }, require = createRequire(import.meta.url); compileFunction(code, ['require', 'module', 'exports'])( (name) => name === '@/lib/business-plan-guidance' ? guidance : require(name), module, module.exports, ); let plan = financialReportFixture(13); const render = () => module.exports.FinancialPlanDetails({ plan, onChange: (next) => { plan = reload(next); assert.ok(plan); }, }); const nodes = (n) => Array.isArray(n) ? n.flatMap(nodes) : n && typeof n === 'object' ? [n, ...nodes(n.props?.children)] : []; const text = (n) => typeof n === 'string' ? n : Array.isArray(n) ? n.map(text).join('') : n && typeof n === 'object' ? text(n.props?.children) : ''; const field = (label) => { const node = nodes(render()).find( (n) => n.type === 'label' && text(n).includes(label), ); assert.ok(node, label); return nodes(node).find( (n) => n.type === 'input' || n.type === 'select', ); }; field('Projectar os anos seguintes').props.onChange({ target: { checked: true }, }); assert.equal(plan.applyAnnualGrowth, true); field('Prazo de recebimento a crédito').props.onChange({ target: { value: '91' }, }); assert.equal(plan.creditTermDays, '91'); field('Planear dividendos').props.onChange({ target: { checked: true } }); field('Dividendos, mês 1').props.onChange({ target: { value: '12.25' } }); assert.equal(plan.dividendsByPeriod[0], '12.25'); const select = () => nodes(render()).find((n) => n.type === 'select'); select().props.onChange({ target: { value: 'annual_example' } }); assert.equal(plan.reportSource, 'annual_example'); assert.ok(plan.annualExampleSnapshot); assert.equal(buildAnnualExampleTables(plan).length, 11); select().props.onChange({ target: { value: 'investor' } }); assert.equal(plan.reportSource, 'investor'); assert.equal(plan.dividendsByPeriod[0], '12.25'); assert.equal(plan.products[0].monthlyUnits, '10'); }); void test('the credit warning uses the declared 90-day boundary without converting or changing monthly cash flows', () => { const p = financialReportFixture(12), baseline = forecastBusinessPlan(p); for (const days of ['0', '30', '90', '91', '365']) { p.creditTermDays = days; const restored = reload(p); assert.equal(restored.creditTermDays, days); assert.deepEqual(forecastBusinessPlan(restored), baseline); assert.equal( financialPlanWarnings( restored, buildIntegralFinancialTables(restored), ).some((w) => w.id.endsWith('-credit')), Number(days) > 90, ); } for (const invalid of ['-1', '366', '30.5', 'abc']) { p.creditTermDays = invalid; assert.throws( () => forecastBusinessPlan(p), /prazo entre 0 e 365 dias/, ); } });