import * as plugins from './plugins.js'; import { assertSkrType } from './core/core.chart.js'; import { Account } from './skr.classes.account.js'; import type { JournalEntry } from './skr.classes.journalentry.js'; import { JournalPoster } from './skr.posting.js'; import { postJournalInput, postTransactionInput, reverseJournalInput, reverseTransactionInput, } from './skr.journalbooking.js'; import { aggregateAccountBalance, aggregateTrialBalance } from './skr.balances.js'; import { accountLineViews } from './skr.txview.js'; import type { TAccountType, TSKRType, ITransactionData, ITransactionView, IJournalEntry, IJournalEntryLine, IAccountBalance, } from './skr.types.js'; import { SKR03_ACCOUNTS } from './skr03.data.js'; import { SKR04_ACCOUNTS } from './skr04.data.js'; // Module-level Maps for O(1) SKR standard lookups const STANDARD_SKR_MAP = { SKR03: new Map(SKR03_ACCOUNTS.map(a => [a.accountNumber, a])), SKR04: new Map(SKR04_ACCOUNTS.map(a => [a.accountNumber, a])), }; /** Signed balance in cents as the account type reads it (debit-normal or credit-normal). */ function typedBalanceCents(accountType: TAccountType, debitCents: number, creditCents: number): number { switch (accountType) { case 'asset': case 'expense': return debitCents - creditCents; case 'liability': case 'equity': case 'revenue': return creditCents - debitCents; } } /** The first and last millisecond (UTC) of a 'YYYY-MM' period, as the poster derives periods. */ function periodRange(period: string): { dateFrom: Date; dateTo: Date } { const match = /^(\d{4})-(\d{2})$/.exec(period); if (!match) { throw new Error(`Period ${period} is not in the format YYYY-MM`); } const year = Number.parseInt(match[1], 10); const month = Number.parseInt(match[2], 10); return { dateFrom: new Date(Date.UTC(year, month - 1, 1)), dateTo: new Date(Date.UTC(year, month, 1) - 1), }; } /** * Ledger operations of one chart on the hashed journal. Posting, reversing, * history and balances all go through the unified journal path * (skr.journalbooking.ts, JournalPoster, the balance aggregation). */ export class Ledger { private logger: plugins.smartlog.Smartlog; private poster = new JournalPoster(); constructor(private skrType: TSKRType) { assertSkrType(skrType); this.logger = new plugins.smartlog.Smartlog({ logContext: { company: 'fin.cx', companyunit: 'skr', containerName: 'Ledger', environment: 'local', runtime: 'node', zone: 'local', }, }); } /** * Post a transaction as a hashed two-line journal entry. Returns its * transaction-shaped view. */ public async postTransaction( transactionData: ITransactionData, ): Promise { this.logger.log( 'info', `Posting transaction: ${transactionData.description}`, ); const view = await postTransactionInput(this.skrType, transactionData, this.poster); this.logger.log( 'info', `Transaction ${view.transactionNumber} posted successfully`, ); return view; } /** * Post a journal entry with validation. Returns the hashed, immutable entry. */ public async postJournalEntry( journalData: IJournalEntry, ): Promise { this.logger.log( 'info', `Posting journal entry: ${journalData.description}`, ); // Validate against SKR standard (warnings only by default) await this.validateAccountsAgainstSKR(journalData.lines, { strict: false, // Start with warnings only warnOnNameMismatch: false // Names vary, don't spam logs }); const journalEntry = await postJournalInput(this.skrType, journalData, this.poster); this.logger.log( 'info', `Journal entry ${journalEntry.journalNumber} posted successfully`, ); return journalEntry; } /** * Validate accounts against SKR standard data */ private async validateAccountsAgainstSKR( lines: IJournalEntryLine[], options?: { strict?: boolean; warnOnNameMismatch?: boolean } ): Promise { const { strict = false, warnOnNameMismatch = false } = options || {}; const skrMap = STANDARD_SKR_MAP[this.skrType]; if (!skrMap) { this.logger.log('warn', `No SKR standard map available for ${this.skrType}`); return; } const uniqueAccountNumbers = [...new Set(lines.map(line => line.accountNumber))]; for (const accountNumber of uniqueAccountNumbers) { const standardAccount = skrMap.get(accountNumber); if (!standardAccount) { // An individual account of the books is what its parent is: its type is checked against the parent's const individualAccount = await Account.getAccountByNumber(accountNumber, this.skrType); const parentAccount = individualAccount?.parentAccountNumber ? skrMap.get(individualAccount.parentAccountNumber) : undefined; if (individualAccount && parentAccount) { if (individualAccount.accountType !== parentAccount.accountType) { const message = `Individual account ${accountNumber} type mismatch: its parent ${parentAccount.accountNumber} is '${parentAccount.accountType}', got '${individualAccount.accountType}'`; if (strict) { throw new Error(message); } else { this.logger.log('warn', message); } } continue; } // Special case: SKR04 class 8 is designated for custom accounts ("frei") if (this.skrType === 'SKR04' && accountNumber.startsWith('8')) { this.logger.log('debug', `Account ${accountNumber} is in SKR04 class 8 (custom accounts allowed)`); continue; } const message = `Account ${accountNumber} is not a standard ${this.skrType} account`; if (strict) { throw new Error(message); } else { this.logger.log('warn', message); } continue; } // Get actual account from database to compare const dbAccount = await Account.getAccountByNumber(accountNumber, this.skrType); if (!dbAccount) { // Account doesn't exist in DB; posting refuses it (validateAccountForPosting) continue; } // Validate type and class match SKR standard if (dbAccount.accountType !== standardAccount.accountType) { const message = `Account ${accountNumber} type mismatch: expected '${standardAccount.accountType}', got '${dbAccount.accountType}'`; if (strict) { throw new Error(message); } else { this.logger.log('warn', message); } } if (dbAccount.accountClass !== standardAccount.accountClass) { const message = `Account ${accountNumber} class mismatch: expected ${standardAccount.accountClass}, got ${dbAccount.accountClass}`; if (strict) { throw new Error(message); } else { this.logger.log('warn', message); } } // Warn on name mismatch (common and acceptable in practice) if (warnOnNameMismatch && dbAccount.accountName !== standardAccount.accountName) { this.logger.log('info', `Account ${accountNumber} name differs from SKR standard: '${dbAccount.accountName}' vs '${standardAccount.accountName}'` ); } } } /** * Reverse a two-line entry via Storno; the original is never mutated (GoBD). * Returns the Storno's transaction view. */ public async reverseTransaction(transactionId: string): Promise { this.logger.log('info', `Reversing transaction: ${transactionId}`); const storno = await reverseTransactionInput(this.skrType, transactionId, this.poster); this.logger.log('info', `Transaction reversed: ${storno.transactionNumber}`); return storno; } /** * Reverse a journal entry via Storno; the original is never mutated (GoBD). */ public async reverseJournalEntry(journalId: string): Promise { this.logger.log('info', `Reversing journal entry: ${journalId}`); const storno = await reverseJournalInput(this.skrType, journalId, this.poster); this.logger.log('info', `Journal entry reversed: ${storno.journalNumber}`); return storno; } /** * Account history: one view per journal line on the account, by date. */ public async getAccountHistory( accountNumber: string, dateFrom?: Date, dateTo?: Date, ): Promise { const account = await Account.getAccountByNumber( accountNumber, this.skrType, ); if (!account) { throw new Error(`Account ${accountNumber} not found`); } const views = await accountLineViews(accountNumber, this.skrType); return views.filter((view) => { if (dateFrom && view.date < dateFrom) return false; if (dateTo && view.date > dateTo) return false; return true; }); } /** * Get account balance at a specific date */ public async getAccountBalance( accountNumber: string, asOfDate?: Date, ): Promise { const account = await Account.getAccountByNumber( accountNumber, this.skrType, ); if (!account) { throw new Error(`Account ${accountNumber} not found`); } const totals = await aggregateAccountBalance( accountNumber, this.skrType, asOfDate ? { dateTo: asOfDate } : undefined, ); return { accountNumber, debitTotal: totals.debitCents / 100, creditTotal: totals.creditCents / 100, balance: typedBalanceCents(account.accountType, totals.debitCents, totals.creditCents) / 100, lastUpdated: new Date(), }; } /** * Close accounting period (create closing entries) */ public async closeAccountingPeriod( period: string, // Format: YYYY-MM closingAccountNumber: string = '9400', // Default P&L account ): Promise { this.logger.log('info', `Closing accounting period: ${period}`); const closingEntries: JournalEntry[] = []; // Get all revenue and expense accounts const revenueAccounts = await Account.getAccountsByType( 'revenue', this.skrType, ); const expenseAccounts = await Account.getAccountsByType( 'expense', this.skrType, ); // Totals of every account in the period, from the journal const trialBalance = await aggregateTrialBalance(this.skrType, periodRange(period)); const totalsByAccount = new Map( trialBalance.accounts.map((totals) => [totals.accountNumber, totals]), ); const periodBalanceCents = (account: Account): number => { const totals = totalsByAccount.get(account.accountNumber); return totals ? typedBalanceCents(account.accountType, totals.debitCents, totals.creditCents) : 0; }; // Create closing entry for revenue accounts const revenueLines: IJournalEntryLine[] = []; let totalRevenueCents = 0; for (const account of revenueAccounts) { const balanceCents = periodBalanceCents(account); if (balanceCents !== 0) { // Revenue accounts have credit balance, so debit to close revenueLines.push({ accountNumber: account.accountNumber, debit: Math.abs(balanceCents) / 100, description: `Closing ${account.accountName}`, postingKey: 40, // Tax-free - internal closing entry }); totalRevenueCents += Math.abs(balanceCents); } } if (totalRevenueCents > 0) { // Credit the closing account revenueLines.push({ accountNumber: closingAccountNumber, credit: totalRevenueCents / 100, description: 'Revenue closing to P&L', postingKey: 40, // Tax-free - internal closing entry }); const revenueClosingEntry = await this.postJournalEntry({ date: new Date(), description: `Closing revenue accounts for period ${period}`, reference: `CLOSE-REV-${period}`, lines: revenueLines, skrType: this.skrType, }); closingEntries.push(revenueClosingEntry); } // Create closing entry for expense accounts const expenseLines: IJournalEntryLine[] = []; let totalExpenseCents = 0; for (const account of expenseAccounts) { const balanceCents = periodBalanceCents(account); if (balanceCents !== 0) { // Expense accounts have debit balance, so credit to close expenseLines.push({ accountNumber: account.accountNumber, credit: Math.abs(balanceCents) / 100, description: `Closing ${account.accountName}`, postingKey: 40, // Tax-free - internal closing entry }); totalExpenseCents += Math.abs(balanceCents); } } if (totalExpenseCents > 0) { // Debit the closing account expenseLines.push({ accountNumber: closingAccountNumber, debit: totalExpenseCents / 100, description: 'Expense closing to P&L', postingKey: 40, // Tax-free - internal closing entry }); const expenseClosingEntry = await this.postJournalEntry({ date: new Date(), description: `Closing expense accounts for period ${period}`, reference: `CLOSE-EXP-${period}`, lines: expenseLines, skrType: this.skrType, }); closingEntries.push(expenseClosingEntry); } this.logger.log( 'info', `Period ${period} closed with ${closingEntries.length} entries`, ); return closingEntries; } /** * Validate double-entry rules */ public validateDoubleEntry( debitAmount: number, creditAmount: number, ): boolean { return Math.abs(debitAmount - creditAmount) < 0.01; } /** * Get unbalanced transactions (for audit). The journal poster enforces an * exact balance atomically, so there are none; chain integrity is checked * with verifyHashChain(). */ public async getUnbalancedTransactions(): Promise { return []; } /** * Recalculate the balance fields every account caches (debitTotal, * creditTotal, balance) from the journal. */ public async recalculateAllBalances(): Promise { this.logger.log('info', 'Recalculating all account balances'); const accounts = await Account.getInstances({ skrType: this.skrType }); const trialBalance = await aggregateTrialBalance(this.skrType); const totalsByAccount = new Map( trialBalance.accounts.map((totals) => [totals.accountNumber, totals]), ); for (const account of accounts) { const totals = totalsByAccount.get(account.accountNumber); const debitCents = totals?.debitCents ?? 0; const creditCents = totals?.creditCents ?? 0; account.debitTotal = debitCents / 100; account.creditTotal = creditCents / 100; account.balance = typedBalanceCents(account.accountType, debitCents, creditCents) / 100; account.updatedAt = new Date(); await account.save(); } this.logger.log( 'info', `Recalculated balances for ${accounts.length} accounts`, ); } }