fix: validate simulator dates and reconcile QA calculations reports and language

This commit is contained in:
2026-10-20 21:00:52 +02:00
parent 59ab4fe956
commit a690c665fb
39 changed files with 757 additions and 184 deletions
+20 -1
View File
@@ -398,6 +398,15 @@ export async function generateProjectDossierDocx(
];
for (const section of model.sections) {
if (section.id === 'annexes') {
if (!attachments.some((item) => item.include)) {
children.push(
new Paragraph({
text: 'Anexos: não foram seleccionados ficheiros.',
spacing: { before: 80, after: 80 },
}),
);
continue;
}
children.push(
new Paragraph({
text: section.title,
@@ -447,7 +456,10 @@ export async function generateProjectDossierDocx(
alignment: AlignmentType.RIGHT,
children: [
new TextRun({
text: 'InvesteMoz · '+model.title.slice(0, 60)+' · privado · página ',
text:
'InvesteMoz · ' +
model.title.slice(0, 60) +
' · privado · página ',
size: 18,
}),
new SimpleField('PAGE'),
@@ -580,6 +592,13 @@ export async function createProjectDossierPrintHtml(
): Promise<string> {
const content: string[] = [];
for (const section of model.sections) {
if (
section.id === 'annexes' &&
!attachments.some((item) => item.include)
) {
content.push('<p>Anexos: não foram seleccionados ficheiros.</p>');
continue;
}
content.push(`<section><h2>${escapeHtml(section.title)}</h2>`);
for (const paragraph of section.paragraphs)
content.push(`<p>${escapeHtml(paragraph)}</p>`);
+71 -12
View File
@@ -111,29 +111,57 @@ function classification(origin: string): string {
return 'Referência/estado indicado';
}
export function formatDossierReportValue(field: string, value: string, currency = ''): string {
export function formatDossierReportValue(
field: string,
value: string,
currency = '',
): string {
if (field === 'Estado do plano detalhado') {
return value.replace('Snapshot versionado disponível; usar também a exportação do plano financeiro', 'Plano guardado disponível; consulte também a exportação financeira');
return value.replace(
'Snapshot versionado disponível; usar também a exportação do plano financeiro',
'Plano guardado disponível; consulte também a exportação financeira',
);
}
if (field === 'Reconciliação do financiamento') {
const states: Record<string, string> = { shortfall: 'Financiamento insuficiente', surplus: 'Fontes superiores aos usos previstos', balanced: 'Fontes e usos equilibrados', unknown: 'Informação insuficiente', incomplete: 'Informação insuficiente' };
const states: Record<string, string> = {
shortfall: 'Financiamento insuficiente',
surplus: 'Fontes superiores aos usos previstos',
balanced: 'Fontes e usos equilibrados',
unknown: 'Informação insuficiente',
incomplete: 'Informação insuficiente',
};
return states[value] ?? value;
}
if (/^Necessidade \d+$/.test(field)) {
value = value.replace('; gap;', '; Competência em falta;').replace('; unknown;', '; Por confirmar;').replace('; available;', '; Disponível (declarado);');
value = value
.replace('; gap;', '; Competência em falta;')
.replace('; unknown;', '; Por confirmar;')
.replace('; available;', '; Disponível (declarado);');
}
if (/^Marco \d+$/.test(field)) {
value = value.replace('; planned;', '; Planeado;').replace('; in_progress;', '; Em curso;').replace('; completed;', '; Concluído (declarado);');
value = value
.replace('; planned;', '; Planeado;')
.replace('; in_progress;', '; Em curso;')
.replace('; completed;', '; Concluído (declarado);');
}
if (/^(Necessidade|Marco) \d+$/.test(field)) {
value = value.replace(/(custo|planeado|realizado): ([^;]*)(?=;|$)/g, (_, label: string, amount: string) => {
const raw = amount.trim();
return `${label}: ${raw ? (/^\d+(?:\.\d{1,2})?$/.test(raw) ? `${raw} ${currency || '(moeda não informada)'}` : raw) : 'Não informado'}`;
}).replace(/prazo: (?=;|$)/g, 'prazo: Não informado');
value = value
.replace(
/(custo|planeado|realizado): ([^;]*)(?=;|$)/g,
(_, label: string, amount: string) => {
const raw = amount.trim();
return `${label}: ${raw ? (/^\d+(?:\.\d{1,2})?$/.test(raw) ? `${raw} ${currency || '(moeda não informada)'}` : raw) : 'Não informado'}`;
},
)
.replace(/prazo: (?=;|$)/g, 'prazo: Não informado');
}
// Presentation only: group the decimal string without converting the amount
// to a JavaScript float or changing the saved financial snapshot.
return value.replace(/^(-?)(\d+)\.(\d{2}) ([A-Z]{3})$/, (_, sign: string, whole: string, cents: string, currency: string) => `${sign}${whole.replace(/\B(?=(\d{3})+(?!\d))/g, ' ')},${cents} ${currency}`);
return value.replace(
/^(-?)(\d+)\.(\d{2}) ([A-Z]{3})$/,
(_, sign: string, whole: string, cents: string, currency: string) =>
`${sign}${whole.replace(/\B(?=(\d{3})+(?!\d))/g, ' ')},${cents} ${currency}`,
);
}
const rowSection: Record<string, DossierReportSectionId> = {
Projecto: 'project',
@@ -214,6 +242,32 @@ function makeSections(
classification: 'Referência da revisão',
},
);
const highlights = new Set([
'Saldo operacional estimado',
'Diferença por financiar',
'Prestação do primeiro período',
]);
const budgetPeriod = rows.find(
(row) => row[1] === 'Periodicidade do orçamento',
)?.[2];
for (const [, field, value, origin] of rows.slice(1)) {
if (!highlights.has(field)) continue;
summary.rows.push({
field:
field === 'Saldo operacional estimado' && budgetPeriod
? `${field} — ${budgetPeriod}`
: field,
value: absent(
formatDossierReportValue(
field,
value,
text(draft, 'currency'),
),
),
origin,
classification: classification(origin),
});
}
}
for (const [sectionName, field, value, origin] of rows.slice(1)) {
@@ -226,9 +280,14 @@ function makeSections(
if (!section) continue;
section.rows.push({
field,
value: absent(formatDossierReportValue(field, value, text(draft, 'currency'))),
value: absent(
formatDossierReportValue(field, value, text(draft, 'currency')),
),
origin,
classification: value.trim() === '' ? 'Informação em falta' : classification(origin),
classification:
value.trim() === ''
? 'Informação em falta'
: classification(origin),
});
}
+13
View File
@@ -1544,6 +1544,10 @@ export function validateSimulationDraft(
draft: SimulationDraft,
sectionId: string,
): Record<string, string> {
// The separate arithmetic validator checks its three inputs. Fiscal
// eligibility facts are not inputs of this planning-only calculation.
if (sectionId === 'tax' && draft.fiscal_scenario_mode === 'custom_planning')
return {};
const errors: Record<string, string> = {};
for (const field of simulationFieldGroups[sectionId] ?? []) {
if (field.showWhen && !field.showWhen(draft)) continue;
@@ -1594,6 +1598,15 @@ export function validateSimulationDraft(
errors[field.key] =
'Introduza um endereço de correio electrónico válido.';
}
if (
sectionId === 'tax' &&
draft.fiscal_scenario_mode === 'approved_parameters' &&
draft.fiscal_periodicity === 'one_off' &&
!getFiscalPeriodRange(draft)
) {
errors.fiscal_reference_date =
'Introduza uma data válida da operação no ano fiscal seleccionado. Não foi usada uma data alternativa.';
}
if (
sectionId === 'financial' &&
[