import assert from 'node:assert/strict'; import test from 'node:test'; import fs from 'node:fs'; import { createRequire } from 'node:module'; import { compileFunction } from 'node:vm'; import ts from 'typescript'; import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import JSZip from 'jszip'; import * as presentation from '../../resources/js/lib/financial-issue-presentation.ts'; import * as integral from '../../resources/js/lib/integral-financial-report.ts'; import { serializeBusinessPlanSnapshot } from '../../resources/js/lib/business-financial-plan.ts'; import { buildComplementaryTables } from '../../resources/js/lib/complementary-report.ts'; import { financialReportFixture } from './fixtures/integral-financial-plan.mjs'; import { complementaryFixture } from './fixtures/complementary-plan.mjs'; import { createProjectDossierReport, createProjectDossierPrintHtml, generateProjectDossierDocx, } from '../../resources/js/lib/project-dossier-report.ts'; const mismatch = () => ({ ...financialReportFixture(12), fundingBreakdown: { ownerCapital: '700', investorCapital: '0', additionalCapital: '0', }, }); void test('deduplication never hides a forecast error behind an unreadable report snapshot or the annual example', () => { const plan = mismatch(); const error = integral.buildIntegralFinancialTables(plan)[0].issues[0]; assert.equal(presentation.forecastErrorShownInReport(plan, error), true); assert.equal( presentation.forecastErrorShownInReport(plan, 'Other error'), false, ); plan.reportAssumptions.startupExpenses = 'invalid structure'; assert.equal(presentation.forecastErrorShownInReport(plan, error), false); delete plan.reportAssumptions; plan.reportSource = 'annual_example'; assert.equal(presentation.forecastErrorShownInReport(plan, error), false); }); void test('capital mismatch names the exact compared controls once and preserves all seven validity flags', () => { const plan = mismatch(), tables = integral.buildIntegralFinancialTables(plan), before = JSON.stringify({ plan, tables }); assert.equal(tables.filter((t) => t.issues.length).length, 7); const issues = presentation.financialIssuesForDisplay(tables); assert.equal(issues.length, 1); assert.equal(issues[0].tables.length, 7); for (const field of [ 'Capital próprio', 'Capital do proprietário', 'Capital do investidor', 'Capital adicional angariado', ]) assert.ok(issues[0].message.includes(field)); assert.equal(JSON.stringify({ plan, tables }), before); plan.fundingBreakdown.ownerCapital = '600'; assert.deepEqual( presentation.financialIssuesForDisplay( integral.buildIntegralFinancialTables(plan), ), [], ); }); void test('opening imbalance identifies original fields and exact difference without guessing the responsible balance', () => { const plan = financialReportFixture(12); plan.reportAssumptions.openingEquity = '999'; const issues = presentation.financialIssuesForDisplay( integral.buildIntegralFinancialTables(plan), ); assert.equal(issues.length, 1); const message = issues[0].message; assert.match(message, /diferença 1,00/); assert.match(message, /Capital e resultados anteriores/); assert.match(message, /não permite identificar automaticamente/); }); void test('personnel mismatch points to both tables and quantity, salary and active months; correction removes it', () => { const { plan, draft, team } = complementaryFixture(); team[0].monthly_salary = '100.01'; draft.project_team_snapshot = JSON.stringify(team); const tables = buildComplementaryTables(draft, plan); const before = JSON.stringify({ plan, draft, tables }); const message = presentation .financialIssuesForDisplay(tables) .find((i) => i.message.includes('Mapa de pessoal')).message; for (const field of [ 'Folha salarial prevista', 'Pessoal', 'quantidade', 'remuneração mensal', 'meses activos', ]) assert.ok(message.includes(field)); assert.equal(JSON.stringify({ plan, draft, tables }), before); team[0].monthly_salary = '100.00'; draft.project_team_snapshot = JSON.stringify(team); assert.ok( !presentation .financialIssuesForDisplay(buildComplementaryTables(draft, plan)) .some((i) => i.message.includes('Mapa de pessoal')), ); }); void test('inventory and startup messages identify their controls; unknown diagnostics remain visible without invented attribution', () => { assert.match( presentation.financialIssueMessage( 'A soma das existencias iniciais por produto deve coincidir com as existencias iniciais do plano.', ), /Planear stock por produto/, ); assert.match( presentation.financialIssueMessage( 'As aquisições do cenário não correspondem às necessidades de activos. Confira os valores e adopte as aquisições calculadas.', ), /Aquisição de activos/, ); const raw = 'Diagnóstico específico não mapeado'; const tables = [ { id: 'a', title: 'Tabela A', issues: [raw, raw] }, { id: 'b', title: 'Tabela B', issues: [raw] }, ]; assert.deepEqual(presentation.financialIssuesForDisplay(tables), [ { message: raw, tables: ['Tabela A', 'Tabela B'] }, ]); }); void test('real table component presents one issue panel while retaining every table and calculated row', () => { const code = ts.transpileModule( fs.readFileSync( new URL( '../../resources/js/components/investment-report-tables.tsx', import.meta.url, ), 'utf8', ), { 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/integral-financial-report' ? integral : name === '@/lib/financial-issue-presentation' ? presentation : require(name), module, module.exports, ); const tables = integral.buildIntegralFinancialTables(mismatch()), message = presentation.financialIssuesForDisplay(tables)[0].message; const html = renderToStaticMarkup( React.createElement(module.exports.InvestmentReportTables, { tables }), ); assert.equal( html.replace(/ data-correction-message="[^"]*"/g, '').split(message) .length - 1, 1, ); assert.equal( (html.match(/aria-label="Dados financeiros a corrigir"/g) ?? []).length, 1, ); assert.ok(tables.every((t) => html.includes(t.title))); const valid = integral.buildIntegralFinancialTables( financialReportFixture(12), ); assert.ok( !renderToStaticMarkup( React.createElement(module.exports.InvestmentReportTables, { tables: valid, }), ).includes('Dados financeiros a corrigir'), ); }); void test('print and Word present the same capital correction only once, without mutating report tables', async () => { const report = createProjectDossierReport( { project_title: 'SINTÉTICO V12', business_plan_snapshot: serializeBusinessPlanSnapshot(mismatch()), }, { selectedSections: new Set(['finance']), generatedAt: '2026-11-20T12:00:00Z', }, ); const before = JSON.stringify(report), message = presentation.financialIssuesForDisplay( report.sections.find((s) => s.id === 'finance').tables, )[0].message; const html = await createProjectDossierPrintHtml(report, []); assert.equal( html.replace(/ data-correction-message="[^"]*"/g, '').split(message) .length - 1, 1, ); 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.equal(xml.split(message).length - 1, 1); assert.equal(JSON.stringify(report), before); });