/** * The pure part of OPOS (Offene-Posten-Buchhaltung): open items derived from * personal-account lines, their aging and how a bank movement settles one. * Nothing here touches a database; `skr.opos.ts` loads the lines of the v2 * ledger and adds the dunning metadata around these functions. * * A line on a personal account (debtors and creditors by the policy's ranges) * belongs to the open item keyed by (account, Belegfeld 1); the item is open * while its signed sum is non-zero. The key is DATEV's: Belegfeld 1 is the * "Rechnungs-/Belegnummer[, w]ird als 'Schlüssel' für den Ausgleich offener * Rechnungen genutzt" (DATEV-Format, Buchungsstapel field 11), so every * settlement — a payment, a credit note, a refund — repeats the INVOICE number * there and lands on the invoice's item. */ import type { IAccountPolicy } from './core.accountpolicy.js'; import { isCreditorAccount, isDebtorAccount } from './core.accountpolicy.js'; import { RecipeRefusalError } from './core.errors.js'; export type TOposKind = 'debtor' | 'creditor'; export interface IOpenItem { accountNumber: string; kind: TOposKind; /** belegfeld1 of the originating lines — the invoice number */ reference: string; /** original claim (sum of the claim-side lines) */ invoiceCents: number; /** settled so far (sum of the settlement-side lines, credit notes included) */ clearedCents: number; /** * invoiceCents - clearedCents. > 0 is an open claim; < 0 is a credit in the * counterparty's favour — an over-settled item or a credit note beyond what * was still open — which a refund settles (see planOpenItemSettlement). */ openCents: number; firstDate: string; lastDate: string; entryIds: string[]; dunningLevel: number; dueDate?: string; } export interface IAgingBucket { label: string; maxAgeDays: number | null; items: IOpenItem[]; totalCents: number; } /** One personal-account line of a posted entry, the input of the derivation. */ export interface IOposLineRow { entryId: string; accountNumber: string; belegfeld1?: string; side: 'debit' | 'credit'; /** negative for the line of a Generalumkehr: it takes back what its side booked, a claim or a settlement */ amountCents: number; date: Date; } /** Whether an account is a debtor or a creditor account of the policy, or neither. */ export function oposKindOf(accountNumber: string, policy: IAccountPolicy): TOposKind | null { if (isDebtorAccount(policy, accountNumber)) return 'debtor'; if (isCreditorAccount(policy, accountNumber)) return 'creditor'; return null; } /** * Group personal-account lines into open items. Pure. Debtors: claims are * debits, settlements credits; creditors inverse — so a customer credit note * (debtor credit) settles exactly like an incoming payment, which is why it * has to repeat the invoice number in Belegfeld 1. Items with openCents === 0 * are settled and omitted unless includeSettled is set. */ export function deriveOpenItems( rows: IOposLineRow[], policy: IAccountPolicy, options?: { kind?: TOposKind; includeSettled?: boolean }, ): IOpenItem[] { const groups = new Map(); for (const row of rows) { const kind = oposKindOf(row.accountNumber, policy); if (!kind) continue; if (options?.kind && kind !== options.kind) continue; const key = `${row.accountNumber}:${row.belegfeld1}`; let item = groups.get(key); if (!item) { item = { accountNumber: row.accountNumber, kind, reference: row.belegfeld1 ?? '', invoiceCents: 0, clearedCents: 0, openCents: 0, firstDate: row.date.toISOString().slice(0, 10), lastDate: row.date.toISOString().slice(0, 10), entryIds: [], dunningLevel: 0, }; groups.set(key, item); } const isClaim = (kind === 'debtor') === (row.side === 'debit'); if (isClaim) item.invoiceCents += row.amountCents; else item.clearedCents += row.amountCents; item.lastDate = row.date.toISOString().slice(0, 10); if (!item.entryIds.includes(row.entryId)) item.entryIds.push(row.entryId); } const items: IOpenItem[] = []; for (const item of groups.values()) { item.openCents = item.invoiceCents - item.clearedCents; if (item.openCents !== 0 || options?.includeSettled) items.push(item); } return items.sort( (a, b) => a.accountNumber.localeCompare(b.accountNumber) || a.firstDate.localeCompare(b.firstDate), ); } /** Aging buckets relative to asOf, by days since dueDate (falling back to the item's first posting date). */ export function bucketOpenItems( items: IOpenItem[], asOf: Date, bucketDays: number[] = [30, 60, 90], ): IAgingBucket[] { const buckets: IAgingBucket[] = [ { label: 'not_due', maxAgeDays: -1, items: [], totalCents: 0 }, ...bucketDays.map((days, index) => ({ label: index === 0 ? `0-${days}` : `${bucketDays[index - 1] + 1}-${days}`, maxAgeDays: days, items: [] as IOpenItem[], totalCents: 0, })), { label: `> ${bucketDays[bucketDays.length - 1]}`, maxAgeDays: null, items: [], totalCents: 0 }, ]; for (const item of items) { const anchor = item.dueDate ?? item.firstDate; const ageDays = Math.floor((asOf.getTime() - new Date(anchor).getTime()) / 86_400_000); const bucket = buckets.find((candidate) => candidate.maxAgeDays !== null && ageDays <= candidate.maxAgeDays) ?? buckets[buckets.length - 1]; bucket.items.push(item); bucket.totalCents += item.openCents; } return buckets; } /** How a bank movement settles an open item (see planOpenItemSettlement). */ export interface IOpenItemSettlementPlan { /** the movement on the bank account: money in or money out */ direction: 'incoming' | 'outgoing'; /** amount the personal account is cleared by */ expectedCents: number; /** amount that actually moves on the bank account */ paidCents: number; /** the movement covers only part of the outstanding amount */ partial: boolean; } /** * Decide direction and amounts for settling an open item with a bank * movement. Pure — the posting is done by the caller. * * The sign of `openCents` picks the direction, not the kind of the account * alone: a debtor's open claim is collected (incoming), but a debtor item that * a credit note pushed into a CREDIT is money we owe the customer, so it is * settled by a refund (outgoing) — and a creditor works the other way round. * The refund repeats the item's reference, so it clears the same Belegfeld 1 * key and the item disappears instead of turning into a second one. * * A plain underpayment (no Skonto, beyond tolerance) is a PARTIAL settlement: * only the paid amount is booked and the rest stays open. */ export function planOpenItemSettlement(params: { item: IOpenItem; paidCents: number; diffToleranceCents?: number; /** a Skonto branch consumes the whole outstanding amount, never partial */ skonto?: boolean; }): IOpenItemSettlementPlan { const outstandingCents = Math.abs(params.item.openCents); if (outstandingCents === 0) { throw new RecipeRefusalError( 'open_item_settled', `Open item ${params.item.accountNumber}/${params.item.reference || '(no reference)'} is already settled — nothing to pay or refund`, { account: params.item.accountNumber }, ); } const isCredit = params.item.openCents < 0; const direction: 'incoming' | 'outgoing' = (params.item.kind === 'debtor') !== isCredit ? 'incoming' : 'outgoing'; const shortfall = outstandingCents - params.paidCents; const partial = !params.skonto && shortfall > (params.diffToleranceCents ?? 0); return { direction, expectedCents: partial ? params.paidCents : outstandingCents, paidCents: params.paidCents, partial, }; }