feat(finance): validate opt-in day terms without supplier advances

This commit is contained in:
2026-11-21 10:21:15 +02:00
parent be7196d246
commit 1f44a63caf
23 changed files with 1268 additions and 46 deletions
+179 -45
View File
@@ -1,3 +1,8 @@
import {
buildDayTermSchedule,
isDayTerms,
type DayTerms,
} from './financial-day-terms.ts';
import { csvCell } from './csv.js';
import { calculateStartupAssetRequirements } from './startup-asset-requirements.ts';
@@ -83,6 +88,8 @@ function validCurrency(value: string): boolean {
}
export type BusinessFinancialPlanInput = {
/** Explicit opt-in. Missing keeps all historical calculations unchanged. */
dayTerms?: DayTerms;
economicClassification?: {
code: string;
revision: string;
@@ -202,22 +209,25 @@ export function serializeBusinessPlanSnapshot(
plan: BusinessFinancialPlanInput,
): string {
const snapshot = JSON.stringify({
version: plan.startupAssetRequirements
? 19
: [
'applyAnnualGrowth',
'creditTermDays',
'dividendsByPeriod',
'operatingExpenseLines',
'fundingBreakdown',
'reportSource',
].some(
(key) =>
plan[key as keyof BusinessFinancialPlanInput] !==
undefined,
)
? 18
: 17,
version:
plan.dayTerms !== undefined
? 20
: plan.startupAssetRequirements
? 19
: [
'applyAnnualGrowth',
'creditTermDays',
'dividendsByPeriod',
'operatingExpenseLines',
'fundingBreakdown',
'reportSource',
].some(
(key) =>
plan[key as keyof BusinessFinancialPlanInput] !==
undefined,
)
? 18
: 17,
plan: {
...plan,
...(plan.useSupplierPaymentTerms === true
@@ -301,12 +311,18 @@ export function restoreBusinessPlanSnapshot(
decoded.version !== 16 &&
decoded.version !== 17 &&
decoded.version !== 18 &&
decoded.version !== 19) ||
decoded.version !== 19 &&
decoded.version !== 20) ||
!decoded.plan ||
typeof decoded.plan !== 'object'
)
return null;
const plan = decoded.plan as Record<string, unknown>;
if (
plan.dayTerms !== undefined &&
(decoded.version !== 20 || !isDayTerms(plan.dayTerms))
)
return null;
if (
decoded.version < 18 &&
[
@@ -439,7 +455,7 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[12, 13, 14, 15, 16, 17].includes(Number(decoded.version)) &&
[12, 13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) &&
(!Object.hasOwn(plan, 'inventoryPurchaseSchedule') ||
!Object.hasOwn(plan, 'useInventoryPurchaseSchedule') ||
typeof plan.useInventoryPurchaseSchedule !== 'boolean')
@@ -450,7 +466,9 @@ export function restoreBusinessPlanSnapshot(
plan.inventoryPurchaseSchedule !== null
) {
if (
![12, 13, 14, 15, 16, 17].includes(Number(decoded.version)) ||
![12, 13, 14, 15, 16, 17, 20].includes(
Number(decoded.version),
) ||
!Array.isArray(plan.inventoryPurchaseSchedule) ||
plan.inventoryPurchaseSchedule.length < Number(plan.periods) ||
plan.inventoryPurchaseSchedule.length > 60 ||
@@ -473,14 +491,14 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[13, 14, 15, 16, 17].includes(Number(decoded.version)) &&
[13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) &&
!Object.hasOwn(plan, 'monthlyVariableCostPaymentsByPeriod')
)
return null;
if (
plan.monthlyVariableCostPaymentsByPeriod !== undefined &&
plan.monthlyVariableCostPaymentsByPeriod !== null &&
(![13, 14, 15, 16, 17].includes(Number(decoded.version)) ||
(![13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) ||
!Array.isArray(plan.monthlyVariableCostPaymentsByPeriod) ||
plan.monthlyVariableCostPaymentsByPeriod.length <
Number(plan.periods) ||
@@ -545,7 +563,7 @@ export function restoreBusinessPlanSnapshot(
if (openingCollectionRate < 0n || openingCollectionRate > 100_000_000n)
return null;
if (
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17].includes(
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
Number(decoded.version),
)
) {
@@ -618,7 +636,7 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17].includes(
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
Number(decoded.version),
)
) {
@@ -657,7 +675,7 @@ export function restoreBusinessPlanSnapshot(
const schedule = plan[field];
if (
schedule !== undefined &&
(![11, 12, 13, 14, 15, 16, 17].includes(
(![11, 12, 13, 14, 15, 16, 17, 20].includes(
Number(decoded.version),
) ||
!Array.isArray(schedule) ||
@@ -747,7 +765,7 @@ export function restoreBusinessPlanSnapshot(
const costSchedule = productData.unitVariableCostByPeriod;
const validMoneySchedule = (values: unknown) =>
values === undefined ||
([10, 11, 12, 13, 14, 15, 16, 17].includes(
([10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
Number(decoded.version),
) &&
Array.isArray(values) &&
@@ -756,7 +774,7 @@ export function restoreBusinessPlanSnapshot(
values.every((value) => typeof value === 'string'));
return (
(schedule !== undefined &&
(![9, 10, 11, 12, 13, 14, 15, 16, 17].includes(
(![9, 10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
Number(decoded.version),
) ||
!Array.isArray(schedule) ||
@@ -795,7 +813,7 @@ export function restoreBusinessPlanSnapshot(
entry.paymentLagMonths < 0 ||
entry.paymentLagMonths > 12)) ||
(entry.paymentInstallments !== undefined &&
(![16, 17].includes(
(![16, 17, 20].includes(
Number(decoded.version),
) ||
!Array.isArray(
@@ -853,7 +871,7 @@ export function restoreBusinessPlanSnapshot(
})
)
return null;
return {
const restored = {
...plan,
inventoryPurchaseLeadMonths: Number(
plan.inventoryPurchaseLeadMonths ?? 0,
@@ -915,6 +933,9 @@ export function restoreBusinessPlanSnapshot(
? plan.monthlyVariableCostPaymentsByPeriod.map(String)
: null,
} as unknown as BusinessFinancialPlanInput;
if (restored.dayTerms && !options.editable)
forecastBusinessPlan(restored);
return restored;
} catch {
return null;
}
@@ -1439,7 +1460,47 @@ export function compareBusinessScenarios(input: BusinessFinancialPlanInput) {
}
/** Forecast separates invoiced sales, collections, accounting expenses and cash payments. */
type ActiveDayTerms = ReturnType<typeof buildDayTermSchedule> & {
config: DayTerms;
};
export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
const config = input.dayTerms;
if (config !== undefined && !isDayTerms(config))
throw new Error('Prazos em dias: estrutura inválida.');
if (!config || !(config.sales || config.purchases || config.services))
return forecastBusinessPlanBase(input);
// First pass obtains economic recognition from the unchanged calculator. The second
// replaces only opted-in cash schedules. Neither pass mutates stored/manual inputs.
const economic = forecastBusinessPlanBase(input);
if (!input.reportAssumptions?.startYear?.trim())
throw new Error(
'Prazos em dias — Ano inicial: preencha o ano do relatório.',
);
const day = buildDayTermSchedule(
config,
Number(input.reportAssumptions.startYear),
economic.rows.length,
{
sales: economic.rows.map((r) => cents(r.revenue, 'Vendas')),
purchases: economic.rows.map((r) =>
r.inventoryReceipts === null
? null
: cents(r.inventoryReceipts, 'Recepções'),
),
services: economic.rows.map((r) =>
cents(r.operatingExpenses, 'Serviços reconhecidos'),
),
},
cents,
);
return forecastBusinessPlanBase(input, { ...day, config });
}
function forecastBusinessPlanBase(
input: BusinessFinancialPlanInput,
day?: ActiveDayTerms,
) {
if (input.startupAssetRequirements) {
const needs = calculateStartupAssetRequirements(input);
if (
@@ -2243,10 +2304,13 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
const rows = [];
for (let month = 1; month <= periods; month++) {
const periodVariableCostPayment =
variableCostPaymentsByPeriod[month - 1];
const periodVariableCostPayment = day?.config.purchases
? day.schedules.purchases[month - 1]
: variableCostPaymentsByPeriod[month - 1];
const periodOperatingExpense = operatingExpenseByPeriod[month - 1];
const periodOperatingPayment = operatingPaymentsByPeriod[month - 1];
const periodOperatingPayment = day?.config.services
? day.schedules.services[month - 1]
: operatingPaymentsByPeriod[month - 1];
const periodPayrollExpense = payrollExpenseByPeriod[month - 1];
const periodPayrollPayment = payrollPaymentsByPeriod[month - 1];
const revenue = revenueByPeriod[month - 1];
@@ -2368,7 +2432,14 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
let salesCollections: bigint | null = null;
let salesScheduledCollections: bigint | null = null;
let salesRecoveryCollections: bigint | null = null;
if (salesCollectionLagMonths !== null) {
if (day?.config.sales) {
salesCollections = day.schedules.sales[month - 1];
salesScheduledCollections = salesCollections;
salesRecoveryCollections = 0n;
salesReceivables += revenue - salesCollections;
totalSalesCollections += salesCollections;
totalScheduledSalesCollections += salesCollections;
} else if (salesCollectionLagMonths !== null) {
const collectionMonth = month + salesCollectionLagMonths;
const scheduledCollection =
(revenue * salesCollectionRate + 50_000_000n) / 100_000_000n;
@@ -2415,7 +2486,13 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
totalSalesRecoveryCollections += salesRecoveryCollections;
totalSalesCollections += salesCollections;
}
const totalCollections = monthlyCollections + (salesCollections ?? 0n);
const activeManualCollections =
day?.config.sales &&
input.reportAssumptions?.manualCollectionsKind !== 'other_income'
? 0n
: monthlyCollections;
const totalCollections =
activeManualCollections + (salesCollections ?? 0n);
const legacyOpeningReceivablesCollections =
month === openingReceivablesCollectionMonth
? openingReceivablesCollectionAmount
@@ -2463,7 +2540,9 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
? null
: format(salesRecoveryCollections),
otherCollections:
salesCollections === null ? null : format(monthlyCollections),
salesCollections === null
? null
: format(activeManualCollections),
salesReceivablesClosing:
salesCollections === null ? null : format(salesReceivables),
variableCost: format(costOfSales),
@@ -2572,8 +2651,9 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
paymentLagMonths: order.paymentLagMonths,
}),
),
paymentSchedule:
supplierPaymentSchedules?.[index] ?? null,
paymentSchedule: day?.config.purchases
? null
: (supplierPaymentSchedules?.[index] ?? null),
totalPurchases: format(
productStockInputs[index].orders!.reduce(
(sum, order) => sum + order.amount,
@@ -2651,26 +2731,36 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
amount: format(installment.amount),
})),
totalSalesCollections:
salesCollectionLagMonths === null
salesCollectionLagMonths === null && !day?.config.sales
? null
: format(totalSalesCollections),
totalScheduledSalesCollections:
salesCollectionLagMonths === null
salesCollectionLagMonths === null && !day?.config.sales
? null
: format(totalScheduledSalesCollections),
totalSalesRecoveryCollections:
salesCollectionLagMonths === null
salesCollectionLagMonths === null && !day?.config.sales
? null
: format(totalSalesRecoveryCollections),
salesReceivablesAtEnd:
salesCollectionLagMonths === null ? null : format(salesReceivables),
salesCollectionLagMonths === null && !day?.config.sales
? null
: format(salesReceivables),
salesCollectionLagMonths,
salesCollectionPercent:
salesCollectionLagMonths === null ? null : salesCollectionPercent,
salesCollectionLagMonths === null && !day?.config.sales
? null
: salesCollectionPercent,
totalPayments: format(totalOperatingPayments),
supplierPaymentsOutstandingAtEnd: useSupplierPaymentTerms
? format(supplierPaymentsOutstanding)
: null,
supplierPaymentsOutstandingAtEnd: day?.config.purchases
? format(
day.events
.filter((e) => e.kind === 'purchases' && e.outsideHorizon)
.reduce((sum, e) => sum + BigInt(e.amount), 0n),
)
: useSupplierPaymentTerms
? format(supplierPaymentsOutstanding)
: null,
totalProfitBeforeTax: format(totalProfitBeforeTax),
endingCash: format(cash),
inventoryProjection,
@@ -2940,7 +3030,19 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
),
),
};
return { ...output, presentationCurrency, conversion };
return {
...output,
presentationCurrency,
conversion,
...(day
? {
dayTermEvents: day.events.map((e) => ({
...e,
amount: format(BigInt(e.amount)),
})),
}
: {}),
};
}
/** Reproducible local report: original assumptions, declared FX basis, and the same forecast totals. */
@@ -3495,6 +3597,38 @@ export function exportBusinessPlanCsv(
'Estimativa sem aconselhamento fiscal, parâmetros legais, sazonalidade, inflação ou validação contabilística. Moeda original preservada.',
],
];
if (result.dayTermEvents) {
rows.push(
[],
[
'Prazos em dias — agendas anteriores das categorias seleccionadas conservadas inactivas',
],
[
'Categoria',
'Origem',
'Parcela',
'Reconhecimento',
'Origem do prazo',
'Vencimento',
'Montante',
'Precisão',
'Horizonte',
],
...result.dayTermEvents.map((e) => [
e.kind,
e.originId,
e.parcelId,
e.recognition,
e.origin,
e.due,
e.amount,
e.approximate ? 'aproximação mensal' : 'datas individuais',
e.outsideHorizon
? 'fora do horizonte, sem caixa neste plano'
: `mês ${e.dueMonth}`,
]),
);
}
return `\uFEFF${rows
.map((row) => row.map(csvCell).join(','))
.join('\r\n')}`;