/** * JournalPoster — the atomic v2 posting path. * * Flow per posting: pure pre-flight validation (stateless core) → one database * transaction containing period-lock re-check, gapless sequence allocation, * hash computation, entry save, and a compare-and-swap on the chain head. * The session's withTransaction() retries transient conflicts; an abort rolls * the sequence $inc back, so numbering stays gapless. * * JournalEntry (schemaVersion 2) is the single source of truth — no * Transaction-pair explosion. Balances are aggregations (skr.balances.ts). */ import * as core from './core/index.js'; import { getDbSync } from './skr.database.js'; import { JournalEntry } from './skr.classes.journalentry.js'; import { allocateSequence, advanceHead } from './skr.sequence.js'; import { assertPeriodOpen, fiscalYearOf, periodOf } from './skr.period.js'; import { PeriodLockedError, TransactionsUnsupportedError } from './skr.errors.js'; import type { IJournalEntryLine } from './skr.types.js'; export interface IPostDraftOptions { policy?: core.IAccountPolicy; postedAt?: Date; createdBy?: string; } /** * The exact structure whose canonical form is hashed into the chain. * Built identically by the poster (from the draft) and the verifier (from the * persisted document) — every optional is normalized so both sides match. */ export function buildHashPayload(entry: { sequenceNumber: number; skrType: string; fiscalYear: number; date: Date; postedAt: Date; description: string; reference?: string | null; taxScenario?: string | null; currency?: string | null; reversalOf?: string | null; lines: Array<{ accountNumber: string; counterAccount?: string | null; side?: string | null; amountCents?: number | null; buKey?: string | null; buchungstext?: string | null; belegfeld1?: string | null; costCenter1?: string | null; docLink?: string | null; vatAmountCents?: number | null; reverseChargeParagraph?: string | null; }>; }): Record { return { sequenceNumber: entry.sequenceNumber, skrType: entry.skrType, fiscalYear: entry.fiscalYear, date: entry.date, postedAt: entry.postedAt, description: entry.description ?? '', reference: entry.reference ?? '', taxScenario: entry.taxScenario ?? '', currency: entry.currency ?? 'EUR', reversalOf: entry.reversalOf ?? '', lines: entry.lines.map((line) => ({ accountNumber: line.accountNumber, counterAccount: line.counterAccount ?? '', side: line.side ?? '', amountCents: line.amountCents ?? 0, buKey: line.buKey ?? '', buchungstext: line.buchungstext ?? '', belegfeld1: line.belegfeld1 ?? '', costCenter1: line.costCenter1 ?? '', docLink: line.docLink ?? '', vatAmountCents: line.vatAmountCents ?? 0, // added after entries were posted without it: hashed only where present, so their hashes stay ...(line.reverseChargeParagraph !== undefined && line.reverseChargeParagraph !== null ? { reverseChargeParagraph: line.reverseChargeParagraph } : {}), })), }; } export class JournalPoster { /** * Probe transaction support with a no-op transaction. Fails hard — * filing-grade posting has no non-transactional fallback. */ public async assertTransactionSupport(): Promise { const session = getDbSync().createSession(); try { await session.withTransaction(async (transaction) => { await JournalEntry.getInstance({ id: 'txn-probe' }, { session: transaction }); }); } catch (error) { const message = error instanceof Error ? error.message : String(error); throw new TransactionsUnsupportedError(message); } finally { await session.close(); } } /** * Validate and atomically post a journal draft. Returns the persisted, * hashed, immutable JournalEntry. */ public async postDraft( draft: core.IJournalDraft, options?: IPostDraftOptions, ): Promise { const validation = core.validateJournalDraft(draft, options?.policy); if (!validation.valid) { throw new Error(`Journal draft invalid: ${validation.errors.join('; ')}`); } if (draft.generalumkehr === true) { // the persisted JournalEntry has no Generalumkehr mark: stored without it, the lines would book again instead of reversing throw new Error('The database ledger does not record a Generalumkehr; reverse a posted entry with postStorno'); } const normalized = validation.normalized; const period = periodOf(normalized.date); const fiscalYear = fiscalYearOf(normalized.date); const postedAt = options?.postedAt ?? new Date(); const session = getDbSync().createSession(); try { let posted: JournalEntry | null = null; await session.withTransaction(async (transaction) => { await assertPeriodOpen(normalized.skrType, period, transaction); const { sequenceNumber, prevHash } = await allocateSequence( normalized.skrType, fiscalYear, transaction, ); const lines: IJournalEntryLine[] = normalized.lines.map((line) => ({ accountNumber: line.accountNumber, // legacy float mirrors keep v1 reports readable during migration debit: line.side === 'debit' ? line.amountCents / 100 : 0, credit: line.side === 'credit' ? line.amountCents / 100 : 0, description: line.buchungstext, side: line.side, amountCents: line.amountCents, counterAccount: line.counterAccount, buKey: line.buKey, buchungstext: line.buchungstext, belegfeld1: line.belegfeld1, costCenter1: line.costCenter1, docLink: line.docLink, vatAmountCents: line.vatAmountCents, ...(line.reverseChargeParagraph !== undefined ? { reverseChargeParagraph: line.reverseChargeParagraph } : {}), })); const entry = new JournalEntry({ date: normalized.date, description: normalized.description, reference: normalized.reference, skrType: normalized.skrType, lines, }); entry.schemaVersion = 2; entry.sequenceNumber = sequenceNumber; entry.prevHash = prevHash; entry.taxScenario = normalized.taxScenario; entry.currency = normalized.currency; entry.reversalOf = normalized.reversalOf; entry.status = 'posted'; entry.postedAt = postedAt; entry.finalizedAt = null; entry.createdBy = options?.createdBy ?? 'system'; // period/fiscalYear are UTC-derived here; the constructor derives them // from local time, so overwrite for determinism entry.period = period; entry.fiscalYear = fiscalYear; entry.entryHash = core.entryHash( prevHash, buildHashPayload({ sequenceNumber, skrType: normalized.skrType, fiscalYear, date: normalized.date, postedAt, description: normalized.description, reference: normalized.reference, taxScenario: normalized.taxScenario, currency: normalized.currency, reversalOf: normalized.reversalOf, lines, }), ); await entry.save({ session: transaction }); await advanceHead( normalized.skrType, fiscalYear, prevHash, entry.entryHash, transaction, ); posted = entry; }); if (!posted) { throw new Error('Posting transaction did not complete'); } return posted; } catch (error) { if (error instanceof PeriodLockedError) throw error; throw error; } finally { await session.close(); } } /** * Storno: post a reversal entry for a hashed entry WITHOUT mutating the * original (GoBD). The reversal references the original via belegfeld1 and * reference; reversal state is derived by querying, never stored on the * original. */ public async postStorno( original: JournalEntry, options?: IPostDraftOptions & { date?: Date; description?: string }, ): Promise { if (original.schemaVersion !== 2 || !original.entryHash) { throw new Error('postStorno only reverses schemaVersion-2 (hashed) entries'); } const draft: core.IJournalDraft = { date: options?.date ?? new Date(), description: options?.description ?? `Storno ${original.journalNumber}: ${original.description}`, reference: `STORNO-${original.journalNumber}`, skrType: original.skrType, reversalOf: original.id, currency: (original.currency as 'EUR') ?? 'EUR', taxScenario: original.taxScenario as core.TTaxScenario | undefined, lines: original.lines.map((line) => ({ accountNumber: line.accountNumber, counterAccount: line.counterAccount ?? '', side: line.side === 'debit' ? 'credit' : 'debit', amountCents: line.amountCents ?? 0, buKey: (line.buKey ?? '') as core.TBuKey, // the Storno takes the base out of the field of the UStVA it stood in ...(line.reverseChargeParagraph !== undefined && line.reverseChargeParagraph !== null ? { reverseChargeParagraph: line.reverseChargeParagraph } : {}), buchungstext: `Storno: ${line.buchungstext ?? ''}`, belegfeld1: original.journalNumber, })), }; return this.postDraft(draft, options); } }