fix: complete V09 financial diagnostic coverage in isolated QA

This commit is contained in:
2026-11-21 23:15:58 +02:00
parent 84018e3f25
commit 1349952d0f
36 changed files with 1245 additions and 29 deletions
+10 -5
View File
@@ -3,6 +3,7 @@ import {
correctionFieldHints,
correctionGroupMatches,
fieldLabelMatches,
normaliseFieldLabel,
revealCorrectionTarget,
} from '@/lib/field-corrections';
@@ -88,6 +89,10 @@ export default function PortalCorrections() {
[target(control, label || 'Campo indicado')],
);
}
const availableLabels = names.map(({ label }) => label);
const exactLabels = new Set(
availableLabels.map(normaliseFieldLabel),
);
for (const node of root.querySelectorAll<HTMLElement>(
'[data-correction-message],[role="alert"]',
)) {
@@ -102,13 +107,13 @@ export default function PortalCorrections() {
node.textContent?.replace(/\s+/g, ' ').trim() ||
'';
if (!message) continue;
const hints = correctionFieldHints(
message,
names.map(({ label }) => label),
);
const hints = correctionFieldHints(message, availableLabels);
const matches = names.filter(
({ label }) =>
label && hints.some((h) => fieldLabelMatches(label, h)),
label &&
hints.some((h) =>
fieldLabelMatches(label, h, exactLabels),
),
);
// Restrict explicit product/parcel/milestone/personnel diagnostics to the matching real group, if present.
const index =
+30 -8
View File
@@ -1040,7 +1040,7 @@ function cents(value: string, label: string, signed = false): bigint {
).exec(value.trim());
if (!match || value.length > 40)
throw new Error(
`${label}: use um montante${signed ? '' : ' não negativo'} com até duas casas decimais.`,
`${label}: ${businessPlanNumberError(value, { allowNegative: signed }) || `Introduza um montante${signed ? '' : ' não negativo'} com até duas casas decimais.`}`,
);
const sign = match[1].startsWith('-') ? -1n : 1n;
return (
@@ -1054,7 +1054,7 @@ function quantity(value: string): bigint {
const match = /^(\d+)(?:\.(\d{1,3}))?$/.exec(value.trim());
if (!match || value.length > 40)
throw new Error(
'Quantidade: use um valor não negativo com até três casas decimais.',
`Quantidade: ${businessPlanNumberError(value) || 'Introduza um valor não negativo com até três casas decimais.'}`,
);
return (
BigInt(match[1]) * 1000n +
@@ -1195,7 +1195,7 @@ function percentMicro(value: string, label: string): bigint {
const match = /^(-?\d+)(?:\.(\d{1,6}))?$/.exec(value.trim());
if (!match || value.length > 40)
throw new Error(
`${label}: indique uma percentagem com até seis casas.`,
`${label}: ${businessPlanNumberError(value, { allowNegative: true }) || 'Introduza uma percentagem com até seis casas.'}`,
);
const sign = match[1].startsWith('-') ? -1n : 1n;
return (
@@ -1558,6 +1558,26 @@ type ActiveDayTerms = ReturnType<typeof buildDayTermSchedule> & {
};
export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
try {
return forecastBusinessPlanChecked(input);
} catch (error) {
if (
error instanceof Error &&
[
'Movimentos por período — Ano inicial: preencha o ano do relatório entre 1900 e 9993.',
'Prazos em dias — Ano inicial: indique o ano do relatório entre 1900 e 9993.',
'Adiantamentos: preencha o ano inicial do relatório entre 1900 e 9993.',
].includes(error.message)
) {
throw new Error(
`«Ano inicial»: ${businessPlanNumberError(input.reportAssumptions?.startYear ?? '') || 'Indique o ano do relatório entre 1900 e 9993.'}`,
);
}
throw error;
}
}
function forecastBusinessPlanChecked(input: BusinessFinancialPlanInput) {
const config = input.dayTerms;
const advances = input.supplierAdvances;
if (
@@ -1768,7 +1788,9 @@ function forecastBusinessPlanBase(
'Percentagem de cobrança',
);
if (salesCollectionRate < 0n || salesCollectionRate > 100_000_000n)
throw new Error('A percentagem de cobrança deve estar entre 0 e 100.');
throw new Error(
'Percentagem de cobrança: Introduza uma percentagem entre 0% e 100%.',
);
const openingReceivablesCollectionMonth =
input.openingReceivablesCollectionMonth ?? null;
if (
@@ -1791,7 +1813,7 @@ function forecastBusinessPlanBase(
openingReceivablesCollectionRate > 100_000_000n
)
throw new Error(
'A percentagem de cobrança dos valores a receber deve estar entre 0 e 100.',
'Percentagem de cobrança dos valores a receber: Introduza uma percentagem entre 0% e 100%.',
);
const openingReceivablesInstallments =
input.openingReceivablesInstallments ?? [];
@@ -1820,7 +1842,7 @@ function forecastBusinessPlanBase(
);
if (rate < 0n || rate > 100_000_000n)
throw new Error(
'A percentagem de cada parcela deve estar entre 0 e 100.',
'Percentagem de cada parcela: Introduza uma percentagem entre 0% e 100%.',
);
openingReceivablesScheduledRate += rate;
return rate;
@@ -1854,7 +1876,7 @@ function forecastBusinessPlanBase(
);
if (rate < 0n || rate > 100_000_000n)
throw new Error(
'A percentagem de cada liquidação deve estar entre 0 e 100.',
'Percentagem de cada liquidação: Introduza uma percentagem entre 0% e 100%.',
);
openingPayablesScheduledRate += rate;
return rate;
@@ -1893,7 +1915,7 @@ function forecastBusinessPlanBase(
);
if (rate < 0n || rate > 100_000_000n)
throw new Error(
'A percentagem de recuperação deve estar entre 0 e 100.',
'Percentagem de recuperação: Introduza uma percentagem entre 0% e 100%.',
);
salesRecoveryRates.set(entry.month, rate);
});
+11 -1
View File
@@ -136,9 +136,19 @@ export function correctionFieldHints(
]),
];
}
export function fieldLabelMatches(label: string, hint: string): boolean {
export function fieldLabelMatches(
label: string,
hint: string,
availableLabels?: string[] | Set<string>,
): boolean {
const a = normaliseFieldLabel(label),
b = normaliseFieldLabel(hint);
if (
availableLabels instanceof Set
? availableLabels.has(b)
: availableLabels?.some((value) => normaliseFieldLabel(value) === b)
)
return a === b;
return (
!!a &&
!!b &&
+39 -12
View File
@@ -1,6 +1,7 @@
import {
forecastBusinessPlan,
monthlyProjectedSales,
businessPlanNumberError,
type BusinessFinancialPlanInput,
} from './business-financial-plan.ts';
import { calculateStartupAssetRequirements } from './startup-asset-requirements.ts';
@@ -50,6 +51,16 @@ const cents = (value: string): bigint => {
const amount = BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0'));
return negative ? -amount : amount;
};
/** Diagnostic wrapper only: preserve the report's signed parser and precision. */
const fieldCents = (value: string, field: string): bigint => {
try {
return cents(value);
} catch {
throw new Error(
`«${field}»: ${businessPlanNumberError(value, { allowNegative: true }) || 'Introduza um montante com até duas casas decimais.'}`,
);
}
};
export const reportMoney = (amount: bigint): string => {
const abs = amount < 0n ? -amount : amount;
return `${amount < 0n ? '-' : ''}${abs / 100n}.${String(abs % 100n).padStart(2, '0')}`;
@@ -151,21 +162,30 @@ export function buildIntegralFinancialTables(
Number(a.startYear) < 1900 ||
Number(a.startYear) > 9999
)
throw new Error('Indique o ano inicial do relatório (1900–9999).');
throw new Error(
`«Ano inicial»: ${businessPlanNumberError(a.startYear) || 'Indique o ano inicial do relatório (1900–9999).'}`,
);
const needs = plan.startupAssetRequirements
? calculateStartupAssetRequirements(plan)
: undefined;
const openingFixed = cents(a.openingFixedAssets),
const openingFixed = fieldCents(
a.openingFixedAssets,
'Activos fixos anteriores (valor líquido)',
),
otherAssets =
cents(a.openingOtherAssets) + (needs?.currentAcquisition ?? 0n),
openingEquity = cents(a.openingEquity);
fieldCents(a.openingOtherAssets, 'Outros activos anteriores') +
(needs?.currentAcquisition ?? 0n),
openingEquity = fieldCents(
a.openingEquity,
'Capital e resultados anteriores',
);
if (
[openingFixed, otherAssets, openingEquity].some(
(value) => value < 0n,
)
)
throw new Error(
'Os saldos iniciais complementares não podem ser negativos.',
`Saldos de abertura / «${openingFixed < 0n ? 'Activos fixos anteriores (valor líquido)' : otherAssets < 0n ? 'Outros activos anteriores' : 'Capital e resultados anteriores'}»: Este valor não pode ser negativo.`,
);
if (
!Array.isArray(a.startupExpenses) ||
@@ -175,16 +195,23 @@ export function buildIntegralFinancialTables(
throw new Error(
'Declare as despesas de arranque, incluindo uma linha de zero quando não existirem.',
);
const startup = a.startupExpenses.reduce((total, row) => {
const startup = a.startupExpenses.reduce((total, row, index) => {
if (
!row.label.trim() ||
row.label.length > 160 ||
cents(row.amount) < 0n
fieldCents(row.amount, `Montante de arranque ${index + 1}`) < 0n
)
throw new Error(
'Cada despesa de arranque exige designação e montante não negativo.',
!row.label.trim()
? `«Despesa ${index + 1}»: Preencha este campo para continuar.`
: row.label.length > 160
? `«Despesa ${index + 1}»: Reduza a designação para até 160 caracteres.`
: `«Montante de arranque ${index + 1}»: Este valor não pode ser negativo.`,
);
return total + cents(row.amount);
return (
total +
fieldCents(row.amount, `Montante de arranque ${index + 1}`)
);
}, 0n);
const count = result.rows.length;
const schedule = (values: string[], field: string) => {
@@ -198,12 +225,12 @@ export function buildIntegralFinancialTables(
amount = cents(value);
} catch {
throw new Error(
`Impostos por mês — ${field}, mês ${month + 1}: preencha este campo com um montante até duas casas decimais; indique zero apenas quando aplicável.`,
`Impostos por mês / «${field} — mês ${month + 1}»: ${businessPlanNumberError(value, { allowNegative: true }) || 'Introduza um montante com até duas casas decimais.'} Indique zero apenas quando aplicável.`,
);
}
if (amount < 0n)
throw new Error(
`Impostos por mês — ${field}, mês ${month + 1}: o montante não pode ser negativo. Corrija este campo.`,
`Impostos por mês / «${field} — mês ${month + 1}»: Este valor não pode ser negativo. Corrija este campo.`,
);
return amount;
});
@@ -218,7 +245,7 @@ export function buildIntegralFinancialTables(
);
if (!a.taxSource.trim())
throw new Error(
'Indique a fonte ou o pressuposto fiscal, incluindo quando não prevê imposto.',
'«Fonte ou pressuposto dos impostos estimados»: Preencha este campo para continuar. Identifique a fonte ou o pressuposto fiscal, incluindo quando não prevê imposto.',
);
if (
cents(plan.grants) > 0n &&