/** * Pure journal validation. No chart lookups, no persistence — structural and * arithmetic invariants only. Account-existence checks belong to the * persistence layer, which owns the chart of accounts. */ import type { IJournalDraft, IJournalLineDraft, IValidationResult, TReverseChargeParagraph } from './core.types.js'; import { REVERSE_CHARGE_PARAGRAPHS } from './core.types.js'; import { isKnownBuKey, isReverseChargeBuKey } from './core.bukeys.js'; import { isSkrType } from './core.chart.js'; import type { IAccountPolicy } from './core.accountpolicy.js'; import { isAutomatikAccount } from './core.accountpolicy.js'; import { DATEV_MAX_BELEGFELD, datevBelegfeldOf, datevBelegInfoFault, isDatevBelegfeld } from './core.belegfeld.js'; import { entryRefusals, lineFieldOf } from './core.entryissues.js'; export { DATEV_MAX_BELEGFELD } from './core.belegfeld.js'; export const DATEV_MAX_BUCHUNGSTEXT = 60; /** What the writer does with a Belegfeld DATEV does not take: it maps it (`datevBelegfeldOf`) and keeps the text as a Beleginfo. */ const belegfeldMapped = (labelArg: string, fieldArg: string, valueArg: string): string => { const mapped = datevBelegfeldOf(valueArg); return `${labelArg}: ${fieldArg} "${valueArg}" is not 1 to ${DATEV_MAX_BELEGFELD} of the characters DATEV takes (A-Z, a-z, 0-9 and $ & % * + - /); the Buchungsstapel writes ${mapped === undefined ? 'none' : `"${mapped}"`}, the text as a Beleginfo`; }; /** * Validate (and normalize) a journal draft. * * Normalization: negative amounts are flipped to the opposite side so the * ledger only ever stores positive amounts with an explicit side. A draft * marked `generalumkehr` is not normalized: its lines keep their sides and * must state positive amounts, which the mark makes count negative; a * negative amount there is refused, since it would negate twice. * Balance check is EXACT — integer cents, no tolerance. * * Each error has its issue (`IEntryIssue`) in `issues`, in the same order: * the rule's code, the field and the line. */ export function validateJournalDraft( draft: IJournalDraft, policy?: IAccountPolicy, ): IValidationResult { const { errors, issues, refuse } = entryRefusals(); const warnings: string[] = []; if (draft.generalumkehr !== undefined && typeof draft.generalumkehr !== 'boolean') { refuse('generalumkehr_invalid', 'generalumkehr', 'generalumkehr must be true or false'); } const normalizedLines: IJournalLineDraft[] = draft.lines.map((line, index) => { if (draft.generalumkehr === true) { if (line.amountCents < 0) { refuse( 'amount_not_positive', lineFieldOf(index, 'amountCents'), `line ${index + 1} (${line.accountNumber || '?'}): a Generalumkehr line states its amount positive, the mark makes it count negative; got ${line.amountCents}`, index, ); } return { ...line }; } if (line.amountCents < 0) { return { ...line, amountCents: -line.amountCents, side: line.side === 'debit' ? 'credit' : 'debit', }; } return { ...line }; }); const normalized: IJournalDraft = { ...draft, lines: normalizedLines }; if (!(draft.date instanceof Date) || Number.isNaN(draft.date.getTime())) { refuse('date_invalid', 'date', 'Journal draft requires a valid date'); } if (!isSkrType(draft.skrType)) { refuse('chart_invalid', 'skrType', `the draft's chart of accounts must be SKR03 or SKR04, not ${String(draft.skrType)}`); } if (!draft.description) { warnings.push('Journal draft has no description'); } if (draft.currency !== 'EUR') { refuse('currency_not_eur', 'currency', `Core booking currency must be EUR, got '${draft.currency}'`); } if (normalizedLines.length < 2) { refuse('too_few_lines', 'lines', 'A journal entry requires at least two lines'); } let debitTotal = 0; let creditTotal = 0; normalizedLines.forEach((line, index) => { const label = `line ${index + 1} (${line.accountNumber || '?'})`; if (!Number.isSafeInteger(line.amountCents)) { refuse('amount_not_whole_cents', lineFieldOf(index, 'amountCents'), `${label}: amountCents must be a safe integer, got ${line.amountCents}`, index); return; } if (line.amountCents === 0) { refuse('amount_zero', lineFieldOf(index, 'amountCents'), `${label}: amount must not be zero`, index); return; } if (!line.accountNumber) { refuse('account_missing', lineFieldOf(index, 'accountNumber'), `${label}: accountNumber is required`, index); } if (!line.counterAccount) { refuse('counter_account_missing', lineFieldOf(index, 'counterAccount'), `${label}: counterAccount (Gegenkonto) is required`, index); } else if (line.counterAccount === line.accountNumber) { refuse('same_account', lineFieldOf(index, 'counterAccount'), `${label}: account and counterAccount must differ`, index); } if (!isKnownBuKey(line.buKey)) { refuse('bu_key_unknown', lineFieldOf(index, 'buKey'), `${label}: unknown BU key '${line.buKey}'`, index); } // the paragraph of § 13b a base falls under, read back as null where a store keeps none const paragraph: unknown = line.reverseChargeParagraph; if (paragraph !== undefined && paragraph !== null) { if (!REVERSE_CHARGE_PARAGRAPHS.includes(paragraph as TReverseChargeParagraph)) { refuse( 'reverse_charge_paragraph_invalid', lineFieldOf(index, 'reverseChargeParagraph'), `${label}: reverseChargeParagraph must be one of ${REVERSE_CHARGE_PARAGRAPHS.join(', ')}, not ${String(paragraph)}`, index, ); } else if (!isReverseChargeBuKey(line.buKey)) { refuse( 'reverse_charge_paragraph_without_key', lineFieldOf(index, 'reverseChargeParagraph'), `${label}: reverseChargeParagraph ${String(paragraph)} belongs to the base of a tax the recipient owes under § 13b UStG, a line with BU key 91 or 94, not '${line.buKey}'`, index, ); } } if (line.buchungstext && line.buchungstext.length > DATEV_MAX_BUCHUNGSTEXT) { warnings.push( `${label}: buchungstext exceeds ${DATEV_MAX_BUCHUNGSTEXT} chars and will be truncated in DATEV export`, ); } // a Belegfeld DATEV does not take is written mapped (`datevBelegfelderOf`), never cut: said, the draft stays as given for (const field of ['belegfeld1', 'belegfeld2'] as const) { const value = line[field]; if (value && !isDatevBelegfeld(value)) { warnings.push(belegfeldMapped(label, field, value)); } } if (line.belegInfo !== undefined) { const fault = datevBelegInfoFault(line.belegInfo); if (fault) { refuse('beleginfo_invalid', lineFieldOf(index, 'belegInfo'), `${label}: ${fault}`, index); } } if (policy) { if (isAutomatikAccount(policy, line.accountNumber) && line.buKey !== '' && line.buKey !== '40') { refuse('automatik_bu_key', lineFieldOf(index, 'buKey'), `${label}: Automatikkonto must not carry BU key '${line.buKey}' (only none or 40)`, index); } // a line carried from a closed year reaches DATEV plain, without key 40 (`consolidateJournalDraftForDatev`): on an // Automatikkonto the automatism would book a tax from it; one that stays put there carries no declaresAs if (line.declaresAs !== undefined && line.declaresAs !== null && isAutomatikAccount(policy, line.accountNumber)) { refuse( 'declares_as_automatik_account', lineFieldOf(index, 'declaresAs'), `${label}: a line that declares as another account (declaresAs ${String(line.declaresAs)}) must not sit on an Automatikkonto: DATEV gets it without a key, and the automatism would book a tax from it`, index, ); } if ( line.accountNumber === policy.debtorsControl || line.accountNumber === policy.creditorsControl ) { refuse('control_account', lineFieldOf(index, 'accountNumber'), `${label}: direct posting to control account ${line.accountNumber} — use a personal account`, index); } } if (line.side === 'debit') { debitTotal += line.amountCents; } else { creditTotal += line.amountCents; } }); // the reference is the Belegfeld 1 of every line that states none if (draft.reference && draft.lines.some((line) => !line.belegfeld1) && !isDatevBelegfeld(draft.reference)) { warnings.push(belegfeldMapped('the draft', 'reference', draft.reference)); } if (draft.belegInfo !== undefined) { const fault = datevBelegInfoFault(draft.belegInfo); if (fault) { refuse('beleginfo_invalid', 'belegInfo', `the draft: ${fault}`); } } if (errors.length === 0 && debitTotal !== creditTotal) { refuse('unbalanced', 'lines', `Entry is not balanced: debit ${debitTotal} cents !== credit ${creditTotal} cents`); } return { valid: errors.length === 0, errors, issues, warnings, normalized }; }