/** * Booking recipes — pure builders: (input, policy) => IJournalDraft. * No persistence, no chart lookups; amounts are integer cents and every * fractional computation goes through @fin.cx/calculation. */ import * as plugins from './core.plugins.js'; import type { IJournalDraft, TOtherEuStateSupply, TPlaceOfSupply, IJournalLineDraft, TBuKey, TCents, TTaxScenario, TReverseChargeParagraph, TSKRType, } from './core.types.js'; import { REVERSE_CHARGE_PARAGRAPHS } from './core.types.js'; import type { IAccountPolicy } from './core.accountpolicy.js'; import { isAutomatikAccount, isCreditorAccount, isDebtorAccount, paymentFeesAccount, SHAREHOLDER_CLAIM_ACCOUNTS, SHAREHOLDER_CLAIM_FORMS, type TShareholderClaimForm } from './core.accountpolicy.js'; import { isReverseChargeBuKey, suggestBuKey } from './core.bukeys.js'; import { RecipeRefusalError, type IRecipeRefusalDetails } from './core.errors.js'; import { chartOf } from './core.chart.js'; import { accountRateMismatchOf, STATED_VAT_TOLERANCE_CENTS } from './core.accountrate.js'; import { isProfitAndLossAccount, isVatMarkedAccount, vatCheckAccountOf } from './core.booksaccounts.js'; import { CHART_AUTOMATIK_ACCOUNTS, CHART_VAT_ACCOUNTS, CHART_ZERO_RATE_REVENUE_ACCOUNTS } from './core.chartaccounts.js'; const { allocateCents, splitGrossCents, vatFromNetCents } = plugins.calculation; export interface IVendorInvoiceInput { date: Date; /** creditor personal account (70000-99999) */ vendorAccount: string; expenseAccount?: string; /** invoice total that becomes payable (for §13b / igE this equals net) */ grossCents: TCents; vatRatePercent?: number; scenario?: TTaxScenario; invoiceNumber?: string; /** * The part of the German tax that is excluded from the input-tax deduction * (§ 15 Abs. 2 and 4 UStG), POSITIVE integer cents, at most the tax: all of * it for a purchase used for tax-exempt sales, such as every purchase of a * Kleinunternehmer (§ 19 Abs. 1 UStG, § 15 Abs. 2 Satz 1 Nr. 1 UStG), a * part where a purchase is used for both. It is cost: booked with the base on * the expense account, and only the rest on the input-tax account. Under § * 13b and an intra-Community acquisition the base keeps the scenario's key, * so the tax is owed and deducted in full where the key declares it, and * the part excluded is taken back from the input tax as a booking of its * own without a key: Dr the expense account, Cr the scenario's input-tax * account. Absent or 0: the whole tax is deducted. Refused * beyond the tax, on a scenario without German VAT, and on an expense * account whose DATEV automatism books input tax at a rate * (`non_deductible_vat_invalid`, `automatik_account_not_allowed`). */ nonDeductibleVatCents?: TCents; /** * Under § 13b UStG (`reverse_charge_13b`): the paragraph the purchase falls * under (`TReverseChargeParagraph`), stamped on the base line with the key * of the scenario (`IJournalLineDraft.reverseChargeParagraph`), which * places the base in the UStVA (Kz 46, 73 or 84). A base whose tax is * booked as stated (`vatCents`) carries no key, so the paragraph is not * stamped there. Refused on another scenario * (`reverse_charge_paragraph_invalid`). */ reverseChargeParagraph?: TReverseChargeParagraph; description: string; costCenter1?: string; docLink?: string; } export interface ICustomerInvoiceInput { date: Date; /** debtor personal account (10000-69999) */ customerAccount: string; revenueAccount?: string; grossCents: TCents; vatRatePercent?: number; scenario?: TTaxScenario; /** `other_eu_state_taxable` only, and required there: what the sale supplies */ otherEuStateSupply?: TOtherEuStateSupply; /** `not_taxable_here` only, and required there: where the sale has its place */ placeOfSupply?: TPlaceOfSupply; invoiceNumber?: string; description: string; costCenter1?: string; docLink?: string; } /** The invoice a correction document corrects (§ 31 Abs. 5 UStDV). */ export interface ICorrectedInvoiceReference { /** the corrected invoice's number (§ 14 Abs. 4 Satz 1 Nr. 4 UStG) */ invoiceNumber: string; /** its issue date; when given, the credit note may not predate it */ date?: Date; } export interface ICustomerCreditNoteInput { /** * Date of the entry, the Belegdatum. This date decides the * Besteuerungszeitraum of the correction: § 17 Abs. 1 Satz 8 UStG corrects * the tax in the period in which the change of the tax base occurred, never * in the period of the corrected invoice. It is the credit note's own date, * unless the caller books the correction on another day (`issueDate`), which * is the caller's decision: for example books that date every row by the * payment or the settlement that books it. */ date: Date; /** * The credit note's own date, where the caller books it on another day * (`date`). A correction may not predate the invoice it corrects; that is read * from this date, from `date` where absent. Given, it must be a valid `Date` * (`credit_note_issue_date_invalid`). */ issueDate?: Date; /** debtor personal account of the corrected invoice (10000-69999) */ customerAccount: string; /** * Revenue account the corrected invoice was booked on. A cancellation or * return reverses the revenue itself, so it belongs on that account and * not on an Erlösschmälerungen account (those carry price reductions — * Skonto, Rabatt, Bonus). */ revenueAccount?: string; /** credited amount as a POSITIVE gross — the whole invoice or a part of it */ grossCents: TCents; vatRatePercent?: number; scenario?: TTaxScenario; /** `other_eu_state_taxable` only, and required there: what the corrected sale supplied */ otherEuStateSupply?: TOtherEuStateSupply; /** `not_taxable_here` only, and required there: where the corrected sale had its place */ placeOfSupply?: TPlaceOfSupply; /** * The credit note's own number (§ 14 Abs. 4 Satz 1 Nr. 4 UStG). Required: * it becomes the entry's `reference`, the only place the booking names the * document it stands for — Belegfeld 1 is taken by the clearing key. */ creditNoteNumber: string; /** what this document corrects — required, a correction must identify it */ correctedInvoice: ICorrectedInvoiceReference; description: string; costCenter1?: string; docLink?: string; } /** * One VAT group of a document: the part of it taxed under one scenario and rate. * A document's groups may carry either sign — an invoice with a credited line * at another rate, or a correction that lowers one rate and raises another. */ export interface IDocumentVatGroup { /** * The group's amount as it changes the open item of the document's * counterparty, integer cents: POSITIVE raises it (for a customer: what the * customer owes; for a vendor: what is owed to the vendor), NEGATIVE lowers * it. The gross for domestic scenarios, the net for § 13b and intra-EU * acquisitions (the invoice total there is net), zero for a group without * an amount — nothing is booked for it. */ amountCents: TCents; vatRatePercent?: number; scenario?: TTaxScenario; /** `other_eu_state_taxable` only (customer documents), and required there: what the group supplies */ otherEuStateSupply?: TOtherEuStateSupply; /** `not_taxable_here` only (customer documents), and required there: where the group's sale has its place */ placeOfSupply?: TPlaceOfSupply; /** revenue account (customer documents) or expense account (vendor documents) */ account?: string; /** * The group's tax as the document states it (or the part of it this entry * books), integer cents with the sign of `amountCents`: booked as given in * place of what the rate gives, so the parts of one document's tax add up * to the tax it states (§ 14 Abs. 4 Satz 1 Nr. 8, § 14c UStG). It may differ * from what the rate gives by one cent at most, else it is refused * (`vat_amount_off_rate`); a scenario without German VAT takes none but 0. * Where it differs, the base line carries no key that has DATEV compute the * tax (none, or 40 on an Automatikkonto), and the export books it as stated * on the tax account. */ vatCents?: TCents; /** * Vendor documents only: the part of the group's German tax excluded from * the input-tax deduction (§ 15 Abs. 2 and 4 UStG), with the sign of * `amountCents`, at most its tax (`IVendorInvoiceInput.nonDeductibleVatCents`). * A customer document refuses it (`non_deductible_vat_invalid`). */ nonDeductibleVatCents?: TCents; /** * Vendor documents only, under § 13b UStG: the paragraph the group falls * under, stamped on its keyed base line * (`IVendorInvoiceInput.reverseChargeParagraph`). Refused on another * scenario and on a customer document (`reverse_charge_paragraph_invalid`). */ reverseChargeParagraph?: TReverseChargeParagraph; } /** What a document is, and so which numbers its booking carries. */ export type TBookedDocument = /** an invoice: its number is the entry reference and Belegfeld 1, the open-item key */ | { kind: 'invoice'; invoiceNumber?: string } /** * a correction of an invoice (§ 31 Abs. 5 UStDV): its own number is the * entry reference, the corrected invoice's number Belegfeld 1, so the * correction books on that invoice's open item */ | { kind: 'credit_note'; creditNoteNumber: string; correctedInvoice: ICorrectedInvoiceReference; /** * the correction's own date, where the caller books it on another day (the input's `date`, which decides the * period of the correction); a correction may not predate the invoice it corrects, which is read from this date, * from the input's `date` where absent. Given, it must be a valid `Date` (`credit_note_issue_date_invalid`) */ issueDate?: Date; }; export interface ICustomerDocumentInput { /** * the entry's date, the Belegdatum, which decides the period (for a correction § 17 Abs. 1 Satz 8 UStG): the * document's date, or another day the caller books it on; a correction's own date is then `document.issueDate` */ date: Date; /** debtor personal account (10000-69999) */ customerAccount: string; document: TBookedDocument; groups: IDocumentVatGroup[]; /** * The document's durchlaufende Posten (§ 10 Abs. 1 Satz 6 UStG): amounts * received and spent in the name and for the account of another, which are * no part of the consideration and bear no VAT. Integer cents of either * sign, as they change the open item of the counterparty (a group's * `amountCents` convention). Booked as one entry of their own after the * groups' entries, the personal account against `policy.passThrough`, * without VAT and without a BU key, with the document's numbers. 0 or * absent books nothing; a document of durchlaufende Posten alone needs no * VAT group with an amount. */ passThroughCents?: TCents; description: string; costCenter1?: string; docLink?: string; } export interface IVendorDocumentInput { /** * the entry's date, the Belegdatum, which decides the period (for a correction § 17 Abs. 1 Satz 8 UStG): the * document's date, or another day the caller books it on; a correction's own date is then `document.issueDate` */ date: Date; /** creditor personal account (70000-99999) */ vendorAccount: string; document: TBookedDocument; groups: IDocumentVatGroup[]; /** * The document's durchlaufende Posten (§ 10 Abs. 1 Satz 6 UStG): amounts * the supplier's document asks for that are spent in the name and for the * account of another than the books (such as a fee paid on a client's * behalf), which are no expense of the books and bear no VAT. Integer cents of either * sign, as they change the open item of the counterparty (a group's * `amountCents` convention). Booked as one entry of their own after the * groups' entries, the personal account against `policy.passThrough`, * without VAT and without a BU key, with the document's numbers. 0 or * absent books nothing; a document of durchlaufende Posten alone needs no * VAT group with an amount. */ passThroughCents?: TCents; /** * The part of the document's expense the income tax does not let the * business deduct, booked on an account of its own: of a business meal 30 % * (§ 4 Abs. 5 Satz 1 Nr. 2 EStG), on the nicht abzugsfähige * Bewirtungskosten (SKR03 4654, SKR04 6644), as `businessMealOf` of * @fin.cx/expenses computes it. The expense of a group is what it costs the * books: its amount less the input tax it deducts. The part is split over the * groups in proportion to their expense, the cents the split leaves by the * largest remainder, and each group's entry books its share on the account * and the rest of its expense on the group's account. The input tax stays * deducted in full (§ 15 Abs. 1a Satz 2 UStG), as a booking of its own: no * line carries a key that has DATEV compute it, since two expense lines * share the one tax. Refused (`nondeductible_expense_invalid`): an account * that is no expense account of the chart (`isProfitAndLossAccount`) or that * books a tax itself (an Automatikkonto, one marked for the UStVA), an * amount of no positive whole cents or beyond the document's expense, a * group that lowers the document, and a group whose recipient owes the tax * (§ 13b UStG, an intra-Community acquisition). */ nondeductibleExpense?: INondeductibleExpense; description: string; costCenter1?: string; /** KOST2 of every line, the project (DATEV Buchungsstapel field 38) */ costCenter2?: string; docLink?: string; } /** The part of a purchase's expense that is not deductible, and the account it is booked on (`IVendorDocumentInput.nondeductibleExpense`). */ export interface INondeductibleExpense { account: string; /** positive integer cents, at most the document's expense */ amountCents: TCents; } /** * One part of the invoice a Skonto was granted on: the gross amount at one * VAT rate. The recipe splits the Skonto over the shares in proportion to * their gross amounts, because a Skonto of a percentage of the invoice price * lowers each part of it by that percentage — and so the Bemessungsgrundlage * of each rate by its own share (§ 17 Abs. 1 Sätze 1 und 2 UStG). */ export interface ISkontoShare { /** * 19 or 7 for a part taxed at that German rate; its share is booked on the * policy's Skonto account of the rate, or on `account` when it names one, * with the VAT correction at the rate. * 0 for a part that carries no German VAT and whose recipient self-assesses * none (a tax-free supply, a 0 % supply, a supplier under § 19 UStG); its * share is booked on `account`, without VAT. * With `selfAssessed`, 19 or 7: the German rate at which the recipient owes * the tax on the part. */ ratePercent: number; /** * the amount at this rate the Skonto was granted on, positive integer cents: * the gross of the part, or with `selfAssessed` its net, the only amount the * supplier charged */ grossCents: TCents; /** * The account the part's share reduces. For a sale an income account of * the chart, for a purchase an expense account — commonly the revenue or * expense account the part was booked on, so the correction lands on the * same UStVA Kennzahl (e.g. SKR03 8125 → Kz 41, 8400 → Kz 81). * * Required for a part at 0 %; an account whose automatism books VAT at a * rate is refused there. Optional for a part at 19 % or 7 %: unset, the * share is booked on the policy's Skonto account of the rate; named, it * reduces that account instead, with the same VAT correction. An account * whose automatism books VAT at another rate, and one the chart marks for * the UStVA without an automatism at the rate (tax-free, taxable abroad), * is refused there. */ account?: string; /** * The part is a sale taxed in another member state (`other_eu_state_taxable`): * that state's rate and the kind of supply. Its share lowers that state's * Bemessungsgrundlage and the tax owed there with it (Art. 90 Abs. 1 * MwStSystRL), so it is split at that state's rate: the net share on * `account`, the revenue account the part was booked on, and the tax on the * policy's VAT account of that state for the kind of supply * (`vat.otherEuStateGoods`, `…Services`, `…ElectronicServices`). The part * carries no German VAT (`ratePercent` 0) and is a sale's. */ otherEuState?: ISkontoOtherEuState; /** * The part is turnover not taxable here that no other member state's tax * was charged on (`not_taxable_here`, `other_eu_state_recipient_liable`), so * its share lowers the revenue alone. Required, or `otherEuState`, for a * part at 0 % on an account that takes both kinds of sale: the policy's * `revenue.otherEuStateServices` where it is also a `notTaxableHere…` * account (SKR03 8339, SKR04 4339 by default). */ notTaxableHere?: true; /** * The part is a purchase whose recipient owes its German tax: under § 13b * UStG (`reverse_charge_13b`) or as an intra-Community acquisition * (`intra_eu_acquisition`). Its Skonto lowers the Bemessungsgrundlage, and * § 17 Abs. 1 Satz 5 UStG applies Sätze 1 to 4 to it: the tax the * recipient owes is corrected and so is its input-tax deduction, each by * the tax on the reduction at `ratePercent`. The share is booked net on * `account`, the expense account the part was booked on, with the key of * the scenario (§ 13b: 94 / 91, acquisition: 19 / 18), and the invoice's * pair of tax lines swapped (`vat.reverseChargeInput` / `…Output`, * `vat.intraEuAcqInput` / `…Output`). A purchase's only, at 19 or 7 %. */ selfAssessed?: TSelfAssessedScenario; /** * With `selfAssessed`: the recipient deducts none of the tax it owes on the * part (§ 15 Abs. 2 UStG; a Kleinunternehmer, whose sales are exempt under * § 19 Abs. 1 UStG), as its invoice was booked * (`IDocumentVatGroup.nonDeductibleVatCents` of all its tax). The Skonto * corrects the tax owed (§ 17 Abs. 1 Satz 5 UStG) and, since that tax was * cost, the expense by the tax too: the share on `account` with the key of * the scenario, which lowers the tax owed and its deduction in full, and the * deduction given back by all of the tax from `account` (Dr input tax, Cr * `account`, without a key), as the invoice took it back. A part with * German VAT the recipient pays without owing it and does not deduct is * given at 0 % on its expense account instead. */ nonDeductible?: true; /** * A purchase's part whose tax the recipient deducted in part, by the key of * § 15 Abs. 4 UStG its invoice was booked by (a purchase used for both * taxable and exempt sales): the deductible part in percent, above 0 and * below 100, up to two places (62.5). The Skonto corrects the deduction * claimed (§ 17 Abs. 1 Satz 2 UStG), so of the tax on the share only the * part of the key (`deductibleVatCentsOf`) lowers the input tax; the rest * was cost and lowers `account` with the share. A domestic part at 19 or * 7 % names the expense account it was booked on, one without a DATEV * automatism at a rate, and books it without a key: the share's net and * the rest of its tax on it, the deductible part on the input-tax account * of the rate. With `selfAssessed` the share keeps the scenario's key, which * lowers the tax owed and its deduction in full, and the rest beside the * deductible part is given back to the input tax from `account`, a booking * of its own without a key (`IVendorInvoiceInput.nonDeductibleVatCents` of * the rest, as the invoice was booked). Refused on a sale, on a part * without German VAT and with `nonDeductible` (`non_deductible_vat_invalid`). */ deductiblePercent?: number; /** * With `selfAssessed: 'reverse_charge_13b'`: the paragraph of § 13b UStG the * invoice's part fell under (`TReverseChargeParagraph`), stamped on the * share's keyed base line, so the reduction lowers the UStVA field its * base stands in (Kz 46, 73 or 84). Refused on any other part * (`reverse_charge_paragraph_invalid`). */ reverseChargeParagraph?: TReverseChargeParagraph; } /** The scenarios of a purchase whose recipient owes the German tax itself (§ 13b UStG, § 1a UStG). */ export type TSelfAssessedScenario = Extract; /** The other member state's rate and the kind of supply of a Skonto part taxed there. */ export interface ISkontoOtherEuState { /** that state's rate in percent, decimals allowed; 0 for a supply it exempts with the right to deduct (Art. 98 Abs. 2 MwStSystRL) */ ratePercent: number; supply: TOtherEuStateSupply; } /** * The Skonto of a bank payment: the whole difference at one rate, or split * over the rates of the invoice. */ export type TBankPaymentSkonto = /** the whole Skonto at this rate, 19 or 7 — for an invoice at one rate */ | { ratePercent: number } /** * The Skonto split over the parts of the invoice at each rate, in * proportion to their gross amounts; the cents the split leaves go by the * largest remainder, so the parts add up to the Skonto exactly. One share * per rate; parts at 0 % one per account. */ | { shares: ISkontoShare[] }; export interface IBankPaymentInput { date: Date; direction: 'outgoing' | 'incoming'; bankAccount?: string; /** personal debtor/creditor account being settled */ counterpartyAccount: string; /** open gross amount being settled */ expectedCents: TCents; /** amount that actually moved on the bank account */ paidCents: TCents; /** book the difference as Skonto, with the VAT correction at each rate it falls on */ skonto?: TBankPaymentSkonto; /** write off differences up to this size to rounding-diff accounts (default 0) */ diffToleranceCents?: TCents; /** * Book what moved beyond `expectedCents` to this account, without VAT and * without a BU key: a payout the payer knowingly made beyond what it owed, * or money received beyond the open item that is not the counterparty's to * keep on its account. The caller decides what the excess is; the recipe * only books it. The account must be a profit-and-loss account of the chart * in use — an expense for an outgoing excess, income for an incoming one * (`CHART_PROFIT_AND_LOSS_ACCOUNTS`, or an individual account of the books * under one: `isProfitAndLossAccount`) — and none the chart marks for the * UStVA or with a tax automatism (`CHART_VAT_ACCOUNTS`, `isVatMarkedAccount`), nor an * Automatikkonto or VAT account of the policy; everything else, every * balance-sheet account included, is refused, and so is an excess named * when nothing moved beyond the expected amount. It takes precedence over `diffToleranceCents` for * an excess. With it, `expectedCents` may be 0: a payment wholly beyond the * open item (one already settled) is all excess. */ excess?: { account: string }; description: string; reference?: string; } export interface IInternalTransferInput { date: Date; fromBankAccount: string; toBankAccount: string; amountCents: TCents; description: string; reference?: string; } /** * A customer's open item settled by money that reached the business outside * its bank accounts: into the till, into the owner's private account, or into * a shareholder's. */ export interface IReceivableSettledOutsideInput { /** the day the money was paid */ date: Date; /** the customer's personal account that holds the open item */ debtorAccount: string; /** * the account the money went to: the till (`policy.cash`), the owner's * Privatentnahmen (`policy.privateAccounts.withdrawal`, a sole trader or a * partner) or the company's claim against a shareholder on the account of * its form (`shareholderClaimAccount(policy.skrType, shareholderForm)`) */ account: string; /** * of a payment into a shareholder's account: the company's form, and of a * KGaA who the shareholder is (`TShareholderClaimForm`), whose account * `account` must be; unset for the till and the Privatentnahmen */ shareholderForm?: TShareholderClaimForm; amountCents: TCents; description: string; /** * the invoice number: Belegfeld 1, which settles the open item. Unset for * an invoice that names none (a Kleinbetragsrechnung, § 33 UStDV), whose * open item carries none either: the payment has no Belegfeld 1, as a bank * payment of it would not (`bookBankPayment`); `docLink` leads to the Beleg */ reference?: string; docLink?: string; /** * The open item this payment settles, positive integer cents. Unset, the * payment settles exactly what it paid: all of the open item, or a part of * it whose rest stays open. Set, the customer's account is credited with * it, and the difference to `amountCents` is booked as a bank payment's is * (`bookBankPayment`): as the Skonto `skonto` names, at each rate with the * output VAT corrected (§ 17 Abs. 1 UStG), or within `diffToleranceCents` * on the rounding accounts — and refused beyond them * (`shortfall_beyond_tolerance`, `excess_beyond_tolerance`). */ expectedCents?: TCents; /** the Skonto the customer took, on the policy's gewährte Skonti; needs `expectedCents` */ skonto?: TBankPaymentSkonto; /** differences up to this size go to the rounding accounts (default 0); needs `expectedCents` */ diffToleranceCents?: TCents; } export interface ISuspenseInput { date: Date; direction: 'incoming' | 'outgoing'; amountCents: TCents; bankAccount?: string; description: string; reference?: string; } /** * The tax of a fee (`IPaymentFeeInput.scenario`): none (`domestic_tax_free`), * as on a payment or securities service exempt under § 4 Nr. 8 UStG; German * VAT at 19 or 7 % the provider charged (`domestic_standard`, * `domestic_reduced`), as on a custody fee, since § 4 Nr. 8 e UStG exempts no * Verwahrung und Verwaltung von Wertpapieren; or the tax the books owe for a * service from a provider abroad (`reverse_charge_13b`, § 13b Abs. 1 and 2 * Nr. 1 UStG), as on a market-data subscription of a broker in another member * state. A fee pays for a service, so no scenario of goods is one of them. */ export type TPaymentFeeScenario = Extract; export const PAYMENT_FEE_SCENARIOS: readonly TPaymentFeeScenario[] = ['domestic_tax_free', 'domestic_standard', 'domestic_reduced', 'reverse_charge_13b']; /** * A fee a bank or a payment provider (PayPal, Wise) kept from, or gave back * to, the balance of the account it holds (`bookPaymentFee`). */ export interface IPaymentFeeInput { date: Date; /** `charged`: the fee was kept from the balance, an expense; `refunded`: a fee was given back, which reduces it */ direction: 'charged' | 'refunded'; /** * the fee, positive integer cents, as it moved the balance: the gross under * German VAT, the net under § 13b, where the provider charges no tax */ amountCents: TCents; /** the account the provider holds, where the fee moved the balance; the policy's `bank` where absent */ bankAccount?: string; /** * The account the fee is booked on, for a fee that pays for another service * than moving money: a depot's custody fee, a broker's market data, advice. * The policy's `paymentFees` where absent; named, the policy need not name * that account. Checked as a purchase's expense account: at 19 or 7 %, one * the chart ties to another rate or to no German VAT is refused * (`account_rate_mismatch`); without German VAT, one whose DATEV automatism * books input tax at a rate, and under § 13b any Automatikkonto * (`automatik_account_not_allowed`, field `expenseAccount`). */ expenseAccount?: string; /** * The fee's tax (`TPaymentFeeScenario`), booked as on a vendor invoice * (`bookVendorInvoice`) with the provider's account in the supplier's * place: at 19 or 7 % the fee net on the expense account with its input tax * by the key of the rate; under § 13b the fee on it with the tax owed and * deducted in a pair, key 94 or 91. Absent: none, as `domestic_tax_free`. * Another scenario is refused (`payment_fee_input_invalid`). */ scenario?: TPaymentFeeScenario; /** * the German rate under 19 or 7 % or § 13b, the scenario's where absent (19 * under § 13b); a fee without German VAT takes none but 0 * (`payment_fee_input_invalid`) */ vatRatePercent?: number; /** * The part of the fee's German tax excluded from the input-tax deduction * (§ 15 Abs. 2 and 4 UStG), positive integer cents, at most the tax, as * `IVendorInvoiceInput.nonDeductibleVatCents`. Books that deduct none of it, * such as books whose sales are exempt or a Kleinunternehmer's (§ 19 Abs. 1 * UStG), state `nonDeductible` instead, and books deducting by a key of * § 15 Abs. 4 UStG `deductiblePercent`: the recipe then computes the tax. * At 19 or 7 % the part is booked with the fee on the expense account; * under § 13b the fee keeps key 94 or 91 and the part is taken back from * the input tax as a booking of its own. Refused beyond the tax, on a fee * without German VAT and beside `deductiblePercent` or `nonDeductible` * (`non_deductible_vat_invalid`). */ nonDeductibleVatCents?: TCents; /** * The books deduct none of the fee's German tax (§ 15 Abs. 2 UStG: books * whose sales are exempt; a Kleinunternehmer, § 19 Abs. 1 UStG), as * `ISkontoShare.nonDeductible`. The recipe computes the tax as the scenario * books it (from the gross at 19 or 7 %, under § 13b from the net) and * excludes all of it from the deduction, as `nonDeductibleVatCents` of all * of it would: at 19 or 7 % it is booked with the fee on the expense * account; under § 13b the fee keeps key 94 or 91, the tax is owed and * deducted in a pair, and all of it is taken back from the input tax as a * booking of its own without a key (Dr the expense account, Cr the input * tax). Refused beside `deductiblePercent` and `nonDeductibleVatCents`, on a * fee without German VAT, and as any other value than `true` * (`non_deductible_vat_invalid`, field `nonDeductible`). */ nonDeductible?: true; /** * The key of § 15 Abs. 4 UStG for books whose fee serves both taxable and * exempt sales: the deductible part of the fee's German tax in percent, * above 0 and below 100 with up to two places (62.5), as * `ISkontoShare.deductiblePercent` and * `IExpenseClaimReceiptInput.deductiblePercent`. The recipe computes the * tax as the scenario books it (from the gross at 19 or 7 %, under § 13b * from the net) and excludes the rest of it from the deduction * (`deductibleVatCentsOf`), as `nonDeductibleVatCents` would. Refused * beside `nonDeductibleVatCents` or `nonDeductible`, on a fee without * German VAT, and out of range (`non_deductible_vat_invalid`). */ deductiblePercent?: number; /** * Under § 13b UStG (`reverse_charge_13b`): the paragraph the fee falls * under, Abs. 1 (`abs_1`, a provider established in another member state) * or Abs. 2 Nr. 1 (`abs_2`, a provider in a third country), stamped on the * fee's keyed base line (`IJournalLineDraft.reverseChargeParagraph`). * Refused on another scenario and as `abs_2_nr_3`, an Umsatz under the * GrEStG, which a fee is not (`reverse_charge_paragraph_invalid`). */ reverseChargeParagraph?: TReverseChargeParagraph; description: string; reference?: string; } export interface ISuspenseResolutionInput { date: Date; direction: 'incoming' | 'outgoing'; amountCents: TCents; /** the account the suspense amount really belongs to */ targetAccount: string; description: string; reference?: string; } export interface IFxDifferenceInput { kind: 'payable' | 'receivable'; /** EUR value at booking date */ bookedCents: TCents; /** EUR value actually settled */ settledCents: TCents; counterAccount: string; buchungstext: string; belegfeld1?: string; } interface ILineSpec { accountNumber: string; counterAccount: string; side: 'debit' | 'credit'; amountCents: TCents; buKey?: IJournalLineDraft['buKey']; /** the paragraph of § 13b the keyed base line falls under (`IJournalLineDraft.reverseChargeParagraph`) */ reverseChargeParagraph?: TReverseChargeParagraph; } function makeDraft( base: { date: Date; description: string; reference?: string; scenario?: TTaxScenario; belegfeld1?: string; costCenter1?: string; /** KOST2, on the lines only where given */ costCenter2?: string; docLink?: string; }, policy: IAccountPolicy, lines: ILineSpec[], ): IJournalDraft { return { date: base.date, description: base.description, reference: base.reference, skrType: chartOf(policy), currency: 'EUR', taxScenario: base.scenario, lines: lines .filter((line) => line.amountCents !== 0) .map((line) => ({ accountNumber: line.accountNumber, counterAccount: line.counterAccount, side: line.side, amountCents: line.amountCents, buKey: line.buKey ?? '', ...(line.reverseChargeParagraph !== undefined ? { reverseChargeParagraph: line.reverseChargeParagraph } : {}), buchungstext: base.description, belegfeld1: base.belegfeld1, costCenter1: base.costCenter1, ...(base.costCenter2 !== undefined ? { costCenter2: base.costCenter2 } : {}), docLink: base.docLink, })), }; } function assertPositive(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, }); } } /** * Refuse a revenue or expense account whose DATEV automatism books German * Umsatzsteuer or Vorsteuer at a rate (`CHART_VAT_AUTOMATIK_RATES`, e.g. * SKR03 8400, 3400) for a booking that carries no German VAT at that rate: * the line would carry no BU key, so DATEV would book the tax of the * automatism on import and report the base under that rate's Kennzahl. */ function assertNoVatRateAutomatik( account: string, field: 'revenueAccount' | 'expenseAccount', scenario: TTaxScenario, policy: IAccountPolicy, ): void { const mismatch = accountRateMismatchOf(policy, account, undefined); if (mismatch) { throw new RecipeRefusalError( mismatch.code, `${field} ${account} books German VAT at ${mismatch.automatikRatePercent} % by its DATEV automatism; a booking under '${scenario}' carries none — name an account without that automatism`, { field, account, scenario, ratePercent: mismatch.automatikRatePercent }, ); } } /** * The account of goods without a DATEV tax automatism, Wareneingang, which a * purchase whose recipient owes the German tax is named to book on instead of * an Automatikkonto (`refuseSelfAssessedAutomatik`). */ const SELF_ASSESSED_GOODS_ACCOUNT: Readonly> = { SKR03: '3200', SKR04: '5200' }; /** Whether DATEV applies a tax automatism to a line on the account: an Automatikkonto, or an individual account under one whose automatism books VAT at a rate. */ function hasTaxAutomatik(policy: IAccountPolicy, account: string): boolean { return isAutomatikAccount(policy, account) || accountRateMismatchOf(policy, account, undefined) !== undefined; } /** * Refuse, for a purchase whose recipient owes the German tax (§ 13b UStG, an * intra-Community acquisition under § 1a UStG), an expense account with a * DATEV tax automatism: an Automatikkonto of the chart or the policy * (`isAutomatikAccount`; SKR 03 3300, 3400, 3731, 3736, SKR 04 5300, 5400, * 5731, 5736), or an individual account under one that books Vorsteuer at a * rate (`accountRateMismatchOf`). Its base would carry key 40 instead of the * scenario's key (94 / 91, 19 / 18): DATEV would report it as a domestic * purchase at the account's rate and no reader of the keyed lines would find * it in its UStVA field (Kz 46, 73, 84; 89, 93), whatever its paragraph and * whether its tax is stated. The refusal names accounts without an * automatism: Wareneingang (SKR 03 3200, SKR 04 5200) and the policy's * Nebenkosten des Geldverkehrs (`paymentFees`: SKR 03 4970, SKR 04 6855). */ function refuseSelfAssessedAutomatik(account: string, field: string, scenario: TTaxScenario, policy: IAccountPolicy): void { if (!hasTaxAutomatik(policy, account)) { return; } const ratePercent = accountRateMismatchOf(policy, account, undefined)?.automatikRatePercent; const instead = [ { account: SELF_ASSESSED_GOODS_ACCOUNT[chartOf(policy)], use: 'Wareneingang, for goods' }, ...(policy.paymentFees !== undefined ? [{ account: policy.paymentFees, use: 'Nebenkosten des Geldverkehrs, for a fee' }] : []), ].filter((candidateArg) => !hasTaxAutomatik(policy, candidateArg.account)); throw new RecipeRefusalError( 'automatik_account_not_allowed', `${field} ${account} has a DATEV tax automatism${ratePercent !== undefined ? ` (German VAT at ${ratePercent} %)` : ''}; under '${scenario}' the recipient owes the tax, and its base on that account would carry key 40 instead of the scenario's key, outside its UStVA field — book it on an account without an automatism${instead.length > 0 ? `, such as ${instead.map((candidateArg) => `${candidateArg.account} (${candidateArg.use})`).join(' or ')}` : ''}`, { field, account, scenario, ...(ratePercent !== undefined ? { ratePercent } : {}) }, ); } /** * Refuse, for a domestic booking at 19 or 7 %, a revenue or expense account * the chart ties to another rate — an automatism at the other rate * (`CHART_VAT_AUTOMATIK_RATES`, e.g. SKR03 8300 at a sale at 19 %) — or to no * German VAT — marked for the UStVA without an automatism at a rate * (`CHART_VAT_ACCOUNTS`: tax-free revenue, revenue taxed abroad). The line * would carry key 40 next to its VAT line, but DATEV reports the base by the * account, under the other rate's Kennzahl or a tax-free one. Other rates * (16 and 5 % of 2020) are not checked: the chart's automatisms know 19 and 7. */ function assertAccountAtRate( account: string, field: 'revenueAccount' | 'expenseAccount' | 'advances.paid' | 'advances.received', scenario: TTaxScenario, ratePercent: number, policy: IAccountPolicy, ): void { const mismatch = accountRateMismatchOf(policy, account, ratePercent); if (!mismatch) { return; } throw new RecipeRefusalError( mismatch.code, mismatch.automatikRatePercent !== undefined ? `${field} ${account} books German VAT at ${mismatch.automatikRatePercent} % by its DATEV automatism, and DATEV reports its base at that rate; a booking at ${ratePercent} % goes on an account of that rate` : `${field} ${account} is marked in ${policy.skrType} for the UStVA without German VAT at ${ratePercent} % (tax-free, or taxed abroad); a booking at ${ratePercent} % goes on an account of that rate`, { field, account, scenario, ratePercent }, ); } /** * Refuse a supply taxable at 0 % (`domestic_zero_rate`, § 12 Abs. 3 UStG) * stated at another rate: the recipe books it without tax on the account of * Kz 87, so a document at 19 or 7 % would lose its tax without a word. A rate * of 0, or none, is the zero rate. */ function refuseZeroRateAtAnotherRate( ratePercent: number | undefined, account: string, scenario: TTaxScenario, ): void { if (scenario !== 'domestic_zero_rate' || ratePercent === undefined || ratePercent === 0) { return; } throw new RecipeRefusalError( 'account_rate_mismatch', `a supply taxable at 0 % (§ 12 Abs. 3 UStG) is booked without tax on ${account}; vatRatePercent ${ratePercent} is another rate's, whose sale goes under its own scenario`, { field: 'vatRatePercent', account, scenario, ratePercent }, ); } /** * Refuse a revenue account whose base DATEV reports in UStVA Kz 87, the * supplies taxable at 0 % (`CHART_ZERO_RATE_REVENUE_ACCOUNTS`, § 12 Abs. 3 * UStG), for a sale that is no such supply, and any other account for one * that is: DATEV reports the base by the account, so a zero-rated sale on an * export account would be reported as an export (Kz 43), and an export on * the zero-rate account as a zero-rated supply. */ function assertZeroRateAccount(account: string, scenario: TTaxScenario, policy: IAccountPolicy): void { // an individual account under the account of 0 % is one too (`vatCheckAccountOf`) const zeroRate = CHART_ZERO_RATE_REVENUE_ACCOUNTS[chartOf(policy)].includes(vatCheckAccountOf(policy, account)); if (zeroRate === (scenario === 'domestic_zero_rate')) { return; } throw new RecipeRefusalError( 'account_rate_mismatch', zeroRate ? `revenueAccount ${account} is the account of supplies taxable at 0 % (§ 12 Abs. 3 UStG, UStVA Kz 87); a sale under '${scenario}' goes on an account of its own case` : `a supply taxable at 0 % (§ 12 Abs. 3 UStG) goes on an account DATEV reports in UStVA Kz 87 (${CHART_ZERO_RATE_REVENUE_ACCOUNTS[chartOf(policy)].join(', ')}), not on revenueAccount ${account}`, { field: 'revenueAccount', account, scenario, ratePercent: 0 }, ); } /** * The calendar day a booking date belongs to. Booking dates are read in UTC * everywhere (`periodOf`, `fiscalYearOf`, the DATEV Belegdatum), so two dates * of the same UTC day are the same booking day whatever time they carry. */ function bookingDayOf(date: Date): number { return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()); } /** * The part of a purchase's German tax excluded from the input-tax deduction * (`IVendorInvoiceInput.nonDeductibleVatCents`), checked against the tax the * recipe books: whole cents, at most that tax, none on a scenario without * German VAT, and not on an expense account whose DATEV automatism books * input tax at a rate (it would deduct the tax on import). 0 where unset. */ function nonDeductibleOf( excludedArg: TCents | undefined, vatCentsArg: TCents, expenseAccountArg: string, scenarioArg: TTaxScenario, policy: IAccountPolicy, ): TCents { if (excludedArg === undefined || excludedArg === 0) { return 0; } if (!Number.isSafeInteger(excludedArg) || excludedArg < 0) { throw new RecipeRefusalError('non_deductible_vat_invalid', `nonDeductibleVatCents must be a positive integer cent amount, got ${excludedArg}`, { field: 'nonDeductibleVatCents', amountCents: excludedArg, }); } if (excludedArg > vatCentsArg) { throw new RecipeRefusalError( 'non_deductible_vat_invalid', vatCentsArg === 0 ? `nonDeductibleVatCents ${excludedArg} on scenario '${scenarioArg}', which books no German tax to deduct` : `nonDeductibleVatCents ${excludedArg} exceeds the tax of ${vatCentsArg} cents`, { field: 'nonDeductibleVatCents', amountCents: excludedArg, scenario: scenarioArg }, ); } assertNoVatRateAutomatik(expenseAccountArg, 'expenseAccount', scenarioArg, policy); return excludedArg; } /** * The paragraph of § 13b UStG an input names (`reverseChargeParagraph`), * checked: one of `TReverseChargeParagraph`, under `reverse_charge_13b` only, * and for a fee (`feeArg`) not Abs. 2 Nr. 3, since a fee is no Umsatz under * the GrEStG. Refused `reverse_charge_paragraph_invalid`. */ function reverseChargeParagraphOf( paragraphArg: unknown, scenarioArg: TTaxScenario | undefined, fieldArg: string, feeArg = false, ): TReverseChargeParagraph | undefined { if (paragraphArg === undefined) return undefined; if (!REVERSE_CHARGE_PARAGRAPHS.includes(paragraphArg as TReverseChargeParagraph)) { throw new RecipeRefusalError( 'reverse_charge_paragraph_invalid', `${fieldArg} must be one of ${REVERSE_CHARGE_PARAGRAPHS.join(', ')}, got ${String(paragraphArg)}`, { field: fieldArg }, ); } if (scenarioArg !== 'reverse_charge_13b') { throw new RecipeRefusalError( 'reverse_charge_paragraph_invalid', `${fieldArg} is the paragraph of a tax the recipient owes under § 13b UStG, not one of scenario '${String(scenarioArg ?? 'domestic_standard')}'`, { field: fieldArg, ...(scenarioArg !== undefined ? { scenario: scenarioArg } : {}) }, ); } if (feeArg && paragraphArg === 'abs_2_nr_3') { throw new RecipeRefusalError( 'reverse_charge_paragraph_invalid', `${fieldArg} abs_2_nr_3 is the paragraph of an Umsatz under the GrEStG, which a fee is not: a fee falls under § 13b Abs. 1 or Abs. 2 Nr. 1`, { field: fieldArg, scenario: scenarioArg }, ); } return paragraphArg as TReverseChargeParagraph; } /** * The part of a German tax that is deductible by a key of § 15 Abs. 4 UStG, * for a purchase used for both taxable and exempt sales: `vatCents` times * `deductiblePercent` / 100, rounded half up (away from zero on a half) to * the cent, with the sign of `vatCents`. The rest, `vatCents` less it, is the * part excluded from the deduction (`nonDeductibleVatCents`); a Skonto's * share by the same key (`ISkontoShare.deductiblePercent`) and a receipt of * an expense claim (`IExpenseClaimReceiptInput.deductiblePercent`) are split * by this rule too. Refused (`non_deductible_vat_invalid`): a key that is not * above 0 and below 100 with up to two places; (`amount_not_whole_cents`) a * tax of no whole cents. */ export function deductibleVatCentsOf(vatCents: TCents, deductiblePercent: number): TCents { if (!Number.isSafeInteger(vatCents)) { throw new RecipeRefusalError('amount_not_whole_cents', `vatCents must be an integer cent amount, got ${vatCents}`, { field: 'vatCents', amountCents: vatCents }); } const basisPoints = BigInt(deductibleBasisPointsOf(deductiblePercent, 'deductiblePercent')); const deductible = Number((BigInt(Math.abs(vatCents)) * basisPoints + 5_000n) / 10_000n); return vatCents < 0 ? -deductible : deductible; } /** A key of § 15 Abs. 4 UStG in hundredths of a percent: above 0 and below 100 %, up to two places, else refused. */ function deductibleBasisPointsOf(percentArg: unknown, fieldArg: string): number { const basisPoints = typeof percentArg === 'number' && Number.isFinite(percentArg) ? Math.round(percentArg * 100) : NaN; if (!(basisPoints > 0 && basisPoints < 10_000) || Math.abs((percentArg as number) * 100 - basisPoints) > 1e-6) { throw new RecipeRefusalError( 'non_deductible_vat_invalid', `${fieldArg} must be the deductible part in percent, above 0 and below 100 with up to two places, got ${String(percentArg)}`, { field: fieldArg }, ); } return basisPoints; } /** * Eingangsrechnung and a correction of it share one shape: the invoice books * expense debit / Vorsteuer debit / creditor credit, a correction that lowers * the invoice books the same accounts with both sides swapped. * domestic: expense net + Vorsteuer + creditor gross. * §13b / igE: expense net with the scenario's key + paired input/output VAT * + creditor net, and a part excluded from the deduction as its own * key-less correction (expense against the input tax). * tax-free/import: expense gross + creditor gross. */ function buildVendorDocument( input: { date: Date; vendorAccount: string; expenseAccount?: string; grossCents: TCents; vatRatePercent?: number; /** the tax as stated, POSITIVE (`IDocumentVatGroup.vatCents`) */ vatCents?: TCents; /** the part of the tax excluded from the deduction, POSITIVE (`IVendorInvoiceInput.nonDeductibleVatCents`) */ nonDeductibleVatCents?: TCents; /** under § 13b, the paragraph the keyed base line falls under (`IVendorInvoiceInput.reverseChargeParagraph`) */ reverseChargeParagraph?: TReverseChargeParagraph; /** this group's share of the part of the expense that is not deductible, checked (`IVendorDocumentInput.nondeductibleExpense`) */ nondeductibleExpense?: INondeductibleExpense; scenario?: TTaxScenario; description: string; costCenter1?: string; docLink?: string; }, policy: IAccountPolicy, kind: TDocumentKind, base: Parameters[0], ): IJournalDraft { assertPositive(input.grossCents, 'grossCents'); const scenario = input.scenario ?? 'domestic_standard'; if (scenario === 'other_eu_state_recipient_liable' || scenario === 'not_taxable_here') { throw new RecipeRefusalError( 'scenario_not_for_purchases', `Scenario '${scenario}' is a sale's: a purchase is booked under the scenario of its own supply`, { scenario }, ); } if (scenario === 'other_eu_state_taxable') { throw new RecipeRefusalError( 'scenario_not_for_purchases', `Scenario 'other_eu_state_taxable' is a sale's: VAT another member state charged on a purchase is no German input tax (§ 15 Abs. 1 Satz 1 Nr. 1 UStG) — book the purchase without German VAT`, { scenario }, ); } const rate = vendorRateOf(scenario, input.vatRatePercent); const paragraph = reverseChargeParagraphOf(input.reverseChargeParagraph, scenario, 'reverseChargeParagraph'); const expenseAccount = input.expenseAccount ?? policy.expenseDefault; /** the correction is the invoice with both sides swapped */ const side = (invoiceSide: 'debit' | 'credit'): 'debit' | 'credit' => kind === 'invoice' ? invoiceSide : invoiceSide === 'debit' ? 'credit' : 'debit'; /** * The expense of the entry on its lines: on the expense account, less the share that is not deductible, which * goes on its own account. The creditor's line names the first of them that books an amount. */ const nondeductible = input.nondeductibleExpense; const expenseLines = (expenseCentsArg: TCents, buKeyArg: TBuKey): ILineSpec[] => [ { accountNumber: expenseAccount, counterAccount: input.vendorAccount, side: side('debit'), amountCents: expenseCentsArg - (nondeductible?.amountCents ?? 0), buKey: buKeyArg, }, ...(nondeductible ? [{ accountNumber: nondeductible.account, counterAccount: input.vendorAccount, side: side('debit'), amountCents: nondeductible.amountCents }] : []), ]; const expenseCounter = (expenseCentsArg: TCents): string => nondeductible && expenseCentsArg === nondeductible.amountCents ? nondeductible.account : expenseAccount; const expenseIsAutomatik = isAutomatikAccount(policy, expenseAccount); if (scenario === 'domestic_standard' || scenario === 'domestic_reduced') { assertAccountAtRate(expenseAccount, 'expenseAccount', scenario, rate, policy); const { vatCents, stated } = documentVatOf(splitGrossCents(input.grossCents, rate).vatCents, input.vatCents, rate, scenario); const excludedCents = nonDeductibleOf(input.nonDeductibleVatCents, vatCents, expenseAccount, scenario, policy); const netCents = input.grossCents - vatCents; const vatAccount = rate === 7 ? policy.vat.inputReduced : policy.vat.inputStandard; // the tax excluded from the deduction is cost, booked with its base const expenseCents = netCents + excludedCents; return makeDraft(base, policy, [ ...expenseLines( expenseCents, suggestBuKey({ direction: 'inbound', scenario, ratePercent: rate, targetIsAutomatik: expenseIsAutomatik, hasExplicitVatLines: vatCents - excludedCents > 0, // a tax deducted only in part is none DATEV may compute from the base, nor one two expense lines share vatAsStated: stated || excludedCents > 0 || nondeductible !== undefined, }), ), { accountNumber: vatAccount, counterAccount: input.vendorAccount, side: side('debit'), amountCents: vatCents - excludedCents, }, { accountNumber: input.vendorAccount, counterAccount: expenseCounter(expenseCents), side: side('credit'), amountCents: input.grossCents, }, ]); } if (scenario === 'reverse_charge_13b' || scenario === 'intra_eu_acquisition') { // on an Automatikkonto the base would carry key 40, outside the scenario's UStVA field refuseSelfAssessedAutomatik(expenseAccount, 'expenseAccount', scenario, policy); // invoice total is net; German VAT is self-assessed in paired lines const { vatCents, stated } = documentVatOf(vatFromNetCents(input.grossCents, rate), input.vatCents, rate, scenario); const excludedCents = nonDeductibleOf(input.nonDeductibleVatCents, vatCents, expenseAccount, scenario, policy); const inputVatAccount = scenario === 'reverse_charge_13b' ? policy.vat.reverseChargeInput : policy.vat.intraEuAcqInput; const outputVatAccount = scenario === 'reverse_charge_13b' ? policy.vat.reverseChargeOutput : policy.vat.intraEuAcqOutput; const buKey = suggestBuKey({ direction: 'inbound', scenario, ratePercent: rate, targetIsAutomatik: expenseIsAutomatik, hasExplicitVatLines: vatCents > 0, // a tax as its document states it is none DATEV may compute from the base: the pair is then a booking of its own vatAsStated: stated, }); return makeDraft(base, policy, [ { accountNumber: expenseAccount, counterAccount: input.vendorAccount, side: side('debit'), amountCents: input.grossCents, buKey, // the paragraph of § 13b stands beside its key only: a base without one (a tax as stated) carries none ...(paragraph !== undefined && isReverseChargeBuKey(buKey) ? { reverseChargeParagraph: paragraph } : {}), }, // the tax owed and deducted in full, as the key has DATEV book it { accountNumber: inputVatAccount, counterAccount: outputVatAccount, side: side('debit'), amountCents: vatCents, }, { accountNumber: outputVatAccount, counterAccount: inputVatAccount, side: side('credit'), amountCents: vatCents, }, { accountNumber: input.vendorAccount, counterAccount: expenseAccount, side: side('credit'), amountCents: input.grossCents, }, // the part excluded from the deduction taken back from the input tax as cost (§ 9b Abs. 1 EStG), a booking of its // own without a key, so the base and the tax owed stand in full where the key declares them ...inputTaxCorrectionLines(expenseAccount, inputVatAccount, excludedCents, side('debit')), ]); } // domestic_tax_free, export_third_country (import without German VAT), // intra_eu_supply is not a vendor scenario but degrades to the same shape refuseStatedVatWithoutGermanVat(input.vatCents, scenario); nonDeductibleOf(input.nonDeductibleVatCents, 0, expenseAccount, scenario, policy); assertNoVatRateAutomatik(expenseAccount, 'expenseAccount', scenario, policy); refuseZeroRateAtAnotherRate(input.vatRatePercent, expenseAccount, scenario); return makeDraft(base, policy, [ ...expenseLines(input.grossCents, ''), { accountNumber: input.vendorAccount, counterAccount: expenseCounter(input.grossCents), side: side('credit'), amountCents: input.grossCents, }, ]); } /** * The correction of a self-assessed tax's deduction by the part excluded from * it (§ 15 Abs. 2 and 4 UStG): that part on the expense account, on * `expenseSideArg`, against the scenario's input-tax account on the other * side, without a key. Nothing for none. */ function inputTaxCorrectionLines(expenseAccountArg: string, inputVatAccountArg: string, excludedCentsArg: TCents, expenseSideArg: 'debit' | 'credit'): ILineSpec[] { if (excludedCentsArg === 0) return []; return [ { accountNumber: expenseAccountArg, counterAccount: inputVatAccountArg, side: expenseSideArg, amountCents: excludedCentsArg }, { accountNumber: inputVatAccountArg, counterAccount: expenseAccountArg, side: expenseSideArg === 'debit' ? 'credit' : 'debit', amountCents: excludedCentsArg }, ]; } /** The German rate a vendor document's group is booked at: the one given, else the scenario's (0 without German VAT). */ function vendorRateOf(scenarioArg: TTaxScenario, ratePercentArg: number | undefined): number { return ratePercentArg ?? (scenarioArg === 'domestic_reduced' ? 7 : scenarioArg === 'domestic_tax_free' ? 0 : 19); } /** * Eingangsrechnung (vendor invoice). * domestic: expense net + Vorsteuer + creditor gross. * §13b / igE: expense net + paired input/output VAT + creditor net. * tax-free/import: expense gross + creditor gross. */ export function bookVendorInvoice( input: IVendorInvoiceInput, policy: IAccountPolicy, ): IJournalDraft { const scenario = input.scenario ?? 'domestic_standard'; return buildVendorDocument(input, policy, 'invoice', { date: input.date, description: input.description, reference: input.invoiceNumber, scenario, belegfeld1: input.invoiceNumber, costCenter1: input.costCenter1, docLink: input.docLink, }); } /** * Ausgangsrechnung and Rechnungskorrektur share one shape: the invoice books * debtor debit / revenue credit / output VAT credit, the credit note books the * same accounts with both sides swapped. Keeping one builder is what makes an * invoice and its full credit note net every account to zero. */ type TDocumentKind = 'invoice' | 'credit_note'; function buildCustomerDocument( input: { date: Date; customerAccount: string; revenueAccount?: string; grossCents: TCents; vatRatePercent?: number; /** the tax as stated, POSITIVE (`IDocumentVatGroup.vatCents`) */ vatCents?: TCents; scenario?: TTaxScenario; otherEuStateSupply?: TOtherEuStateSupply; placeOfSupply?: TPlaceOfSupply; description: string; costCenter1?: string; docLink?: string; }, policy: IAccountPolicy, kind: TDocumentKind, base: Parameters[0], ): IJournalDraft { assertPositive(input.grossCents, 'grossCents'); const scenario = input.scenario ?? 'domestic_standard'; const rate = input.vatRatePercent ?? (scenario === 'domestic_reduced' ? 7 : scenario === 'domestic_standard' ? 19 : 0); /** the credit note is the invoice with both sides swapped */ const side = (invoiceSide: 'debit' | 'credit'): 'debit' | 'credit' => kind === 'invoice' ? invoiceSide : invoiceSide === 'debit' ? 'credit' : 'debit'; if (scenario === 'other_eu_state_taxable') { // the other state's rate and the kind of supply decide the booking; neither is assumed const otherRate = input.vatRatePercent; if (typeof otherRate !== 'number' || !Number.isFinite(otherRate) || otherRate < 0) { throw new RecipeRefusalError( 'other_eu_state_rate_required', `Scenario 'other_eu_state_taxable' requires vatRatePercent, the rate of the member state the sale is taxed in, got ${otherRate}`, { field: 'vatRatePercent', scenario, ...(typeof otherRate === 'number' ? { ratePercent: otherRate } : {}) }, ); } const supply = input.otherEuStateSupply; if (supply !== 'goods' && supply !== 'electronic_services' && supply !== 'other_services') { throw new RecipeRefusalError( 'other_eu_state_supply_required', `Scenario 'other_eu_state_taxable' requires otherEuStateSupply ('goods', 'electronic_services' or 'other_services'), got ${supply}`, { field: 'otherEuStateSupply', scenario }, ); } const revenueAccount = input.revenueAccount ?? (supply === 'goods' ? policy.revenue.otherEuStateGoods : supply === 'electronic_services' ? policy.revenue.otherEuStateElectronicServices : policy.revenue.otherEuStateServices); assertNoVatRateAutomatik(revenueAccount, 'revenueAccount', scenario, policy); const vatAccount = supply === 'goods' ? policy.vat.otherEuStateGoods : supply === 'electronic_services' ? policy.vat.otherEuStateElectronicServices : policy.vat.otherEuStateServices; const { vatCents } = documentVatOf(splitGrossCents(input.grossCents, otherRate).vatCents, input.vatCents, otherRate, scenario); const netCents = input.grossCents - vatCents; return makeDraft(base, policy, [ { accountNumber: input.customerAccount, counterAccount: revenueAccount, side: side('debit'), amountCents: input.grossCents, }, { accountNumber: revenueAccount, counterAccount: input.customerAccount, side: side('credit'), amountCents: netCents, buKey: suggestBuKey({ direction: 'outbound', scenario, ratePercent: otherRate, targetIsAutomatik: isAutomatikAccount(policy, revenueAccount), // the other state's VAT is no German tax: it cancels no automatism of the revenue account hasExplicitVatLines: false, }), }, { accountNumber: vatAccount, counterAccount: input.customerAccount, side: side('credit'), amountCents: vatCents, }, ]); } if (scenario === 'domestic_standard' || scenario === 'domestic_reduced') { const revenueAccount = input.revenueAccount ?? (rate === 7 ? policy.revenue.domesticReduced : policy.revenue.domesticStandard); assertAccountAtRate(revenueAccount, 'revenueAccount', scenario, rate, policy); const revenueIsAutomatik = isAutomatikAccount(policy, revenueAccount); const { vatCents, stated } = documentVatOf(splitGrossCents(input.grossCents, rate).vatCents, input.vatCents, rate, scenario); const netCents = input.grossCents - vatCents; const vatAccount = rate === 7 ? policy.vat.outputReduced : policy.vat.outputStandard; return makeDraft(base, policy, [ { accountNumber: input.customerAccount, counterAccount: revenueAccount, side: side('debit'), amountCents: input.grossCents, }, { accountNumber: revenueAccount, counterAccount: input.customerAccount, side: side('credit'), amountCents: netCents, buKey: suggestBuKey({ direction: 'outbound', scenario, ratePercent: rate, targetIsAutomatik: revenueIsAutomatik, hasExplicitVatLines: vatCents > 0, vatAsStated: stated, }), }, { accountNumber: vatAccount, counterAccount: input.customerAccount, side: side('credit'), amountCents: vatCents, }, ]); } refuseStatedVatWithoutGermanVat(input.vatCents, scenario); let revenueAccount = input.revenueAccount; if (scenario === 'not_taxable_here' && input.placeOfSupply !== 'eu' && input.placeOfSupply !== 'third_country') { throw new RecipeRefusalError( 'place_of_supply_required', `Scenario 'not_taxable_here' requires placeOfSupply ('eu' or 'third_country'), got ${input.placeOfSupply}`, { field: 'placeOfSupply', scenario }, ); } if (!revenueAccount) { if (scenario === 'intra_eu_supply') revenueAccount = policy.revenue.intraEuSupply; else if (scenario === 'export_third_country') revenueAccount = policy.revenue.export; else if (scenario === 'domestic_zero_rate') revenueAccount = zeroRateAccountOf(policy); else if (scenario === 'reverse_charge_13b') revenueAccount = policy.revenue.reverseCharge; else if (scenario === 'other_eu_state_recipient_liable') revenueAccount = policy.revenue.otherEuStateRecipientLiable; else if (scenario === 'not_taxable_here') { revenueAccount = input.placeOfSupply === 'eu' ? policy.revenue.notTaxableHereEu : policy.revenue.notTaxableHereThirdCountry; } else { throw new RecipeRefusalError( 'revenue_account_required', `Scenario '${scenario}' requires an explicit revenueAccount — no policy default exists`, { scenario }, ); } } assertNoVatRateAutomatik(revenueAccount, 'revenueAccount', scenario, policy); assertZeroRateAccount(revenueAccount, scenario, policy); refuseZeroRateAtAnotherRate(input.vatRatePercent, revenueAccount, scenario); const revenueIsAutomatik = isAutomatikAccount(policy, revenueAccount); return makeDraft(base, policy, [ { accountNumber: input.customerAccount, counterAccount: revenueAccount, side: side('debit'), amountCents: input.grossCents, }, { accountNumber: revenueAccount, counterAccount: input.customerAccount, side: side('credit'), amountCents: input.grossCents, buKey: suggestBuKey({ direction: 'outbound', scenario, ratePercent: 0, targetIsAutomatik: revenueIsAutomatik, hasExplicitVatLines: false, }), }, ]); } /** * Ausgangsrechnung (customer invoice). `invoiceNumber` becomes Belegfeld 1 on * every line — DATEV's key for clearing open items, so every later payment or * credit note that repeats it settles THIS invoice. */ export function bookCustomerInvoice( input: ICustomerInvoiceInput, policy: IAccountPolicy, ): IJournalDraft { const scenario = input.scenario ?? 'domestic_standard'; return buildCustomerDocument(input, policy, 'invoice', { date: input.date, description: input.description, reference: input.invoiceNumber, scenario, belegfeld1: input.invoiceNumber, costCenter1: input.costCenter1, docLink: input.docLink, }); } /** * Rechnungskorrektur / Stornorechnung for a customer invoice — a genuine * business event, not a correction of a wrong posting. * * Booking: revenue debit net, output VAT debit, debtor credit gross — the * invoice with both sides swapped, on the SAME revenue account. Legal basis: * - § 17 Abs. 1 Satz 1 UStG: the supplier corrects the tax he owes when the * Bemessungsgrundlage changes; Abs. 2 Nr. 3 applies that "sinngemäß" when * the supply is "rückgängig gemacht worden". * - § 17 Abs. 1 Satz 8 UStG: the correction belongs to the Besteuerungs- * zeitraum "in dem die Änderung der Bemessungsgrundlage eingetreten ist" * — the credit note's own period, so `date` is the credit note's date. * - § 31 Abs. 5 UStDV: the correction travels on "ein Dokument, das * spezifisch und eindeutig auf die Rechnung bezogen ist" — the DOCUMENT * carries the reference, so both numbers are required inputs. * - § 146 Abs. 4 AO / § 239 Abs. 3 HGB: nothing about the original entry is * touched — this is an additional entry, and `IJournalDraft.reversalOf` * stays unset because that field marks the technical reversal of a wrong * POSTING (see `SkrApi.postStorno`), not a corrected invoice. * * Which number goes where is DATEV's rule, not a preference. Belegfeld 1 is * the open-item key: "Rechnungs-/Belegnummer[.] Wird als 'Schlüssel' für den * Ausgleich offener Rechnungen genutzt" and, spelled out for the same field in * the Wiederkehrende-Buchungen format, "Bei einer Zahlung oder Gutschrift wird * der Offene Posten nur dann ausgeglichen, wenn die Belegnummer mit dem * Belegfeld 1 identisch ist" (DATEV-Format, Formatbeschreibung Buchungsstapel * field 11 / Wiederkehrende Buchungen field 10). So a credit note carries the * CORRECTED INVOICE's number in Belegfeld 1 — that is what makes it settle the * invoice's open item instead of opening a second one — and its own number in * the entry `reference`, which is persisted, hashed and shown in the ledger * views. Belegfeld 2 stays empty: DATEV defines it as a Belegnummer or OPOS * processing info, but the ledger does not persist it (docs/credit-notes.md). * * `grossCents` is the POSITIVE credited amount: the full invoice gross or the * credited part of it. Pass the revenue account of the corrected invoice. */ export function bookCustomerCreditNote( input: ICustomerCreditNoteInput, policy: IAccountPolicy, ): IJournalDraft { const identity = correctionIdentity(input.creditNoteNumber, input.correctedInvoice, input.date, input.issueDate); const scenario = input.scenario ?? 'domestic_standard'; return buildCustomerDocument(input, policy, 'credit_note', { date: input.date, description: input.description, scenario, ...identity, costCenter1: input.costCenter1, docLink: input.docLink, }); } /** * The numbers a correction document books under: its own number as the entry * `reference` and the corrected invoice's number as Belegfeld 1, the DATEV key * that clears that invoice's open item. Both are required, and a correction may * not predate the calendar day of the invoice it corrects, read from the * correction's own date: `issueDateArg`, or the entry's date where it has none. * An own date that is given and is no day is refused * (`credit_note_issue_date_invalid`), never read as absent. */ function correctionIdentity( creditNoteNumberArg: string | undefined, correctedInvoiceArg: ICorrectedInvoiceReference | undefined, entryDateArg: Date, issueDateArg: Date | undefined, ): { reference: string; belegfeld1: string } { const correctedInvoiceNumber = correctedInvoiceArg?.invoiceNumber?.trim(); if (!correctedInvoiceNumber) { throw new RecipeRefusalError( 'corrected_invoice_required', 'correctedInvoice.invoiceNumber is required — a credit note must identify the invoice it corrects (§ 31 Abs. 5 UStDV) and it is the Belegfeld 1 key that clears that invoice', ); } const creditNoteNumber = creditNoteNumberArg?.trim(); if (!creditNoteNumber) { throw new RecipeRefusalError( 'credit_note_number_required', 'creditNoteNumber is required — the correction document carries its own fortlaufende Nummer (§ 14 Abs. 4 Satz 1 Nr. 4 UStG) and the entry names it in reference', ); } if (issueDateArg !== undefined && !(issueDateArg instanceof Date && !Number.isNaN(issueDateArg.getTime()))) { throw new RecipeRefusalError( 'credit_note_issue_date_invalid', `issueDate of credit note ${creditNoteNumber} is no day (${String(issueDateArg)}); pass the correction's own date as a Date, or leave it out where the entry is dated on it`, { field: 'issueDate' }, ); } const dateArg = issueDateArg ?? entryDateArg; const correctedInvoiceDate = correctedInvoiceArg?.date; if ( correctedInvoiceDate instanceof Date && !Number.isNaN(correctedInvoiceDate.getTime()) && dateArg instanceof Date && !Number.isNaN(dateArg.getTime()) && bookingDayOf(dateArg) < bookingDayOf(correctedInvoiceDate) ) { throw new RecipeRefusalError( 'credit_note_predates_invoice', `Credit note date ${dateArg.toISOString().slice(0, 10)} predates corrected invoice ${correctedInvoiceNumber} of ${correctedInvoiceDate.toISOString().slice(0, 10)}`, ); } return { reference: creditNoteNumber, belegfeld1: correctedInvoiceNumber }; } /** the reference and Belegfeld 1 of a document's entries */ function documentIdentity( documentArg: TBookedDocument, dateArg: Date, ): { reference?: string; belegfeld1?: string } { if (documentArg?.kind === 'invoice') { return { reference: documentArg.invoiceNumber, belegfeld1: documentArg.invoiceNumber }; } if (documentArg?.kind === 'credit_note') { return correctionIdentity(documentArg.creditNoteNumber, documentArg.correctedInvoice, dateArg, documentArg.issueDate); } // TBookedDocument has no other kind: a caller that reaches here broke the type, an invariant, not a refusal throw new Error(`document.kind must be 'invoice' or 'credit_note'`); } /** * the groups of a document that carry an amount; refuses a document with none, * unless it has durchlaufende Posten (`passThroughCents`), which may stand alone */ function bookableGroups(groupsArg: IDocumentVatGroup[], passThroughCentsArg?: TCents): IDocumentVatGroup[] { if (passThroughCentsArg !== undefined && !Number.isSafeInteger(passThroughCentsArg)) { throw new RecipeRefusalError('amount_not_whole_cents', `passThroughCents must be an integer cent amount, got ${passThroughCentsArg}`, { field: 'passThroughCents', amountCents: passThroughCentsArg, }); } const passesThrough = passThroughCentsArg !== undefined && passThroughCentsArg !== 0; if (!Array.isArray(groupsArg) || (groupsArg.length === 0 && !passesThrough)) { throw new RecipeRefusalError('document_groups_missing', 'groups must list the VAT groups of the document', { field: 'groups' }); } for (const group of groupsArg) { if (!Number.isSafeInteger(group?.amountCents)) { throw new RecipeRefusalError('amount_not_whole_cents', `amountCents of every group must be an integer cent amount, got ${group?.amountCents}`, { field: 'groups.amountCents', amountCents: group?.amountCents, }); } } const bookable = groupsArg.filter((group) => group.amountCents !== 0); if (bookable.length === 0 && !passesThrough) { throw new RecipeRefusalError('document_without_amount', 'a document needs at least one VAT group with an amount, or durchlaufende Posten', { field: 'groups' }); } return bookable; } /** A vendor group's tax excluded from the deduction, POSITIVE, with the sign of its amount checked (`IDocumentVatGroup.nonDeductibleVatCents`). */ function groupNonDeductibleOf(groupArg: IDocumentVatGroup): TCents | undefined { const excluded = groupArg.nonDeductibleVatCents; if (excluded === undefined || excluded === 0) { return undefined; } if (!Number.isSafeInteger(excluded) || Math.sign(excluded) !== Math.sign(groupArg.amountCents)) { throw new RecipeRefusalError( 'non_deductible_vat_invalid', `nonDeductibleVatCents ${excluded} of a group must be integer cents with the sign of its amount ${groupArg.amountCents}`, { field: 'groups.nonDeductibleVatCents', amountCents: excluded }, ); } return Math.abs(excluded); } /** The magnitude of a group's stated tax, refused where its sign is not the group's. */ function statedVatOf(groupArg: IDocumentVatGroup): TCents | undefined { const vatCents = groupArg.vatCents; if (vatCents === undefined) { return undefined; } if (!Number.isSafeInteger(vatCents)) { throw new RecipeRefusalError('amount_not_whole_cents', `vatCents of a group must be an integer cent amount, got ${vatCents}`, { field: 'groups.vatCents', amountCents: vatCents, }); } if (vatCents !== 0 && Math.sign(vatCents) !== Math.sign(groupArg.amountCents)) { throw new RecipeRefusalError('vat_amount_off_rate', `vatCents ${vatCents} has another sign than the group's amount ${groupArg.amountCents}`, { field: 'groups.vatCents', amountCents: vatCents, }); } return Math.abs(vatCents); } /** * The tax a document entry books: what the rate gives, or the tax stated * (`IDocumentVatGroup.vatCents`) where one is and it is within a cent of it; * `stated` where that differs from what the rate gives, so the entry must not * have DATEV compute it. */ function documentVatOf( computedArg: TCents, statedArg: TCents | undefined, rateArg: number, scenarioArg: TTaxScenario, ): { vatCents: TCents; stated: boolean } { if (statedArg === undefined) { return { vatCents: computedArg, stated: false }; } const differenceCents = statedArg - computedArg; if (Math.abs(differenceCents) > STATED_VAT_TOLERANCE_CENTS) { throw new RecipeRefusalError( 'vat_amount_off_rate', `vatCents ${statedArg} is not the tax of the group at ${rateArg} %, which is ${computedArg} (a stated tax may differ by ${STATED_VAT_TOLERANCE_CENTS} cent at most)`, { field: 'groups.vatCents', amountCents: statedArg, differenceCents, toleranceCents: STATED_VAT_TOLERANCE_CENTS, ratePercent: rateArg, scenario: scenarioArg }, ); } return { vatCents: statedArg, stated: differenceCents !== 0 }; } /** * A scenario without German VAT takes a stated tax of 0 only: any other, * a cent included, is refused (`vat_amount_off_rate`), since the recipe books * no tax it could carry. */ function refuseStatedVatWithoutGermanVat(statedArg: TCents | undefined, scenarioArg: TTaxScenario): void { if (statedArg !== undefined && statedArg !== 0) { throw new RecipeRefusalError('vat_amount_off_rate', `vatCents ${statedArg} on scenario '${scenarioArg}', which books no German VAT`, { field: 'groups.vatCents', amountCents: statedArg, differenceCents: statedArg, toleranceCents: 0, ratePercent: 0, scenario: scenarioArg, }); } } /** * The entry of a document's durchlaufende Posten (§ 10 Abs. 1 Satz 6 UStG): * the personal account against `policy.passThrough`, without VAT and without a * BU key, with the document's numbers, so it books on the document's open * item. For a customer a positive amount is owed by the customer (debtor * debit, pass-through credit), for a vendor owed to the vendor (pass-through * debit, creditor credit); a negative amount swaps both sides. `undefined` for * none. The account may carry no DATEV tax automatism and no UStVA mark: the * amounts are no turnover and no input tax. */ function passThroughEntry( counterpartyArg: { kind: 'customer' | 'vendor'; account: string }, passThroughCentsArg: TCents | undefined, policy: IAccountPolicy, base: Parameters[0], ): IJournalDraft | undefined { if (passThroughCentsArg === undefined || passThroughCentsArg === 0) { return undefined; } const account = policy.passThrough; if (account === undefined) { throw new RecipeRefusalError( 'pass_through_account_missing', 'the policy names no passThrough account, where durchlaufende Posten are booked', { field: 'passThrough' }, ); } if (isAutomatikAccount(policy, account) || isVatMarkedAccount(policy, account)) { throw new RecipeRefusalError( 'pass_through_account_not_allowed', `the policy's passThrough account ${account} has a DATEV tax automatism or is marked for the UStVA; durchlaufende Posten bear no VAT`, { field: 'passThrough', account }, ); } // a customer's open item rises on the debit side, a vendor's on the credit side const counterpartyDebit = counterpartyArg.kind === 'customer' ? passThroughCentsArg > 0 : passThroughCentsArg < 0; const amountCents = Math.abs(passThroughCentsArg); return makeDraft(base, policy, [ { accountNumber: counterpartyArg.account, counterAccount: account, side: counterpartyDebit ? 'debit' : 'credit', amountCents }, { accountNumber: account, counterAccount: counterpartyArg.account, side: counterpartyDebit ? 'credit' : 'debit', amountCents }, ]); } /** * A customer document with VAT groups of either sign — an invoice with a * credited line at another rate, or a correction that lowers one rate and * raises another — booked as one set of entries, one per group, each with its * own sign: a positive group as an invoice (debtor debit gross, revenue credit * net, output VAT credit), a negative group as a correction of it (the same * accounts, both sides swapped). The sign of the document's total does not * matter; a document whose groups offset each other books both and leaves the * open item unchanged. * * Every entry of the set carries the document's numbers (`TBookedDocument`), * so they all book on one open item: an invoice's own number, or for a * correction the corrected invoice's number in Belegfeld 1 and its own in * `reference`. One entry per group is also what keeps the DATEV export valid: * each entry consolidates into one Buchungssatz per group — the revenue * account against the debtor with the group's BU key — the way a single-group * invoice or credit note does. Each group is taxed on its own: § 17 Abs. 1 * Satz 1 UStG corrects the tax of the rate whose Bemessungsgrundlage changes, * and the UStVA reads each group on its own revenue account. * * Returns the entries in the order of `groups`; a group of zero books nothing. */ export function bookCustomerDocument( input: ICustomerDocumentInput, policy: IAccountPolicy, ): IJournalDraft[] { const identity = documentIdentity(input.document, input.date); if (input.groups.some((group) => group.nonDeductibleVatCents !== undefined && group.nonDeductibleVatCents !== 0)) { throw new RecipeRefusalError( 'non_deductible_vat_invalid', 'nonDeductibleVatCents is a purchase\'s: the tax of a sale is owed, not deducted', { field: 'groups.nonDeductibleVatCents' }, ); } if (input.groups.some((group) => group.reverseChargeParagraph !== undefined)) { throw new RecipeRefusalError( 'reverse_charge_paragraph_invalid', 'reverseChargeParagraph is a purchase\'s: on a sale under § 13b the recipient owes the tax, which these books neither owe nor declare as a base', { field: 'groups.reverseChargeParagraph' }, ); } const entries = bookableGroups(input.groups, input.passThroughCents).map((group) => { const scenario = group.scenario ?? 'domestic_standard'; return buildCustomerDocument( { date: input.date, customerAccount: input.customerAccount, revenueAccount: group.account, grossCents: Math.abs(group.amountCents), vatRatePercent: group.vatRatePercent, vatCents: statedVatOf(group), scenario, otherEuStateSupply: group.otherEuStateSupply, placeOfSupply: group.placeOfSupply, description: input.description, costCenter1: input.costCenter1, docLink: input.docLink, }, policy, group.amountCents > 0 ? 'invoice' : 'credit_note', { date: input.date, description: input.description, scenario, ...identity, costCenter1: input.costCenter1, docLink: input.docLink, }, ); }); const passThrough = passThroughEntry({ kind: 'customer', account: input.customerAccount }, input.passThroughCents, policy, { date: input.date, description: input.description, ...identity, costCenter1: input.costCenter1, docLink: input.docLink, }); return passThrough ? [...entries, passThrough] : entries; } /** * A vendor document with VAT groups of either sign, booked as one set of * entries, one per group, each with its own sign: a positive group as a vendor * invoice (expense debit, Vorsteuer debit, creditor credit), a negative group * as a correction of it (the same accounts, both sides swapped), for every * scenario `bookVendorInvoice` books (§ 13b and intra-EU acquisitions with * their paired VAT). § 17 Abs. 1 Satz 2 UStG corrects the Vorsteuer of the * recipient, and Satz 5 applies that to intra-Community acquisitions (§ 1 * Abs. 1 Nr. 5) and to § 13b. The numbers follow * `TBookedDocument` as in `bookCustomerDocument`: a vendor's credit note names * the vendor's invoice it corrects in Belegfeld 1, so it books on that * invoice's open item. * * The part of the expense that is not deductible (`nondeductibleExpense`, * such as a business meal's 30 %) is split over the groups by their expense * and booked on its own account beside each group's account. * * Returns the entries in the order of `groups`; a group of zero books nothing. */ export function bookVendorDocument( input: IVendorDocumentInput, policy: IAccountPolicy, ): IJournalDraft[] { const identity = documentIdentity(input.document, input.date); const groups = bookableGroups(input.groups, input.passThroughCents); const nondeductibleShares = nondeductibleSharesOf(input.nondeductibleExpense, groups, input.vendorAccount, policy); const entries = groups.map((group, index) => { const scenario = group.scenario ?? 'domestic_standard'; const nondeductibleShare = nondeductibleShares?.[index] ?? 0; const paragraph = reverseChargeParagraphOf(group.reverseChargeParagraph, scenario, 'groups.reverseChargeParagraph'); return buildVendorDocument( { date: input.date, vendorAccount: input.vendorAccount, expenseAccount: group.account, grossCents: Math.abs(group.amountCents), vatRatePercent: group.vatRatePercent, vatCents: statedVatOf(group), nonDeductibleVatCents: groupNonDeductibleOf(group), ...(paragraph !== undefined ? { reverseChargeParagraph: paragraph } : {}), ...(input.nondeductibleExpense !== undefined && nondeductibleShare > 0 ? { nondeductibleExpense: { account: input.nondeductibleExpense.account, amountCents: nondeductibleShare } } : {}), scenario, description: input.description, costCenter1: input.costCenter1, docLink: input.docLink, }, policy, group.amountCents > 0 ? 'invoice' : 'credit_note', { date: input.date, description: input.description, scenario, ...identity, costCenter1: input.costCenter1, ...(input.costCenter2 !== undefined ? { costCenter2: input.costCenter2 } : {}), docLink: input.docLink, }, ); }); const passThrough = passThroughEntry({ kind: 'vendor', account: input.vendorAccount }, input.passThroughCents, policy, { date: input.date, description: input.description, ...identity, costCenter1: input.costCenter1, ...(input.costCenter2 !== undefined ? { costCenter2: input.costCenter2 } : {}), docLink: input.docLink, }); return passThrough ? [...entries, passThrough] : entries; } /** * The shares of the vendor document's groups in the part of its expense that * is not deductible (`IVendorDocumentInput.nondeductibleExpense`), in the * order of the groups: split by the groups' expense, the cents the split * leaves by the largest remainder. `undefined` for a document without it. * Refuses what the field's documentation names (`nondeductible_expense_invalid`). */ function nondeductibleSharesOf( partArg: INondeductibleExpense | undefined, groupsArg: IDocumentVatGroup[], vendorAccountArg: string, policy: IAccountPolicy, ): TCents[] | undefined { if (partArg === undefined) { return undefined; } const refusal = (messageArg: string, detailsArg: IRecipeRefusalDetails): RecipeRefusalError => new RecipeRefusalError('nondeductible_expense_invalid', messageArg, detailsArg); const account = partArg.account; if (typeof account !== 'string' || account.trim() === '' || account === vendorAccountArg) { throw refusal(`nondeductibleExpense.account ${String(account)} names no account beside the vendor's`, { field: 'nondeductibleExpense.account', account: String(account) }); } if (!isProfitAndLossAccount(policy, account, 'expense') || isAutomatikAccount(policy, account) || isVatMarkedAccount(policy, account)) { throw refusal( `nondeductibleExpense.account ${account} is no expense account of ${chartOf(policy)}, or it books a tax of its own (a DATEV tax automatism, a mark for the UStVA)`, { field: 'nondeductibleExpense.account', account }, ); } const amountCents = partArg.amountCents; if (!Number.isSafeInteger(amountCents) || amountCents <= 0) { throw refusal(`nondeductibleExpense.amountCents must be a positive integer cent amount, got ${amountCents}`, { field: 'nondeductibleExpense.amountCents', amountCents }); } const expenses = groupsArg.map((group) => { const scenario = group.scenario ?? 'domestic_standard'; if (group.amountCents < 0) { throw refusal(`a group of ${group.amountCents} lowers the document: a part that is not deductible is a purchase's, not a correction's`, { field: 'groups.amountCents', amountCents: group.amountCents, }); } if (scenario === 'reverse_charge_13b' || scenario === 'intra_eu_acquisition') { throw refusal(`a part that is not deductible is not split off a group under '${scenario}', whose recipient owes the tax`, { field: 'groups.scenario', scenario }); } return vendorGroupExpenseOf(group, scenario); }); const expenseCents = expenses.reduce((sum, cents) => sum + cents, 0); if (amountCents > expenseCents) { throw refusal(`nondeductibleExpense.amountCents ${amountCents} exceeds the document's expense of ${expenseCents} cents`, { field: 'nondeductibleExpense.amountCents', amountCents, differenceCents: amountCents - expenseCents, }); } return allocateCents(amountCents, expenses); } /** * What a vendor document's group costs the books, as `buildVendorDocument` * books it on the expense account: its amount less the input tax it deducts; * all of it for a group without German VAT. A tax off its rate or excluded * beyond itself is refused there, when the group is booked. */ function vendorGroupExpenseOf(groupArg: IDocumentVatGroup, scenarioArg: TTaxScenario): TCents { const grossCents = Math.abs(groupArg.amountCents); if (scenarioArg !== 'domestic_standard' && scenarioArg !== 'domestic_reduced') { return grossCents; } const rate = vendorRateOf(scenarioArg, groupArg.vatRatePercent); const { vatCents } = documentVatOf(splitGrossCents(grossCents, rate).vatCents, statedVatOf(groupArg), rate, scenarioArg); const excludedCents = Math.min(groupNonDeductibleOf(groupArg) ?? 0, vatCents); return grossCents - vatCents + excludedCents; } /** * The account an excess of a bank payment is booked to (`IBankPaymentInput.excess`) * takes it as a plain amount in the profit and loss, outside the VAT return. * Allowed only is an account that: * - is an account of the chart in use (`policy.skrType`, @fin.cx/chartdata * 2026) — so no personal account, and nothing the chart does not hold; * - is a profit-and-loss account by the chart's classification * (`CHART_PROFIT_AND_LOSS_ACCOUNTS`: type `expense` or `revenue` with an * income-statement position, HGB § 275), or an individual account of the * books under one (`isProfitAndLossAccount`) — so no balance-sheet account: no * bank, no VAT receivable or liability, no personal or clearing account; * - is an expense for an outgoing excess and income for an incoming one; * - is none the chart marks for the UStVA or with a DATEV tax automatism * (`CHART_VAT_ACCOUNTS`), nor an individual account that takes its parent's * UStVA mapping (`isVatMarkedAccount`), and no Automatikkonto or VAT account * of the policy (`automatikkonten`, `vat`, `vatSettlement`). * An excess named when nothing moved beyond the expected amount is refused. */ function assertExcessAccount(account: string, input: IBankPaymentInput, bank: string, policy: IAccountPolicy): void { const excessRefusal = (accountArg: string, messageArg: string): RecipeRefusalError => new RecipeRefusalError('excess_account_not_allowed', messageArg, { field: 'excess.account', account: accountArg, direction: input.direction }); if (typeof account !== 'string' || account.trim() === '') { throw new RecipeRefusalError('excess_account_required', 'excess.account names no account', { field: 'excess.account' }); } if (account === bank || account === input.counterpartyAccount) { throw excessRefusal(account, `excess.account ${account} is the bank or the personal account of this payment; the excess is booked apart from both`); } const wanted = input.direction === 'outgoing' ? 'expense' : 'income'; if (!isProfitAndLossAccount(policy, account, wanted)) { throw excessRefusal(account, isProfitAndLossAccount(policy, account, wanted === 'expense' ? 'income' : 'expense') ? `excess.account ${account} is ${input.direction === 'outgoing' ? 'income' : 'an expense'} in ${policy.skrType}; an ${input.direction} excess goes to ${input.direction === 'outgoing' ? 'an expense' : 'income'}` : `excess.account ${account} is no profit-and-loss account of ${policy.skrType} (a balance-sheet account, a personal account, or none the chart holds); an excess goes to the profit and loss`); } if (isAutomatikAccount(policy, account)) { throw excessRefusal(account, `excess.account ${account} is an Automatikkonto, which books VAT by itself; an excess is booked without VAT`); } if (Object.values(policy.vat).includes(account) || Object.values(policy.vatSettlement).includes(account)) { throw excessRefusal(account, `excess.account ${account} is a VAT account; an excess is booked without VAT`); } if (isVatMarkedAccount(policy, account)) { throw excessRefusal(account, `excess.account ${account} is marked in ${policy.skrType} for the UStVA or with a tax automatism; an excess is booked without VAT, outside the VAT return`); } if (input.paidCents <= input.expectedCents) { throw new RecipeRefusalError( 'excess_not_applicable', `excess.account is named, but ${input.paidCents} cents moved for ${input.expectedCents} expected: nothing moved beyond the open item`, { field: 'excess', account, direction: input.direction }, ); } } /** The rates the policy holds a Skonto account and a VAT account for. */ const SKONTO_VAT_RATES: readonly number[] = [19, 7]; function assertSkontoVatRate(ratePercent: number, label: string): void { if (!SKONTO_VAT_RATES.includes(ratePercent)) { throw new RecipeRefusalError( 'skonto_rate_unsupported', `${label} is ${ratePercent}: a Skonto is booked at 19 % or 7 %, where the policy holds its Skonto and VAT accounts; a part without VAT goes in \`shares\` at 0 % with the account it reduces`, { field: label, ratePercent }, ); } } /** * The account a part at 0 % books its share of the Skonto on, without VAT: * a profit-and-loss account of the chart in use (`CHART_PROFIT_AND_LOSS_ACCOUNTS`, * or an individual account of the books under one: `isProfitAndLossAccount`), * income for a sale (incoming) and an expense for a purchase (outgoing), and * none whose DATEV automatism books VAT at a rate * (`CHART_VAT_RATE_AUTOMATIK_ACCOUNTS`), nor a Skonto or VAT account of the * policy. A tax-free automatism (e.g. SKR03 8125) is allowed: it books no VAT. */ function assertSkontoAccountWithoutVat(account: unknown, label: string, input: IBankPaymentInput, bank: string, policy: IAccountPolicy): void { if (typeof account !== 'string' || account.trim() === '') { throw new RecipeRefusalError( 'skonto_account_required', `${label}.account is required for a part at 0 %: the chart holds no Skonto account without VAT, so name the account the part's share reduces`, { field: `${label}.account` }, ); } if (account === bank || account === input.counterpartyAccount) { throw skontoAccountRefusal(label, account, `${label}.account ${account} is the bank or the personal account of this payment`); } if (!isProfitAndLossAccount(policy, account, input.direction === 'outgoing' ? 'expense' : 'income')) { throw skontoAccountRefusal( label, account, `${label}.account ${account} is no ${input.direction === 'outgoing' ? 'expense' : 'income'} account of ${policy.skrType}; the Skonto of ${input.direction === 'outgoing' ? 'a purchase reduces an expense' : 'a sale reduces income'}`, ); } if ( accountRateMismatchOf(policy, account, undefined) !== undefined || Object.values(policy.skonto).includes(account) || Object.values(policy.vat).includes(account) || Object.values(policy.vatSettlement).includes(account) ) { throw skontoAccountRefusal(label, account, `${label}.account ${account} books VAT at a rate; a part at 0 % is booked without VAT`); } } /** * The account a part at 19 % or 7 % names to book its share on instead of * the policy's Skonto account: the account the part was booked on, reduced * with the VAT correction at the rate. A profit-and-loss account of the chart * in use, income for a sale and an expense for a purchase, whose DATEV * automatism, if it has one, books VAT at the same rate * (`CHART_VAT_AUTOMATIK_RATES`), and which the chart does not mark for the * UStVA otherwise (`CHART_VAT_ACCOUNTS`: tax-free revenue, revenue taxable * abroad, whose Kennzahl takes no correction of German VAT). */ function assertSkontoAccountAtRate( account: unknown, ratePercent: number, label: string, input: IBankPaymentInput, bank: string, policy: IAccountPolicy, ): void { if (typeof account !== 'string' || account.trim() === '') { throw new RecipeRefusalError( 'skonto_account_required', `${label}.account names no account; leave it unset to book the share on the policy's Skonto account of the rate`, { field: `${label}.account` }, ); } if (account === bank || account === input.counterpartyAccount) { throw skontoAccountRefusal(label, account, `${label}.account ${account} is the bank or the personal account of this payment`); } if (!isProfitAndLossAccount(policy, account, input.direction === 'outgoing' ? 'expense' : 'income')) { throw skontoAccountRefusal( label, account, `${label}.account ${account} is no ${input.direction === 'outgoing' ? 'expense' : 'income'} account of ${policy.skrType}; the Skonto of ${input.direction === 'outgoing' ? 'a purchase reduces an expense' : 'a sale reduces income'}`, ); } const mismatch = accountRateMismatchOf(policy, account, ratePercent); if (mismatch) { throw skontoAccountRefusal( label, account, mismatch.automatikRatePercent !== undefined ? `${label}.account ${account} books VAT at ${mismatch.automatikRatePercent} % by its automatism; the share of a part at ${ratePercent} % is corrected at ${ratePercent} %` : `${label}.account ${account} is marked in ${policy.skrType} for the UStVA without VAT at ${ratePercent} %; the share of a part at ${ratePercent} % reduces an account of that rate`, ); } } function skontoAccountRefusal(label: string, account: string, message: string): RecipeRefusalError { return new RecipeRefusalError('skonto_account_not_allowed', message, { field: `${label}.account`, account }); } /** * A part taxed in another member state: a sale's (`incoming`), without German * VAT, with that state's rate (0 or more) and the kind of supply, on the * revenue account it lowers — an income account of the chart without an * automatism at a rate, as a part at 0 % takes. */ function assertSkontoOtherEuState(share: ISkontoShare, label: string, input: IBankPaymentInput, bank: string, policy: IAccountPolicy): void { const other = share.otherEuState as ISkontoOtherEuState; if (input.direction !== 'incoming') { throw new RecipeRefusalError( 'skonto_other_eu_state_on_purchase', `${label}.otherEuState is a sale's: the Skonto of a purchase on which another member state charged VAT corrects no German input tax — give the part at 0 % with the expense account it lowers`, { field: `${label}.otherEuState`, direction: input.direction }, ); } if (share.ratePercent !== 0) { throw new RecipeRefusalError( 'skonto_other_eu_state_with_german_rate', `${label}.ratePercent is ${share.ratePercent}: a part taxed in another member state carries no German VAT; give it at 0 % with that state's rate in otherEuState`, { field: `${label}.ratePercent`, ratePercent: share.ratePercent }, ); } if (typeof other.ratePercent !== 'number' || !Number.isFinite(other.ratePercent) || other.ratePercent < 0) { throw new RecipeRefusalError( 'other_eu_state_rate_required', `${label}.otherEuState.ratePercent must be the rate of the member state the part is taxed in, got ${other.ratePercent}`, { field: `${label}.otherEuState.ratePercent`, ...(typeof other.ratePercent === 'number' ? { ratePercent: other.ratePercent } : {}) }, ); } if (other.supply !== 'goods' && other.supply !== 'electronic_services' && other.supply !== 'other_services') { throw new RecipeRefusalError( 'other_eu_state_supply_required', `${label}.otherEuState.supply must be 'goods', 'electronic_services' or 'other_services', got ${other.supply}`, { field: `${label}.otherEuState.supply` }, ); } assertSkontoAccountWithoutVat(share.account, label, input, bank, policy); } /** * A part whose recipient owes the German tax (`ISkontoShare.selfAssessed`): * a purchase's, at 19 or 7 %, on the expense account the part was booked * on — one of the chart, which is neither the bank nor the creditor, nor a * Skonto or VAT account of the policy, and without a DATEV tax automatism * (`refuseSelfAssessedAutomatik`: it would book domestic Vorsteuer on import * next to the self-assessed pair, and carry key 40) — and neither taxed in * another member state nor not taxable here. */ function assertSkontoSelfAssessed(share: ISkontoShare, label: string, input: IBankPaymentInput, bank: string, policy: IAccountPolicy): void { if (share.otherEuState !== undefined || share.notTaxableHere !== undefined) { throw new RecipeRefusalError( 'skonto_self_assessed_conflict', `${label} names selfAssessed and ${share.otherEuState !== undefined ? 'otherEuState' : 'notTaxableHere'}: a part whose recipient owes the German tax is taxable here`, { field: label }, ); } if (share.selfAssessed !== 'reverse_charge_13b' && share.selfAssessed !== 'intra_eu_acquisition') { throw new RecipeRefusalError( 'skonto_self_assessed_conflict', `${label}.selfAssessed must be 'reverse_charge_13b' or 'intra_eu_acquisition', got ${String(share.selfAssessed)}`, { field: `${label}.selfAssessed` }, ); } if (input.direction !== 'outgoing') { throw new RecipeRefusalError( 'skonto_self_assessed_on_sale', `${label}.selfAssessed is a purchase's: on a sale the recipient owes the tax, which these books neither owe nor deduct — give the part at 0 % with the revenue account it lowers`, { field: `${label}.selfAssessed`, direction: input.direction }, ); } assertSkontoVatRate(share.ratePercent, `${label}.ratePercent`); const account = share.account; if (typeof account !== 'string' || account.trim() === '') { throw new RecipeRefusalError( 'skonto_account_required', `${label}.account is required for a part whose recipient owes the tax: the chart holds no Skonto account for it, so name the expense account the part was booked on`, { field: `${label}.account` }, ); } if (account === bank || account === input.counterpartyAccount) { throw skontoAccountRefusal(label, account, `${label}.account ${account} is the bank or the personal account of this payment`); } if (!isProfitAndLossAccount(policy, account, 'expense')) { throw skontoAccountRefusal(label, account, `${label}.account ${account} is no expense account of ${policy.skrType}; the Skonto of a purchase reduces an expense`); } if ( Object.values(policy.skonto).includes(account) || Object.values(policy.vat).includes(account) || Object.values(policy.vatSettlement).includes(account) ) { throw skontoAccountRefusal(label, account, `${label}.account ${account} is a Skonto or VAT account of the policy; name the expense account the part was booked on`); } // as its invoice: on an Automatikkonto the share would carry key 40, outside the scenario's UStVA field refuseSelfAssessedAutomatik(account, `${label}.account`, share.selfAssessed, policy); } /** * A part whose tax was deducted in part (`ISkontoShare.deductiblePercent`): a * purchase's, with German VAT at a rate (domestic or `selfAssessed`, whose * own checks follow), not `nonDeductible`, by a key above 0 and below 100 %. * A domestic part names the expense account it was booked on, where the rest * of its tax was cost, and one without a DATEV automatism at a rate: its line * carries no key, so the automatism would book the tax again on import. */ function assertSkontoDeductiblePercent(share: ISkontoShare, label: string, input: IBankPaymentInput, policy: IAccountPolicy): void { const field = `${label}.deductiblePercent`; if (input.direction !== 'outgoing') { throw new RecipeRefusalError('non_deductible_vat_invalid', `${field} is a purchase's: the tax of a sale is owed, not deducted`, { field }); } if (share.nonDeductible !== undefined) { throw new RecipeRefusalError( 'non_deductible_vat_invalid', `${label} names nonDeductible and deductiblePercent: its tax was deducted either not at all or in part`, { field }, ); } if (share.otherEuState !== undefined || share.notTaxableHere !== undefined || share.ratePercent === 0) { throw new RecipeRefusalError( 'non_deductible_vat_invalid', `${field} belongs to a part with German VAT at a rate; a part without it has no tax to deduct`, { field }, ); } deductibleBasisPointsOf(share.deductiblePercent, field); if (share.selfAssessed === undefined) { if (share.account === undefined) { throw new RecipeRefusalError( 'skonto_account_required', `${label}.account is required for a part whose tax was deducted in part: name the expense account it was booked on, where the rest of its tax was cost`, { field: `${label}.account` }, ); } const mismatch = accountRateMismatchOf(policy, share.account, undefined); if (mismatch) { throw skontoAccountRefusal( label, share.account, `${label}.account ${share.account} books VAT at ${mismatch.automatikRatePercent} % by its DATEV automatism; a part whose tax was deducted in part is booked without a key, so name an account without it`, ); } } } /** The policy's VAT account of another member state for a kind of supply. */ function otherEuStateVatAccount(policy: IAccountPolicy, supply: TOtherEuStateSupply): string { return supply === 'goods' ? policy.vat.otherEuStateGoods : supply === 'electronic_services' ? policy.vat.otherEuStateElectronicServices : policy.vat.otherEuStateServices; } /** Refuse a Skonto the recipe cannot book right, before anything is booked. */ function assertSkonto(skonto: TBankPaymentSkonto, input: IBankPaymentInput, bank: string, policy: IAccountPolicy): void { if ('shares' in skonto) { if (!Array.isArray(skonto.shares) || skonto.shares.length === 0) { throw new RecipeRefusalError('skonto_shares_missing', 'skonto.shares names no share', { field: 'skonto.shares' }); } const seen = new Set(); skonto.shares.forEach((share, index) => { const label = `skonto.shares[${index}]`; assertPositive(share.grossCents, `${label}.grossCents`); if (share.selfAssessed === undefined && share.notTaxableHere !== undefined && (share.otherEuState !== undefined || share.ratePercent !== 0)) { throw new RecipeRefusalError( 'skonto_other_eu_state_case_required', share.otherEuState !== undefined ? `${label} names both otherEuState and notTaxableHere; a part is either taxed in another member state or not taxable there` : `${label}.notTaxableHere belongs to a part at 0 %, not to one at ${share.ratePercent} %`, { field: label, ...(share.account !== undefined ? { account: share.account } : {}) }, ); } if (share.nonDeductible !== undefined && (share.nonDeductible !== true || share.selfAssessed === undefined)) { throw new RecipeRefusalError( 'non_deductible_vat_invalid', `${label}.nonDeductible belongs to a part whose recipient owes the tax (selfAssessed); a part with German VAT it does not deduct is given at 0 % on its expense account`, { field: `${label}.nonDeductible` }, ); } if (share.deductiblePercent !== undefined) { assertSkontoDeductiblePercent(share, label, input, policy); } if (share.reverseChargeParagraph !== undefined) { // the line rule of keys 91 and 94: the paragraph of a part whose recipient owes the tax under § 13b only reverseChargeParagraphOf(share.reverseChargeParagraph, share.selfAssessed === 'reverse_charge_13b' ? 'reverse_charge_13b' : undefined, `${label}.reverseChargeParagraph`); } if (share.selfAssessed !== undefined) { assertSkontoSelfAssessed(share, label, input, bank, policy); } else if (share.otherEuState !== undefined) { assertSkontoOtherEuState(share, label, input, bank, policy); } else if (share.ratePercent === 0) { assertSkontoAccountWithoutVat(share.account, label, input, bank, policy); // the chart marks it for the UStVA without an automatism: revenue taxed in another member state, whose tax // there the share lowers too const account = share.account as string; const subject = vatCheckAccountOf(policy, account); if (CHART_VAT_ACCOUNTS[chartOf(policy)].includes(subject) && !CHART_AUTOMATIK_ACCOUNTS[chartOf(policy)].includes(subject)) { throw new RecipeRefusalError( 'skonto_other_eu_state_required', `${label}.account ${account} is revenue taxed in another member state; its share lowers that state's tax too — name that state's rate and the kind of supply in ${label}.otherEuState`, { field: `${label}.otherEuState`, account }, ); } // the policy's account of services taxed in another member state: that state's tax is lowered too, unless it // also takes turnover not taxable here and the part says it is that if (account === policy.revenue.otherEuStateServices) { const shared = account === policy.revenue.notTaxableHereEu || account === policy.revenue.notTaxableHereThirdCountry; if (!shared) { throw new RecipeRefusalError( 'skonto_other_eu_state_required', `${label}.account ${account} is revenue taxed in another member state; its share lowers that state's tax too — name that state's rate and the kind of supply in ${label}.otherEuState`, { field: `${label}.otherEuState`, account }, ); } if (share.notTaxableHere !== true) { throw new RecipeRefusalError( 'skonto_other_eu_state_case_required', `${label}.account ${account} takes both services taxed in another member state and turnover not taxable here: name that state's rate in ${label}.otherEuState, or set ${label}.notTaxableHere`, { field: label, account }, ); } } } else { assertSkontoVatRate(share.ratePercent, `${label}.ratePercent`); if (share.account !== undefined) { assertSkontoAccountAtRate(share.account, share.ratePercent, label, input, bank, policy); } } const key = `${share.ratePercent}|${share.account ?? ''}|${share.otherEuState ? `${share.otherEuState.ratePercent}|${share.otherEuState.supply}` : ''}|${share.selfAssessed ?? ''}|${share.nonDeductible === true ? 'nd' : ''}|${share.deductiblePercent ?? ''}|${share.reverseChargeParagraph ?? ''}`; if (seen.has(key)) { throw new RecipeRefusalError( 'skonto_share_duplicate', share.account !== undefined ? `${label} names the part at ${share.ratePercent} % on ${share.account} a second time` : `${label} names the part at ${share.ratePercent} % a second time`, { field: label }, ); } seen.add(key); }); } else { assertSkontoVatRate(skonto.ratePercent, 'skonto.ratePercent'); } } /** * The lines of a Skonto of `skontoCents`: per rate the Skonto account with * the net share (key 40 — the explicit VAT line cancels the automatism) and * the VAT correction, per part at 0 % the named account with the whole share. * Purchases credit them (erhaltene Skonti), sales debit them (gewährte Skonti). */ function skontoLines(skonto: TBankPaymentSkonto, skontoCents: TCents, input: IBankPaymentInput, policy: IAccountPolicy): ILineSpec[] { const parts: Array< | { kind: 'rate'; ratePercent: number; cents: TCents; account?: string; deductiblePercent?: number } | { kind: 'withoutVat'; account: string; cents: TCents } | { kind: 'otherEuState'; account: string; cents: TCents; otherEuState: ISkontoOtherEuState } | { kind: 'selfAssessed'; account: string; cents: TCents; ratePercent: number; scenario: TSelfAssessedScenario; nonDeductible: boolean; deductiblePercent?: number; reverseChargeParagraph?: TReverseChargeParagraph; } > = []; if ('shares' in skonto) { const baseCents = skonto.shares.reduce((sum, share) => sum + share.grossCents, 0); if (skontoCents > baseCents) { throw new RecipeRefusalError( 'skonto_exceeds_shares', `A Skonto of ${skontoCents} cents exceeds the ${baseCents} cents of the shares it was granted on`, { field: 'skonto.shares', amountCents: skontoCents }, ); } const allocated = allocateCents(skontoCents, skonto.shares.map((share) => share.grossCents)); skonto.shares.forEach((share, index) => { if (share.selfAssessed !== undefined && share.account !== undefined) { parts.push({ kind: 'selfAssessed', account: share.account, cents: allocated[index], ratePercent: share.ratePercent, scenario: share.selfAssessed, nonDeductible: share.nonDeductible === true, ...(share.deductiblePercent !== undefined ? { deductiblePercent: share.deductiblePercent } : {}), ...(share.reverseChargeParagraph !== undefined ? { reverseChargeParagraph: share.reverseChargeParagraph } : {}), }); } else if (share.otherEuState !== undefined && share.account !== undefined) { parts.push({ kind: 'otherEuState', account: share.account, cents: allocated[index], otherEuState: share.otherEuState }); } else if (share.ratePercent !== 0) { parts.push({ kind: 'rate', ratePercent: share.ratePercent, cents: allocated[index], ...(share.account !== undefined ? { account: share.account } : {}), ...(share.deductiblePercent !== undefined ? { deductiblePercent: share.deductiblePercent } : {}), }); } else if (share.account !== undefined) { parts.push({ kind: 'withoutVat', account: share.account, cents: allocated[index] }); } else { // assertSkonto refused such a share before: an invariant, not a refusal throw new Error(`skonto.shares[${index}].account is required for a part at 0 %`); } }); } else { parts.push({ kind: 'rate', ratePercent: skonto.ratePercent, cents: skontoCents }); } const purchase = input.direction === 'outgoing'; const side = purchase ? 'credit' : 'debit'; const lines: ILineSpec[] = []; for (const part of parts) { if (part.kind === 'withoutVat') { lines.push({ accountNumber: part.account, counterAccount: input.counterpartyAccount, side, amountCents: part.cents }); continue; } if (part.kind === 'selfAssessed') { // the share lowers the base; the tax on it at the part's rate lowers both the tax owed and its deduction // (§ 17 Abs. 1 Satz 5 UStG), the invoice's pair of lines swapped; its key lets DATEV book that pair itself const vatCents = vatFromNetCents(part.cents, part.ratePercent); const inputVatAccount = part.scenario === 'reverse_charge_13b' ? policy.vat.reverseChargeInput : policy.vat.intraEuAcqInput; const outputVatAccount = part.scenario === 'reverse_charge_13b' ? policy.vat.reverseChargeOutput : policy.vat.intraEuAcqOutput; const buKey = suggestBuKey({ direction: 'inbound', scenario: part.scenario, ratePercent: part.ratePercent, targetIsAutomatik: isAutomatikAccount(policy, part.account), hasExplicitVatLines: vatCents > 0, }); lines.push({ accountNumber: part.account, counterAccount: input.counterpartyAccount, side: 'credit', amountCents: part.cents, buKey, ...(part.reverseChargeParagraph !== undefined && isReverseChargeBuKey(buKey) ? { reverseChargeParagraph: part.reverseChargeParagraph } : {}), }); lines.push( { accountNumber: inputVatAccount, counterAccount: outputVatAccount, side: 'credit', amountCents: vatCents }, { accountNumber: outputVatAccount, counterAccount: inputVatAccount, side: 'debit', amountCents: vatCents }, ); if (part.nonDeductible || part.deductiblePercent !== undefined) { // the tax owed not deducted was cost: of the deduction lowered in full, the part not deducted is given back to // the input tax from the expense, a booking of its own without a key, as the invoice took it back const deductibleCents = part.deductiblePercent === undefined ? 0 : deductibleVatCentsOf(vatCents, part.deductiblePercent); lines.push(...inputTaxCorrectionLines(part.account, inputVatAccount, vatCents - deductibleCents, 'credit')); } continue; } if (part.kind === 'otherEuState') { // the net lowers the revenue, that state's tax lowers the liability to it; no German key on either const { netCents, vatCents } = splitGrossCents(part.cents, part.otherEuState.ratePercent); lines.push({ accountNumber: part.account, counterAccount: input.counterpartyAccount, side, amountCents: netCents }); lines.push({ accountNumber: otherEuStateVatAccount(policy, part.otherEuState.supply), counterAccount: input.counterpartyAccount, side, amountCents: vatCents, }); continue; } const reduced = part.ratePercent === 7; const { netCents, vatCents } = splitGrossCents(part.cents, part.ratePercent); // a tax deducted in part: only that part lowers the input tax, the rest was cost and lowers the account with the net const deductibleCents = part.deductiblePercent === undefined ? vatCents : deductibleVatCentsOf(vatCents, part.deductiblePercent); const skontoAccount = part.account ?? (purchase ? reduced ? policy.skonto.receivedReduced : policy.skonto.receivedStandard : reduced ? policy.skonto.grantedReduced : policy.skonto.grantedStandard); const vatAccount = purchase ? reduced ? policy.vat.inputReduced : policy.vat.inputStandard : reduced ? policy.vat.outputReduced : policy.vat.outputStandard; lines.push({ accountNumber: skontoAccount, counterAccount: input.counterpartyAccount, side, amountCents: netCents + vatCents - deductibleCents, // the policy's Skonto accounts are Automatikkonten: key 40 next to the explicit VAT line; a named account takes // key 40 as an Automatikkonto too, otherwise the key of its rate, into which DATEV folds the VAT line — none // where the tax was deducted in part, which no key computes buKey: part.account === undefined ? vatCents > 0 ? '40' : '' : suggestBuKey({ direction: purchase ? 'inbound' : 'outbound', scenario: reduced ? 'domestic_reduced' : 'domestic_standard', ratePercent: part.ratePercent, targetIsAutomatik: isAutomatikAccount(policy, part.account), hasExplicitVatLines: deductibleCents > 0, vatAsStated: part.deductiblePercent !== undefined, }), }); lines.push({ accountNumber: vatAccount, counterAccount: input.counterpartyAccount, side, amountCents: deductibleCents, }); } return lines; } /** * Bank payment clearing a debtor/creditor open amount, with Skonto * (incl. VAT correction), a small-difference write-off, or an excess booked * to an account the caller names (`excess`, without VAT). * * The Skonto is booked at one rate (`skonto: { ratePercent }`) or split over * the rates of the invoice (`skonto: { shares }`) in proportion to the gross * amount at each: § 17 Abs. 1 Satz 1 UStG corrects the tax of each taxable * Umsatz by the change of its own Bemessungsgrundlage, Satz 2 the input tax * of the recipient alike, and § 22 Abs. 2 Nr. 1 Satz 2 UStG (UStAE 22.2 * Abs. 2 Satz 2) keeps the Entgelte and their later changes apart by rate. * * Direction picks the Skonto side: `outgoing` books erhaltene Skonti with an * input-VAT correction (we pay a creditor less), `incoming` books gewährte * Skonti with an output-VAT correction (a debtor pays us less). Combining a * direction with the wrong kind of counterparty — a refund paid out to a * debtor, or a payment received from a creditor — would book the opposite * VAT, so the combination is refused instead. */ export function bookBankPayment(input: IBankPaymentInput, policy: IAccountPolicy): IJournalDraft { if (input.excess && input.expectedCents === 0) { // a payout wholly beyond the open item: all of it is the excess, and the personal account is not touched } else { assertPositive(input.expectedCents, 'expectedCents'); } assertPositive(input.paidCents, 'paidCents'); if (input.skonto && input.direction === 'outgoing' && isDebtorAccount(policy, input.counterpartyAccount)) { throw new RecipeRefusalError( 'skonto_wrong_counterparty', `Outgoing payment to debtor ${input.counterpartyAccount} must not carry skonto — that branch books erhaltene Skonti with an input-VAT correction. Book the reduction as a customer credit note (bookCustomerCreditNote) and refund the plain amount.`, { field: 'skonto', direction: input.direction, account: input.counterpartyAccount }, ); } if (input.skonto && input.direction === 'incoming' && isCreditorAccount(policy, input.counterpartyAccount)) { throw new RecipeRefusalError( 'skonto_wrong_counterparty', `Incoming payment from creditor ${input.counterpartyAccount} must not carry skonto — that branch books gewährte Skonti with an output-VAT correction.`, { field: 'skonto', direction: input.direction, account: input.counterpartyAccount }, ); } const bank = input.bankAccount ?? policy.bank; const tolerance = input.diffToleranceCents ?? 0; if (input.excess) { assertExcessAccount(input.excess.account, input, bank, policy); } if (input.skonto) { assertSkonto(input.skonto, input, bank, policy); } const base = { date: input.date, description: input.description, reference: input.reference, belegfeld1: input.reference, }; const diff = input.expectedCents - input.paidCents; const lines: ILineSpec[] = []; if (input.direction === 'outgoing') { lines.push( { accountNumber: input.counterpartyAccount, counterAccount: bank, side: 'debit', amountCents: input.expectedCents, }, { accountNumber: bank, counterAccount: input.counterpartyAccount, side: 'credit', amountCents: input.paidCents, }, ); if (diff > 0) { if (input.skonto) { lines.push(...skontoLines(input.skonto, diff, input, policy)); } else if (diff <= tolerance) { lines.push({ accountNumber: policy.roundingDiff.gain, counterAccount: input.counterpartyAccount, side: 'credit', amountCents: diff, }); } else { throw new RecipeRefusalError( 'shortfall_beyond_tolerance', `Underpayment of ${diff} cents exceeds tolerance ${tolerance} — pass skonto or resolve explicitly`, { direction: input.direction, differenceCents: diff, toleranceCents: tolerance }, ); } } else if (diff < 0) { const overpaid = -diff; if (input.excess) { lines.push({ accountNumber: input.excess.account, counterAccount: bank, side: 'debit', amountCents: overpaid, }); } else if (overpaid <= tolerance) { lines.push({ accountNumber: policy.roundingDiff.loss, counterAccount: input.counterpartyAccount, side: 'debit', amountCents: overpaid, }); } else { throw new RecipeRefusalError( 'excess_beyond_tolerance', `Overpayment of ${overpaid} cents exceeds tolerance ${tolerance} — resolve explicitly`, { direction: input.direction, differenceCents: overpaid, toleranceCents: tolerance }, ); } } } else { lines.push( { accountNumber: bank, counterAccount: input.counterpartyAccount, side: 'debit', amountCents: input.paidCents, }, { accountNumber: input.counterpartyAccount, counterAccount: bank, side: 'credit', amountCents: input.expectedCents, }, ); if (diff > 0) { if (input.skonto) { lines.push(...skontoLines(input.skonto, diff, input, policy)); } else if (diff <= tolerance) { lines.push({ accountNumber: policy.roundingDiff.loss, counterAccount: input.counterpartyAccount, side: 'debit', amountCents: diff, }); } else { throw new RecipeRefusalError( 'shortfall_beyond_tolerance', `Short payment of ${diff} cents exceeds tolerance ${tolerance} — pass skonto or resolve explicitly`, { direction: input.direction, differenceCents: diff, toleranceCents: tolerance }, ); } } else if (diff < 0) { const overReceived = -diff; if (input.excess) { lines.push({ accountNumber: input.excess.account, counterAccount: bank, side: 'credit', amountCents: overReceived, }); } else if (overReceived <= tolerance) { lines.push({ accountNumber: policy.roundingDiff.gain, counterAccount: input.counterpartyAccount, side: 'credit', amountCents: overReceived, }); } else { throw new RecipeRefusalError( 'excess_beyond_tolerance', `Over-receipt of ${overReceived} cents exceeds tolerance ${tolerance} — resolve explicitly`, { direction: input.direction, differenceCents: overReceived, toleranceCents: tolerance }, ); } } } return makeDraft(base, policy, lines); } /** * Bank-to-bank transfer via Geldtransit — two drafts, one per bank statement, * so each side reconciles independently. */ export function bookInternalTransfer( input: IInternalTransferInput, policy: IAccountPolicy, ): [IJournalDraft, IJournalDraft] { assertPositive(input.amountCents, 'amountCents'); const base = { date: input.date, description: input.description, reference: input.reference, belegfeld1: input.reference, }; const outgoing = makeDraft(base, policy, [ { accountNumber: policy.geldtransit, counterAccount: input.fromBankAccount, side: 'debit', amountCents: input.amountCents, }, { accountNumber: input.fromBankAccount, counterAccount: policy.geldtransit, side: 'credit', amountCents: input.amountCents, }, ]); const incoming = makeDraft(base, policy, [ { accountNumber: input.toBankAccount, counterAccount: policy.geldtransit, side: 'debit', amountCents: input.amountCents, }, { accountNumber: policy.geldtransit, counterAccount: input.toBankAccount, side: 'credit', amountCents: input.amountCents, }, ]); return [outgoing, incoming]; } /** * A customer's open item settled outside the bank accounts: the account the * money went to debit, the customer's personal account credit, with the * invoice number as Belegfeld 1. The invoice booked the revenue and the VAT * already, so no line carries VAT or a BU key; under the Istversteuerung the * VAT falls due on `date`, the day of the payment. * * Only three kinds of account are allowed: the till (`policy.cash`), the * Privatentnahmen (`policy.privateAccounts.withdrawal`) and the claim against * a shareholder on the account of the company's form, which the input names * (`shareholderForm`, `SHAREHOLDER_CLAIM_ACCOUNTS`); every other account is * refused (`settlement_account_not_allowed`) — a second bank account, PayPal * and any other account of the chart or outside it belong in the books, whose * movements are booked from their statements — and so is a claim account * without its form, or with another form's (`details.field` * `shareholderForm` or `account`). Which fits the legal form is the caller's: * the till for anyone, the Privatentnahmen for a sole trader or a partner, * the claim against a shareholder for a company. The invoice number, where the invoice * names one, is Belegfeld 1, which settles the open item; without one the * payment has no Belegfeld 1, as a bank payment of the invoice would not. A * reference given but blank is refused (`settlement_reference_required`). * * With `expectedCents` the open item is settled in full, and a Skonto or a * rounding difference booked with it exactly as a bank payment of it would * be, on the account the money went to (`bookBankPayment`, `incoming`); a * Skonto or a tolerance without the open item it is measured against is * refused (`settlement_open_item_required`). */ export function bookReceivableSettledOutside(input: IReceivableSettledOutsideInput, policy: IAccountPolicy): IJournalDraft { assertPositive(input.amountCents, 'amountCents'); if (!isDebtorAccount(policy, input.debtorAccount)) { throw new RecipeRefusalError( 'debtor_account_required', `debtorAccount ${input.debtorAccount} is no personal account of a customer in ${policy.skrType} (${policy.debtorRange[0]}–${policy.debtorRange[1]})`, { field: 'debtorAccount', account: input.debtorAccount }, ); } const account = input.account; if (typeof account !== 'string' || account.trim() === '') { throw new RecipeRefusalError('settlement_account_required', 'account names no account the money went to', { field: 'account' }); } if (input.reference !== undefined && (typeof input.reference !== 'string' || input.reference.trim() === '')) { throw new RecipeRefusalError( 'settlement_reference_required', 'reference is given but names no invoice number; in Belegfeld 1 it settles the open item, and an invoice that names none leaves it unset', { field: 'reference' }, ); } // an allow-list: every other account — a second bank account, PayPal, the bank or clearing accounts, any account of // the chart or outside it — is refused, as money on an account of the books is booked from its own statement const shareholderForm = input.shareholderForm; if (shareholderForm !== undefined) { if (!SHAREHOLDER_CLAIM_FORMS.includes(shareholderForm)) { throw new RecipeRefusalError( 'settlement_account_not_allowed', `shareholderForm ${String(shareholderForm)} is none of ${SHAREHOLDER_CLAIM_FORMS.join(', ')}`, { field: 'shareholderForm' }, ); } // the claim against a shareholder is on the account of the company's form, and on no other const claimAccount = SHAREHOLDER_CLAIM_ACCOUNTS[chartOf(policy)][shareholderForm]; if (account !== claimAccount) { throw new RecipeRefusalError( 'settlement_account_not_allowed', `account ${account} is not where a company of the form ${shareholderForm} books its claim against a shareholder in ${policy.skrType}: that is ${claimAccount}`, { field: 'account', account }, ); } } else if (account !== policy.cash && account !== policy.privateAccounts.withdrawal) { // an account kept for claims against shareholders asks for the form; the other assets (a cooperative's claim) are // a general account of the chart, which without the form is no account a payment outside the bank goes to const forms = SHAREHOLDER_CLAIM_FORMS.filter((formArg) => formArg !== 'eg' && SHAREHOLDER_CLAIM_ACCOUNTS[chartOf(policy)][formArg] === account); throw new RecipeRefusalError( 'settlement_account_not_allowed', forms.length > 0 ? `account ${account} holds a company's claim against a shareholder in ${policy.skrType} (${forms.join(', ')}): name the company's form in shareholderForm` : `account ${account} is none a customer's payment outside the bank accounts goes to in ${policy.skrType}: the till (${policy.cash}), the Privatentnahmen (${policy.privateAccounts.withdrawal}) or the claim against a shareholder on the account of the company's form (shareholderForm); money on a bank or PayPal account of the books is booked from its statement`, forms.length > 0 ? { field: 'shareholderForm', account } : { field: 'account', account }, ); } if (input.expectedCents === undefined && (input.skonto !== undefined || input.diffToleranceCents !== undefined)) { throw new RecipeRefusalError( 'settlement_open_item_required', `${input.skonto !== undefined ? 'skonto' : 'diffToleranceCents'} is measured against the open item the payment settles; name it in expectedCents`, { field: input.skonto !== undefined ? 'skonto' : 'diffToleranceCents' }, ); } if (input.expectedCents !== undefined) { // the open item settled in full: the difference is booked as a bank payment's, on the account the money went to const draft = bookBankPayment( { date: input.date, direction: 'incoming', bankAccount: account, counterpartyAccount: input.debtorAccount, expectedCents: input.expectedCents, paidCents: input.amountCents, ...(input.skonto !== undefined ? { skonto: input.skonto } : {}), ...(input.diffToleranceCents !== undefined ? { diffToleranceCents: input.diffToleranceCents } : {}), description: input.description, ...(input.reference !== undefined ? { reference: input.reference } : {}), }, policy, ); // the Beleg the payment was stated on, on every line, as the plain settlement links it return input.docLink === undefined ? draft : { ...draft, lines: draft.lines.map((lineArg) => ({ ...lineArg, docLink: input.docLink })) }; } return makeDraft( { date: input.date, description: input.description, ...(input.reference !== undefined ? { reference: input.reference, belegfeld1: input.reference } : {}), docLink: input.docLink, }, policy, [ { accountNumber: account, counterAccount: input.debtorAccount, side: 'debit', amountCents: input.amountCents }, { accountNumber: input.debtorAccount, counterAccount: account, side: 'credit', amountCents: input.amountCents }, ], ); } /** * Book a fee a bank or a payment provider kept from the balance of the account * it holds (`charged`), or gave back (`refunded`), on the policy's account of * Nebenkosten des Geldverkehrs (`paymentFeesAccount`: SKR 03 4970, SKR 04 * 6855) or on the `expenseAccount` named. Without a scenario no input VAT and * no BU key: a payment service is exempt (§ 4 Nr. 8 UStG). With German VAT or * under § 13b (`scenario`) the fee is booked as a vendor invoice paid from the * balance, and a fee given back as its correction (§ 17 Abs. 1 UStG). The fee * is its own entry, apart from the payment it was kept from, whose open item * is settled by the payment's whole amount. */ export function bookPaymentFee(input: IPaymentFeeInput, policy: IAccountPolicy): IJournalDraft { assertPositive(input.amountCents, 'amountCents'); const scenario = input.scenario ?? 'domestic_tax_free'; if (!PAYMENT_FEE_SCENARIOS.includes(scenario)) { throw new RecipeRefusalError( 'payment_fee_input_invalid', `a fee bears no German VAT, VAT at 19 or 7 % or the tax § 13b UStG has the books owe (${PAYMENT_FEE_SCENARIOS.join(', ')}), not ${String(scenario)}`, { field: 'scenario', scenario }, ); } const fees = input.expenseAccount ?? paymentFeesAccount(policy); const bank = input.bankAccount ?? policy.bank; const paragraph = reverseChargeParagraphOf(input.reverseChargeParagraph, scenario, 'reverseChargeParagraph', true); if (input.deductiblePercent !== undefined && input.nonDeductibleVatCents !== undefined) { throw new RecipeRefusalError( 'non_deductible_vat_invalid', 'deductiblePercent and nonDeductibleVatCents both state the part of the tax not deducted: give the key, or the cents, not both', { field: 'deductiblePercent', scenario }, ); } if (input.deductiblePercent !== undefined && scenario === 'domestic_tax_free') { throw new RecipeRefusalError( 'non_deductible_vat_invalid', `deductiblePercent on scenario '${scenario}', which books no German tax to deduct`, { field: 'deductiblePercent', scenario }, ); } if (input.nonDeductible !== undefined) { const conflict = input.nonDeductible !== true ? `nonDeductible must be true where given, got ${String(input.nonDeductible)}` : input.deductiblePercent !== undefined ? 'nonDeductible and deductiblePercent both state the part of the tax not deducted: none of it is deducted, or the key\'s part is, not both' : input.nonDeductibleVatCents !== undefined ? 'nonDeductible and nonDeductibleVatCents both state the part of the tax not deducted: give nonDeductible, and the recipe computes the tax, or the cents, not both' : scenario === 'domestic_tax_free' ? `nonDeductible on scenario '${scenario}', which books no German tax to deduct` : undefined; if (conflict !== undefined) { throw new RecipeRefusalError('non_deductible_vat_invalid', conflict, { field: 'nonDeductible', scenario }); } } const base = { date: input.date, description: input.description, reference: input.reference, belegfeld1: input.reference, }; if (scenario !== 'domestic_tax_free') { // a key, or none deducted: the tax the scenario books on the fee, from the gross at 19 or 7 %, under § 13b from the // net, and of it the rest beside the deductible part excluded, or all of it let excludedCents = input.nonDeductibleVatCents; if (input.deductiblePercent !== undefined || input.nonDeductible === true) { const rate = vendorRateOf(scenario, input.vatRatePercent); const vatCents = scenario === 'reverse_charge_13b' ? vatFromNetCents(input.amountCents, rate) : splitGrossCents(input.amountCents, rate).vatCents; excludedCents = input.deductiblePercent !== undefined ? vatCents - deductibleVatCentsOf(vatCents, input.deductiblePercent) : vatCents; } return buildVendorDocument( { date: input.date, vendorAccount: bank, expenseAccount: fees, grossCents: input.amountCents, ...(input.vatRatePercent !== undefined ? { vatRatePercent: input.vatRatePercent } : {}), ...(excludedCents !== undefined ? { nonDeductibleVatCents: excludedCents } : {}), ...(paragraph !== undefined ? { reverseChargeParagraph: paragraph } : {}), scenario, description: input.description, }, policy, input.direction === 'charged' ? 'invoice' : 'credit_note', { ...base, scenario }, ); } if (input.vatRatePercent !== undefined && input.vatRatePercent !== 0) { throw new RecipeRefusalError( 'payment_fee_input_invalid', `vatRatePercent ${input.vatRatePercent} on a fee without German VAT; a fee taxed at a rate names its scenario`, { field: 'vatRatePercent', scenario, ratePercent: input.vatRatePercent }, ); } nonDeductibleOf(input.nonDeductibleVatCents, 0, fees, scenario, policy); // the policy's own account, for a fee that names neither, is taken as before (hints.md, Next major) if (input.expenseAccount !== undefined || input.scenario !== undefined) { assertNoVatRateAutomatik(fees, 'expenseAccount', scenario, policy); } // a fee without a scenario names none on its entry, as before the scenario was known const entry = input.scenario !== undefined ? { ...base, scenario } : base; if (input.direction === 'charged') { return makeDraft(entry, policy, [ { accountNumber: fees, counterAccount: bank, side: 'debit', amountCents: input.amountCents }, { accountNumber: bank, counterAccount: fees, side: 'credit', amountCents: input.amountCents }, ]); } return makeDraft(entry, policy, [ { accountNumber: bank, counterAccount: fees, side: 'debit', amountCents: input.amountCents }, { accountNumber: fees, counterAccount: bank, side: 'credit', amountCents: input.amountCents }, ]); } /** * Park an unclear bank movement on the clearing account. */ export function bookToSuspense(input: ISuspenseInput, policy: IAccountPolicy): IJournalDraft { assertPositive(input.amountCents, 'amountCents'); const bank = input.bankAccount ?? policy.bank; const base = { date: input.date, description: input.description, reference: input.reference, belegfeld1: input.reference, }; if (input.direction === 'incoming') { return makeDraft(base, policy, [ { accountNumber: bank, counterAccount: policy.clearing, side: 'debit', amountCents: input.amountCents }, { accountNumber: policy.clearing, counterAccount: bank, side: 'credit', amountCents: input.amountCents }, ]); } return makeDraft(base, policy, [ { accountNumber: policy.clearing, counterAccount: bank, side: 'debit', amountCents: input.amountCents }, { accountNumber: bank, counterAccount: policy.clearing, side: 'credit', amountCents: input.amountCents }, ]); } /** * Move a parked suspense amount to its real account once clarified. */ export function resolveSuspense( input: ISuspenseResolutionInput, policy: IAccountPolicy, ): IJournalDraft { assertPositive(input.amountCents, 'amountCents'); const base = { date: input.date, description: input.description, reference: input.reference, belegfeld1: input.reference, }; if (input.direction === 'incoming') { return makeDraft(base, policy, [ { accountNumber: policy.clearing, counterAccount: input.targetAccount, side: 'debit', amountCents: input.amountCents, }, { accountNumber: input.targetAccount, counterAccount: policy.clearing, side: 'credit', amountCents: input.amountCents, }, ]); } return makeDraft(base, policy, [ { accountNumber: input.targetAccount, counterAccount: policy.clearing, side: 'debit', amountCents: input.amountCents, }, { accountNumber: policy.clearing, counterAccount: input.targetAccount, side: 'credit', amountCents: input.amountCents, }, ]); } /** One side of an offset between personal accounts: the account and the number of its open item. */ export interface IPersonalAccountOffsetSide { /** a personal account of a customer or a supplier (`policy.debtorRange`, `policy.creditorRange`) */ account: string; /** * the number of the open item on it the offset settles: Belegfeld 1, which * settles an open item only where it is the item's number. Unset for an item * that carries none (an invoice without a number, § 33 UStDV) */ reference?: string; } /** * What the business owes a party set off against what the party owes the * business (Aufrechnung, §§ 387–389 BGB), where the two claims stand on two * personal accounts. */ export interface IPersonalAccountOffsetInput { /** the day the offset was declared (§ 388 BGB), as the caller states it */ date: Date; /** * the claim the business owes the party, debited: a supplier's invoice on its * creditor account, or a credit the business owes a customer back on the * customer's account */ owedByBusiness: IPersonalAccountOffsetSide; /** * the claim the party owes the business, credited: an invoice to a customer * on the customer's account, or what a supplier owes back of its credit note * on its creditor account */ owedToBusiness: IPersonalAccountOffsetSide; /** what is set off, positive integer cents */ amountCents: TCents; description: string; docLink?: string; } /** * An offset between two personal accounts, or two open items of one: the * claim the business owes the party debited, the claim the party owes the * business credited, by the amount set off — Kreditor an Debitor for a party * that is customer and supplier, one account against the other of a party on * two accounts of one kind (a renamed customer, a supplier under two creditor * accounts), and one item against another on one account (a credit owed back * on the item of the invoice it corrects, set off against a later invoice). No * money moves and no line carries VAT or a BU key: each document booked its * tax, and a set-off counts as the payment of both on its day (UStAE 13.6 * Abs. 1 Satz 12), which the caller's tax timing reads, not the entry. * * Belegfeld 1 settles an open item only where it is the item's number. Where * both sides name the same number, or neither names one, the entry is one * booking between the two accounts. Otherwise each side is booked against the * clearing account (`policy.clearing`) with its own item's number, two DATEV * rows that net to 0 on the clearing account, so each item is settled by its * own number; the entry then names no reference of its own. On one account * that moves what is set off from one item to the other and leaves the * account's balance as it was. * * Refused: a side that is no personal account (`personal_account_required`), * both sides on one account and one item (`offset_same_account`: the same * number, or none on either — the claims are one open item already), a number * given but blank (`offset_reference_required`), and an amount that is not * positive whole cents (`amount_not_positive`). */ export function bookPersonalAccountOffset(input: IPersonalAccountOffsetInput, policy: IAccountPolicy): IJournalDraft { assertPositive(input.amountCents, 'amountCents'); const sides = [ ['owedByBusiness', input.owedByBusiness], ['owedToBusiness', input.owedToBusiness], ] as const; for (const [field, side] of sides) { const account = side?.account; if (typeof account !== 'string' || !/^\d+$/u.test(account) || !(isDebtorAccount(policy, account) || isCreditorAccount(policy, account))) { throw new RecipeRefusalError( 'personal_account_required', `${field}.account ${String(account)} is no personal account of a customer (${policy.debtorRange[0]}–${policy.debtorRange[1]}) or a supplier (${policy.creditorRange[0]}–${policy.creditorRange[1]}) in ${policy.skrType}`, { field: `${field}.account`, account: String(account) }, ); } if (side.reference !== undefined && (typeof side.reference !== 'string' || side.reference.trim() === '')) { throw new RecipeRefusalError( 'offset_reference_required', `${field}.reference is given but names no number; in Belegfeld 1 it settles the open item, and an item that carries none leaves it unset`, { field: `${field}.reference` }, ); } } const owedBy = input.owedByBusiness; const owedTo = input.owedToBusiness; if (owedBy.account === owedTo.account && owedBy.reference === owedTo.reference) { throw new RecipeRefusalError( 'offset_same_account', `both sides of the offset are the same open item on ${owedBy.account}${owedBy.reference !== undefined ? ` (${owedBy.reference})` : ', under no number'}: the two claims meet on it already, and nothing is booked between it and itself`, { accounts: [owedBy.account, owedTo.account] }, ); } if (owedBy.reference === owedTo.reference) { // one number keys both open items, or neither carries one: one booking between the two accounts return makeDraft( { date: input.date, description: input.description, ...(owedBy.reference !== undefined ? { reference: owedBy.reference, belegfeld1: owedBy.reference } : {}), docLink: input.docLink, }, policy, [ { accountNumber: owedBy.account, counterAccount: owedTo.account, side: 'debit', amountCents: input.amountCents }, { accountNumber: owedTo.account, counterAccount: owedBy.account, side: 'credit', amountCents: input.amountCents }, ], ); } // each open item by its own number: two bookings through the clearing account, which nets to 0 const draft = makeDraft({ date: input.date, description: input.description, docLink: input.docLink }, policy, [ { accountNumber: owedBy.account, counterAccount: policy.clearing, side: 'debit', amountCents: input.amountCents }, { accountNumber: policy.clearing, counterAccount: owedBy.account, side: 'credit', amountCents: input.amountCents }, { accountNumber: policy.clearing, counterAccount: owedTo.account, side: 'debit', amountCents: input.amountCents }, { accountNumber: owedTo.account, counterAccount: policy.clearing, side: 'credit', amountCents: input.amountCents }, ]); const numbers = [owedBy.reference, owedBy.reference, owedTo.reference, owedTo.reference]; return { ...draft, lines: draft.lines.map((lineArg, indexArg) => { const { belegfeld1: _unset, ...line } = lineArg; return numbers[indexArg] !== undefined ? { ...line, belegfeld1: numbers[indexArg] } : line; }), }; } /** * Realized FX difference lines for a settlement whose EUR value moved between * booking and payment. Returns lines to embed into the settlement draft * (empty array when there is no difference). */ export function fxDifferenceLines( input: IFxDifferenceInput, policy: IAccountPolicy, ): IJournalLineDraft[] { const diff = input.settledCents - input.bookedCents; if (diff === 0) return []; const isGain = input.kind === 'payable' ? diff < 0 : diff > 0; const amountCents = Math.abs(diff); return [ { accountNumber: isGain ? policy.fx.gain : policy.fx.loss, counterAccount: input.counterAccount, side: isGain ? 'credit' : 'debit', amountCents, buKey: '', buchungstext: input.buchungstext, belegfeld1: input.belegfeld1, }, ]; } /** * An advance (Anzahlung): money received or paid before the supply. * `vatRatePercent` is the rate its tax is at: for a received one the tax that * arises when it is received (§ 13 Abs. 1 Nr. 1 Buchst. a Satz 4 UStG), 0 where * none does (a supply without German VAT, UStAE 13.5 Abs. 4); for a paid one * the input tax deducted with it once the invoice for it is at hand (§ 15 * Abs. 1 Satz 1 Nr. 1 Satz 3 UStG), 0 while it is not or there is none. */ export interface IAdvanceInput { date: Date; /** gross, positive */ grossCents: TCents; vatRatePercent: 0 | 7 | 19; /** the account the money moved on; unset: the policy's bank */ bankAccount?: string; description: string; /** Belegfeld 1: the order or the invoice of the advance */ reference?: string; docLink?: string; } /** * The clearing of an advance on the final invoice, booked with the invoice at * the supply: the advance, at the rate it was booked at, against the personal * account the invoice books in full, so the account of the advance is cleared * and the tax of the invoice's month is the invoice's less the advance's * (§ 14 Abs. 5 Satz 2 UStG). */ export interface IAdvanceClearingInput { date: Date; /** a customer's personal account for a received advance, a supplier's for a paid one */ partyAccount: string; /** gross, positive: what the advance booked */ grossCents: TCents; /** the rate the advance was booked at */ vatRatePercent: 0 | 7 | 19; description: string; /** Belegfeld 1: the final invoice's number, which keys the personal account's open item */ reference?: string; docLink?: string; } /** The zero-rate revenue account of a policy (§ 12 Abs. 3 UStG), or the refusal when it names none. */ function zeroRateAccountOf(policy: IAccountPolicy): string { if (!policy.revenue.domesticZeroRate) { throw new RecipeRefusalError('zero_rate_account_missing', `the policy of ${policy.skrType} names no account of supplies taxable at 0 % (\`revenue.domesticZeroRate\`)`, { scenario: 'domestic_zero_rate' }); } return policy.revenue.domesticZeroRate; } /** The advance accounts of a policy, or the refusal when it names none. */ function advancesOf(policy: IAccountPolicy): NonNullable { if (!policy.advances) { throw new RecipeRefusalError('advance_accounts_missing', `the policy of ${policy.skrType} names no accounts of advances (\`advances\`)`, {}); } return policy.advances; } /** The account of an advance at its rate, checked against the chart's automatism, and its net and tax. */ function advancePartsOf( kind: 'paid' | 'received', input: { grossCents: TCents; vatRatePercent: number }, policy: IAccountPolicy, ): { account: string; netCents: TCents; vatCents: TCents; vatAccount?: string; buKey: TBuKey } { assertPositive(input.grossCents, 'grossCents'); const rate = input.vatRatePercent; if (rate !== 0 && rate !== 7 && rate !== 19) { throw new RecipeRefusalError('advance_rate_unsupported', `an advance is booked at 0, 7 or 19 %, got ${rate} %`, { field: 'vatRatePercent', ratePercent: rate }); } const accounts = advancesOf(policy)[kind]; if (rate === 0) { return { account: accounts.untaxed, netCents: input.grossCents, vatCents: 0, buKey: '' }; } const account = rate === 7 ? accounts.reduced : accounts.standard; const scenario: TTaxScenario = rate === 7 ? 'domestic_reduced' : 'domestic_standard'; assertAccountAtRate(account, kind === 'paid' ? 'advances.paid' : 'advances.received', scenario, rate, policy); const { netCents, vatCents } = splitGrossCents(input.grossCents, rate); const vatAccount = kind === 'paid' ? rate === 7 ? policy.vat.inputReduced : policy.vat.inputStandard : rate === 7 ? policy.vat.outputReduced : policy.vat.outputStandard; const buKey = suggestBuKey({ direction: kind === 'paid' ? 'inbound' : 'outbound', scenario, ratePercent: rate, targetIsAutomatik: isAutomatikAccount(policy, account), hasExplicitVatLines: vatCents > 0, }); return { account, netCents, vatCents, vatAccount, buKey }; } /** * A received advance: the bank against the account of advances received of * its rate, and the output tax that arises with it on its own line. */ export function bookAdvanceReceived(input: IAdvanceInput, policy: IAccountPolicy): IJournalDraft { const parts = advancePartsOf('received', input, policy); const bank = input.bankAccount ?? policy.bank; const base = { date: input.date, description: input.description, reference: input.reference, belegfeld1: input.reference, docLink: input.docLink }; return makeDraft(base, policy, [ { accountNumber: bank, counterAccount: parts.account, side: 'debit', amountCents: input.grossCents }, { accountNumber: parts.account, counterAccount: bank, side: 'credit', amountCents: parts.netCents, buKey: parts.buKey }, ...(parts.vatAccount ? [{ accountNumber: parts.vatAccount, counterAccount: bank, side: 'credit' as const, amountCents: parts.vatCents }] : []), ]); } /** * A paid advance: the account of advances paid of its rate and the input tax * deducted with it on its own line, against the bank. */ export function bookAdvancePaid(input: IAdvanceInput, policy: IAccountPolicy): IJournalDraft { const parts = advancePartsOf('paid', input, policy); const bank = input.bankAccount ?? policy.bank; const base = { date: input.date, description: input.description, reference: input.reference, belegfeld1: input.reference, docLink: input.docLink }; return makeDraft(base, policy, [ { accountNumber: parts.account, counterAccount: bank, side: 'debit', amountCents: parts.netCents, buKey: parts.buKey }, ...(parts.vatAccount ? [{ accountNumber: parts.vatAccount, counterAccount: bank, side: 'debit' as const, amountCents: parts.vatCents }] : []), { accountNumber: bank, counterAccount: parts.account, side: 'credit', amountCents: input.grossCents }, ]); } /** * The input tax of an advance paid without an invoice for it at hand * (`bookAdvancePaid` at 0 %), deducted once both are there. */ export interface IAdvanceDeductionInput { /** the day the advance was paid */ paidOn: Date; /** the day the invoice for it came to hand */ invoiceAtHandOn: Date; /** what was paid and stands on the account without tax, positive */ paidCents: TCents; /** what the invoice states for the advance, gross, positive; at most `paidCents` */ grossCents: TCents; vatRatePercent: 7 | 19; description: string; /** Belegfeld 1: the invoice of the advance */ reference?: string; docLink?: string; } /** * The input tax of a paid advance, deducted when it is both paid and * invoiced (§ 15 Abs. 1 Satz 1 Nr. 1 Satz 3 UStG): on the later of the two * days, so in the month that falls in, and only as far as it was paid. The * advance, or the part the invoice states, moves from the account without * tax (`bookAdvancePaid` at 0 %) to the account of its rate, with its input * tax on its own line. Refused beyond what was paid * (`advance_deduction_beyond_payment`) and at 0 % (`advance_rate_unsupported`). */ export function deductAdvancePaidInputTax(input: IAdvanceDeductionInput, policy: IAccountPolicy): IJournalDraft { if (input.vatRatePercent !== 7 && input.vatRatePercent !== 19) { throw new RecipeRefusalError('advance_rate_unsupported', `the input tax of an advance is deducted at 7 or 19 %, got ${input.vatRatePercent} %`, { field: 'vatRatePercent', ratePercent: input.vatRatePercent }); } assertPositive(input.paidCents, 'paidCents'); assertPositive(input.grossCents, 'grossCents'); if (input.grossCents > input.paidCents) { throw new RecipeRefusalError( 'advance_deduction_beyond_payment', `the invoice states ${input.grossCents} cents for the advance, but ${input.paidCents} were paid: input tax is deducted only as far as the advance was paid`, { field: 'grossCents', amountCents: input.grossCents, differenceCents: input.grossCents - input.paidCents }, ); } const parts = advancePartsOf('paid', input, policy); const untaxed = advancesOf(policy).paid.untaxed; const date = input.invoiceAtHandOn.getTime() > input.paidOn.getTime() ? input.invoiceAtHandOn : input.paidOn; const base = { date, description: input.description, reference: input.reference, belegfeld1: input.reference, docLink: input.docLink }; return makeDraft(base, policy, [ { accountNumber: parts.account, counterAccount: untaxed, side: 'debit', amountCents: parts.netCents, buKey: parts.buKey }, ...(parts.vatAccount ? [{ accountNumber: parts.vatAccount, counterAccount: untaxed, side: 'debit' as const, amountCents: parts.vatCents }] : []), { accountNumber: untaxed, counterAccount: parts.account, side: 'credit', amountCents: input.grossCents }, ]); } /** * The clearing of a received advance on the final invoice: the account of the * advance and its output tax against the customer's personal account. */ export function clearAdvanceReceived(input: IAdvanceClearingInput, policy: IAccountPolicy): IJournalDraft { if (!isDebtorAccount(policy, input.partyAccount)) { throw new RecipeRefusalError('advance_party_account_required', `a received advance is cleared against a customer's personal account, not ${input.partyAccount}`, { field: 'partyAccount', account: input.partyAccount }); } const parts = advancePartsOf('received', input, policy); const base = { date: input.date, description: input.description, reference: input.reference, belegfeld1: input.reference, docLink: input.docLink }; return makeDraft(base, policy, [ { accountNumber: parts.account, counterAccount: input.partyAccount, side: 'debit', amountCents: parts.netCents, buKey: parts.buKey }, ...(parts.vatAccount ? [{ accountNumber: parts.vatAccount, counterAccount: input.partyAccount, side: 'debit' as const, amountCents: parts.vatCents }] : []), { accountNumber: input.partyAccount, counterAccount: parts.account, side: 'credit', amountCents: input.grossCents }, ]); } /** * The clearing of a paid advance on the final invoice: the supplier's * personal account against the account of the advance and its input tax. */ export function clearAdvancePaid(input: IAdvanceClearingInput, policy: IAccountPolicy): IJournalDraft { if (!isCreditorAccount(policy, input.partyAccount)) { throw new RecipeRefusalError('advance_party_account_required', `a paid advance is cleared against a supplier's personal account, not ${input.partyAccount}`, { field: 'partyAccount', account: input.partyAccount }); } const parts = advancePartsOf('paid', input, policy); const base = { date: input.date, description: input.description, reference: input.reference, belegfeld1: input.reference, docLink: input.docLink }; return makeDraft(base, policy, [ { accountNumber: input.partyAccount, counterAccount: parts.account, side: 'debit', amountCents: input.grossCents }, { accountNumber: parts.account, counterAccount: input.partyAccount, side: 'credit', amountCents: parts.netCents, buKey: parts.buKey }, ...(parts.vatAccount ? [{ accountNumber: parts.vatAccount, counterAccount: input.partyAccount, side: 'credit' as const, amountCents: parts.vatCents }] : []), ]); }