fix: persist annual demonstration through existing simulation drafts

This commit is contained in:
2026-11-20 11:11:38 +02:00
parent 18dda022a0
commit 51d31d3790
9 changed files with 341 additions and 11 deletions
@@ -6,6 +6,10 @@ 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';
@@ -140,9 +144,40 @@ function editor(initialSnapshot) {
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 [
@@ -133,3 +133,157 @@ void test('annual example renders expected results and source gaps without block
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);
}
});