feat(finance): project PGC-PE supplier advances by operation in QA

This commit is contained in:
2026-11-21 10:42:41 +02:00
parent d1fcdcd947
commit c2a985dc6b
23 changed files with 2380 additions and 83 deletions
+203 -71
View File
@@ -1,3 +1,9 @@
import {
advanceEventLabels,
buildSupplierAdvances,
isSupplierAdvances,
type SupplierAdvances,
} from './supplier-advances.ts';
import {
buildDayTermSchedule,
isDayTerms,
@@ -90,6 +96,7 @@ function validCurrency(value: string): boolean {
export type BusinessFinancialPlanInput = {
/** Explicit opt-in. Missing keeps all historical calculations unchanged. */
dayTerms?: DayTerms;
supplierAdvances?: SupplierAdvances;
economicClassification?: {
code: string;
revision: string;
@@ -210,24 +217,27 @@ export function serializeBusinessPlanSnapshot(
): string {
const snapshot = JSON.stringify({
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.supplierAdvances !== undefined
? 21
: 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
@@ -312,7 +322,8 @@ export function restoreBusinessPlanSnapshot(
decoded.version !== 17 &&
decoded.version !== 18 &&
decoded.version !== 19 &&
decoded.version !== 20) ||
decoded.version !== 20 &&
decoded.version !== 21) ||
!decoded.plan ||
typeof decoded.plan !== 'object'
)
@@ -320,7 +331,13 @@ export function restoreBusinessPlanSnapshot(
const plan = decoded.plan as Record<string, unknown>;
if (
plan.dayTerms !== undefined &&
(decoded.version !== 20 || !isDayTerms(plan.dayTerms))
(![20, 21].includes(decoded.version) || !isDayTerms(plan.dayTerms))
)
return null;
if (
plan.supplierAdvances !== undefined &&
(decoded.version !== 21 ||
!isSupplierAdvances(plan.supplierAdvances))
)
return null;
if (
@@ -455,7 +472,9 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[12, 13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) &&
[12, 13, 14, 15, 16, 17, 20, 21].includes(
Number(decoded.version),
) &&
(!Object.hasOwn(plan, 'inventoryPurchaseSchedule') ||
!Object.hasOwn(plan, 'useInventoryPurchaseSchedule') ||
typeof plan.useInventoryPurchaseSchedule !== 'boolean')
@@ -466,7 +485,7 @@ export function restoreBusinessPlanSnapshot(
plan.inventoryPurchaseSchedule !== null
) {
if (
![12, 13, 14, 15, 16, 17, 20].includes(
![12, 13, 14, 15, 16, 17, 20, 21].includes(
Number(decoded.version),
) ||
!Array.isArray(plan.inventoryPurchaseSchedule) ||
@@ -491,14 +510,14 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) &&
[13, 14, 15, 16, 17, 20, 21].includes(Number(decoded.version)) &&
!Object.hasOwn(plan, 'monthlyVariableCostPaymentsByPeriod')
)
return null;
if (
plan.monthlyVariableCostPaymentsByPeriod !== undefined &&
plan.monthlyVariableCostPaymentsByPeriod !== null &&
(![13, 14, 15, 16, 17, 20].includes(Number(decoded.version)) ||
(![13, 14, 15, 16, 17, 20, 21].includes(Number(decoded.version)) ||
!Array.isArray(plan.monthlyVariableCostPaymentsByPeriod) ||
plan.monthlyVariableCostPaymentsByPeriod.length <
Number(plan.periods) ||
@@ -563,7 +582,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, 20].includes(
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
Number(decoded.version),
)
) {
@@ -636,7 +655,7 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
Number(decoded.version),
)
) {
@@ -675,7 +694,7 @@ export function restoreBusinessPlanSnapshot(
const schedule = plan[field];
if (
schedule !== undefined &&
(![11, 12, 13, 14, 15, 16, 17, 20].includes(
(![11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
Number(decoded.version),
) ||
!Array.isArray(schedule) ||
@@ -765,7 +784,7 @@ export function restoreBusinessPlanSnapshot(
const costSchedule = productData.unitVariableCostByPeriod;
const validMoneySchedule = (values: unknown) =>
values === undefined ||
([10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
([10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
Number(decoded.version),
) &&
Array.isArray(values) &&
@@ -774,7 +793,7 @@ export function restoreBusinessPlanSnapshot(
values.every((value) => typeof value === 'string'));
return (
(schedule !== undefined &&
(![9, 10, 11, 12, 13, 14, 15, 16, 17, 20].includes(
(![9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21].includes(
Number(decoded.version),
) ||
!Array.isArray(schedule) ||
@@ -813,7 +832,7 @@ export function restoreBusinessPlanSnapshot(
entry.paymentLagMonths < 0 ||
entry.paymentLagMonths > 12)) ||
(entry.paymentInstallments !== undefined &&
(![16, 17, 20].includes(
(![16, 17, 20, 21].includes(
Number(decoded.version),
) ||
!Array.isArray(
@@ -933,7 +952,10 @@ export function restoreBusinessPlanSnapshot(
? plan.monthlyVariableCostPaymentsByPeriod.map(String)
: null,
} as unknown as BusinessFinancialPlanInput;
if (restored.dayTerms && !options.editable)
if (
(restored.dayTerms || restored.supplierAdvances) &&
!options.editable
)
forecastBusinessPlan(restored);
return restored;
} catch {
@@ -1466,40 +1488,70 @@ type ActiveDayTerms = ReturnType<typeof buildDayTermSchedule> & {
export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
const config = input.dayTerms;
const advances = input.supplierAdvances;
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.
if (advances !== undefined && !isSupplierAdvances(advances))
throw new Error('Adiantamentos: estrutura inválida.');
const useAdvances = advances && (advances.purchases || advances.services);
// A category has exactly one cash agenda. Inactive day/manual inputs remain saved.
const activeDays = config
? {
...config,
purchases: config.purchases && !advances?.purchases,
services: config.services && !advances?.services,
}
: undefined;
const useDays =
activeDays &&
(activeDays.sales || activeDays.purchases || activeDays.services);
if (!useDays && !useAdvances) return forecastBusinessPlanBase(input);
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 });
const year = Number(input.reportAssumptions?.startYear);
const recognized = {
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'),
),
};
const day = useDays
? {
...buildDayTermSchedule(
activeDays,
year,
economic.rows.length,
recognized,
cents,
),
config: activeDays,
}
: undefined;
const advance = useAdvances
? {
...buildSupplierAdvances(
advances,
year,
economic.rows.length,
recognized,
cents,
),
config: advances,
}
: undefined;
return forecastBusinessPlanBase(input, day, advance);
}
function forecastBusinessPlanBase(
input: BusinessFinancialPlanInput,
day?: ActiveDayTerms,
advance?: ReturnType<typeof buildSupplierAdvances> & {
config: SupplierAdvances;
},
) {
if (input.startupAssetRequirements) {
const needs = calculateStartupAssetRequirements(input);
@@ -2304,13 +2356,17 @@ function forecastBusinessPlanBase(
const rows = [];
for (let month = 1; month <= periods; month++) {
const periodVariableCostPayment = day?.config.purchases
? day.schedules.purchases[month - 1]
: variableCostPaymentsByPeriod[month - 1];
const periodVariableCostPayment = advance?.config.purchases
? advance.payments.purchases[month - 1]
: day?.config.purchases
? day.schedules.purchases[month - 1]
: variableCostPaymentsByPeriod[month - 1];
const periodOperatingExpense = operatingExpenseByPeriod[month - 1];
const periodOperatingPayment = day?.config.services
? day.schedules.services[month - 1]
: operatingPaymentsByPeriod[month - 1];
const periodOperatingPayment = advance?.config.services
? advance.payments.services[month - 1]
: 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];
@@ -2504,7 +2560,10 @@ function forecastBusinessPlanBase(
const openingPayablesPayments =
openingPayablesInstallmentSchedule.get(month) ?? 0n;
openingPayablesBalance -= openingPayablesPayments;
const allCollections = totalCollections + openingReceivablesCollections;
const allCollections =
totalCollections +
openingReceivablesCollections +
(advance?.refunds[month - 1] ?? 0n);
const totalPayments =
periodVariableCostPayment +
periodOperatingPayment +
@@ -2752,15 +2811,28 @@ function forecastBusinessPlanBase(
? null
: salesCollectionPercent,
totalPayments: format(totalOperatingPayments),
supplierPaymentsOutstandingAtEnd: day?.config.purchases
supplierPaymentsOutstandingAtEnd: advance?.config.purchases
? format(
day.events
.filter((e) => e.kind === 'purchases' && e.outsideHorizon)
.reduce((sum, e) => sum + BigInt(e.amount), 0n),
advance.operations
.filter((o) => o.kind === 'purchases')
.reduce(
(sum, o) =>
sum +
cents(o.monthly.at(-1)!.obligation, 'Obrigação'),
0n,
),
)
: useSupplierPaymentTerms
? format(supplierPaymentsOutstanding)
: null,
: 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,
@@ -3032,6 +3104,15 @@ function forecastBusinessPlanBase(
};
return {
...output,
...(advance
? {
supplierAdvanceLedger: {
regime: advance.config.regime,
monthly: advance.monthly,
operations: advance.operations,
},
}
: {}),
presentationCurrency,
conversion,
...(day
@@ -3629,6 +3710,57 @@ export function exportBusinessPlanCsv(
]),
);
}
if (result.supplierAdvanceLedger) {
rows.push(
[],
[
'Adiantamentos por operação — PGC-PE; projecções sem IVA, câmbio, perdas ou penalizações',
],
[
'Operação',
'Parcela',
'Fornecedor',
'Reconhecimento',
'Factura',
'Mês',
'Obrigação bruta',
'Adiantamento activo',
'Líquido por liquidar',
],
...result.supplierAdvanceLedger.operations.flatMap((o) =>
o.monthly.map((m) => [
o.originId,
o.parcelId,
o.supplier,
o.recognitionDate || 'Por confirmar',
o.invoiceDate || 'Por confirmar',
m.month,
m.obligation,
m.advance,
m.netDue,
]),
),
[],
[
'Operação',
'Parcela',
'Movimento',
'Data',
'Montante',
'Horizonte',
],
...result.supplierAdvanceLedger.operations.flatMap((o) =>
o.events.map((e) => [
o.originId,
o.parcelId,
advanceEventLabels[e.kind],
e.date,
e.amount,
e.outsideHorizon ? 'Fora do horizonte' : 'No horizonte',
]),
),
);
}
return `\uFEFF${rows
.map((row) => row.map(csvCell).join(','))
.join('\r\n')}`;
+23 -3
View File
@@ -86,11 +86,16 @@ function assertForecastReconciles(forecast: Forecast): void {
);
previousOpeningReceivables = openingReceivablesBalance;
totalOpeningReceivablesCollections += openingReceivablesCollections;
const advanceRefund = cents(
forecast.supplierAdvanceLedger?.monthly[row.month - 1].refunded ??
'0',
);
const otherCollections =
row.otherCollections === null
? cents(String(row.cashCollections)) -
salesCollections -
openingReceivablesCollections
openingReceivablesCollections -
advanceRefund
: cents(String(row.otherCollections));
if (otherCollections < 0n)
throw new Error(
@@ -100,7 +105,10 @@ function assertForecastReconciles(forecast: Forecast): void {
const collections = cents(String(row.cashCollections));
if (
collections !==
salesCollections + openingReceivablesCollections + otherCollections
salesCollections +
openingReceivablesCollections +
otherCollections +
advanceRefund
)
throw new Error(
'As cobranças mensais não reconciliam com as suas origens.',
@@ -260,8 +268,20 @@ export function buildFinancialFiscalBridge(forecast: Forecast) {
(row.salesCollections === null
? 0n
: cents(row.salesCollections)) -
cents(row.openingReceivablesCollections),
cents(row.openingReceivablesCollections) -
cents(
forecast.supplierAdvanceLedger?.monthly[
row.month - 1
].refunded ?? '0',
),
),
...(forecast.supplierAdvanceLedger
? {
supplierAdvanceRefunds:
forecast.supplierAdvanceLedger.monthly[row.month - 1]
.refunded,
}
: {}),
collections: row.cashCollections,
collectionsTotal: row.cashCollections,
salesReceivablesBalance: row.salesReceivablesClosing,
+60 -5
View File
@@ -4,6 +4,7 @@ import {
type BusinessFinancialPlanInput,
} from './business-financial-plan.ts';
import { calculateStartupAssetRequirements } from './startup-asset-requirements.ts';
import { advanceEventLabels } from './supplier-advances.ts';
export type InvestmentReportTable = {
id: string;
@@ -518,7 +519,10 @@ export function buildIntegralFinancialTables(
const opening = cash;
cash += netCash;
receivables +=
cents(row.revenue) - cents(row.cashCollections) + otherIncome;
cents(row.revenue) -
cents(row.cashCollections) +
otherIncome +
cents(result.supplierAdvanceLedger?.monthly[i].refunded ?? '0');
const purchases =
row.inventoryReceipts === null
? null
@@ -538,6 +542,13 @@ export function buildIntegralFinancialTables(
cents(row.payrollPayments) -
cents(row.interestPayment) -
cents(row.openingPayablesPayments);
const advance = cents(
result.supplierAdvanceLedger?.monthly[i].advance ?? '0',
);
obligations += cents(
result.supplierAdvanceLedger?.monthly[i].refunded ?? '0',
);
const grossObligations = obligations + advance;
taxDue += taxExpenses[i] - taxPayments[i];
depreciation += cents(row.depreciation);
principal += cents(row.principalRepayment);
@@ -566,11 +577,12 @@ export function buildIntegralFinancialTables(
fixed -
depreciation +
otherAssets +
positive(-obligations) +
positive(-grossObligations) +
advance +
positive(-taxDue);
const liabilities =
positive(-receivables) +
positive(obligations) +
positive(grossObligations) +
positive(taxDue) +
loans -
principal +
@@ -581,7 +593,8 @@ export function buildIntegralFinancialTables(
opening,
cash,
receivables,
obligations: obligationsKnown ? obligations : null,
obligations: obligationsKnown ? grossObligations : null,
advance,
taxDue,
profit,
netCash,
@@ -679,7 +692,12 @@ export function buildIntegralFinancialTables(
for (const [key, label] of [
['cash', 'Caixa líquida'],
['receivables', 'Recebíveis líquidos'],
['obligations', 'Obrigações operacionais líquidas'],
[
'obligations',
result.supplierAdvanceLedger
? 'Obrigações operacionais brutas'
: 'Obrigações operacionais líquidas',
],
['taxDue', 'Saldo fiscal estimado'],
['fixed', 'Activos fixos líquidos'],
['loans', 'Empréstimos e suprimentos por reembolsar'],
@@ -694,6 +712,43 @@ export function buildIntegralFinancialTables(
label,
ledger.map((row) => row[key]),
);
if (result.supplierAdvanceLedger) {
stocks(
'balance',
'Adiantamentos identificados a fornecedores',
ledger.map((row) => row.advance),
);
stocks(
'balance',
'Líquido por liquidar — operações identificadas',
result.supplierAdvanceLedger.monthly.map((row) =>
cents(row.netDue),
),
);
for (const [key, label] of [
['paid', 'Adiantamentos pagos'],
['applied', 'Aplicações sem movimento de caixa'],
['refunded', 'Devoluções de adiantamentos'],
['settled', 'Remanescentes pagos'],
] as const)
flows(
'cashflow',
label + ' (discriminação)',
result.supplierAdvanceLedger.monthly.map((row) =>
cents(row[key]),
),
);
table('balance').notes.push(
'PGC-PE: adiantamentos identificados apresentados no activo, separados das obrigações brutas. Líquido por liquidar é calculado por operação/parcela, sem compensação entre operações. Devoluções não são receita; aplicações não movimentam caixa.',
);
table('cashflow').notes.push(
'Adiantamentos, aplicações, devoluções e remanescentes são projecções discriminadas, já incluídas nos totais de caixa quando aplicável; não somar novamente. Sem automatização de IVA, câmbio, perdas, penalizações ou contratos especiais.',
...result.supplierAdvanceLedger.operations.map(
(o) =>
`${o.originId}/${o.parcelId} — ${o.supplier}: reconhecimento ${o.recognitionDate || 'por confirmar'}; factura ${o.invoiceDate || 'por confirmar'}. ${o.events.map((e) => `${advanceEventLabels[e.kind]}: ${e.date}, ${e.amount} ${plan.currency}${e.outsideHorizon ? ' (fora do horizonte)' : ''}`).join('; ')}.`,
),
);
}
table('balance').rows.push([
'Existências',
...ledger.map((row) =>
+340
View File
@@ -0,0 +1,340 @@
export type AdvanceKind = 'purchases' | 'services';
export type AdvanceEventKind = 'advance' | 'apply' | 'refund' | 'settle';
export type SupplierAdvanceOperation = {
originId: string;
parcelId: string;
supplier: string;
kind: AdvanceKind;
amount: string;
recognitionDate: string;
invoiceDate: string;
ordinaryContract: boolean;
events: {
id: string;
kind: AdvanceEventKind;
date: string;
amount: string;
}[];
};
export type SupplierAdvances = {
regime: '' | 'PGC-PE';
purchases: boolean;
services: boolean;
operations: SupplierAdvanceOperation[];
};
export const advanceLabels = {
purchases: 'Mercadorias',
services: 'Serviços adquiridos',
};
export const advanceEventLabels = {
advance: 'Pagamento antecipado',
apply: 'Aplicação do adiantamento',
refund: 'Devolução do adiantamento',
settle: 'Pagamento do remanescente',
};
const text = (v: unknown) => typeof v === 'string' && v.length <= 160;
export function isSupplierAdvances(v: unknown): v is SupplierAdvances {
if (!v || typeof v !== 'object') return false;
const c = v as SupplierAdvances;
return (
['', 'PGC-PE'].includes(c.regime) &&
typeof c.purchases === 'boolean' &&
typeof c.services === 'boolean' &&
Array.isArray(c.operations) &&
c.operations.length <= 120 &&
c.operations.every(
(o) =>
o &&
['purchases', 'services'].includes(o.kind) &&
typeof o.ordinaryContract === 'boolean' &&
[
'originId',
'parcelId',
'supplier',
'amount',
'recognitionDate',
'invoiceDate',
].every((k) => text(o[k as keyof SupplierAdvanceOperation])) &&
Array.isArray(o.events) &&
o.events.length <= 60 &&
o.events.every(
(e) =>
e &&
text(e.id) &&
text(e.date) &&
text(e.amount) &&
Object.hasOwn(advanceEventLabels, e.kind),
),
)
);
}
function date(value: string): Date | null {
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
const d = new Date(value + 'T00:00:00Z');
return Number.isFinite(d.getTime()) &&
d.toISOString().slice(0, 10) === value
? d
: null;
}
const money = (n: bigint) => `${n / 100n}.${String(n % 100n).padStart(2, '0')}`;
/** Projected events only. No accounting postings or actual payments are executed. */
export function buildSupplierAdvances(
config: SupplierAdvances,
year: number,
periods: number,
recognized: Record<AdvanceKind, (bigint | null)[]>,
parse: (value: string, label: string) => bigint,
) {
if (!isSupplierAdvances(config))
throw Error('Adiantamentos: estrutura inválida.');
if (config.regime !== 'PGC-PE')
throw Error(
'Adiantamentos: seleccione explicitamente PGC-PE. Outros regimes não estão automatizados.',
);
if (!Number.isSafeInteger(year) || year < 1900 || year > 9993)
throw Error(
'Adiantamentos: preencha o ano inicial do relatório entre 1900 e 9993.',
);
const index = (d: Date) =>
(d.getUTCFullYear() - year) * 12 + d.getUTCMonth();
const start = new Date(Date.UTC(year, 0, 1));
const end = new Date(Date.UTC(year, periods, 1));
const sums = {
purchases: Array<bigint>(periods).fill(0n),
services: Array<bigint>(periods).fill(0n),
};
const payments = {
purchases: Array<bigint>(periods).fill(0n),
services: Array<bigint>(periods).fill(0n),
};
const refunds = Array<bigint>(periods).fill(0n);
const paid = Array<bigint>(periods).fill(0n);
const applied = Array<bigint>(periods).fill(0n);
const settled = Array<bigint>(periods).fill(0n);
const balances = Array.from({ length: periods }, () => ({
advance: 0n,
obligation: 0n,
netDue: 0n,
}));
const seen = new Set<string>();
const origins = new Map<string, string>();
const operations = config.operations
.filter((o) => config[o.kind])
.map((o) => {
const label = `Adiantamentos — ${o.originId || 'operação por preencher'}/${o.parcelId || 'parcela por preencher'}`;
const fail = (message: string): never => {
throw Error(`${label}: ${message}`);
};
if (!o.originId.trim() || !o.parcelId.trim() || !o.supplier.trim())
fail('identifique operação, parcela e fornecedor.');
if (!o.ordinaryContract)
fail(
'confirme contrato ordinário; contratos especiais estão excluídos.',
);
const key = JSON.stringify([
o.kind,
o.originId.trim(),
o.parcelId.trim(),
]);
if (seen.has(key)) fail('operação/parcela duplicada.');
seen.add(key);
const originKey = JSON.stringify([o.kind, o.originId.trim()]);
const identity = JSON.stringify([
o.supplier.trim(),
o.recognitionDate,
o.invoiceDate,
]);
if (origins.has(originKey) && origins.get(originKey) !== identity)
fail(
'parcelas da mesma operação devem conservar fornecedor, reconhecimento e factura.',
);
origins.set(originKey, identity);
const amount = parse(o.amount, `${label} — valor da operação`);
if (amount <= 0n)
fail('indique um valor positivo para a operação.');
const recognition = o.recognitionDate
? date(o.recognitionDate)
: null;
const invoice = o.invoiceDate ? date(o.invoiceDate) : null;
if (o.recognitionDate && !recognition)
fail('data de reconhecimento inválida.');
if (o.invoiceDate && !invoice) fail('data de factura inválida.');
if (recognition && recognition < start)
fail(
'saldos anteriores não podem ser individualizados por inferência; use apenas operações novas do plano.',
);
if (recognition && index(recognition) < periods)
sums[o.kind][index(recognition)] += amount;
const ids = new Set<string>();
const events = o.events
.map((e, order) => {
if (!e.id.trim() || ids.has(e.id.trim()))
fail('identifique cada movimento sem duplicações.');
ids.add(e.id.trim());
const when = date(e.date);
if (!when || when < start)
fail(
'data de movimento insuficiente, inválida ou anterior ao plano.',
);
const value = parse(
e.amount,
`${label} — ${advanceEventLabels[e.kind]}`,
);
if (value <= 0n)
fail('os movimentos devem ter montantes positivos.');
return { ...e, value, when: when!, order };
})
.sort(
(a, b) =>
a.when.getTime() - b.when.getTime() ||
a.order - b.order,
);
let advance = 0n,
obligation = 0n,
isRecognized = false,
eventIndex = 0;
const audit: {
id: string;
kind: AdvanceEventKind;
date: string;
amount: string;
outsideHorizon: boolean;
advance: string;
obligation: string;
netDue: string;
}[] = [];
const process = (e: (typeof events)[number]) => {
if (!isRecognized && recognition && recognition <= e.when) {
obligation = amount;
isRecognized = true;
}
const m = index(e.when);
const inside = m >= 0 && m < periods;
if (e.kind === 'advance') {
if (isRecognized)
fail(
'pagamento após reconhecimento deve ser remanescente, não novo adiantamento.',
);
advance += e.value;
if (inside) {
payments[o.kind][m] += e.value;
paid[m] += e.value;
}
} else if (e.kind === 'apply') {
if (!isRecognized || !invoice || invoice > e.when)
fail(
'aplicação exige reconhecimento e factura correspondente, sem antecipar datas.',
);
if (e.value > advance || e.value > obligation)
fail(
'aplicação excede o saldo da mesma parcela ou a obrigação reconhecida.',
);
advance -= e.value;
obligation -= e.value;
if (inside) applied[m] += e.value;
} else if (e.kind === 'refund') {
if (e.value > advance)
fail(
'devolução excede o adiantamento não utilizado da mesma parcela.',
);
advance -= e.value;
if (inside) refunds[m] += e.value;
} else {
const netDue =
obligation > advance ? obligation - advance : 0n;
if (!isRecognized || !invoice || invoice > e.when)
fail(
'pagamento do remanescente exige reconhecimento e factura.',
);
if (e.value > netDue)
fail(
'pagamento excede o líquido por liquidar; não volte a pagar o adiantamento associado.',
);
obligation -= e.value;
if (inside) {
payments[o.kind][m] += e.value;
settled[m] += e.value;
}
}
audit.push({
id: e.id,
kind: e.kind,
date: e.date,
amount: money(e.value),
outsideHorizon: !inside,
advance: money(advance),
obligation: money(obligation),
netDue: money(
obligation > advance ? obligation - advance : 0n,
),
});
};
const monthly = [];
for (let m = 0; m < periods; m++) {
const boundary = new Date(Date.UTC(year, m + 1, 1));
while (
eventIndex < events.length &&
events[eventIndex].when < boundary
)
process(events[eventIndex++]);
if (!isRecognized && recognition && recognition < boundary) {
obligation = amount;
isRecognized = true;
}
const netDue = obligation > advance ? obligation - advance : 0n;
balances[m].advance += advance;
balances[m].obligation += obligation;
balances[m].netDue += netDue;
monthly.push({
month: m + 1,
advance: money(advance),
obligation: money(obligation),
netDue: money(netDue),
recognized: isRecognized,
});
}
// Validate future events as well; they never leak into the last month of cash.
while (eventIndex < events.length) process(events[eventIndex++]);
return {
originId: o.originId,
parcelId: o.parcelId,
supplier: o.supplier,
kind: o.kind,
amount: money(amount),
recognitionDate: o.recognitionDate,
invoiceDate: o.invoiceDate,
recognitionOutsideHorizon: !recognition || recognition >= end,
monthly,
events: audit,
};
});
for (const kind of ['purchases', 'services'] as const) {
if (!config[kind]) continue;
for (let m = 0; m < periods; m++) {
if (
recognized[kind][m] === null ||
sums[kind][m] !== recognized[kind][m]
)
throw Error(
`Adiantamentos — ${advanceLabels[kind]}, mês ${m + 1}: distribua exactamente o reconhecimento económico por operações/parcelas, sem repetir valores nem converter dados desconhecidos em zero.`,
);
}
}
return {
payments,
refunds,
operations,
monthly: balances.map((b, i) => ({
month: i + 1,
advance: money(b.advance),
obligation: money(b.obligation),
netDue: money(b.netDue),
paid: money(paid[i]),
applied: money(applied[i]),
refunded: money(refunds[i]),
settled: money(settled[i]),
})),
};
}