import * as plugins from './plugins.js'; import * as path from 'path'; import { ChartOfAccounts } from './skr.classes.chartofaccounts.js'; import { Ledger } from './skr.classes.ledger.js'; import { Reports } from './skr.classes.reports.js'; import { Account } from './skr.classes.account.js'; import { Transaction } from './skr.classes.transaction.js'; import { JournalEntry } from './skr.classes.journalentry.js'; import { SkrExport, type IExportOptions } from './skr.export.js'; import { LedgerExporter } from './skr.export.ledger.js'; import { AccountsExporter } from './skr.export.accounts.js'; import { BalancesExporter } from './skr.export.balances.js'; import { PdfReportGenerator, type IPdfReportOptions } from './skr.export.pdf.js'; import { SecurityManager, type ISigningOptions } from './skr.security.js'; import * as core from './core/index.js'; import { JournalPoster, type IPostDraftOptions } from './skr.posting.js'; import { listTransactionViews, postJournalInput, postTransactionInput, reverseJournalInput, reverseTransactionInput, } from './skr.journalbooking.js'; import { festschreibePeriod, getPeriodState, type ILedgerPeriodState } from './skr.period.js'; import { verifyHashChain, type IChainVerificationResult } from './skr.verify.js'; import { aggregateTrialBalance, aggregateAccountBalance, type IBalanceQueryOptions, type ITrialBalanceCents, type IAccountBalanceCents, } from './skr.balances.js'; import { entryToTransactionView, accountLineViews } from './skr.txview.js'; import { listAppliedMigrations, type ISkrMigrationRecord } from '../ts_migration/index.js'; import { InvoiceAdapter } from './skr.invoice.adapter.js'; import { InvoiceStorage } from './skr.invoice.storage.js'; import { InvoiceBookingEngine, type IBookingOptions, type IBookingResult } from './skr.invoice.booking.js'; import type { IInvoice, IInvoiceFilter, IInvoiceImportOptions, IInvoiceExportOptions, IBookingRules, TInvoiceDirection, } from './skr.invoice.entity.js'; import type { TDatabaseConfig, TSKRType, IAccountData, IAccountFilter, ITransactionData, ITransactionFilter, IJournalEntry, IReportParams, ITrialBalanceReport, IIncomeStatement, IBalanceSheet, IAccountBalance, ITransactionView, } from './skr.types.js'; /** * Main API class for SKR accounting operations */ export class SkrApi { private chartOfAccounts: ChartOfAccounts; private ledger: Ledger | null = null; private reports: Reports | null = null; private logger: plugins.smartlog.Smartlog; private initialized: boolean = false; private currentSKRType: TSKRType | null = null; private invoiceAdapter: InvoiceAdapter | null = null; private invoiceStorage: InvoiceStorage | null = null; private invoiceBookingEngine: InvoiceBookingEngine | null = null; private journalPoster: JournalPoster = new JournalPoster(); /** the books' individual accounts as stored, read on `initialize` and after every change through this API; the default policy carries them */ private individualAccounts: plugins.chartdata.IIndividualAccountDeclaration[] = []; constructor(private config: TDatabaseConfig) { this.chartOfAccounts = new ChartOfAccounts(config); this.logger = new plugins.smartlog.Smartlog({ logContext: { company: 'fin.cx', companyunit: 'skr', containerName: 'SkrApi', environment: 'local', runtime: 'node', zone: 'local', }, }); } /** * Initialize the API with specified SKR type */ public async initialize(skrType: TSKRType): Promise { core.assertSkrType(skrType); this.logger.log('info', `Initializing SKR API with ${skrType}`); // Connect, run the versioned migrations and prepare every collection — // before the chart is seeded and before any transaction opens await this.chartOfAccounts.init(); // Initialize chart of accounts if (skrType === 'SKR03') { await this.chartOfAccounts.initializeSKR03(); } else { await this.chartOfAccounts.initializeSKR04(); } this.currentSKRType = skrType; this.individualAccounts = await this.chartOfAccounts.getIndividualAccounts(); this.ledger = new Ledger(skrType); this.reports = new Reports(skrType); // v2 posting path: transactions are mandatory — fail hard, // filing-grade posting has no non-transactional fallback await this.journalPoster.assertTransactionSupport(); // Initialize invoice components this.invoiceAdapter = new InvoiceAdapter(); const invoicePath = this.config.invoiceExportPath || path.resolve(process.cwd(), 'exports', 'invoices'); this.invoiceStorage = new InvoiceStorage(invoicePath); this.invoiceBookingEngine = new InvoiceBookingEngine(skrType); this.initialized = true; this.logger.log('info', 'SKR API initialized successfully'); } /** * Ensure API is initialized */ private ensureInitialized(): void { if (!this.initialized || !this.currentSKRType) { throw new Error('API not initialized. Call initialize() first.'); } } // ========== Account Management ========== /** * Create a new account */ public async createAccount( accountData: Partial, ): Promise { this.ensureInitialized(); return await this.chartOfAccounts.createCustomAccount(accountData); } /** * Get account by number */ public async getAccount(accountNumber: string): Promise { this.ensureInitialized(); return await this.chartOfAccounts.getAccountByNumber(accountNumber); } /** * Update an account */ public async updateAccount( accountNumber: string, updates: Partial, ): Promise { this.ensureInitialized(); const account = await this.chartOfAccounts.updateAccount(accountNumber, updates); if (account.parentAccountNumber) { // an individual account's name is its declaration's await this.getIndividualAccounts(); } return account; } /** * Delete an account */ public async deleteAccount(accountNumber: string): Promise { this.ensureInitialized(); await this.chartOfAccounts.deleteAccount(accountNumber); await this.getIndividualAccounts(); } /** * Declare an individual account of the books (Individualkonto) on a number * DATEV leaves free after the account it belongs to; the default policy * (`getDefaultPolicy`) carries it from then on. @fin.cx/chartdata checks it * together with the individual accounts already declared and refuses it * with its `IndividualAccountsError` (`problems`); nothing is stored then. */ public async declareIndividualAccount( declaration: plugins.chartdata.IIndividualAccountDeclaration, ): Promise { this.ensureInitialized(); const account = await this.chartOfAccounts.declareIndividualAccount(declaration); await this.getIndividualAccounts(); return account; } /** * The declarations of the books' individual accounts as stored, by account * number. Reading them also refreshes the ones the default policy carries, * so declarations stored by another instance are taken. */ public async getIndividualAccounts(): Promise { this.ensureInitialized(); this.individualAccounts = await this.chartOfAccounts.getIndividualAccounts(); return [...this.individualAccounts]; } /** * List accounts with optional filter */ public async listAccounts(filter?: IAccountFilter): Promise { this.ensureInitialized(); return await this.chartOfAccounts.getAllAccounts(filter); } /** * Search accounts by term */ public async searchAccounts(searchTerm: string): Promise { this.ensureInitialized(); return await this.chartOfAccounts.searchAccounts(searchTerm); } /** * Get accounts by class */ public async getAccountsByClass(accountClass: number): Promise { this.ensureInitialized(); return await this.chartOfAccounts.getAccountsByClass(accountClass); } /** * Get accounts by type */ public async getAccountsByType( accountType: IAccountData['accountType'], ): Promise { this.ensureInitialized(); return await this.chartOfAccounts.getAccountsByType(accountType); } // ========== Transaction Management (v2: hashed journal entries) ========== /** * Post a simple transaction. Since v2 this creates a hashed two-line * journal entry (exact cents) — the Transaction collection is frozen. */ public async postTransaction( transactionData: ITransactionData, ): Promise { this.ensureInitialized(); return postTransactionInput(this.currentSKRType!, transactionData, this.journalPoster); } /** * Post a journal entry. Since v2 the entry is hashed, sequenced, and * immutable; float inputs are converted to exact cents with a drift guard. */ public async postJournalEntry( journalData: IJournalEntry, ): Promise { this.ensureInitialized(); return postJournalInput(this.currentSKRType!, journalData, this.journalPoster); } /** * Get a transaction view by id (two-line v2 entries project 1:1). */ public async getTransaction( transactionId: string, ): Promise { this.ensureInitialized(); const entry = await JournalEntry.getInstance({ id: transactionId }); if (!entry || entry.schemaVersion !== 2) return null; return entryToTransactionView(entry); } /** * List transaction views with optional filter (two-line v2 entries). */ public async listTransactions( filter?: ITransactionFilter, ): Promise { this.ensureInitialized(); return listTransactionViews(this.currentSKRType!, filter); } /** * Get per-line transaction views for one account. */ public async getAccountTransactions( accountNumber: string, ): Promise { this.ensureInitialized(); return accountLineViews(accountNumber, this.currentSKRType!); } /** * Reverse via Storno — the original entry is never mutated (GoBD). */ public async reverseTransaction(transactionId: string): Promise { this.ensureInitialized(); return reverseTransactionInput(this.currentSKRType!, transactionId, this.journalPoster); } /** * Reverse a journal entry via Storno. */ public async reverseJournalEntry(journalId: string): Promise { this.ensureInitialized(); return reverseJournalInput(this.currentSKRType!, journalId, this.journalPoster); } // ========== Reporting ========== /** * Generate trial balance */ public async generateTrialBalance( params?: IReportParams, ): Promise { this.ensureInitialized(); if (!this.reports) throw new Error('Reports not initialized'); return await this.reports.getTrialBalance(params); } /** * Generate income statement */ public async generateIncomeStatement( params?: IReportParams, ): Promise { this.ensureInitialized(); if (!this.reports) throw new Error('Reports not initialized'); return await this.reports.getIncomeStatement(params); } /** * Generate balance sheet */ public async generateBalanceSheet( params?: IReportParams, ): Promise { this.ensureInitialized(); if (!this.reports) throw new Error('Reports not initialized'); return await this.reports.getBalanceSheet(params); } /** * Generate general ledger */ public async generateGeneralLedger(params?: IReportParams): Promise { this.ensureInitialized(); if (!this.reports) throw new Error('Reports not initialized'); return await this.reports.getGeneralLedger(params); } /** * Generate cash flow statement */ public async generateCashFlowStatement(params?: IReportParams): Promise { this.ensureInitialized(); if (!this.reports) throw new Error('Reports not initialized'); return await this.reports.getCashFlowStatement(params); } /** * Export report to CSV */ public async exportReportToCSV( reportType: 'trial_balance' | 'income_statement' | 'balance_sheet', params?: IReportParams, ): Promise { this.ensureInitialized(); if (!this.reports) throw new Error('Reports not initialized'); return await this.reports.exportToCSV(reportType, params); } /** * Export to DATEV format (EXTF 700 Buchungsstapel over v2 entries). * For a fully parameterized export use exportDatevBuchungsstapel(). */ public async exportToDATEV(params?: IReportParams): Promise { this.ensureInitialized(); const dateFrom = params?.dateFrom ?? new Date('1970-01-01T00:00:00.000Z'); const dateTo = params?.dateTo ?? new Date('2999-12-31T00:00:00.000Z'); const { csv } = await this.exportDatevBuchungsstapel({ dateFrom, dateTo, consultantNumber: 0, clientNumber: 0, fiscalYearStart: new Date(Date.UTC(dateFrom.getUTCFullYear(), 0, 1)), label: 'Buchungsstapel', }); return csv; } // ========== Period Management ========== /** * Close accounting period: post P&L-zeroing entries (v2) into the period. * Locking is a separate deliberate act — call festschreibePeriod() after. */ public async closePeriod( period: string, closingAccountNumber: string = '9400', ): Promise { this.ensureInitialized(); const [year, month] = period.split('-').map((part) => Number.parseInt(part, 10)); const dateFrom = new Date(Date.UTC(year, month - 1, 1)); const dateTo = new Date(Date.UTC(year, month, 0, 23, 59, 59, 999)); const trialBalance = await this.getTrialBalanceCents({ dateFrom, dateTo }); const revenueLines: core.IJournalLineDraft[] = []; const expenseLines: core.IJournalLineDraft[] = []; for (const balance of trialBalance.accounts) { const account = await Account.getAccountByNumber( balance.accountNumber, this.currentSKRType!, ); if (!account) continue; if (account.accountType === 'revenue') { const net = balance.creditCents - balance.debitCents; if (net !== 0) { revenueLines.push({ accountNumber: balance.accountNumber, counterAccount: closingAccountNumber, side: net > 0 ? 'debit' : 'credit', amountCents: Math.abs(net), buKey: '40', buchungstext: `Abschluss ${period}`, }); } } else if (account.accountType === 'expense') { const net = balance.debitCents - balance.creditCents; if (net !== 0) { expenseLines.push({ accountNumber: balance.accountNumber, counterAccount: closingAccountNumber, side: net > 0 ? 'credit' : 'debit', amountCents: Math.abs(net), buKey: '40', buchungstext: `Abschluss ${period}`, }); } } } const entries: JournalEntry[] = []; const closeDraft = async ( lines: core.IJournalLineDraft[], reference: string, ): Promise => { if (lines.length === 0) return; const debitSum = lines .filter((line) => line.side === 'debit') .reduce((sum, line) => sum + line.amountCents, 0); const creditSum = lines .filter((line) => line.side === 'credit') .reduce((sum, line) => sum + line.amountCents, 0); const net = debitSum - creditSum; if (net !== 0) { lines.push({ accountNumber: closingAccountNumber, counterAccount: lines[0].accountNumber, side: net > 0 ? 'credit' : 'debit', amountCents: Math.abs(net), buKey: '', buchungstext: `Abschluss ${period}`, }); } entries.push( await this.journalPoster.postDraft({ date: dateTo, description: `Periodenabschluss ${period}`, reference, skrType: this.currentSKRType!, currency: 'EUR', lines, }), ); }; await closeDraft(revenueLines, `CLOSE-REV-${period}`); await closeDraft(expenseLines, `CLOSE-EXP-${period}`); return entries; } /** * Get account balance (aggregated from v2 entries, exact cents inside). */ public async getAccountBalance( accountNumber: string, asOfDate?: Date, ): Promise { this.ensureInitialized(); const account = await Account.getAccountByNumber( accountNumber, this.currentSKRType!, ); if (!account) { throw new Error(`Account ${accountNumber} not found`); } const balance = await this.getAccountBalanceCents(accountNumber, { dateTo: asOfDate, }); const signed = account.accountType === 'asset' || account.accountType === 'expense' ? balance.balanceCents : -balance.balanceCents; return { accountNumber, debitTotal: balance.debitCents / 100, creditTotal: balance.creditCents / 100, balance: signed / 100, lastUpdated: new Date(), }; } /** * Refresh the (informational) balance caches on Account documents from the * aggregated v2 ledger. */ public async recalculateBalances(): Promise { this.ensureInitialized(); const trialBalance = await this.getTrialBalanceCents(); for (const balance of trialBalance.accounts) { const account = await Account.getAccountByNumber( balance.accountNumber, this.currentSKRType!, ); if (!account) continue; account.debitTotal = balance.debitCents / 100; account.creditTotal = balance.creditCents / 100; account.balance = account.accountType === 'asset' || account.accountType === 'expense' ? balance.balanceCents / 100 : -balance.balanceCents / 100; await account.save(); } } // ========== Import/Export ========== /** * Import accounts from CSV */ public async importAccountsFromCSV(csvContent: string): Promise { this.ensureInitialized(); return await this.chartOfAccounts.importAccountsFromCSV(csvContent); } /** * Export accounts to CSV */ public async exportAccountsToCSV(): Promise { this.ensureInitialized(); return await this.chartOfAccounts.exportAccountsToCSV(); } /** * Export Jahresabschluss in GoBD-compliant BagIt format * Creates a revision-safe export for 10-year archival */ public async exportJahresabschluss(options: IExportOptions): Promise { this.ensureInitialized(); if (!this.ledger || !this.reports || !this.currentSKRType) { throw new Error('API not fully initialized'); } this.logger.log('info', `Starting Jahresabschluss export for fiscal year ${options.fiscalYear}`); // Create export instance const exporter = new SkrExport(options); // Create BagIt structure await exporter.createBagItStructure(); await exporter.createExportMetadata(this.currentSKRType); await exporter.createSchemas(); // Export accounting data await this.exportLedgerData(exporter, options); await this.exportAccountData(exporter, options); await this.exportBalanceData(exporter, options); // Generate PDF reports if requested if (options.generatePdfReports) { await this.generatePdfReports(exporter, options); } // Sign export if requested if (options.signExport) { await this.signExport(exporter, options); } // Every payload file the exporters wrote belongs into the manifest await exporter.registerUnlistedDataFiles(); // Create manifests and validate await exporter.writeManifests(); const merkleRoot = await exporter.createMerkleTree(); const isValid = await exporter.validateBagIt(); if (!isValid) { throw new Error('BagIt validation failed'); } this.logger.log('ok', `Jahresabschluss export completed. Merkle root: ${merkleRoot}`); return options.exportPath; } /** * Export ledger data in NDJSON format */ private async exportLedgerData(exporter: SkrExport, options: IExportOptions): Promise { if (!this.ledger) throw new Error('Ledger not initialized'); const ledgerExporter = new LedgerExporter(exporter.directory); await ledgerExporter.initialize(); // Get all transactions for the period const transactions = await this.chartOfAccounts.getTransactions({ dateFrom: options.dateFrom, dateTo: options.dateTo }); // Export each transaction for (const transaction of transactions) { const transactionData = transaction; await ledgerExporter.exportTransaction(transactionData as any); } // Get all journal entries for the period // Use MongoDB query syntax for date range const journalEntries = await JournalEntry.getInstances({ date: { $gte: options.dateFrom, $lte: options.dateTo }, skrType: this.currentSKRType!, }); // Export each journal entry for (const entry of journalEntries) { const entryData = entry; await ledgerExporter.exportJournalEntry(entryData as any); } const entryCount = await ledgerExporter.close(); this.logger.log('info', `Exported ${entryCount} ledger entries`); } /** * Export account data in CSV format */ private async exportAccountData(exporter: SkrExport, options: IExportOptions): Promise { const accountsExporter = new AccountsExporter(exporter.directory); // Get all accounts const accounts = await this.chartOfAccounts.getAllAccounts(); // Add each account to export for (const account of accounts) { const accountData = account; accountsExporter.addAccount(accountData as any); } // Export to CSV and JSON await accountsExporter.exportToCSV(); await accountsExporter.exportToJSON(); this.logger.log('info', `Exported ${accountsExporter.getAccountCount()} accounts`); } /** * Export balance data in CSV format */ private async exportBalanceData(exporter: SkrExport, options: IExportOptions): Promise { if (!this.ledger) throw new Error('Ledger not initialized'); const balancesExporter = new BalancesExporter( exporter.directory, options.fiscalYear ); // Get all accounts with balances const accounts = await this.chartOfAccounts.getAllAccounts(); for (const account of accounts) { const balance = await this.ledger.getAccountBalance( account.accountNumber, options.dateTo ); if (balance) { balancesExporter.addBalance( account.accountNumber, account.accountName, balance as IAccountBalance, `${options.fiscalYear}` ); } } // Export balance reports await balancesExporter.exportToCSV(); await balancesExporter.exportTrialBalance(); await balancesExporter.exportClassSummary(); this.logger.log('info', `Exported ${balancesExporter.getBalanceCount()} account balances`); } /** * Generate PDF reports for the export */ private async generatePdfReports(exporter: SkrExport, options: IExportOptions): Promise { if (!this.reports) throw new Error('Reports not initialized'); const skrType = this.currentSKRType; if (!skrType) { throw new Error('API not initialized. Call initialize() first.'); } const pdfOptions: IPdfReportOptions = { companyName: options.companyInfo?.name || 'Unternehmen', companyAddress: options.companyInfo?.address, taxId: options.companyInfo?.taxId, registrationNumber: options.companyInfo?.registrationNumber, fiscalYear: options.fiscalYear, dateFrom: options.dateFrom, dateTo: options.dateTo, preparedDate: new Date() }; const pdfGenerator = new PdfReportGenerator(exporter.directory, pdfOptions); await pdfGenerator.initialize(); try { // Generate reports const trialBalance = await this.reports.getTrialBalance({ dateFrom: options.dateFrom, dateTo: options.dateTo, skrType, }); const incomeStatement = await this.reports.getIncomeStatement({ dateFrom: options.dateFrom, dateTo: options.dateTo, skrType, }); const balanceSheet = await this.reports.getBalanceSheet({ dateFrom: options.dateFrom, dateTo: options.dateTo, skrType, }); // Generate PDFs const jahresabschlussPdf = await pdfGenerator.generateJahresabschlussPdf( trialBalance, incomeStatement, balanceSheet ); // Save PDFs await pdfGenerator.savePdfReport('jahresabschluss.pdf', jahresabschlussPdf); // Store in BagIt structure await exporter.storeDocument(jahresabschlussPdf, 'jahresabschluss.pdf'); this.logger.log('info', 'PDF reports generated successfully'); } finally { await pdfGenerator.close(); } } /** * Sign the export with CAdES signature */ private async signExport(exporter: SkrExport, options: IExportOptions): Promise { const signingOptions: ISigningOptions = { certificatePem: options.signExport ? undefined : undefined, // Use provided cert or generate privateKeyPem: options.signExport ? undefined : undefined, includeTimestamp: options.timestampExport !== false }; const security = new SecurityManager(signingOptions); // Generate self-signed certificate if none provided let cert: string, key: string; if (!signingOptions.certificatePem) { const generated = await security.generateSelfSignedCertificate( options.companyInfo?.name || 'SKR Export System' ); cert = generated.certificate; key = generated.privateKey; } else { cert = signingOptions.certificatePem; key = signingOptions.privateKeyPem!; } // Sign the manifest const manifestPath = path.resolve( options.exportPath, `jahresabschluss_${options.fiscalYear}`, 'manifest-sha256.txt' ); await security.createDetachedSignature( manifestPath, path.resolve( options.exportPath, `jahresabschluss_${options.fiscalYear}`, 'data', 'metadata', 'signatures', 'manifest.cades' ) ); this.logger.log('info', 'Export signed with CAdES signature'); } // ========== Utility Methods ========== // ========== v2 Ledger (hashed, gapless, festschreibbar) ========== /** * Default account policy for the active chart, with the books' individual * accounts (`individualAccounts`) where they declare any: the drafts this * API validates and the recipes built on it see an individual account as * its parent. */ public getDefaultPolicy(): core.IAccountPolicy { this.ensureInitialized(); const policy = core.getDefaultPolicy(this.currentSKRType!); if (this.individualAccounts.length === 0) { return policy; } return { ...policy, individualAccounts: structuredClone(this.individualAccounts) }; } /** * Post a validated journal draft atomically (v2 path: exact cents, * gapless sequence, hash chain). Use the recipes in `core` to build drafts. */ public async postDraft( draft: core.IJournalDraft, options?: IPostDraftOptions, ): Promise { this.ensureInitialized(); return this.journalPoster.postDraft(draft, { policy: options?.policy ?? this.getDefaultPolicy(), ...options, }); } /** * Reverse a hashed entry via Storno — the original is never mutated. */ public async postStorno( entry: JournalEntry, options?: IPostDraftOptions & { date?: Date; description?: string }, ): Promise { this.ensureInitialized(); return this.journalPoster.postStorno(entry, { policy: options?.policy ?? this.getDefaultPolicy(), ...options, }); } /** * Festschreibung: finalize all posted v2 entries of a period and lock it * against further postings (GoBD). */ public async festschreibePeriod( period: string, lockedBy?: string, ): Promise<{ finalizedEntries: number }> { this.ensureInitialized(); return festschreibePeriod({ skrType: this.currentSKRType!, period, lockedBy, }); } public async getPeriodState(period: string): Promise { this.ensureInitialized(); return getPeriodState(this.currentSKRType!, period); } /** * Recompute the whole hash chain for a fiscal year and compare it against * the stored chain head — the audit-trail integrity check. */ public async verifyAuditChain(fiscalYear: number): Promise { this.ensureInitialized(); return verifyHashChain(this.currentSKRType!, fiscalYear); } /** * Exact trial balance in integer cents, aggregated from v2 entries. */ public async getTrialBalanceCents( options?: IBalanceQueryOptions, ): Promise { this.ensureInitialized(); return aggregateTrialBalance(this.currentSKRType!, options); } public async getAccountBalanceCents( accountNumber: string, options?: IBalanceQueryOptions, ): Promise { this.ensureInitialized(); return aggregateAccountBalance(accountNumber, this.currentSKRType!, options); } /** * DATEV Buchungsstapel (EXTF 700 / v13) over the v2 entries of a date * range. Returns the CSV string (persist as CP1252!) and filename. */ public async exportDatevBuchungsstapel(options: { dateFrom: Date; dateTo: Date; consultantNumber: number; clientNumber: number; fiscalYearStart: Date; label?: string; festschreibung?: boolean; createdAt?: Date; }): Promise<{ csv: string; filename: string; rowCount: number }> { this.ensureInitialized(); const cursor = await JournalEntry.getCursor( { skrType: this.currentSKRType!, schemaVersion: 2, status: { $in: ['posted', 'finalized'] }, date: { $gte: options.dateFrom, $lte: options.dateTo }, }, { sort: { sequenceNumber: 1 } }, ); const docs = await cursor.toArray(); const drafts: core.IJournalDraft[] = docs.map((doc) => ({ date: doc.date as Date, description: doc.description as string, reference: doc.reference as string, skrType: doc.skrType as TSKRType, currency: 'EUR', taxScenario: doc.taxScenario as core.TTaxScenario | undefined, lines: (doc.lines as core.IJournalLineDraft[]).map((line) => ({ accountNumber: line.accountNumber, counterAccount: line.counterAccount ?? '', side: (line.side ?? 'debit') as 'debit' | 'credit', amountCents: line.amountCents ?? 0, buKey: (line.buKey ?? '') as core.TBuKey, buchungstext: line.buchungstext ?? '', belegfeld1: line.belegfeld1, costCenter1: line.costCenter1, docLink: line.docLink, })), })); const rows = core.journalDraftsToDatevRows(drafts, { festschreibung: options.festschreibung, }); const result = core.writeExtfBuchungsstapel(rows, { createdAt: options.createdAt ?? new Date(), consultantNumber: options.consultantNumber, clientNumber: options.clientNumber, fiscalYearStart: options.fiscalYearStart, dateFrom: options.dateFrom, dateTo: options.dateTo, label: options.label ?? `Buchungsstapel ${options.dateFrom.toISOString().slice(0, 10)}`, festschreibung: options.festschreibung ?? false, }); return { ...result, rowCount: rows.length }; } /** * The migration steps applied to this database, oldest first, each with its * report (Verfahrensdokumentation artifact). `initialize()` runs pending * steps before anything else touches the ledger. */ public async getMigrationRecords(): Promise { this.ensureInitialized(); return listAppliedMigrations(); } // ========== OPOS (open items) ========== public async listOpenItems(options?: { kind?: import('./skr.opos.js').TOposKind; accountNumber?: string; asOf?: Date; includeSettled?: boolean; }): Promise { this.ensureInitialized(); const { listOpenItems } = await import('./skr.opos.js'); return listOpenItems(this.currentSKRType!, this.getDefaultPolicy(), options); } public async getOposAging( kind: import('./skr.opos.js').TOposKind, asOf: Date, bucketDays?: number[], ): Promise { this.ensureInitialized(); const { getAging } = await import('./skr.opos.js'); return getAging(this.currentSKRType!, this.getDefaultPolicy(), kind, asOf, bucketDays); } public async getControlTotals(asOf?: Date): Promise { this.ensureInitialized(); const { getControlTotals } = await import('./skr.opos.js'); return getControlTotals(this.currentSKRType!, this.getDefaultPolicy(), asOf); } // ========== UStVA extraction ========== /** * One period's movements + exact igE/§13b scenario bases, with the books' * individual accounts, shaped for @fin.cx/tax `computeUstva()`. Review * `warnings` before filing. */ public async getUstvaPeriodData( dateFrom: Date, dateTo: Date, ): Promise { this.ensureInitialized(); const { getUstvaPeriodData } = await import('./skr.ustva.js'); return getUstvaPeriodData(this.currentSKRType!, this.getDefaultPolicy(), { dateFrom, dateTo, }); } public async setDunning(params: { accountNumber: string; reference: string; dunningLevel?: number; dueDate?: string; }): Promise { this.ensureInitialized(); const { setOposMeta } = await import('./skr.opos.js'); return setOposMeta({ skrType: this.currentSKRType!, ...params }); } /** * Settle an open item with a bank payment (Skonto and small-difference * write-offs via the core recipe); ordinary v2 posting, fully audited. * * An item with a NEGATIVE openCents is a credit in the counterparty's * favour — what a customer credit note leaves behind on an invoice that was * already paid. It is settled by paying the money back, so the direction * flips (see planOpenItemSettlement); the refund repeats the item's * reference and therefore clears the same open item. */ public async settleOpenItem(params: { item: import('./skr.opos.js').IOpenItem; paidCents: number; date: Date; bankAccount?: string; /** the Skonto at one rate, or split over the rates of the invoice (see core.bookBankPayment) */ skonto?: core.TBankPaymentSkonto; diffToleranceCents?: number; description?: string; }): Promise { this.ensureInitialized(); const { planOpenItemSettlement } = await import('./skr.opos.js'); const plan = planOpenItemSettlement({ item: params.item, paidCents: params.paidCents, diffToleranceCents: params.diffToleranceCents, skonto: Boolean(params.skonto), }); const draft = core.bookBankPayment( { date: params.date, direction: plan.direction, bankAccount: params.bankAccount, counterpartyAccount: params.item.accountNumber, expectedCents: plan.expectedCents, paidCents: plan.paidCents, skonto: params.skonto, diffToleranceCents: params.diffToleranceCents, description: params.description ?? `${params.item.openCents < 0 ? 'Erstattung' : 'Ausgleich'} ${params.item.reference || params.item.accountNumber}`, reference: params.item.reference || undefined, }, this.getDefaultPolicy(), ); return this.journalPoster.postDraft(draft, { policy: this.getDefaultPolicy() }); } /** * Get current SKR type */ public getSKRType(): TSKRType | null { return this.currentSKRType; } /** * Get account class description */ public getAccountClassDescription(accountClass: number): string { this.ensureInitialized(); return this.chartOfAccounts.getAccountClassDescription(accountClass); } /** * Validate double-entry rules */ public validateDoubleEntry( debitAmount: number, creditAmount: number, ): boolean { if (!this.ledger) throw new Error('Ledger not initialized'); return this.ledger.validateDoubleEntry(debitAmount, creditAmount); } /** * Get unbalanced transactions (for audit) */ public async getUnbalancedTransactions(): Promise { this.ensureInitialized(); // v2 posting enforces exact balance atomically — imbalance is impossible; // chain integrity is checked via verifyAuditChain() return []; } /** * Close the API and database connection */ public async close(): Promise { await this.chartOfAccounts.close(); this.initialized = false; this.currentSKRType = null; this.individualAccounts = []; this.ledger = null; this.reports = null; this.logger.log('info', 'SKR API closed'); } // ========== Batch Operations ========== /** * Post multiple transactions */ public async postBatchTransactions( transactions: ITransactionData[], ): Promise { this.ensureInitialized(); const results: ITransactionView[] = []; const errors: Array<{ index: number; error: string }> = []; for (let i = 0; i < transactions.length; i++) { try { const transaction = await this.postTransaction(transactions[i]); results.push(transaction); } catch (error) { errors.push({ index: i, error: error instanceof Error ? error.message : String(error) }); } } if (errors.length > 0) { this.logger.log( 'warn', `Batch transaction posting completed with ${errors.length} errors`, ); throw new Error( `Batch posting failed for ${errors.length} transactions: ${JSON.stringify(errors)}`, ); } return results; } /** * Create multiple accounts */ public async createBatchAccounts( accounts: IAccountData[], ): Promise { this.ensureInitialized(); const results: Account[] = []; const errors: Array<{ index: number; error: string }> = []; for (let i = 0; i < accounts.length; i++) { try { const account = await this.createAccount(accounts[i]); results.push(account); } catch (error) { errors.push({ index: i, error: error instanceof Error ? error.message : String(error) }); } } if (errors.length > 0) { this.logger.log( 'warn', `Batch account creation completed with ${errors.length} errors`, ); throw new Error( `Batch creation failed for ${errors.length} accounts: ${JSON.stringify(errors)}`, ); } return results; } // ========== Pagination Support ========== /** * Get paginated accounts */ public async getAccountsPaginated( page: number = 1, pageSize: number = 50, filter?: IAccountFilter, ): Promise<{ data: Account[]; total: number; page: number; pageSize: number; totalPages: number; }> { this.ensureInitialized(); const allAccounts = await this.listAccounts(filter); const total = allAccounts.length; const totalPages = Math.ceil(total / pageSize); const start = (page - 1) * pageSize; const end = start + pageSize; const data = allAccounts.slice(start, end); return { data, total, page, pageSize, totalPages, }; } /** * Get paginated transactions */ public async getTransactionsPaginated( page: number = 1, pageSize: number = 50, filter?: ITransactionFilter, ): Promise<{ data: ITransactionView[]; total: number; page: number; pageSize: number; totalPages: number; }> { this.ensureInitialized(); const allTransactions = await this.listTransactions(filter); const total = allTransactions.length; const totalPages = Math.ceil(total / pageSize); const start = (page - 1) * pageSize; const end = start + pageSize; const data = allTransactions.slice(start, end); return { data, total, page, pageSize, totalPages, }; } // ========== Invoice Management ========== /** * Import an invoice from file or buffer * Parses, validates, and optionally books the invoice */ public async importInvoice( file: Buffer | string, direction: TInvoiceDirection, options?: IInvoiceImportOptions ): Promise { this.ensureInitialized(); if (!this.invoiceAdapter || !this.invoiceStorage || !this.invoiceBookingEngine) { throw new Error('Invoice components not initialized'); } this.logger.log('info', `Importing ${direction} invoice`); // Parse and validate invoice const invoice = await this.invoiceAdapter.parseInvoice(file, direction); // Store invoice await this.invoiceStorage.initialize(); const contentHash = await this.invoiceStorage.storeInvoice(invoice); invoice.contentHash = contentHash; // Auto-book if requested if (options?.autoBook) { const bookingResult = await this.bookInvoice( invoice, options.bookingRules, { autoBook: true, confidenceThreshold: options.confidenceThreshold || 80, skipValidation: options.validateOnly } ); if (bookingResult.success && bookingResult.bookingInfo) { invoice.bookingInfo = bookingResult.bookingInfo; invoice.status = 'posted'; // Update stored metadata with booking information await this.invoiceStorage.updateMetadata(invoice.contentHash, { journalEntryId: bookingResult.bookingInfo.journalEntryId, transactionIds: bookingResult.bookingInfo.transactionIds }); } } this.logger.log('info', `Invoice imported successfully: ${invoice.invoiceNumber}`); return invoice; } /** * Book an invoice to the ledger */ public async bookInvoice( invoice: IInvoice, bookingRules?: Partial, options?: IBookingOptions ): Promise { this.ensureInitialized(); if (!this.invoiceBookingEngine) { throw new Error('Invoice booking engine not initialized'); } this.logger.log('info', `Booking invoice ${invoice.invoiceNumber}`); const result = await this.invoiceBookingEngine.bookInvoice( invoice, bookingRules, options ); if (result.success) { this.logger.log('info', `Invoice booked successfully with confidence ${result.confidence}%`); // Update stored metadata if invoice has a content hash if (invoice.contentHash && result.bookingInfo && this.invoiceStorage) { await this.invoiceStorage.updateMetadata(invoice.contentHash, { journalEntryId: result.bookingInfo.journalEntryId, transactionIds: result.bookingInfo.transactionIds }); } } else { this.logger.log('error', `Invoice booking failed: ${result.errors?.join(', ')}`); } return result; } /** * Export an invoice in a different format */ public async exportInvoice( invoice: IInvoice, options: IInvoiceExportOptions ): Promise<{ xml: string; pdf?: Buffer }> { this.ensureInitialized(); if (!this.invoiceAdapter) { throw new Error('Invoice adapter not initialized'); } this.logger.log('info', `Exporting invoice ${invoice.invoiceNumber} to ${options.format}`); // Convert format if needed const xml = await this.invoiceAdapter.convertFormat(invoice, options.format); // Generate PDF if requested let pdf: Buffer | undefined; if (options.embedInPdf) { const result = await this.invoiceAdapter.generateInvoice(invoice, options.format); pdf = result.pdf; } return { xml, pdf }; } /** * Search invoices by filter */ public async searchInvoices(filter: IInvoiceFilter): Promise { this.ensureInitialized(); if (!this.invoiceStorage) { throw new Error('Invoice storage not initialized'); } await this.invoiceStorage.initialize(); const metadata = await this.invoiceStorage.searchInvoices(filter); const invoices: IInvoice[] = []; for (const meta of metadata) { const invoice = await this.invoiceStorage.retrieveInvoice(meta.contentHash); if (invoice) { invoices.push(invoice); } } return invoices; } /** * Get invoice by content hash */ public async getInvoice(contentHash: string): Promise { this.ensureInitialized(); if (!this.invoiceStorage) { throw new Error('Invoice storage not initialized'); } await this.invoiceStorage.initialize(); return await this.invoiceStorage.retrieveInvoice(contentHash); } /** * Get invoice storage statistics */ public async getInvoiceStatistics(): Promise { this.ensureInitialized(); if (!this.invoiceStorage) { throw new Error('Invoice storage not initialized'); } await this.invoiceStorage.initialize(); return await this.invoiceStorage.getStatistics(); } /** * Create EN16931 compliance report for invoices */ public async createInvoiceComplianceReport(): Promise { this.ensureInitialized(); if (!this.invoiceStorage) { throw new Error('Invoice storage not initialized'); } await this.invoiceStorage.initialize(); await this.invoiceStorage.createComplianceReport(); this.logger.log('info', 'Invoice compliance report created'); } /** * Generate an invoice from internal data */ public async generateInvoice( invoiceData: Partial, format: IInvoiceExportOptions['format'] ): Promise<{ xml: string; pdf?: Buffer }> { this.ensureInitialized(); if (!this.invoiceAdapter) { throw new Error('Invoice adapter not initialized'); } this.logger.log('info', `Generating invoice in ${format} format`); return await this.invoiceAdapter.generateInvoice(invoiceData, format); } }