/** * DATEV Buchungsstapel (EXTF 700, Formatversion 13) row model and writer. * * Layout verified against a DATEV-importable reference file (2026-07-09): * 125 data columns, 31 header fields, decimal-comma amounts, Belegdatum TTMM, * text fields quoted, field 114 = Festschreibung. The writer emits a CSV * STRING with CRLF; persisting it as CP1252 is the IO layer's job. * One manual import into real DATEV per release candidate remains the final * conformance gate (readme.plan.md, M0). * * A DATEV row is one Buchungssatz: the amount is booked on Konto with the * Soll/Haben mark and on Gegenkonto with the opposite side. A journal draft * is a balanced set of lines, so it is consolidated into bookings before it * is written (see journalDraftsToDatevRows); writing one row per line would * book every draft twice on import. */ import * as plugins from './core.plugins.js'; import type { IJournalDraft, IJournalLineDraft, TBuKey, TCents, TLineSide } from './core.types.js'; import { getDefaultPolicy, isAutomatikAccount, type IAccountPolicy } from './core.accountpolicy.js'; import { accountRateMismatchOf, vatRateOfAccount } from './core.accountrate.js'; import { DATEV_COLUMN_CAPTIONS } from './core.datev.captions.js'; import { DATEV_MAX_BUCHUNGSTEXT } from './core.validate.js'; import { datevBelegfelderOf, datevBelegInfoFault, type IDatevBelegInfo } from './core.belegfeld.js'; const { allocateCents, centsToString, splitGrossCents } = plugins.calculation; export const DATEV_COLUMN_COUNT = 125; export const DATEV_HEADER_FIELD_COUNT = 31; export interface IDatevBuchungsstapelRow { umsatzCents: TCents; sollHaben: 'S' | 'H'; konto: string; gegenKonto: string; buSchluessel: TBuKey; belegDatum: Date; /** as DATEV takes it (`isDatevBelegfeld`); the writer maps any other text (`datevBelegfelderOf`), its original as a Beleginfo */ belegfeld1?: string; belegfeld2?: string; /** fields 21 to 36: 1 to 8 pairs of Art (at most 20 characters) and Inhalt (at most 210), both given (`datevBelegInfoFault`) */ belegInfo?: IDatevBelegInfo[]; buchungstext: string; /** document GUID; written as `BEDI "GUID"` (field 20) */ belegLink?: string; kost1?: string; kost2?: string; festschreibung?: boolean; /** * DATEV Buchungsstapel field 118 "Generalumkehr" (format description on * developer.datev.de, "Buchungsstapel", read 2026-09-25: `^(["](0|1)["])$`, * "G oder 1 = Generalumkehr, 0 = keine Generalumkehr"). `true` writes "1": * the row is a general reversal. `false` writes "0"; absent writes nothing. * `journalDraftsToDatevRows` sets it to `true` on every row of a draft * marked `generalumkehr`, and leaves it unset otherwise. */ generalumkehr?: boolean; /** * Field 115 "Leistungsdatum", written TTMMJJJJ. The format description * (developer.datev.de, "Buchungsstapel", read 2026-09-25) gives * `^((0[1-9]|[1-2]\d|3[0-1])(0[1-9]|1[0-2])([2])([0])(\d{2}))$`, so years * 2000 to 2099 only, and: "Beim Import des Leistungsdatums muss das Feld * ‚116 Datum Zuord. Steuerperiode' gefüllt sein. Der Einsatz des * Leistungsdatums muss in Absprache mit dem Steuerberater erfolgen." A row * with a Leistungsdatum and without field 116 is refused. */ leistungsdatum?: Date; /** * Field 116 "Datum Zuord. Steuerperiode", written TTMMJJJJ, with the same * expression as field 115. `journalDraftsToDatevRows` sets neither: which * day assigns a booking to its tax period is agreed with the advisor. */ datumZuordSteuerperiode?: Date; /** * DATEV Buchungsstapel field 40 "EU-Mitgliedstaat u. UStID (Bestimmung)" * (format description on developer.datev.de, "Buchungsstapel", read * 2026-09-25: `^(["].{0,15}["])$`; a 2-digit country code, Greece `EL`, * Northern Ireland `XI`, then at most 13 characters of the VAT ID). Written * quoted where given; absent writes nothing. What DATEV derives from it * (DATEV doc 9211462) is not public; the field only states the recipient's * VAT ID. */ euVatIdDestination?: string; } /** The shape field 40 takes: a country code of two capitals and at most 13 letters, digits, `+` or `*`. */ const EU_VAT_ID_DESTINATION = /^[A-Z]{2}[A-Z0-9+*]{0,13}$/; export interface IDatevExtfHeaderOptions { /** deterministic input — core never reads the clock */ createdAt: Date; consultantNumber: number; clientNumber: number; fiscalYearStart: Date; dateFrom: Date; dateTo: Date; label: string; festschreibung: boolean; accountLength?: number; /** 2-char producer id in the header */ origin?: string; exportedBy?: string; } function pad(value: number, width: number): string { return String(value).padStart(width, '0'); } function formatYyyymmdd(date: Date): string { return `${date.getUTCFullYear()}${pad(date.getUTCMonth() + 1, 2)}${pad(date.getUTCDate(), 2)}`; } function formatTtmm(date: Date): string { return `${pad(date.getUTCDate(), 2)}${pad(date.getUTCMonth() + 1, 2)}`; } /** Fields 115-117: TTMMJJJJ, years 2000 to 2099 by the format description's expression. */ function formatTtmmjjjj(date: Date, field: string): string { if (!(date instanceof Date) || Number.isNaN(date.getTime())) { throw new Error(`DATEV field ${field} needs a valid date`); } const year = date.getUTCFullYear(); if (year < 2000 || year > 2099) { throw new Error(`DATEV field ${field} takes the years 2000 to 2099 only, not ${year}`); } return `${formatTtmm(date)}${year}`; } function formatTimestamp(date: Date): string { return ( formatYyyymmdd(date) + pad(date.getUTCHours(), 2) + pad(date.getUTCMinutes(), 2) + pad(date.getUTCSeconds(), 2) + pad(date.getUTCMilliseconds(), 3) ); } function formatAmount(cents: TCents): string { return centsToString(cents).replace('.', ',').replace('-', '-'); } /** * A line break (CRLF counts as one), a control character of C0 or C1, DEL, or a Unicode line or paragraph separator: * inside a field it would split the row's line of the file, or put into DATEV what nobody can see. */ const CONTROL_IN_TEXT = /\r\n|[\u0000-\u001F\u007F-\u009F\u2028\u2029]/gu; /** * A text field as the file writes it: a `"` as `'` and each line break or control character as one space, so the * field stays on its row's line, then cut to `maxLength`, and quoted. */ function quote(value: string, maxLength?: number): string { let sanitized = value.replace(/"/g, "'").replace(CONTROL_IN_TEXT, ' '); if (maxLength && sanitized.length > maxLength) { sanitized = sanitized.slice(0, maxLength); } return `"${sanitized}"`; } export interface IDatevRowsOptions { festschreibung?: boolean; /** * Recognises VAT lines and Automatikkonten while consolidating; defaults to * the default policy of each draft's chart. */ policy?: IAccountPolicy; } /** Domestic tax keys whose row carries the gross amount; DATEV computes the VAT. */ const VAT_RATE_OF_KEY: Partial> = { '9': 19, '8': 7, '3': 19, '2': 7 }; function isVatAccount(policy: IAccountPolicy, accountNumber: string): boolean { return Object.values(policy.vat).includes(accountNumber); } function signedCents(line: IJournalLineDraft): TCents { return line.side === 'debit' ? line.amountCents : -line.amountCents; } function mirrors(left: IJournalLineDraft, right: IJournalLineDraft): boolean { return ( left.counterAccount === right.accountNumber && right.counterAccount === left.accountNumber && signedCents(left) + signedCents(right) === 0 ); } function declares(line: IJournalLineDraft): boolean { return line.declaresAs !== undefined && line.declaresAs !== null; } /** * Whether two lines carried from a closed year book one amount against each * other on one account, so they net to nothing there: both name the account * they declare as, sit on one account, cancel, and each line's counter * account is the account the other declares as (the § 13b input and output * tax, SKR03 1577 against 1787, both moved onto 1790 with their counter * accounts kept). Two lines booked against their own account are no such * pair: they stay, and the guard refuses the row. */ function cancelOnOneAccount(left: IJournalLineDraft, right: IJournalLineDraft): boolean { return ( declares(left) && declares(right) && left.accountNumber === right.accountNumber && signedCents(left) + signedCents(right) === 0 && left.counterAccount === right.declaresAs && right.counterAccount === left.declaresAs ); } /** * The lines with their counter accounts as DATEV states them. A correction * carried from a closed year moves lines and keeps every counter account as * booked, so a counter account may name an account no line of the draft is * on any more. Such a line takes as its counter account the account A the * lines declaring its counter account sit on (the vendor line against 4920 * takes 2020, where the expense declaring 4920 now is). Lines declaring it on * more than one account leave A unclear: that throws. A line whose A is its * own account keeps its counter account, for `cancelOnOneAccount`; a counter * account no line is on and none declares stays as it is. */ function countersResolved(lines: IJournalLineDraft[], draftLabel: string): IJournalLineDraft[] { const accounts = new Set(lines.map((line) => line.accountNumber)); return lines.map((line, index) => { if (accounts.has(line.counterAccount)) return line; const candidates = [...new Set(lines.filter((other) => declares(other) && other.declaresAs === line.counterAccount).map((other) => other.accountNumber))]; if (candidates.length > 1) { throw new Error( `${draftLabel} cannot be written as DATEV bookings: line ${index + 1} (${line.accountNumber} ${line.side} ${line.amountCents} against ${line.counterAccount}) has a counter account declared on ${candidates.join(' and ')}, so its Gegenkonto is unclear`, ); } if (candidates.length === 0 || candidates[0] === line.accountNumber) return line; return { ...line, counterAccount: candidates[0] }; }); } /** * A line that counts in the VAT return as another account (`declaresAs`: a * correction of a closed year carried into a later year onto the * periodenfremde account or the VAT of past years) as DATEV gets it: plain, * without BU key, rate, VAT account or § 13b paragraph. Its tax belongs to the * closed year's return; a key would make DATEV book it again in the year of * the booking, and DATEV refuses a key on the VAT of past years (SKR03 1789 to * 1791, SKR04 3840/3841/3845, KU). */ function plainIfDeclared(line: IJournalLineDraft): IJournalLineDraft { if (line.declaresAs === undefined || line.declaresAs === null) return line; const { vatRatePercent: _rate, vatAccount: _vatAccount, reverseChargeParagraph: _paragraph, ...plain } = line; return { ...plain, buKey: '' }; } /** Keys that make DATEV compute a self-assessed VAT pair (input against output VAT). */ function selfAssessedKeysOf(policy: IAccountPolicy, accountA: string, accountB: string): TBuKey[] | undefined { if (accountA === accountB) return undefined; const reverseCharge = [policy.vat.reverseChargeInput, policy.vat.reverseChargeOutput]; const intraEu = [policy.vat.intraEuAcqInput, policy.vat.intraEuAcqOutput]; if (reverseCharge.includes(accountA) && reverseCharge.includes(accountB)) return ['94', '91']; if (intraEu.includes(accountA) && intraEu.includes(accountB)) return ['19', '18']; return undefined; } /** * Consolidate one balanced draft into the lines that become DATEV bookings. * * 0. A line that counts in the VAT return as another account (`declaresAs`) * is plain before anything else (`plainIfDeclared`): no BU key, rate, VAT * account or § 13b paragraph, so it neither carries a tax of its own nor * makes a pair or a fold below. No row carries a tax field for it. A line * whose counter account no line is on any more takes the account the * lines declaring that counter account sit on (`countersResolved`; more * than one such account throws). * 1. VAT lines. A §13b / intra-EU pair (input and output VAT booked against * each other) is dropped when a base line of the draft carries the key * that makes DATEV compute both sides (94/91, 19/18); without such a key * the pair stays and becomes one explicit booking. Domestic VAT lines are * folded, per Gegenkonto and side, into the base lines whose BU key * carries their rate (9/8, 3/2), sharing the VAT in proportion; a VAT * line without a keyed base is folded into an Automatikkonto base (key * 40 becomes '') only when it is the single remaining VAT line, that * base is the single Automatikkonto candidate, the account's automatism * books the VAT line's rate (`accountRateMismatchOf`: the chart's rate of * the account; one a policy adds is taken at the VAT line's rate), and it * computes the same tax from the gross (a tax a document states, * `IDocumentVatGroup.vatCents`, may differ by a cent). An account whose * automatism books another rate, or none, would book its own tax from * the gross row (7 % VAT on SKR03 8820 booked at 19 %), so the VAT line * is not folded there. Everything else stays an explicit booking on the * tax account, next to a base that carries key 40: an Automatikkonto base * of its group whose automatism books a tax is written with key 40, so * DATEV books no tax of its own on top, as the draft books none on it. * 2. Two carried lines that book one amount against each other on one * account (`cancelOnOneAccount`: the § 13b pair of a closed year carried * onto the previous year's VAT) net to nothing there and give no booking. * Mirror lines (A against B and B against A with the same amount) become * one booking, taken from the line with a BU key, else from the debit * line. * 3. Split lines against one aggregate line (their signed sum cancels the * aggregate) become one booking each; the aggregate line is dropped. * Anything left over throws: writing it would double the booking on import; * so does a booking against its own account, which no row may state. */ export function consolidateJournalDraftForDatev( draft: IJournalDraft, policy: IAccountPolicy, ): IJournalLineDraft[] { if (draft.generalumkehr === true) { const negative = draft.lines.findIndex((line) => line.amountCents < 0); if (negative >= 0) { throw new Error( `Journal draft "${draft.description}" is a Generalumkehr, and its line ${negative + 1} states a negative amount; a Generalumkehr line states its amount positive`, ); } } const when = draft.date instanceof Date && !Number.isNaN(draft.date.getTime()) ? draft.date.toISOString().slice(0, 10) : 'undated'; const draftLabel = `Journal draft "${draft.description}" (${when}${draft.reference ? `, ${draft.reference}` : ''})`; const lines: IJournalLineDraft[] = countersResolved( draft.lines .map((line) => line.amountCents < 0 ? { ...line, amountCents: -line.amountCents, side: (line.side === 'debit' ? 'credit' : 'debit') as TLineSide } : { ...line }, ) .map(plainIfDeclared) .filter((line) => line.amountCents !== 0), draftLabel, ); const consumed = new Set(); const open = (): number[] => lines.map((_, index) => index).filter((index) => !consumed.has(index)); const isVat = (index: number): boolean => isVatAccount(policy, lines[index].accountNumber); // 1a self-assessed VAT pairs for (const i of open()) { if (consumed.has(i) || !isVat(i)) continue; for (const j of open()) { if (j <= i || !isVat(j) || !mirrors(lines[i], lines[j])) continue; const keys = selfAssessedKeysOf(policy, lines[i].accountNumber, lines[j].accountNumber); if (keys && open().some((k) => !isVat(k) && keys.includes(lines[k].buKey))) { consumed.add(i); consumed.add(j); } break; } } // 1b domestic VAT lines folded into their base lines, per Gegenkonto and side const fold = (vatIndex: number, bases: number[], clearKey: boolean): void => { const shares = allocateCents(lines[vatIndex].amountCents, bases.map((j) => lines[j].amountCents)); bases.forEach((j, position) => { lines[j] = { ...lines[j], amountCents: lines[j].amountCents + shares[position], buKey: clearKey ? '' : lines[j].buKey }; }); consumed.add(vatIndex); }; const groups = new Map(); for (const i of open()) { if (!isVat(i) || vatRateOfAccount(policy, lines[i].accountNumber) === undefined) continue; const key = `${lines[i].counterAccount}|${lines[i].side}`; groups.set(key, [...(groups.get(key) ?? []), i]); } for (const [key, vatLines] of groups) { const bases = open().filter((j) => !isVat(j) && `${lines[j].counterAccount}|${lines[j].side}` === key); const remaining: number[] = []; for (const i of vatLines) { const rate = vatRateOfAccount(policy, lines[i].accountNumber); const keyed = bases.filter((j) => VAT_RATE_OF_KEY[lines[j].buKey] === rate); if (keyed.length === 0) { remaining.push(i); continue; } fold(i, keyed, false); } const automatik = bases.filter( (j) => isAutomatikAccount(policy, lines[j].accountNumber) && (lines[j].buKey === '' || lines[j].buKey === '40'), ); // an Automatikkonto computes the tax from the gross on import at the rate of its automatism: only a tax at that rate // it computes alike is left to it, a tax booked as its document states it (SKR-VAT1) or at another rate stays a // booking of its own next to the base with key 40 if (remaining.length === 1 && automatik.length === 1) { const vatRate = vatRateOfAccount(policy, lines[remaining[0]].accountNumber); const gross = lines[automatik[0]].amountCents + lines[remaining[0]].amountCents; if ( vatRate !== undefined && accountRateMismatchOf(policy, lines[automatik[0]].accountNumber, vatRate) === undefined && splitGrossCents(gross, vatRate).vatCents === lines[remaining[0]].amountCents ) { fold(remaining[0], automatik, true); } } // a VAT line of the group stays a booking of its own: an Automatikkonto base whose automatism books a tax carries // key 40, or DATEV would book that tax from the base on top of it if (remaining.some((i) => !consumed.has(i))) { for (const j of automatik) { if (lines[j].buKey === '' && accountRateMismatchOf(policy, lines[j].accountNumber, undefined) !== undefined) { lines[j] = { ...lines[j], buKey: '40' }; } } } } const bookings: IJournalLineDraft[] = []; // 2 mirror lines for (const i of open()) { if (consumed.has(i)) continue; for (const j of open()) { if (j <= i) continue; if (cancelOnOneAccount(lines[i], lines[j])) { consumed.add(i); consumed.add(j); break; } if (mirrors(lines[i], lines[j])) { const keep = lines[i].buKey !== '' ? i : lines[j].buKey !== '' ? j : lines[i].side === 'debit' ? i : j; bookings.push(lines[keep]); consumed.add(i); consumed.add(j); break; } } } // 3 split lines against their aggregate line for (const aggregateIndex of open()) { if (consumed.has(aggregateIndex)) continue; const aggregate = lines[aggregateIndex]; const group = open().filter((index) => index !== aggregateIndex && lines[index].counterAccount === aggregate.accountNumber); if (group.length === 0) continue; if (signedCents(aggregate) + group.reduce((sum, index) => sum + signedCents(lines[index]), 0) !== 0) continue; for (const index of group) { bookings.push(lines[index]); consumed.add(index); } consumed.add(aggregateIndex); } const leftover = open(); if (leftover.length > 0) { const detail = leftover .map((index) => `line ${index + 1} (${lines[index].accountNumber} ${lines[index].side} ${lines[index].amountCents} against ${lines[index].counterAccount})`) .join(', '); throw new Error(`${draftLabel} cannot be written as DATEV bookings: ${detail} has no counter line`); } const ownAccount = bookings.find((line) => line.accountNumber === line.counterAccount); if (ownAccount !== undefined) { throw new Error( `${draftLabel} cannot be written as DATEV bookings: ${ownAccount.accountNumber} ${ownAccount.side} ${ownAccount.amountCents} is booked against its own account`, ); } return bookings; } /** * Convert journal drafts into DATEV rows: one row per booking after * consolidateJournalDraftForDatev, with the line's counterAccount as * Gegenkonto. A draft marked `generalumkehr` gives the rows of the booking it * reverses, with the same amounts and Soll/Haben marks, each with field 118 * set; one with a negative line is refused. */ export function journalDraftsToDatevRows( drafts: IJournalDraft[], options?: IDatevRowsOptions, ): IDatevBuchungsstapelRow[] { const rows: IDatevBuchungsstapelRow[] = []; for (const draft of drafts) { const policy = options?.policy ?? getDefaultPolicy(draft.skrType); for (const line of consolidateJournalDraftForDatev(draft, policy)) { // the Belegfelder as DATEV takes them, with the line's own Beleginfo, else, where the line takes the draft's // reference, the draft's; a text DATEV does not take mapped, the text kept as a Beleginfo const { belegfeld1, belegfeld2, belegInfo } = datevBelegfelderOf({ belegfeld1: line.belegfeld1 ?? draft.reference, belegfeld2: line.belegfeld2, belegInfo: line.belegInfo ?? (line.belegfeld1 === undefined ? draft.belegInfo : undefined), }); rows.push({ umsatzCents: line.amountCents, sollHaben: line.side === 'debit' ? 'S' : 'H', konto: line.accountNumber, gegenKonto: line.counterAccount, buSchluessel: line.buKey, belegDatum: draft.date, belegfeld1, belegfeld2, ...(belegInfo !== undefined ? { belegInfo: belegInfo.map((pair) => ({ ...pair })) } : {}), buchungstext: line.buchungstext || draft.description, belegLink: line.docLink, kost1: line.costCenter1, kost2: line.costCenter2, festschreibung: options?.festschreibung, ...(draft.generalumkehr === true ? { generalumkehr: true } : {}), }); } } return rows; } /** Field 20 links a document image: `BEDI "GUID"`, quotes doubled inside the CSV field. */ /** * Field 20 "Beleglink" as `BEDI "GUID"`, whatever form the link was given in: a line break or control character in it * written as a space, as in every other text field (`CONTROL_IN_TEXT`), so the row stays on its line. */ function formatBelegLink(value: string): string { const guid = value .replace(CONTROL_IN_TEXT, ' ') .trim() .replace(/^BEDI\s*/iu, '') .replace(/^"+|"+$/gu, '') .replace(/"/g, "'"); return `"BEDI ""${guid}"""`; } function rowToFields(row: IDatevBuchungsstapelRow): string[] { const fields = new Array(DATEV_COLUMN_COUNT).fill(''); fields[0] = formatAmount(row.umsatzCents); // 1 Umsatz fields[1] = quote(row.sollHaben); // 2 Soll/Haben-Kennzeichen fields[6] = row.konto; // 7 Konto fields[7] = row.gegenKonto; // 8 Gegenkonto if (row.buSchluessel !== '') fields[8] = quote(row.buSchluessel); // 9 BU-Schlüssel fields[9] = formatTtmm(row.belegDatum); // 10 Belegdatum // Belegfeld 1 and 2 as DATEV takes them, never cut: a text of other characters mapped (`datevBelegfelderOf`), the text // kept as a Beleginfo where the row states none; mapping what is mapped already changes nothing const belegfelder = datevBelegfelderOf({ belegfeld1: row.belegfeld1, belegfeld2: row.belegfeld2, belegInfo: row.belegInfo }); if (belegfelder.belegfeld1) fields[10] = quote(belegfelder.belegfeld1); // 11 Belegfeld 1 if (belegfelder.belegfeld2) fields[11] = quote(belegfelder.belegfeld2); // 12 Belegfeld 2 fields[13] = quote(row.buchungstext, DATEV_MAX_BUCHUNGSTEXT); // 14 Buchungstext if (row.belegLink) fields[19] = formatBelegLink(row.belegLink); // 20 Beleglink if (belegfelder.belegInfo !== undefined) { const fault = datevBelegInfoFault(belegfelder.belegInfo); if (fault) throw new Error(`Buchungsstapel fields 21 to 36: ${fault}`); belegfelder.belegInfo.forEach((pair, index) => { fields[20 + 2 * index] = quote(pair.art); // 21, 23 … 35 Beleginfo-Art fields[21 + 2 * index] = quote(pair.inhalt); // 22, 24 … 36 Beleginfo-Inhalt }); } if (row.kost1) fields[36] = quote(row.kost1); // 37 KOST1 if (row.kost2) fields[37] = quote(row.kost2); // 38 KOST2 if (row.festschreibung !== undefined) fields[113] = row.festschreibung ? '1' : '0'; // 114 if (row.leistungsdatum !== undefined) { if (row.datumZuordSteuerperiode === undefined) { throw new Error('DATEV field 115 Leistungsdatum needs field 116 Datum Zuord. Steuerperiode'); } fields[114] = formatTtmmjjjj(row.leistungsdatum, '115 Leistungsdatum'); // 115 } if (row.datumZuordSteuerperiode !== undefined) { fields[115] = formatTtmmjjjj(row.datumZuordSteuerperiode, '116 Datum Zuord. Steuerperiode'); // 116 } if (row.generalumkehr !== undefined) fields[117] = row.generalumkehr ? '"1"' : '"0"'; // 118 Generalumkehr if (row.euVatIdDestination !== undefined) { if (!EU_VAT_ID_DESTINATION.test(row.euVatIdDestination)) { throw new Error( `Buchungsstapel field 40 takes a country code and at most 13 characters of the VAT ID (at most 15 in all), got '${row.euVatIdDestination}'`, ); } fields[39] = quote(row.euVatIdDestination); // 40 EU-Mitgliedstaat u. UStID (Bestimmung) } return fields; } /** * The 125 fields of one Buchungsstapel row exactly as `writeExtfBuchungsstapel` * writes them, quoted and cut to their lengths, before they are joined with * `;`: the row's line in the file is `datevRowFields(row).join(';')`. What a * reader of one row needs to know without writing a whole file, for example * which of its characters an encoding of the file cannot carry. Throws as * the writer throws for a row it refuses. */ export function datevRowFields(row: IDatevBuchungsstapelRow): string[] { return rowToFields(row); } function buildHeaderLine(header: IDatevExtfHeaderOptions): string { const fields = new Array(DATEV_HEADER_FIELD_COUNT).fill(''); fields[0] = '"EXTF"'; fields[1] = '700'; fields[2] = '21'; fields[3] = '"Buchungsstapel"'; fields[4] = '13'; fields[5] = formatTimestamp(header.createdAt); fields[7] = quote(header.origin ?? 'SK'); fields[8] = quote(header.exportedBy ?? 'fin.cx/skr'); fields[10] = String(header.consultantNumber); fields[11] = String(header.clientNumber); fields[12] = formatYyyymmdd(header.fiscalYearStart); fields[13] = String(header.accountLength ?? 4); fields[14] = formatYyyymmdd(header.dateFrom); fields[15] = formatYyyymmdd(header.dateTo); fields[16] = quote(header.label, 30); fields[18] = '1'; // Buchungstyp: Finanzbuchführung fields[20] = header.festschreibung ? '1' : '0'; fields[21] = '"EUR"'; return fields.join(';'); } /** * Produce the complete EXTF file content (header, caption row, data rows). */ export function writeExtfBuchungsstapel( rows: IDatevBuchungsstapelRow[], header: IDatevExtfHeaderOptions, ): { csv: string; filename: string } { const lines: string[] = [ buildHeaderLine(header), DATEV_COLUMN_CAPTIONS.join(';'), ...rows.map((row) => rowToFields(row).join(';')), ]; const csv = lines.join('\r\n') + '\r\n'; const filename = `EXTF_Buchungsstapel_${formatYyyymmdd(header.dateFrom)}_${formatYyyymmdd(header.dateTo)}.csv`; return { csv, filename }; }