Files
Investidor-V2/resources/js/lib/integral-financial-report.ts
T

780 lines
30 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,
type BusinessFinancialPlanInput,
} from './business-financial-plan.ts';
import { calculateStartupAssetRequirements } from './startup-asset-requirements.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;
};
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);
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. */
export function buildIntegralFinancialTables(
plan: BusinessFinancialPlanInput,
): 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('Indique o ano inicial do relatório (1900–9999).');
const needs = plan.startupAssetRequirements
? calculateStartupAssetRequirements(plan)
: undefined;
const openingFixed = cents(a.openingFixedAssets),
otherAssets =
cents(a.openingOtherAssets) + (needs?.currentAcquisition ?? 0n),
openingEquity = cents(a.openingEquity);
if (
[openingFixed, otherAssets, openingEquity].some(
(value) => value < 0n,
)
)
throw new Error(
'Os saldos iniciais complementares não podem ser negativos.',
);
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) => {
if (
!row.label.trim() ||
row.label.length > 160 ||
cents(row.amount) < 0n
)
throw new Error(
'Cada despesa de arranque exige designação e montante não negativo.',
);
return total + cents(row.amount);
}, 0n);
const count = result.rows.length;
const schedule = (values: 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) => {
const amount = cents(value);
if (amount < 0n)
throw new Error(
'Os impostos estimados não podem ser negativos.',
);
return amount;
});
};
const taxExpenses = schedule(a.taxExpenseByMonth),
taxPayments = schedule(a.taxPaymentByMonth);
if (!a.taxSource.trim())
throw new Error(
'Indique 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 (
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;
let depreciation = 0n,
cumulativeProfit = -startup,
principal = 0n;
let distributedDividends = 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 otherIncome =
a.manualCollectionsKind === 'other_income'
? cents(plan.monthlyCollections)
: 0n;
const profit =
cents(row.profitBeforeTax) + otherIncome - taxExpenses[i];
const netCash = cents(row.netCashFlow) - taxPayments[i];
const opening = cash;
cash += netCash;
receivables +=
cents(row.revenue) - cents(row.cashCollections) + otherIncome;
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);
taxDue += taxExpenses[i] - taxPayments[i];
depreciation += cents(row.depreciation);
principal += cents(row.principalRepayment);
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 (depreciation > fixed || principal > loans)
table('balance').issues.push(
`Mês ${i + 1}: depreciação superior aos activos ou reembolso superior à dívida; confira os dados.`,
);
const assets =
cash +
positive(receivables) +
(inventory ?? 0n) +
fixed -
depreciation +
otherAssets +
positive(-obligations) +
positive(-taxDue);
const liabilities =
positive(-receivables) +
positive(obligations) +
positive(taxDue) +
loans -
principal +
deferredGrant;
const capital =
paidCapital + cumulativeProfit - distributedDividends;
return {
opening,
cash,
receivables,
obligations: obligationsKnown ? obligations : null,
taxDue,
profit,
netCash,
assets: inventory === null || !obligationsKnown ? null : assets,
liabilities: obligationsKnown ? liabilities : null,
capital,
difference:
inventory === null || !obligationsKnown
? null
: assets - liabilities - capital,
loans: loans - principal,
paidCapital,
accumulatedResults: cumulativeProfit - distributedDividends,
fixed: fixed - 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'));
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 (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', 'Obrigações operacionais líquidas'],
['taxDue', 'Saldo fiscal estimado'],
['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]),
);
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.',
);
} catch (error) {
for (const entry of tables)
entry.issues.push(
error instanceof Error
? error.message
: 'Complete os dados do plano financeiro.',
);
}
return tables;
}