/** * DATEV Buchungsstapel (EXTF 700, Datenkategorie 21) reader: the file a tax * advisor hands back, such as the closing entries of a year, read into the * rows `writeExtfBuchungsstapel` writes and into journal drafts, so they can * be posted as entries taken over from another system. * * The file is Windows-1252 (CP1252), fields separated by `;`, texts quoted * with `"` and a quote inside doubled. A row's Belegdatum is TTMM: its year * is the one of the Stapel's period (header fields 15 and 16, "Datum von" and * "Datum bis") that the day falls in, counted from the Wirtschaftsjahr-Beginn * (header field 13). Only the BU keys skr's table knows (`BU_KEY_RULES`) are * taken: any other key is refused, naming the row. Amounts in another * currency than the euro are refused as well. * * A row is one Buchungssatz: the amount on Konto with the Soll/Haben mark and * on Gegenkonto with the other side. Its tax is unfolded as `journalDraftsToDatevRows` * folds it: a key of a domestic rate, or an Automatikkonto without a key, * books the tax that rate gives from the gross on its own line; a key of a * tax the recipient owes books the pair of input and output tax on the net; * key 40 and key 1 book none. The account the tax is computed on is the * row's profit-and-loss account or Automatikkonto, else the one that is no * personal or money account of the policy; where that cannot be told the row * is refused. */ import * as plugins from './core.plugins.js'; import type { IJournalDraft, IJournalLineDraft, TBuKey, TCents, TLineSide } from './core.types.js'; import { isAutomatikAccount, isCreditorAccount, isDebtorAccount, type IAccountPolicy } from './core.accountpolicy.js'; import { BU_KEY_RULES } from './core.bukeys.js'; import { chartOf } from './core.chart.js'; import { CHART_VAT_AUTOMATIK_RATES, CHART_VAT_AUTOMATIK_TAX_TYPES } from './core.chartaccounts.js'; import { isProfitAndLossAccount } from './core.booksaccounts.js'; import { DATEV_COLUMN_COUNT, type IDatevBuchungsstapelRow } from './core.datev.js'; import { validateJournalDraft } from './core.validate.js'; import { DATEV_MAX_BELEGINFO_ART, DATEV_MAX_BELEGINFO_INHALT, DATEV_MAX_BELEGINFO_PAIRS, type IDatevBelegInfo } from './core.belegfeld.js'; const { splitGrossCents, vatFromNetCents } = plugins.calculation; export type TDatevImportErrorCode = /** the first line is no EXTF header of a Buchungsstapel, or a field of it is not readable (`details.field`) */ | 'extf_header_invalid' /** the Stapel or a row is in another currency than the euro (`details.field`, `.value`) */ | 'extf_currency_unsupported' /** a field of a row is not readable (`details.row`, `.line`, `.field`, `.value`) */ | 'extf_row_malformed' /** a BU key skr's table does not know (`details.row`, `.line`, `.key`) */ | 'extf_bu_key_unknown' /** a Belegdatum that falls in no day of the Stapel's period (`details.row`, `.line`, `.value`) */ | 'extf_date_outside_period' /** a row with a tax whose account cannot be told: both or neither side can carry it (`details.row`, `.line`, `.accounts`) */ | 'extf_tax_account_unclear' /** the entry a row gives is no valid journal draft (`details.row`, `.line`, `.errors`) */ | 'extf_row_invalid'; export interface IDatevImportErrorDetails { /** the data row, from 1 */ row?: number; /** the line of the file, from 1: the data row plus the header and the caption line */ line?: number; field?: string; value?: string; key?: string; accounts?: string[]; errors?: string[]; } /** A Buchungsstapel that cannot be read as it is: the file is the problem, not the code. */ export class DatevImportError extends Error { public readonly code: TDatevImportErrorCode; public readonly details: IDatevImportErrorDetails; constructor(code: TDatevImportErrorCode, message: string, details: IDatevImportErrorDetails = {}) { super(message); this.name = 'DatevImportError'; this.code = code; this.details = details; } } /** What the header of a Buchungsstapel states (the fields `writeExtfBuchungsstapel` writes). */ export interface IDatevExtfHeader { formatVersion: number; createdAt?: Date; consultantNumber: number; clientNumber: number; /** Wirtschaftsjahr-Beginn (field 13) */ fiscalYearStart: Date; /** Sachkontenlänge (field 14) */ accountLength: number; /** the period (fields 15 and 16) */ dateFrom: Date; dateTo: Date; label: string; festschreibung: boolean; } export interface IExtfBuchungsstapel { header: IDatevExtfHeader; rows: IDatevBuchungsstapelRow[]; /** * what was read but not taken, each naming its row, line and field: a * Beleginfo pair of one part only, or of an Art or Inhalt longer than DATEV * takes, is skipped (fields 21 to 36) */ warnings: string[]; } /** One row of a Stapel with the journal draft it gives. */ export interface IImportedDatevRow { /** the data row, from 1 */ row: number; datevRow: IDatevBuchungsstapelRow; draft: IJournalDraft; } /** * The fields of one CSV line: `;` separated, a quoted field with doubled * quotes inside. A quote left open to the end of the line, or text after a * closing quote before the next `;`, is no field DATEV writes: `malformedArg` * is told why. */ function fieldsOf(lineArg: string, malformedArg: (reasonArg: string) => never): string[] { const fields: string[] = []; let current = ''; let quoted = false; let closed = false; for (let index = 0; index < lineArg.length; index += 1) { const char = lineArg[index]; if (quoted) { if (char === '"') { if (lineArg[index + 1] === '"') { current += '"'; index += 1; } else { quoted = false; closed = true; } } else { current += char; } } else if (char === ';') { fields.push(current); current = ''; closed = false; } else if (closed) { malformedArg(`field ${fields.length + 1} has text after its closing quote`); } else if (char === '"' && current === '') { quoted = true; } else { current += char; } } if (quoted) { malformedArg(`field ${fields.length + 1} opens a quote that is never closed`); } fields.push(current); return fields; } /** A day of the calendar from `YYYYMMDD`, or undefined. */ function dayOf(valueArg: string): Date | undefined { const match = /^(\d{4})(\d{2})(\d{2})$/u.exec(valueArg); if (!match) return undefined; const date = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]))); return date.getUTCMonth() === Number(match[2]) - 1 && date.getUTCDate() === Number(match[3]) ? date : undefined; } /** A day from `TTMMJJJJ` (fields 115 to 117), or undefined. */ function dayOfTtmmjjjj(valueArg: string): Date | undefined { const match = /^(\d{2})(\d{2})(\d{4})$/u.exec(valueArg); return match ? dayOf(`${match[3]}${match[2]}${match[1]}`) : undefined; } function headerOf(fieldsArg: string[]): IDatevExtfHeader { const invalid = (fieldArg: string, messageArg: string): DatevImportError => new DatevImportError('extf_header_invalid', `the header of the Buchungsstapel: ${messageArg}`, { field: fieldArg, line: 1 }); if (fieldsArg[0] !== 'EXTF') throw invalid('1', `it is no EXTF file (field 1 is "${fieldsArg[0] ?? ''}")`); if (fieldsArg[2] !== '21') throw invalid('3', `Datenkategorie ${fieldsArg[2] ?? ''} is no Buchungsstapel (21)`); const integer = (indexArg: number, labelArg: string): number => { const value = fieldsArg[indexArg] ?? ''; if (!/^\d+$/u.test(value)) throw invalid(String(indexArg + 1), `${labelArg} is not a number: "${value}"`); return Number(value); }; const day = (indexArg: number, labelArg: string): Date => { const value = dayOf(fieldsArg[indexArg] ?? ''); if (!value) throw invalid(String(indexArg + 1), `${labelArg} is no day YYYYMMDD: "${fieldsArg[indexArg] ?? ''}"`); return value; }; const fiscalYearStart = day(12, 'the Wirtschaftsjahr-Beginn'); const dateFrom = day(14, 'Datum von'); const dateTo = day(15, 'Datum bis'); if (dateTo.getTime() < dateFrom.getTime()) throw invalid('16', 'Datum bis lies before Datum von'); // the period lies within the one Wirtschaftsjahr that begins on field 13, so a TTMM day has one year const fiscalYearEnd = new Date(Date.UTC(fiscalYearStart.getUTCFullYear() + 1, fiscalYearStart.getUTCMonth(), fiscalYearStart.getUTCDate())); if (dateFrom.getTime() < fiscalYearStart.getTime() || dateTo.getTime() >= fiscalYearEnd.getTime()) { throw invalid('15', 'the period from Datum von to Datum bis lies outside the Wirtschaftsjahr that begins on the Wirtschaftsjahr-Beginn'); } const currency = fieldsArg[21] ?? ''; if (currency !== '' && currency !== 'EUR') { throw new DatevImportError('extf_currency_unsupported', `the Buchungsstapel is in ${currency}; these books are in euro`, { field: '22', value: currency, line: 1 }); } const created = /^(\d{8})(\d{2})(\d{2})(\d{2})(\d{3})$/u.exec(fieldsArg[5] ?? ''); const createdDay = created ? dayOf(created[1]) : undefined; return { formatVersion: integer(4, 'the format version'), ...(created && createdDay ? { createdAt: new Date(createdDay.getTime() + ((Number(created[2]) * 60 + Number(created[3])) * 60 + Number(created[4])) * 1000 + Number(created[5])) } : {}), consultantNumber: integer(10, 'the Beraternummer'), clientNumber: integer(11, 'the Mandantennummer'), fiscalYearStart, accountLength: integer(13, 'the Sachkontenlänge'), dateFrom, dateTo, label: fieldsArg[16] ?? '', festschreibung: fieldsArg[20] === '1', }; } /** The day of a TTMM Belegdatum within the Stapel's period, counted from the fiscal year's beginning. */ function belegDatumOf(valueArg: string, headerArg: IDatevExtfHeader): Date | undefined { const match = /^(\d{2})(\d{2})$/u.exec(valueArg); if (!match) return undefined; const startYear = headerArg.fiscalYearStart.getUTCFullYear(); for (const year of [startYear, startYear + 1]) { const day = dayOf(`${year}${match[2]}${match[1]}`); if (day && day.getTime() >= headerArg.dateFrom.getTime() && day.getTime() <= headerArg.dateTo.getTime()) return day; } return undefined; } function rowOf(fieldsArg: string[], rowArg: number, headerArg: IDatevExtfHeader, warningsArg: string[]): IDatevBuchungsstapelRow { const line = rowArg + 2; const malformed = (fieldArg: string, valueArg: string, messageArg: string): DatevImportError => new DatevImportError('extf_row_malformed', `row ${rowArg} (line ${line}): ${messageArg}`, { row: rowArg, line, field: fieldArg, value: valueArg }); const at = (indexArg: number): string => fieldsArg[indexArg] ?? ''; const amount = at(0); if (!/^\d+(,\d{1,2})?$/u.test(amount)) throw malformed('1', amount, `the amount "${amount}" is no positive amount with a decimal comma`); const [euros, cents = ''] = amount.split(','); const umsatzCents: TCents = Number(euros) * 100 + Number(cents.padEnd(2, '0')); if (!Number.isSafeInteger(umsatzCents) || umsatzCents <= 0) throw malformed('1', amount, `the amount "${amount}" is no positive amount`); const sollHaben = at(1); if (sollHaben !== 'S' && sollHaben !== 'H') throw malformed('2', sollHaben, `the Soll/Haben mark "${sollHaben}" is neither S nor H`); const currency = at(2); if (currency !== '' && currency !== 'EUR') { throw new DatevImportError('extf_currency_unsupported', `row ${rowArg} (line ${line}) is in ${currency}; these books are in euro`, { row: rowArg, line, field: '3', value: currency }); } const konto = at(6); const gegenKonto = at(7); if (!/^\d+$/u.test(konto)) throw malformed('7', konto, `the Konto "${konto}" is no account number`); if (!/^\d+$/u.test(gegenKonto)) throw malformed('8', gegenKonto, `the Gegenkonto "${gegenKonto}" is no account number`); const key = at(8); if (key !== '' && key !== '40' && !Object.prototype.hasOwnProperty.call(BU_KEY_RULES, key)) { throw new DatevImportError('extf_bu_key_unknown', `row ${rowArg} (line ${line}) carries the BU key ${key}, which these books do not know`, { row: rowArg, line, key }); } const belegDatum = belegDatumOf(at(9), headerArg); if (!belegDatum) { if (!/^\d{4}$/u.test(at(9))) throw malformed('10', at(9), `the Belegdatum "${at(9)}" is no day TTMM`); throw new DatevImportError('extf_date_outside_period', `row ${rowArg} (line ${line}): the Belegdatum ${at(9)} falls on no day of the Stapel's period`, { row: rowArg, line, value: at(9) }); } const optionalDay = (indexArg: number): Date | undefined => { if (at(indexArg) === '') return undefined; const day = dayOfTtmmjjjj(at(indexArg)); if (!day) throw malformed(String(indexArg + 1), at(indexArg), `field ${indexArg + 1} "${at(indexArg)}" is no day TTMMJJJJ`); return day; }; const belegLink = at(19).replace(/^BEDI\s*/iu, '').replace(/^"+|"+$/gu, ''); // fields 21 to 36: the Beleginfo pairs, each of both parts ("Eine Beleginfo besteht immer aus den Bestandteilen // Beleginfo-Art und Beleginfo-Inhalt"), Art of at most 20 characters, Inhalt of at most 210. A pair DATEV would not // take is information beside the booking, not the booking: it is skipped, said as a warning const belegInfo: IDatevBelegInfo[] = []; for (let pair = 0; pair < DATEV_MAX_BELEGINFO_PAIRS; pair += 1) { const [art, inhalt] = [at(20 + 2 * pair), at(21 + 2 * pair)]; if (art === '' && inhalt === '') continue; const skipped = (fieldArg: number, reasonArg: string): void => { warningsArg.push(`row ${rowArg} (line ${line}), field ${fieldArg}: Beleginfo ${pair + 1} ${reasonArg}; skipped`); }; if (art === '' || inhalt === '') { skipped(art === '' ? 21 + 2 * pair : 22 + 2 * pair, `gives only its ${art === '' ? `Inhalt "${inhalt}"` : `Art "${art}"`}, not both parts`); } else if (art.length > DATEV_MAX_BELEGINFO_ART) { skipped(21 + 2 * pair, `has an Art of ${art.length} characters, more than ${DATEV_MAX_BELEGINFO_ART}`); } else if (inhalt.length > DATEV_MAX_BELEGINFO_INHALT) { skipped(22 + 2 * pair, `has an Inhalt of ${inhalt.length} characters, more than ${DATEV_MAX_BELEGINFO_INHALT}`); } else { belegInfo.push({ art, inhalt }); } } const leistungsdatum = optionalDay(114); const datumZuordSteuerperiode = optionalDay(115); return { umsatzCents, sollHaben, konto, gegenKonto, buSchluessel: key as TBuKey, belegDatum, ...(at(10) !== '' ? { belegfeld1: at(10) } : {}), ...(at(11) !== '' ? { belegfeld2: at(11) } : {}), buchungstext: at(13), ...(belegLink !== '' ? { belegLink } : {}), ...(belegInfo.length > 0 ? { belegInfo } : {}), ...(at(36) !== '' ? { kost1: at(36) } : {}), ...(at(37) !== '' ? { kost2: at(37) } : {}), ...(at(113) !== '' ? { festschreibung: at(113) === '1' } : {}), ...(leistungsdatum ? { leistungsdatum } : {}), ...(datumZuordSteuerperiode ? { datumZuordSteuerperiode } : {}), ...(at(117) !== '' ? { generalumkehr: at(117) === '1' } : {}), ...(at(39) !== '' ? { euVatIdDestination: at(39) } : {}), }; } /** * Reads a Buchungsstapel as DATEV writes it: Windows-1252 bytes, the EXTF * header, the caption line and one row per Buchungssatz. Refuses with a * `DatevImportError` naming the row; a Beleginfo pair DATEV would not take is * skipped, named in `warnings`. */ export function readExtfBuchungsstapel(bytesArg: Uint8Array): IExtfBuchungsstapel { const text = new TextDecoder('windows-1252').decode(bytesArg); const lines = text.split(/\r?\n/u).filter((lineArg, indexArg, allArg) => !(lineArg === '' && indexArg === allArg.length - 1)); if (lines.length < 2) throw new DatevImportError('extf_header_invalid', 'the Buchungsstapel has no header and caption line', { line: 1 }); const lineFields = (indexArg: number, codeArg: 'extf_header_invalid' | 'extf_row_malformed'): string[] => fieldsOf(lines[indexArg], (reasonArg) => { const details: IDatevImportErrorDetails = codeArg === 'extf_row_malformed' ? { row: indexArg - 1, line: indexArg + 1 } : { line: indexArg + 1 }; throw new DatevImportError(codeArg, codeArg === 'extf_row_malformed' ? `row ${indexArg - 1} (line ${indexArg + 1}): ${reasonArg}` : `line ${indexArg + 1}: ${reasonArg}`, details); }); const header = headerOf(lineFields(0, 'extf_header_invalid')); const captions = lineFields(1, 'extf_header_invalid'); if (captions[0] !== 'Umsatz (ohne Soll/Haben-Kz)') { throw new DatevImportError('extf_header_invalid', 'the second line is not the caption line of a Buchungsstapel', { line: 2, field: '1', value: captions[0] ?? '' }); } if (captions.length !== DATEV_COLUMN_COUNT) { throw new DatevImportError('extf_header_invalid', `the caption line has ${captions.length} fields, not the ${DATEV_COLUMN_COUNT} of a Buchungsstapel`, { line: 2 }); } const warnings: string[] = []; const rows = lines.slice(2).map((_, indexArg) => { const fields = lineFields(indexArg + 2, 'extf_row_malformed'); // a row has every field of the caption line: one cut short would lose its later fields (the Beleglink, field 118) if (fields.length !== captions.length) { throw new DatevImportError('extf_row_malformed', `row ${indexArg + 1} (line ${indexArg + 3}) has ${fields.length} fields, not the ${captions.length} of the caption line`, { row: indexArg + 1, line: indexArg + 3 }); } return rowOf(fields, indexArg + 1, header, warnings); }); return { header, rows, warnings }; } /** Whether an account can carry the row's tax: a profit-and-loss account or an Automatikkonto. */ function carriesTax(policyArg: IAccountPolicy, accountArg: string): boolean { return isProfitAndLossAccount(policyArg, accountArg, 'expense') || isProfitAndLossAccount(policyArg, accountArg, 'income') || isAutomatikAccount(policyArg, accountArg); } /** Whether an account is a personal account or one money moves on in the policy. */ function isPersonalOrMoney(policyArg: IAccountPolicy, accountArg: string): boolean { return isDebtorAccount(policyArg, accountArg) || isCreditorAccount(policyArg, accountArg) || [policyArg.bank, policyArg.cash, policyArg.clearing, policyArg.geldtransit].includes(accountArg); } /** The side of the row the tax is computed on: `konto` or `gegenKonto`; undefined where it cannot be told. */ function taxSideOf(rowArg: IDatevBuchungsstapelRow, policyArg: IAccountPolicy): 'konto' | 'gegenKonto' | undefined { const onKonto = carriesTax(policyArg, rowArg.konto); const onGegenkonto = carriesTax(policyArg, rowArg.gegenKonto); if (onKonto !== onGegenkonto) return onKonto ? 'konto' : 'gegenKonto'; const kontoIsMoney = isPersonalOrMoney(policyArg, rowArg.konto); const gegenkontoIsMoney = isPersonalOrMoney(policyArg, rowArg.gegenKonto); if (kontoIsMoney !== gegenkontoIsMoney) return kontoIsMoney ? 'gegenKonto' : 'konto'; return undefined; } /** The tax a row books by its key or by the automatism of the account it is on: the rate, the kind and the accounts. */ function taxOf( rowArg: IDatevBuchungsstapelRow, accountArg: string, policyArg: IAccountPolicy, ): { kind: 'gross'; rate: number; vatAccount: string } | { kind: 'self_assessed'; rate: number; inputAccount: string; outputAccount: string } | undefined { const { vat } = policyArg; switch (rowArg.buSchluessel) { case '2': return { kind: 'gross', rate: 7, vatAccount: vat.outputReduced }; case '3': return { kind: 'gross', rate: 19, vatAccount: vat.outputStandard }; case '8': return { kind: 'gross', rate: 7, vatAccount: vat.inputReduced }; case '9': return { kind: 'gross', rate: 19, vatAccount: vat.inputStandard }; case '18': return { kind: 'self_assessed', rate: 7, inputAccount: vat.intraEuAcqInput, outputAccount: vat.intraEuAcqOutput }; case '19': return { kind: 'self_assessed', rate: 19, inputAccount: vat.intraEuAcqInput, outputAccount: vat.intraEuAcqOutput }; case '91': return { kind: 'self_assessed', rate: 7, inputAccount: vat.reverseChargeInput, outputAccount: vat.reverseChargeOutput }; case '94': return { kind: 'self_assessed', rate: 19, inputAccount: vat.reverseChargeInput, outputAccount: vat.reverseChargeOutput }; case '': { // an Automatikkonto without a key: DATEV books the tax its automatism gives const rate = CHART_VAT_AUTOMATIK_RATES[chartOf(policyArg)][accountArg]; const taxType = CHART_VAT_AUTOMATIK_TAX_TYPES[chartOf(policyArg)][accountArg]; if (rate === undefined || taxType === undefined) return undefined; const vatAccount = taxType === 'ust' ? rate === 7 ? vat.outputReduced : vat.outputStandard : rate === 7 ? vat.inputReduced : vat.inputStandard; return { kind: 'gross', rate, vatAccount }; } default: // key 40 cancels the automatism, key 1 is tax-free: neither books a tax return undefined; } } /** * Whether a row's key books on an Automatikkonto the tax its automatism * books, at its rate on its tax account, such as key 3 on SKR03 8611 (19 % * USt): the key says again what the account says, so the row books as it * would without it. */ function keyRestatesAutomatism(rowArg: IDatevBuchungsstapelRow, accountArg: string, policyArg: IAccountPolicy): boolean { if (rowArg.buSchluessel === '' || !isAutomatikAccount(policyArg, accountArg)) return false; const keyed = taxOf(rowArg, accountArg, policyArg); const automatism = taxOf({ ...rowArg, buSchluessel: '' }, accountArg, policyArg); return keyed?.kind === 'gross' && automatism?.kind === 'gross' && keyed.rate === automatism.rate && keyed.vatAccount === automatism.vatAccount; } /** Whether a row books a tax at all: a key of a tax, or an Automatikkonto at a rate on either side without a key. */ function booksTax(rowArg: IDatevBuchungsstapelRow, policyArg: IAccountPolicy): boolean { const rule = rowArg.buSchluessel === '' ? null : BU_KEY_RULES[rowArg.buSchluessel as Exclude]; if (rule) return rule.taxType !== 'automatik_aufhebung' && rule.ratePercent !== null && rule.ratePercent > 0; const rates = CHART_VAT_AUTOMATIK_RATES[chartOf(policyArg)]; return rates[rowArg.konto] !== undefined || rates[rowArg.gegenKonto] !== undefined; } /** * The journal draft of one row of a Buchungsstapel, its tax unfolded onto * the tax accounts of the policy as `consolidateJournalDraftForDatev` folds * it, so a Stapel skr wrote reads back into drafts it writes again row for * row. A key on an Automatikkonto that books the tax of its automatism is * read as the automatism (`keyRestatesAutomatism`), so the account never * carries it; a key of another tax stays on the account, which * `validateJournalDraft` refuses (`automatik_bu_key`). Refuses * (`extf_tax_account_unclear`) a row that books a tax where the account it is * computed on cannot be told. */ export function journalDraftOfDatevRow(rowArg: IDatevBuchungsstapelRow, policyArg: IAccountPolicy): IJournalDraft { const kontoSide: TLineSide = rowArg.sollHaben === 'S' ? 'debit' : 'credit'; const other = (sideArg: TLineSide): TLineSide => (sideArg === 'debit' ? 'credit' : 'debit'); const texts = { buchungstext: rowArg.buchungstext, ...(rowArg.belegfeld1 !== undefined ? { belegfeld1: rowArg.belegfeld1 } : {}), ...(rowArg.belegfeld2 !== undefined ? { belegfeld2: rowArg.belegfeld2 } : {}), ...(rowArg.kost1 !== undefined ? { costCenter1: rowArg.kost1 } : {}), ...(rowArg.kost2 !== undefined ? { costCenter2: rowArg.kost2 } : {}), ...(rowArg.belegLink !== undefined ? { docLink: rowArg.belegLink } : {}), ...(rowArg.belegInfo !== undefined ? { belegInfo: rowArg.belegInfo.map((pairArg) => ({ ...pairArg })) } : {}), }; const draftOf = (linesArg: IJournalLineDraft[]): IJournalDraft => ({ date: rowArg.belegDatum, description: rowArg.buchungstext, ...(rowArg.belegfeld1 !== undefined ? { reference: rowArg.belegfeld1 } : {}), skrType: chartOf(policyArg), currency: 'EUR', ...(rowArg.generalumkehr === true ? { generalumkehr: true } : {}), lines: linesArg, }); const taxSide = taxSideOf(rowArg, policyArg); const base = taxSide === 'gegenKonto' ? { account: rowArg.gegenKonto, counter: rowArg.konto, side: other(kontoSide) } : { account: rowArg.konto, counter: rowArg.gegenKonto, side: kontoSide }; if (booksTax(rowArg, policyArg)) { if (!taxSide) { throw new DatevImportError('extf_tax_account_unclear', `the row books a tax, and neither or both of ${rowArg.konto} and ${rowArg.gegenKonto} can carry it`, { accounts: [rowArg.konto, rowArg.gegenKonto], }); } const tax = taxOf(rowArg, base.account, policyArg); if (tax?.kind === 'gross') { const { netCents, vatCents } = splitGrossCents(rowArg.umsatzCents, tax.rate); // an Automatikkonto keeps its automatism cancelled next to the explicit tax line, as the recipes book it, also where its key only restated the automatism const key: TBuKey = keyRestatesAutomatism(rowArg, base.account, policyArg) ? '' : rowArg.buSchluessel; const baseKey: TBuKey = key !== '' ? key : vatCents > 0 ? '40' : ''; return draftOf([ { accountNumber: base.account, counterAccount: base.counter, side: base.side, amountCents: vatCents > 0 ? netCents : rowArg.umsatzCents, buKey: baseKey, ...texts }, ...(vatCents > 0 ? [{ accountNumber: tax.vatAccount, counterAccount: base.counter, side: base.side, amountCents: vatCents, buKey: '' as TBuKey, ...texts }] : []), { accountNumber: base.counter, counterAccount: base.account, side: other(base.side), amountCents: rowArg.umsatzCents, buKey: '', ...texts }, ]); } if (tax?.kind === 'self_assessed') { const vatCents = vatFromNetCents(rowArg.umsatzCents, tax.rate); return draftOf([ { accountNumber: base.account, counterAccount: base.counter, side: base.side, amountCents: rowArg.umsatzCents, buKey: rowArg.buSchluessel, ...texts }, { accountNumber: tax.inputAccount, counterAccount: tax.outputAccount, side: base.side, amountCents: vatCents, buKey: '', ...texts }, { accountNumber: tax.outputAccount, counterAccount: tax.inputAccount, side: other(base.side), amountCents: vatCents, buKey: '', ...texts }, { accountNumber: base.counter, counterAccount: base.account, side: other(base.side), amountCents: rowArg.umsatzCents, buKey: '', ...texts }, ]); } } // no tax: the Buchungssatz as it stands, its key on the account it belongs to return draftOf([ { accountNumber: base.account, counterAccount: base.counter, side: base.side, amountCents: rowArg.umsatzCents, buKey: rowArg.buSchluessel, ...texts }, { accountNumber: base.counter, counterAccount: base.account, side: other(base.side), amountCents: rowArg.umsatzCents, buKey: '', ...texts }, ]); } /** * Reads a Buchungsstapel and gives each row's journal draft, each checked * against the policy (`validateJournalDraft`). Refuses the first row that * cannot be read or booked, naming it. What the reading skipped is in * `warnings` (`readExtfBuchungsstapel`): a Beleginfo DATEV would not take * never refuses a row, as the drafts carry only the pairs it took. */ export function importExtfBuchungsstapel(bytesArg: Uint8Array, policyArg: IAccountPolicy): { header: IDatevExtfHeader; entries: IImportedDatevRow[]; warnings: string[] } { const { header, rows, warnings } = readExtfBuchungsstapel(bytesArg); const entries = rows.map((datevRow, indexArg) => { const row = indexArg + 1; let draft: IJournalDraft; try { draft = journalDraftOfDatevRow(datevRow, policyArg); } catch (error) { if (error instanceof DatevImportError) { throw new DatevImportError(error.code, `row ${row} (line ${row + 2}): ${error.message}`, { ...error.details, row, line: row + 2 }); } throw error; } const validation = validateJournalDraft(draft, policyArg); if (!validation.valid) { throw new DatevImportError('extf_row_invalid', `row ${row} (line ${row + 2}) gives no valid entry: ${validation.errors.join('; ')}`, { row, line: row + 2, errors: validation.errors }); } return { row, datevRow, draft }; }); return { header, entries, warnings }; }