/** * The ledger as pure functions over journal entries: the lines of every * entry, the trial balance (Summen- und Saldenliste), the sheet of one * account (Kontenblatt) and the open items of the personal accounts. Nothing * here is stored or read from a database: the caller hands in the entries — * journal drafts of the recipes, or posted entries of any ledger — and gets * the figures back, in exact integer cents. * * What the functions refuse, because a figure built from it would be false: * an entry whose debits and credits differ, an amount that is not a whole * number of cents, an entry id given twice (it would be counted twice), a * date that is no date, a period that is no day or ends before it begins. * * Days are UTC calendar days (`date.toISOString().slice(0, 10)`), as the * recipes write them and as the rest of the core reads them. */ import type { IAccountPolicy } from './core.accountpolicy.js'; import { deriveOpenItems, type IOpenItem, type IOposLineRow, type TOposKind } from './core.openitems.js'; import type { IJournalLineDraft, TBuKey, TLineSide } from './core.types.js'; /** One journal entry as the ledger reads it: a draft of the recipes with an id, or a posted entry. */ export interface ILedgerEntryInput { /** unique across the entries handed in */ id: string; date: Date; description?: string; /** the entry's reference; a line without its own Belegfeld 1 falls back to it for its open item */ reference?: string; /** a general reversal: every line keeps its side and counts negative there (see `IJournalDraft.generalumkehr`) */ generalumkehr?: boolean; /** an opening entry (EB-Werte): its lines are the accounts' opening balances, not turnover */ opening?: boolean; /** * Voranmeldungszeitraum, `YYYY-MM` as `IPostedEntryPayload.vatPeriod`: the * VAT month the entry is declared in, which a correction of an earlier * return names (§ 16 Abs. 1 Satz 2 UStG) though its date lies later. * Absent: the month of `date`. Read by `computeUstVerprobung` only. */ vatPeriod?: string; lines: IJournalLineDraft[]; } /** One line of the ledger: a line of an entry, on the side it books, with its amount positive. */ export interface ILedgerLine { entryId: string; /** `YYYY-MM-DD`, UTC */ date: string; accountNumber: string; counterAccount: string; side: TLineSide; /** positive */ amountCents: number; /** the line of a Generalumkehr: it stays on its side and counts negative there */ generalumkehr: boolean; /** the line of an opening entry */ opening: boolean; /** debit positive, credit negative; a Generalumkehr line the other way round */ signedCents: number; buKey: TBuKey; buchungstext: string; belegfeld1?: string; belegfeld2?: string; /** KOST1, the line's cost centre, as the entry states it */ costCenter1?: string; /** KOST2, the line's second cost centre (a project, for example), as the entry states it */ costCenter2?: string; reference?: string; docLink?: string; } /** An opening balance (Saldovortrag / EB-Wert) of one account: debit positive. */ export interface IOpeningBalance { accountNumber: string; signedCents: number; } /** Which days the figures are for. Both ends are optional and inclusive, as `YYYY-MM-DD`. */ export interface ILedgerPeriodOptions { /** lines before this day count as brought forward (`prior…`); unset: none are */ periodFrom?: string; /** lines after this day are left out; unset: none are */ periodTo?: string; } export interface ITrialBalanceOptions extends ILedgerPeriodOptions { /** * the opening balances; with none given and no opening entry among the * entries, none are recorded, and every account's `openingCents` is `null`. * Given both, they add up. */ opening?: IOpeningBalance[]; } /** One row of the Summen- und Saldenliste. */ export interface ITrialBalanceAccount { accountNumber: string; /** `null` when no opening balances were handed in at all; `0` for an account without one among them */ openingCents: number | null; /** lines before the period (within the entries handed in) */ priorDebitCents: number; priorCreditCents: number; periodDebitCents: number; periodCreditCents: number; /** prior + period */ cumulativeDebitCents: number; cumulativeCreditCents: number; /** opening + cumulative debit − cumulative credit: debit positive */ balanceCents: number; } export interface ITrialBalance { periodFrom?: string; periodTo?: string; /** by account number: numbers of digits by their value, of equal value by their text; other numbers after them, by their text */ accounts: ITrialBalanceAccount[]; hasOpeningBalances: boolean; /** the sum of the opening balances; a set that balances sums to 0 */ openingDifferenceCents: number; /** over the cumulative columns */ totalDebitCents: number; totalCreditCents: number; /** debits equal credits and the opening balances sum to 0 */ isBalanced: boolean; } export interface IAccountSheetOptions extends ILedgerPeriodOptions { /** * the account's opening balance, debit positive; with none given and no * opening entry among the entries, none is recorded. Given both, they add up. */ openingCents?: number; } export interface IAccountSheetLine { entryId: string; date: string; counterAccount: string; buchungstext: string; belegfeld1?: string; reference?: string; docLink?: string; buKey: TBuKey; /** negative on a Generalumkehr line booked in Soll */ debitCents: number; /** negative on a Generalumkehr line booked in Haben */ creditCents: number; /** the running balance after this line, debit positive */ balanceCents: number; generalumkehr: boolean; } /** The Kontenblatt of one account for a period. */ export interface IAccountSheet { accountNumber: string; periodFrom?: string; periodTo?: string; /** `null` when no opening balance is recorded */ openingCents: number | null; /** the signed sum of the lines before the period, within the entries handed in */ carriedCents: number; /** the lines of the period, by day and then in the order the entries came in */ lines: IAccountSheetLine[]; debitCents: number; creditCents: number; /** opening (or 0) + carried + period debit − period credit */ closingCents: number; } export interface IOpenItemsOptions { kind?: TOposKind; includeSettled?: boolean; /** only lines up to and including this day, `YYYY-MM-DD` */ asOf?: string; } const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/u; const requireDay = (valueArg: string, nameArg: string): string => { const parsed = new Date(`${valueArg}T00:00:00.000Z`); if (!ISO_DAY.test(valueArg) || Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== valueArg) { throw new Error(`${nameArg} must be a day as YYYY-MM-DD, not "${valueArg}"`); } return valueArg; }; const requireCents = (valueArg: number, whereArg: string): number => { if (!Number.isSafeInteger(valueArg)) { throw new Error(`${whereArg}: ${valueArg} is not a whole number of cents`); } return valueArg; }; /** The period of the options, its days checked: a day as `YYYY-MM-DD` that exists, and an end on or after the beginning. */ export const ledgerPeriodOf = (optionsArg: ILedgerPeriodOptions | undefined): { from?: string; to?: string } => { const from = optionsArg?.periodFrom === undefined ? undefined : requireDay(optionsArg.periodFrom, 'periodFrom'); const to = optionsArg?.periodTo === undefined ? undefined : requireDay(optionsArg.periodTo, 'periodTo'); if (from !== undefined && to !== undefined && to < from) { throw new Error(`the period ends (${to}) before it begins (${from})`); } return { from, to }; }; /** Where a line falls against a period: before it, in it, or after it. */ const placeOf = (dayArg: string, periodArg: { from?: string; to?: string }): 'prior' | 'period' | 'after' => { if (periodArg.to !== undefined && dayArg > periodArg.to) return 'after'; if (periodArg.from !== undefined && dayArg < periodArg.from) return 'prior'; return 'period'; }; /** * The order of a listing by account number: numbers of digits only by their * value — so the general-ledger accounts (four digits) come before the * debtors (10000–69999) and the creditors (70000–99999) — and, of equal * value, by their text (`0027` before `27`). Numbers with other characters * follow, by their text. */ const DIGITS = /^\d+$/u; const compareAccountNumbers = (leftArg: string, rightArg: string): number => { const leftDigits = DIGITS.test(leftArg); const rightDigits = DIGITS.test(rightArg); if (leftDigits !== rightDigits) return leftDigits ? -1 : 1; if (leftDigits) { const leftValue = leftArg.replace(/^0+/u, ''); const rightValue = rightArg.replace(/^0+/u, ''); if (leftValue.length !== rightValue.length) return leftValue.length - rightValue.length; if (leftValue !== rightValue) return leftValue < rightValue ? -1 : 1; } return leftArg < rightArg ? -1 : leftArg > rightArg ? 1 : 0; }; /** What a line adds to the turnover of its side: its amount, negative on a Generalumkehr line. */ const turnoverOf = (lineArg: ILedgerLine): number => (lineArg.generalumkehr ? -lineArg.amountCents : lineArg.amountCents); /** The lines by day, and within a day in the order they came in. */ const inDayOrder = (linesArg: readonly ILedgerLine[]): ILedgerLine[] => linesArg .map((lineArg, indexArg) => ({ line: lineArg, index: indexArg })) .sort((leftArg, rightArg) => leftArg.line.date.localeCompare(rightArg.line.date) || leftArg.index - rightArg.index) .map(({ line }) => line); /** * Every line of every entry, in the order the entries and their lines came * in. A negative amount books on the other side, as DATEV reads it; a line of * 0 is no line. The lines of a Generalumkehr keep their sides and count * negative there. Refuses an entry that does not balance, an amount that is * not a whole number of cents, an id given twice, a date that is no date and * a Generalumkehr with a negative amount. */ export function ledgerLinesOf(entries: readonly ILedgerEntryInput[]): ILedgerLine[] { const seen = new Set(); const result: ILedgerLine[] = []; for (const entry of entries) { if (typeof entry.id !== 'string' || entry.id.length === 0) { throw new Error('every entry needs an id'); } if (seen.has(entry.id)) { throw new Error(`the entry ${entry.id} is given twice, and would be counted twice`); } seen.add(entry.id); if (!(entry.date instanceof Date) || Number.isNaN(entry.date.getTime())) { throw new Error(`the entry ${entry.id} has no valid date`); } if (entry.generalumkehr !== undefined && typeof entry.generalumkehr !== 'boolean') { throw new Error(`the entry ${entry.id} has a generalumkehr that is neither true nor false`); } const generalumkehr = entry.generalumkehr === true; const date = entry.date.toISOString().slice(0, 10); let sum = 0; for (const [index, line] of entry.lines.entries()) { const amount = requireCents(line.amountCents, `entry ${entry.id}, line ${index + 1}`); if (amount === 0) continue; if (generalumkehr && amount < 0) { throw new Error( `entry ${entry.id}, line ${index + 1}: a Generalumkehr line states its amount positive, the mark makes it count negative; got ${amount}`, ); } const side: TLineSide = amount > 0 ? line.side : line.side === 'debit' ? 'credit' : 'debit'; const amountCents = Math.abs(amount); const turnoverCents = generalumkehr ? -amountCents : amountCents; const signedCents = side === 'debit' ? turnoverCents : -turnoverCents; sum += signedCents; result.push({ entryId: entry.id, date, accountNumber: line.accountNumber, counterAccount: line.counterAccount, side, amountCents, generalumkehr, opening: entry.opening === true, signedCents, buKey: line.buKey, buchungstext: line.buchungstext, ...(line.belegfeld1 ? { belegfeld1: line.belegfeld1 } : {}), ...(line.belegfeld2 ? { belegfeld2: line.belegfeld2 } : {}), ...(line.costCenter1 ? { costCenter1: line.costCenter1 } : {}), ...(line.costCenter2 ? { costCenter2: line.costCenter2 } : {}), ...(entry.reference ? { reference: entry.reference } : {}), ...(line.docLink ? { docLink: line.docLink } : {}), }); } if (sum !== 0) { throw new Error(`the entry ${entry.id} does not balance: its debits and credits differ by ${sum} cents`); } } return result; } /** * The Summen- und Saldenliste of the entries: per account the opening * balance, what was booked before the period and in it, the cumulated sums * and the balance. Accounts that carry only an opening balance are listed. * The accounts are listed by account number, a number of digits by its * value: the general-ledger accounts (four digits) first, then the debtors * (10000–69999) and the creditors (70000–99999); of equal value (`0027`, * `27`) by the text, and a number with other characters after them all. * A Generalumkehr line lowers the sum of its side, so an entry and its * Generalumkehr leave the turnover as if neither had been booked. The lines * of an opening entry (up to the period's end) are the opening balances, not * turnover. */ export function trialBalanceOf(entries: readonly ILedgerEntryInput[], options?: ITrialBalanceOptions): ITrialBalance { const period = ledgerPeriodOf(options); const lines = ledgerLinesOf(entries); const hasOpeningBalances = options?.opening !== undefined || lines.some((lineArg) => lineArg.opening && placeOf(lineArg.date, period) !== 'after'); const rows = new Map(); const rowOf = (accountArg: string): ITrialBalanceAccount => { let row = rows.get(accountArg); if (!row) { row = { accountNumber: accountArg, openingCents: hasOpeningBalances ? 0 : null, priorDebitCents: 0, priorCreditCents: 0, periodDebitCents: 0, periodCreditCents: 0, cumulativeDebitCents: 0, cumulativeCreditCents: 0, balanceCents: 0, }; rows.set(accountArg, row); } return row; }; let openingDifferenceCents = 0; const openingAccounts = new Set(); for (const opening of options?.opening ?? []) { if (openingAccounts.has(opening.accountNumber)) { throw new Error(`the opening balance of ${opening.accountNumber} is given twice`); } openingAccounts.add(opening.accountNumber); const cents = requireCents(opening.signedCents, `the opening balance of ${opening.accountNumber}`); rowOf(opening.accountNumber).openingCents = cents; openingDifferenceCents += cents; } for (const line of lines) { const place = placeOf(line.date, period); if (place === 'after') continue; const row = rowOf(line.accountNumber); if (line.opening) { row.openingCents = (row.openingCents ?? 0) + line.signedCents; openingDifferenceCents += line.signedCents; continue; } if (place === 'prior') { if (line.side === 'debit') row.priorDebitCents += turnoverOf(line); else row.priorCreditCents += turnoverOf(line); } else if (line.side === 'debit') { row.periodDebitCents += turnoverOf(line); } else { row.periodCreditCents += turnoverOf(line); } } let totalDebitCents = 0; let totalCreditCents = 0; const accounts = [...rows.values()].sort((leftArg, rightArg) => compareAccountNumbers(leftArg.accountNumber, rightArg.accountNumber)); for (const row of accounts) { row.cumulativeDebitCents = row.priorDebitCents + row.periodDebitCents; row.cumulativeCreditCents = row.priorCreditCents + row.periodCreditCents; row.balanceCents = (row.openingCents ?? 0) + row.cumulativeDebitCents - row.cumulativeCreditCents; totalDebitCents += row.cumulativeDebitCents; totalCreditCents += row.cumulativeCreditCents; } return { ...(period.from !== undefined ? { periodFrom: period.from } : {}), ...(period.to !== undefined ? { periodTo: period.to } : {}), accounts, hasOpeningBalances, openingDifferenceCents, totalDebitCents, totalCreditCents, isBalanced: totalDebitCents === totalCreditCents && openingDifferenceCents === 0, }; } /** * The Kontenblatt of one account: its lines in the period, by day and then in * the order the entries came in, each with the running balance, which starts * from the opening balance and what was booked before the period. A * Generalumkehr line stands on its side with a negative amount. The lines of * an opening entry (up to the period's end) are the opening balance. */ export function accountSheetOf( entries: readonly ILedgerEntryInput[], accountNumber: string, options?: IAccountSheetOptions, ): IAccountSheet { const period = ledgerPeriodOf(options); let openingCents = options?.openingCents === undefined ? null : requireCents(options.openingCents, `the opening balance of ${accountNumber}`); const ofAccount = inDayOrder(ledgerLinesOf(entries).filter((lineArg) => lineArg.accountNumber === accountNumber)); let carriedCents = 0; let debitCents = 0; let creditCents = 0; const periodLines: ILedgerLine[] = []; for (const line of ofAccount) { const place = placeOf(line.date, period); if (line.opening) { if (place !== 'after') openingCents = (openingCents ?? 0) + line.signedCents; continue; } if (place === 'prior') carriedCents += line.signedCents; else if (place === 'period') periodLines.push(line); } let running = (openingCents ?? 0) + carriedCents; const lines: IAccountSheetLine[] = periodLines.map((line) => { running += line.signedCents; if (line.side === 'debit') debitCents += turnoverOf(line); else creditCents += turnoverOf(line); return { entryId: line.entryId, date: line.date, counterAccount: line.counterAccount, buchungstext: line.buchungstext, ...(line.belegfeld1 ? { belegfeld1: line.belegfeld1 } : {}), ...(line.reference ? { reference: line.reference } : {}), ...(line.docLink ? { docLink: line.docLink } : {}), buKey: line.buKey, debitCents: line.side === 'debit' ? turnoverOf(line) : 0, creditCents: line.side === 'credit' ? turnoverOf(line) : 0, balanceCents: running, generalumkehr: line.generalumkehr, }; }); return { accountNumber, ...(period.from !== undefined ? { periodFrom: period.from } : {}), ...(period.to !== undefined ? { periodTo: period.to } : {}), openingCents, carriedCents, lines, debitCents, creditCents, closingCents: (openingCents ?? 0) + carriedCents + debitCents - creditCents, }; } /** * The open items of the personal accounts in the entries (see * `deriveOpenItems`): a line without its own Belegfeld 1 falls back to its * entry's reference, as in the database ledger's OPOS. The lines are read by * day and within a day in the order the entries came in, as the database * ledger reads them by date, so an item's first and last day and its aging do * not depend on the order the entries are handed in; its entry ids follow the * days, and within a day the order the entries came in. */ export function openItemsOf( entries: readonly ILedgerEntryInput[], policy: IAccountPolicy, options?: IOpenItemsOptions, ): IOpenItem[] { const asOf = options?.asOf === undefined ? undefined : requireDay(options.asOf, 'asOf'); const rows: IOposLineRow[] = inDayOrder(ledgerLinesOf(entries).filter((lineArg) => asOf === undefined || lineArg.date <= asOf)) .map((lineArg) => ({ entryId: lineArg.entryId, accountNumber: lineArg.accountNumber, belegfeld1: lineArg.belegfeld1 || lineArg.reference || '', side: lineArg.side, amountCents: turnoverOf(lineArg), date: new Date(`${lineArg.date}T00:00:00.000Z`), })); return deriveOpenItems(rows, policy, { ...(options?.kind ? { kind: options.kind } : {}), ...(options?.includeSettled ? { includeSettled: true } : {}), }); }