Simulador: os campos numéricos aceitam «25.000», «1 500» e «1500,50»
tests / ci (push) Canceled after 0s

O campo numérico do navegador segue a língua do navegador: «25.000» era
lido como 25 e a vírgula decimal podia ser recusada, pelo que o investidor
via o valor mudar ou não conseguia escrever. Os campos de montantes do
simulador, do plano de negócio e do orçamento inicial passam a usar um
campo de texto decimal que lê os números como se escrevem em Moçambique,
mostra «Lido como …» quando reinterpreta e deixa o texto inválido chegar à
validação, que o explica.

Os campos inteiros (horizonte, prazo de entrega, vida útil, mês económico)
deixam de saltar para 1 quando se apaga para reescrever; se o valor escrito
não for aceite, ao sair do campo volta o valor em vigor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
This commit is contained in:
Claude
2026-12-04 23:01:57 +02:00
committed by nala
parent 52176edc21
commit 4745331ebd
28 changed files with 559 additions and 196 deletions
@@ -14,6 +14,7 @@ import {
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';
import { decimalInputModule } from './helpers/decimal-input.mjs';
// Exercise the real input callbacks and the parent's snapshot echo, including
// effects. No server, database or fiscal rates are used by this regression.
@@ -111,7 +112,9 @@ function editor(initialSnapshot) {
PlanEconomicClassification: () => null,
},
}[name] ??
require(name),
(name === '@/components/decimal-input'
? decimalInputModule
: require(name)),
module,
module.exports,
);
@@ -9,6 +9,7 @@ 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';
import { decimalInputModule } from './helpers/decimal-input.mjs';
const require = createRequire(import.meta.url);
function load(name, mocks) {
const source = fs.readFileSync(
@@ -24,7 +25,11 @@ function load(name, mocks) {
}).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(key) => mocks[key] ?? require(key),
(key) =>
mocks[key] ??
(key === '@/components/decimal-input'
? decimalInputModule
: require(key)),
module,
module.exports,
);
+152
View File
@@ -0,0 +1,152 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
normalizeDecimalInput,
presentDecimal,
} from '../../resources/js/lib/decimal-input.ts';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
/** The real field, with state kept between calls as React would keep it. */
function field(initial, emitted, accepts = () => true) {
const memory = [];
let cursor = 0;
let value = initial;
const hooks = {
...React,
useId: () => 'decimal-hint',
useEffect() {},
useRef(start) {
const id = cursor++;
if (!(id in memory)) memory[id] = { current: start };
return memory[id];
},
useState(start) {
const id = cursor++;
if (!(id in memory)) memory[id] = start;
return [memory[id], (next) => (memory[id] = next)];
},
};
const module = { exports: {} };
compileFunction(
ts.transpileModule(
fs.readFileSync(
'resources/js/components/decimal-input.tsx',
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText,
['require', 'module', 'exports'],
)(
(id) =>
id === 'react'
? hooks
: id === '@/lib/decimal-input'
? { normalizeDecimalInput, presentDecimal }
: require(id),
module,
module.exports,
);
const render = () => {
cursor = 0;
const tree = module.exports.DecimalInput({
value,
onValueChange(next) {
emitted.push(next);
if (accepts(next)) value = next;
},
});
return [tree.props.children].flat().filter(Boolean);
};
return {
input: () => render()[0],
hint: () => render()[1],
type(text) {
render()[0].props.onChange({ target: { value: text } });
},
};
}
test('numbers are read as written in Mozambique, never silently changed (Criar Hotel: campos que não aceitam introdução)', () => {
for (const [typed, stored] of [
['25.000', '25000'],
['1.500.000', '1500000'],
['1 500', '1500'],
['1 500', '1500'],
['1500,50', '1500.50'],
['1.500,25', '1500.25'],
[',5', '0.5'],
['1500.50', '1500.50'],
['0.125', '0.125'],
['1.5', '1.5'],
['120', '120'],
['-25.000', '-25000'],
['', ''],
[' ', ''],
])
assert.equal(normalizeDecimalInput(typed), stored, typed);
for (const invalid of [
'abc',
'1,2,3',
'1.234.5',
'12.34,5.6',
'1e5',
'--1',
])
assert.equal(normalizeDecimalInput(invalid), null, invalid);
assert.equal(presentDecimal('1500000.5'), '1 500 000,5');
assert.equal(presentDecimal('-25000'), '-25 000');
});
test('the simulator field takes «25.000» and «1 500,50» as typed, says how it read them and keeps the text while it is being written', () => {
const emitted = [];
const f = field('', emitted);
assert.equal(f.input().type, 'input');
assert.equal(f.input().props.type, 'text');
assert.equal(f.input().props.inputMode, 'decimal');
f.type('25.000');
assert.equal(emitted.at(-1), '25000');
assert.equal(f.input().props.value, '25.000');
assert.match(
renderToStaticMarkup(f.hint()),
/Lido como 25(\s|&nbsp;| )000/,
);
f.type('1 500,50');
assert.equal(emitted.at(-1), '1500.50');
f.type('abc');
assert.equal(emitted.at(-1), 'abc', 'invalid text reaches validation');
f.type('');
assert.equal(emitted.at(-1), '');
});
test('an integer field emptied while retyping shows again the value still in force', () => {
const emitted = [];
// Like the horizon: the plan only accepts a number.
const f = field(12, emitted, (next) => /^\d+$/.test(next));
assert.equal(f.input().props.value, '12');
f.type('');
assert.equal(f.input().props.value, '');
f.input().props.onBlur({});
assert.equal(f.input().props.value, '12');
f.type('1,5');
f.input().props.onBlur({});
assert.equal(
f.input().props.value,
'12',
'a fraction of a month is not kept',
);
f.type('24');
f.input().props.onBlur({});
assert.equal(f.input().props.value, '24');
});
@@ -29,6 +29,11 @@ import {
createProjectDossierPrintHtml,
generateProjectDossierDocx,
} from '../../resources/js/lib/project-dossier-report.ts';
import {
decimalInputModule,
isNumberField,
typeNumber,
} from './helpers/decimal-input.mjs';
const cell = (tables, id, label, index) =>
tables.find((t) => t.id === id).rows.find((r) => r[0] === label)[index];
@@ -357,7 +362,11 @@ void test('actual editor controls preserve declarations through snapshot reload
require = createRequire(import.meta.url);
compileFunction(code, ['require', 'module', 'exports'])(
(name) =>
name === '@/lib/business-plan-guidance' ? guidance : require(name),
name === '@/lib/business-plan-guidance'
? guidance
: name === '@/components/decimal-input'
? decimalInputModule
: require(name),
module,
module.exports,
);
@@ -390,19 +399,18 @@ void test('actual editor controls preserve declarations through snapshot reload
);
assert.ok(node, label);
return nodes(node).find(
(n) => n.type === 'input' || n.type === 'select',
(n) =>
isNumberField(n) || n.type === 'input' || n.type === 'select',
);
};
field('Projectar os anos seguintes').props.onChange({
target: { checked: true },
});
assert.equal(plan.applyAnnualGrowth, true);
field('Prazo de recebimento a crédito').props.onChange({
target: { value: '91' },
});
typeNumber(field('Prazo de recebimento a crédito'), '91');
assert.equal(plan.creditTermDays, '91');
field('Planear dividendos').props.onChange({ target: { checked: true } });
field('Dividendos, mês 1').props.onChange({ target: { value: '12.25' } });
typeNumber(field('Dividendos, mês 1'), '12.25');
assert.equal(plan.dividendsByPeriod[0], '12.25');
assert.equal(
nodes(render()).some(
@@ -8,6 +8,7 @@ import ts from 'typescript';
import * as finance from '../../resources/js/lib/financial-calculators.ts';
import * as contract from '../../resources/js/lib/simulation-contract.ts';
import * as fundingContext from '../../resources/js/lib/planning-finance-context.ts';
import { decimalInputModule } from './helpers/decimal-input.mjs';
const require = createRequire(import.meta.url);
const nodes = tree => Array.isArray(tree) ? tree.flatMap(nodes) : tree && typeof tree === 'object' ? [tree, ...nodes(tree.props?.children)] : [];
const text = tree => Array.isArray(tree) ? tree.map(text).join('') : tree?.props ? text(tree.props.children) : typeof tree === 'string' ? tree : '';
@@ -16,7 +17,7 @@ function harness(snapshot = '') {
const memory=[], deps=[];
const hooks={...React, useState(initial) {const id=cursor++;if(!(id in memory))memory[id]=typeof initial==='function'?initial():initial;return[memory[id],next=>{const value=typeof next==='function'?next(memory[id]):next;if(!Object.is(value,memory[id])){memory[id]=value;dirty=true;}}];},useEffect(effect, next) {const id=cursor++;if(!deps[id]||next.some((value,i)=>!Object.is(value,deps[id][i]))){queue.push(effect);deps[id]=next;}}};
const module={exports:{}};
compileFunction(ts.transpileModule(fs.readFileSync('resources/js/components/simulation-financial-tools.tsx','utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX}}).outputText,['require','module','exports'])(id=>id==='react'?hooks:id==='@/components/currency-select'?{default:()=>null}:id==='@/lib/financial-calculators'?finance:id==='@/lib/simulation-contract'?contract:id==='@/lib/planning-finance-context'?fundingContext:require(id),module,module.exports);
compileFunction(ts.transpileModule(fs.readFileSync('resources/js/components/simulation-financial-tools.tsx','utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX}}).outputText,['require','module','exports'])(id=>id==='react'?hooks:id==='@/components/currency-select'?{default:()=>null}:id==='@/lib/financial-calculators'?finance:id==='@/lib/simulation-contract'?contract:id==='@/lib/planning-finance-context'?fundingContext:(id==='@/components/decimal-input'?decimalInputModule:require(id)),module,module.exports);
const props={currency:'MZN',focus:'funding',loanRelevant:false,snapshot,sourceFunding:{total:'2000000',secured:''},onSnapshotChange(value){props.snapshot=value;dirty=true;},onCurrencyChange(){},onFundingChange(key,value){props.sourceFunding={...props.sourceFunding,[key]:value};dirty=true;}};
const render=()=>{for(let i=0;i<12;i++){cursor=0;queue=[];dirty=false;tree=module.exports.SimulationFinancialTools(props);for(const effect of queue)effect();if(!dirty)return;}throw new Error('Render did not settle');};
render();
+57
View File
@@ -0,0 +1,57 @@
// The real DecimalInput, compiled for the harnesses that load components with
// their own `require`, plus helpers to type into it from a walked element tree.
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import ts from 'typescript';
import * as decimal from '../../../resources/js/lib/decimal-input.ts';
const require = createRequire(import.meta.url);
const module = { exports: {} };
compileFunction(
ts.transpileModule(
fs.readFileSync(
new URL(
'../../../resources/js/components/decimal-input.tsx',
import.meta.url,
),
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText,
['require', 'module', 'exports'],
)(
(id) =>
id === 'react'
? React
: id === '@/lib/decimal-input'
? decimal
: require(id),
module,
module.exports,
);
export const decimalInputModule = module.exports;
export const DecimalInput = module.exports.DecimalInput;
/** A number field in a walked tree: the decimal field or a plain number input. */
export const isNumberField = (node) =>
node?.type === DecimalInput ||
(node?.type === 'input' && node.props?.type === 'number');
/** Types `value` as the investor would, through whichever field the tree holds. */
export function typeNumber(node, value) {
const text = String(value);
if (node.type === DecimalInput) {
const normalized = decimal.normalizeDecimalInput(text);
node.props.onValueChange(normalized === null ? text : normalized);
return;
}
node.props.onChange({ target: { value: text } });
}
@@ -15,6 +15,11 @@ import {
serializeBusinessPlanSnapshot,
restoreBusinessPlanSnapshot,
} from '../../resources/js/lib/business-financial-plan.ts';
import {
decimalInputModule,
isNumberField,
typeNumber,
} from './helpers/decimal-input.mjs';
void test('one startup editor retains all rows and persists an edit without duplicating controls or changing reconciliation', () => {
const source = fs.readFileSync(
@@ -39,17 +44,19 @@ void test('one startup editor retains all rows and persists an edit without dupl
? report
: name === '@/lib/irpc-plan-scenario'
? irpcScenario
: name === './investment-report-tables'
? { InvestmentReportTables: () => null }
: name === '@/lib/financial-plan-warnings'
? warnings
: name === '@/lib/annual-example-report'
? annual
: name === './business-plan-warnings'
? { BusinessPlanWarnings: () => null }
: name === './startup-asset-requirements'
? { StartupAssetRequirements: () => null }
: require(name),
: name === './investment-report-tables'
? { InvestmentReportTables: () => null }
: name === '@/lib/financial-plan-warnings'
? warnings
: name === '@/lib/annual-example-report'
? annual
: name === './business-plan-warnings'
? { BusinessPlanWarnings: () => null }
: name === './startup-asset-requirements'
? { StartupAssetRequirements: () => null }
: name === '@/components/decimal-input'
? decimalInputModule
: require(name),
module,
module.exports,
);
@@ -80,9 +87,7 @@ void test('one startup editor retains all rows and persists an edit without dupl
'Montante de arranque 1',
),
);
nodes(label)
.find((node) => node.type === 'input')
.props.onChange({ target: { value: '100.25' } });
typeNumber(nodes(label).find(isNumberField), '100.25');
plan = restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(plan));
assert.equal(plan.reportAssumptions.startupExpenses[0].amount, '100.25');
assert.match(renderToStaticMarkup(render()), /value="100.25"/);
@@ -5,6 +5,11 @@ import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import ts from 'typescript';
import {
decimalInputModule,
isNumberField,
typeNumber,
} from './helpers/decimal-input.mjs';
import * as finance from '../../resources/js/lib/financial-calculators.ts';
import * as operating from '../../resources/js/lib/investment-operating-assistance.ts';
const require = createRequire(import.meta.url);
@@ -63,7 +68,9 @@ function harness(file, snapshot = '') {
? finance
: id === '@/lib/investment-operating-assistance'
? operating
: require(id),
: id === '@/components/decimal-input'
? decimalInputModule
: require(id),
module,
module.exports,
);
@@ -94,12 +101,7 @@ function harness(file, snapshot = '') {
test('initial budget has no sample amounts and adopts a sum only through the explicit action', () => {
const h = harness('investment-initial-budget.tsx');
const amounts = () =>
h
.nodes()
.filter(
(node) => node.type === 'input' && node.props.type === 'number',
);
const amounts = () => h.nodes().filter(isNumberField);
assert.deepEqual(
amounts().map((node) => node.props.value),
['', '', '', ''],
@@ -112,9 +114,7 @@ test('initial budget has no sample amounts and adopts a sum only through the exp
false,
);
for (let i = 0; i < 4; i++) {
amounts()[i].props.onChange({
target: { value: String((i + 1) * 1000) },
});
typeNumber(amounts()[i], (i + 1) * 1000);
h.render();
}
assert.equal(
@@ -131,9 +131,7 @@ test('initial budget has no sample amounts and adopts a sum only through the exp
assert.deepEqual(
restored
.nodes()
.filter(
(node) => node.type === 'input' && node.props.type === 'number',
)
.filter(isNumberField)
.map((node) => node.props.value),
['1000', '2000', '3000', '4000'],
);
@@ -145,14 +143,9 @@ test('hotel estimate is selected deliberately, saved as assumptions, then adopte
.find((node) => node.type === 'select')
.props.onChange({ target: { value: 'hotel' } });
h.render();
const amounts = () =>
h
.nodes()
.filter(
(node) => node.type === 'input' && node.props.type === 'number',
);
const amounts = () => h.nodes().filter(isNumberField);
for (const [i, value] of ['10', '5000', '50', '300'].entries()) {
amounts()[i].props.onChange({ target: { value } });
typeNumber(amounts()[i], value);
h.render();
}
assert.equal(
@@ -30,6 +30,11 @@ import {
generateProjectDossierDocx,
} from '../../resources/js/lib/project-dossier-report.ts';
import { selectPlanCae } from '../../resources/js/lib/cae-mozambique.ts';
import {
decimalInputModule,
isNumberField,
typeNumber,
} from './helpers/decimal-input.mjs';
const cell = (ts, id, label, col) =>
ts.find((t) => t.id === id).rows.find((r) => r[0] === label)[col];
const cents = (s) => BigInt(s.replace('.', ''));
@@ -213,7 +218,9 @@ void test('F16 real editor adopts only acquisitions on explicit action and can r
? requirements
: name === '@/lib/integral-financial-report'
? { newReportAssumptions }
: require(name),
: name === '@/components/decimal-input'
? decimalInputModule
: require(name),
module,
module.exports,
);
@@ -253,9 +260,7 @@ void test('F16 real editor adopts only acquisitions on explicit action and can r
const l = nodes(render()).find(
(n) => n.type === 'label' && text(n).startsWith(label),
);
nodes(l)
.find((n) => n.type === 'input')
.props.onChange({ target: { value } });
typeNumber(nodes(l).find(isNumberField), value);
}
nodes(render())
.find((n) => n.type === 'button' && text(n).includes('Adoptar'))
+6 -1
View File
@@ -14,6 +14,7 @@ import * as annual from '../../resources/js/lib/annual-example-report.ts';
import * as warnings from '../../resources/js/lib/financial-plan-warnings.ts';
import * as irpcScenario from '../../resources/js/lib/irpc-plan-scenario.ts';
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
import { decimalInputModule } from './helpers/decimal-input.mjs';
const require = createRequire(import.meta.url);
const modules = {
@@ -48,7 +49,11 @@ function component(name) {
compileFunction(code, ['require', 'module', 'exports'])(
(id) =>
modules[id] ??
(id.startsWith('./') ? component(id.slice(2)) : require(id)),
(id.startsWith('./')
? component(id.slice(2))
: id === '@/components/decimal-input'
? decimalInputModule
: require(id)),
module,
module.exports,
);
+6 -1
View File
@@ -11,6 +11,7 @@ import { complementaryFixture } from './fixtures/complementary-plan.mjs';
import * as business from '../../resources/js/lib/business-financial-plan.ts';
import * as dossier from '../../resources/js/lib/project-dossier.ts';
import * as complementary from '../../resources/js/lib/complementary-report.ts';
import { decimalInputModule } from './helpers/decimal-input.mjs';
test('V12 final: supplier import without product stock identifies the incompatible controls without weakening rejection', () => {
const plan = financialReportFixture(2);
@@ -105,7 +106,11 @@ test('V12 final: actual personnel component receives currency, withholds reconci
},
};
compileFunction(code, ['require', 'module', 'exports'])(
(key) => mocks[key] ?? require(key),
(key) =>
mocks[key] ??
(key === '@/components/decimal-input'
? decimalInputModule
: require(key)),
module,
module.exports,
);