fix: clarify complementary field diagnostics and target exact QA controls

This commit is contained in:
2026-11-21 22:13:16 +02:00
parent 77f621b48d
commit 84018e3f25
27 changed files with 1264 additions and 39 deletions
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import {
correctionFieldHints,
correctionGroupMatches,
fieldLabelMatches,
revealCorrectionTarget,
} from '@/lib/field-corrections';
@@ -101,14 +102,17 @@ export default function PortalCorrections() {
node.textContent?.replace(/\s+/g, ' ').trim() ||
'';
if (!message) continue;
const hints = correctionFieldHints(message);
const hints = correctionFieldHints(
message,
names.map(({ label }) => label),
);
const matches = names.filter(
({ label }) =>
label && hints.some((h) => fieldLabelMatches(label, h)),
);
// Restrict explicit product/parcel/milestone/personnel diagnostics to the matching real group, if present.
const index =
/(?:produto|parcela|marco|função|necessidade)\s+(\d+)/i.exec(
/(?:produto|parcela|marco|função|necessidade|segmento)\s+(\d+)/i.exec(
message,
);
const indexed = index
@@ -120,10 +124,7 @@ export default function PortalCorrections() {
group?.getAttribute('aria-label') ||
group?.querySelector('legend')?.textContent ||
'';
return new RegExp(
`(?:produto|parcela|marco|função|necessidade)\\s+${index[1]}\\b`,
'i',
).test(name);
return correctionGroupMatches(message, name);
})
: [];
add(
+102 -30
View File
@@ -55,6 +55,34 @@ const integer = (s: string | undefined, min: number, max: number) => {
throw Error(`Indique um inteiro entre ${min} e ${max}.`);
return Number(s);
};
// Decorate existing parsers without changing accepted values or arithmetic.
const fieldAmount = (value: string | undefined, field: string) => {
try {
return amount(value);
} catch {
throw Error(
`«${field}»: ${businessPlanNumberError(value ?? '') || 'Introduza um montante não negativo com até duas casas decimais (ex.: 25000.00).'}`,
);
}
};
const fieldInteger = (
value: string | undefined,
field: string,
min: number,
max: number,
) => {
try {
return integer(value, min, max);
} catch {
throw Error(
`«${field}»: ${businessPlanNumberError(value ?? '') || `Introduza um número inteiro entre ${min} e ${max}.`}`,
);
}
};
const requireField = (value: string | undefined, field: string) => {
if (!value?.trim())
throw Error(`«${field}»: Preencha este campo para continuar.`);
};
const date = (s: string) =>
/^\d{4}-\d{2}-\d{2}$/.test(s) &&
Number.isFinite(Date.parse(s)) &&
@@ -130,10 +158,17 @@ export function buildComplementaryTables(
throw Error(
'Indique segmentos, clientes potenciais, crescimento e fonte ou hipótese para completar a análise; os dados guardados não serão substituídos automaticamente.',
);
const year = integer(m.baseYear, 1900, 9999),
years = integer(m.years, 2, 10);
const year = fieldInteger(
m.baseYear,
'Ano-base de mercado',
1900,
9999,
),
years = fieldInteger(m.years, 'Horizonte de mercado (anos)', 2, 10);
if (year + years - 1 > 9999)
throw Error('O horizonte de mercado excede o ano 9999.');
throw Error(
'«Horizonte de mercado (anos)»: Reduza o horizonte ou o ano-base para não exceder o ano 9999.',
);
market.headers.push(
...Array.from({ length: years }, (_, i) => String(year + i)),
'Crescimento anual composto',
@@ -141,9 +176,14 @@ export function buildComplementaryTables(
const totals = Array(years).fill(0) as number[];
for (const [i, s] of m.segments.entries()) {
try {
if (!s.label?.trim() || !s.basis?.trim())
throw Error('Indique nome e fonte ou hipótese.');
let clients = integer(s.customers, 0, Number.MAX_SAFE_INTEGER);
requireField(s.label, 'Nome do segmento');
requireField(s.basis, 'Fonte e data, ou hipótese ilustrativa');
let clients = fieldInteger(
s.customers,
'Clientes potenciais no ano-base',
0,
Number.MAX_SAFE_INTEGER,
);
if (
typeof s.growthPercent !== 'string' ||
!/^-?\d+(?:\.\d{1,4})?$/.test(s.growthPercent) ||
@@ -151,7 +191,7 @@ export function buildComplementaryTables(
Number(s.growthPercent) < -100
)
throw Error(
'Indique crescimento igual ou superior a −100%.',
`«Crescimento anual do segmento (%)»: ${businessPlanNumberError(s.growthPercent ?? '', { allowNegative: true }) || 'Introduza uma percentagem igual ou superior a −100%, com até quatro casas decimais.'}`,
);
const growth = Number(s.growthPercent),
series = [clients];
@@ -251,33 +291,44 @@ export function buildComplementaryTables(
let planned = unknown,
realised = unknown;
try {
budget += amount(r.planned_amount);
budget += fieldAmount(r.planned_amount, 'Montante planeado');
planned = reportMoney(amount(r.planned_amount));
} catch {
} catch (e) {
budgetComplete = false;
milestones.issues.push(
`Marco ${i + 1}: orçamento em falta ou inválido.`,
`Marcos / Marco ${i + 1}: ${(e as Error).message}`,
);
}
if (r.actual_amount !== '') {
try {
actual += amount(r.actual_amount);
actual += fieldAmount(r.actual_amount, 'Montante realizado');
realised = reportMoney(amount(r.actual_amount));
} catch {
} catch (e) {
actualComplete = false;
milestones.issues.push(`Marco ${i + 1}: realizado inválido.`);
milestones.issues.push(
`Marcos / Marco ${i + 1}: ${(e as Error).message}`,
);
}
} else actualComplete = false;
if (
!r.title.trim() ||
!r.responsible?.trim() ||
!r.department?.trim() ||
!date(r.start_date ?? '') ||
!date(r.due_date)
)
milestones.issues.push(
`Marco ${i + 1}: complete título, responsável, departamento e datas de início/término válidas.`,
);
for (const [value, label] of [
[r.title, 'Marco ou resultado'],
[r.responsible, 'Responsável pelo marco'],
[r.department, 'Departamento do marco'],
]) {
if (!value?.trim())
milestones.issues.push(
`Marcos / Marco ${i + 1} / «${label}»: Preencha este campo para continuar.`,
);
}
for (const [value, label] of [
[r.start_date, 'Data de início'],
[r.due_date, 'Prazo previsto'],
]) {
if (!date(value ?? ''))
milestones.issues.push(
`Marcos / Marco ${i + 1} / «${label}»: ${!value ? 'Preencha este campo para continuar.' : 'Introduza uma data válida.'}`,
);
}
if (
date(r.start_date ?? '') &&
date(r.due_date) &&
@@ -360,8 +411,8 @@ export function buildComplementaryTables(
);
for (const [i, r] of team.entries()) {
try {
if (!r.competency.trim() || !r.department?.trim())
throw Error('Indique função e departamento.');
requireField(r.competency, 'Competência ou função');
requireField(r.department, 'Departamento (mapa de pessoal)');
const quantityError = businessPlanNumberError(r.quantity ?? '', {
integer: true,
});
@@ -369,11 +420,32 @@ export function buildComplementaryTables(
throw Error(
`«Quantidade de pessoas (inteiro)»: ${quantityError}`,
);
const count = integer(r.quantity, 0, 1000000),
salary = amount(r.monthly_salary),
start = integer(r.start_month, 1, periods),
end = integer(r.end_month, 1, periods);
if (start > end) throw Error('O mês final precede o mês inicial.');
const count = fieldInteger(
r.quantity,
'Quantidade de pessoas (inteiro)',
0,
1000000,
),
salary = fieldAmount(
r.monthly_salary,
'Remuneração mensal por pessoa (moeda do projecto)',
),
start = fieldInteger(
r.start_month,
'Mês inicial no plano (1 = Janeiro do ano inicial)',
1,
periods,
),
end = fieldInteger(
r.end_month,
'Mês final no plano',
1,
periods,
);
if (start > end)
throw Error(
'«Mês final no plano»: O mês final não pode ser anterior ao mês inicial. Corrija o mês final ou o mês inicial.',
);
headcount += count;
const values = totals.map((_, j) =>
j + 1 >= start && j + 1 <= end ? salary * BigInt(count) : 0n,
+28 -1
View File
@@ -112,9 +112,18 @@ const routes: [RegExp, string[]][] = [
['Importar plano financeiro InvestMoz (.json, até 60 KB)'],
],
];
export function correctionFieldHints(message: string): string[] {
export function correctionFieldHints(
message: string,
availableLabels?: string[],
): string[] {
const normal = normaliseFieldLabel(message);
const quoted = [...message.matchAll(/«([^»]+)»/g)].map((m) => m[1]);
const exact = quoted.filter((h) =>
availableLabels?.some(
(label) => normaliseFieldLabel(label) === normaliseFieldLabel(h),
),
);
if (exact.length) return exact;
const mapped = routes
.filter(([pattern]) => pattern.test(normal))
.flatMap(([, labels]) => labels);
@@ -137,6 +146,24 @@ export function fieldLabelMatches(label: string, hint: string): boolean {
(b.length >= 7 && (a.startsWith(b + ' ') || b.startsWith(a + ' '))))
);
}
/** Match repeated groups by kind as well as index; personnel uses Necessidade in the editor. */
export function correctionGroupMatches(
message: string,
groupName: string,
): boolean {
const match =
/\b(produto|parcela|marco|funcao|necessidade|segmento)\s+(\d+)\b/.exec(
normaliseFieldLabel(message),
);
if (!match) return true;
const kind =
match[1] === 'funcao' || match[1] === 'necessidade'
? '(?:funcao|necessidade)'
: match[1];
return new RegExp(`\\b${kind}\\s+${match[2]}\\b`).test(
normaliseFieldLabel(groupName),
);
}
export function revealCorrectionTarget(target: HTMLElement): void {
const control = target.matches(
'input,select,textarea,button,[contenteditable="true"]',