238 lines
8.9 KiB
TypeScript
238 lines
8.9 KiB
TypeScript
import type { BusinessFinancialPlanInput } from './business-financial-plan.ts';
|
|
import {
|
|
businessPlanWarnings,
|
|
type PlanWarningMetrics,
|
|
} from './business-plan-guidance.ts';
|
|
import {
|
|
displayReportMoney,
|
|
type InvestmentReportTable,
|
|
} from './integral-financial-report.ts';
|
|
|
|
/** Only use determined values from the same tables/version, never replace missing amounts by zero. */
|
|
export function financialPlanWarningMetrics(
|
|
plan: BusinessFinancialPlanInput,
|
|
tables: InvestmentReportTable[],
|
|
) {
|
|
const periods = plan.periods ?? 12;
|
|
const read = (id: string, label: string, column: number) => {
|
|
const t = tables.find((t) => t.id === id);
|
|
if (!t || t.issues.length) return undefined;
|
|
const value = t.rows.find((r) => r[0] === label)?.[column];
|
|
return value && /^-?\d+(?:\.\d{1,2})?$/.test(value)
|
|
? Number(value)
|
|
: undefined;
|
|
};
|
|
return Array.from({ length: Math.ceil(periods / 12) }, (_, year) => {
|
|
const col = periods + year + 1;
|
|
const count = Math.min(12, periods - year * 12);
|
|
const sales = read('sales', 'Vendas totais', col);
|
|
const costs = read('profit-loss', 'Custo directo', col);
|
|
const operating = read('profit-loss', 'Despesas operacionais', col);
|
|
const payroll = read('profit-loss', 'Pessoal', col);
|
|
const depreciation = read('profit-loss', 'Depreciação', col);
|
|
const fixed =
|
|
operating !== undefined &&
|
|
payroll !== undefined &&
|
|
depreciation !== undefined
|
|
? operating + payroll + depreciation
|
|
: undefined;
|
|
const previous = year
|
|
? read('sales', 'Vendas totais', col - 1)
|
|
: undefined;
|
|
const metrics: PlanWarningMetrics = {
|
|
currency: plan.currency,
|
|
creditDays: inputCreditDays(plan.creditTermDays),
|
|
fundingGap:
|
|
year === 0
|
|
? (read(
|
|
'funding',
|
|
'Falta para a reserva requerida (projecção)',
|
|
1,
|
|
) ?? read('funding', 'Diferença por financiar', 1))
|
|
: undefined,
|
|
netProfit: read('profit-loss', 'Lucro líquido', col),
|
|
sales,
|
|
directCosts: costs,
|
|
monthlyExpenses: fixed === undefined ? undefined : fixed / count,
|
|
monthlyBreakEven:
|
|
sales &&
|
|
costs !== undefined &&
|
|
fixed !== undefined &&
|
|
sales > costs
|
|
? fixed / count / ((sales - costs) / sales)
|
|
: undefined,
|
|
cash: read('cashflow', 'Caixa final', col),
|
|
growthPercent:
|
|
previous && sales !== undefined && count === 12
|
|
? (sales / previous - 1) * 100
|
|
: year === 0 && plan.annualGrowthPercent?.trim()
|
|
? Number(plan.annualGrowthPercent)
|
|
: undefined,
|
|
assets: read('balance', 'Total do activo', col),
|
|
liabilities: read('balance', 'Total do passivo', col),
|
|
ownAndInvestorCapital: /^\d+(?:\.\d{1,2})?$/.test(plan.equity)
|
|
? Number(plan.equity)
|
|
: undefined,
|
|
};
|
|
return {
|
|
year: Number(plan.reportAssumptions?.startYear) + year,
|
|
metrics,
|
|
count,
|
|
};
|
|
});
|
|
}
|
|
|
|
/** Presentation of already-calculated monthly values; never produces or changes amounts. */
|
|
function periodGuidance(
|
|
plan: BusinessFinancialPlanInput,
|
|
tables: InvestmentReportTable[],
|
|
) {
|
|
if (plan.reportSource === 'annual_example') return [];
|
|
const salesTable = tables.find((t) => t.id === 'sales');
|
|
const costsTable = tables.find((t) => t.id === 'profit-loss');
|
|
const read = (
|
|
table: InvestmentReportTable | undefined,
|
|
label: string,
|
|
col: number,
|
|
) => {
|
|
if (!table || table.issues.length) return undefined;
|
|
const value = table?.rows.find((row) => row[0] === label)?.[col];
|
|
return typeof value === 'string' && /^-?\d+\.\d{2}$/.test(value)
|
|
? BigInt(value.replace('.', ''))
|
|
: undefined;
|
|
};
|
|
const noContribution: string[] = [],
|
|
missingSales: string[] = [];
|
|
for (let col = 1; col <= (plan.periods ?? 12); col++) {
|
|
const sales = read(salesTable, 'Vendas totais', col),
|
|
cost = read(costsTable, 'Custo directo', col);
|
|
const period = (salesTable?.headers[col] ?? `Mês ${col}`).replace(
|
|
/^(\d{4})-(\d{2})$/,
|
|
'$2/$1',
|
|
);
|
|
if (
|
|
sales !== undefined &&
|
|
sales > 0n &&
|
|
cost !== undefined &&
|
|
cost >= sales
|
|
)
|
|
noContribution.push(period);
|
|
if (
|
|
sales === 0n &&
|
|
[
|
|
'Custo directo',
|
|
'Despesas operacionais',
|
|
'Pessoal',
|
|
'Depreciação',
|
|
'Juros',
|
|
'Imposto estimado',
|
|
].some((label) => {
|
|
const value = read(costsTable, label, col);
|
|
return value !== undefined && value > 0n;
|
|
})
|
|
)
|
|
missingSales.push(period);
|
|
}
|
|
return [
|
|
...(noContribution.length
|
|
? [
|
|
{
|
|
id: 'period-no-contribution',
|
|
message: `Com este custo variável não há margem para cobrir os custos fixos. Reveja o custo variável ou o preço. Períodos a rever: ${noContribution.join(', ')}.`,
|
|
},
|
|
]
|
|
: []),
|
|
...(missingSales.length
|
|
? [
|
|
{
|
|
id: 'period-sales-required',
|
|
message: `Indique as vendas previstas para calcular a margem e o ponto de equilíbrio. Períodos a rever: ${missingSales.join(', ')}.`,
|
|
},
|
|
]
|
|
: []),
|
|
];
|
|
}
|
|
|
|
export function financialPlanWarnings(
|
|
plan: BusinessFinancialPlanInput,
|
|
tables: InvestmentReportTable[],
|
|
) {
|
|
const periodWarnings = periodGuidance(plan, tables);
|
|
const annualWarnings = financialPlanWarningMetrics(plan, tables).flatMap(
|
|
({ year, metrics, count }) => {
|
|
// The warning helper compares a full year's sales to a monthly threshold.
|
|
const adjusted = {
|
|
...metrics,
|
|
sales:
|
|
metrics.sales === undefined
|
|
? undefined
|
|
: (metrics.sales * 12) / count,
|
|
directCosts:
|
|
metrics.directCosts === undefined
|
|
? undefined
|
|
: (metrics.directCosts * 12) / count,
|
|
};
|
|
const warnings = businessPlanWarnings(
|
|
adjusted,
|
|
plan.warningLimits,
|
|
).map((w) => ({
|
|
...w,
|
|
id: `${year}-${w.id}`,
|
|
message: `${year}: ${w.message}`,
|
|
}));
|
|
if (
|
|
inputCreditDays(plan.creditTermDays) === undefined &&
|
|
(plan.salesCollectionLagMonths ?? 0) > 3
|
|
)
|
|
warnings.push({
|
|
id: `${year}-credit`,
|
|
message: `${year}: O prazo de recebimento é superior a três meses no modelo mensal e pressiona a caixa. Confirme o prazo indicado.`,
|
|
});
|
|
return warnings;
|
|
},
|
|
);
|
|
const cashflow = tables.find((table) => table.id === 'cashflow');
|
|
const closing = cashflow?.rows.find((row) => row[0] === 'Caixa final');
|
|
if (!cashflow || cashflow.issues.length || !closing)
|
|
return [...annualWarnings, ...periodWarnings];
|
|
const months = [
|
|
'Janeiro',
|
|
'Fevereiro',
|
|
'Março',
|
|
'Abril',
|
|
'Maio',
|
|
'Junho',
|
|
'Julho',
|
|
'Agosto',
|
|
'Setembro',
|
|
'Outubro',
|
|
'Novembro',
|
|
'Dezembro',
|
|
];
|
|
const monthlyWarnings = closing
|
|
.slice(1, (plan.periods ?? 12) + 1)
|
|
.flatMap((value, index) => {
|
|
const period = cashflow.headers[index + 1];
|
|
const calendar = /^(\d{4})-(0[1-9]|1[0-2])$/.exec(period ?? '');
|
|
if (
|
|
!calendar ||
|
|
!/^-\d+\.\d{2}$/.test(value) ||
|
|
BigInt(value.replace('.', '')) >= 0n
|
|
)
|
|
return [];
|
|
return [
|
|
{
|
|
id: `cash-negative-${period}`,
|
|
message: `O saldo de caixa fica negativo em ${months[Number(calendar[2]) - 1]} de ${calendar[1]}: ${displayReportMoney(value)} ${plan.currency}. Reveja os pagamentos, os prazos de crédito ou o financiamento.`,
|
|
},
|
|
];
|
|
});
|
|
return [...annualWarnings, ...periodWarnings, ...monthlyWarnings];
|
|
}
|
|
|
|
function inputCreditDays(value: string | undefined) {
|
|
return value && /^\d+$/.test(value) && Number(value) <= 365
|
|
? Number(value)
|
|
: undefined;
|
|
}
|