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')}`;
+205
View File
@@ -0,0 +1,205 @@
export type DayTermKind = 'sales' | 'purchases' | 'services';
export type DayTermOperation = {
originId: string;
parcelId: string;
kind: DayTermKind;
month: number;
amount: string;
recognitionBasis: 'monthly' | 'date' | 'unknown';
recognitionDate: string;
originBasis: 'recognition' | 'date' | 'unknown';
originDate: string;
termDays: string;
};
export type DayTerms = {
sales: boolean;
purchases: boolean;
services: boolean;
operations: DayTermOperation[];
};
export const dayTermLabels: Record<DayTermKind, string> = {
sales: 'Vendas e prestações',
purchases: 'Mercadorias recebidas',
services: 'Serviços adquiridos reconhecidos',
};
export function isDayTerms(value: unknown): value is DayTerms {
if (!value || typeof value !== 'object') return false;
const c = value as DayTerms;
return (
['sales', 'purchases', 'services'].every(
(k) => typeof c[k as DayTermKind] === 'boolean',
) &&
Array.isArray(c.operations) &&
c.operations.length <= 240 &&
c.operations.every(
(o) =>
o &&
Object.hasOwn(dayTermLabels, o.kind) &&
Number.isSafeInteger(o.month) &&
o.month >= 1 &&
o.month <= 60 &&
[
'originId',
'parcelId',
'amount',
'recognitionDate',
'originDate',
'termDays',
].every(
(k) =>
typeof o[k as keyof DayTermOperation] === 'string' &&
String(o[k as keyof DayTermOperation]).length <= 160,
) &&
['monthly', 'date', 'unknown'].includes(o.recognitionBasis) &&
['recognition', 'date', 'unknown'].includes(o.originBasis),
)
);
}
function civilDate(value: string): Date | null {
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
const d = new Date(value + 'T00:00:00.000Z');
return Number.isFinite(d.getTime()) &&
d.toISOString().slice(0, 10) === value
? d
: null;
}
const iso = (d: Date) => d.toISOString().slice(0, 10);
/** Only opted-in channels replace their complete cash agenda. No legacy input is mutated. */
export function buildDayTermSchedule(
config: DayTerms,
year: number,
periods: number,
recognized: Record<DayTermKind, (bigint | null)[]>,
parseAmount: (value: string, label: string) => bigint,
) {
if (!isDayTerms(config))
throw new Error(
'Prazos em dias: estrutura inválida. Reveja operações e parcelas.',
);
if (!Number.isSafeInteger(year) || year < 1900 || year > 9993)
throw new Error(
'Prazos em dias — Ano inicial: indique o ano do relatório entre 1900 e 9993.',
);
const schedules: Record<DayTermKind, bigint[]> = {
sales: Array(periods).fill(0n),
purchases: Array(periods).fill(0n),
services: Array(periods).fill(0n),
};
const amounts: Record<DayTermKind, bigint[]> = {
sales: Array(periods).fill(0n),
purchases: Array(periods).fill(0n),
services: Array(periods).fill(0n),
};
const seen = new Set<string>();
const origins = new Map<string, string>();
const events = config.operations
.filter((o) => config[o.kind])
.map((o) => {
const label = `Prazos em dias — ${dayTermLabels[o.kind]}, origem ${o.originId || 'por preencher'}, parcela ${o.parcelId || 'por preencher'}`;
const fail = (message: string): never => {
throw new Error(`${label}: ${message}`);
};
if (!o.originId.trim() || !o.parcelId.trim())
fail('preencha a origem e a parcela para impedir duplicações.');
const key = JSON.stringify([
o.kind,
o.originId.trim(),
o.parcelId.trim(),
]);
if (seen.has(key))
fail(
'parcela duplicada; conserve apenas um movimento da mesma origem/parcela.',
);
seen.add(key);
if (o.month > periods)
fail(
'mês de reconhecimento fora do horizonte; reveja o mês ou use a agenda manual.',
);
const start = new Date(Date.UTC(year, o.month - 1, 1));
const recognition =
o.recognitionBasis === 'monthly'
? new Date(Date.UTC(year, o.month, 0))
: o.recognitionBasis === 'date'
? civilDate(o.recognitionDate)
: null;
if (!recognition)
fail(
'data de reconhecimento insuficiente ou inválida; indique uma data ou escolha explicitamente a aproximação mensal. Operação excluída do cálculo automático.',
);
const r = recognition!;
if (
r.getUTCFullYear() !== start.getUTCFullYear() ||
r.getUTCMonth() !== start.getUTCMonth()
)
fail(
'data de reconhecimento não pertence ao mês económico indicado; corrija a data ou o mês.',
);
const origin =
o.originBasis === 'recognition'
? r
: o.originBasis === 'date'
? civilDate(o.originDate)
: null;
if (!origin)
fail(
'data de origem do prazo insuficiente ou inválida; indique o evento contratual ou escolha reconhecimento. Operação excluída do cálculo automático.',
);
if (o.kind === 'sales' && iso(origin!) !== iso(r))
fail(
'origem do recebimento deve ser a venda/prestação reconhecida; corrija a origem.',
);
if (!/^\d+$/.test(o.termDays) || Number(o.termDays) > 365)
fail(
'Prazo (dias): indique um inteiro entre 0 e 365; vazio não significa zero.',
);
const due = new Date(origin!.getTime());
due.setUTCDate(due.getUTCDate() + Number(o.termDays));
if (due < r)
fail(
'vencimento anterior ao reconhecimento: antecipação excluída de F20-A. Use a agenda manual existente; adiantamentos identificados dependem de F20-B.',
);
const amount = parseAmount(o.amount, `${label} — Montante`);
const originKey = JSON.stringify([o.kind, o.originId.trim()]);
const identity = JSON.stringify([
o.month,
iso(r),
o.recognitionBasis,
]);
if (origins.has(originKey) && origins.get(originKey) !== identity)
fail(
'parcelas da mesma origem têm reconhecimentos diferentes; confira origem, mês e data.',
);
origins.set(originKey, identity);
amounts[o.kind][o.month - 1] += amount;
const dueMonth =
(due.getUTCFullYear() - year) * 12 + due.getUTCMonth() + 1;
if (dueMonth <= periods) schedules[o.kind][dueMonth - 1] += amount;
return {
...o,
amount: amount.toString(),
recognition: iso(r),
origin: iso(origin!),
due: iso(due),
dueMonth,
approximate: o.recognitionBasis === 'monthly',
outsideHorizon: dueMonth > periods,
};
});
for (const kind of Object.keys(dayTermLabels) as DayTermKind[]) {
if (!config[kind]) continue;
for (let i = 0; i < periods; i++) {
if (recognized[kind][i] === null)
throw new Error(
`Prazos em dias — ${dayTermLabels[kind]}, mês ${i + 1}: reconhecimento indeterminado; preencha a agenda económica antes de activar este modo.`,
);
if (amounts[kind][i] !== recognized[kind][i])
throw new Error(
`Prazos em dias — ${dayTermLabels[kind]}, mês ${i + 1}: a soma dos montantes das origens/parcelas deve coincidir com o valor reconhecido. Corrija a distribuição; não some uma coorte às operações já individualizadas.`,
);
}
}
return { schedules, events };
}
@@ -224,6 +224,7 @@ export function buildIntegralFinancialTables(
'Escolha o tratamento das subvenções: capital ou passivo diferido.',
);
if (
!plan.dayTerms?.sales &&
cents(plan.monthlyCollections) > 0n &&
!['sales', 'other_income'].includes(a.manualCollectionsKind)
)
@@ -784,6 +785,15 @@ export function buildIntegralFinancialTables(
table('break-even').notes.push(
'Vendas de equilíbrio = custos fixos operacionais, pessoal e depreciação ÷ margem de contribuição ponderada. Juros e impostos excluídos. Arredondamento apenas no resultado final, ao centavo.',
);
if (result.dayTermEvents) {
table('cashflow').notes.push(
'Prazos em dias: as agendas seleccionadas substituem as agendas anteriores de caixa, conservadas inactivas. Saldos de abertura mantêm as agendas próprias. Não inclui adiantamentos.',
...result.dayTermEvents.map(
(e) =>
`${e.kind === 'sales' ? 'Vendas/prestações' : e.kind === 'purchases' ? 'Mercadorias recebidas' : 'Serviços adquiridos'} — ${e.originId}/${e.parcelId}: ${e.amount} ${plan.currency}; reconhecimento ${e.recognition}; origem ${e.origin}; vencimento ${e.due}${e.approximate ? ' (aproximação mensal)' : ''}; ${e.outsideHorizon ? 'fora do horizonte, sem movimento de caixa neste plano' : `mês de caixa ${e.dueMonth}`}.`,
),
);
}
} catch (error) {
for (const entry of tables)
entry.issues.push(