Files
Investidor-V2/resources/js/lib/integral-financial-report.ts
T
Claude f9f569d285 Fluxo de caixa: o IVA das vendas entra na tesouraria e é entregue ao Estado no mês seguinte
Decisão do proprietário de 04/12/2026. Quando o «IVA mensal das vendas
projectadas» está calculado para as vendas actuais (taxa da actividade,
16% ou 5%), o fluxo de caixa do relatório financeiro integral passa a ter
«IVA recebido dos clientes», em proporção das vendas efectivamente
cobradas, e «IVA entregue ao Estado» no mês seguinte ao da facturação, com
a declaração periódica (CIVA, Lei 13/2016, artigos 23(1) e 32(1)(b): até ao
último dia do mês seguinte). O balanço mostra o «IVA a entregar ao Estado»
e o IVA facturado ainda por cobrar fica nos recebíveis; o balanço continua
reconciliado e o resultado não muda, porque o IVA não é receita nem custo.

Sem resultado actual e completo, o IVA não entra e o plano diz o que falta
calcular. O resumo do dossier soma o IVA às cobranças e aos pagamentos para
coincidir com as tabelas. O IVA dedutível nas compras não é considerado.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
2026-12-05 06:14:24 +02:00

1100 lines
47 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
forecastBusinessPlan,
monthlyProjectedSales,
businessPlanNumberError,
type BusinessFinancialPlanInput,
} from './business-financial-plan.ts';
import { calculateStartupAssetRequirements } from './startup-asset-requirements.ts';
import {
advanceEventLabels,
advanceDocumentLabel,
} from './supplier-advances.ts';
export type InvestmentReportTable = {
id: string;
title: string;
headers: string[];
rows: string[][];
notes: string[];
issues: string[];
};
/** Shared print/Word layout: repeat the rubric beside at most four periods. */
export function investmentReportTableSlices(table: InvestmentReportTable) {
return Array.from(
{ length: Math.ceil((table.headers.length - 1) / 4) },
(_, chunk) => {
const start = 1 + chunk * 4;
const indices = [
0,
...Array.from(
{ length: Math.min(4, table.headers.length - start) },
(_, i) => start + i,
),
];
return {
headers: indices.map((i) => table.headers[i]),
rows: table.rows.map((row) =>
indices.map((i) => displayReportMoney(row[i] ?? '')),
),
};
},
);
}
const cents = (value: string): bigint => {
if (!/^-?\d+(?:\.\d{1,2})?$/.test(value))
throw new Error(
'Preencha os montantes do relatório com até duas casas decimais.',
);
const negative = value.startsWith('-');
const [whole, fraction = ''] = value.replace(/^-/, '').split('.');
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')}`;
};
export const displayReportMoney = (value: string) => {
if (!/^-?\d+\.\d{2}$/.test(value)) return value;
const [whole, fraction] = value.split('.');
return `${whole.replace(/\B(?=(\d{3})+(?!\d))/g, ' ')},${fraction}`;
};
const positive = (value: bigint) => (value > 0n ? value : 0n);
/** «16» or «5» as hundredths of a percent. */
const vatRateHundredths = (rate: string) => {
const [whole, fraction = ''] = rate.trim().split('.');
if (!/^\d+$/.test(whole) || !/^\d{0,2}$/.test(fraction))
throw new Error('Taxa de IVA inválida no resultado publicado.');
return BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0'));
};
/** amount × rate, half up to the cent (amount in cents, rate in hundredths of a percent). */
const percentOf = (amount: bigint, rate: bigint) => {
const scaled = amount * rate;
const sign = scaled < 0n ? -1n : 1n;
const abs = scaled * sign;
return (sign * (abs + 5000n)) / 10000n;
};
export function newReportAssumptions(
periods: number,
): NonNullable<BusinessFinancialPlanInput['reportAssumptions']> {
return {
startYear: '',
openingFixedAssets: '',
openingOtherAssets: '',
openingEquity: '',
startupExpenses: [],
taxExpenseByMonth: Array(periods).fill(''),
taxPaymentByMonth: Array(periods).fill(''),
taxSource: '',
grantsTreatment: '',
manualCollectionsKind: '',
};
}
export function isReportAssumptions(
value: unknown,
): value is NonNullable<BusinessFinancialPlanInput['reportAssumptions']> {
if (!value || typeof value !== 'object' || Array.isArray(value))
return false;
const a = value as Record<string, unknown>;
const short = (entry: unknown, length = 40) =>
typeof entry === 'string' && entry.length <= length;
return (
[
'startYear',
'openingFixedAssets',
'openingOtherAssets',
'openingEquity',
].every((key) => short(a[key])) &&
short(a.taxSource, 2000) &&
['', 'capital', 'deferred'].includes(String(a.grantsTreatment)) &&
['', 'sales', 'other_income'].includes(
String(a.manualCollectionsKind),
) &&
['taxExpenseByMonth', 'taxPaymentByMonth'].every(
(key) =>
Array.isArray(a[key]) &&
a[key].length <= 60 &&
a[key].every((entry: unknown) => short(entry)),
) &&
Array.isArray(a.startupExpenses) &&
a.startupExpenses.length <= 40 &&
a.startupExpenses.every(
(entry) =>
entry &&
typeof entry === 'object' &&
short(entry.label, 160) &&
short(entry.amount),
)
);
}
/** Read only declared investor inputs. The synthetic annual example is never used. */
/**
* IVA of the plan's sales, as calculated by the published IVA version for the
* plan's activity (16% or 5%): billed per month, in cents. When present it is
* included in the treasury: received with the sales collections and delivered
* to the State in the following month (CIVA, arts. 23(1) and 32(1)(b)).
*/
export type IntegralVat = {
ratePercent: string;
billedByMonth: bigint[];
source: string;
};
export function buildIntegralFinancialTables(
plan: BusinessFinancialPlanInput,
vat: IntegralVat | null = null,
): InvestmentReportTable[] {
const titles = [
['startup', 'Start-up / arranque'],
['sales', 'Previsão de Vendas'],
['funding', 'Financiamento'],
['break-even', 'Ponto de Equilíbrio'],
['profit-loss', 'Lucros e Perdas'],
['cashflow', 'Fluxo de Caixa'],
['balance', 'Balanço Projectado'],
];
const tables = titles.map(([id, title]) => ({
id,
title,
headers: ['Rubrica', 'Valor'],
rows: [] as string[][],
notes: [
'Projecção com dados declarados; não confirma valores realizados.',
],
issues: [] as string[],
}));
const table = (id: string) => tables.find((entry) => entry.id === id)!;
try {
const result = forecastBusinessPlan(plan);
const a = plan.reportAssumptions;
if (!isReportAssumptions(a))
throw new Error(
'Complete os dados contabilísticos complementares do relatório.',
);
if (
!/^\d{4}$/.test(a.startYear) ||
Number(a.startYear) < 1900 ||
Number(a.startYear) > 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 = fieldCents(
a.openingFixedAssets,
'Activos fixos anteriores (valor líquido)',
),
otherAssets =
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(
`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) ||
a.startupExpenses.length === 0 ||
a.startupExpenses.length > 40
)
throw new Error(
'Declare as despesas de arranque, incluindo uma linha de zero quando não existirem.',
);
const startup = a.startupExpenses.reduce((total, row, index) => {
if (
!row.label.trim() ||
row.label.length > 160 ||
fieldCents(row.amount, `Montante de arranque ${index + 1}`) < 0n
)
throw new Error(
!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 +
fieldCents(row.amount, `Montante de arranque ${index + 1}`)
);
}, 0n);
const count = result.rows.length;
const schedule = (values: string[], field: string) => {
if (!Array.isArray(values) || values.length !== count)
throw new Error(
'Preencha imposto estimado e pagamento fiscal para cada mês, incluindo zero quando aplicável.',
);
return values.map((value, month) => {
let amount: bigint;
try {
amount = cents(value);
} catch {
throw new Error(
`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}»: Este valor não pode ser negativo. Corrija este campo.`,
);
return amount;
});
};
const taxExpenses = schedule(
a.taxExpenseByMonth,
'Imposto reconhecido',
),
taxPayments = schedule(
a.taxPaymentByMonth,
'Pagamento fiscal previsto',
);
if (!a.taxSource.trim())
throw new Error(
'«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 &&
!['capital', 'deferred'].includes(a.grantsTreatment)
)
throw new Error(
'Escolha o tratamento das subvenções: capital ou passivo diferido.',
);
if (
!plan.dayTerms?.sales &&
cents(plan.monthlyCollections) > 0n &&
!['sales', 'other_income'].includes(a.manualCollectionsKind)
)
throw new Error(
'Classifique os recebimentos manuais como vendas ou outras receitas.',
);
const periodHeaders = result.rows.map(
(row) =>
`${Number(a.startYear) + Math.floor((row.month - 1) / 12)}-${String(((row.month - 1) % 12) + 1).padStart(2, '0')}`,
);
const years = [
...new Set(periodHeaders.map((period) => period.slice(0, 4))),
];
const annualIndices = years.map((year) =>
periodHeaders
.map((period, index) => (period.startsWith(year) ? index : -1))
.filter((index) => index >= 0),
);
const headers = [
'Rubrica',
...periodHeaders,
...years.map(
(year, i) =>
`${year}${annualIndices[i].length < 12 ? ' (parcial)' : ''}`,
),
];
const flows = (id: string, label: string, values: bigint[]) =>
table(id).rows.push([
label,
...values.map(reportMoney),
...annualIndices.map((indices) =>
reportMoney(
indices.reduce(
(total, index) => total + values[index],
0n,
),
),
),
]);
const stocks = (id: string, label: string, values: (bigint | null)[]) =>
table(id).rows.push([
label,
...values.map((value) =>
value === null ? 'Por determinar' : reportMoney(value),
),
...annualIndices.map((indices) =>
values[indices.at(-1)!] === null
? 'Por determinar'
: reportMoney(values[indices.at(-1)!]!),
),
]);
for (const id of [
'sales',
'break-even',
'profit-loss',
'cashflow',
'balance',
])
table(id).headers = headers;
table('startup').rows = [
...a.startupExpenses.map((row) => [
row.label,
reportMoney(cents(row.amount)),
]),
['Despesas de arranque', reportMoney(startup)],
[
'Investimento em activos',
reportMoney(cents(plan.assetInvestment)),
],
['Existências iniciais', reportMoney(cents(plan.inventory))],
['Recebíveis iniciais', reportMoney(cents(plan.receivables))],
['Obrigações iniciais', reportMoney(cents(plan.payables))],
[
'Usos líquidos iniciais',
reportMoney(cents(result.initialUses) + startup),
],
];
table('startup').notes.push(
'Despesas de arranque reconhecidas e pagas no início. Saldos patrimoniais anteriores não são novas despesas.',
);
if (needs) {
table('startup').headers = [
'Rubrica',
'Requerido',
'Disponível antes de financiamento',
];
table('startup').rows = [
...a.startupExpenses.map((r) => [
r.label,
reportMoney(cents(r.amount)),
'Despesa planeada, não pagamento realizado',
]),
[
'Despesas de arranque',
reportMoney(startup),
'Por realizar no cenário',
],
[
'Caixa',
reportMoney(needs.cashRequired),
reportMoney(needs.cashAvailable),
],
[
'Outros activos correntes',
reportMoney(needs.currentRequired),
reportMoney(needs.currentAvailable),
],
[
'Activos de longo prazo',
reportMoney(needs.fixedRequired),
reportMoney(needs.fixedAvailable),
],
[
'Total de activos requeridos',
reportMoney(needs.totalRequiredAssets),
reportMoney(
needs.cashAvailable +
needs.currentAvailable +
needs.fixedAvailable,
),
],
[
'Requisitos brutos de arranque',
reportMoney(needs.grossRequirements),
'Disponibilidade não se presume',
],
[
'Existências/recebíveis iniciais já planeados',
reportMoney(needs.currentAlreadyPlanned),
'Não são disponibilidade confirmada',
],
[
'Aquisições adicionais correntes',
reportMoney(needs.currentAcquisition),
'Por adquirir',
],
[
'Aquisições adicionais de longo prazo',
reportMoney(needs.fixedAcquisition),
'Por adquirir',
],
];
table('startup').notes.push(
'Caixa requerida é a reserva desejada após o arranque; caixa disponível é o saldo declarado antes de novo financiamento. Valores disponíveis são declarados, não certificados. Não se presume liquidação de activos excedentários.',
);
}
table('funding').rows = [
...(plan.fundingBreakdown
? [
[
'Capital do proprietário',
plan.fundingBreakdown.ownerCapital,
],
[
'Capital do investidor',
plan.fundingBreakdown.investorCapital,
],
[
'Capital adicional angariado',
plan.fundingBreakdown.additionalCapital,
],
]
: []),
['Capital introduzido', plan.equity],
['Suprimentos', plan.shareholderLoans],
['Empréstimos', plan.bankLoanProceeds],
['Subvenções declaradas', plan.grants],
['Total de fontes', result.financing],
[
'Usos líquidos com arranque',
reportMoney(cents(result.initialUses) + startup),
],
[
'Diferença por financiar',
reportMoney(cents(result.fundingGap) + startup),
],
[
'Caixa após financiamento e arranque',
reportMoney(
cents(result.openingCashAfterInitialUses) - startup,
),
],
].map(([label, value]) => [label, reportMoney(cents(value))]);
if (needs) {
const projectedCash =
cents(result.openingCashAfterInitialUses) - startup;
const plannedLabels: Record<string, string> = {
'Capital introduzido': 'Capital planeado',
Suprimentos: 'Suprimentos planeados',
Empréstimos: 'Empréstimos planeados',
'Subvenções declaradas': 'Subvenções planeadas',
'Total de fontes': 'Total de fontes planeadas',
};
table('funding').rows = table('funding')
.rows.filter(
(row) => row[0] !== 'Caixa após financiamento e arranque',
)
.map(([label, value]) => [
plannedLabels[label] ?? label,
value,
]);
table('funding').rows.push(
[
'Requisitos brutos de arranque',
reportMoney(needs.grossRequirements),
],
[
'Caixa disponível antes de financiamento',
reportMoney(needs.cashAvailable),
],
[
'Reserva de caixa requerida após arranque',
reportMoney(needs.cashRequired),
],
[
'Caixa projectada após arranque com fontes planeadas',
reportMoney(projectedCash),
],
[
'Falta para a reserva requerida (projecção)',
reportMoney(positive(needs.cashRequired - projectedCash)),
],
);
table('funding').notes.push(
'Capital, empréstimos e subvenções são fontes planeadas do cenário, não financiamento realizado. A diferença original entre usos e fontes conserva a fórmula aprovada; a falta para a reserva inclui separadamente o objectivo de caixa e a disponibilidade declarada.',
);
}
table('funding').notes.push(
'Financiamento insuficiente é aviso não bloqueante. As fontes são pressupostos do plano, não confirmação bancária.',
);
for (const product of plan.products) {
const sales = monthlyProjectedSales({
...plan,
products: [product],
});
if (sales.some((value) => value === null))
throw new Error('Complete a previsão de vendas por produto.');
flows(
'sales',
product.label,
sales.map((value) => cents(value!)),
);
}
flows(
'sales',
'Vendas totais',
result.rows.map((row) => cents(row.revenue)),
);
let cash = cents(result.openingCashAfterInitialUses) - startup;
let receivables = cents(plan.receivables),
obligations = cents(plan.payables),
taxDue = 0n,
vatDue = 0n;
const vatRate = vat ? vatRateHundredths(vat.ratePercent) : 0n;
const vatReceived: bigint[] = [];
const vatDelivered: bigint[] = [];
let depreciation = 0n,
cumulativeProfit = -startup,
principal = 0n;
let distributedDividends = 0n;
let subsequentFixed = 0n,
subsequentBorrowings = 0n;
let legacyPrincipal = 0n,
legacyDepreciation = 0n;
let obligationsKnown = true;
const fixed =
openingFixed +
cents(plan.assetInvestment) -
(needs?.currentAcquisition ?? 0n);
const loans =
cents(plan.bankLoanProceeds) + cents(plan.shareholderLoans);
const grantCapital =
a.grantsTreatment === 'capital' ? cents(plan.grants) : 0n;
const deferredGrant = cents(plan.grants) - grantCapital;
const paidCapital = openingEquity + cents(plan.equity) + grantCapital;
const initialDifference =
cash +
cents(plan.inventory) +
receivables +
fixed +
otherAssets -
obligations -
loans -
deferredGrant -
paidCapital -
cumulativeProfit;
if (initialDifference !== 0n)
table('balance').issues.push(
`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)
: 0n;
const profit =
cents(row.profitBeforeTax) + otherIncome - taxExpenses[i];
// IVA: billed with each sale, received in proportion to the sales collected
// (opening receivables, refunds and other income excluded), delivered the next month.
const salesCash =
cents(row.cashCollections) -
cents(row.openingReceivablesCollections ?? '0') -
cents(
result.supplierAdvanceLedger?.monthly[i].refunded ?? '0',
) -
otherIncome;
const received = vat ? percentOf(salesCash, vatRate) : 0n;
const billed = vat ? (vat.billedByMonth[i] ?? 0n) : 0n;
const delivered =
vat && i > 0 ? (vat.billedByMonth[i - 1] ?? 0n) : 0n;
vatReceived.push(received);
vatDelivered.push(delivered);
vatDue += billed - delivered;
const netCash =
cents(row.netCashFlow) - taxPayments[i] + received - delivered;
const opening = cash;
cash += netCash;
receivables +=
cents(row.revenue) -
cents(row.cashCollections) +
otherIncome +
billed -
received +
cents(result.supplierAdvanceLedger?.monthly[i].refunded ?? '0');
const purchases =
row.inventoryReceipts === null
? null
: cents(row.inventoryReceipts);
if (purchases === null) obligationsKnown = false;
if (purchases === null)
table('balance').issues.push(
`Mês ${i + 1}: active e preencha a agenda de compras/recepções para determinar existências e obrigações.`,
);
obligations +=
(purchases ?? 0n) +
cents(row.operatingExpenses) +
cents(row.payrollExpense) +
cents(row.interestExpense) -
cents(row.variableCostPayments) -
cents(row.operatingPayments) -
cents(row.payrollPayments) -
cents(row.interestPayment) -
cents(row.openingPayablesPayments);
const advance = cents(
result.supplierAdvanceLedger?.monthly[i].advance ?? '0',
);
obligations += cents(
result.supplierAdvanceLedger?.monthly[i].refunded ?? '0',
);
// 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 =
row.inventoryClosing === null
? null
: cents(row.inventoryClosing);
if (cents(row.inventoryShortfall ?? '0') > 0n)
table('balance').issues.push(
`Mês ${i + 1}: existências insuficientes para as vendas declaradas.`,
);
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 (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.`,
);
const assets =
cash +
positive(receivables) +
(inventory ?? 0n) +
fixed +
subsequentFixed -
depreciation +
otherAssets +
positive(-tradeObligations) +
interestAssets +
advance +
positive(-taxDue);
const liabilities =
positive(-receivables) +
positive(tradeObligations) +
interestLiabilities +
positive(taxDue) +
vatDue +
loans +
subsequentBorrowings -
principal +
deferredGrant;
const capital =
paidCapital + cumulativeProfit - distributedDividends;
return {
opening,
cash,
receivables,
obligations: obligationsKnown ? tradeObligations : null,
advance,
taxDue,
vatDue,
profit,
netCash,
assets: inventory === null || !obligationsKnown ? null : assets,
liabilities: obligationsKnown ? liabilities : null,
capital,
difference:
inventory === null || !obligationsKnown
? null
: assets - liabilities - capital,
loans: loans + subsequentBorrowings - principal,
paidCapital,
accumulatedResults: cumulativeProfit - distributedDividends,
fixed: fixed + subsequentFixed - depreciation,
inventory,
};
});
const data = (key: keyof (typeof result.rows)[number]) =>
result.rows.map((row) => cents(String(row[key])));
flows('profit-loss', 'Vendas', data('revenue'));
flows(
'profit-loss',
'Outras receitas de caixa declaradas',
result.rows.map(() =>
a.manualCollectionsKind === 'other_income'
? cents(plan.monthlyCollections)
: 0n,
),
);
for (const [key, label] of [
['variableCost', 'Custo directo'],
['operatingExpenses', 'Despesas operacionais'],
['payrollExpense', 'Pessoal'],
['depreciation', 'Depreciação'],
['interestExpense', 'Juros'],
] as const)
flows('profit-loss', label, data(key));
for (const line of plan.operatingExpenseLines ?? [])
flows(
'profit-loss',
`Despesa: ${line.label}`,
result.rows.map((_, i) =>
cents(line.amountsByPeriod?.[i] ?? line.monthlyAmount),
),
);
table('profit-loss').notes.push(
...(plan.operatingExpenseLines
? [
'As despesas discriminadas são componentes do total operacional, não despesas adicionais.',
]
: []),
);
flows('profit-loss', 'Imposto estimado', taxExpenses);
flows(
'profit-loss',
'Lucro líquido',
ledger.map((row) => row.profit),
);
stocks(
'cashflow',
'Caixa inicial',
ledger.map((row) => row.opening),
);
// Annual opening cash is the first month's opening, not the closing stock.
table('cashflow').rows[0] = [
'Caixa inicial',
...ledger.map((row) => reportMoney(row.opening)),
...annualIndices.map((indices) =>
reportMoney(ledger[indices[0]].opening),
),
];
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'],
['payrollPayments', 'Pagamentos de pessoal'],
['interestPayment', 'Juros pagos'],
['principalRepayment', 'Capital reembolsado'],
['openingPayablesPayments', 'Pagamento de obrigações iniciais'],
] as const)
flows('cashflow', label, data(key));
flows('cashflow', 'Pagamento fiscal estimado', taxPayments);
if (vat) {
flows('cashflow', 'IVA recebido dos clientes', vatReceived);
flows('cashflow', 'IVA entregue ao Estado', vatDelivered);
table('cashflow').notes.push(
`IVA das vendas à taxa de ${vat.ratePercent.replace('.', ',')}% (${vat.source}): recebido com as cobranças das vendas e entregue ao Estado no mês seguinte ao da facturação, com a declaração periódica (CIVA, artigos 23(1) e 32(1)(b): até ao último dia do mês seguinte). Não inclui IVA dedutível nas compras; o IVA não é receita nem custo do negócio. O IVA facturado no último mês fica por entregar no balanço.`,
);
}
if (plan.dividendsByPeriod)
flows('cashflow', 'Dividendos distribuídos', data('dividends'));
flows(
'cashflow',
'Fluxo líquido',
ledger.map((row) => row.netCash),
);
stocks(
'cashflow',
'Caixa final',
ledger.map((row) => row.cash),
);
for (const [key, label] of [
['cash', 'Caixa líquida'],
['receivables', 'Recebíveis líquidos'],
[
'obligations',
result.supplierAdvanceLedger
? 'Obrigações operacionais brutas'
: 'Obrigações operacionais líquidas',
],
['taxDue', 'Saldo fiscal estimado'],
...(vat ? ([['vatDue', 'IVA a entregar ao Estado']] as const) : []),
['fixed', 'Activos fixos líquidos'],
['loans', 'Empréstimos e suprimentos por reembolsar'],
['paidCapital', 'Capital declarado e anterior'],
['accumulatedResults', 'Resultados acumulados, incluindo arranque'],
['assets', 'Total do activo'],
['liabilities', 'Total do passivo'],
['capital', 'Capital e resultados'],
] as const)
stocks(
'balance',
label,
ledger.map((row) => row[key]),
);
if (plan.accountingRegime)
table('balance').notes.push(
`Regime contabilístico declarado no plano: ${plan.accountingRegime}. Tratamentos limitados ao âmbito implementado; não equivale a certificação integral do regime.`,
);
if (result.supplierAdvanceLedger) {
stocks(
'balance',
'Adiantamentos identificados a fornecedores',
ledger.map((row) => row.advance),
);
stocks(
'balance',
'Líquido por liquidar — operações identificadas',
result.supplierAdvanceLedger.monthly.map((row) =>
cents(row.netDue),
),
);
for (const [key, label] of [
['paid', 'Adiantamentos pagos'],
['applied', 'Aplicações sem movimento de caixa'],
['refunded', 'Devoluções de adiantamentos'],
['settled', 'Remanescentes pagos'],
] as const)
flows(
'cashflow',
label + ' (discriminação)',
result.supplierAdvanceLedger.monthly.map((row) =>
cents(row[key]),
),
);
table('balance').notes.push(
`${result.supplierAdvanceLedger.regime}: adiantamentos identificados apresentados no activo, separados das obrigações brutas. Líquido por liquidar é calculado por operação/parcela, sem compensação entre operações. Devoluções não são receita; aplicações não movimentam caixa.`,
);
table('cashflow').notes.push(
'Adiantamentos, aplicações, devoluções e remanescentes são projecções discriminadas, já incluídas nos totais de caixa quando aplicável; não somar novamente. Sem automatização de IVA, câmbio, perdas, penalizações ou contratos especiais.',
...result.supplierAdvanceLedger.operations.map(
(o) =>
`${o.originId}/${o.parcelId} — ${o.supplier}: reconhecimento ${o.recognitionDate || 'por confirmar'}; factura ${o.invoiceDate || 'por confirmar'}. ${o.formalAgreement ? `Acordo formal ${o.formalAgreement.reference}, ${o.formalAgreement.date}. ` : ''}${o.events.map((e) => `${advanceEventLabels[e.kind]}: ${e.date}, ${e.amount} ${plan.currency}${e.outsideHorizon ? ' (fora do horizonte)' : ''}`).join('; ')}.`,
),
);
}
if (result.supplierAdvanceLedger?.regime === 'PGC-NIRF')
table('balance').notes.push(
...result.supplierAdvanceLedger.operations.map(
(o) =>
`${o.originId}/${o.parcelId}: ${o.monthly.map((m) => `mês ${m.month}, ${advanceDocumentLabel(m.documentaryStatus ?? '')}`).join('; ')}.`,
),
);
if (result.supplierAdvanceLedger?.regime === 'PGC-NIRF')
table('cashflow').notes.push(
...result.supplierAdvanceLedger.operations.flatMap((o) =>
o.events
.filter((e) => e.applicationBasis)
.map(
(e) =>
`${o.originId}/${o.parcelId}: aplicação ${e.date}, fundamento ${e.applicationBasis!.kind === 'formal_agreement' ? 'acordo formal' : 'factura'}, referência ${e.applicationBasis!.reference}, data ${e.applicationBasis!.date}.`,
),
),
);
table('balance').rows.push([
'Existências',
...ledger.map((row) =>
row.inventory === null
? 'Por determinar'
: reportMoney(row.inventory),
),
...annualIndices.map((indices) =>
ledger[indices.at(-1)!].inventory === null
? 'Por determinar'
: reportMoney(ledger[indices.at(-1)!].inventory!),
),
]);
table('balance').rows.push([
'Diferença do balanço',
...ledger.map((row) =>
row.difference === null
? 'Por determinar'
: reportMoney(row.difference),
),
...annualIndices.map((indices) =>
ledger[indices.at(-1)!].difference === null
? 'Por determinar'
: reportMoney(ledger[indices.at(-1)!].difference!),
),
]);
if (
ledger.some(
(row) => row.difference !== null && row.difference !== 0n,
)
)
table('balance').issues.push(
'Existem períodos não reconciliados; reveja as rubricas indicadas.',
);
table('balance').notes.push(
'Caixa negativa conserva-se como défice projectado de tesouraria; não cria dívida, crédito aprovado ou financiamento mobilizado. Recebíveis negativos são adiantamentos de clientes; obrigações negativas são adiantamentos a fornecedores.',
'Capital inicial e activos anteriores são declarados. Depreciação e reembolsos provêm do motor existente. Subvenções: ' +
(a.grantsTreatment || 'sem montante declarado') +
'.',
);
table('profit-loss').notes.push(
'As despesas de arranque constam da abertura, sem repetição mensal. Impostos: ' +
a.taxSource,
);
table('cashflow').notes.push(
'O caixa de abertura já inclui fontes, usos e despesas de arranque; os movimentos iniciais não são repetidos nos meses.',
);
const contributions = result.rows.map(
(row) => cents(row.revenue) - cents(row.variableCost),
);
const fixedCosts = result.rows.map(
(row) =>
cents(row.operatingExpenses) +
cents(row.payrollExpense) +
cents(row.depreciation),
);
const breakEven = (
sales: bigint,
contribution: bigint,
fixedCost: bigint,
) =>
contribution <= 0n
? 'Indeterminado — margem sem contribuição positiva'
: reportMoney(
(fixedCost * sales + contribution / 2n) / contribution,
);
table('break-even').rows = [
[
'Vendas de equilíbrio',
...result.rows.map((row, i) =>
breakEven(
cents(row.revenue),
contributions[i],
fixedCosts[i],
),
),
...annualIndices.map((indices) =>
breakEven(
indices.reduce(
(v, i) => v + cents(result.rows[i].revenue),
0n,
),
indices.reduce((v, i) => v + contributions[i], 0n),
indices.reduce((v, i) => v + fixedCosts[i], 0n),
),
),
],
];
table('break-even').notes.push(
'Vendas de equilíbrio = custos fixos operacionais, pessoal e depreciação ÷ margem de contribuição ponderada. Juros e impostos excluídos. Arredondamento apenas no resultado final, ao centavo.',
);
if (result.dayTermEvents) {
table('cashflow').notes.push(
'Prazos em dias: as agendas seleccionadas substituem as agendas anteriores de caixa, conservadas inactivas. Saldos de abertura mantêm as agendas próprias. Não inclui adiantamentos.',
...result.dayTermEvents.map(
(e) =>
`${e.kind === 'sales' ? 'Vendas/prestações' : e.kind === 'purchases' ? 'Mercadorias recebidas' : 'Serviços adquiridos'} — ${e.originId}/${e.parcelId}: ${e.amount} ${plan.currency}; reconhecimento ${e.recognition}; origem ${e.origin}; vencimento ${e.due}${e.approximate ? ' (aproximação mensal)' : ''}; ${e.outsideHorizon ? 'fora do horizonte, sem movimento de caixa neste plano' : `mês de caixa ${e.dueMonth}`}.`,
),
);
}
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(
error instanceof Error
? error.message
: 'Complete os dados do plano financeiro.',
);
}
return tables;
}