Files
Investidor-V2/resources/js/lib/financial-plan-warnings.ts
T

162 lines
6.2 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,
};
});
}
export function financialPlanWarnings(
plan: BusinessFinancialPlanInput,
tables: InvestmentReportTable[],
) {
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).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;
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, ...monthlyWarnings];
}
function inputCreditDays(value: string | undefined) {
return value && /^\d+$/.test(value) && Number(value) <= 365
? Number(value)
: undefined;
}