/** * Accounting period locks (Festschreibung). One document per * (skrType, period 'YYYY-MM') in the LedgerPeriod collection. * * festschreibePeriod() stamps all posted schemaVersion-2 entries of the * period as finalized with an atomic plural update — deliberately bypassing * the doc-level immutability guard (beforeSave), because the finalization * fields live OUTSIDE the entry hash. Detection of any other tampering is * verifyHashChain()'s job. */ import * as plugins from './plugins.js'; import { getDbSync, type TDbSession } from './skr.database.js'; import { JournalEntry } from './skr.classes.journalentry.js'; import { PeriodLockedError } from './skr.errors.js'; import { getSequenceState } from './skr.sequence.js'; import type { TSKRType } from './skr.types.js'; export const LEDGER_PERIOD_COLLECTION = 'LedgerPeriod'; export interface ILedgerPeriodState { skrType: TSKRType; period: string; // YYYY-MM status: 'open' | 'locked'; lockedAt?: Date; lockedBy?: string; chainCheckpoint?: { lastSequenceNumber: number; headHash: string } | null; } /** The lock state of one (skrType, period). */ @plugins.nosqldb.compoundIndex({ name: 'skrType_1_period_1', key: { skrType: 1, period: 1 }, options: { unique: true }, }) @plugins.nosqldb.Collection(() => getDbSync(), { collectionName: LEDGER_PERIOD_COLLECTION }) export class LedgerPeriod extends plugins.nosqldb.SmartDataDbDoc { @plugins.nosqldb.svDb() public skrType!: TSKRType; @plugins.nosqldb.svDb() public period!: string; @plugins.nosqldb.svDb() public status!: 'open' | 'locked'; @plugins.nosqldb.svDb() public lockedAt?: Date; @plugins.nosqldb.svDb() public lockedBy?: string; @plugins.nosqldb.svDb() public chainCheckpoint?: { lastSequenceNumber: number; headHash: string } | null; } export function periodOf(date: Date): string { return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}`; } export function fiscalYearOf(date: Date): number { return date.getUTCFullYear(); } /** * Throws PeriodLockedError when the period is festgeschrieben. Runs inside * the posting transaction so a concurrent lock aborts the posting. */ export async function assertPeriodOpen( skrType: TSKRType, period: string, session?: TDbSession, ): Promise { const doc = await LedgerPeriod.getInstance({ skrType, period }, { session }); if (doc && doc.status === 'locked') { throw new PeriodLockedError(skrType, period); } } export async function getPeriodState( skrType: TSKRType, period: string, ): Promise { const doc = await LedgerPeriod.getInstance({ skrType, period }); if (!doc) return null; return { skrType, period, status: doc.status, lockedAt: doc.lockedAt, lockedBy: doc.lockedBy, chainCheckpoint: doc.chainCheckpoint ?? null, }; } /** * Festschreibung: lock the period against new postings and stamp all posted * schemaVersion-2 entries as finalized. Idempotent — locking a locked period * throws so callers notice double runs. */ export async function festschreibePeriod(params: { skrType: TSKRType; period: string; lockedBy?: string; lockedAt?: Date; }): Promise<{ finalizedEntries: number; checkpoint: ILedgerPeriodState['chainCheckpoint'] }> { const session = getDbSync().createSession(); const lockedAt = params.lockedAt ?? new Date(); try { let finalizedEntries = 0; let checkpoint: ILedgerPeriodState['chainCheckpoint'] = null; await session.withTransaction(async (transaction) => { const existing = await LedgerPeriod.getInstance( { skrType: params.skrType, period: params.period }, { session: transaction }, ); if (existing && existing.status === 'locked') { throw new PeriodLockedError(params.skrType, params.period); } const stamp = await JournalEntry.atomicUpdateMany( { skrType: params.skrType, period: params.period, schemaVersion: 2, status: 'posted', }, { $set: { status: 'finalized', finalizedAt: lockedAt } }, { session: transaction }, ); finalizedEntries = stamp.modifiedCount; await LedgerPeriod.atomicUpdate( { skrType: params.skrType, period: params.period }, { $set: { status: 'locked', lockedAt, lockedBy: params.lockedBy ?? 'system', }, }, { upsert: true, session: transaction }, ); }); // checkpoint outside the txn: reads the settled chain head const fiscalYear = Number.parseInt(params.period.slice(0, 4), 10); const state = await getSequenceState(params.skrType, fiscalYear); if (state) { checkpoint = { lastSequenceNumber: state.value, headHash: state.headHash }; await LedgerPeriod.atomicUpdate( { skrType: params.skrType, period: params.period }, { $set: { chainCheckpoint: checkpoint } }, ); } return { finalizedEntries, checkpoint }; } finally { await session.close(); } }