Simulador: números validados à entrada, latitude negativa aceite e rascunho guardado com o resto

Cada número do simulador é verificado enquanto se escreve, com os mesmos
limites que o servidor aplica ao guardar (percentagens 0–100, empregos e
prazos inteiros, coordenadas). A validação anterior recusava qualquer número
negativo, incluindo as latitudes de Moçambique (−10 a −27), e o investidor
não conseguia indicar a localização.

Um número que o servidor recusaria fica neste navegador até ser corrigido e
deixa de seguir no rascunho do servidor, para que os outros campos continuem
a ser guardados; o campo explica-o. «Continuar» continua bloqueado enquanto
houver erros no passo.

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:19:39 +02:00
committed by nala
parent 4745331ebd
commit e95cdde5d9
3 changed files with 178 additions and 17 deletions
+19 -1
View File
@@ -53,6 +53,8 @@ import {
simulationFieldAvailableAtDetailLevel, simulationFieldAvailableAtDetailLevel,
simulationOptions, simulationOptions,
validateSimulationDraft, validateSimulationDraft,
draftNumberError,
isDraftNumberKey,
validateCustomFiscalPlanning, validateCustomFiscalPlanning,
getFiscalPeriodRange, getFiscalPeriodRange,
projectQuestionnaireVersion, projectQuestionnaireVersion,
@@ -2094,9 +2096,14 @@ export function SimulationForm() {
} }
return next; return next;
}); });
// Numbers are checked as they are typed, with the server's own limits.
const numberError = isDraftNumberKey(key)
? draftNumberError(key, value)
: null;
setErrors((current) => { setErrors((current) => {
const next = { ...current }; const next = { ...current };
delete next[key]; if (numberError) next[key] = numberError;
else delete next[key];
return next; return next;
}); });
if (['purpose', 'journey_type', 'detail_level'].includes(key)) if (['purpose', 'journey_type', 'detail_level'].includes(key))
@@ -3864,6 +3871,17 @@ export function SimulationForm() {
{fieldError} {fieldError}
</p> </p>
)} )}
{isDraftNumberKey(field.key) &&
draftNumberError(
field.key,
draft[field.key],
) && (
<p className="mt-1 text-sm text-slate-600">
Os outros campos continuam a ser
guardados; este valor só é guardado
depois de corrigido.
</p>
)}
{ivaNotes} {ivaNotes}
{field.key === 'reduction' && ( {field.key === 'reduction' && (
<p className="mt-1 text-sm text-slate-600"> <p className="mt-1 text-sm text-slate-600">
+103 -16
View File
@@ -1670,7 +1670,11 @@ export function partitionSimulationDraft(
const economic_snapshot: Record<string, unknown> = {}; const economic_snapshot: Record<string, unknown> = {};
const personal_labels: Record<string, string | string[]> = {}; const personal_labels: Record<string, string | string[]> = {};
const economic_labels: Record<string, string | string[]> = {}; const economic_labels: Record<string, string | string[]> = {};
// A number the server would refuse stays in this browser until corrected;
// leaving it out lets every other field of the draft be saved.
const refused = new Set(invalidDraftNumberKeys(draft));
for (const [key, value] of Object.entries(draft)) { for (const [key, value] of Object.entries(draft)) {
if (refused.has(key)) continue;
if ( if (
!includePersonal && !includePersonal &&
privateDraftKeys.has(key.replace(/_label$/, '')) privateDraftKeys.has(key.replace(/_label$/, ''))
@@ -1744,6 +1748,102 @@ export function simulationDraftFingerprint(draft: SimulationDraft): string {
return JSON.stringify(sort(partitionSimulationDraft(draft))); return JSON.stringify(sort(partitionSimulationDraft(draft)));
} }
const draftNumberRanges: Record<
string,
{ min?: number; max?: number; integer?: boolean; message: string }
> = {
rate: {
min: 0,
max: 100,
message: 'Introduza uma percentagem entre 0 e 100.',
},
reduction: {
min: 0,
max: 100,
message: 'Introduza uma percentagem entre 0 e 100.',
},
local_content_percentage: {
min: 0,
max: 100,
message: 'Introduza uma percentagem entre 0 e 100.',
},
// Mozambique lies south of the equator: its latitudes are negative.
latitude: {
min: -90,
max: 90,
message:
'Introduza uma latitude entre -90 e 90 (em Moçambique, negativa).',
},
longitude: {
min: -180,
max: 180,
message: 'Introduza uma longitude entre -180 e 180.',
},
fiscal_establishments: {
min: 1,
integer: true,
message: 'Introduza um número inteiro igual ou superior a 1.',
},
...Object.fromEntries(
[
'direct_jobs',
'indirect_jobs',
'national_jobs',
'foreign_jobs',
'financing_term_months',
'project_duration_years',
].map((key) => [
key,
{
min: 0,
integer: true,
message:
'Introduza um número inteiro igual ou superior a zero.',
},
]),
),
};
/**
* The same limits the server applies when it saves the draft, so the investor
* sees the problem while typing and the rest of the draft is still saved.
*/
export function draftNumberError(key: string, value: unknown): string | null {
if (value === undefined || value === null || value === '') return null;
const range = draftNumberRanges[key] ?? {
min: 0,
message: 'Introduza um número igual ou superior a zero.',
};
const text = String(value).trim();
const number = Number(text);
if (text === '' || !Number.isFinite(number)) return range.message;
if (range.integer && !Number.isInteger(number)) return range.message;
if (range.min !== undefined && number < range.min) return range.message;
if (range.max !== undefined && number > range.max) return range.message;
return null;
}
let draftNumberKeys: Set<string> | undefined;
/** Whether the simulator field is a number the server checks. */
export function isDraftNumberKey(key: string): boolean {
draftNumberKeys ??= new Set(
Object.values(simulationFieldGroups)
.flat()
.filter((field) => field.type === 'number')
.map((field) => field.key),
);
return draftNumberKeys.has(key);
}
/** Number fields whose current text the server would refuse. */
export function invalidDraftNumberKeys(draft: SimulationDraft): string[] {
return Object.keys(draft).filter(
(key) =>
isDraftNumberKey(key) && draftNumberError(key, draft[key]) !== null,
);
}
export function validateSimulationDraft( export function validateSimulationDraft(
draft: SimulationDraft, draft: SimulationDraft,
sectionId: string, sectionId: string,
@@ -1782,22 +1882,9 @@ export function validateSimulationDraft(
) { ) {
errors[field.key] = 'Este campo é obrigatório.'; errors[field.key] = 'Este campo é obrigatório.';
} }
if (field.type === 'number' && value !== undefined && value !== '') { const numberError =
const number = Number(value); field.type === 'number' ? draftNumberError(field.key, value) : null;
if (!Number.isFinite(number) || number < 0) if (numberError) errors[field.key] = numberError;
errors[field.key] =
'Introduza um número igual ou superior a zero.';
}
if (
['rate', 'reduction', 'local_content_percentage'].includes(
field.key,
) &&
value !== undefined &&
value !== ''
) {
if (Number(value) > 100)
errors[field.key] = 'O valor não pode exceder 100.';
}
if ( if (
field.key === 'email' && field.key === 'email' &&
typeof value === 'string' && typeof value === 'string' &&
+56
View File
@@ -17,6 +17,8 @@ import {
readVersionedArithmeticReportReference, readVersionedArithmeticReportReference,
moveSearchChoiceIndex, moveSearchChoiceIndex,
getFiscalPeriodRange, getFiscalPeriodRange,
draftNumberError,
invalidDraftNumberKeys,
} from '../../resources/js/lib/simulation-form.ts'; } from '../../resources/js/lib/simulation-form.ts';
void test('an invalid fiscal operation date has a field error and no substitute period', () => { void test('an invalid fiscal operation date has a field error and no substitute period', () => {
@@ -928,3 +930,57 @@ void test('arithmetic result CSV neutralizes formula-like report metadata', () =
/ID da execução,"'=HYPERLINK\(""https:\/\/example\.invalid""\)"/, /ID da execução,"'=HYPERLINK\(""https:\/\/example\.invalid""\)"/,
); );
}); });
void test('numbers are checked with the server limits while typing; a Mozambican latitude is accepted (tarefa 19)', () => {
assert.equal(draftNumberError('latitude', '-25.9692'), null);
assert.equal(draftNumberError('longitude', '32.5732'), null);
assert.match(draftNumberError('latitude', '-95'), /entre -90 e 90/);
assert.match(
draftNumberError('total_investment', 'abc'),
/igual ou superior a zero/,
);
assert.match(
draftNumberError('total_investment', '-1'),
/igual ou superior a zero/,
);
assert.equal(draftNumberError('total_investment', '25000'), null);
assert.match(draftNumberError('direct_jobs', '1.5'), /inteiro/);
assert.equal(draftNumberError('direct_jobs', '12'), null);
assert.match(
draftNumberError('fiscal_establishments', '0'),
/igual ou superior a 1/,
);
assert.match(draftNumberError('rate', '101'), /entre 0 e 100/);
assert.equal(
draftNumberError('total_investment', ''),
null,
'empty is not a number error',
);
assert.deepEqual(
validateSimulationDraft(
{ site_known: 'yes', latitude: '-25.9692', longitude: '32.5732' },
'location',
).latitude,
undefined,
);
});
void test('a refused number stays in the browser while the rest of the draft is saved (tarefa 19)', () => {
const draft = {
journey_type: 'investor',
project_title: 'Criar Hotel',
total_investment: 'abc',
own_capital: '25000',
direct_jobs: '1.5',
};
assert.deepEqual(invalidDraftNumberKeys(draft).sort(), [
'direct_jobs',
'total_investment',
]);
const { economic_snapshot } = partitionSimulationDraft(draft);
assert.equal('total_investment' in economic_snapshot, false);
assert.equal('direct_jobs' in economic_snapshot, false);
assert.equal(economic_snapshot.own_capital, '25000');
assert.equal(economic_snapshot.project_title, 'Criar Hotel');
assert.equal(getAutosaveSnapshot(draft).total_investment, 'abc');
});