fix: recover simulator cashflow and verify QA continuity and report assumptions

This commit is contained in:
2026-10-20 22:00:48 +02:00
parent a690c665fb
commit c22003a3da
20 changed files with 773 additions and 95 deletions
@@ -474,6 +474,10 @@ export function exportFinancialToolsCsv(
],
['Prazo (meses)', input.loan.termMonths],
['Periodicidade (meses)', input.loan.periodMonths],
[
'Arredondamento',
'Montantes a duas casas decimais; juros e prestação arredondados à unidade monetária mínima, metade para cima; última prestação ajusta o saldo residual.',
],
['Carência (períodos)', input.loan.gracePeriods ?? 0],
['Comissão inicial', input.loan.upfrontFee ?? '0'],
['Comissão periódica', input.loan.recurringFee ?? '0'],
+68
View File
@@ -1,5 +1,73 @@
import { csvCell } from './csv.js';
export function defaultCashflowDraftInputs() {
return {
openingCash: '0',
monthlyRevenue: '200000',
monthlyOperatingCosts: '150000',
monthlyDebtService: '0',
monthlyTaxAssessed: '',
monthlyTaxSchedule: Array.from({ length: 12 }, () => ''),
vatCreditEstimated: '0',
vatRefundRequested: '0',
vatRefundRecognized: '0',
vatRefundExpectedReceipt: '0',
vatRefundExpectedMonth: '',
};
}
export type CashflowDraftSnapshot = {
version: 1;
taxMode: 'fixed' | 'schedule';
inputs: ReturnType<typeof defaultCashflowDraftInputs>;
};
/** Preserve editable strings, including unanswered and invalid amounts, without inventing zero. */
export function restoreCashflowDraftSnapshot(
snapshot: string | undefined,
): CashflowDraftSnapshot | null {
if (!snapshot || snapshot.length > 20000) return null;
try {
const parsed = JSON.parse(snapshot);
if (
!parsed ||
parsed.version !== 1 ||
!['fixed', 'schedule'].includes(parsed.taxMode) ||
!parsed.inputs ||
typeof parsed.inputs !== 'object' ||
Array.isArray(parsed.inputs)
)
return null;
const keys = Object.keys(defaultCashflowDraftInputs());
if (Object.keys(parsed.inputs).some((key) => !keys.includes(key)))
return null;
for (const key of keys) {
const value = parsed.inputs[key];
if (key === 'monthlyTaxSchedule') {
if (
!Array.isArray(value) ||
value.length !== 12 ||
value.some(
(item) => typeof item !== 'string' || item.length > 160,
)
)
return null;
} else if (typeof value !== 'string' || value.length > 160)
return null;
}
return { version: 1, taxMode: parsed.taxMode, inputs: parsed.inputs };
} catch {
return null;
}
}
export function serializeCashflowDraftSnapshot(
taxMode: CashflowDraftSnapshot['taxMode'],
inputs: CashflowDraftSnapshot['inputs'],
): string {
return JSON.stringify({ version: 1, taxMode, inputs });
}
export type MonthlyCashflowInput = {
openingCash: string;
monthlyRevenue: string;
+6 -1
View File
@@ -171,6 +171,7 @@ const rowSection: Record<string, DossierReportSectionId> = {
'Empréstimo educativo': 'finance',
'Ponto de equilíbrio': 'finance',
Orçamento: 'finance',
Tesouraria: 'finance',
Equipa: 'team',
'Necessidade de negócio': 'resources',
Financiamento: 'resources',
@@ -246,6 +247,8 @@ function makeSections(
'Saldo operacional estimado',
'Diferença por financiar',
'Prestação do primeiro período',
'Saldo final total',
'Caixa conhecida antes de imposto em falta',
]);
const budgetPeriod = rows.find(
(row) => row[1] === 'Periodicidade do orçamento',
@@ -256,7 +259,9 @@ function makeSections(
field:
field === 'Saldo operacional estimado' && budgetPeriod
? `${field} — ${budgetPeriod}`
: field,
: field === 'Saldo final total'
? 'Saldo final de tesouraria — 12 meses'
: field,
value: absent(
formatDossierReportValue(
field,
+68 -2
View File
@@ -1,5 +1,9 @@
import { displayValue } from './display-value.ts';
import { csvCellWithDelimiter } from './csv.js';
import {
restoreCashflowDraftSnapshot,
projectMonthlyCashflow,
} from './monthly-cashflow.ts';
import {
calculateFinancialTools,
restoreFinancialToolsSnapshot,
@@ -330,7 +334,7 @@ export function buildProjectDossierRows(
[
'Empréstimo educativo',
'Taxa anual pressuposta',
`${finance.loan.rate}% (${finance.loan.rateType})`,
`${finance.loan.rate}% (${finance.loan.rateType === 'nominal' ? 'nominal anual' : 'efectiva anual'})`,
'Declarada pelo utilizador; não é taxa de produto',
],
[
@@ -342,7 +346,7 @@ export function buildProjectDossierRows(
[
'Empréstimo educativo',
'Método e pressupostos substituídos',
`Saldo decrescente; capital ${finance.loan.principal}; taxa ${finance.loan.rate}% ${finance.loan.rateType}; ${finance.loan.months} meses; período ${finance.loan.periodMonths} meses; carência ${finance.loan.gracePeriods}; comissão inicial ${finance.loan.upfrontFee}; comissão periódica ${finance.loan.recurringFee}`,
`Saldo decrescente; capital ${finance.loan.principal} ${currency}; taxa ${finance.loan.rate}% ${finance.loan.rateType === 'nominal' ? 'nominal anual (dividida pelos períodos do ano)' : 'efectiva anual (convertida para o período)'}; prazo ${finance.loan.months} meses; periodicidade ${finance.loan.periodMonths} meses; carência ${finance.loan.gracePeriods} períodos; comissão inicial ${finance.loan.upfrontFee} ${currency}; comissão periódica ${finance.loan.recurringFee} ${currency}. Montantes a duas casas decimais; juros e prestação arredondados à unidade monetária mínima, metade para cima; última prestação ajusta o saldo residual.`,
'Cronograma do simulador; taxa declarada, sem correspondência a produto',
],
[
@@ -604,6 +608,68 @@ export function buildProjectDossierRows(
'Planeado/realizado declarado pelo utilizador',
]);
}
if (draft.cashflow_snapshot) {
const saved = restoreCashflowDraftSnapshot(
String(draft.cashflow_snapshot),
);
const origin =
'Estimativa de planeamento; pressupostos guardados da ferramenta que podem incluir exemplos iniciais. Não confirma impostos nem recebimentos.';
try {
if (!saved)
throw new Error(
'Pressupostos de tesouraria não recuperáveis; não foram substituídos por valores alternativos.',
);
const currency = String(draft.currency ?? '');
if (!currency)
throw new Error(
'Indique uma moeda para interpretar os montantes de tesouraria.',
);
const input = {
...saved.inputs,
currency,
...(saved.taxMode === 'fixed'
? { monthlyTaxSchedule: undefined }
: { monthlyTaxAssessed: '' }),
};
const projection = projectMonthlyCashflow(input);
const amount = (value: string | null) =>
value === null ? 'Indeterminado' : `${value} ${currency}`;
rows.push([
'Tesouraria',
'Pressupostos e período',
`12 meses; moeda ${currency}; saldo inicial ${saved.inputs.openingCash}; receita mensal ${saved.inputs.monthlyRevenue}; custos mensais ${saved.inputs.monthlyOperatingCosts}; dívida mensal ${saved.inputs.monthlyDebtService}; imposto ${saved.taxMode === 'fixed' ? 'mensal fixo: ' + (saved.inputs.monthlyTaxAssessed || 'não informado') : 'variável por mês (vazio não é zero)'}. Crédito estimado ${saved.inputs.vatCreditEstimated}; pedido ${saved.inputs.vatRefundRequested}; reconhecido ${saved.inputs.vatRefundRecognized}; recebimento previsto ${saved.inputs.vatRefundExpectedReceipt}; mês previsto ${saved.inputs.vatRefundExpectedMonth || 'não informado'}.`,
origin,
]);
rows.push([
'Tesouraria',
'Saldo final total',
amount(projection.endingCash),
origin,
]);
rows.push([
'Tesouraria',
'Caixa conhecida antes de imposto em falta',
amount(projection.endingCashBeforeUnassessedTax),
origin,
]);
for (const row of projection.rows)
rows.push([
'Tesouraria',
`Mês ${row.month}`,
`Imposto assumido: ${amount(row.taxAssessed)}; recebimento de IVA previsto: ${amount(row.vatRefundExpectedReceipt)}; fluxo líquido: ${amount(row.netFlow)}; saldo final total: ${amount(row.closingCash)}.`,
origin,
]);
} catch (cause) {
rows.push([
'Tesouraria',
'Estado da tesouraria',
cause instanceof Error
? cause.message
: 'Tesouraria indeterminada; reveja os pressupostos.',
origin,
]);
}
}
return rows;
}