fix(qa): reconcile report summary and separate Word period tables

This commit is contained in:
2026-11-20 12:14:08 +02:00
parent d367e18eec
commit 722322f9f6
6 changed files with 157 additions and 4 deletions
+9 -2
View File
@@ -456,12 +456,19 @@ export async function generateProjectDossierDocx(
new Paragraph({
text: entry.title,
heading: HeadingLevel.HEADING_2,
keepNext: true,
}),
);
for (const note of [...entry.issues, ...entry.notes])
children.push(new Paragraph(note));
for (const slice of investmentReportTableSlices(entry))
children.push(new Paragraph({ text: note, keepNext: true }));
for (const slice of investmentReportTableSlices(entry)) {
// Word merges adjacent tables and then repeats the first
// table's period header on subsequent pages.
children.push(
new Paragraph({ spacing: { before: 0, after: 0 } }),
);
children.push(tableForDocx(slice.headers, slice.rows));
}
}
if (!section.rows.length && !section.paragraphs.length)
children.push(
+85 -1
View File
@@ -1,6 +1,8 @@
import { displayValue } from './display-value.ts';
import {
buildIntegralFinancialTables,
displayReportMoney,
reportMoney,
type InvestmentReportTable,
} from './integral-financial-report.ts';
import { restoreBusinessPlanSnapshot } from './business-financial-plan.ts';
@@ -521,8 +523,90 @@ function makeSections(
const financialPlan = restoreBusinessPlanSnapshot(
text(draft, 'business_plan_snapshot'),
);
if (finance && financialPlan?.reportAssumptions)
if (finance && financialPlan?.reportAssumptions) {
finance.tables = buildIntegralFinancialTables(financialPlan);
const periods = financialPlan.periods ?? 12;
const cell = (id: string, label: string) =>
finance.tables
?.find((table) => table.id === id)
?.rows.find((row) => row[0] === label);
const sumRows = (id: string, labels: string[]) => {
let total = 0n;
for (const label of labels) {
const values = cell(id, label)?.slice(1, periods + 1);
if (
!values ||
values.length !== periods ||
values.some((value) => !/^-?\d+\.\d{2}$/.test(value))
)
return null;
total += values.reduce(
(sum, value) => sum + BigInt(value.replace('.', '')),
0n,
);
}
return reportMoney(total);
};
const gap = cell('funding', 'Diferença por financiar')?.[1];
const values: Record<string, string | undefined | null> = {
'Caixa final projectada': cell('cashflow', 'Caixa final')?.[
periods
],
'Pagamentos no horizonte': sumRows('cashflow', [
'Pagamentos de compras',
'Pagamentos operacionais',
'Pagamentos de pessoal',
'Juros pagos',
'Capital reembolsado',
'Pagamento de obrigações iniciais',
'Pagamento fiscal estimado',
]),
'Resultado antes de impostos': sumRows('profit-loss', [
'Lucro líquido',
'Imposto estimado',
]),
'Diferença entre usos e fontes': gap,
};
for (const row of finance.rows) {
if (row.field in values) {
const value = values[row.field];
row.value = value
? `${displayReportMoney(value)} ${financialPlan.currency}`
: 'Por determinar — complete os dados complementares do relatório';
row.origin =
'Mesmas tabelas financeiras do relatório, incluindo complementos declarados';
row.classification =
'Projecção calculada; não é valor realizado';
} else if (row.field === 'Reconciliação do financiamento') {
row.value =
!gap || !/^-?\d+\.\d{2}$/.test(gap)
? 'Informação insuficiente'
: formatDossierReportValue(
row.field,
Number(gap) > 0
? 'shortfall'
: Number(gap) < 0
? 'surplus'
: 'balanced',
);
} else if (
row.field === 'Fórmula e valores substituídos' &&
row.origin.includes('Métodos do plano financeiro')
) {
row.value =
'Facturação: quantidade × preço por produto. Caixa final: caixa de abertura após fontes, usos e arranque + recebimentos − pagamentos, incluindo pagamentos fiscais estimados. Os totais usam os mesmos meses e pressupostos das tabelas abaixo.';
}
}
const net = sumRows('profit-loss', ['Lucro líquido']);
finance.rows.push({
field: 'Resultado líquido no horizonte',
value: net
? `${displayReportMoney(net)} ${financialPlan.currency}`
: 'Por determinar',
origin: 'Soma dos mesmos resultados mensais da tabela Lucros e Perdas; arranque reconhecido na abertura',
classification: 'Projecção calculada; não é valor realizado',
});
}
if (
finance &&
['fiscal_rule_qa_preview', 'fiscal_rule_published'].includes(