import test from 'node:test'; import assert from 'node:assert/strict'; import { financialReportFixture } from './fixtures/integral-financial-plan.mjs'; import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts'; import { buildFinancialRatiosTable } from '../../resources/js/lib/financial-ratios-report.ts'; import { financialIssueMessage, financialIssuesForDisplay, } from '../../resources/js/lib/financial-issue-presentation.ts'; import { serializeBusinessPlanSnapshot, restoreBusinessPlanSnapshot, forecastBusinessPlan, } from '../../resources/js/lib/business-financial-plan.ts'; test('V12: current classification identifies each invalid field once without changing ratio rows or statements', () => { const plan = financialReportFixture(2); const source = buildIntegralFinancialTables(plan); const original = structuredClone(source); plan.ratioCurrentBalances = { assetsByMonth: ['0', '0'], liabilitiesByMonth: ['0', '0'], }; const valid = buildFinancialRatiosTable(plan, source); for (const [key, label] of [ ['assetsByMonth', 'Activo corrente'], ['liabilitiesByMonth', 'Passivo corrente'], ]) { for (const value of ['', '999999']) { plan.ratioCurrentBalances[key][0] = value; const table = buildFinancialRatiosTable(plan, source); assert.equal(table.issues.length, 1); assert.ok(table.issues[0].includes(label + ' — mês 1:')); assert.match( table.issues[0], value === '' ? /preencha um montante/ : /excede o total/, ); assert.equal( table.rows.find((row) => row[0] === 'Liquidez corrente')[1], 'Por determinar', ); } plan.ratioCurrentBalances[key][0] = '0'; assert.deepEqual(buildFinancialRatiosTable(plan, source), valid); } assert.deepEqual(source, original); }); test('V12: missing or negative tax cells identify exact field and month; correction removes diagnostic', () => { const plan = financialReportFixture(2); const valid = buildIntegralFinancialTables(plan); for (const [key, label, original] of [ ['taxExpenseByMonth', 'Imposto reconhecido', '30'], ['taxPaymentByMonth', 'Pagamento fiscal previsto', '20'], ]) { for (const value of ['', '-1']) { plan.reportAssumptions[key][1] = value; const issues = financialIssuesForDisplay( buildIntegralFinancialTables(plan), ); assert.equal(issues.length, 1); assert.ok(issues[0].message.includes(label + ', mês 2')); assert.match( issues[0].message, value === '' ? /preencha este campo/ : /não pode ser negativo/, ); } plan.reportAssumptions[key][1] = original; assert.deepEqual(buildIntegralFinancialTables(plan), valid); } }); test('V12: stock and period reconciliation messages identify original controls without altering issues or rows', () => { const raw = [ 'Mês 2: existências insuficientes para as vendas declaradas.', 'Existem períodos não reconciliados; reveja as rubricas indicadas.', ]; const tables = [ { id: 'balance', title: 'Balanço Projectado', issues: raw, rows: [['Diferença do balanço', '-200.00']], }, ]; const before = JSON.stringify(tables); const messages = financialIssuesForDisplay(tables); assert.equal(messages.length, 2); for (const field of [ 'mês 2', 'Existências iniciais', 'Encomenda', 'Unidades por mes', ]) assert.ok(messages[0].message.includes(field)); assert.match(messages[1].message, /Diferença do balanço/); assert.match(messages[1].message, /não identifica um único campo errado/); assert.equal(JSON.stringify(tables), before); }); test('V12: opening installment overflow names the right percentage fields and never attributes a false unique culprit', () => { for (const [kind, text] of [ [ 'receivables', 'A soma das cobranças declaradas de recebíveis de abertura não pode exceder 100%.', ], [ 'payables', 'A soma das liquidações declaradas de valores a pagar não pode exceder 100%.', ], ]) { const message = financialIssueMessage(text); assert.match(message, /Fluxo de Caixa/); assert.match(message, /Percentagem do saldo inicial/); assert.match( message, kind === 'receivables' ? /recebíveis/ : /valores a pagar/, ); const plan = financialReportFixture(2); const key = kind === 'receivables' ? 'openingReceivablesInstallments' : 'openingPayablesInstallments'; plan[key] = [ { month: 1, percent: '60' }, { month: 2, percent: '50' }, ]; assert.throws( () => forecastBusinessPlan(plan), /não pode exceder 100%/, ); plan[key][1].percent = '40'; assert.doesNotThrow(() => forecastBusinessPlan(plan)); } }); test('V12 regression: duplicate recovery months remain editable without blanking a saved plan; strict restore and forecast still reject', () => { const plan = financialReportFixture(2); plan.salesRecoverySchedule = [ { month: 1, percent: '0' }, { month: 1, percent: '0' }, ]; const snapshot = serializeBusinessPlanSnapshot(plan); assert.equal(restoreBusinessPlanSnapshot(snapshot), null); const editable = restoreBusinessPlanSnapshot(snapshot, { editable: true }); assert.ok(editable); assert.equal(editable.products[0].unitPrice, '100'); assert.deepEqual( editable.salesRecoverySchedule, plan.salesRecoverySchedule, ); assert.throws(() => forecastBusinessPlan(editable), /mês único/); assert.match( financialIssueMessage( 'Cada recuperação deve ter um mês único dentro do horizonte.', ), /campos «Mês»/, ); editable.salesRecoverySchedule[1].month = 2; const recovered = restoreBusinessPlanSnapshot( serializeBusinessPlanSnapshot(editable), ); assert.ok(recovered); assert.doesNotThrow(() => forecastBusinessPlan(recovered)); });