/** * Balance computation for the v2 ledger: always aggregated from the * journal, never incrementally stored. Exact integer cents throughout. */ import type * as plugins from './plugins.js'; import { JournalEntry } from './skr.classes.journalentry.js'; import { getDbSync } from './skr.database.js'; import type { TSKRType } from './skr.types.js'; import { assertSkrType } from './core/core.chart.js'; export interface IAccountBalanceCents { accountNumber: string; debitCents: number; creditCents: number; /** debit - credit; sign interpretation belongs to the account type */ balanceCents: number; } export interface ITrialBalanceCents { accounts: IAccountBalanceCents[]; totalDebitCents: number; totalCreditCents: number; isBalanced: boolean; } export interface IBalanceQueryOptions { dateFrom?: Date; dateTo?: Date; /** include festgeschriebene entries (default true) */ includeFinalized?: boolean; } function entryFilter( skrType: TSKRType, options?: IBalanceQueryOptions, ): plugins.nosqldb.MongoFilter { const statuses: Array = options?.includeFinalized === false ? ['posted'] : ['posted', 'finalized']; const filter: plugins.nosqldb.MongoFilter = { schemaVersion: 2, skrType, status: { $in: statuses }, }; if (options?.dateFrom || options?.dateTo) { filter.date = { ...(options.dateFrom ? { $gte: options.dateFrom } : {}), ...(options.dateTo ? { $lte: options.dateTo } : {}), }; } return filter; } /** Groups per page: the client's largest page, so a usual ledger is read in one round trip. */ const GROUP_PAGE_LIMIT = 10_000; type TSideTotals = Map; /** * Debit and credit cents per account over the lines of the matching * entries, summed server-side per (account, side) and read page by page in * group key order until every group is in. An account whose lines carry * neither side is listed with zero on both sides. */ async function sideTotalsByAccount( query: { filter: plugins.nosqldb.MongoFilter; elementFilter?: { 'lines.accountNumber': string }; }, session?: plugins.nosqldb.SmartdataSession, ): Promise { const totals: TSideTotals = new Map(); const groups = JournalEntry.iterateGroupedTotals({ groupBy: ['lines.accountNumber', 'lines.side'], unwind: 'lines', sums: ['lines.amountCents'], filter: query.filter, ...(query.elementFilter ? { elementFilter: query.elementFilter } : {}), limit: GROUP_PAGE_LIMIT, ...(session ? { session } : {}), }); for await (const row of groups) { const accountNumber = row.group['lines.accountNumber']; const side = row.group['lines.side']; const amountCents = row.sums['lines.amountCents']; if (typeof accountNumber !== 'string' || typeof amountCents !== 'number') { throw new Error(`A journal line group has no account number or amount: ${JSON.stringify(row.group)}`); } const account = totals.get(accountNumber) ?? { debitCents: 0, creditCents: 0 }; if (side === 'debit') account.debitCents += amountCents; else if (side === 'credit') account.creditCents += amountCents; totals.set(accountNumber, account); } return totals; } /** * Aggregated trial balance over all schemaVersion-2 entries. */ export async function aggregateTrialBalance( skrType: TSKRType, options?: IBalanceQueryOptions, ): Promise { assertSkrType(skrType); // One transaction reads every page from one snapshot, so an entry posted // between two pages cannot land on one side of the balance only. const session = getDbSync().createSession(); let totals: TSideTotals = new Map(); try { await session.withTransaction(async (transaction) => { totals = await sideTotalsByAccount({ filter: entryFilter(skrType, options) }, transaction); }); } finally { await session.close(); } const accounts: IAccountBalanceCents[] = [...totals.entries()] .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) .map(([accountNumber, { debitCents, creditCents }]) => ({ accountNumber, debitCents, creditCents, balanceCents: debitCents - creditCents, })); const totalDebitCents = accounts.reduce((sum, account) => sum + account.debitCents, 0); const totalCreditCents = accounts.reduce((sum, account) => sum + account.creditCents, 0); return { accounts, totalDebitCents, totalCreditCents, isBalanced: totalDebitCents === totalCreditCents, }; } /** * Exact balance of one account. The entry filter selects the entries that * touch the account; the element filter keeps only the account's own lines, * so at most one group per side is read. */ export async function aggregateAccountBalance( accountNumber: string, skrType: TSKRType, options?: IBalanceQueryOptions, ): Promise { assertSkrType(skrType); const totals = await sideTotalsByAccount({ filter: { ...entryFilter(skrType, options), 'lines.accountNumber': accountNumber }, elementFilter: { 'lines.accountNumber': accountNumber }, }); const { debitCents, creditCents } = totals.get(accountNumber) ?? { debitCents: 0, creditCents: 0 }; return { accountNumber, debitCents, creditCents, balanceCents: debitCents - creditCents }; }