/** * OPOS (Offene-Posten-Buchhaltung): open-item accounting over the v2 ledger. * * Open items are DERIVED from the hashed journal — no separate bookkeeping * state that could drift. A line on a personal account (debtors 10000-69999, * creditors 70000-99999) belongs to the open item keyed by * (account, belegfeld1); 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. * Settling an item is ordinary posting (core.bookBankPayment + JournalPoster), * so Festschreibung and the audit chain apply unchanged. * * The derivation itself is pure and lives in the core * (`core.deriveOpenItems`, `core.bucketOpenItems`, `core.openItemsOf`; * re-exported here): only listOpenItems/getAging add the database and the * dunning metadata around it. * * Only dunning metadata lives outside the ledger (OposMeta collection) — * process state, not bookkeeping. */ import * as core from './core/index.js'; import { deriveOpenItems, bucketOpenItems, oposKindOf, type IAgingBucket, type IOpenItem, type IOposLineRow, type TOposKind, } from './core/core.openitems.js'; // the pure derivation lives in the core (`@fin.cx/skr/core`); it is exported here as before export { deriveOpenItems, bucketOpenItems, planOpenItemSettlement } from './core/core.openitems.js'; export type { IAgingBucket, IOpenItem, IOpenItemSettlementPlan, IOposLineRow, TOposKind } from './core/core.openitems.js'; import * as plugins from './plugins.js'; import { getDbSync } from './skr.database.js'; import { JournalEntry } from './skr.classes.journalentry.js'; import type { IJournalEntryLine, TSKRType } from './skr.types.js'; export const OPOS_META_COLLECTION = 'OposMeta'; /** The unique key of a dunning record: one per (skrType, account, reference). */ export const OPOS_META_INDEX_NAME = 'skrType_1_accountNumber_1_reference_1'; /** Dunning metadata of one open item — process state, not bookkeeping. */ @plugins.nosqldb.compoundIndex({ name: OPOS_META_INDEX_NAME, key: { skrType: 1, accountNumber: 1, reference: 1 }, options: { unique: true }, }) @plugins.nosqldb.Collection(() => getDbSync(), { collectionName: OPOS_META_COLLECTION }) export class OposMeta extends plugins.nosqldb.SmartDataDbDoc { @plugins.nosqldb.svDb() public skrType!: TSKRType; @plugins.nosqldb.svDb() public accountNumber!: string; @plugins.nosqldb.svDb() public reference!: string; @plugins.nosqldb.svDb() public dunningLevel?: number; @plugins.nosqldb.svDb() public dueDate?: string; @plugins.nosqldb.svDb() public updatedAt!: Date; } /** The fields of a posted journal entry the open-item derivation reads. */ export interface IOposEntryLike { id: string; date: Date; reference?: string; lines: Array>; } export interface IControlTotals { debtorsCents: number; creditorsCents: number; debtorAccounts: number; creditorAccounts: number; } /** * Pick the personal-account lines out of posted journal documents. Pure — the * documents come from the caller. A line without its own Belegfeld 1 falls * back to the entry reference; both empty means the line belongs to the * unreferenced bucket of its account. */ export function extractPersonalLines( docs: IOposEntryLike[], policy: core.IAccountPolicy, accountNumber?: string, ): IOposLineRow[] { const rows: IOposLineRow[] = []; for (const doc of docs) { for (const line of doc.lines ?? []) { const account = line.accountNumber; if (!oposKindOf(account, policy)) continue; if (accountNumber && account !== accountNumber) continue; rows.push({ entryId: doc.id, accountNumber: account, belegfeld1: line.belegfeld1 || doc.reference || '', side: line.side as 'debit' | 'credit', amountCents: line.amountCents ?? 0, date: doc.date, }); } } return rows; } async function loadPersonalLines( skrType: TSKRType, policy: core.IAccountPolicy, accountNumber?: string, asOf?: Date, ): Promise { const filter: plugins.nosqldb.MongoFilter = { skrType, schemaVersion: 2, status: { $in: ['posted', 'finalized'] }, }; if (asOf) filter.date = { $lte: asOf }; if (accountNumber) filter['lines.accountNumber'] = accountNumber; const cursor = await JournalEntry.getCursor(filter, { sort: { date: 1, sequenceNumber: 1 } }); const docs = await cursor.toArray(); return extractPersonalLines(docs, policy, accountNumber); } /** * Derive open items from the ledger and merge the dunning metadata onto them. */ export async function listOpenItems( skrType: TSKRType, policy: core.IAccountPolicy, options?: { kind?: TOposKind; accountNumber?: string; asOf?: Date; includeSettled?: boolean; }, ): Promise { core.assertSkrType(skrType); const rows = await loadPersonalLines(skrType, policy, options?.accountNumber, options?.asOf); const items = deriveOpenItems(rows, policy, { kind: options?.kind, includeSettled: options?.includeSettled, }); const meta = await OposMeta.getInstances({ skrType }); const metaByKey = new Map(meta.map((m) => [`${m.accountNumber}:${m.reference}`, m])); for (const item of items) { const extra = metaByKey.get(`${item.accountNumber}:${item.reference}`); if (extra) { item.dunningLevel = extra.dunningLevel ?? 0; item.dueDate = extra.dueDate; } } return items; } /** * Aging list relative to asOf, bucketed by days since dueDate (falling back * to the item's first posting date). */ export async function getAging( skrType: TSKRType, policy: core.IAccountPolicy, kind: TOposKind, asOf: Date, bucketDays: number[] = [30, 60, 90], ): Promise { const items = await listOpenItems(skrType, policy, { kind, asOf }); return bucketOpenItems(items, asOf, bucketDays); } /** * Subledger control totals: the aggregated personal-account balances that a * balance sheet reports as Forderungen (B.II.1) / Verbindlichkeiten (C.4) * aus Lieferungen und Leistungen. Control accounts themselves are blocked for * posting, so these aggregates ARE the control balances. */ export async function getControlTotals( skrType: TSKRType, policy: core.IAccountPolicy, asOf?: Date, ): Promise { core.assertSkrType(skrType); const rows = await loadPersonalLines(skrType, policy, undefined, asOf); let debtorsCents = 0; let creditorsCents = 0; const debtorAccounts = new Set(); const creditorAccounts = new Set(); for (const row of rows) { const signed = row.side === 'debit' ? row.amountCents : -row.amountCents; if (oposKindOf(row.accountNumber, policy) === 'debtor') { debtorsCents += signed; debtorAccounts.add(row.accountNumber); } else { creditorsCents -= signed; // creditors carry credit balances positive creditorAccounts.add(row.accountNumber); } } return { debtorsCents, creditorsCents, debtorAccounts: debtorAccounts.size, creditorAccounts: creditorAccounts.size, }; } /** * Dunning metadata (process state, not bookkeeping — letters are out of * scope; the level/due-date state machine is in). */ export async function setOposMeta(params: { skrType: TSKRType; accountNumber: string; reference: string; dunningLevel?: number; dueDate?: string; }): Promise { core.assertSkrType(params.skrType); const update: plugins.nosqldb.ISmartdataAtomicUpdate['$set'] = { updatedAt: new Date() }; if (params.dunningLevel !== undefined) update.dunningLevel = params.dunningLevel; if (params.dueDate !== undefined) update.dueDate = params.dueDate; await OposMeta.atomicUpdate( { skrType: params.skrType, accountNumber: params.accountNumber, reference: params.reference }, { $set: update }, { upsert: true }, ); }