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

290 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 React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
import * as guidance from '../../resources/js/lib/business-plan-guidance.ts';
import * as business from '../../resources/js/lib/business-financial-plan.ts';
import * as catalogue from '../../resources/js/lib/catalogue-choice.ts';
const require = createRequire(import.meta.url);
function load(name, mocks) {
const source = fs.readFileSync(
new URL(`../../resources/js/components/${name}.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: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(key) => mocks[key] ?? require(key),
module,
module.exports,
);
return module.exports;
}
function nodes(tree) {
if (Array.isArray(tree)) return tree.flatMap(nodes);
return tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
}
void test('a saved catalogue choice retains its exact value without exposing an internal identifier', () => {
const { default: Select } = load('catalogue-choice-select', {
react: {
useId: () => 'test-choice',
useState: (initial) => [initial, () => {}],
},
'./territory-search-select': () => null,
'@/lib/catalogue-choice': catalogue,
});
const id = 'a2000000-0000-4000-8000-000000000013';
let chosen;
const element = Select({
label: 'Actividade a comparar',
value: id,
options: [],
onChange: (value) => {
chosen = value;
},
});
assert.equal(element.props.selected.id, id);
assert.equal(
element.props.selected.name,
'Escolha guardada — designação por recuperar',
);
assert.ok(!element.props.selected.name.includes(id));
element.props.onChange({ id, name: 'Designação recuperada' });
assert.equal(chosen, id);
assert.equal(
Select({
label: 'Actividade',
value: id,
options: [{ value: id, label: 'Hotelaria documentada' }],
onChange() {},
}).props.selected.name,
'Hotelaria documentada',
);
});
void test('warning dismissal is local, never blocks a form, and changed assumptions reveal the warning again', () => {
let dismissed = [];
const { BusinessPlanWarnings } = load('business-plan-warnings', {
react: {
...React,
useState: () => [
dismissed,
(next) => {
dismissed = next(dismissed);
},
],
},
'@/lib/business-plan-guidance': guidance,
});
const metrics = { fundingGap: 100, currency: 'MZN' };
const tree = BusinessPlanWarnings({ metrics });
assert.ok(nodes(tree).some((node) => node.props?.role === 'status'));
assert.equal(
nodes(tree).some((node) => node.props?.role === 'alert'),
false,
);
const button = nodes(tree).find((node) => node.type === 'button');
assert.equal(button.props.type, 'button');
assert.equal(button.props.disabled, undefined);
button.props.onClick();
assert.equal(BusinessPlanWarnings({ metrics }), null);
assert.ok(
BusinessPlanWarnings({ metrics: { ...metrics, fundingGap: 200 } }),
);
});
void test('annual example renders expected results and source gaps without blocking errors or inferred monthly rows', () => {
const warningModule = load('business-plan-warnings', {
'@/lib/business-plan-guidance': guidance,
});
const { SimulationAnnualExample } = load('simulation-annual-example', {
'@/lib/business-plan-guidance': guidance,
'@/lib/business-financial-plan': business,
'./business-plan-warnings': warningModule,
});
const html = renderToStaticMarkup(
React.createElement(SimulationAnnualExample, { currency: 'MZN' }),
);
assert.match(html, /Linhas mensais por reconciliar/);
assert.match(html, /Avisos — pode continuar/);
assert.match(html, /Neste ano o negócio dá prejuízo/);
assert.match(
html,
/As vendas mensais médias não atingem o ponto de equilíbrio/,
);
assert.match(html, /não se distribuem valores pelos meses/);
assert.match(html, /Balanço projectado/);
assert.match(html, /Distribuição mensal ilustrativa/);
assert.match(html, /Não é financiamento confirmado/);
assert.equal((html.match(/Projecção mensal/g) ?? []).length, 3);
assert.doesNotMatch(html, /role="alert"|aria-invalid="true"|disabled=/);
assert.match(html.replace(/[\s\u00a0\u202f]/g, ''), /1325000[.,]00/);
});
void test('annual example edits survive parent snapshot, draft storage, reload and reopening without changing investor forecast', async () => {
const form = await import('../../resources/js/lib/simulation-form.ts');
const { SimulationAnnualExample } = load('simulation-annual-example', {
'@/lib/business-plan-guidance': guidance,
'@/lib/business-financial-plan': business,
'./business-plan-warnings': { BusinessPlanWarnings: () => null },
});
const input = {
currency: 'MZN',
openingCash: '0',
assetInvestment: '0',
products: [
{
label: 'Serviço de teste',
monthlyUnits: '1',
unitPrice: '100',
unitVariableCost: '40',
},
],
...Object.fromEntries(
[
'monthlyCollections',
'monthlyVariableCostPayments',
'monthlyInventoryPurchases',
'monthlyOperatingExpenses',
'monthlyOperatingPayments',
'monthlyPayrollExpense',
'monthlyPayrollPayments',
'inventory',
'receivables',
'payables',
'equity',
'shareholderLoans',
'bankLoanProceeds',
'grants',
'assetDepreciation',
'monthlyInterestExpense',
'monthlyInterestPayment',
'monthlyPrincipalRepayment',
].map((key) => [key, '0']),
),
depreciationLifeMonths: 60,
periods: 12,
};
const investorBefore = business.forecastBusinessPlan(input);
let snapshot;
const render = () =>
SimulationAnnualExample({
currency: 'MZN',
snapshot,
onSnapshotChange: (value) => {
snapshot = value;
},
});
const field = (tree, label) =>
nodes(tree).find(
(node) =>
node.props?.label === label &&
typeof node.props.onChange === 'function',
);
field(render(), 'Vendas previstas').props.onChange('14537.25');
const edited = guidance.restoreAnnualExampleSnapshot(snapshot);
assert.equal(edited.years[0].sales, '14537.25');
const before = guidance.calculateAnnualReferencePlan(edited);
const saved = {
purpose: 'simulate_only',
business_plan_snapshot: business.serializeBusinessPlanSnapshot({
...input,
annualExampleSnapshot: snapshot,
}),
};
const browserCopy = JSON.parse(
JSON.stringify(form.getAutosaveSnapshot(saved)),
);
const serverCopy = JSON.parse(
JSON.stringify(form.partitionSimulationDraft(saved, false)),
);
for (const recoveredDraft of [
browserCopy,
form.restoreSimulationDraft(serverCopy.economic_snapshot, {}),
]) {
const investorPlan = business.restoreBusinessPlanSnapshot(
recoveredDraft.business_plan_snapshot,
);
assert.ok(investorPlan);
snapshot = investorPlan.annualExampleSnapshot;
assert.equal(
field(render(), 'Vendas previstas').props.value,
'14537.25',
);
const after = guidance.calculateAnnualReferencePlan(
guidance.restoreAnnualExampleSnapshot(snapshot),
);
assert.deepEqual(after, before);
assert.ok(
after.years.every(
(year) =>
year.balanceDifference === '0.00' &&
year.illustrativeMonths.every(
(month) => month.balanceDifference === '0.00',
),
),
);
assert.deepEqual(
business.forecastBusinessPlan(investorPlan),
investorBefore,
);
}
field(render(), 'Vendas previstas').props.onChange('');
assert.equal(
guidance.restoreAnnualExampleSnapshot(snapshot).years[0].sales,
'',
);
assert.equal(field(render(), 'Vendas previstas').props.value, '');
assert.throws(
() =>
guidance.calculateAnnualReferencePlan(
guidance.restoreAnnualExampleSnapshot(snapshot),
),
/Preencha/,
);
});
void test('annual example refuses unknown storage versions, extra investor fields and oversized snapshots without overwriting them', () => {
const valid = guidance.serializeAnnualExampleSnapshot(
guidance.newAnnualReferencePlan(),
);
for (const source of [
'{',
'x'.repeat(12001),
valid.replace('"version":1', '"version":2'),
valid.replace('"openingCash"', '"investorName"'),
]) {
assert.equal(guidance.restoreAnnualExampleSnapshot(source), null);
const { SimulationAnnualExample } = load('simulation-annual-example', {
'@/lib/business-plan-guidance': guidance,
'@/lib/business-financial-plan': business,
'./business-plan-warnings': { BusinessPlanWarnings: () => null },
});
let overwritten = false;
const html = renderToStaticMarkup(
SimulationAnnualExample({
currency: 'MZN',
snapshot: source,
onSnapshotChange: () => {
overwritten = true;
},
}),
);
assert.match(html, /conteúdo guardado foi preservado/);
assert.equal(overwritten, false);
}
});