feat: implement F22 period financing and asset agendas in isolated QA

This commit is contained in:
2026-11-21 11:55:43 +02:00
parent 6b91fd2bcd
commit 1950bb69ec
35 changed files with 2298 additions and 61 deletions
+136 -10
View File
@@ -485,6 +485,10 @@ export function buildIntegralFinancialTables(
cumulativeProfit = -startup,
principal = 0n;
let distributedDividends = 0n;
let subsequentFixed = 0n,
subsequentBorrowings = 0n;
let legacyPrincipal = 0n,
legacyDepreciation = 0n;
let obligationsKnown = true;
const fixed =
openingFixed +
@@ -512,6 +516,9 @@ export function buildIntegralFinancialTables(
`Saldos de abertura não reconciliados: diferença ${reportMoney(initialDifference)}. Confira o património e o capital anteriores; não há compensação automática.`,
);
const ledger = result.rows.map((row, i) => {
const movements = result.periodInvestmentLedger?.monthly[i];
subsequentFixed += cents(row.assetAcquisitions ?? '0');
subsequentBorrowings += cents(row.newBorrowings ?? '0');
const otherIncome =
a.manualCollectionsKind === 'other_income'
? cents(plan.monthlyCollections)
@@ -551,10 +558,23 @@ export function buildIntegralFinancialTables(
obligations += cents(
result.supplierAdvanceLedger?.monthly[i].refunded ?? '0',
);
const grossObligations = obligations + advance;
// New financing interest is shown separately from trade obligations.
obligations -=
cents(row.newInterestExpense ?? '0') -
cents(row.newInterestPayment ?? '0');
const tradeObligations = obligations + advance;
const interestLiabilities = cents(
movements?.interestLiabilities ?? '0',
);
const interestAssets = cents(movements?.interestAssets ?? '0');
taxDue += taxExpenses[i] - taxPayments[i];
depreciation += cents(row.depreciation);
principal += cents(row.principalRepayment);
legacyPrincipal +=
cents(row.principalRepayment) -
cents(row.newPrincipalRepayment ?? '0');
legacyDepreciation +=
cents(row.depreciation) - cents(row.newDepreciation ?? '0');
cumulativeProfit += profit;
distributedDividends += cents(row.dividends);
const inventory =
@@ -565,11 +585,11 @@ export function buildIntegralFinancialTables(
table('balance').issues.push(
`Mês ${i + 1}: existências insuficientes para as vendas declaradas.`,
);
if (depreciation > fixed)
if (legacyDepreciation > fixed)
table('balance').issues.push(
`Balanço Projectado — mês ${i + 1}: a depreciação acumulada excede os activos fixos disponíveis. Confira «Base depreciável contabilística» e «Vida útil (meses)» face a «Aquisição de activos» e «Activos fixos anteriores (valor líquido)»; corrija os pressupostos inconsistentes.`,
);
if (principal > loans)
if (legacyPrincipal > loans)
table('balance').issues.push(
`Balanço Projectado — mês ${i + 1}: o capital reembolsado acumulado excede a dívida declarada. Confira «Reembolso de capital» face a «Empréstimo recebido» e «Suprimentos»; corrija os pressupostos inconsistentes.`,
);
@@ -577,17 +597,21 @@ export function buildIntegralFinancialTables(
cash +
positive(receivables) +
(inventory ?? 0n) +
fixed -
fixed +
subsequentFixed -
depreciation +
otherAssets +
positive(-grossObligations) +
positive(-tradeObligations) +
interestAssets +
advance +
positive(-taxDue);
const liabilities =
positive(-receivables) +
positive(grossObligations) +
positive(tradeObligations) +
interestLiabilities +
positive(taxDue) +
loans -
loans +
subsequentBorrowings -
principal +
deferredGrant;
const capital =
@@ -596,7 +620,7 @@ export function buildIntegralFinancialTables(
opening,
cash,
receivables,
obligations: obligationsKnown ? grossObligations : null,
obligations: obligationsKnown ? tradeObligations : null,
advance,
taxDue,
profit,
@@ -608,10 +632,10 @@ export function buildIntegralFinancialTables(
inventory === null || !obligationsKnown
? null
: assets - liabilities - capital,
loans: loans - principal,
loans: loans + subsequentBorrowings - principal,
paidCapital,
accumulatedResults: cumulativeProfit - distributedDividends,
fixed: fixed - depreciation,
fixed: fixed + subsequentFixed - depreciation,
inventory,
};
});
@@ -670,6 +694,32 @@ export function buildIntegralFinancialTables(
),
];
flows('cashflow', 'Recebimentos', data('cashCollections'));
if (result.periodInvestmentLedger) {
flows(
'cashflow',
'Novos empréstimos e suprimentos',
result.rows.map((r) => cents(r.newBorrowings ?? '0')),
);
flows(
'cashflow',
'Aquisições posteriores de activos',
result.rows.map((r) => cents(r.assetAcquisitions ?? '0')),
);
stocks(
'balance',
'Juros de novos financiamentos por pagar',
result.periodInvestmentLedger.monthly.map((r) =>
cents(r.interestLiabilities),
),
);
stocks(
'balance',
'Juros de novos financiamentos pagos antecipadamente',
result.periodInvestmentLedger.monthly.map((r) =>
cents(r.interestAssets),
),
);
}
for (const [key, label] of [
['variableCostPayments', 'Pagamentos de compras'],
['operatingPayments', 'Pagamentos operacionais'],
@@ -874,6 +924,82 @@ export function buildIntegralFinancialTables(
),
);
}
if (result.periodInvestmentLedger) {
const movement = result.periodInvestmentLedger;
tables.push({
id: 'period-investments',
title: 'Financiamentos e activos por período',
headers: [
'Tipo',
'Origem',
'Mês',
'Desembolso',
'Principal',
'Juros reconhecidos',
'Juros pagos',
'Saldo de capital',
'Aquisição',
'Depreciação',
'Activo líquido',
],
rows: [
...movement.financings.flatMap((f) =>
f.monthly.map((r) => [
f.kind === 'bank'
? 'Empréstimo bancário'
: 'Suprimento',
`${f.id} — ${f.label}`,
String(r.month),
r.borrowings,
r.principal,
r.interestExpense,
r.interestPaid,
r.balance,
'—',
'—',
'—',
]),
),
...movement.assets.flatMap((a) =>
a.monthly.map((r) => [
'Activo',
`${a.id} — ${a.label}`,
String(r.month),
'—',
'—',
'—',
'—',
'—',
r.acquisition,
r.depreciation,
r.net,
]),
),
],
issues: [],
notes: [
`Regime ${movement.regime}. Projecções declaradas; não são desembolsos, pagamentos ou lançamentos efectuados. Juros não são capitalizados automaticamente.`,
...movement.assets.map(
(a) =>
`${a.id}: reconhecimento ${a.recognitionDate}; pagamento ${a.paymentDate}; disponibilidade ${a.availableDate || 'não depreciável'}; base ${a.base}; vida útil ${a.lifeMonths || 'não aplicável'} meses; primeira fracção ${a.firstFraction || 'não aplicável'}; último mês de depreciação ${a.lastMonth ?? 'não aplicável'}; base ainda não depreciada ${a.remainingDepreciation}. ${a.linearBasis}`,
),
...movement.financings.flatMap((f) =>
f.drawdowns
.filter((d) => d.outsideHorizon)
.map(
(d) =>
`${f.id}/${d.id}: desembolso ${d.amount} em ${d.date}, fora do horizonte; não incluído na caixa.`,
),
),
...movement.assets
.filter((a) => a.outsideHorizon)
.map(
(a) =>
`${a.id}: aquisição ${a.cost} em ${a.recognitionDate}, fora do horizonte; não incluída na caixa nem nos activos reconhecidos deste plano.`,
),
],
});
}
} catch (error) {
for (const entry of tables)
entry.issues.push(