300 lines
12 KiB
TypeScript
300 lines
12 KiB
TypeScript
import {
|
||
calculateAnnualReferencePlan,
|
||
calculateDecisionRatios,
|
||
restoreAnnualExampleSnapshot,
|
||
businessPlanWarnings,
|
||
} from './business-plan-guidance.ts';
|
||
import type { BusinessFinancialPlanInput } from './business-financial-plan.ts';
|
||
import {
|
||
reportMoney,
|
||
type InvestmentReportTable,
|
||
} from './integral-financial-report.ts';
|
||
import { buildComplementaryTables } from './complementary-report.ts';
|
||
|
||
/** Presentation adapter only: uses the approved annual calculation, never converts it into investor movements. */
|
||
export function buildAnnualExampleTables(
|
||
input: BusinessFinancialPlanInput,
|
||
): InvestmentReportTable[] {
|
||
const plan = restoreAnnualExampleSnapshot(input.annualExampleSnapshot);
|
||
if (!plan)
|
||
throw new Error(
|
||
'Carregue e guarde primeiro o cenário anual de exemplo.',
|
||
);
|
||
const result = calculateAnnualReferencePlan(plan);
|
||
const notes = [
|
||
`Exemplo sintético; projecções ilustrativas em ${input.currency || 'moeda por seleccionar'}. Não são dados reais do investidor.`,
|
||
'Totais anuais preservados. A distribuição dos 36 meses é ilustrativa e reconciliada, não uma reprodução das linhas mensais inconsistentes do documento.',
|
||
];
|
||
const make = (
|
||
id: string,
|
||
title: string,
|
||
headers: string[],
|
||
rows: string[][],
|
||
): InvestmentReportTable => ({
|
||
id,
|
||
title,
|
||
headers,
|
||
rows: rows.map((row) =>
|
||
row.map((v, i) =>
|
||
i > 0 && /^-?\d+(?:\.\d{1,2})?$/.test(v)
|
||
? `${v.split('.')[0]}.${(v.split('.')[1] ?? '').padEnd(2, '0')}`
|
||
: v,
|
||
),
|
||
),
|
||
notes: id === 'startup' ? [...notes] : [],
|
||
issues: [],
|
||
});
|
||
const headers = ['Rubrica', ...plan.years.map((y) => String(y.year))];
|
||
const value = (n: number) => n.toFixed(2);
|
||
const row = (
|
||
label: string,
|
||
get: (y: (typeof result.years)[number], i: number) => string,
|
||
) => [label, ...result.years.map(get)];
|
||
const startup = make(
|
||
'startup',
|
||
'Start-up — exemplo',
|
||
['Rubrica', 'Montante'],
|
||
[
|
||
...plan.startupExpenses.map((r) => [r.label, r.amount]),
|
||
['Despesas de arranque', result.startupExpenses],
|
||
['Caixa necessária', plan.openingCash],
|
||
['Outros activos correntes', plan.otherCurrentAssets],
|
||
['Activos de longo prazo', plan.longTermAssets],
|
||
['Total de activos', result.assets],
|
||
['Requisitos totais', result.requiredFunding],
|
||
],
|
||
);
|
||
const sales = make('sales', 'Previsão de Vendas — exemplo', headers, [
|
||
row('Vendas totais', (y) => y.sales),
|
||
row('Custo directo', (y) => y.directCosts),
|
||
]);
|
||
sales.notes.push(
|
||
'Linhas por serviço do original não reconciliam com os totais anuais aceites. Mantêm-se agregadas; não se inventa a diferença por produto.',
|
||
);
|
||
const funding = make(
|
||
'funding',
|
||
'Financiamento — exemplo',
|
||
['Rubrica', 'Montante'],
|
||
[
|
||
['Capital do proprietário', plan.ownerCapital],
|
||
['Capital do investidor', plan.investorCapital],
|
||
['Empréstimos', plan.loans],
|
||
['Dinheiro adicional angariado', plan.additionalMoney],
|
||
['Total de fontes confirmadas', result.availableFunding],
|
||
['Financiamento necessário', result.requiredFunding],
|
||
[
|
||
'Capital por mobilizar — hipótese, não financiamento confirmado',
|
||
result.capitalToMobilise,
|
||
],
|
||
['Diferença por financiar', result.fundingGap],
|
||
],
|
||
);
|
||
const breakeven = make(
|
||
'break-even',
|
||
'Ponto de Equilíbrio — exemplo',
|
||
headers,
|
||
[
|
||
row('Receita mensal de equilíbrio', (y) =>
|
||
y.monthlyBreakEven === null
|
||
? 'Por determinar'
|
||
: value(y.monthlyBreakEven),
|
||
),
|
||
row('Custos fixos mensais', (y) => value(y.monthlyFixedCosts)),
|
||
],
|
||
);
|
||
const profit = make('profit-loss', 'Lucros e Perdas — exemplo', headers, [
|
||
row('Vendas', (y) => y.sales),
|
||
row('Custo directo', (y) => y.directCosts),
|
||
row('Margem bruta', (y) => y.grossMargin),
|
||
row('Despesas operacionais', (y) => y.operatingExpenses),
|
||
row('Resultado operacional', (y) => y.operatingProfit),
|
||
row('Juros', (_, i) => plan.years[i].interest),
|
||
row('Imposto estimado', (_, i) => plan.years[i].taxes),
|
||
row('Lucro líquido', (y) => y.netProfit),
|
||
]);
|
||
const cash = make('cashflow', 'Fluxo de Caixa — exemplo', headers, [
|
||
row('Caixa recebida', (_, i) => plan.years[i].cashReceived),
|
||
row('Caixa gasta', (_, i) => plan.years[i].cashSpent),
|
||
row('Fluxo líquido', (y) => y.cashFlow),
|
||
row('Caixa final', (y) => y.closingCash),
|
||
]);
|
||
const balance = make('balance', 'Balanço — exemplo', headers, [
|
||
row('Caixa líquida', (y) => y.closingCash),
|
||
row('Recebíveis líquidos', (y) => y.receivables),
|
||
row('Outros activos correntes', () => plan.otherCurrentAssets),
|
||
row('Activos fixos líquidos', () => plan.longTermAssets),
|
||
row('Total do activo', (y) => y.closingAssets),
|
||
row('Obrigações operacionais', (y) => y.operatingLiabilities),
|
||
row('Saldo fiscal estimado', (y) => y.vatBalance),
|
||
row('Total do passivo', (y) => y.closingLiabilities),
|
||
row('Capital e resultados', (y) => y.closingCapital),
|
||
row('Diferença do balanço', (y) => y.balanceDifference),
|
||
]);
|
||
balance.notes.push(
|
||
'Capital por mobilizar é hipótese de projecção explicitamente identificada; não é uma fonte obtida nem uma compensação contabilística.',
|
||
);
|
||
const cents = (s: string) => {
|
||
const negative = s.startsWith('-');
|
||
const [a, b = ''] = s.replace('-', '').split('.');
|
||
const n = BigInt(a) * 100n + BigInt(b.padEnd(2, '0'));
|
||
return negative ? -n : n;
|
||
};
|
||
const projectedCapital =
|
||
cents(result.availableFunding) +
|
||
cents(result.capitalToMobilise) -
|
||
cents(plan.loans);
|
||
const ratios = result.years.map((y, i) => {
|
||
try {
|
||
return calculateDecisionRatios(
|
||
{
|
||
cash: y.closingCash,
|
||
receivables: y.receivables,
|
||
inventory: '0',
|
||
otherCurrentAssets: plan.otherCurrentAssets,
|
||
longTermAssets: plan.longTermAssets,
|
||
accumulatedDepreciation: '0',
|
||
currentLiabilities: reportMoney(
|
||
cents(y.operatingLiabilities) + cents(y.vatBalance),
|
||
),
|
||
longTermLiabilities: plan.loans,
|
||
paidCapital: reportMoney(projectedCapital),
|
||
retainedResults: reportMoney(
|
||
cents(y.closingCapital) -
|
||
projectedCapital -
|
||
cents(y.netProfit),
|
||
),
|
||
periodResult: y.netProfit,
|
||
},
|
||
y.sales,
|
||
i ? result.years[i - 1].sales : undefined,
|
||
);
|
||
} catch {
|
||
return {
|
||
salesGrowth:
|
||
y.growthPercent === null ? null : y.growthPercent / 100,
|
||
currentLiquidity: null,
|
||
debtAssets: null,
|
||
netMargin:
|
||
y.netMarginPercent === null
|
||
? null
|
||
: y.netMarginPercent / 100,
|
||
returnOnEquity: null,
|
||
};
|
||
}
|
||
});
|
||
const ratio = make(
|
||
'ratios',
|
||
'Rácios financeiros — exemplo',
|
||
headers,
|
||
(
|
||
[
|
||
['salesGrowth', 'Crescimento das vendas', true],
|
||
['currentLiquidity', 'Liquidez corrente', false],
|
||
['debtAssets', 'Endividamento', true],
|
||
['netMargin', 'Margem líquida', true],
|
||
['returnOnEquity', 'Retorno do capital', true],
|
||
] as const
|
||
).map(([key, label, percent]) => [
|
||
label,
|
||
...ratios.map((r) =>
|
||
r?.[key] == null
|
||
? 'Por determinar'
|
||
: `${value(r[key]! * (percent ? 100 : 1)).replace('.', ',')}${percent ? '%' : '×'}`,
|
||
),
|
||
]),
|
||
);
|
||
const marketInput = {
|
||
...input,
|
||
marketAnalysis: {
|
||
baseYear: '2025',
|
||
years: '5',
|
||
segments: [
|
||
['Publicidade', '100000', '45'],
|
||
['Marketing Digital', '800', '50'],
|
||
['Intermediação Comercial', '150', '50'],
|
||
['eCommerce', '50000', '65'],
|
||
['Consultoria Financeira', '10', '75'],
|
||
['Formação', '500', '75'],
|
||
['Comunicação', '100', '15'],
|
||
['Eventos', '10', '5'],
|
||
].map(([label, customers, growthPercent]) => ({
|
||
label,
|
||
customers,
|
||
growthPercent,
|
||
basis: 'Hipótese ilustrativa do documento PN, tabela T002; não é procura demonstrada.',
|
||
})),
|
||
},
|
||
};
|
||
const market = buildComplementaryTables({}, marketInput)[0];
|
||
market.notes.push(
|
||
'Linha Desenvolvimento de aplicativos sem base numérica legível no original: não introduzida como zero. Projecções recalculadas pelas fórmulas do modelo; não se copiam totais inconsistentes.',
|
||
);
|
||
const milestones = make(
|
||
'milestones',
|
||
'Marcos — exemplo',
|
||
[
|
||
'Marco',
|
||
'Início',
|
||
'Término',
|
||
'Orçamento',
|
||
'Responsável',
|
||
'Departamento',
|
||
],
|
||
[
|
||
'Produzir Portal',
|
||
'Produzir Plano de Negócios',
|
||
'Contratar Pessoal Administrativo',
|
||
'Contratar Pessoal Vendas',
|
||
'Contratar Gestores do Portal',
|
||
].map((label) => [
|
||
label,
|
||
'2026-07-01',
|
||
'2026-07-31',
|
||
'0.00',
|
||
'Osmane Nala (exemplo do documento)',
|
||
'DG',
|
||
]),
|
||
);
|
||
const personnel = make('personnel', 'Pessoal — exemplo', headers, [
|
||
row('Folha de pagamento agregada', (_, i) => plan.years[i].payroll),
|
||
row('Encargos da folha', (_, i) => plan.years[i].payrollCharges),
|
||
]);
|
||
personnel.notes.push(
|
||
'O original não reconcilia remunerações por departamento com a folha agregada. Preservados os totais anuais aceites; quantidade e repartição por função permanecem por determinar, sem inventar trabalhadores ou salários.',
|
||
);
|
||
for (const y of result.years)
|
||
profit.notes.push(
|
||
...businessPlanWarnings({
|
||
currency: input.currency,
|
||
sales: Number(y.sales),
|
||
directCosts: Number(y.directCosts),
|
||
netProfit: Number(y.netProfit),
|
||
monthlyExpenses: y.monthlyFixedCosts,
|
||
monthlyBreakEven: y.monthlyBreakEven,
|
||
cash: Number(y.closingCash),
|
||
growthPercent: y.growthPercent ?? undefined,
|
||
assets: Number(y.closingAssets),
|
||
liabilities: Number(y.closingLiabilities),
|
||
ownAndInvestorCapital:
|
||
Number(plan.ownerCapital) + Number(plan.investorCapital),
|
||
fundingGap:
|
||
y.year === result.years[0].year
|
||
? Number(result.fundingGap)
|
||
: undefined,
|
||
}).map((w) => `Aviso não bloqueante — ${y.year}: ${w.message}`),
|
||
);
|
||
return [
|
||
startup,
|
||
market,
|
||
sales,
|
||
milestones,
|
||
personnel,
|
||
funding,
|
||
breakeven,
|
||
profit,
|
||
cash,
|
||
balance,
|
||
ratio,
|
||
];
|
||
}
|