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
+89
View File
@@ -0,0 +1,89 @@
import {
useEffect,
useId,
useRef,
useState,
type InputHTMLAttributes,
} from 'react';
import { normalizeDecimalInput, presentDecimal } from '@/lib/decimal-input';
type Props = Omit<
InputHTMLAttributes<HTMLInputElement>,
'type' | 'value' | 'onChange' | 'min' | 'max' | 'step'
> & {
value: string | number | null | undefined;
/** Receives the stored format ("1500.50"), or the raw text when it is not a number, so validation can explain it. */
onValueChange: (value: string) => void;
min?: string | number;
max?: string | number;
step?: string | number;
};
/**
* Number field that reads «25.000», «1 500» and «1500,50» as written in
* Mozambique, instead of the browser's number input, which follows the
* browser locale (25.000 → 25; a comma may be refused).
*/
export function DecimalInput({
value: rawValue,
onValueChange,
min: _min,
max: _max,
step: _step,
onBlur,
...rest
}: Props) {
const value =
rawValue === null || rawValue === undefined ? '' : String(rawValue);
const hintId = useId();
const [text, setText] = useState(value);
const emitted = useRef(value);
useEffect(() => {
// A value set elsewhere (draft recovery, another field) replaces the text.
if (normalizeDecimalInput(text) !== value) setText(value);
emitted.current = value;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]);
const read = normalizeDecimalInput(text);
const reinterpreted =
read !== null && read !== '' && read !== text.trim() ? read : null;
return (
<>
<input
{...rest}
type="text"
inputMode="decimal"
autoComplete="off"
value={text}
onBlur={(event) => {
// A field the plan did not accept (an emptied horizon, a
// fraction of a month) shows again the value still in force.
if (emitted.current !== value) {
setText(value);
emitted.current = value;
}
onBlur?.(event);
}}
aria-describedby={
[rest['aria-describedby'], reinterpreted ? hintId : null]
.filter(Boolean)
.join(' ') || undefined
}
onChange={(event) => {
setText(event.target.value);
const normalized = normalizeDecimalInput(
event.target.value,
);
emitted.current =
normalized === null ? event.target.value : normalized;
onValueChange(emitted.current);
}}
/>
{reinterpreted && (
<span id={hintId} className="mt-1 block text-xs text-slate-600">
Lido como {presentDecimal(reinterpreted)}
</span>
)}
</>
);
}
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import {
forecastBusinessPlan,
type BusinessFinancialPlanInput,
@@ -198,15 +199,15 @@ export function FinancialDayTerms({
))}
<label className="grid gap-1">
Mês económico
<input
<DecimalInput
className="w-full min-w-0 rounded border p-2"
type="number"
min="1"
max={plan.periods}
value={o.month}
onChange={(e) =>
onValueChange={(value) =>
/^\d+$/.test(value) &&
update(index, {
month: Number(e.target.value),
month: Number(value),
})
}
/>
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
/** Optional declarations share the existing plan snapshot; no independent storage. */
export function FinancialPlanDetails({
@@ -10,13 +11,12 @@ export function FinancialPlanDetails({
const input = (label: string, value: string, save: (s: string) => void) => (
<label className="grid gap-1 text-sm">
{label}
<input
<DecimalInput
className="min-w-0 rounded border p-2"
type="number"
min="0"
step="0.01"
value={value}
onChange={(e) => save(e.target.value)}
onValueChange={(value) => save(value)}
/>
</label>
);
@@ -27,15 +27,14 @@ export function FinancialPlanDetails({
</summary>
<label className="grid gap-1 text-sm">
Prazo de recebimento a crédito (dias, quando conhecido)
<input
type="number"
<DecimalInput
min="0"
max="365"
step="1"
className="min-w-0 rounded border p-2"
value={plan.creditTermDays ?? ''}
onChange={(e) =>
onChange({ ...plan, creditTermDays: e.target.value })
onValueChange={(value) =>
onChange({ ...plan, creditTermDays: value })
}
/>
</label>
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
import { buildFinancialRatiosTable } from '@/lib/financial-ratios-report';
import { InvestmentReportTables } from './investment-report-tables';
@@ -68,14 +69,13 @@ export function FinancialRatiosPlan({
? 'Activo corrente'
: 'Passivo corrente'}{' '}
— mês {i + 1}
<input
<DecimalInput
className="min-w-0 rounded border p-2"
type="number"
min="0"
step="0.01"
value={s?.[key][i] ?? ''}
onChange={(e) =>
save(key, i, e.target.value)
onValueChange={(value) =>
save(key, i, value)
}
/>
</label>
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
import {
buildIntegralFinancialTables,
@@ -49,13 +50,12 @@ export function IntegralFinancialPlan({
) => (
<label className="grid gap-1 text-sm">
{label}
<input
type="number"
<DecimalInput
min="0"
step="0.01"
className="min-w-0 rounded border p-2"
value={value}
onChange={(event) => save(event.target.value)}
onValueChange={(value) => save(value)}
/>
</label>
);
@@ -78,16 +78,13 @@ export function IntegralFinancialPlan({
<div className="grid gap-3 sm:grid-cols-2">
<label className="grid gap-1 text-sm">
Ano inicial
<input
type="number"
<DecimalInput
min="1900"
max="9999"
step="1"
className="rounded border p-2"
value={a.startYear}
onChange={(event) =>
update({ startYear: event.target.value })
}
onValueChange={(value) => update({ startYear: value })}
/>
</label>
{!plan.startupAssetRequirements &&
@@ -319,8 +316,8 @@ function TaxScenario({
<h4 className="font-semibold">Cenário fiscal</h4>
<p className="text-sm">
Escolha o cenário e o simulador calcula o IRPC de cada ano a
partir do lucro antes de impostos, para ver o lucro líquido
e a viabilidade. Pode depois ajustar mês a mês.
partir do lucro antes de impostos, para ver o lucro líquido e a
viabilidade. Pode depois ajustar mês a mês.
</p>
<label className="grid gap-1 text-sm">
Cenário
@@ -331,13 +328,11 @@ function TaxScenario({
setScenario(event.target.value as IrpcPlanScenario)
}
>
{Object.entries(irpcPlanScenarios).map(
([key, option]) => (
<option key={key} value={key}>
{option.label}
</option>
),
)}
{Object.entries(irpcPlanScenarios).map(([key, option]) => (
<option key={key} value={key}>
{option.label}
</option>
))}
</select>
</label>
<button
@@ -345,10 +340,7 @@ function TaxScenario({
className="rounded bg-emerald-800 px-3 py-2 text-white"
onClick={() => {
try {
const result = irpcScenarioSchedule(
plan,
scenario,
);
const result = irpcScenarioSchedule(plan, scenario);
setScenarioError('');
onApply(result);
} catch (cause) {
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import CurrencySelect from './currency-select';
/** A planning interval is not the amount used in a financial calculation. */
@@ -30,15 +31,14 @@ export default function InvestmentBudgetRange({
).map((field, index) => (
<label key={field} className="grid gap-1">
{index === 0 ? 'Desde' : 'Até'}
<input
<DecimalInput
className="min-w-0 rounded border p-2"
disabled={disabled}
type="number"
min="0"
step="any"
value={values[field] ?? ''}
onChange={(event) =>
onChange(field, event.target.value)
onValueChange={(value) =>
onChange(field, value)
}
/>
</label>
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import { useState } from 'react';
import { sumFinancialAmounts } from '@/lib/financial-calculators';
type Row = { label: string; amount: string };
@@ -82,19 +83,18 @@ export default function InvestmentInitialBudget({
</label>
<label>
Montante {currency}
<input
<DecimalInput
className="block w-full rounded border p-2"
type="number"
min="0"
step="0.01"
value={row.amount}
onChange={(e) =>
onValueChange={(value) =>
save(
rows.map((item, i) =>
i === index
? {
...item,
amount: e.target.value,
amount: value,
}
: item,
),
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import { useState } from 'react';
import {
estimateOperatingCosts,
@@ -32,13 +33,12 @@ export default function InvestmentOperatingAssistance({
) => (
<label className="block">
{label}
<input
<DecimalInput
className="block w-full rounded border p-2"
type="number"
min="0"
step="0.01"
value={data[key]}
onChange={(e) => save({ ...data, [key]: e.target.value })}
onValueChange={(value) => save({ ...data, [key]: value })}
/>
</label>
);
@@ -195,13 +195,12 @@ export default function InvestmentOperatingAssistance({
</label>
<label>
Estimativa anual
<input
<DecimalInput
className="block w-full rounded border p-2"
type="number"
min="0"
step="0.01"
value={row.annual}
onChange={(e) =>
onValueChange={(value) =>
save({
...data,
costs: data.costs.map(
@@ -209,9 +208,7 @@ export default function InvestmentOperatingAssistance({
i === index
? {
...item,
annual: e
.target
.value,
annual: value,
}
: item,
),
+10 -17
View File
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import {
readRows,
type ProjectMilestone,
@@ -231,19 +232,18 @@ export function ProjectTeamPlanner({
</label>
<label className="text-sm">
Custo estimado (moeda do projecto)
<input
type="number"
<DecimalInput
min="0"
step="0.01"
className="mt-1 w-full rounded border p-2"
value={row.estimated_cost}
onChange={(e) =>
onValueChange={(value) =>
persist(
update(
rows,
index,
'estimated_cost',
e.target.value,
value,
),
)
}
@@ -424,19 +424,18 @@ export function ProjectMilestonePlanner({
</label>
<label className="text-sm">
Montante planeado
<input
type="number"
<DecimalInput
min="0"
step="0.01"
className="mt-1 w-full rounded border p-2"
value={row.planned_amount}
onChange={(e) =>
onValueChange={(value) =>
persist(
update(
rows,
index,
'planned_amount',
e.target.value,
value,
),
)
}
@@ -444,20 +443,14 @@ export function ProjectMilestonePlanner({
</label>
<label className="text-sm">
Montante realizado
<input
type="number"
<DecimalInput
min="0"
step="0.01"
className="mt-1 w-full rounded border p-2"
value={row.actual_amount}
onChange={(e) =>
onValueChange={(value) =>
persist(
update(
rows,
index,
'actual_amount',
e.target.value,
),
update(rows, index, 'actual_amount', value),
)
}
/>
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import { BusinessPlanWarnings } from './business-plan-warnings';
import {
getProjectReadiness,
@@ -262,16 +263,14 @@ export function ProjectReadiness({
</label>
<label className="grid gap-1 text-sm font-medium">
Custo previsto ({currency})
<input
type="number"
<DecimalInput
min="0"
step="0.01"
className="rounded border p-2"
value={response.estimated_cost}
onChange={(event) =>
onValueChange={(value) =>
updateResponse(item.id, {
estimated_cost:
event.target.value,
estimated_cost: value,
})
}
/>
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import {
calculateAnnualReferencePlan,
newAnnualReferencePlan,
@@ -43,14 +44,13 @@ function ExampleNumber({
return (
<label className="grid gap-1 text-sm">
{label}
<input
type="number"
<DecimalInput
min="0"
step="0.01"
className="min-w-0 rounded border p-2"
value={value}
aria-invalid={!!error}
onChange={(event) => onChange(event.target.value)}
onValueChange={(value) => onChange(value)}
/>
{error && (
<span role="alert" className="text-red-800">
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import { WarningLimitsEditor } from './warning-limits-editor';
import { SupplierAdvancesEditor } from '@/components/supplier-advances';
import { PeriodInvestmentsEditor } from '@/components/period-investments';
@@ -110,14 +111,13 @@ function MoneyInput({
return (
<label className="block text-sm font-medium">
{label}
<input
type="number"
<DecimalInput
min={allowNegative ? undefined : '0'}
step={step}
value={value}
onChange={(event) => {
onValueChange={(next) => {
setTouched(true);
onChange(event.target.value);
onChange(next);
}}
onBlur={() => setTouched(true)}
aria-invalid={!!error}
@@ -1038,13 +1038,12 @@ export function SimulationBusinessPlan({
<label className="block text-sm font-medium">
Taxa indicativa ({plan.presentationCurrency} por
1 {currency})
<input
type="number"
<DecimalInput
min="0.00000001"
step="0.00000001"
value={plan.fxRate ?? ''}
onChange={(event) =>
update('fxRate', event.target.value)
onValueChange={(value) =>
update('fxRate', value)
}
className="mt-1 w-full rounded border p-2"
aria-required="true"
@@ -1092,14 +1091,13 @@ export function SimulationBusinessPlan({
)}
<label className="block text-sm font-medium">
Horizonte (meses)
<input
type="number"
<DecimalInput
min="1"
max="60"
step="1"
value={String(plan.periods ?? 12)}
onChange={(event) =>
updatePeriods(Number(event.target.value))
onValueChange={(value) =>
/^\d+$/.test(value) && updatePeriods(Number(value))
}
className="mt-1 w-full rounded border p-2"
/>
@@ -1350,26 +1348,23 @@ export function SimulationBusinessPlan({
</label>
<label>
Percentagem
<input
<DecimalInput
className="mt-1 w-full rounded border p-2"
type="number"
min="0"
max="100"
step="0.01"
value={
part.percent
}
onChange={(
event,
onValueChange={(
value,
) =>
updateProductPaymentInstallment(
index,
month,
partIndex,
'percent',
event
.target
.value,
value,
)
}
/>
@@ -1446,17 +1441,16 @@ export function SimulationBusinessPlan({
className="block text-sm"
>
Unidades - mes {month + 1}
<input
type="number"
<DecimalInput
min="0"
step="0.001"
value={units}
onChange={(event) =>
onValueChange={(value) =>
updateProductSchedule(
index,
'monthlyUnitsByPeriod',
month,
event.target.value,
value,
)
}
className="mt-1 w-full rounded border p-2"
@@ -1872,8 +1866,7 @@ export function SimulationBusinessPlan({
/>
<label className="block text-sm font-medium">
Prazo de entrega das compras (meses)
<input
type="number"
<DecimalInput
min="0"
max="12"
step="1"
@@ -1881,10 +1874,11 @@ export function SimulationBusinessPlan({
plan.inventoryPurchaseLeadMonths ??
0,
)}
onChange={(event) =>
onValueChange={(value) =>
/^\d+$/.test(value) &&
update(
'inventoryPurchaseLeadMonths',
Number(event.target.value),
Number(value),
)
}
className="mt-1 w-full rounded border p-2"
@@ -2282,16 +2276,13 @@ export function SimulationBusinessPlan({
/>
<label className="block text-sm">
Vida útil (meses)
<input
type="number"
<DecimalInput
min="1"
max="600"
value={plan.depreciationLifeMonths}
onChange={(event) =>
update(
'depreciationLifeMonths',
Number(event.target.value),
)
onValueChange={(value) =>
/^\d+$/.test(value) &&
update('depreciationLifeMonths', Number(value))
}
className="mt-1 w-full rounded border p-2"
/>
@@ -2370,19 +2361,14 @@ export function SimulationBusinessPlan({
).map(([key, label]) => (
<label key={key} className="block text-sm">
{label}
<input
type="number"
<DecimalInput
min="-100"
step="0.01"
value={
scenarioAdjustments[scenario][key]
}
onChange={(event) =>
updateScenario(
scenario,
key,
event.target.value,
)
onValueChange={(value) =>
updateScenario(scenario, key, value)
}
className="mt-1 w-full rounded border p-2"
/>
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import CurrencySelect from '@/components/currency-select';
import { useEffect, useState } from 'react';
import {
@@ -223,13 +224,12 @@ export function SimulationCashflowPlanner({
{taxMode === 'fixed' ? (
<label className="block max-w-xs text-sm font-medium">
Imposto manual do cenário personalizado por mês
<input
type="number"
<DecimalInput
min="0"
step="0.01"
value={inputs.monthlyTaxAssessed}
onChange={(event) =>
set('monthlyTaxAssessed', event.target.value)
onValueChange={(value) =>
set('monthlyTaxAssessed', value)
}
className="mt-1 w-full rounded border p-2"
/>
@@ -243,19 +243,18 @@ export function SimulationCashflowPlanner({
<label key={index} className="text-sm font-medium">
Imposto manual do cenário personalizado — mês{' '}
{index + 1}
<input
type="number"
<DecimalInput
min="0"
step="0.01"
value={value}
onChange={(event) =>
onValueChange={(value) =>
update({
...inputs,
monthlyTaxSchedule:
inputs.monthlyTaxSchedule.map(
(amount, month) =>
month === index
? event.target.value
? value
: amount,
),
})
@@ -301,8 +300,7 @@ export function SimulationCashflowPlanner({
).map(([key, label]) => (
<label key={key} className="text-sm font-medium">
{label}
<input
type="number"
<DecimalInput
min={key === 'vatRefundExpectedMonth' ? '1' : '0'}
max={
key === 'vatRefundExpectedMonth'
@@ -313,7 +311,7 @@ export function SimulationCashflowPlanner({
key === 'vatRefundExpectedMonth' ? '1' : '0.01'
}
value={inputs[key]}
onChange={(event) => set(key, event.target.value)}
onValueChange={(value) => set(key, value)}
className="mt-1 w-full rounded border p-2"
/>
</label>
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import CurrencySelect from '@/components/currency-select';
import {
fundingDifferences,
@@ -29,12 +30,11 @@ function Field({
return (
<label className="block text-sm font-medium">
{label}
<input
type="number"
<DecimalInput
min="0"
step={step}
value={value}
onChange={(event) => onChange(event.target.value)}
onValueChange={(value) => onChange(value)}
className="mt-1 w-full rounded border p-2"
/>
</label>
+24 -10
View File
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import { focusCorrectionId } from '@/lib/field-corrections';
import FiscalOperationPicker from './fiscal-operation-picker';
import { SimulationIrpcAnnual } from '@/components/simulation-irpc-annual';
@@ -298,7 +299,8 @@ const fieldGuidance: Record<
why: 'As chaves para o sucesso são os poucos factores de que o negócio depende para resultar.',
example:
'Exemplo ilustrativo: qualidade do serviço, boas relações com os clientes, equipa com experiência complementar.',
clarify: 'Indique três a cinco factores, separados por vírgulas ou por linhas.',
clarify:
'Indique três a cinco factores, separados por vírgulas ou por linhas.',
},
project_problem: {
why: 'Uma necessidade concreta ajuda a explicar a razão do projecto.',
@@ -3808,23 +3810,35 @@ export function SimulationForm() {
: undefined
}
/>
) : (
<input
) : (field.type ??
(isArea ? 'number' : 'text')) ===
'number' ? (
<DecimalInput
id={`field-${field.key}`}
type={
field.type ??
(isArea ? 'number' : 'text')
}
min={
field.type === 'number'
? '0'
: undefined
}
step={
field.type === 'number'
? 'any'
className="w-full rounded-lg border border-slate-300 p-3 focus-visible:outline-2 focus-visible:outline-emerald-700"
value={String(draft[field.key] ?? '')}
onValueChange={(value) =>
change(field.key, value)
}
aria-invalid={Boolean(fieldError)}
aria-required={
fieldRequired || undefined
}
aria-describedby={
fieldError
? `error-${field.key}`
: undefined
}
/>
) : (
<input
id={`field-${field.key}`}
type={field.type ?? 'text'}
className="w-full rounded-lg border border-slate-300 p-3 focus-visible:outline-2 focus-visible:outline-emerald-700"
value={String(draft[field.key] ?? '')}
onChange={(e) =>
@@ -1,3 +1,4 @@
import { DecimalInput } from '@/components/decimal-input';
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
import {
calculateStartupAssetRequirements,
@@ -33,13 +34,12 @@ export function StartupAssetRequirements({
const field = (label: string, value: string, save: (s: string) => void) => (
<label className="grid gap-1 text-sm">
{label}
<input
type="number"
<DecimalInput
min="0"
step="0.01"
className="min-w-0 rounded border p-2"
value={value}
onChange={(e) => save(e.target.value)}
onValueChange={(value) => save(value)}
/>
</label>
);
+56
View File
@@ -0,0 +1,56 @@
/**
* Read numbers the way investors in Mozambique write them.
*
* Browser number inputs follow the browser's locale: «25.000» becomes 25 and
* «1500,50» may be refused, so a value silently changes or a field seems not to
* accept input. Here a comma is the decimal mark; dots and spaces between
* groups of three digits are thousands separators. The result keeps the
* stored, locale-free format ("1500.50") used by every calculation.
*
* Returns '' for an empty field and null when the text is not a number.
*/
export function normalizeDecimalInput(raw: string): string | null {
const text = raw.replace(/[\s  ]/g, '');
if (text === '') return '';
const sign = text.startsWith('-') ? '-' : '';
const body = sign ? text.slice(1) : text;
if (!/^[\d.,]+$/.test(body)) return null;
let canonical: string;
if (body.includes(',')) {
if (body.split(',').length > 2) return null;
const [whole, fraction] = body.split(',');
if (whole.includes('.') && !thousands(whole.split('.'))) return null;
canonical =
(whole.replace(/\./g, '') || '0') +
(fraction ? '.' + fraction : '');
} else if (body.includes('.')) {
const groups = body.split('.');
canonical = thousands(groups)
? groups.join('')
: groups.length === 2
? body
: '';
} else canonical = body;
if (!/^\d+(\.\d+)?$/.test(canonical)) return null;
return sign + canonical;
}
/** «25.000» or «1.500.000»: a first group of 1–3 digits (not 0) and groups of three. */
function thousands(groups: string[]): boolean {
return (
groups.length > 1 &&
/^[1-9]\d{0,2}$/.test(groups[0]) &&
groups.slice(1).every((group) => /^\d{3}$/.test(group))
);
}
/** The value as the investor will recognise it: thousands spaced, comma decimal. */
export function presentDecimal(canonical: string): string {
const [whole, fraction] = canonical.replace('-', '').split('.');
const spaced = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
return (
(canonical.startsWith('-') ? '-' : '') +
spaced +
(fraction ? ',' + fraction : '')
);
}
@@ -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,
);