fix: retain editable investment plans and record partial QA continuity evidence

This commit is contained in:
2026-11-20 09:25:49 +02:00
parent bae996e10d
commit 04d8db6c1b
17 changed files with 1011 additions and 290 deletions
@@ -0,0 +1,231 @@
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 * 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) =>
({
react: hooks,
'@/components/currency-select': { CurrencySelect: () => null },
'@/lib/business-financial-plan': business,
'@/lib/simulation-contract': contract,
'@/lib/financial-fiscal-bridge': bridge,
})[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,
};
}
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,
);
});
+161 -90
View File
@@ -1,26 +1,26 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import { createRequire } from "node:module";
import { compileFunction } from "node:vm";
import React from "react";
import ts from "typescript";
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import React from 'react';
import ts from 'typescript';
const require = createRequire(import.meta.url);
const nodes = (tree) =>
Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === "object"
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
const text = (tree) =>
Array.isArray(tree)
? tree.map(text).join("")
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === "string"
: typeof tree === 'string'
? tree
: "";
: '';
// Real page event handlers, simulated Inertia transport. Not a browser or visual acceptance.
function harness(filters, errors = {}) {
@@ -32,7 +32,8 @@ function harness(filters, errors = {}) {
return [
memory[id],
(next) => {
memory[id] = typeof next === "function" ? next(memory[id]) : next;
memory[id] =
typeof next === 'function' ? next(memory[id]) : next;
},
];
};
@@ -40,7 +41,10 @@ function harness(filters, errors = {}) {
let form;
const TerritoryFields = () => null;
const module = { exports: {} };
const source = fs.readFileSync("resources/js/pages/funding/index.tsx", "utf8");
const source = fs.readFileSync(
'resources/js/pages/funding/index.tsx',
'utf8',
);
compileFunction(
ts.transpileModule(source, {
compilerOptions: {
@@ -48,10 +52,10 @@ function harness(filters, errors = {}) {
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText,
["require", "module", "exports"],
['require', 'module', 'exports'],
)(
(id) => {
if (id === "react")
if (id === 'react')
return {
...React,
useState: state,
@@ -60,9 +64,9 @@ function harness(filters, errors = {}) {
return value;
},
};
if (id === "@inertiajs/react")
if (id === '@inertiajs/react')
return {
Link: "a",
Link: 'a',
useForm(initial) {
const [data, set] = state(initial);
form = {
@@ -70,7 +74,11 @@ function harness(filters, errors = {}) {
errors: {},
processing: false,
setData(key, value) {
set(typeof key === "string" ? { ...data, [key]: value } : key);
set(
typeof key === 'string'
? { ...data, [key]: value }
: key,
);
},
get(url) {
submitted = { url, data };
@@ -79,22 +87,25 @@ function harness(filters, errors = {}) {
return form;
},
};
if (id === "@/pages/investment/shared") return { Frame: "main", card: "", button: "" };
if (id === "@/components/funding-classification")
if (id === '@/pages/investment/shared')
return { Frame: 'main', card: '', button: '' };
if (id === '@/components/funding-classification')
return {
financialCategories: {
banking: "Banca",
insurance_intermediation: "Mediação de seguros",
banking: 'Banca',
insurance_intermediation: 'Mediação de seguros',
},
financialTypes: {
commercial_bank: "Banco comercial",
broker: "Corretora",
other: "Outro",
commercial_bank: 'Banco comercial',
broker: 'Corretora',
other: 'Outro',
},
};
if (id === "@/components/investment-territory") return { TerritoryFields };
if (id === "@/components/funding-institution") return { InstitutionView: "article" };
if (id === "./shared") return { windowLabels: {} };
if (id === '@/components/investment-territory')
return { TerritoryFields };
if (id === '@/components/funding-institution')
return { InstitutionView: 'article' };
if (id === './shared') return { windowLabels: {} };
return require(id);
},
module,
@@ -105,11 +116,11 @@ function harness(filters, errors = {}) {
criteriaErrors: errors,
items: { data: [], links: [] },
options: { sectors: [], territories: [] },
kinds: { institution: "Instituição", fund: "Fundo" },
kinds: { institution: 'Instituição', fund: 'Fundo' },
management: false,
categoryTypes: {
banking: ["commercial_bank"],
insurance_intermediation: ["broker"],
banking: ['commercial_bank'],
insurance_intermediation: ['broker'],
},
};
let tree;
@@ -120,9 +131,11 @@ function harness(filters, errors = {}) {
return tree;
}
const select = (label) =>
nodes(nodes(tree).find((n) => n.type === "label" && text(n).startsWith(label))).find(
(n) => n.type === "select",
);
nodes(
nodes(tree).find(
(n) => n.type === 'label' && text(n).startsWith(label),
),
).find((n) => n.type === 'select');
render();
return {
render,
@@ -134,92 +147,150 @@ function harness(filters, errors = {}) {
};
}
test("institution category restricts types and removes only an incompatible dependent choice", () => {
void test('searching another province resets only the search location and preserves the investment scope', () => {
const filters = {
category: 'banking',
institution_type: 'commercial_bank',
need: 'investment',
context: 'case-qa',
opportunity: 'opportunity-qa',
province_id: 'province-qa',
district_id: 'district-qa',
territory: 'district-qa',
location_mode: 'physical',
certainty: 'documented',
};
const h = harness(filters);
const action = nodes(h.tree()).find(
(n) =>
n.type === 'button' &&
text(n) === 'Procurar instituição noutra província',
);
assert.ok(action);
action.props.onClick();
h.render();
for (const key of [
'territory',
'province_id',
'district_id',
'admin_post_id',
'locality_id',
])
assert.equal(h.form().data[key], '');
for (const key of [
'category',
'institution_type',
'need',
'context',
'opportunity',
'location_mode',
'certainty',
])
assert.equal(h.form().data[key], filters[key]);
assert.deepEqual(h.territory().props.initial, []);
assert.equal(h.submitted(), undefined);
assert.match(
text(h.tree()),
/a localização do investimento no dossier mantém-se/,
);
});
void test('institution category restricts types and removes only an incompatible dependent choice', () => {
const h = harness({
category: "insurance_intermediation",
institution_type: "broker",
sector: "7",
need: "investment",
territory: "district-qa",
category: 'insurance_intermediation',
institution_type: 'broker',
sector: '7',
need: 'investment',
territory: 'district-qa',
});
h.select("Categoria da instituição").props.onChange({
target: { value: "banking" },
h.select('Categoria da instituição').props.onChange({
target: { value: 'banking' },
});
h.render();
assert.equal(h.form().data.institution_type, "");
assert.equal(h.form().data.institution_type, '');
for (const [key, value] of Object.entries({
sector: "7",
need: "investment",
territory: "district-qa",
sector: '7',
need: 'investment',
territory: 'district-qa',
}))
assert.equal(h.form().data[key], value);
assert.deepEqual(
nodes(h.select("Tipo de instituição"))
.filter((n) => n.type === "option")
nodes(h.select('Tipo de instituição'))
.filter((n) => n.type === 'option')
.map((n) => n.props.value),
["", "commercial_bank", "other"],
['', 'commercial_bank', 'other'],
);
assert.match(text(h.tree()), /tipo anterior não pertence/);
const results = nodes(h.tree()).find((n) => n.type === "details");
const results = nodes(h.tree()).find((n) => n.type === 'details');
assert.equal(results.props.open, false);
assert.match(text(results), /pesquisa anterior/);
});
test("contradictory record criteria remain explicit until the user chooses a correction", () => {
void test('contradictory record criteria remain explicit until the user chooses a correction', () => {
const h = harness(
{
kind: "fund",
category: "banking",
institution_type: "commercial_bank",
location_mode: "physical",
province_id: "province-qa",
sector: "8",
state: "closed",
certainty: "documented",
kind: 'fund',
category: 'banking',
institution_type: 'commercial_bank',
location_mode: 'physical',
province_id: 'province-qa',
sector: '8',
state: 'closed',
certainty: 'documented',
},
{ kind: ["Combinação incompatível."] },
{ kind: ['Combinação incompatível.'] },
);
assert.match(text(h.tree()), /A pesquisa não foi executada/);
assert.equal(h.form().data.kind, "fund");
assert.equal(h.form().data.kind, 'fund');
const action = nodes(h.tree()).find(
(n) => n.type === "button" && /Manter o fundo/.test(text(n)),
(n) => n.type === 'button' && /Manter o fundo/.test(text(n)),
);
action.props.onClick();
h.render();
assert.equal(h.form().data.category, "");
assert.equal(h.form().data.institution_type, "");
assert.equal(h.form().data.location_mode, "coverage");
assert.equal(h.form().data.category, '');
assert.equal(h.form().data.institution_type, '');
assert.equal(h.form().data.location_mode, 'coverage');
for (const [key, value] of Object.entries({
kind: "fund",
province_id: "province-qa",
sector: "8",
state: "closed",
certainty: "documented",
kind: 'fund',
province_id: 'province-qa',
sector: '8',
state: 'closed',
certainty: 'documented',
}))
assert.equal(h.form().data[key], value);
nodes(h.tree())
.find((n) => n.type === "form")
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.equal(h.submitted().url, "/fundos");
assert.equal(h.submitted().data.province_id, "province-qa");
assert.ok(h.territory(), "the catalogue consumes the common hierarchical location control");
assert.equal(h.submitted().url, '/fundos');
assert.equal(h.submitted().data.province_id, 'province-qa');
assert.ok(
h.territory(),
'the catalogue consumes the common hierarchical location control',
);
});
test("local search defaults to documented presence and keeps the explicit unknown option and chosen territory", () => {
const h = harness({ territory: "district-qa", sector: "7" });
h.select("Localização a pesquisar").props.onChange({ target: { value: "physical" } });
h.render();
assert.equal(h.form().data.certainty, "documented");
assert.equal(h.form().data.territory, "district-qa");
assert.equal(h.form().data.sector, "7");
h.select("Informação por confirmar").props.onChange({ target: { value: "include_unknown" } });
h.render();
assert.equal(h.form().data.certainty, "include_unknown");
const resumed = harness({
location_mode: "physical",
territory: "district-qa",
certainty: "include_unknown",
void test('local search defaults to documented presence and keeps the explicit unknown option and chosen territory', () => {
const h = harness({ territory: 'district-qa', sector: '7' });
h.select('Localização a pesquisar').props.onChange({
target: { value: 'physical' },
});
assert.equal(resumed.form().data.certainty, "include_unknown");
assert.equal(harness({ location_mode: "physical" }).form().data.certainty, "documented");
h.render();
assert.equal(h.form().data.certainty, 'documented');
assert.equal(h.form().data.territory, 'district-qa');
assert.equal(h.form().data.sector, '7');
h.select('Informação por confirmar').props.onChange({
target: { value: 'include_unknown' },
});
h.render();
assert.equal(h.form().data.certainty, 'include_unknown');
const resumed = harness({
location_mode: 'physical',
territory: 'district-qa',
certainty: 'include_unknown',
});
assert.equal(resumed.form().data.certainty, 'include_unknown');
assert.equal(
harness({ location_mode: 'physical' }).form().data.certainty,
'documented',
);
});
+26
View File
@@ -8,6 +8,32 @@ import {
import { getSimulationSections } from '../../resources/js/lib/simulation-form.ts';
import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.ts';
void test('readiness explains stored answer codes in Portuguese without changing the draft', () => {
const draft = {
target_customers: 'Clientes sintéticos',
market_assumption: 'Hipótese por testar',
customer_validation_status: 'partial',
cost_estimate_status: 'unknown',
location_assessment_status: 'no',
funding_status: 'in_process',
receivables_timing_status: 'not_started',
annual_revenue: '12000',
};
const before = JSON.stringify(draft);
const origins = getProjectReadiness(draft)
.map((item) => item.origin)
.join('\n');
assert.match(origins, /Parcialmente/);
assert.match(origins, /Por confirmar/);
assert.match(origins, /Estado declarado: Não/);
assert.match(origins, /Em curso/);
assert.doesNotMatch(
origins,
/\b(?:partial|unknown|in_process|not_started)\b/,
);
assert.equal(JSON.stringify(draft), before);
});
void test('idea journey reuses one dossier and exposes the six requested stages', () => {
const sections = getSimulationSections({
purpose: 'simulate_only',