import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import { compileFunction } from 'node:vm'; import { createRequire } from 'node:module'; import ts from 'typescript'; import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import * as normal from '../../resources/js/lib/irpc-normal.ts'; import * as rational from '../../resources/js/lib/fiscal-rational.ts'; import * as inputText from '../../resources/js/lib/input-text.ts'; import { monthlyIvaInput, monthlyIvaKey, } from '../../resources/js/lib/monthly-iva.ts'; import { partitionSimulationDraft, restoreSimulationDraft, } from '../../resources/js/lib/simulation-form.ts'; const require = createRequire(import.meta.url); function load(file, mocks) { const module = { exports: {} }; const source = fs.readFileSync( new URL('../../resources/js/components/' + file, import.meta.url), 'utf8', ); const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX, }, }).outputText; compileFunction(code, ['require', 'module', 'exports'])( (n) => mocks[n] ?? require(n), module, module.exports, ); return module.exports; } const nodes = (n) => Array.isArray(n) ? n.flatMap(nodes) : n && typeof n === 'object' ? [n, ...nodes(n.props?.children)] : []; const settings = { start: '2026-01', basis: 'net', declared: true, auto: false, }; const seed = () => JSON.parse( fs.readFileSync( new URL('./fixtures/irpc-base-preserved.json', import.meta.url), 'utf8', ), ); void test('IVA plan source forwards current sales, never the old independent base; operation choice is explicit and recoverable', () => { const Monthly = () => null; const { SimulationPublishedIva } = load('simulation-published-iva.tsx', { '../lib/input-text.ts': inputText, './simulation-monthly-iva': { SimulationMonthlyIva: Monthly }, }); const draft = { ...seed(), currency: 'MZN', fiscal_period: '2026', published_iva_base: '999999', monthly_iva_settings: JSON.stringify(settings), }; const calls = []; const onCalculate = async (input) => { calls.push(input); }; let changed; const props = { draft, busy: false, onCalculate, onChange: (field, value) => { changed = [field, value]; }, }; let tree = SimulationPublishedIva(props); let monthly = nodes(tree).find((n) => n.type === Monthly); assert.ok(monthly); assert.equal(monthly.props.onCalculate, onCalculate); assert.equal(monthly.props.draft, draft); const linked = SimulationPublishedIva({ ...props, planAlreadyVisible: true, }); assert.equal( nodes(linked).some((n) => n.type === Monthly), false, ); assert.equal( nodes(linked).find((n) => n.type === 'a').props.href, '#monthly-projected-iva', ); const request = monthlyIvaInput(monthly.props.draft, settings); assert.ok(request.monthly_sales.every((r) => r.amount !== '999999')); assert.equal('base' in request, false); assert.equal( nodes(tree).some((n) => n.type === 'input'), false, ); nodes(tree) .find((n) => n.type === 'select') .props.onChange({ target: { value: 'operation' } }); assert.deepEqual(changed, ['published_iva_base_source', 'operation']); const partition = partitionSimulationDraft({ ...draft, published_iva_base_source: 'operation', }); const restored = restoreSimulationDraft( partition.economic_snapshot, partition.personal_snapshot, ); tree = SimulationPublishedIva({ ...props, draft: restored }); assert.equal( nodes(tree).some((n) => n.type === Monthly), false, ); assert.equal(restored.published_iva_base, '999999'); const modified = structuredClone(draft); const saved = JSON.parse(modified.business_plan_snapshot); saved.plan.products[0].unitPrice = String( Number(saved.plan.products[0].unitPrice) + 10, ); modified.business_plan_snapshot = JSON.stringify(saved); assert.notEqual( monthlyIvaKey(monthlyIvaInput(modified, settings)), monthlyIvaKey(request), ); assert.equal( monthlyIvaInput(draft, { ...settings, basis: 'included' }) .sales_vat_basis, 'included', ); assert.equal(calls.length, 0); }); void test('IVA plan selected without source cannot silently fall back to a hand-entered base', () => { const Monthly = () => null; const { SimulationPublishedIva } = load('simulation-published-iva.tsx', { '../lib/input-text.ts': inputText, './simulation-monthly-iva': { SimulationMonthlyIva: Monthly }, }); const html = renderToStaticMarkup( SimulationPublishedIva({ draft: { published_iva_base_source: 'plan', published_iva_base: '100', }, busy: false, onCalculate: async () => {}, onChange() {}, }), ); assert.match(html, /Prepare as vendas no plano/); assert.doesNotMatch(html, /aria-label="Base tributável líquida"/); }); void test('IRPC readonly base tracks current deductions, marks stale saved results, preserves history and leaves missing inputs indeterminate', () => { const Component = load('irpc-current-base.tsx', { '@/lib/irpc-normal': normal, '@/lib/fiscal-rational': rational, }).default; const draft = seed(), before = JSON.stringify(draft); const html = () => renderToStaticMarkup(React.createElement(Component, { draft })); assert.match(html(), /4400\.00 MZN/); assert.doesNotMatch(html(), / { l.requested = '0'; }); draft.modelo_a_snapshot = normal.saveNormalBook(draft, book); assert.match(html(), /6700\.00 MZN/); assert.match(html(), /Os dados mudaram/); assert.deepEqual(normal.normalBook(draft).result, oldResult); book.base.benefits = { state: '', amount: '', reference: '' }; draft.modelo_a_snapshot = normal.saveNormalBook(draft, book); assert.match( html(), /aria-label="Matéria colectável actual">Por determinar/, ); assert.equal(normal.calculateNormal(draft, book).taxableBase, null); });