/** * The posted entry of a main book (Hauptbuch) and its hash chain: what an * entry records, its validation, its hash chained to the entry before it, * the next number of a ledger, and the check of a whole chain. Pure: the * caller stores the entries; nothing here reads a clock or a database. * * What an entry records follows GoBD Rz. 94 (BMF-Schreiben of 28.11.2019): * a unique Beleg number, the amount, currency and exchange rate of a foreign * amount, the explanation, Belegdatum, Buchungsdatum, Erfassungsdatum, the * authorisation, Buchungsperiode/Voranmeldungszeitraum, VAT rate, tax key, * VAT amount and account, account and counter account, debit and credit. * The entries of a ledger (one per organization and fiscal year) are * numbered 1, 2, 3 … without gaps. The hash of each entry covers its * predecessor's hash, so an entry changed, removed or put in between after * it was recorded is found (§ 146 Abs. 4 AO, § 239 Abs. 3 HGB; GoBD Rz. 58, * 107-108). */ import * as plugins from './core.plugins.js'; import type { IEntryIssue, IInputTaxUse, IJournalLineDraft, TInputTaxUseKind, TSKRType } from './core.types.js'; import { INPUT_TAX_USE_KINDS } from './core.types.js'; import { isAutomatikAccount, type IAccountPolicy } from './core.accountpolicy.js'; import { accountRateMismatchOf, STATED_VAT_TOLERANCE_CENTS, vatRateOfAccount } from './core.accountrate.js'; import { canonicalize } from './core.hash.js'; import { DATEV_MAX_BELEGFELD, DATEV_MAX_BUCHUNGSTEXT, validateJournalDraft } from './core.validate.js'; import { isDatevBelegfeld } from './core.belegfeld.js'; import { entryRefusals, lineFieldOf } from './core.entryissues.js'; /** * Where an exchange rate comes from: the BMF's monthly average for VAT * (§ 16 Abs. 6 Satz 1 UStG), the ECB reference rate of the day, what the bank * converted, or a rate a person stated with its Beleg. */ export type TExchangeRateSource = 'bmf_monthly' | 'ecb_daily' | 'bank' | 'stated'; /** A foreign amount behind an entry in euro (GoBD Rz. 77, 94). */ export interface IPostedEntryForeignAmount { /** ISO 4217, not EUR */ currency: string; amountCents: number; /** units of `currency` for one euro, the decimal with a point as published */ rate: string; rateDate: string; rateSource: TExchangeRateSource; } /** The record of the ledger's owner an entry was built from, and its revision. */ export interface IPostedEntrySource { /** opaque to the core */ kind: string; id: string; revision: number; } /** * What caused an entry to be posted, for example the statement that made a * repost (Storno and Neubuchung) necessary, and when it was recorded. Opaque * to the core, as `IPostedEntrySource` is. */ export interface IPostedEntryCause { kind: string; id: string; /** epoch milliseconds */ recordedAt: number; } /** One posted entry as the hash chain covers it. */ export interface IPostedEntryPayload { /** the version of the stored shape, the owner's */ schemaVersion: number; /** the chain the entry belongs to: one per organization and fiscal year */ ledgerId: string; /** 1, 2, 3 … per ledger, without gaps */ seq: number; /** the number people read, opaque to the core */ entryNumber: string; /** Belegdatum, `YYYY-MM-DD` */ documentDate: string; /** Buchungsdatum, `YYYY-MM-DD`: places the entry in its period and its fiscal year */ postingDate: string; /** Erfassungsdatum: when it was recorded, epoch milliseconds */ recordedAt: number; /** Buchungsperiode, `YYYY-MM`: the month of `postingDate` */ period: string; /** Voranmeldungszeitraum, `YYYY-MM` */ vatPeriod?: string; /** Leistungsdatum (`on`) or Leistungszeitraum (`from` and `to`) */ performance?: { on?: string; from?: string; to?: string }; source: IPostedEntrySource; /** unique per ledger owner: a source's revision is posted once, and its reversal once */ sourceKey: string; /** the canonical hash of the source's content the entry was built from */ sourceDigest: string; /** the Belege (GoBD Rz. 64, 71) */ documentIds: string[]; /** * The bank movements that are the entry's Beleg themselves: the electronic * account statement data, kept unchanged, of a movement nothing else * explains (GoBD Rz. 76-78), opaque ids of the owner's store. Covered by the * hash where given; an entry without it hashes as one made before it existed. */ movementIds?: string[]; description: string; party?: { name: string; contactId?: string; vatId?: string; taxNumber?: string }; /** as posted: positive amounts; the entry's `generalumkehr` makes each count negative on its side */ lines: IJournalLineDraft[]; currency: 'EUR'; foreign?: IPostedEntryForeignAmount; /** a general reversal; absent (or false) when it is none */ generalumkehr?: boolean; /** the entry this one reverses */ reversalOf?: string; /** the Autorisierung of Rz. 94: a person, a part of the application, a job */ recordedBy: { userId?: string; system?: string; jobId?: string }; /** the person who confirmed the source before it was posted */ confirmedBy?: { userId: string; at: number }; chart: TSKRType; accountLength: number; /** the version of the rules that built the entry from its source (GoBD Rz. 80) */ rulesVersion: string; /** * What the entry's supply is used for, as far as its input tax is concerned * (`IInputTaxUse`, § 15 Abs. 2 and 4 UStG), as a person stated it: one per * entry, as a Beleg has one. A statement, never a computation: the amounts * are the lines'. Covered by the hash where given; an entry without it * hashes as one made before it existed. Refused: a kind that is none of * `TInputTaxUseKind`, a key beside another kind than `mixed` or one that is * no decimal above 0 and below 100 with up to two places * (`input_tax_use_invalid`), `mixed` without its key * (`input_tax_use_key_missing`), and, with a policy, `exempt` on an entry * whose lines on any of the policy's input-tax accounts (`vat.inputStandard`, * `…Reduced`, `intraEuAcqInput`, `reverseChargeInput`) do not net to zero, * each account apart (`input_tax_use_exempt_deducts`), a line counting as * the account it declares as (`IJournalLineDraft.declaresAs`): a § 13b or * intra-Community pair whose deduction a correction takes back in full * passes, as does its reversal. */ inputTaxUse?: IInputTaxUse; /** * What caused this entry to be posted, for example the statement that made * a repost necessary; absent on entries posted for their own source. * Covered by the hash where given; an entry without it hashes as one made * before it existed. Refused (`cause_invalid`): no object, a `kind` or `id` * that is no non-empty text, a `recordedAt` that is no whole number of * epoch milliseconds from 0, and any other key. */ cause?: IPostedEntryCause; /** * The history this entry was decided on, read through these times (epoch * milliseconds) per named store. The consuming app's provenance: the core * keeps it and hashes it and gives it no meaning. Covered by the hash where * given; an entry without it hashes as one made before it existed. Refused * (`read_through_invalid`): no plain object, an empty one (it would hash * otherwise than an absent one), a key that is no letter followed by letters * and digits (keys become document field names: no `.` or `$`), and a time * that is no whole number of epoch milliseconds from 0. */ readThrough?: Record; } /** A posted entry with its place in the chain. */ export interface IPostedEntry extends IPostedEntryPayload { prevHash: string; entryHash: string; } /** The last entry of a ledger, which the next one follows. */ export interface ILedgerChainHead { seq: number; entryHash: string; /** when given, it must be the ledger of the next entry */ ledgerId?: string; } export interface IPostedEntryValidationOptions { /** the Automatikkonto and control-account rules of `validateJournalDraft`, and the VAT of each Automatikkonto line (`validatePostedEntry`) */ policy?: IAccountPolicy; /** the fiscal year the ledger is for: the posting date must lie in it */ fiscalYear?: { start: string; end: string }; } export type TLedgerChainBreakReason = /** a seq that is not the previous one plus 1, or a first seq that is not 1 */ | 'gap' /** a seq given twice in a row */ | 'duplicate' /** an entry of another ledger */ | 'ledger' /** a prevHash that is not the previous entry's hash (the genesis for the first) */ | 'prev_hash' /** a hash that no longer matches what the entry records */ | 'entry_hash'; export interface ILedgerChainBreak { /** the position in the list handed in */ index: number; seq: number; reason: TLedgerChainBreakReason; } const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/u; const ISO_MONTH = /^\d{4}-(0[1-9]|1[0-2])$/u; const DECIMAL = /^\d+(\.\d+)?$/u; const HASH = /^[0-9a-f]{64}$/u; const RATE_SOURCES: readonly TExchangeRateSource[] = ['bmf_monthly', 'ecb_daily', 'bank', 'stated']; const isDay = (valueArg: unknown): valueArg is string => { if (typeof valueArg !== 'string' || !ISO_DAY.test(valueArg)) return false; const time = Date.parse(`${valueArg}T00:00:00.000Z`); return !Number.isNaN(time) && new Date(time).toISOString().slice(0, 10) === valueArg; }; const isText = (valueArg: unknown): valueArg is string => typeof valueArg === 'string' && valueArg.length > 0; /** A value that is there: neither undefined nor null (a store may read an absent field back as null). */ const present = (valueArg: T | null | undefined): valueArg is T => valueArg !== undefined && valueArg !== null; /** Only the fields that are there, in a fresh object. */ const pick = (sourceArg: object, keysArg: readonly string[]): Record => { const result: Record = {}; const source = sourceArg as Record; for (const key of keysArg) { if (present(source[key])) result[key] = source[key]; } return result; }; const LINE_KEYS = [ 'accountNumber', 'counterAccount', 'side', 'amountCents', 'buKey', 'buchungstext', 'belegfeld1', 'belegfeld2', 'costCenter1', 'costCenter2', 'docLink', 'vatAmountCents', 'vatRatePercent', 'vatAccount', 'reverseChargeParagraph', 'declaresAs', ] as const; const CAUSE_KEYS = ['kind', 'id', 'recordedAt'] as const; /** * What the hash of a posted entry covers: exactly the fields of * `IPostedEntryPayload`, an absent field and one read back as `null` alike, * `generalumkehr: false` as absent. Fields beyond them (a store's own id, an * organization id, the two hashes) are left out, so a stored entry can be * handed in as it is. */ export function postedEntryPayloadOf(entry: IPostedEntryPayload): IPostedEntryPayload { const payload: Record = { ...pick(entry, [ 'schemaVersion', 'ledgerId', 'seq', 'entryNumber', 'documentDate', 'postingDate', 'recordedAt', 'period', 'vatPeriod', 'sourceKey', 'sourceDigest', 'documentIds', 'description', 'currency', 'reversalOf', 'chart', 'accountLength', 'rulesVersion', ]), lines: (entry.lines ?? []).map((lineArg) => pick(lineArg, LINE_KEYS)), recordedBy: pick(entry.recordedBy ?? {}, ['userId', 'system', 'jobId']), }; if (present(entry.source)) payload.source = pick(entry.source, ['kind', 'id', 'revision']); if (present(entry.movementIds)) payload.movementIds = entry.movementIds; if (present(entry.performance)) payload.performance = pick(entry.performance, ['on', 'from', 'to']); if (present(entry.party)) payload.party = pick(entry.party, ['name', 'contactId', 'vatId', 'taxNumber']); if (present(entry.foreign)) payload.foreign = pick(entry.foreign, ['currency', 'amountCents', 'rate', 'rateDate', 'rateSource']); if (present(entry.confirmedBy)) payload.confirmedBy = pick(entry.confirmedBy, ['userId', 'at']); if (entry.generalumkehr === true) payload.generalumkehr = true; if (present(entry.inputTaxUse)) payload.inputTaxUse = pick(entry.inputTaxUse, ['kind', 'deductiblePercent']); if (present(entry.cause)) payload.cause = pick(entry.cause, CAUSE_KEYS); if (present(entry.readThrough)) payload.readThrough = { ...entry.readThrough }; return payload as unknown as IPostedEntryPayload; } /** * The hash of a posted entry: `entryHash(prevHash, payload)` — SHA-256 over * the predecessor's hash and the canonical form (`canonicalize`: keys sorted, * arrays in order, integers only) of `postedEntryPayloadOf(entry)`. */ export function postedEntryHash(prevHash: string, entry: IPostedEntryPayload): string { return plugins.sha256FromStringSync(`${prevHash}\n${canonicalize(postedEntryPayloadOf(entry))}`); } /** The hash the first entry of a ledger chains to: SHA-256 of `GENESIS:LEDGER:`. */ export function ledgerGenesisHash(ledgerId: string): string { if (!isText(ledgerId)) throw new Error('ledgerId must be a non-empty text'); return plugins.sha256FromStringSync(`GENESIS:LEDGER:${ledgerId}`); } /** * The number and predecessor hash of a ledger's next entry: 1 and the genesis * after no entry, else one more than the last entry's number and its hash. * Refuses a head that is no entry, and one of another ledger. */ export function planNextEntry(head: ILedgerChainHead | null, ledgerId: string): { seq: number; prevHash: string } { const genesis = ledgerGenesisHash(ledgerId); if (head === null) return { seq: 1, prevHash: genesis }; if (!Number.isSafeInteger(head.seq) || head.seq < 1) { throw new Error(`the last entry's seq must be a whole number from 1, not ${String(head.seq)}`); } if (typeof head.entryHash !== 'string' || !HASH.test(head.entryHash)) { throw new Error('the last entry has no entryHash'); } if (head.ledgerId !== undefined && head.ledgerId !== ledgerId) { throw new Error(`the last entry belongs to the ledger ${head.ledgerId}, not ${ledgerId}`); } return { seq: head.seq + 1, prevHash: head.entryHash }; } /** * Validate a posted entry. Unlike `validateJournalDraft` it normalises * nothing, and what is a warning for a draft is an error here, because a * posted entry can never be put right afterwards. It refuses: fewer than two * lines; an amount that is not a positive whole number of cents; debits and * credits that differ; an account equal to its counter account, or either * missing; an unknown BU key; a Buchungstext over 60 characters; a Belegfeld * that is empty, over 36 characters or with characters DATEV does not take; a currency other * than EUR; dates that are no days; a period that is not the posting date's * month; a posting date outside the fiscal year when one is given; a foreign * amount in EUR, not in whole cents, or with a rate that is no positive * decimal; a missing ledger, number, source, digest or authorisation; and with * a policy the Automatikkonto and control-account rules, and a line on an * Automatikkonto whose German VAT does not fit the tax the chart ties the * account to (`automatikRateIssuesOf`); a `reverseChargeParagraph` beside a * BU key that is none of § 13b; a `declaresAs` that is no non-empty text; * and a use statement (`inputTaxUse`) of another shape, or, with a policy, an * `exempt` one whose input-tax accounts * do not each net to zero; a `cause` of another shape; and a `readThrough` * that is no non-empty plain object of named epoch milliseconds. Each error has its issue * (`IEntryIssue`) in `issues`, in the same order: the rule's code, the field * and the line. */ export function validatePostedEntry( payload: IPostedEntryPayload, options?: IPostedEntryValidationOptions, ): { valid: boolean; errors: string[]; issues: IEntryIssue[] } { const { errors, issues, refuse, adopt } = entryRefusals(); if (!Number.isSafeInteger(payload.schemaVersion)) refuse('schema_version_invalid', 'schemaVersion', 'schemaVersion must be a whole number'); if (!isText(payload.ledgerId)) refuse('ledger_id_missing', 'ledgerId', 'ledgerId must be a non-empty text'); if (!Number.isSafeInteger(payload.seq) || payload.seq < 1) refuse('seq_invalid', 'seq', `seq must be a whole number from 1, not ${String(payload.seq)}`); if (!isText(payload.entryNumber)) refuse('entry_number_missing', 'entryNumber', 'entryNumber must be a non-empty text'); const fiscalYear = options?.fiscalYear; if (fiscalYear !== undefined && (!isDay(fiscalYear.start) || !isDay(fiscalYear.end) || fiscalYear.end < fiscalYear.start)) { refuse('fiscal_year_invalid', 'fiscalYear', `the fiscal year ${String(fiscalYear.start)} to ${String(fiscalYear.end)} is not a span of days`); } if (!isDay(payload.documentDate)) refuse('document_date_invalid', 'documentDate', `documentDate must be a day as YYYY-MM-DD, not "${String(payload.documentDate)}"`); if (!isDay(payload.postingDate)) { refuse('posting_date_invalid', 'postingDate', `postingDate must be a day as YYYY-MM-DD, not "${String(payload.postingDate)}"`); } else { if (fiscalYear !== undefined && isDay(fiscalYear.start) && isDay(fiscalYear.end) && (payload.postingDate < fiscalYear.start || payload.postingDate > fiscalYear.end)) { refuse('posting_date_outside_fiscal_year', 'postingDate', `postingDate ${payload.postingDate} is not in the fiscal year ${fiscalYear.start} to ${fiscalYear.end}`); } if (payload.period !== payload.postingDate.slice(0, 7)) { refuse('period_not_posting_month', 'period', `period must be the month of the postingDate (${payload.postingDate.slice(0, 7)}), not "${String(payload.period)}"`); } } if (typeof payload.period !== 'string' || !ISO_MONTH.test(payload.period)) refuse('period_invalid', 'period', `period must be a month as YYYY-MM, not "${String(payload.period)}"`); if (present(payload.vatPeriod) && (typeof payload.vatPeriod !== 'string' || !ISO_MONTH.test(payload.vatPeriod))) { refuse('vat_period_invalid', 'vatPeriod', `vatPeriod must be a month as YYYY-MM, not "${String(payload.vatPeriod)}"`); } if (present(payload.performance)) { const { on, from, to } = payload.performance; const single = present(on) && !present(from) && !present(to) && isDay(on); const span = !present(on) && isDay(from) && isDay(to) && from <= to; if (!single && !span) refuse('performance_invalid', 'performance', 'performance is a day (`on`) or a span of days (`from` and `to`)'); } if (!Number.isSafeInteger(payload.recordedAt) || payload.recordedAt < 0) refuse('recorded_at_invalid', 'recordedAt', `recordedAt must be epoch milliseconds, not ${String(payload.recordedAt)}`); const source = payload.source; if (!present(source) || !isText(source.kind) || !isText(source.id) || !Number.isSafeInteger(source.revision) || source.revision < 1) { refuse('source_invalid', 'source', 'source needs a kind, an id and a revision from 1'); } if (!isText(payload.sourceKey)) refuse('source_key_missing', 'sourceKey', 'sourceKey must be a non-empty text'); if (!isText(payload.sourceDigest)) refuse('source_digest_missing', 'sourceDigest', 'sourceDigest must be a non-empty text'); if (!Array.isArray(payload.documentIds) || !payload.documentIds.every(isText)) refuse('document_ids_invalid', 'documentIds', 'documentIds must be a list of non-empty texts'); if (present(payload.movementIds) && (!Array.isArray(payload.movementIds) || !payload.movementIds.every(isText))) { refuse('movement_ids_invalid', 'movementIds', 'movementIds must be a list of non-empty texts'); } if (typeof payload.description !== 'string') refuse('description_invalid', 'description', 'description must be a text'); if (present(payload.party) && !isText(payload.party.name)) refuse('party_name_missing', 'party.name', 'party needs a name'); if (payload.currency !== 'EUR') refuse('currency_not_eur', 'currency', `the books are in EUR, not ${String(payload.currency)}; a foreign amount goes into foreign`); if (present(payload.foreign)) { const foreign = payload.foreign; if (typeof foreign.currency !== 'string' || !/^[A-Z]{3}$/u.test(foreign.currency) || foreign.currency === 'EUR') { refuse('foreign_currency_invalid', 'foreign.currency', `the foreign currency must be an ISO 4217 code other than EUR, not "${String(foreign.currency)}"`); } if (!Number.isSafeInteger(foreign.amountCents)) refuse('foreign_amount_invalid', 'foreign.amountCents', 'the foreign amount must be whole cents'); if (typeof foreign.rate !== 'string' || !DECIMAL.test(foreign.rate) || Number(foreign.rate) === 0) { refuse('foreign_rate_invalid', 'foreign.rate', `the foreign rate must be a positive decimal with a point, not "${String(foreign.rate)}"`); } if (!isDay(foreign.rateDate)) refuse('foreign_rate_date_invalid', 'foreign.rateDate', 'the foreign rateDate must be a day as YYYY-MM-DD'); if (!RATE_SOURCES.includes(foreign.rateSource)) refuse('foreign_rate_source_invalid', 'foreign.rateSource', `the foreign rateSource must be one of ${RATE_SOURCES.join(', ')}`); } if (present(payload.generalumkehr) && typeof payload.generalumkehr !== 'boolean') refuse('generalumkehr_invalid', 'generalumkehr', 'generalumkehr must be true or false'); if (present(payload.reversalOf) && !isText(payload.reversalOf)) refuse('reversal_of_invalid', 'reversalOf', 'reversalOf must be a non-empty text'); const recordedBy = payload.recordedBy ?? {}; if (![recordedBy.userId, recordedBy.system, recordedBy.jobId].some(isText)) { refuse('recorded_by_missing', 'recordedBy', 'recordedBy must name a person, a part of the application or a job'); } if (present(payload.confirmedBy) && (!isText(payload.confirmedBy.userId) || !Number.isSafeInteger(payload.confirmedBy.at))) { refuse('confirmed_by_invalid', 'confirmedBy', 'confirmedBy needs a userId and the time as epoch milliseconds'); } if (payload.chart !== 'SKR03' && payload.chart !== 'SKR04') refuse('chart_invalid', 'chart', `chart must be SKR03 or SKR04, not ${String(payload.chart)}`); if (!Number.isSafeInteger(payload.accountLength) || payload.accountLength < 1) refuse('account_length_invalid', 'accountLength', 'accountLength must be a whole number from 1'); if (!isText(payload.rulesVersion)) refuse('rules_version_missing', 'rulesVersion', 'rulesVersion must be a non-empty text'); const lines = Array.isArray(payload.lines) ? payload.lines : []; if (lines.length < 2) refuse('too_few_lines', 'lines', 'a posted entry has at least two lines'); lines.forEach((lineArg, indexArg) => { const label = `line ${indexArg + 1} (${lineArg.accountNumber || '?'})`; if (!Number.isSafeInteger(lineArg.amountCents) || lineArg.amountCents <= 0) { refuse( Number.isSafeInteger(lineArg.amountCents) ? 'amount_not_positive' : 'amount_not_whole_cents', lineFieldOf(indexArg, 'amountCents'), `${label}: a posted line states a positive amount of whole cents, not ${String(lineArg.amountCents)}`, indexArg, ); } if (typeof lineArg.buchungstext !== 'string' || lineArg.buchungstext.length > DATEV_MAX_BUCHUNGSTEXT) { refuse('buchungstext_invalid', lineFieldOf(indexArg, 'buchungstext'), `${label}: the Buchungstext is a text of at most ${DATEV_MAX_BUCHUNGSTEXT} characters`, indexArg); } for (const field of ['belegfeld1', 'belegfeld2'] as const) { const value = lineArg[field]; // Belegfeld 1 and 2 as DATEV takes them (`isDatevBelegfeld`, the format description's fields 11 and 12) if (present(value) && !isDatevBelegfeld(value)) { refuse( 'belegfeld_invalid', lineFieldOf(indexArg, field), `${label}: ${field} "${String(value)}" is not 1 to ${DATEV_MAX_BELEGFELD} of the characters DATEV takes (A-Z, a-z, 0-9 and $ & % * + - /; no _, spaces, umlauts, dots, commas, semicolons or colons)`, indexArg, ); } } if (present(lineArg.vatRatePercent) && (typeof lineArg.vatRatePercent !== 'string' || !DECIMAL.test(lineArg.vatRatePercent))) { refuse('vat_rate_invalid', lineFieldOf(indexArg, 'vatRatePercent'), `${label}: vatRatePercent must be a decimal with a point, not "${String(lineArg.vatRatePercent)}"`, indexArg); } if (present(lineArg.vatAmountCents) && !Number.isSafeInteger(lineArg.vatAmountCents)) { refuse('vat_amount_invalid', lineFieldOf(indexArg, 'vatAmountCents'), `${label}: vatAmountCents must be whole cents`, indexArg); } if (present(lineArg.vatAccount) && !isText(lineArg.vatAccount)) refuse('vat_account_invalid', lineFieldOf(indexArg, 'vatAccount'), `${label}: vatAccount must be a non-empty text`, indexArg); if (present(lineArg.declaresAs) && !isText(lineArg.declaresAs)) { refuse('declares_as_invalid', lineFieldOf(indexArg, 'declaresAs'), `${label}: declaresAs must be a non-empty text, the account the line counts as in the VAT return`, indexArg); } }); if (lines.length >= 2 && lines.every((lineArg) => Number.isSafeInteger(lineArg.amountCents) && lineArg.amountCents > 0)) { const validation = validateJournalDraft( { date: new Date(isDay(payload.postingDate) ? `${payload.postingDate}T00:00:00.000Z` : Number.NaN), description: payload.description, skrType: payload.chart, currency: payload.currency, ...(payload.generalumkehr === true ? { generalumkehr: true } : {}), lines: lines.map((lineArg) => ({ ...lineArg })), }, options?.policy, ); // dates, currency and amounts are checked above in the posted entry's own words; the draft's chart is the entry's adopt( validation.issues .filter((issueArg) => issueArg.code !== 'date_invalid' && issueArg.code !== 'currency_not_eur') .map((issueArg) => (issueArg.field === 'skrType' ? { ...issueArg, field: 'chart' } : issueArg)), ); } if (options?.policy) { adopt(automatikRateIssuesOf(lines, options.policy)); } if (present(payload.inputTaxUse)) { adopt(inputTaxUseIssuesOf(payload.inputTaxUse, lines, payload.generalumkehr === true, options?.policy)); } if (present(payload.cause)) { adopt(causeIssuesOf(payload.cause)); } if (present(payload.readThrough)) { adopt(readThroughIssuesOf(payload.readThrough)); } return { valid: errors.length === 0, errors, issues }; } /** A key of `readThrough`: it becomes a document field name, so no `.` or `$`. */ const READ_THROUGH_KEY = /^[A-Za-z][A-Za-z0-9]*$/u; /** * The issues of an entry's `readThrough` (`IPostedEntryPayload.readThrough`): * a plain object (no array, Date or class instance) with at least one key, * each key a letter followed by letters and digits, each value whole epoch * milliseconds from 0. An empty object is refused, since it would hash * otherwise than an absent one. */ function readThroughIssuesOf(readThrough: unknown): IEntryIssue[] { const { issues, refuse } = entryRefusals(); const prototype = typeof readThrough === 'object' && readThrough !== null ? Object.getPrototypeOf(readThrough) : undefined; if (prototype !== Object.prototype && prototype !== null) { refuse('read_through_invalid', 'readThrough', 'readThrough must be a plain object of store names and epoch milliseconds'); return issues; } const times = readThrough as Record; const keys = Object.keys(times); if (keys.length === 0) { refuse('read_through_invalid', 'readThrough', 'readThrough names at least one store; leave it out instead of an empty object'); return issues; } for (const key of keys) { const time = times[key]; if (!READ_THROUGH_KEY.test(key)) { refuse('read_through_invalid', `readThrough.${key}`, `readThrough.${key}: a store name is a letter followed by letters and digits`); } else if (typeof time !== 'number' || !Number.isSafeInteger(time) || time < 0) { refuse('read_through_invalid', `readThrough.${key}`, `readThrough.${key} must be epoch milliseconds, not ${String(time)}`); } } return issues; } /** * The issues of an entry's cause (`IPostedEntryPayload.cause`): an object of * exactly `kind`, `id` and `recordedAt`, two non-empty texts and whole epoch * milliseconds from 0. A key beyond them is refused, since the hash would not * cover it. */ function causeIssuesOf(cause: unknown): IEntryIssue[] { const { issues, refuse } = entryRefusals(); if (typeof cause !== 'object' || cause === null || Array.isArray(cause)) { refuse('cause_invalid', 'cause', 'cause must be an object of kind, id and recordedAt'); return issues; } const fields = cause as Record; const extra = Object.keys(fields).filter((keyArg) => !(CAUSE_KEYS as readonly string[]).includes(keyArg)); if (extra.length > 0) refuse('cause_invalid', 'cause', `cause has only kind, id and recordedAt, not ${extra.join(', ')}`); if (!isText(fields.kind)) refuse('cause_invalid', 'cause.kind', 'cause.kind must be a non-empty text'); if (!isText(fields.id)) refuse('cause_invalid', 'cause.id', 'cause.id must be a non-empty text'); const recordedAt = fields.recordedAt; if (typeof recordedAt !== 'number' || !Number.isSafeInteger(recordedAt) || recordedAt < 0) { refuse('cause_invalid', 'cause.recordedAt', `cause.recordedAt must be epoch milliseconds, not ${String(recordedAt)}`); } return issues; } /** * A key of § 15 Abs. 4 UStG as its one canonical text, since the hash covers * the text: a decimal with a point, above 0 and below 100, up to two places, * no leading zero but a single one before the point, no trailing zero in the * fraction and no bare point (`"62.5"`, `"62.05"`, `"50"`, `"0.5"`; not * `"62.50"`, `"62.0"`, `"062.5"`, `"62."`, `".5"`). */ const DEDUCTIBLE_PERCENT = /^(?:[1-9]\d?|0)(?:\.\d?[1-9])?$/u; /** * The issues of an entry's use statement (`IPostedEntryPayload.inputTaxUse`): * its shape always, and with a policy whether an `exempt` entry moves input * tax: the signed sum of its lines on each of the policy's input-tax accounts * (a Generalumkehr's lines counting the other way) must be zero, since a use * without the right to deduct neither deducts nor corrects a deduction. A * line is on the account it counts as in the VAT return, `declaresAs` where * it gives one: input tax of a closed year carried onto the previous year's * VAT (SKR03 1790, SKR04 3841) still deducts. */ function inputTaxUseIssuesOf( use: IInputTaxUse, lines: readonly IJournalLineDraft[], generalumkehr: boolean, policy: IAccountPolicy | undefined, ): IEntryIssue[] { const { issues, refuse } = entryRefusals(); const kind: unknown = use.kind; const key: unknown = use.deductiblePercent; if (!INPUT_TAX_USE_KINDS.includes(kind as TInputTaxUseKind)) { refuse('input_tax_use_invalid', 'inputTaxUse.kind', `inputTaxUse.kind must be one of ${INPUT_TAX_USE_KINDS.join(', ')}, not ${String(kind)}`); return issues; } if (present(key)) { if (kind !== 'mixed') { refuse('input_tax_use_invalid', 'inputTaxUse.deductiblePercent', `inputTaxUse.deductiblePercent is the key of a mixed use, not of ${String(kind)}`); } else if (typeof key !== 'string' || !DEDUCTIBLE_PERCENT.test(key) || Number(key) <= 0) { refuse( 'input_tax_use_invalid', 'inputTaxUse.deductiblePercent', `inputTaxUse.deductiblePercent must be the deductible part in percent as a decimal text, above 0 and below 100 with up to two places in its canonical form, without leading or trailing zeros or a bare point ("62.5", "50", "0.5"), not ${typeof key === 'string' ? `"${key}"` : String(key)}`, ); } } else if (kind === 'mixed') { refuse('input_tax_use_key_missing', 'inputTaxUse.deductiblePercent', 'inputTaxUse of kind mixed states its key of § 15 Abs. 4 UStG (deductiblePercent)'); } if (kind === 'exempt' && policy) { // each account apart: a debit on one beside a credit on another would misstate two fields of the UStVA const inputTaxAccounts = [...new Set([policy.vat.inputStandard, policy.vat.inputReduced, policy.vat.intraEuAcqInput, policy.vat.reverseChargeInput])]; for (const account of inputTaxAccounts) { const netCents = lines .filter((lineArg) => (lineArg.declaresAs ?? lineArg.accountNumber) === account) .reduce((sumArg, lineArg) => sumArg + (lineArg.side === 'debit' ? lineArg.amountCents : -lineArg.amountCents) * (generalumkehr ? -1 : 1), 0); if (netCents !== 0) { refuse( 'input_tax_use_exempt_deducts', 'inputTaxUse.kind', `inputTaxUse exempt: a supply used for tax-free sales without the right to deduct neither deducts input tax nor corrects a deduction, but the entry's lines on the input-tax account ${account} net to a ${netCents > 0 ? 'debit' : 'credit'} of ${Math.abs(netCents)} cents`, ); } } } return issues; } /** * The lines of a posted entry on an Automatikkonto whose German VAT does not * fit the tax the chart ties the account to (`accountRateMismatchOf`, by which * the recipes refuse a booking: `account_rate_mismatch`, * `automatik_account_not_allowed`; and `vat_amount_off_rate` for a tax off the * rate's). The VAT of a line is that of the domestic VAT lines with its counter * account and side, the group `consolidateJournalDraftForDatev` folds them in, * and each of them is assigned by its rate and amount: the VAT lines of a * group at a rate amount to the tax at that rate on the group's lines whose * automatism books that rate, each line's tax as its net gives it within the * cent a document may state otherwise (`STATED_VAT_TOLERANCE_CENTS`, as the * recipes book it); more VAT at the rate only as far as the other lines of the * group that may carry it (accounts without an automatism) take it, at most * the tax at the rate on their amounts. VAT at a rate no line of the group may * carry so is refused on its lines of a tax-free automatism, or, without * those, on the VAT lines themselves; a Skonto's part at 19 % beside its part * at 0 % carries its own. A group * without domestic VAT in an entry that self-assesses German VAT (an * intra-Community acquisition or § 13b on the policy's accounts of either, * the account's line with key 40) is not checked. A line with key 40 lifts * its account's automatism: DATEV books it as if the account had none (DATEV * Dok.-Nr. 1046108, "als ob keine Automatik-Funktion vorhanden ist"), so it * needs no VAT; where the lines with key 40 of a rate carry VAT, it is their * tax at their accounts' rate, within a cent each, as the recipes book a * stated tax beside key 40, never a part of it. A reclass between * Automatikkonten and the accruals of a close are so posted net. So a sale at 7 % on 8820 is refused, which DATEV would book at 19 % * from one gross row without a BU key; one without VAT and without the key, * from which it would take 19 %; and 8400 at 7 % beside 8300 at 19 % against * one account where their amounts tell it, the tax at each rate then not that * of the lines of the rate. */ function automatikRateIssuesOf(lines: readonly IJournalLineDraft[], policy: IAccountPolicy): IEntryIssue[] { const vatAccounts = Object.values(policy.vat); const selfAssessed = [policy.vat.intraEuAcqInput, policy.vat.intraEuAcqOutput, policy.vat.reverseChargeInput, policy.vat.reverseChargeOutput]; const selfAssessesVat = lines.some((lineArg) => selfAssessed.includes(lineArg.accountNumber)); const labelOf = (indexArg: number): string => `line ${indexArg + 1} (${lines[indexArg].accountNumber})`; const { issues, refuse } = entryRefusals(); const groups = new Map(); lines.forEach((lineArg, indexArg) => { const key = `${lineArg.counterAccount}|${lineArg.side}`; groups.set(key, [...(groups.get(key) ?? []), indexArg]); }); for (const group of groups.values()) { const vatCentsByRate = new Map(); for (const index of group) { const rate = vatRateOfAccount(policy, lines[index].accountNumber); if (rate !== undefined) vatCentsByRate.set(rate, (vatCentsByRate.get(rate) ?? 0) + lines[index].amountCents); } const bases = group.filter((indexArg) => !vatAccounts.includes(lines[indexArg].accountNumber)); const automatik = bases.filter((indexArg) => isAutomatikAccount(policy, lines[indexArg].accountNumber)); if (automatik.length === 0 || (vatCentsByRate.size === 0 && selfAssessesVat)) continue; /** the rate an Automatikkonto's automatism books, where it books one */ const automatikRateOf = (indexArg: number): number | undefined => accountRateMismatchOf(policy, lines[indexArg].accountNumber, undefined)?.automatikRatePercent; /** * whether a line's key 40 lifts its account's automatism: DATEV books it as if the account had none (Dok.-Nr. * 1046108), so the line needs no VAT; where it carries VAT, it is its account's rate's tax as a booking of its own */ const lifted = (indexArg: number): boolean => lines[indexArg].buKey === '40'; /** the bases of the group that may carry VAT at the rate besides the Automatikkonten of that rate */ const carriersOf = (rateArg: number): number[] => bases.filter((indexArg) => automatikRateOf(indexArg) !== rateArg && accountRateMismatchOf(policy, lines[indexArg].accountNumber, rateArg) === undefined); /** the most VAT at the rate those bases may carry: the tax at the rate on their amounts, within a cent each */ const capacityOf = (rateArg: number): number => carriersOf(rateArg).reduce( (sumArg, indexArg) => sumArg + plugins.calculation.vatFromNetCents(lines[indexArg].amountCents, rateArg) + STATED_VAT_TOLERANCE_CENTS, 0, ); const otherRates = (rateArg: number): number[] => [...vatCentsByRate.keys()].filter((otherArg) => otherArg !== rateArg); // the Automatikkonten of each rate their automatism books, against the VAT of that rate: the tax of the lines // without a key, and that of the lines with key 40 together or none of it, each line's within a cent const rates = [...new Set(automatik.map(automatikRateOf).filter((rateArg): rateArg is number => rateArg !== undefined))]; const issuesBefore = issues.length; for (const rate of rates) { const ofRate = automatik.filter((indexArg) => automatikRateOf(indexArg) === rate); const automated = ofRate.filter((indexArg) => !lifted(indexArg)); const requiredCents = automated.reduce((sumArg, indexArg) => sumArg + plugins.calculation.vatFromNetCents(lines[indexArg].amountCents, rate), 0); const bookedCents = vatCentsByRate.get(rate) ?? 0; const toleranceCents = STATED_VAT_TOLERANCE_CENTS * automated.length; const liftedOfRate = ofRate.filter(lifted); const liftedCents = liftedOfRate.reduce((sumArg, indexArg) => sumArg + plugins.calculation.vatFromNetCents(lines[indexArg].amountCents, rate), 0); /** the tax the lines of the rate carry, with the tolerance of the lines it is carried on: the keyless lines', with or without that of the lines with key 40 */ const carried = [ { cents: requiredCents, toleranceCents }, ...(liftedOfRate.length > 0 ? [{ cents: requiredCents + liftedCents, toleranceCents: toleranceCents + STATED_VAT_TOLERANCE_CENTS * liftedOfRate.length }] : []), ]; const capacityCents = capacityOf(rate); if (carried.some((optionArg) => bookedCents >= optionArg.cents - optionArg.toleranceCents && bookedCents <= optionArg.cents + optionArg.toleranceCents + capacityCents)) { continue; } if (bookedCents < requiredCents - toleranceCents) { for (const index of automated) { const other = otherRates(rate)[0]; if (bookedCents > 0) { refuse( 'vat_amount_off_rate', lineFieldOf(index, 'amountCents'), `${labelOf(index)}: the account books German VAT at ${rate} % by its DATEV automatism; the VAT at ${rate} % of its counter account and side is ${bookedCents} cents, the tax at ${rate} % on its lines of that rate ${requiredCents} (vat_amount_off_rate)`, index, ); } else if (other !== undefined) { refuse( 'account_rate_mismatch', lineFieldOf(index, 'accountNumber'), `${labelOf(index)}: the account books German VAT at ${rate} % by its DATEV automatism, and the entry books ${other} % with it; DATEV would book the line at ${rate} % and report its base at that rate (account_rate_mismatch)`, index, ); } else { refuse( 'automatik_account_not_allowed', lineFieldOf(index, 'accountNumber'), `${labelOf(index)}: the account books German VAT at ${rate} % by its DATEV automatism, and the entry books none with it; DATEV would take that tax from the line (automatik_account_not_allowed)`, index, ); } } } else { for (const index of ofRate) { refuse( 'vat_amount_off_rate', lineFieldOf(index, 'amountCents'), `${labelOf(index)}: the account books German VAT at ${rate} % by its DATEV automatism; the VAT at ${rate} % of its counter account and side is ${bookedCents} cents, the tax at ${rate} % on its lines of that rate ${requiredCents} without key 40, ${liftedCents} with it, and no other line of the group carries the rest (vat_amount_off_rate)`, index, ); } } } // VAT at a rate no Automatikkonto of the group books, beyond what the other lines may carry: refused on the tax-free // automatisms, which DATEV reports without tax, or else on the VAT lines, which belong to no line of the group for (const [rate, bookedCents] of vatCentsByRate) { if (rates.includes(rate) || bookedCents <= capacityOf(rate)) continue; const taxFree = automatik.filter( (indexArg) => automatikRateOf(indexArg) === undefined && accountRateMismatchOf(policy, lines[indexArg].accountNumber, rate) !== undefined, ); for (const index of taxFree) { refuse( 'account_rate_mismatch', lineFieldOf(index, 'accountNumber'), `${labelOf(index)}: the account is marked in ${policy.skrType} for the UStVA without German VAT at ${rate} %, and the entry books ${rate} % with it; DATEV reports its base by the account (account_rate_mismatch)`, index, ); } // a VAT line an Automatikkonto of the group is refused for is not refused a second time if (taxFree.length > 0 || issues.length > issuesBefore) continue; for (const index of group.filter((indexArg) => vatRateOfAccount(policy, lines[indexArg].accountNumber) === rate)) { refuse( 'account_rate_mismatch', lineFieldOf(index, 'accountNumber'), `${labelOf(index)}: the VAT at ${rate} % of its counter account and side is ${bookedCents} cents, and no Automatikkonto of the group books ${rate} % nor do its other lines carry it (account_rate_mismatch)`, index, ); } } } return issues; } /** * Verify the entries of one ledger, in their order: each belongs to the * ledger, is numbered one more than the entry before it (1 for the first), * names that entry's hash (the genesis for the first) and still has the hash * of what it records. Answers the first break, or null when the chain is * whole. Hand in every entry of the ledger: a chain cut short at its end is * whole as far as it goes. */ export function verifyLedgerChain(ledgerId: string, entries: readonly IPostedEntry[]): ILedgerChainBreak | null { let expectedPrev = ledgerGenesisHash(ledgerId); for (let index = 0; index < entries.length; index++) { const entry = entries[index]; if (entry.ledgerId !== ledgerId) return { index, seq: entry.seq, reason: 'ledger' }; if (index > 0 && entry.seq === entries[index - 1].seq) return { index, seq: entry.seq, reason: 'duplicate' }; if (entry.seq !== index + 1) return { index, seq: entry.seq, reason: 'gap' }; if (entry.prevHash !== expectedPrev) return { index, seq: entry.seq, reason: 'prev_hash' }; if (postedEntryHash(entry.prevHash, entry) !== entry.entryHash) return { index, seq: entry.seq, reason: 'entry_hash' }; expectedPrev = entry.entryHash; } return null; }