feat: apply owner warning decisions and add editable annual planning example

This commit is contained in:
2026-11-20 10:01:44 +02:00
parent 04d8db6c1b
commit 5f7db7cd9b
15 changed files with 1069 additions and 32 deletions
@@ -65,13 +65,19 @@ function editor(initialSnapshot) {
}).outputText;
compileFunction(code, ['require', 'module', 'exports'])(
(name) =>
({
(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,
})[name] ?? require(name),
}[name] ??
require(name),
module,
module.exports,
);
@@ -0,0 +1,131 @@
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.doesNotMatch(html, /role="alert"|aria-invalid="true"|disabled=/);
assert.match(html.replace(/[\s\u00a0\u202f]/g, ''), /1325000[.,]00/);
});
@@ -0,0 +1,163 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
businessPlanWarnings,
defaultPlanWarningLimits,
newAnnualReferencePlan,
calculateAnnualReferencePlan,
} from '../../resources/js/lib/business-plan-guidance.ts';
import {
forecastBusinessPlan,
serializeBusinessPlanSnapshot,
restoreBusinessPlanSnapshot,
} from '../../resources/js/lib/business-financial-plan.ts';
import { validateSimulationDraft } from '../../resources/js/lib/simulation-form.ts';
import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.ts';
function businessPlan() {
const amounts = [
'monthlyCollections',
'monthlyVariableCostPayments',
'monthlyInventoryPurchases',
'monthlyOperatingExpenses',
'monthlyOperatingPayments',
'monthlyPayrollExpense',
'monthlyPayrollPayments',
'inventory',
'receivables',
'payables',
'equity',
'shareholderLoans',
'bankLoanProceeds',
'grants',
'assetDepreciation',
'monthlyInterestExpense',
'monthlyInterestPayment',
'monthlyPrincipalRepayment',
];
return {
...Object.fromEntries(amounts.map((key) => [key, '0'])),
currency: 'MZN',
openingCash: '1000',
assetInvestment: '200',
products: [
{
label: 'Serviço sintético',
monthlyUnits: '10',
unitPrice: '100',
unitVariableCost: '40',
},
],
depreciationLifeMonths: 60,
periods: 12,
annualGrowthPercent: '250',
};
}
void test('insufficient funding and growth above 100 percent remain valid, saved assumptions with nonblocking warnings', () => {
const plan = businessPlan();
const snapshot = serializeBusinessPlanSnapshot(plan);
const restored = restoreBusinessPlanSnapshot(snapshot);
assert.equal(restored.annualGrowthPercent, '250');
const result = forecastBusinessPlan(restored);
assert.equal(result.fundingGap, '200.00');
assert.equal(result.totalRevenue, '12000.00', 'a growth target must not overwrite declared sales');
assert.equal(
validateSimulationDraft(
{ business_plan_snapshot: snapshot },
'financial',
).business_plan_snapshot,
undefined,
);
const warnings = businessPlanWarnings({
fundingGap: Number(result.fundingGap),
growthPercent: Number(restored.annualGrowthPercent),
currency: 'MZN',
});
assert.deepEqual(
warnings.map((warning) => warning.id),
['funding', 'growth'],
);
const report = createProjectDossierReport(
{ business_plan_snapshot: snapshot },
{
selectedSections: new Set(['finance']),
generatedAt: '2026-11-20T08:00:00Z',
},
);
assert.match(JSON.stringify(report), /aviso não bloqueante/);
assert.match(JSON.stringify(report), /Crescimento anual pretendido/);
assert.match(JSON.stringify(report), /250%/);
});
void test('owner annual reference reconciles exact startup, margins, profits, cash and unrounded break-even', () => {
const source = newAnnualReferencePlan(),
before = JSON.stringify(source);
const result = calculateAnnualReferencePlan(source),
first = result.years[0];
assert.equal(result.startupExpenses, '1325000.00');
assert.equal(result.assets, '500250.00');
assert.equal(result.requiredFunding, '1825250.00');
assert.equal(result.availableFunding, '0.00');
assert.equal(result.fundingGap, '1825250.00');
assert.equal(first.grossMargin, '1999.00');
assert.equal(first.operatingExpenses, '2415.00');
assert.equal(first.operatingProfit, '-416.00');
assert.equal(first.netProfit, '-416.00');
assert.equal(first.cashFlow, '756.00');
assert.equal(first.closingCash, '90756.00');
assert.equal(Math.round(first.monthlyBreakEven), 1464);
assert.ok(
Math.abs(first.monthlyBreakEven - 2415 / 12 / (1999 / 14537)) < 1e-10,
);
assert.equal(result.years[1].netProfit, '1456.00');
assert.equal(result.years[2].netProfit, '1631.00');
assert.equal(result.years[2].closingCash, '93498.00');
assert.equal(result.monthlyStatus, 'por reconciliar');
assert.equal('monthlyRows' in result, false);
const warnings = businessPlanWarnings({
fundingGap: Number(result.fundingGap),
netProfit: Number(first.netProfit),
sales: Number(first.sales),
directCosts: Number(first.directCosts),
monthlyBreakEven: first.monthlyBreakEven,
});
assert.ok(warnings.some((warning) => warning.id === 'loss'));
assert.ok(warnings.some((warning) => warning.id === 'break-even'));
assert.equal(JSON.stringify(source), before);
});
void test('reference edits update dependent totals and preserve data when an input is invalid', () => {
const source = newAnnualReferencePlan();
source.startupExpenses[0].amount = '25000.25';
assert.equal(
calculateAnnualReferencePlan(source).requiredFunding,
'1825250.25',
);
source.years[0].sales = '';
assert.throws(
() => calculateAnnualReferencePlan(source),
/Preencha este campo para continuar/,
);
assert.equal(source.startupExpenses[0].amount, '25000.25');
source.years[0].sales = '0';
assert.throws(
() => calculateAnnualReferencePlan(source),
/Indique as vendas previstas/,
);
source.years[0].sales = '100';
assert.throws(() => calculateAnnualReferencePlan(source), /não há margem/);
});
void test('warning limits are configurable and equality at the threshold is not a warning', () => {
assert.deepEqual(businessPlanWarnings({ growthPercent: 100 }), []);
assert.deepEqual(
businessPlanWarnings(
{ growthPercent: 250 },
{ ...defaultPlanWarningLimits, annualGrowthPercent: 300 },
),
[],
);
assert.equal(businessPlanWarnings({ creditDays: 91 })[0].id, 'credit');
assert.deepEqual(businessPlanWarnings({ creditDays: 90 }), []);
});