import * as plugins from './plugins.js'; import { getDbSync } from './skr.database.js'; import { Account } from './skr.classes.account.js'; import { validatePostingKey, validatePostingKeyConsistency, getPostingKeyDescription, } from './skr.postingkeys.js'; import type { TSKRType, IJournalEntry, IJournalEntryLine, } from './skr.types.js'; import { ImmutableEntryError, RetiredLedgerWriteError } from './skr.errors.js'; export const JOURNAL_ENTRY_COLLECTION = 'JournalEntry'; /** * The partial unique index over the hash chain's sequence numbers. SmartData * models cannot declare a partial index, so the storage migration * (ts_migration/) owns it and the model tolerates it. */ export const JOURNAL_SEQUENCE_INDEX_NAME = 'skrType_1_fiscalYear_1_sequenceNumber_1'; /** * The partial unique index over `legacyTransactionId`: each legacy Transaction * is imported into the journal at most once. The ledger migration * (ts_migration/) owns it and the model tolerates it. */ export const JOURNAL_LEGACY_TRANSACTION_INDEX_NAME = 'legacyTransactionId_1'; @plugins.nosqldb.Collection(() => getDbSync(), { collectionName: JOURNAL_ENTRY_COLLECTION, toleratedIndexNames: [JOURNAL_SEQUENCE_INDEX_NAME, JOURNAL_LEGACY_TRANSACTION_INDEX_NAME], }) export class JournalEntry extends plugins.nosqldb.SmartDataDbDoc { @plugins.nosqldb.unI() public id!: string; @plugins.nosqldb.svDb() @plugins.nosqldb.index() public journalNumber!: string; @plugins.nosqldb.svDb() @plugins.nosqldb.index() public date!: Date; @plugins.nosqldb.svDb() public description!: string; @plugins.nosqldb.svDb() @plugins.nosqldb.index() public reference!: string; /** the element fields the balance aggregation groups and sums by */ @plugins.nosqldb.svDb({ atomicPaths: ['accountNumber', 'side', 'amountCents'] }) public lines!: IJournalEntryLine[]; @plugins.nosqldb.svDb() @plugins.nosqldb.index() public skrType!: TSKRType; @plugins.nosqldb.svDb() public totalDebits!: number; @plugins.nosqldb.svDb() public totalCredits!: number; @plugins.nosqldb.svDb() public isBalanced!: boolean; @plugins.nosqldb.svDb() @plugins.nosqldb.index() public status!: 'draft' | 'posted' | 'reversed' | 'finalized'; // --- schemaVersion 2: GoBD hash chain + Festschreibung ------------------ @plugins.nosqldb.svDb() public schemaVersion?: number; @plugins.nosqldb.svDb() @plugins.nosqldb.index() public sequenceNumber?: number; @plugins.nosqldb.svDb() public prevHash?: string; @plugins.nosqldb.svDb() public entryHash?: string; @plugins.nosqldb.svDb() public finalizedAt?: Date | null; @plugins.nosqldb.svDb() @plugins.nosqldb.index() public reversalOf?: string; @plugins.nosqldb.svDb() public taxScenario?: string; @plugins.nosqldb.svDb() public currency?: string; @plugins.nosqldb.svDb() public transactionIds!: string[]; @plugins.nosqldb.svDb() @plugins.nosqldb.index() public period!: string; @plugins.nosqldb.svDb() public fiscalYear!: number; @plugins.nosqldb.svDb() public createdAt!: Date; @plugins.nosqldb.svDb() public postedAt!: Date | null; @plugins.nosqldb.svDb() public createdBy!: string; constructor(data?: Partial) { super(); if (data) { this.id = plugins.smartunique.shortId(); this.journalNumber = this.generateJournalNumber(); this.date = data.date || new Date(); this.description = data.description || ''; this.reference = data.reference || ''; this.lines = data.lines || []; this.skrType = data.skrType || 'SKR03'; this.totalDebits = 0; this.totalCredits = 0; this.isBalanced = false; this.status = 'draft'; this.transactionIds = []; // Set period and fiscal year const entryDate = new Date(this.date); this.period = `${entryDate.getFullYear()}-${String(entryDate.getMonth() + 1).padStart(2, '0')}`; this.fiscalYear = entryDate.getFullYear(); this.createdAt = new Date(); this.postedAt = null; this.createdBy = 'system'; // Normalize any negative amounts to the correct side this.sanitizeLines(); // Calculate totals this.calculateTotals(); } } private generateJournalNumber(): string { const timestamp = Date.now(); const random = Math.floor(Math.random() * 1000); return `JE-${timestamp}-${random}`; } private sanitizeLines(): void { for (const line of this.lines) { // Check if both debit and credit are set (not allowed) if (line.debit !== undefined && line.debit !== 0 && line.credit !== undefined && line.credit !== 0) { throw new Error('A line cannot have both debit and credit amounts'); } // Handle negative debit - convert to positive credit if (line.debit !== undefined && line.debit < 0) { line.credit = Math.abs(line.debit); delete (line as any).debit; } // Handle negative credit - convert to positive debit if (line.credit !== undefined && line.credit < 0) { line.debit = Math.abs(line.credit); delete (line as any).credit; } // Check that at least one side has a positive value const hasDebit = line.debit !== undefined && line.debit > 0; const hasCredit = line.credit !== undefined && line.credit > 0; if (!hasDebit && !hasCredit) { throw new Error('Either debit or credit must be a positive number'); } } } private calculateTotals(): void { this.totalDebits = 0; this.totalCredits = 0; for (const line of this.lines) { if (line.debit) { this.totalDebits += line.debit; } if (line.credit) { this.totalCredits += line.credit; } } // Check if balanced (allowing for small rounding differences) const difference = Math.abs(this.totalDebits - this.totalCredits); this.isBalanced = difference < 0.01; } /** * Retired: persisted an unposted draft. Drafts live in memory * (`core.IJournalDraft`); only hashed postings are stored. */ public static async createJournalEntry( _data: IJournalEntry, ): Promise { throw new RetiredLedgerWriteError( 'JournalEntry.createJournalEntry()', 'the journal stores no unposted drafts', 'SkrApi.postJournalEntry(), Ledger.postJournalEntry() or JournalPoster.postDraft()', ); } public addLine(line: IJournalEntryLine): void { // Validate line if (!line.accountNumber) { throw new Error('Account number is required for journal entry line'); } if (!line.debit && !line.credit) { throw new Error('Either debit or credit amount is required'); } if (line.debit && line.credit) { throw new Error('A line cannot have both debit and credit amounts'); } if (line.debit && line.debit < 0) { throw new Error('Debit amount must be positive'); } if (line.credit && line.credit < 0) { throw new Error('Credit amount must be positive'); } this.lines.push(line); this.calculateTotals(); } public removeLine(index: number): void { if (index >= 0 && index < this.lines.length) { this.lines.splice(index, 1); this.calculateTotals(); } } public async validate(): Promise { // Check if entry is balanced if (!this.isBalanced) { throw new Error( `Journal entry is not balanced. Debits: ${this.totalDebits}, Credits: ${this.totalCredits}`, ); } // Check minimum lines if (this.lines.length < 2) { throw new Error('Journal entry must have at least 2 lines'); } // Validate all accounts exist, are active, and can be posted to const validationErrors: string[] = []; const validationWarnings: string[] = []; // Check if this journal entry has VAT lines (for smarter posting key validation) const hasVATLines = this.lines.some(line => line.accountNumber === '1571' || line.accountNumber === '1771' || line.accountNumber === '1576' ); for (const line of this.lines) { // Validate posting key is present (REQUIRED) if (!line.postingKey) { validationErrors.push( `Line for account ${line.accountNumber} is missing required posting key (Buchungsschlüssel). ` + `Posting keys are mandatory for DATEV compliance.` ); continue; // Skip further validation for this line } // Validate account is not an automatic account (Automatikkonto) try { await Account.validateAccountForPosting(line.accountNumber, this.skrType); } catch (error) { validationErrors.push(error instanceof Error ? error.message : String(error)); continue; // Skip further validation for this line } // Get account for posting key validation const account = await Account.getAccountByNumber( line.accountNumber, this.skrType, ); if (!account) { validationErrors.push( `Account ${line.accountNumber} not found for ${this.skrType}`, ); continue; } if (!account.isActive) { validationErrors.push(`Account ${line.accountNumber} is not active`); continue; } // Validate posting key for this line const amount = line.debit || line.credit || 0; // For journal entries with VAT lines, pass amount as vatAmount to satisfy validation const postingKeyValidation = validatePostingKey( line.postingKey, line.accountNumber, amount, hasVATLines ? amount : undefined // If entry has VAT lines, we consider the validation satisfied ); if (!postingKeyValidation.isValid) { validationErrors.push(...postingKeyValidation.errors); } if (postingKeyValidation.warnings.length > 0) { validationWarnings.push(...postingKeyValidation.warnings); } } // Validate posting key consistency across all lines (v1 numeric keys only; // schemaVersion-2 lines carry string buKeys validated by the core) const consistencyValidation = validatePostingKeyConsistency( this.lines.filter( (line): line is IJournalEntryLine & { postingKey: NonNullable } => line.postingKey !== undefined, ), ); if (!consistencyValidation.isValid) { validationErrors.push(...consistencyValidation.errors); } if (consistencyValidation.warnings.length > 0) { validationWarnings.push(...consistencyValidation.warnings); } // Log warnings but don't fail validation if (validationWarnings.length > 0) { console.warn('Journal entry validation warnings:'); validationWarnings.forEach(warning => console.warn(` - ${warning}`)); } // Throw if any errors if (validationErrors.length > 0) { throw new Error( 'Journal entry validation failed:\n' + validationErrors.map(e => ` - ${e}`).join('\n') ); } } /** * Retired: posted this instance in place and wrote a Transaction per * debit/credit pair. A posting is a new hashed entry with its own sequence * number, so an existing instance cannot become one. */ public async post(): Promise { throw new RetiredLedgerWriteError( 'JournalEntry.post()', 'a posting is a new hashed entry, not an existing instance posted in place', 'SkrApi.postJournalEntry(), Ledger.postJournalEntry() or JournalPoster.postDraft()', ); } /** * Retired: marked the original 'reversed'. A posted entry is immutable; * a Storno entry reverses it. */ public async reverse(): Promise { throw new RetiredLedgerWriteError( 'JournalEntry.reverse()', 'a posted entry is immutable (GoBD); a Storno entry reverses it', 'SkrApi.reverseJournalEntry(), Ledger.reverseJournalEntry() or JournalPoster.postStorno()', ); } public async beforeSave(): Promise { // GoBD immutability: once a hashed (schemaVersion 2) entry is persisted it // must never change — corrections happen via Storno entries only. // Festschreibung stamps bypass doc saves (raw updates outside the hash). if (this.creationStatus === 'db' && this.entryHash) { throw new ImmutableEntryError(this.id); } // Normalize any negative amounts to the correct side this.sanitizeLines(); // Recalculate totals before saving this.calculateTotals(); // Validate required fields if (!this.date) { throw new Error('Journal entry date is required'); } if (!this.description) { throw new Error('Journal entry description is required'); } if (this.lines.length === 0) { throw new Error('Journal entry must have at least one line'); } } public async delete( opts?: Parameters['delete']>[0], ): Promise { if (this.entryHash) { throw new ImmutableEntryError(this.id); } await super.delete(opts); } }