/** * Bridges between the legacy v1 shapes (float euros, numeric posting keys, * debit/credit account pairs) and the v2 ledger (cents, string BU keys, * per-line Gegenkonto): * * - input converters: ITransactionData / IJournalEntry -> core.IJournalDraft * - output projections: v2 JournalEntry (lines) -> transaction-shaped views * * The Transaction collection is FROZEN in v2 — these projections are what * keeps transaction-style reads working. */ import * as plugins from './plugins.js'; import * as core from './core/index.js'; import { JournalEntry } from './skr.classes.journalentry.js'; import type { IJournalEntry, IJournalEntryLine, ITransactionData, ITransactionView, IReportParams, TSKRType, } from './skr.types.js'; const { centsFromFloat } = plugins.calculation; /** v1 numeric posting keys that map 1:1 onto the v2 string BU keys */ const NUMERIC_KEY_MAP: Record = { 1: '1', 2: '2', 3: '3', 8: '8', 9: '9', 18: '18', 19: '19', 40: '40', 91: '91', 94: '94', }; export function mapNumericPostingKey(postingKey?: number): core.TBuKey { if (postingKey === undefined || postingKey === null) return ''; return NUMERIC_KEY_MAP[postingKey] ?? ''; } /** * v1 postTransaction input -> two-line v2 draft. The amount is NOT split into * net/VAT (v1 semantics: vatAmount was informational) so ledger figures stay * identical across the migration. */ export function transactionDataToDraft(data: ITransactionData): core.IJournalDraft { const amountCents = centsFromFloat(data.amount); const vatCents = data.vatAmount ? centsFromFloat(data.vatAmount) : 0; const lines: core.IJournalLineDraft[] = [ { accountNumber: data.debitAccount, counterAccount: data.creditAccount, side: 'debit', amountCents, buKey: '', buchungstext: data.description, belegfeld1: data.reference, costCenter1: data.costCenter, }, { accountNumber: data.creditAccount, counterAccount: data.debitAccount, side: 'credit', amountCents, buKey: '', buchungstext: data.description, belegfeld1: data.reference, costCenter1: data.costCenter, }, ]; lines[0].vatAmountCents = vatCents; return { date: data.date, description: data.description, reference: data.reference, skrType: data.skrType, currency: 'EUR', lines, }; } /** * v1 postJournalEntry input -> v2 draft. Gegenkonto derivation: when one side * of the entry has exactly one line, it is the counter account for every line * of the other side (the dominant v1 usage); otherwise the first line of the * opposite side is used (documented heuristic — v1 stored no Gegenkonto). */ export function journalInputToDraft(entry: IJournalEntry): core.IJournalDraft { const debitLines = entry.lines.filter((line) => (line.debit ?? 0) > 0); const creditLines = entry.lines.filter((line) => (line.credit ?? 0) > 0); const counterFor = (side: 'debit' | 'credit'): string => { const opposite = side === 'debit' ? creditLines : debitLines; return opposite[0]?.accountNumber ?? ''; }; const lines: core.IJournalLineDraft[] = entry.lines.map((line) => { const isDebit = (line.debit ?? 0) > 0; return { accountNumber: line.accountNumber, counterAccount: counterFor(isDebit ? 'debit' : 'credit'), side: isDebit ? 'debit' : 'credit', amountCents: centsFromFloat(isDebit ? line.debit! : line.credit!), buKey: mapNumericPostingKey(line.postingKey), buchungstext: line.description ?? entry.description, costCenter1: line.costCenter, }; }); return { date: entry.date, description: entry.description, reference: entry.reference, skrType: entry.skrType, currency: 'EUR', lines, }; } interface IEntryDocLike { id: string; journalNumber?: string; date: Date; description: string; reference?: string; skrType: TSKRType; status: string; period?: string; fiscalYear?: number; postedAt?: Date | null; reversalOf?: string; lines: IJournalEntryLine[]; } /** * Project a two-line v2 entry back into the classic transaction shape. * Returns null for entries with more than two lines (journal-only view). */ export function entryToTransactionView(entry: IEntryDocLike): ITransactionView | null { const debitLine = entry.lines.find((line) => line.side === 'debit'); const creditLine = entry.lines.find((line) => line.side === 'credit'); if (!debitLine || !creditLine || entry.lines.length !== 2) return null; return { id: entry.id, transactionNumber: entry.journalNumber ?? entry.id, date: entry.date, debitAccount: debitLine.accountNumber, creditAccount: creditLine.accountNumber, amount: (debitLine.amountCents ?? 0) / 100, vatAmount: (debitLine.vatAmountCents ?? 0) / 100, description: entry.description, reference: entry.reference ?? '', skrType: entry.skrType, status: entry.status, period: entry.period ?? '', fiscalYear: entry.fiscalYear ?? entry.date.getUTCFullYear(), costCenter: debitLine.costCenter1 ?? creditLine.costCenter1, reversalOf: entry.reversalOf, }; } function dayRange(params?: IReportParams): { from: Date | null; to: Date | null } { const from = params?.dateFrom ? new Date(params.dateFrom) : null; const to = params?.dateTo ? new Date(params.dateTo) : null; if (from) from.setHours(0, 0, 0, 0); if (to) to.setHours(23, 59, 59, 999); return { from, to }; } /** * Load v2 entries of a date range as core drafts (for DATEV export). */ export async function loadDraftsForExport( skrType: TSKRType, dateFrom: Date, dateTo: Date, ): Promise { const cursor = await JournalEntry.getCursor( { skrType, schemaVersion: 2, status: { $in: ['posted', 'finalized'] }, date: { $gte: dateFrom, $lte: dateTo }, }, { sort: { sequenceNumber: 1 } }, ); const entries = await cursor.toArray(); return entries.map((entry) => { return { date: entry.date, description: entry.description, reference: entry.reference, skrType: entry.skrType, currency: 'EUR' as const, lines: entry.lines.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 ?? entry.description, belegfeld1: line.belegfeld1, costCenter1: line.costCenter1, docLink: line.docLink, })), }; }); } /** * Per-account activity as transaction-shaped line views from v2 entries — * the data source for reports (trial balance, general ledger, cash flow). * Each view carries the line's own side and its Gegenkonto. */ export async function accountLineViews( accountNumber: string, skrType: TSKRType, params?: IReportParams, ): Promise { const { from, to } = dayRange(params); const filter: plugins.nosqldb.MongoFilter = { skrType, schemaVersion: 2, status: { $in: ['posted', 'finalized'] }, 'lines.accountNumber': accountNumber, }; if (from || to) { filter.date = { ...(from ? { $gte: from } : {}), ...(to ? { $lte: to } : {}) }; } const cursor = await JournalEntry.getCursor(filter, { sort: { date: 1, sequenceNumber: 1 } }); const entries = await cursor.toArray(); const views: ITransactionView[] = []; for (const entry of entries) { for (const line of entry.lines) { if (line.accountNumber !== accountNumber) continue; const isDebit = line.side === 'debit'; views.push({ id: entry.id, transactionNumber: entry.journalNumber ?? entry.id, date: entry.date, debitAccount: isDebit ? accountNumber : line.counterAccount ?? '', creditAccount: isDebit ? line.counterAccount ?? '' : accountNumber, amount: (line.amountCents ?? 0) / 100, vatAmount: (line.vatAmountCents ?? 0) / 100, description: line.buchungstext ?? entry.description, reference: entry.reference ?? '', skrType: entry.skrType, status: entry.status, period: entry.period ?? '', fiscalYear: entry.fiscalYear ?? entry.date.getUTCFullYear(), costCenter: line.costCenter1, reversalOf: entry.reversalOf, }); } } return views; }