/** * The Einnahmenüberschussrechnung (§ 4 Abs. 3 EStG) as a pure function over * journal entries, beside the trial balance and the account sheet: what a * period's bookings come to on each line of the Anlage EÜR (§ 60 Abs. 4 * EStDV). The caller hands in the entries, as for `trialBalanceOf`; nothing * is stored or read. Which line an account's movements go to, and why an * account is no part of the form, is `@fin.cx/chartdata`'s (`euer`, * `euerExclusion`, `ANLAGE_EUER_FORMS`), generated into `core.euerdata.ts`; * an individual account of the books (`IAccountPolicy.individualAccounts`) * goes where its declaration puts it, its parent's line unless it changes it. * An excluded account's movements are on no line; those of an `out_of_period` * account, which a cash-basis book cannot have, are listed in `unmapped`. * * The form counts the period's movements: the lines of opening entries (the * EB-Werte) are left out, as are the lines before and after the period. A * Generalumkehr line counts negative on its side, so an entry and its * reversal leave nothing. When a payment counts (the ten-day rule of § 11 * Abs. 1 Satz 2 and Abs. 2 Satz 2 EStG for VAT refunds and prepayments) is * the posting date's: a host that applies it posts such a payment on the * prior year's last day. */ import { isCreditorAccount, isDebtorAccount, type IAccountPolicy } from './core.accountpolicy.js'; import { individualAccountsOf } from './core.booksaccounts.js'; import { CHART_EUER, EUER_FORMS } from './core.euerdata.js'; import { ledgerLinesOf, ledgerPeriodOf, type ILedgerEntryInput, type ILedgerPeriodOptions } from './core.ledger.js'; /** * The part of the Anlage EÜR a line belongs to: Betriebseinnahmen, * Betriebsausgaben, or the private Entnahmen and Einlagen of a sole * proprietor (2026 Zeilen 107 and 108). */ export type TEuerSection = 'income' | 'expense' | 'private'; /** One line of the Anlage EÜR of a form year (chartdata `IEuerFormLine`). */ export interface IEuerFormLine { /** unique among the lines of a form year's table */ kennzahl: number; /** the line ("Zeile") on the year's form */ line: number; label: string; section: TEuerSection; /** how the line enters its section's sum: 1 adds, -1 subtracts, 0 not at all ("davon", "nicht abziehbar", the Entnahmen and Einlagen) */ sign: 1 | -1 | 0; /** the side whose movements the line counts, net of the other */ side: 'debit' | 'credit'; } /** The lines of the Anlage EÜR of one form year. */ export interface IEuerForm { year: number; lines: IEuerFormLine[]; } /** Why an account's movements are no part of the Anlage EÜR (chartdata `TEuerExclusion`). */ export type TEuerExclusion = | 'balance_sheet' | 'fixed_asset' | 'inventory' | 'valuation' | 'pass_through' | 'reverse_charge' | 'closing' /** an earlier year's income or expense booked after that year is closed (periodenfremd), a category a cash-basis book does not have: `euerOf` lists it in `unmapped`, and the host refuses or moves the amount */ | 'out_of_period' | 'deferred_current_asset'; /** * Where a chart's account goes: one line, both sides netted toward its side * (`kennzahl`); a line per side (`debitKennzahl`, `creditKennzahl`: the VAT * paid to and refunded by the tax office); or no line, and why (`exclusion`). */ export type TEuerChartEntry = | { kennzahl: number } | { debitKennzahl: number; creditKennzahl: number } | { exclusion: TEuerExclusion }; /** * The Kennzahl of a Kleinunternehmer's receipts (§ 19 Abs. 1 UStG, Zeile 12): * with `smallBusiness` the taxable (Kz 112) and the tax-free or non-taxable * receipts (Kz 103) go there. The "davon" of Zeile 13 (Kz 119) is no * account's: an account does not tell which of its receipts fall under it. */ export const EUER_SMALL_BUSINESS_KENNZAHL = 111; export interface IEuerOptions extends ILedgerPeriodOptions { /** * The chart in use (`policy.skrType`), the books' individual accounts * (`individualAccounts`) and the personal accounts (`debtorRange`, * `creditorRange`): a debtor's or a creditor's account is a claim or a * debt, no part of the form. */ policy: IAccountPolicy; /** the form year whose lines the figures stand on; one of `listEuerFormYears()` */ formYear: number; /** the business is a Kleinunternehmer (§ 19 Abs. 1 UStG): its receipts go to Kz 111 */ smallBusiness?: boolean; } /** One line of the Anlage EÜR with what the period's bookings come to on it. */ export interface IEuerFigure extends IEuerFormLine { /** integer cents, toward the line's side; negative where the other side outweighs (credit notes over sales) */ cents: number; /** the accounts whose movements make the line, in account order, each with its share in cents */ accounts: Array<{ accountNumber: string; cents: number }>; } /** An account with movements in the period that the form leaves out for no reason a cash-basis book can have (see `IEuer.unmapped`); no personal account. */ export interface IEuerUnmappedAccount { accountNumber: string; debitCents: number; creditCents: number; } /** What a period's bookings come to on the Anlage EÜR of a form year. */ export interface IEuer { formYear: number; periodFrom?: string; periodTo?: string; /** every line of the form year, in the form's order, with its amount (0 where nothing goes to it) */ lines: IEuerFigure[]; /** the Summe der Betriebseinnahmen (2026 Zeile 23): the receipts' lines by their sign */ incomeCents: number; /** the Summe der Betriebsausgaben (2026 Zeile 76): the expenses' lines by their sign */ expenseCents: number; /** income less expenses (2026 Zeilen 77 and 78), before the corrections of Zeilen 79 ff. */ resultCents: number; /** * Accounts with movements in the period that are on no line of the form * for no reason a cash-basis book can have: the chart neither maps nor * excludes them, or excludes them as `out_of_period` (periodenfremd, which * § 4 Abs. 3 with § 11 EStG does not know), and they are no personal * account. A host must not state the form while any is listed; it refuses * or moves such an amount. */ unmapped: IEuerUnmappedAccount[]; } /** The form years the core holds the Anlage EÜR of, ascending. */ export function listEuerFormYears(): number[] { return EUER_FORMS.map((formArg) => formArg.year); } /** The Anlage EÜR of a form year; throws for a year the core does not hold. */ export function getEuerForm(yearArg: number): IEuerForm { const form = EUER_FORMS.find((candidateArg) => candidateArg.year === yearArg); if (!form) { throw new Error(`No Anlage EÜR for ${yearArg}. Available: ${listEuerFormYears().join(', ')}`); } return form; } const DIGITS = /^\d+$/u; const byAccount = (leftArg: string, rightArg: string): number => DIGITS.test(leftArg) && DIGITS.test(rightArg) ? Number(leftArg) - Number(rightArg) || leftArg.localeCompare(rightArg) : leftArg.localeCompare(rightArg); /** * What the period's bookings come to on each line of the Anlage EÜR of a * form year (see the module's notes): per account the period's debits and * credits without the opening entries, on the account's line toward its side * or on a line per side, then the sections' sums. Refuses what * `ledgerLinesOf` refuses, a form year the core does not hold and a period * that is no period. */ export function euerOf(entries: readonly ILedgerEntryInput[], options: IEuerOptions): IEuer { const form = getEuerForm(options.formYear); const chart: Record = { ...CHART_EUER[options.policy.skrType] }; for (const [accountNumber, account] of individualAccountsOf(options.policy)) { // chartdata gives every account a line or an exclusion; an individual account takes its parent's or its own if (account.euer !== undefined) chart[accountNumber] = account.euer; else if (account.euerExclusion !== undefined) chart[accountNumber] = { exclusion: account.euerExclusion }; } const { from, to } = ledgerPeriodOf(options); // the period's debits and credits per account, without the opening entries const sums = new Map(); for (const line of ledgerLinesOf(entries)) { if (line.opening || (from !== undefined && line.date < from) || (to !== undefined && line.date > to)) { continue; } const sum = sums.get(line.accountNumber) ?? { debitCents: 0, creditCents: 0 }; const turnover = line.generalumkehr ? -line.amountCents : line.amountCents; if (line.side === 'debit') sum.debitCents += turnover; else sum.creditCents += turnover; sums.set(line.accountNumber, sum); } const figures = new Map(form.lines.map((lineArg) => [lineArg.kennzahl, { ...lineArg, cents: 0, accounts: [] }])); const add = (kennzahlArg: number, accountArg: string, sideArg: 'debit' | 'credit' | 'netted', debitArg: number, creditArg: number): void => { const kennzahl = options.smallBusiness && (kennzahlArg === 112 || kennzahlArg === 103) ? EUER_SMALL_BUSINESS_KENNZAHL : kennzahlArg; const figure = figures.get(kennzahl); if (!figure) { throw new Error(`account ${accountArg} goes to Kz ${kennzahl}, which the Anlage EÜR ${form.year} has no line of`); } const cents = sideArg === 'debit' ? debitArg : sideArg === 'credit' ? creditArg : figure.side === 'credit' ? creditArg - debitArg : debitArg - creditArg; if (cents === 0) return; figure.cents += cents; figure.accounts.push({ accountNumber: accountArg, cents }); }; const unmapped: IEuerUnmappedAccount[] = []; for (const accountNumber of [...sums.keys()].sort(byAccount)) { const { debitCents, creditCents } = sums.get(accountNumber)!; const entry = chart[accountNumber]; if (entry === undefined) { if (!isDebtorAccount(options.policy, accountNumber) && !isCreditorAccount(options.policy, accountNumber) && (debitCents !== 0 || creditCents !== 0)) { unmapped.push({ accountNumber, debitCents, creditCents }); } continue; } if ('exclusion' in entry) { // a cash-basis book has no periodenfremd category: such an amount is listed, the other exclusions stay off the form if (entry.exclusion === 'out_of_period' && (debitCents !== 0 || creditCents !== 0)) { unmapped.push({ accountNumber, debitCents, creditCents }); } continue; } if ('kennzahl' in entry) add(entry.kennzahl, accountNumber, 'netted', debitCents, creditCents); else if ('debitKennzahl' in entry) { add(entry.debitKennzahl, accountNumber, 'debit', debitCents, creditCents); add(entry.creditKennzahl, accountNumber, 'credit', debitCents, creditCents); } } const lines = form.lines.map((lineArg) => figures.get(lineArg.kennzahl)!); const sectionSum = (sectionArg: TEuerSection): number => lines.filter((lineArg) => lineArg.section === sectionArg).reduce((sumArg, lineArg) => sumArg + lineArg.sign * lineArg.cents, 0); const incomeCents = sectionSum('income'); const expenseCents = sectionSum('expense'); return { formYear: form.year, ...(from !== undefined ? { periodFrom: from } : {}), ...(to !== undefined ? { periodTo: to } : {}), lines, incomeCents, expenseCents, resultCents: incomeCents - expenseCents, unmapped, }; } const ISO_DAY = /^(\d{4})-(\d{2})-(\d{2})$/u; /** The last day of February of a year: the 29th in a leap year, else the 28th. */ const lastOfFebruary = (yearArg: number): string => (new Date(Date.UTC(yearArg, 1, 29)).getUTCMonth() === 1 ? '29' : '28'); /** * A day one year earlier. The last day of February stays the last day of * February (`2028-02-29` → `2027-02-28`, `2029-02-28` → `2028-02-29`), so a * period that ends with the month ends with it a year earlier too. */ const yearEarlier = (dayArg: string): string => { const match = ISO_DAY.exec(dayArg); if (!match || new Date(`${dayArg}T00:00:00.000Z`).toISOString().slice(0, 10) !== dayArg) { throw new Error(`${dayArg} is no day as YYYY-MM-DD`); } const yearNumber = Number(match[1]); const year = String(yearNumber - 1).padStart(4, '0'); const day = match[2] === '02' && match[3] === lastOfFebruary(yearNumber) ? lastOfFebruary(yearNumber - 1) : match[3]; return `${year}-${match[2]}-${day}`; }; /** * The same days a year earlier, the period a figure is compared with * (`01.01.–30.09.2026` → `01.01.–30.09.2025`); a period that ends with * February ends with February a year earlier, its 28th or its 29th. A host reads the prior * year's entries and calls `euerOf` for this period on the current form year: * the Kennzahlen are the same from year to year, so the lines compare. */ export function priorYearPeriodOf(periodArg: { periodFrom: string; periodTo: string }): { periodFrom: string; periodTo: string } { return { periodFrom: yearEarlier(periodArg.periodFrom), periodTo: yearEarlier(periodArg.periodTo) }; } /** A line of the Anlage EÜR with the period's amount and the prior year's. */ export interface IEuerComparisonLine extends IEuerFigure { /** the same line's amount in the prior year's period; `null` where there are no prior-year figures */ previousCents: number | null; } /** The current figures and the prior year's, line by line (by Kennzahl), with the sums of both. */ export interface IEuerComparison { current: IEuer; previous: IEuer | null; lines: IEuerComparisonLine[]; } /** * The current figures beside the prior year's, by Kennzahl: `previous` is * `euerOf` over the prior year's entries for `priorYearPeriodOf` the current * period, or `null` where the books hold no prior year. Refuses two figures * of different form years, whose lines would not line up. */ export function euerComparisonOf(current: IEuer, previous: IEuer | null): IEuerComparison { if (previous !== null && previous.formYear !== current.formYear) { throw new Error(`the prior year's figures stand on the ${previous.formYear} form, the current ones on the ${current.formYear} form: compute both on the current form year`); } const prior = new Map((previous?.lines ?? []).map((lineArg) => [lineArg.kennzahl, lineArg.cents])); return { current, previous, lines: current.lines.map((lineArg) => ({ ...lineArg, previousCents: previous === null ? null : prior.get(lineArg.kennzahl) ?? 0 })), }; }