/** * Booking recipes of a main book beyond the documents and payments: the * opening balances (EB-Werte) of a fiscal year, the carry-forward of a closed * year into the next one, the owners' private withdrawals and deposits, and * the payment and refund of the VAT advance return. Pure builders, like * `core.recipes.ts`: (input, policy) => IJournalDraft, integer cents, no * chart lookups. */ import type { IJournalDraft, IJournalLineDraft, TCents } from './core.types.js'; import type { IAccountPolicy } from './core.accountpolicy.js'; import { isAutomatikAccount, isCreditorAccount, isDebtorAccount } from './core.accountpolicy.js'; import { RecipeRefusalError } from './core.errors.js'; import { chartOf } from './core.chart.js'; import { isVatMarkedAccount, vatCheckAccountOf } from './core.booksaccounts.js'; /** One opening balance: an account's balance, or one open item of a personal account. */ export interface IOpeningBalanceLine { accountNumber: string; /** debit positive, credit negative; 0 books nothing */ signedCents: TCents; /** a personal account's open item: its Belegfeld 1 (the invoice number); unset: the entry's reference */ belegfeld1?: string; /** the line's text; unset: the entry's description */ buchungstext?: string; } export interface IOpeningBalancesInput { /** the first day of the fiscal year */ date: Date; balances: IOpeningBalanceLine[]; description: string; reference?: string; /** the Beleg: the prior year's balance sheet, the Saldenliste or the Inventar */ docLink?: string; } /** A closing balance of the year that is carried forward. */ export interface IClosingBalance { accountNumber: string; /** debit positive, credit negative */ signedCents: TCents; /** * `balance_sheet`: carried as the account's opening balance; * `profit_and_loss`: not carried, it makes the year's result; * `private`: a sole trader's or a partner's private account, carried into the capital account. */ kind: 'balance_sheet' | 'profit_and_loss' | 'private'; /** a personal account's open items, whose balances sum to `signedCents`: each is carried by its Belegfeld 1 */ openItems?: Array<{ belegfeld1: string; signedCents: TCents }>; } /** Where the year's result and the private accounts go, by the legal form. */ export type TCarryForwardEquity = /** a company: the result to Gewinnvortrag or Verlustvortrag vor Verwendung (the policy's `resultCarryForward`); no private accounts */ | { kind: 'company' } /** a sole trader: the result and the private accounts to the capital account */ | { kind: 'sole_trader'; capitalAccount: string } /** * a partnership: each partner's share of the result, as the partnership * agreement or the law distributes it, and the partner's private accounts * to the partner's capital account */ | { kind: 'partnership'; partners: Array<{ capitalAccount: string; privateAccounts: string[]; resultShareCents: TCents }>; }; export interface ICarryForwardInput { /** the first day of the new fiscal year */ date: Date; /** every closing balance of the closed year, so that they sum to 0 */ closing: IClosingBalance[]; equity: TCarryForwardEquity; description: string; reference?: string; docLink?: string; } export interface IPrivateMovementInput { date: Date; /** positive */ amountCents: TCents; /** * the business account the money leaves or enters; unset: the policy's * bank. For a voucher the owner paid privately: the creditor's personal * account, with the invoice number as `reference`. */ account?: string; /** unset: the policy's `privateAccounts` */ privateAccount?: string; description: string; /** Belegfeld 1 of the lines */ reference?: string; docLink?: string; } export interface IVatPrepaymentInput { date: Date; /** `payment`: to the Finanzamt; `refund`: from it */ direction: 'payment' | 'refund'; /** positive */ amountCents: TCents; /** the Sondervorauszahlung for the Dauerfristverlängerung (1/11) instead of an advance return */ special?: boolean; bankAccount?: string; description: string; reference?: string; docLink?: string; } export interface IInventoryChangeInput { /** the Stichtag: the last day of the fiscal year the Inventar is made for */ date: Date; /** * the stock of goods the books carry before this entry: the balance of the * policy's `goods.stock` account, which is the stock the prior year's * Inventar valued (0 in the first year the books keep goods) */ bookedCents: TCents; /** the stock of goods on the Stichtag as the Inventar values it (§ 240 Abs. 2, § 253 Abs. 1 and 4 HGB) */ closingCents: TCents; description: string; /** Belegfeld 1 of the lines */ reference?: string; /** the Beleg: the Inventar */ docLink?: string; } /** A stock in cents: whole cents, not below 0. */ function requireStockValue(amountCents: TCents, label: 'bookedCents' | 'closingCents'): void { if (!Number.isSafeInteger(amountCents)) { throw new RecipeRefusalError('amount_not_whole_cents', `${label} must be a whole number of cents, got ${amountCents}`, { field: label, amountCents, }); } if (amountCents < 0) { throw new RecipeRefusalError('inventory_value_negative', `${label} is a stock of goods and cannot be below 0, got ${amountCents}`, { field: label, amountCents, }); } } /** * The change in the stock of goods at the year's end (Bestandsveränderung), * where the purchases of goods are booked as an expense (Wareneingang) and the * stock only at the year's end: the stock the Inventar values on the Stichtag * (`closingCents`) replaces the stock the books carry (`bookedCents`), and the * difference goes on the policy's `goods.stockChange` account, part of the * Materialaufwand (§ 275 Abs. 2 Nr. 5 HGB). A stock that grew: `goods.stock` * debit, `goods.stockChange` credit; one that shrank: the reverse. No VAT and * no BU key: a change in stock is no supply. The stock carries into the next * year with the carry-forward, and no entry reverses this one; the next year * books its own difference. Pure, like every recipe: whether the entry is * one of the year's closing entries is the caller's to decide. * * Refuses a policy without `goods` (`goods_accounts_missing`), a stock or * stock-change account with a DATEV tax automatism or marked for the UStVA * (`goods_account_not_allowed`), an amount that is no whole cents * (`amount_not_whole_cents`) or below 0 (`inventory_value_negative`), and a * stock that did not change (`inventory_unchanged`). */ export function bookInventoryChange(input: IInventoryChangeInput, policy: IAccountPolicy): IJournalDraft { const goods = policy.goods; if (!goods) { throw new RecipeRefusalError( 'goods_accounts_missing', `the policy of ${policy.skrType} names no accounts of goods (\`goods.stock\`, \`goods.stockChange\`), where the change in the stock of goods is booked`, { field: 'goods' }, ); } for (const role of ['stock', 'stockChange'] as const) { const account = goods[role]; if (isAutomatikAccount(policy, account) || isVatMarkedAccount(policy, account)) { throw new RecipeRefusalError( 'goods_account_not_allowed', `the policy's goods.${role} account ${account} has a DATEV tax automatism or is marked for the UStVA; a change in the stock of goods bears no VAT`, { field: `goods.${role}`, account }, ); } } requireStockValue(input.bookedCents, 'bookedCents'); requireStockValue(input.closingCents, 'closingCents'); const changeCents = input.closingCents - input.bookedCents; if (changeCents === 0) { throw new RecipeRefusalError( 'inventory_unchanged', `the stock of goods the Inventar values, ${input.closingCents} cents, is the stock the books carry: there is no change to book`, ); } const lines = changeCents > 0 ? pairOf(goods.stock, goods.stockChange, changeCents, input.description, input.reference, input.docLink) : pairOf(goods.stockChange, goods.stock, -changeCents, input.description, input.reference, input.docLink); return draftOf(input, policy, lines); } function requirePositive(amountCents: TCents, label: string): void { if (!Number.isSafeInteger(amountCents) || amountCents <= 0) { throw new RecipeRefusalError('amount_not_positive', `${label} must be a positive integer cent amount, got ${amountCents}`, { field: label, amountCents, }); } } function draftOf( base: { date: Date; description: string; reference?: string; docLink?: string }, policy: IAccountPolicy, lines: IJournalLineDraft[], ): IJournalDraft { return { date: base.date, description: base.description, ...(base.reference !== undefined ? { reference: base.reference } : {}), skrType: chartOf(policy), currency: 'EUR', lines, }; } /** A booking of `amountCents` on `debit` against `credit`, as its two lines. */ function pairOf( debit: string, credit: string, amountCents: TCents, text: string, belegfeld1: string | undefined, docLink: string | undefined, ): IJournalLineDraft[] { const common = { amountCents, buKey: '' as const, buchungstext: text, ...(belegfeld1 !== undefined ? { belegfeld1 } : {}), ...(docLink !== undefined ? { docLink } : {}), }; return [ { accountNumber: debit, counterAccount: credit, side: 'debit', ...common }, { accountNumber: credit, counterAccount: debit, side: 'credit', ...common }, ]; } /** * The opening balances (EB-Werte) of a fiscal year, as one entry: each * balance on its account against the Saldenvortragskonto — a debtor's against * `openingBalance.debtors`, a creditor's against `.creditors`, every other * against `.generalLedger` — so that the opening balances of all accounts * together leave the three at 0. A personal account is best opened per open * item, each with its invoice number as Belegfeld 1, so its open items and * their later settlement work. Refuses no balance at all, an amount that is * not whole cents, the same account (or open item) twice, a control account * (open the personal accounts) and a Saldenvortragskonto itself. */ export function bookOpeningBalances(input: IOpeningBalancesInput, policy: IAccountPolicy): IJournalDraft { const vortrag = policy.openingBalance; const vortragAccounts = [vortrag.generalLedger, vortrag.debtors, vortrag.creditors]; const seen = new Set(); const lines: IJournalLineDraft[] = []; for (const balance of input.balances) { if (!Number.isSafeInteger(balance.signedCents)) { throw new RecipeRefusalError( 'amount_not_whole_cents', `the opening balance of ${balance.accountNumber} is not a whole number of cents: ${balance.signedCents}`, { field: 'balances.signedCents', account: balance.accountNumber, amountCents: balance.signedCents }, ); } if (vortragAccounts.includes(balance.accountNumber)) { throw new RecipeRefusalError( 'opening_balance_account_not_allowed', `${balance.accountNumber} is a Saldenvortragskonto: it is the counter account of the opening balances, not one of them`, { account: balance.accountNumber }, ); } if (balance.accountNumber === policy.debtorsControl || balance.accountNumber === policy.creditorsControl) { throw new RecipeRefusalError( 'opening_balance_account_not_allowed', `${balance.accountNumber} is a control account: open the balances of the personal accounts instead`, { account: balance.accountNumber }, ); } const key = `${balance.accountNumber}\u0000${balance.belegfeld1 ?? ''}`; if (seen.has(key)) { throw new RecipeRefusalError( 'opening_balance_duplicate', `the opening balance of ${balance.accountNumber}${balance.belegfeld1 ? ` (${balance.belegfeld1})` : ''} is given twice`, { account: balance.accountNumber }, ); } seen.add(key); if (balance.signedCents === 0) continue; const counter = isDebtorAccount(policy, balance.accountNumber) ? vortrag.debtors : isCreditorAccount(policy, balance.accountNumber) ? vortrag.creditors : vortrag.generalLedger; const amount = Math.abs(balance.signedCents); const text = balance.buchungstext ?? input.description; const belegfeld1 = balance.belegfeld1 ?? input.reference; const [debitLine, creditLine] = balance.signedCents > 0 ? pairOf(balance.accountNumber, counter, amount, text, belegfeld1, input.docLink) : pairOf(counter, balance.accountNumber, amount, text, belegfeld1, input.docLink); // the account's line first, then its Saldenvortragskonto lines.push(...(balance.signedCents > 0 ? [debitLine, creditLine] : [creditLine, debitLine])); } if (lines.length === 0) { throw new RecipeRefusalError('opening_balances_empty', 'there is no balance to open: every opening balance is 0 or none was given'); } return draftOf(input, policy, lines); } /** * The accounts of a year's German VAT in a policy: the output and input tax at * each rate, the paired tax of intra-Community acquisitions and of § 13b UStG, * and the advance return's prepayments and Sondervorauszahlung. Not the VAT * owed to another member state (`vat.otherEuState*`), which is no German tax. */ export function germanVatAccountsOf(policy: IAccountPolicy): string[] { const { vat, vatSettlement } = policy; return [ vat.outputStandard, vat.outputReduced, vat.inputStandard, vat.inputReduced, vat.intraEuAcqInput, vat.intraEuAcqOutput, vat.reverseChargeInput, vat.reverseChargeOutput, vatSettlement.prepayment, vatSettlement.specialPrepayment, ]; } /** * A closed year's closing balances with its VAT reclassified for the * carry-forward (`carryForwardOf`): the balances of the year's German VAT * accounts (`vatAccounts`, default `germanVatAccountsOf`) open together on the * previous year's VAT account (`vatSettlement.previousYear`: SKR 03 1790, * SKR 04 3841), and that account's old balance, what was left of the year * before, on the earlier years' account (`vatSettlement.earlierYears`: SKR 03 * 1791, SKR 04 3845), which keeps its own. So the new year's advance returns * start from accounts that hold only their own year's tax, and what a year * owes or is owed stays apart until it is settled. No entry of the closed year * books it: the carry-forward opens the balances there. The balances still sum * as before; accounts left at 0 are not given. * * An individual account of the books under one of the year's VAT accounts * (`IAccountPolicy.individualAccounts`, such as SKR 04 3821 under the * prepayments' 3820) is moved as its parent is, unless its declaration * changes its UStVA mapping: then it stands for itself, as in the VAT checks * (`vatCheckAccountOf`), and is moved only where `vatAccounts` names it. * An individual account under `previousYear` or `earlierYears` itself (SKR 04 * 3842 under 3841, 3846 under 3845) stays on its own number: it holds what the * business keeps apart, such as a year under audit or in dispute, and moving * it is a booking of the new year. * * Refuses a policy without the two accounts (`vat_year_accounts_missing`) and * a VAT account given per open item (`vat_account_per_open_item`). */ export function vatOfPastYearsReclassified( closing: IClosingBalance[], policy: IAccountPolicy, options?: { vatAccounts?: readonly string[] }, ): IClosingBalance[] { const { previousYear, earlierYears } = policy.vatSettlement; if (!previousYear || !earlierYears) { throw new RecipeRefusalError( 'vat_year_accounts_missing', `the policy of ${policy.skrType} names no accounts of the VAT of past years (\`vatSettlement.previousYear\`, \`vatSettlement.earlierYears\`)`, ); } const vatAccounts = new Set((options?.vatAccounts ?? germanVatAccountsOf(policy)).filter((accountArg) => accountArg !== previousYear && accountArg !== earlierYears)); let toPreviousYear = 0; let toEarlierYears = 0; const kept: IClosingBalance[] = []; for (const balance of closing) { const moved = balance.kind === 'balance_sheet' && (vatAccounts.has(balance.accountNumber) || vatAccounts.has(vatCheckAccountOf(policy, balance.accountNumber)) || balance.accountNumber === previousYear || balance.accountNumber === earlierYears); if (!moved) { kept.push(balance); continue; } if (balance.openItems !== undefined) { throw new RecipeRefusalError( 'vat_account_per_open_item', `${balance.accountNumber} is carried whole as the VAT of past years and cannot be given per open item`, { account: balance.accountNumber }, ); } if (balance.accountNumber === previousYear || balance.accountNumber === earlierYears) { toEarlierYears += balance.signedCents; } else { toPreviousYear += balance.signedCents; } } return [ ...kept, ...(toPreviousYear !== 0 ? [{ accountNumber: previousYear, signedCents: toPreviousYear, kind: 'balance_sheet' as const }] : []), ...(toEarlierYears !== 0 ? [{ accountNumber: earlierYears, signedCents: toEarlierYears, kind: 'balance_sheet' as const }] : []), ]; } /** * The carry-forward (Saldovortrag) of a closed year: the opening balances of * the next year, dated its first day (§ 252 Abs. 1 Nr. 1 HGB: "Die Wertansätze * in der Eröffnungsbilanz des Geschäftsjahrs müssen mit denen der * Schlußbilanz des vorhergehenden Geschäftsjahrs übereinstimmen"). The * balance-sheet accounts carry their closing balances, a personal account per * open item where they are given. The profit-and-loss accounts are not * carried: their sum, the year's result, goes to equity by the legal form — * a company's to Gewinnvortrag or Verlustvortrag vor Verwendung, a sole * trader's to the capital account together with the private accounts, a * partnership's by the partners' shares to their capital accounts together * with each partner's private accounts. An account that also carries a * balance of its own gets one line with both. * * Refuses closing balances that do not sum to 0 (the year's books are not * complete or not balanced), open items that do not sum to their account, a * Saldenvortragskonto with a balance (the year's own opening balances did not * balance), private accounts of a company, a private account no partner * holds, and partners' shares that do not sum to the result. */ export function carryForwardOf(input: ICarryForwardInput, policy: IAccountPolicy): IJournalDraft { const vortrag = policy.openingBalance; const vortragAccounts = [vortrag.generalLedger, vortrag.debtors, vortrag.creditors]; let total = 0; let pnl = 0; for (const balance of input.closing) { if (!Number.isSafeInteger(balance.signedCents)) { throw new RecipeRefusalError( 'amount_not_whole_cents', `the closing balance of ${balance.accountNumber} is not a whole number of cents: ${balance.signedCents}`, { field: 'closing.signedCents', account: balance.accountNumber, amountCents: balance.signedCents }, ); } total += balance.signedCents; if (balance.kind === 'profit_and_loss') pnl += balance.signedCents; if (vortragAccounts.includes(balance.accountNumber) && balance.signedCents !== 0) { throw new RecipeRefusalError( 'saldenvortrag_not_cleared', `the Saldenvortragskonto ${balance.accountNumber} closes at ${balance.signedCents} cents: the year's opening balances did not balance`, { account: balance.accountNumber, amountCents: balance.signedCents }, ); } } if (total !== 0) { throw new RecipeRefusalError('closing_balances_unbalanced', `the closing balances do not balance: they sum to ${total} cents, not 0`, { differenceCents: total, }); } // the result: a profit is a credit balance of the profit-and-loss accounts const resultSigned = pnl; // what goes onto an equity account on top of its own balance, debit positive const toEquity = new Map(); const addTo = (accountArg: string, centsArg: number): void => { toEquity.set(accountArg, (toEquity.get(accountArg) ?? 0) + centsArg); }; const privates = input.closing.filter((balanceArg) => balanceArg.kind === 'private'); const equity = input.equity; if (equity.kind === 'company') { if (privates.length > 0) { const accounts = privates.map((balanceArg) => balanceArg.accountNumber); throw new RecipeRefusalError('private_accounts_of_company', `a company has no private accounts, but ${accounts.join(', ')} are given as private`, { accounts, }); } if (resultSigned !== 0) { addTo(resultSigned < 0 ? policy.resultCarryForward.profit : policy.resultCarryForward.loss, resultSigned); } } else if (equity.kind === 'sole_trader') { addTo(equity.capitalAccount, resultSigned); for (const balance of privates) addTo(equity.capitalAccount, balance.signedCents); } else { const shares = equity.partners.reduce((sumArg, partnerArg) => sumArg + partnerArg.resultShareCents, 0); // a share is positive for a profit, as the result is if (!equity.partners.every((partnerArg) => Number.isSafeInteger(partnerArg.resultShareCents)) || shares !== -resultSigned) { throw new RecipeRefusalError( 'partner_shares_mismatch', `the partners' shares sum to ${shares} cents, the year's result is ${-resultSigned} cents`, { differenceCents: shares + resultSigned }, ); } for (const balance of privates) { const holder = equity.partners.find((partnerArg) => partnerArg.privateAccounts.includes(balance.accountNumber)); if (!holder) { throw new RecipeRefusalError('private_account_without_partner', `the private account ${balance.accountNumber} belongs to no partner`, { account: balance.accountNumber, }); } addTo(holder.capitalAccount, balance.signedCents); } for (const partner of equity.partners) addTo(partner.capitalAccount, -partner.resultShareCents); } const balances: IOpeningBalanceLine[] = []; for (const balance of input.closing) { if (balance.kind !== 'balance_sheet' || vortragAccounts.includes(balance.accountNumber)) continue; const extra = toEquity.get(balance.accountNumber); if (extra !== undefined) { if (balance.openItems !== undefined) { throw new RecipeRefusalError( 'result_account_per_open_item', `${balance.accountNumber} takes the result and cannot be carried per open item`, { account: balance.accountNumber }, ); } balances.push({ accountNumber: balance.accountNumber, signedCents: balance.signedCents + extra }); toEquity.delete(balance.accountNumber); continue; } if (balance.openItems !== undefined) { const itemsSum = balance.openItems.reduce((sumArg, itemArg) => sumArg + itemArg.signedCents, 0); if (itemsSum !== balance.signedCents) { throw new RecipeRefusalError( 'open_items_mismatch', `the open items of ${balance.accountNumber} sum to ${itemsSum} cents, its balance is ${balance.signedCents} cents`, { account: balance.accountNumber, differenceCents: itemsSum - balance.signedCents }, ); } for (const item of balance.openItems) { balances.push({ accountNumber: balance.accountNumber, signedCents: item.signedCents, belegfeld1: item.belegfeld1 }); } continue; } balances.push({ accountNumber: balance.accountNumber, signedCents: balance.signedCents }); } for (const [account, cents] of toEquity) balances.push({ accountNumber: account, signedCents: cents }); return bookOpeningBalances( { date: input.date, balances, description: input.description, ...(input.reference !== undefined ? { reference: input.reference } : {}), ...(input.docLink !== undefined ? { docLink: input.docLink } : {}), }, policy, ); } /** * A private withdrawal (Privatentnahme): the private account debit, the * business account credit. For a sole trader or a partner; a company has no * private accounts. */ export function bookPrivateWithdrawal(input: IPrivateMovementInput, policy: IAccountPolicy): IJournalDraft { requirePositive(input.amountCents, 'amountCents'); const privateAccount = input.privateAccount ?? policy.privateAccounts.withdrawal; const account = input.account ?? policy.bank; return draftOf(input, policy, pairOf(privateAccount, account, input.amountCents, input.description, input.reference, input.docLink)); } /** * A private deposit (Privateinlage): the business account debit, the private * account credit. A voucher the owner paid privately is a deposit into the * creditor's personal account: with the invoice number as `reference` it * settles the invoice's open item. */ export function bookPrivateDeposit(input: IPrivateMovementInput, policy: IAccountPolicy): IJournalDraft { requirePositive(input.amountCents, 'amountCents'); const privateAccount = input.privateAccount ?? policy.privateAccounts.deposit; const account = input.account ?? policy.bank; return draftOf(input, policy, pairOf(account, privateAccount, input.amountCents, input.description, input.reference, input.docLink)); } /** * The accounts a draft books on that the chart in use does not have, in the * order the draft first names them. A booking on an account the chart lacks * would be a booking on no account. */ export function missingChartAccountsOf(draft: IJournalDraft, chartAccounts: readonly string[]): string[] { const chart = new Set(chartAccounts); const missing: string[] = []; for (const line of draft.lines) { for (const account of [line.accountNumber, line.counterAccount]) { if (!chart.has(account) && !missing.includes(account)) missing.push(account); } } return missing; } /** * The payment of a VAT advance return to the Finanzamt, or its refund, on * the Umsatzsteuer-Vorauszahlungen account against the bank; with `special` * the Sondervorauszahlung of the Dauerfristverlängerung on its own account. * The VAT accounts themselves are not touched. * * `chartAccounts` are the account numbers of the chart in use. The recipe * refuses, naming them, when it lacks the prepayment account or the bank * account. skr's own charts (from `@fin.cx/chartdata` 2.5) hold SKR 03 * 1780/1781 and SKR 04 3820/3830. */ export function bookVatPrepayment(input: IVatPrepaymentInput, policy: IAccountPolicy, chartAccounts: readonly string[]): IJournalDraft { requirePositive(input.amountCents, 'amountCents'); const prepayment = input.special === true ? policy.vatSettlement.specialPrepayment : policy.vatSettlement.prepayment; const bank = input.bankAccount ?? policy.bank; const lines = input.direction === 'payment' ? pairOf(prepayment, bank, input.amountCents, input.description, input.reference, input.docLink) : pairOf(bank, prepayment, input.amountCents, input.description, input.reference, input.docLink); const draft = draftOf(input, policy, lines); const missing = missingChartAccountsOf(draft, chartAccounts); if (missing.length > 0) { const roleOf = (accountArg: string): string => accountArg === prepayment ? (input.special === true ? 'Umsatzsteuer-Vorauszahlungen 1/11' : 'Umsatzsteuer-Vorauszahlungen') : 'bank'; throw new RecipeRefusalError( 'chart_account_missing', `the chart in use (${policy.skrType}) has no account ${missing.map((accountArg) => `${accountArg} (${roleOf(accountArg)})`).join(', ')}: add it to the chart before booking the VAT prepayment`, { accounts: missing }, ); } return draft; }