feat: apply owner warning decisions and add editable annual planning example
This commit is contained in:
@@ -83,6 +83,7 @@ function validCurrency(value: string): boolean {
|
||||
|
||||
export type BusinessFinancialPlanInput = {
|
||||
currency: string;
|
||||
annualGrowthPercent?: string;
|
||||
presentationCurrency?: string;
|
||||
fxRate?: string;
|
||||
fxDate?: string;
|
||||
@@ -523,6 +524,7 @@ export function restoreBusinessPlanSnapshot(
|
||||
return null;
|
||||
}
|
||||
for (const field of [
|
||||
'annualGrowthPercent',
|
||||
'presentationCurrency',
|
||||
'fxRate',
|
||||
'fxDate',
|
||||
@@ -1252,6 +1254,15 @@ export function compareBusinessScenarios(input: BusinessFinancialPlanInput) {
|
||||
|
||||
/** Forecast separates invoiced sales, collections, accounting expenses and cash payments. */
|
||||
export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
|
||||
if (input.annualGrowthPercent?.trim()) {
|
||||
if (
|
||||
percentMicro(
|
||||
input.annualGrowthPercent,
|
||||
'Crescimento anual pretendido',
|
||||
) < 0n
|
||||
)
|
||||
throw new Error('Este valor não pode ser negativo.');
|
||||
}
|
||||
if (!validCurrency(input.currency))
|
||||
throw new Error('Seleccione um código de moeda ISO suportado.');
|
||||
const periods = input.periods ?? 12;
|
||||
@@ -2748,6 +2759,9 @@ export function exportBusinessPlanCsv(
|
||||
],
|
||||
['Data de exportação', generatedAt],
|
||||
['Horizonte', `${input.periods ?? 12} meses`],
|
||||
...(input.annualGrowthPercent?.trim()
|
||||
? [['Crescimento anual pretendido (%)', input.annualGrowthPercent]]
|
||||
: []),
|
||||
['Moeda de cálculo', result.currency],
|
||||
['Moeda de apresentação', result.presentationCurrency],
|
||||
[
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
export type PlanWarningLimits = {
|
||||
grossMarginPercent: number;
|
||||
cashExpenseMonths: number;
|
||||
annualGrowthPercent: number;
|
||||
creditDays: number;
|
||||
debtAssetsPercent: number;
|
||||
};
|
||||
export const defaultPlanWarningLimits: PlanWarningLimits = {
|
||||
grossMarginPercent: 15,
|
||||
cashExpenseMonths: 1,
|
||||
annualGrowthPercent: 100,
|
||||
creditDays: 90,
|
||||
debtAssetsPercent: 70,
|
||||
};
|
||||
export type PlanWarning = { id: string; message: string };
|
||||
export type PlanWarningMetrics = {
|
||||
fundingGap?: number;
|
||||
currency?: string;
|
||||
netProfit?: number;
|
||||
sales?: number;
|
||||
directCosts?: number;
|
||||
monthlyBreakEven?: number | null;
|
||||
monthlyExpenses?: number;
|
||||
cash?: number;
|
||||
growthPercent?: number;
|
||||
creditDays?: number;
|
||||
liabilities?: number;
|
||||
assets?: number;
|
||||
ownAndInvestorCapital?: number;
|
||||
};
|
||||
|
||||
/** Guidance only: warnings never change the inputs or determine validity. */
|
||||
export function businessPlanWarnings(
|
||||
metrics: PlanWarningMetrics,
|
||||
limits: PlanWarningLimits = defaultPlanWarningLimits,
|
||||
): PlanWarning[] {
|
||||
const warnings: PlanWarning[] = [];
|
||||
const add = (id: string, message: string) => warnings.push({ id, message });
|
||||
if ((metrics.fundingGap ?? 0) > 0)
|
||||
add(
|
||||
'funding',
|
||||
`O financiamento indicado não cobre o investimento necessário. Faltam ${metrics.fundingGap!.toLocaleString('pt-MZ', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}${metrics.currency ? ` ${metrics.currency}` : ''}.`,
|
||||
);
|
||||
if (metrics.netProfit !== undefined && metrics.netProfit < 0)
|
||||
add(
|
||||
'loss',
|
||||
'Neste ano o negócio dá prejuízo. Reveja as vendas ou os custos, ou confirme que é o esperado.',
|
||||
);
|
||||
if (
|
||||
metrics.sales !== undefined &&
|
||||
metrics.sales > 0 &&
|
||||
metrics.directCosts !== undefined
|
||||
) {
|
||||
if (
|
||||
(100 * (metrics.sales - metrics.directCosts)) / metrics.sales <
|
||||
limits.grossMarginPercent
|
||||
)
|
||||
add(
|
||||
'margin',
|
||||
'A margem bruta é baixa e deixa pouca folga para cobrir as despesas.',
|
||||
);
|
||||
if (
|
||||
metrics.monthlyBreakEven != null &&
|
||||
metrics.monthlyBreakEven > metrics.sales / 12
|
||||
)
|
||||
add(
|
||||
'break-even',
|
||||
'As vendas mensais médias não atingem o ponto de equilíbrio. O negócio só cobre os custos com mais vendas.',
|
||||
);
|
||||
}
|
||||
if (
|
||||
metrics.cash !== undefined &&
|
||||
metrics.monthlyExpenses !== undefined &&
|
||||
metrics.cash < metrics.monthlyExpenses * limits.cashExpenseMonths
|
||||
)
|
||||
add(
|
||||
'cash',
|
||||
'A caixa disponível cobre menos de um mês de despesas. Considere reforçar o financiamento.',
|
||||
);
|
||||
if (
|
||||
metrics.growthPercent !== undefined &&
|
||||
metrics.growthPercent > limits.annualGrowthPercent
|
||||
)
|
||||
add(
|
||||
'growth',
|
||||
'O crescimento indicado é muito elevado. Confirme que é realista.',
|
||||
);
|
||||
if (
|
||||
metrics.creditDays !== undefined &&
|
||||
metrics.creditDays > limits.creditDays
|
||||
)
|
||||
add(
|
||||
'credit',
|
||||
'Prazos de recebimento longos pressionam a caixa. Confirme o prazo indicado.',
|
||||
);
|
||||
if (
|
||||
metrics.assets !== undefined &&
|
||||
metrics.assets > 0 &&
|
||||
metrics.liabilities !== undefined &&
|
||||
(metrics.liabilities / metrics.assets) * 100 > limits.debtAssetsPercent
|
||||
)
|
||||
add(
|
||||
'debt',
|
||||
'O peso das dívidas é elevado e pode dificultar o acesso a crédito.',
|
||||
);
|
||||
if (metrics.ownAndInvestorCapital === 0)
|
||||
add(
|
||||
'capital',
|
||||
'Não indicou capital próprio nem de investidor. Todo o financiamento vem de empréstimos ou fica por definir.',
|
||||
);
|
||||
return warnings;
|
||||
}
|
||||
|
||||
export type AnnualReferencePlan = {
|
||||
startupExpenses: { label: string; amount: string }[];
|
||||
openingCash: string;
|
||||
otherCurrentAssets: string;
|
||||
longTermAssets: string;
|
||||
ownerCapital: string;
|
||||
investorCapital: string;
|
||||
loans: string;
|
||||
additionalMoney: string;
|
||||
years: {
|
||||
year: number;
|
||||
sales: string;
|
||||
directCosts: string;
|
||||
payroll: string;
|
||||
payrollCharges: string;
|
||||
otherOperatingExpenses: string;
|
||||
interest: string;
|
||||
taxes: string;
|
||||
cashReceived: string;
|
||||
cashSpent: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
/** Values explicitly supplied by the owner; currency must be chosen in the form. */
|
||||
export function newAnnualReferencePlan(): AnnualReferencePlan {
|
||||
return {
|
||||
startupExpenses: [
|
||||
{ label: 'Constituição da sociedade', amount: '25000' },
|
||||
{ label: 'Material de escritório', amount: '50000' },
|
||||
{ label: 'Seguros', amount: '0' },
|
||||
{ label: 'Rendas', amount: '0' },
|
||||
{ label: 'Computadores', amount: '250000' },
|
||||
{ label: 'Desenvolvimento do portal', amount: '1000000' },
|
||||
],
|
||||
openingCash: '90000',
|
||||
otherCurrentAssets: '150000',
|
||||
longTermAssets: '260250',
|
||||
ownerCapital: '0',
|
||||
investorCapital: '0',
|
||||
loans: '0',
|
||||
additionalMoney: '0',
|
||||
years: [
|
||||
{
|
||||
year: 2025,
|
||||
sales: '14537',
|
||||
directCosts: '12538',
|
||||
payroll: '2100',
|
||||
payrollCharges: '315',
|
||||
otherOperatingExpenses: '0',
|
||||
interest: '0',
|
||||
taxes: '0',
|
||||
cashReceived: '16539',
|
||||
cashSpent: '15783',
|
||||
},
|
||||
{
|
||||
year: 2026,
|
||||
sales: '21500',
|
||||
directCosts: '16200',
|
||||
payroll: '2800',
|
||||
payrollCharges: '420',
|
||||
otherOperatingExpenses: '0',
|
||||
interest: '0',
|
||||
taxes: '624',
|
||||
cashReceived: '24930',
|
||||
cashSpent: '23923',
|
||||
},
|
||||
{
|
||||
year: 2027,
|
||||
sales: '23875',
|
||||
directCosts: '18325',
|
||||
payroll: '2800',
|
||||
payrollCharges: '420',
|
||||
otherOperatingExpenses: '0',
|
||||
interest: '0',
|
||||
taxes: '699',
|
||||
cashReceived: '27857',
|
||||
cashSpent: '26122',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function money(value: string): bigint {
|
||||
if (value.length > 40 || !/^\d+(?:\.\d{1,2})?$/.test(value.trim()))
|
||||
throw new Error(
|
||||
value.trim() === ''
|
||||
? 'Preencha este campo para continuar.'
|
||||
: Number(value) < 0
|
||||
? 'Este valor não pode ser negativo.'
|
||||
: 'Introduza apenas números (ex.: 25.000).',
|
||||
);
|
||||
const [whole, fraction = ''] = value.trim().split('.');
|
||||
return BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0'));
|
||||
}
|
||||
function decimal(value: bigint): string {
|
||||
const abs = value < 0n ? -value : value;
|
||||
return `${value < 0n ? '-' : ''}${abs / 100n}.${String(abs % 100n).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export function calculateAnnualReferencePlan(plan: AnnualReferencePlan) {
|
||||
const startupExpenses = plan.startupExpenses.reduce(
|
||||
(sum, row) => sum + money(row.amount),
|
||||
0n,
|
||||
);
|
||||
const openingCash = money(plan.openingCash);
|
||||
const assets =
|
||||
openingCash +
|
||||
money(plan.otherCurrentAssets) +
|
||||
money(plan.longTermAssets);
|
||||
const requiredFunding = startupExpenses + assets;
|
||||
const availableFunding =
|
||||
money(plan.ownerCapital) +
|
||||
money(plan.investorCapital) +
|
||||
money(plan.loans) +
|
||||
money(plan.additionalMoney);
|
||||
let cash = openingCash;
|
||||
const years = plan.years.map((year, index) => {
|
||||
const sales = money(year.sales),
|
||||
costs = money(year.directCosts);
|
||||
if (sales === 0n && costs > 0n)
|
||||
throw new Error(
|
||||
'Indique as vendas previstas para calcular a margem e o ponto de equilíbrio.',
|
||||
);
|
||||
if (sales > 0n && costs >= sales)
|
||||
throw new Error(
|
||||
'Com este custo variável não há margem para cobrir os custos fixos. Reveja o custo variável ou o preço.',
|
||||
);
|
||||
const grossMargin = sales - costs;
|
||||
const operatingExpenses =
|
||||
money(year.payroll) +
|
||||
money(year.payrollCharges) +
|
||||
money(year.otherOperatingExpenses);
|
||||
const operatingProfit = grossMargin - operatingExpenses;
|
||||
const netProfit =
|
||||
operatingProfit - money(year.interest) - money(year.taxes);
|
||||
const cashFlow = money(year.cashReceived) - money(year.cashSpent);
|
||||
cash += cashFlow;
|
||||
// Keep the unrounded gross-margin fraction in the break-even formula.
|
||||
const monthlyBreakEven =
|
||||
grossMargin > 0n
|
||||
? (Number(operatingExpenses) * Number(sales)) /
|
||||
(1200 * Number(grossMargin))
|
||||
: null;
|
||||
const previousSales =
|
||||
index > 0 ? money(plan.years[index - 1].sales) : null;
|
||||
const growthPercent =
|
||||
previousSales !== null && previousSales > 0n
|
||||
? (Number(sales - previousSales) / Number(previousSales)) * 100
|
||||
: null;
|
||||
return {
|
||||
year: year.year,
|
||||
sales: decimal(sales),
|
||||
directCosts: decimal(costs),
|
||||
grossMargin: decimal(grossMargin),
|
||||
grossMarginPercent:
|
||||
sales > 0n ? (Number(grossMargin) / Number(sales)) * 100 : null,
|
||||
operatingExpenses: decimal(operatingExpenses),
|
||||
operatingProfit: decimal(operatingProfit),
|
||||
netProfit: decimal(netProfit),
|
||||
netMarginPercent:
|
||||
sales > 0n ? (Number(netProfit) / Number(sales)) * 100 : null,
|
||||
cashFlow: decimal(cashFlow),
|
||||
closingCash: decimal(cash),
|
||||
monthlyFixedCosts: Number(operatingExpenses) / 1200,
|
||||
monthlyBreakEven,
|
||||
growthPercent,
|
||||
};
|
||||
});
|
||||
return {
|
||||
startupExpenses: decimal(startupExpenses),
|
||||
assets: decimal(assets),
|
||||
requiredFunding: decimal(requiredFunding),
|
||||
availableFunding: decimal(availableFunding),
|
||||
fundingGap: decimal(
|
||||
requiredFunding > availableFunding
|
||||
? requiredFunding - availableFunding
|
||||
: 0n,
|
||||
),
|
||||
years,
|
||||
monthlyStatus: 'por reconciliar' as const,
|
||||
};
|
||||
}
|
||||
@@ -127,7 +127,7 @@ export function formatDossierReportValue(
|
||||
}
|
||||
if (field === 'Reconciliação do financiamento') {
|
||||
const states: Record<string, string> = {
|
||||
shortfall: 'Financiamento insuficiente',
|
||||
shortfall: 'Financiamento insuficiente — aviso não bloqueante',
|
||||
surplus: 'Fontes superiores aos usos previstos',
|
||||
balanced: 'Fontes e usos equilibrados',
|
||||
unknown: 'Informação insuficiente',
|
||||
|
||||
@@ -561,6 +561,14 @@ export function buildProjectDossierRows(
|
||||
const forecast = forecastBusinessPlan(businessPlan);
|
||||
const source =
|
||||
'Estimativa calculada pelo plano financeiro a partir de pressupostos declarados; não é demonstração contabilística nem resultado confirmado';
|
||||
if (businessPlan.annualGrowthPercent?.trim()) {
|
||||
rows.push([
|
||||
'Plano financeiro',
|
||||
'Crescimento anual pretendido',
|
||||
`${businessPlan.annualGrowthPercent}%`,
|
||||
'Meta declarada pelo utilizador; não substitui as agendas de vendas introduzidas',
|
||||
]);
|
||||
}
|
||||
rows.push(
|
||||
[
|
||||
'Plano financeiro',
|
||||
|
||||
Reference in New Issue
Block a user