Files
Investidor-V2/tests/frontend/business-plan-editing.test.mjs
T

288 lines
10 KiB
JavaScript

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 * as business from '../../resources/js/lib/business-financial-plan.ts';
import {
newAnnualReferencePlan,
serializeAnnualExampleSnapshot,
} from '../../resources/js/lib/business-plan-guidance.ts';
import * as contract from '../../resources/js/lib/simulation-contract.ts';
import * as bridge from '../../resources/js/lib/financial-fiscal-bridge.ts';
import { validateSimulationDraft } from '../../resources/js/lib/simulation-form.ts';
// Exercise the real input callbacks and the parent's snapshot echo, including
// effects. No server, database or fiscal rates are used by this regression.
function editor(initialSnapshot) {
const values = [],
dependencies = [];
let cursor = 0,
pending = [],
changed = false,
snapshot = initialSnapshot;
const hooks = {
...React,
useState(initial) {
const index = cursor++;
if (!(index in values)) values[index] = initial;
return [
values[index],
(next) => {
const value =
typeof next === 'function' ? next(values[index]) : next;
if (!Object.is(value, values[index])) changed = true;
values[index] = value;
},
];
},
useEffect(callback, deps) {
const index = cursor++;
if (
!dependencies[index] ||
deps.some(
(value, i) => !Object.is(value, dependencies[index][i]),
)
) {
dependencies[index] = deps;
pending.push(callback);
}
},
};
const require = createRequire(import.meta.url),
module = { exports: {} };
const source = fs.readFileSync(
new URL(
'../../resources/js/components/simulation-business-plan.tsx',
import.meta.url,
),
'utf8',
);
const code = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
compileFunction(code, ['require', 'module', 'exports'])(
(name) =>
(name === '@/components/integral-financial-plan'
? { IntegralFinancialPlan: () => null }
: undefined) ??
(name === '@/components/business-plan-warnings'
? { BusinessPlanWarnings: () => null }
: name === '@/components/simulation-annual-example'
? { SimulationAnnualExample: () => null }
: undefined) ??
{
react: hooks,
'@/components/currency-select': { CurrencySelect: () => null },
'@/lib/business-financial-plan': business,
'@/lib/simulation-contract': contract,
'@/lib/financial-fiscal-bridge': bridge,
'@/components/financial-plan-details': {
FinancialPlanDetails: () => null,
},
'@/components/market-analysis-plan': {
MarketAnalysisPlan: () => null,
},
'@/components/financial-ratios-plan': {
FinancialRatiosPlan: () => null,
},
'@/components/plan-economic-classification': {
PlanEconomicClassification: () => null,
},
}[name] ??
require(name),
module,
module.exports,
);
let tree;
function render() {
for (let attempt = 0; attempt < 10; attempt++) {
changed = false;
cursor = 0;
pending = [];
tree = module.exports.SimulationBusinessPlan({
currency: 'MZN',
snapshot,
onCurrencyChange() {},
onSnapshotChange(value) {
snapshot = value;
changed = true;
},
});
pending.forEach((callback) => callback());
if (!changed) return;
}
throw new Error('Editor did not settle');
}
function walk(node, predicate) {
if (!node || typeof node !== 'object') return;
if (predicate(node)) return node;
for (const child of React.Children.toArray(node.props?.children)) {
const found = walk(child, predicate);
if (found) return found;
}
}
function field(label) {
const money = walk(
tree,
(node) =>
node.props?.label === label &&
typeof node.props.onChange === 'function',
);
if (money) return money.props;
const container = walk(
tree,
(node) =>
node.type === 'label' &&
React.Children.toArray(node.props.children).some(
(child) => typeof child === 'string' && child === label,
),
);
const input = walk(container, (node) => node.type === 'input');
assert.ok(input, `Missing field: ${label}`);
return {
value: input.props.value,
onChange: (value) => input.props.onChange({ target: { value } }),
};
}
render();
return {
field,
edit(label, value) {
field(label).onChange(value);
render();
},
snapshot: () => snapshot,
example() {
const toggle = walk(
tree,
(node) =>
node.type === 'button' &&
React.Children.toArray(node.props.children).some(
(child) =>
child === 'Carregar cenário anual de exemplo',
),
);
if (toggle) {
toggle.props.onClick();
render();
}
return walk(
tree,
(node) => typeof node.props?.onSnapshotChange === 'function',
)?.props;
},
};
}
void test('annual example snapshot is saved through the existing parent callback and recovered by a fresh editor', () => {
const form = editor();
const exampleSnapshot = serializeAnnualExampleSnapshot(
newAnnualReferencePlan(),
);
form.example().onSnapshotChange(exampleSnapshot);
const recovered = editor(form.snapshot());
assert.equal(recovered.example().snapshot, exampleSnapshot);
recovered.edit('Preço por unidade', '250.50');
assert.equal(recovered.example().snapshot, exampleSnapshot);
});
void test('monthly units, unit price, variable cost and operating expenses remain editable after snapshot echo', () => {
const form = editor();
for (const label of [
'Unidades por mes',
'Preço por unidade',
'Custo variável por unidade',
'Despesas operacionais reconhecidas',
]) {
for (const value of ['', '2', '25', '250.50']) {
form.edit(label, value);
assert.equal(
form.field(label).value,
value,
`${label}: ${value}; saved=${form.snapshot()}`,
);
}
}
const restored = business.restoreBusinessPlanSnapshot(form.snapshot());
assert.ok(restored, 'The edited plan must remain recoverable');
assert.equal(restored.products[0].monthlyUnits, '250.50');
assert.equal(restored.monthlyOperatingExpenses, '250.50');
assert.equal(restored.salesCollectionPercent, '');
assert.equal(restored.openingReceivablesCollectionPercent, '');
const recovered = editor(form.snapshot());
assert.equal(recovered.field('Preço por unidade').value, '250.50');
recovered.edit('Despesas operacionais reconhecidas', '500');
assert.equal(recovered.field('Preço por unidade').value, '250.50');
assert.equal(
recovered.field('Despesas operacionais reconhecidas').value,
'500',
);
assert.throws(() => business.forecastBusinessPlan(restored));
assert.ok(
validateSimulationDraft(
{ business_plan_snapshot: form.snapshot() },
'financial',
).business_plan_snapshot,
);
assert.equal(
validateSimulationDraft({}, 'financial').business_plan_snapshot,
undefined,
);
});
void test('numeric entry messages distinguish missing, invalid, negative, fractional people and percentages', () => {
assert.equal(
business.businessPlanNumberError(''),
'Preencha este campo para continuar.',
);
assert.equal(
business.businessPlanNumberError('abc'),
'Introduza apenas números (ex.: 25.000).',
);
assert.equal(
business.businessPlanNumberError('-1'),
'Este valor não pode ser negativo.',
);
assert.equal(
business.businessPlanNumberError('1.5', { integer: true }),
'Introduza um número inteiro de pessoas.',
);
assert.equal(
business.businessPlanNumberError('101', { percent: true }),
'Introduza uma percentagem entre 0% e 100%.',
);
assert.equal(business.businessPlanNumberError('0'), '');
assert.equal(business.businessPlanNumberError('25.50'), '');
assert.equal(
business.businessPlanNumberError('-25.50', { allowNegative: true }),
'',
);
});
void test('invalid percentages remain editable after recovery without becoming valid calculation inputs', () => {
const form = editor();
form.edit('Preço por unidade', '250.50');
const decoded = JSON.parse(form.snapshot());
decoded.plan.salesCollectionPercent = '101';
const snapshot = JSON.stringify(decoded);
assert.equal(business.restoreBusinessPlanSnapshot(snapshot), null);
const editable = business.restoreBusinessPlanSnapshot(snapshot, {
editable: true,
});
assert.equal(editable.salesCollectionPercent, '101');
assert.equal(editor(snapshot).field('Preço por unidade').value, '250.50');
assert.ok(
validateSimulationDraft(
{ business_plan_snapshot: snapshot },
'financial',
).business_plan_snapshot,
);
});