/** * Booking recipes of a business's securities and derivatives — pure builders, * like `core.recipes.ts`: (input, policy) => IJournalDraft, integer cents. * They book what a securities ledger decided (@fin.cx/depot's movements: what * units cost and brought, the book value released, the kind of result) on the * accounts of the securities roles (@fin.cx/chartdata `TSecuritiesRole`), * resolved for the books by `securitiesAccountOf`: the account DATEV's chart * keeps for the role and tax rule, or the books' individual account that names * the role (`IAccountPolicy.individualAccounts`); for a role DATEV keeps no * account of its own for, the account of its position * (`SECURITIES_POSITION_ACCOUNTS`); the results the law keeps apart — of * Termingeschäfte (§ 15 Abs. 4 Satz 3 EStG) and of short sales — only on an * individual account, else the recipe refuses (`securities_account_missing`). * * By default, the § 8b KStG accounts (`estg_3_40_kstg_8b`) take a share's * sale, its costs, * its write-downs and write-ups whatever the holding (§ 8b Abs. 2 and 3 KStG), * and the dividends of a holding of at least 10 % at the start of the calendar * year (§ 8b Abs. 1 and 4 KStG); a fund's (§ 16 Abs. 3 InvStG: the fund's tax * lives in the depot's tax ledger), a bond's and anything else's take the * ordinary accounts. An explicit `taxTreatment` overrides this default for * sales and exchanges, including their disposal costs, not their holdings. * Every line pairs with its counter account (DATEV * Gegenkonto); a booking that moves money moves it on the depot's cash * account the caller names (`cashAccount`). */ import * as plugins from './core.plugins.js'; import type { IJournalDraft, IJournalLineDraft, TCents, TSKRType } from './core.types.js'; import { otherIncomeAccount, type IAccountPolicy } from './core.accountpolicy.js'; import { booksChartOf, CHART_DATA_YEAR } from './core.booksaccounts.js'; import { chartOf } from './core.chart.js'; import { RecipeRefusalError } from './core.errors.js'; /** What an account books of a business's securities (@fin.cx/chartdata `TSecuritiesRole`). */ export type TSecuritiesRole = plugins.chartdata.TSecuritiesRole; /** The income tax rule an account is kept for (@fin.cx/chartdata `TTaxRule`): `estg_3_40_kstg_8b`. */ export type TTaxRule = plugins.chartdata.TTaxRule; const EIGHT_B: TTaxRule = 'estg_3_40_kstg_8b'; /** * Where a role DATEV's standard charts keep no account of its own for is * booked when the books declare no individual account for it: on the account * of its position (DATEV Kontenrahmen SKR 03, Art.-Nr. 11174, and SKR 04, * Art.-Nr. 11175, gültig für 2026). Options bought, a variation margin paid, * accrued interest bought with a bond and the claim to securities lent are * other assets (§ 266 Abs. 2 B.II.4 HGB, "Sonstige Vermögensgegenstände"); * a writer's obligation, a variation margin received, securities owed after a * short sale and cash collateral to give back other liabilities (§ 266 Abs. 3 * C.8, "Sonstige Verbindlichkeiten"); a writer's premium earned other * operating income (§ 275 Abs. 2 Nr. 4, "Sonstige Erträge", "Sonstige * betriebliche Erträge"). The results of Termingeschäfte and of short sales and * the compensations paid on securities sold short take no account of their * position: the books keep them apart on individual accounts. */ export const SECURITIES_POSITION_ACCOUNTS: Readonly>>>> = { SKR03: positionAccounts({ otherAssets: '1500', otherLiabilities: '1700', otherIncome: '2700' }), SKR04: positionAccounts({ otherAssets: '1300', otherLiabilities: '3500', otherIncome: '4830' }), }; /** * The other operating income and expenses of the charts: SKR 03 2700 * "Sonstige Erträge" and 2300 "Sonstige Aufwendungen", SKR 04 4830 "Sonstige * betriebliche Erträge" and 6300 "Sonstige betriebliche Aufwendungen" * (§ 275 Abs. 2 Nr. 4 and 8 HGB). The income takes a payment received in * place of a dividend on securities lent, which is no dividend; the expenses * the provision for an expected loss from a written option as it is formed. */ const OTHER_OPERATING: Readonly> = { SKR03: { income: '2700', expenses: '2300' }, SKR04: { income: '4830', expenses: '6300' }, }; function positionAccounts(argsArg: { otherAssets: string; otherLiabilities: string; otherIncome: string }): Partial> { return { options_held: argsArg.otherAssets, variation_margin_paid: argsArg.otherAssets, accrued_interest_claim: argsArg.otherAssets, lending_claim: argsArg.otherAssets, written_options: argsArg.otherLiabilities, variation_margin_received: argsArg.otherLiabilities, short_sale_obligations: argsArg.otherLiabilities, collateral_received: argsArg.otherLiabilities, stillhalter_income: argsArg.otherIncome, }; } /** * The account the books book a securities role on, under a tax rule or none: * the account DATEV's chart keeps for it, or the books' individual account * that names it (`booksChartOf`); without one, the account of its position * (`SECURITIES_POSITION_ACCOUNTS`, no tax rule only). Refuses a role neither * gives (`securities_account_missing`), naming the parent chartdata suggests * for its individual account and the numbers free after it. */ export function securitiesAccountOf(policy: IAccountPolicy, role: TSecuritiesRole, taxRule?: TTaxRule): string { const chart = chartOf(policy); const account = booksChartOf(policy).getSecuritiesAccount(role, taxRule); if (account !== null) return account.accountNumber; const position = taxRule === undefined ? SECURITIES_POSITION_ACCOUNTS[chart][role] : undefined; if (position !== undefined) return position; const template = plugins.chartdata.INDIVIDUAL_ACCOUNT_TEMPLATES[chart].find((templateArg) => templateArg.securitiesRole === role); if (template === undefined) { throw new RecipeRefusalError( 'securities_account_missing', `${chart} keeps no account for ${role}${taxRule ? ` under ${taxRule}` : ''}, and the books name none`, { field: role }, ); } const free = plugins.chartdata.freeNumbersOf(chart, CHART_DATA_YEAR, template.parentAccountNumber, policy.individualAccounts ?? []); throw new RecipeRefusalError( 'securities_account_missing', `the books keep no account for ${role}: declare an individual account "${template.accountName}" under ${template.parentAccountNumber}` + (free.length > 0 ? ` (free: ${free.join(', ')})` : `, which leaves no number free in ${chart}: the advisor decides where it goes`), { field: role, account: template.parentAccountNumber, accounts: free }, ); } /** * The account securities of a classification and kind are held on: a current * asset's on the one account of securities held as current assets, a fixed * asset's on the account of its kind (shares, bonds, anything else). */ export function securitiesHoldingAccountOf(policy: IAccountPolicy, classification: TSecuritiesClassification, kind: TSecurityKind): string { if (classification === 'current') return securitiesAccountOf(policy, 'holding_current'); return securitiesAccountOf(policy, kind === 'share' ? 'holding_fixed_shares' : kind === 'bond' ? 'holding_fixed_bonds' : 'holding_fixed'); } // ------------------------------------------------------------------ inputs /** What every securities booking states. */ export interface ISecuritiesBookingBase { /** the booking day: the trade day (Schlusstag), the day of a payment, a closing date */ date: Date; description: string; /** Belegfeld 1 of the lines: the broker's trade or transaction id */ reference?: string; /** the Beleg: the broker's statement or confirmation */ docLink?: string; } /** Whether a security is a fixed asset, held to serve the business lastingly (§ 247 Abs. 2 HGB), or a current one. */ export type TSecuritiesClassification = 'fixed' | 'current'; /** * What a security is, which decides its holding account and its default tax: * - `share`: a share, whose sale, write-down and write-up default to § 8b KStG's * whatever the holding (Abs. 2, 3); * - `fund`: an investment fund's units (InvStG), never § 8b (§ 16 Abs. 3 InvStG); * - `bond`: a bond, interest-bearing; * - `other`: any other security (a certificate, a warrant held as a security). */ export type TSecurityKind = 'share' | 'fund' | 'bond' | 'other'; export type TSecuritiesTaxTreatment = 'ordinary' | 'estg_3_40_kstg_8b'; export interface ISecuritiesPurchaseInput extends ISecuritiesBookingBase { classification: TSecuritiesClassification; kind: TSecurityKind; /** what the units cost, commissions and taxes included (§ 255 Abs. 1 HGB): the depot's `open.amountCents` */ costCents: TCents; /** of it, the book value of a call exercised into the purchase (the depot's `open.transferredCents`), which leaves the options bought; 0 where absent */ transferredCents?: TCents; /** * the account the purchase is paid from: the depot's cash account; for units * that come in without money through the depot, the account they come in * against (a contribution: the owner's private account) */ cashAccount: string; } export interface ISecuritiesSaleInput extends ISecuritiesBookingBase { classification: TSecuritiesClassification; kind: TSecurityKind; /** the disposal's tax treatment; absent: a share's § 8b treatment, anything else's ordinary treatment; never changes the holding account */ taxTreatment?: TSecuritiesTaxTreatment; /** what the sale or redemption brought, net of its costs: the depot's `close.amountCents`; with a put exercised into the sale, less its book value */ proceedsCents: TCents; /** the costs of the sale in it (commission, taxes): the depot's `close.costsCents` */ costsCents: TCents; /** the book value of the units sold: the depot's `close.bookCents` */ bookCents: TCents; /** the book value of a put exercised into the sale, negative (the depot's `close.transferredCents`), which leaves the options bought; 0 where absent */ transferredCents?: TCents; /** * the account what the sale brought is booked on: the depot's cash account; * for units that leave without money through the depot, the account they * leave against (a withdrawal at their value: the owner's private account; a * sale settled elsewhere: the buyer's receivable) */ cashAccount: string; } export interface IOptionPurchaseInput extends ISecuritiesBookingBase { /** the premium paid, costs included: the depot's `open.amountCents` */ costCents: TCents; cashAccount: string; } /** * Where units closed in a Termingeschäft were carried: options bought * (`option`), or a warrant or a certificate held as a security of its * classification, whose result a person decided is a Termingeschäft's. */ export type TTermingeschaeftHolding = { kind: 'option' } | { kind: 'security'; classification: TSecuritiesClassification }; export interface ITermingeschaeftCloseInput extends ISecuritiesBookingBase { held: TTermingeschaeftHolding; /** what the closing brought, net of its costs; 0 at expiry: the depot's `close.amountCents` */ proceedsCents: TCents; /** the book value released: the depot's `close.bookCents` */ bookCents: TCents; cashAccount: string; } export interface IVariationMarginInput extends ISecuritiesBookingBase { /** the day's settlement of a future or a CFD: positive received, negative paid (the depot's `variation_margin.amountCents`) */ amountCents: TCents; /** the contract's variation margin held before it: positive net received, negative net paid (the depot's `variation_margin.heldBeforeCents`) */ heldBeforeCents: TCents; cashAccount: string; } export interface IContractCloseInput extends ISecuritiesBookingBase { /** the variation margin held for the units closed, the result: positive net received, negative net paid (the depot's `close.variationMarginCents`) */ variationMarginCents: TCents; } export interface IWrittenOptionOpenInput extends ISecuritiesBookingBase { /** the premium received, net of costs: the depot's `open.amountCents` of a short option */ premiumCents: TCents; cashAccount: string; } /** * What a written option's closing realises (the depot's `close.resultClass`, * or a person's decision on a buy-back): * - `stillhalter`: the premium earned at expiry or assignment, less what a * closing cost (BFH 18.12.2002 I R 17/02), the writer's income; * - `stillhalter_cash_settled`: settled in cash: the premium earned, and the * settlement paid a Termingeschäft's loss, each gross; * - `termingeschaeft`: a buy-back a person decided is a Termingeschäft: premium * less cost, a gain or a loss of one. */ export type TWrittenOptionResult = 'stillhalter' | 'stillhalter_cash_settled' | 'termingeschaeft'; export interface IWrittenOptionCloseInput extends ISecuritiesBookingBase { result: TWrittenOptionResult; /** the premium the obligation is carried at: the depot's `close.bookCents` */ bookCents: TCents; /** what the closing cost, costs included; 0 at expiry: the depot's `close.amountCents` */ costCents: TCents; cashAccount: string; } export interface IProvisionInput extends ISecuritiesBookingBase { /** positive: the provision formed or raised; negative: released */ amountCents: TCents; } export interface IVariationMarginWriteOffInput extends ISecuritiesBookingBase { /** the variation margin paid beyond what the contract received, written off: positive */ amountCents: TCents; } export interface IShortSaleOpenInput extends ISecuritiesBookingBase { /** what the short sale brought, net of costs: the depot's `open.amountCents` of a short position */ proceedsCents: TCents; cashAccount: string; } export interface IShortSaleCoverInput extends ISecuritiesBookingBase { /** what covering cost, costs included: the depot's `close.amountCents` */ costCents: TCents; /** what the obligation is carried at: the depot's `close.bookCents` */ bookCents: TCents; cashAccount: string; } export interface IObligationValuationInput extends ISecuritiesBookingBase { /** positive: the obligation raised to a higher market value (a loss); negative: lowered back toward what it brought */ amountCents: TCents; } export interface ISecuritiesLendingInput extends ISecuritiesBookingBase { classification: TSecuritiesClassification; kind: TSecurityKind; /** the book value of the units: positive lent out, negative returned (the depot's `lending.bookCents`) */ bookCents: TCents; } /** * What a security paid: a dividend (`dividend`), a fund's distribution * (`distribution`), a bond's coupon beyond accrued interest set off * (`coupon`; `bookAccruedInterest` books one with the claim it sets off). */ export type TSecuritiesIncomeKind = 'dividend' | 'distribution' | 'coupon'; export interface ISecuritiesIncomeInput extends ISecuritiesBookingBase { classification: TSecuritiesClassification; kind: TSecuritiesIncomeKind; /** * a dividend of a holding of at least 10 % of the capital at the start of the * calendar year (§ 8b Abs. 1 and 4 KStG): on the § 8b accounts; a smaller * holding's (Streubesitz) is taxable, on the ordinary ones */ participation10?: boolean; /** the amount paid, gross of tax withheld: positive received, negative reversed */ amountCents: TCents; cashAccount: string; } /** * The tax withheld from a security's income: * - `capital_gains_tax`: German Kapitalertragsteuer with its * Solidaritätszuschlag (5.5 % of it), creditable against the corporate tax * (§ 31 KStG, § 36 Abs. 2 Nr. 2 EStG); the amount is split into both; * - `foreign_creditable`: foreign withholding tax to credit (§ 26 KStG, § 34c * EStG) or deduct; * - `foreign_on_exempt_income`: foreign tax on income exempt at home, neither * credited nor deducted (§ 10 Nr. 2 KStG on a § 8b Abs. 1 dividend); * - `foreign_refundable`: withholding beyond the treaty rate the state refunds * on application, a claim. */ export type TWithholdingKind = 'capital_gains_tax' | 'foreign_creditable' | 'foreign_on_exempt_income' | 'foreign_refundable'; export interface IWithholdingTaxInput extends ISecuritiesBookingBase { kind: TWithholdingKind; /** positive withheld, negative refunded (a correction of the withholding); `capital_gains_tax`: the tax with its Solidaritätszuschlag */ amountCents: TCents; /** * `capital_gains_tax` only: the Solidaritätszuschlag in the amount, as the broker states it; absent, it is the one * the amount holds by § 4 SolZG (5.5 % of the tax, fractions of a cent dropped) */ soliCents?: TCents; cashAccount: string; } /** * Interest and charges around a depot: * - `credit_interest`: interest on the depot's cash, and `lending_fee`, what * the broker pays for securities lent: interest and similar income (the * policy's `otherIncome.interest`); * - `margin_interest`: interest on the depot's debit balance; * - `borrow_fee`: the fees of securities borrowed; * - `compensation_received`: a payment in place of a dividend on securities * lent, no dividend: other operating income; * - `compensation_paid`: a payment in place of a dividend on securities sold * short, part of the short sale's result. */ export type TDepotInterestKind = 'credit_interest' | 'lending_fee' | 'margin_interest' | 'borrow_fee' | 'compensation_received' | 'compensation_paid'; export interface IDepotInterestInput extends ISecuritiesBookingBase { kind: TDepotInterestKind; /** positive as the kind says (received for income, paid for an expense), negative corrected back */ amountCents: TCents; cashAccount: string; } export interface IAccruedInterestInput extends ISecuritiesBookingBase { classification: TSecuritiesClassification; /** accrued interest paid with a purchase (Stückzinsen), a claim: the depot's `accrued_interest.paidCents` */ paidCents: TCents; /** of the interest received with a sale or a coupon, the claim set off: the depot's `accrued_interest.setOffCents` */ setOffCents: TCents; /** the rest of it, interest earned: the depot's `accrued_interest.incomeCents` */ incomeCents: TCents; cashAccount: string; } export interface IInterestAccrualInput extends ISecuritiesBookingBase { classification: TSecuritiesClassification; /** a bond's interest accrued at a closing date, which the next coupon sets off: the depot's `interest_accrual.amountCents` */ amountCents: TCents; } export interface IBondInterestAdjustmentInput extends ISecuritiesBookingBase { classification: TSecuritiesClassification; /** `amortisation`: a premium paid above par spread to maturity; `accretion`: a zero bond's interest accrued into its book value */ kind: 'amortisation' | 'accretion'; amountCents: TCents; } /** What a closing-date valuation values: a security of its kind, or options bought (`option`). */ export type TValuedHolding = TSecurityKind | 'option'; export interface ISecuritiesWriteDownInput extends ISecuritiesBookingBase { classification: TSecuritiesClassification; held: TValuedHolding; amountCents: TCents; /** * a fixed asset's decline: `lasting`, written down (§ 253 Abs. 3 Satz 5 * HGB), or `temporary`, a Finanzanlage written down by choice (Satz 6), * which tax law does not follow (§ 6 Abs. 1 Nr. 2 Satz 2 EStG); required for * a fixed asset, refused for a current one */ decline?: 'lasting' | 'temporary'; } export interface ISecuritiesWriteUpInput extends ISecuritiesBookingBase { classification: TSecuritiesClassification; held: TValuedHolding; /** at most what the units cost (§ 253 Abs. 5 HGB): the caller's cap */ amountCents: TCents; } export interface ISecuritiesReclassificationInput extends ISecuritiesBookingBase { kind: TSecurityKind; from: TSecuritiesClassification; to: TSecuritiesClassification; /** the book value moved (Umwidmung at book value): the depot's `reclassification.bookCents` */ bookCents: TCents; } export interface ISecuritiesAllocationInput extends ISecuritiesBookingBase { /** the classification of the securities given, which the securities received keep */ classification: TSecuritiesClassification; /** what the securities given are */ kind: TSecurityKind; /** * the securities received, each with the part of the book value it takes * over: the depot's `open` movements of an allocation (`open.transferredCents`) */ received: Array<{ kind: TSecurityKind; bookCents: TCents }>; } export interface ISecuritiesExchangeInput extends ISecuritiesBookingBase { /** the classification of the securities given */ classification: TSecuritiesClassification; /** what the securities given are */ kind: TSecurityKind; /** the securities given's tax treatment; absent: derived from their kind as in a sale; never changes either holding account */ taxTreatment?: TSecuritiesTaxTreatment; /** the book value of the securities given: the depot's `close.bookCents` */ bookCents: TCents; /** * the securities received for them, at their cost: the gemeiner Wert of the * securities given (§ 6 Abs. 6 Satz 1 EStG), less money received with them, * plus money paid for them; the depot's `open` of a realizing decision's * `to` (`open.amountCents`) */ received: { classification: TSecuritiesClassification; kind: TSecurityKind; valueCents: TCents }; /** money received with them (positive) or paid for them (negative): the corporate action's cash; 0 where absent */ cashCents?: TCents; /** the depot's cash account the money moves on; named where `cashCents` is not 0 */ cashAccount?: string; } export interface ICurrencyConversionInput extends ISecuritiesBookingBase { /** the cash account the money leaves */ fromAccount: string; /** the cash account it enters */ toAccount: string; /** the conversion's value in euros, both legs: the euro leg, or the broker's euros of a conversion between two other currencies */ amountCents: TCents; } // ------------------------------------------------------------------ recipes /** * A purchase of securities (§ 255 Abs. 1 HGB): the units at their cost, * commissions and taxes included, on the holding account of their * classification and kind, against the cash paid; a call exercised into the * purchase hands its book value over from the options bought (IDW RS BFA 6). */ export function bookSecuritiesPurchase(input: ISecuritiesPurchaseInput, policy: IAccountPolicy): IJournalDraft { requirePositive(input.costCents, 'costCents'); const transferred = input.transferredCents ?? 0; requireWhole(transferred, 'transferredCents'); if (transferred < 0 || transferred > input.costCents) { throw invalid('transferredCents', `transferredCents ${transferred} is a call's book value in the cost, between 0 and the cost ${input.costCents}`, transferred); } const holding = securitiesHoldingAccountOf(policy, input.classification, input.kind); const cash = cashAccountOf(input.cashAccount); return draftOf(input, policy, [ pair(holding, cash, input.costCents - transferred), pair(holding, transferred === 0 ? cash : securitiesAccountOf(policy, 'options_held'), transferred), ]); } /** * A sale or a redemption of securities held (the depot's closings of class * `security`): the book value leaves the holding, the result is a gain or a * loss. * - A current asset is booked net: the result on the account of a current * asset's disposal of a gain or of a loss (§ 275 Abs. 2 Nr. 4 or 8 HGB), as * the result net of costs is one. The § 8b treatment (a share's default) * uses its result accounts, with the * costs of the sale apart on the costs' account of a gain or of a loss, as * DATEV keeps them (§ 8b Abs. 2 Satz 2 KStG: the gain is net of them), so * the result account takes what the sale brought before costs less the book * value — credited to the account of a loss where the costs turn a gain into * a loss; the ordinary treatment books net of its costs. * - A fixed asset is booked gross, as DATEV's disposal accounts of a * Finanzanlage take it: the proceeds on the proceeds account and the book * value on the account of the residual book value, each of a gain or of a * loss; the § 8b treatment (a share's default) keeps its costs apart. * A put exercised into the sale lowers the proceeds by its book value (IDW RS * BFA 6), which leaves the options bought. */ export function bookSecuritiesSale(input: ISecuritiesSaleInput, policy: IAccountPolicy): IJournalDraft { requireWhole(input.proceedsCents, 'proceedsCents'); requireNonNegative(input.costsCents, 'costsCents'); requireNonNegative(input.bookCents, 'bookCents'); const transferred = input.transferredCents ?? 0; requireWhole(transferred, 'transferredCents'); if (transferred > 0) { throw invalid('transferredCents', `transferredCents ${transferred} is a put's book value handed into a sale, 0 or negative`, transferred); } const cash = cashAccountOf(input.cashAccount); const taxRule = disposalTaxRuleOf(input); const variant = input.proceedsCents - input.bookCents >= 0 ? 'gain' : 'loss'; // what the sale brought before its costs, where the § 8b accounts keep them apart const gross = taxRule === undefined ? input.proceedsCents : input.proceedsCents + input.costsCents; const pairs: IPair[] = []; if (taxRule !== undefined) { pairs.push(pair(securitiesAccountOf(policy, variant === 'gain' ? 'sale_costs_gain' : 'sale_costs_loss', EIGHT_B), cash, input.costsCents)); } pairs.push(...disposalPairsOf(policy, input, variant, [{ account: cash, cents: gross }])); if (transferred !== 0) pairs.push(pair(cash, securitiesAccountOf(policy, 'options_held'), -transferred)); return draftOf(input, policy, pairs); } /** * The book value of securities given leaving their holding, and their result, * against what they brought (`broughtArg`, debited in its order; it sums to * what they brought, before costs where the § 8b accounts keep them apart): * - a current asset net: the result on the account of a current asset's * disposal of a gain or of a loss (`variantArg`, by the result net of * costs), what they brought beyond the book value credited to it, short of * it debited; * - a fixed asset gross, as DATEV's disposal accounts of a Finanzanlage take * it: what they brought on the proceeds account and the book value on the * account of the residual book value, each of a gain or of a loss. * A share's on the § 8b accounts by default; an explicit disposal tax * treatment selects the result accounts without changing the holding. */ function disposalPairsOf( policy: IAccountPolicy, givenArg: { classification: TSecuritiesClassification; kind: TSecurityKind; taxTreatment?: TSecuritiesTaxTreatment; bookCents: TCents }, variantArg: 'gain' | 'loss', broughtArg: ReadonlyArray<{ account: string; cents: TCents }>, ): IPair[] { const holding = securitiesHoldingAccountOf(policy, givenArg.classification, givenArg.kind); const taxRule = disposalTaxRuleOf(givenArg); const gross = broughtArg.reduce((sumArg, partArg) => sumArg + partArg.cents, 0); const pairs: IPair[] = []; if (givenArg.classification === 'current') { // the account of a gain or of a loss by the result net of costs, as the costs' account (§ 8b Abs. 2 Satz 2 KStG) const result = securitiesAccountOf(policy, variantArg === 'gain' ? 'sale_gain_current' : 'sale_loss_current', taxRule); // what they brought covers the book value first, in its order, and what is left of it is the gain let toHolding = Math.min(gross, givenArg.bookCents); const gains: IPair[] = []; for (const part of broughtArg) { const covering = Math.min(part.cents, toHolding); toHolding -= covering; pairs.push(pair(part.account, holding, covering)); gains.push(pair(part.account, result, part.cents - covering)); } pairs.push(pair(result, holding, Math.max(givenArg.bookCents - gross, 0)), ...gains); } else { const proceeds = securitiesAccountOf(policy, variantArg === 'gain' ? 'sale_proceeds_fixed_gain' : 'sale_proceeds_fixed_loss', taxRule); pairs.push( ...broughtArg.map((partArg) => pair(partArg.account, proceeds, partArg.cents)), pair(securitiesAccountOf(policy, variantArg === 'gain' ? 'book_value_fixed_gain' : 'book_value_fixed_loss', taxRule), holding, givenArg.bookCents), ); } return pairs; } function disposalTaxRuleOf(inputArg: { kind: TSecurityKind; taxTreatment?: TSecuritiesTaxTreatment }): TTaxRule | undefined { const treatment = inputArg.taxTreatment === undefined ? (inputArg.kind === 'share' ? EIGHT_B : 'ordinary') : inputArg.taxTreatment; switch (treatment) { case 'ordinary': return undefined; case EIGHT_B: return EIGHT_B; default: throw invalid('taxTreatment', `unknown securities tax treatment: ${treatment}`); } } /** Options bought: the premium paid, costs included, an other asset (IDW RS BFA 6), against the cash. */ export function bookOptionPurchase(input: IOptionPurchaseInput, policy: IAccountPolicy): IJournalDraft { requirePositive(input.costCents, 'costCents'); return draftOf(input, policy, [pair(securitiesAccountOf(policy, 'options_held'), cashAccountOf(input.cashAccount), input.costCents)]); } /** * A Termingeschäft closed: options bought sold, expired or settled in cash, * or a warrant or a certificate whose result a person decided is a * Termingeschäft's. The book value leaves; the result goes to the books' * accounts of Termingeschäfte, whose losses § 15 Abs. 4 Satz 3 EStG offsets * only against their gains, for a corporation too (§ 8 Abs. 1 KStG; BFH * I R 60/16). */ export function bookTermingeschaeftClose(input: ITermingeschaeftCloseInput, policy: IAccountPolicy): IJournalDraft { requireNonNegative(input.proceedsCents, 'proceedsCents'); requireNonNegative(input.bookCents, 'bookCents'); const held = input.held.kind === 'option' ? securitiesAccountOf(policy, 'options_held') : securitiesHoldingAccountOf(policy, input.held.classification, 'other'); const gain = securitiesAccountOf(policy, 'termingeschaeft_gain'); const loss = securitiesAccountOf(policy, 'termingeschaeft_loss'); const cash = cashAccountOf(input.cashAccount); const result = input.proceedsCents - input.bookCents; return draftOf( input, policy, result >= 0 ? [pair(cash, held, input.bookCents), pair(cash, gain, result)] : [pair(cash, held, input.proceedsCents), pair(loss, held, -result)], ); } /** * A future's or a CFD's daily settlement (variation margin), held until the * contract closes (§ 252 Abs. 1 Nr. 4 HGB: an open gain is not realised). A * contract's margin is one balance, net: paid beyond what it received an other * asset, received beyond what it paid an other liability. A settlement first * lowers the side the contract stands on, the rest builds the other. */ export function bookVariationMargin(input: IVariationMarginInput, policy: IAccountPolicy): IJournalDraft { requireNonZero(input.amountCents, 'amountCents'); requireWhole(input.heldBeforeCents, 'heldBeforeCents'); const paid = securitiesAccountOf(policy, 'variation_margin_paid'); const received = securitiesAccountOf(policy, 'variation_margin_received'); const cash = cashAccountOf(input.cashAccount); if (input.amountCents > 0) { const lowersPaid = Math.min(input.amountCents, Math.max(-input.heldBeforeCents, 0)); return draftOf(input, policy, [pair(cash, paid, lowersPaid), pair(cash, received, input.amountCents - lowersPaid)]); } const payment = -input.amountCents; const lowersReceived = Math.min(payment, Math.max(input.heldBeforeCents, 0)); return draftOf(input, policy, [pair(received, cash, lowersReceived), pair(paid, cash, payment - lowersReceived)]); } /** * A future or a CFD closed: the variation margin held for the units closed is * the result of a Termingeschäft, a gain where the contract received more than * it paid, a loss where it paid more. */ export function bookContractClose(input: IContractCloseInput, policy: IAccountPolicy): IJournalDraft { requireNonZero(input.variationMarginCents, 'variationMarginCents'); if (input.variationMarginCents > 0) { return draftOf(input, policy, [ pair(securitiesAccountOf(policy, 'variation_margin_received'), securitiesAccountOf(policy, 'termingeschaeft_gain'), input.variationMarginCents), ]); } return draftOf(input, policy, [ pair(securitiesAccountOf(policy, 'termingeschaeft_loss'), securitiesAccountOf(policy, 'variation_margin_paid'), -input.variationMarginCents), ]); } /** * A variation margin paid beyond what the contract received, written off at a * closing date: an open loss (§ 252 Abs. 1 Nr. 4 HGB, imparity), on the * write-downs of current assets other than securities in their usual amount. */ export function bookVariationMarginWriteOff(input: IVariationMarginWriteOffInput, policy: IAccountPolicy): IJournalDraft { requirePositive(input.amountCents, 'amountCents'); return draftOf(input, policy, [ pair(securitiesAccountOf(policy, 'writedown_other_current'), securitiesAccountOf(policy, 'variation_margin_paid'), input.amountCents), ]); } /** * An option written: the premium received is the writer's obligation until * the option expires, is exercised or bought back (BFH 18.12.2002 I R 17/02), * an other liability. */ export function bookWrittenOptionOpen(input: IWrittenOptionOpenInput, policy: IAccountPolicy): IJournalDraft { requirePositive(input.premiumCents, 'premiumCents'); return draftOf(input, policy, [pair(cashAccountOf(input.cashAccount), securitiesAccountOf(policy, 'written_options'), input.premiumCents)]); } /** A written option closed: by expiry, assignment, cash settlement or a buy-back, as its result says (`TWrittenOptionResult`). */ export function bookWrittenOptionClose(input: IWrittenOptionCloseInput, policy: IAccountPolicy): IJournalDraft { requireNonNegative(input.bookCents, 'bookCents'); requireNonNegative(input.costCents, 'costCents'); const obligation = securitiesAccountOf(policy, 'written_options'); const cash = cashAccountOf(input.cashAccount); if (input.result === 'stillhalter_cash_settled') { return draftOf(input, policy, [ pair(obligation, securitiesAccountOf(policy, 'stillhalter_income'), input.bookCents), pair(securitiesAccountOf(policy, 'termingeschaeft_loss'), cash, input.costCents), ]); } const [gain, loss] = input.result === 'stillhalter' ? [securitiesAccountOf(policy, 'stillhalter_income'), securitiesAccountOf(policy, 'stillhalter_income')] : [securitiesAccountOf(policy, 'termingeschaeft_gain'), securitiesAccountOf(policy, 'termingeschaeft_loss')]; const result = input.bookCents - input.costCents; return draftOf( input, policy, result >= 0 ? [pair(obligation, cash, input.costCents), pair(obligation, gain, result)] : [pair(obligation, cash, input.bookCents), pair(loss, cash, -result)], ); } /** * The provision for an expected loss from a written option worth more than * its premium (§ 249 Abs. 1 Satz 1 HGB), formed or raised on the other * operating expenses, released on the income of provisions released. DATEV * marks the provision's account "HB": tax law allows none (§ 5 Abs. 4a EStG). */ export function bookWrittenOptionProvision(input: IProvisionInput, policy: IAccountPolicy): IJournalDraft { requireNonZero(input.amountCents, 'amountCents'); const provision = securitiesAccountOf(policy, 'expected_loss_provision'); if (input.amountCents > 0) { return draftOf(input, policy, [pair(OTHER_OPERATING[chartOf(policy)].expenses, provision, input.amountCents)]); } return draftOf(input, policy, [pair(provision, securitiesAccountOf(policy, 'provision_release'), -input.amountCents)]); } /** * A short sale: securities sold that the depot borrowed. What it brought is * the obligation to deliver them, an other liability, until covered. Refused * until the books keep the accounts of a short sale's result. */ export function bookShortSaleOpen(input: IShortSaleOpenInput, policy: IAccountPolicy): IJournalDraft { requirePositive(input.proceedsCents, 'proceedsCents'); securitiesAccountOf(policy, 'short_sale_gain'); securitiesAccountOf(policy, 'short_sale_loss'); return draftOf(input, policy, [pair(cashAccountOf(input.cashAccount), securitiesAccountOf(policy, 'short_sale_obligations'), input.proceedsCents)]); } /** A short sale covered: the obligation leaves; what it was carried at less what covering cost is the short sale's gain or loss. */ export function bookShortSaleCover(input: IShortSaleCoverInput, policy: IAccountPolicy): IJournalDraft { requireNonNegative(input.costCents, 'costCents'); requireNonNegative(input.bookCents, 'bookCents'); const obligation = securitiesAccountOf(policy, 'short_sale_obligations'); const gain = securitiesAccountOf(policy, 'short_sale_gain'); const loss = securitiesAccountOf(policy, 'short_sale_loss'); const cash = cashAccountOf(input.cashAccount); const result = input.bookCents - input.costCents; return draftOf( input, policy, result >= 0 ? [pair(obligation, cash, input.costCents), pair(obligation, gain, result)] : [pair(obligation, cash, input.bookCents), pair(loss, cash, -result)], ); } /** * The obligation of a short sale valued at a closing date: raised to a * higher market value, an open loss (§ 252 Abs. 1 Nr. 4, § 253 Abs. 1 Satz 2 * HGB), or lowered back toward what it brought. */ export function bookShortSaleValuation(input: IObligationValuationInput, policy: IAccountPolicy): IJournalDraft { requireNonZero(input.amountCents, 'amountCents'); const obligation = securitiesAccountOf(policy, 'short_sale_obligations'); if (input.amountCents > 0) { return draftOf(input, policy, [pair(securitiesAccountOf(policy, 'short_sale_loss'), obligation, input.amountCents)]); } return draftOf(input, policy, [pair(obligation, securitiesAccountOf(policy, 'short_sale_gain'), -input.amountCents)]); } /** * Securities lent (a Sachdarlehen, the broker's securities lending): the * units leave the holding at their book value for the claim to their return * (BFH I R 40/17), which their return sets off again. */ export function bookSecuritiesLending(input: ISecuritiesLendingInput, policy: IAccountPolicy): IJournalDraft { requireNonZero(input.bookCents, 'bookCents'); return draftOf(input, policy, [ pair(securitiesAccountOf(policy, 'lending_claim'), securitiesHoldingAccountOf(policy, input.classification, input.kind), input.bookCents), ]); } /** * A security's income, gross of tax withheld (which `bookWithholdingTax` * books): a dividend, a fund's distribution, a bond's coupon, on the income * account of a fixed or a current asset; a dividend of a holding of at least * 10 % (§ 8b Abs. 1 and 4 KStG) on its § 8b account. */ export function bookSecuritiesIncome(input: ISecuritiesIncomeInput, policy: IAccountPolicy): IJournalDraft { requireNonZero(input.amountCents, 'amountCents'); if (input.participation10 === true && input.kind !== 'dividend') { throw invalid('participation10', `participation10 marks a dividend (§ 8b Abs. 1 and 4 KStG), not a ${input.kind}`); } const income = securitiesAccountOf(policy, input.classification === 'fixed' ? 'income_fixed' : 'income_current', input.participation10 === true ? EIGHT_B : undefined); return draftOf(input, policy, [pair(cashAccountOf(input.cashAccount), income, input.amountCents)]); } /** * Tax withheld from a security's income (`TWithholdingKind`), against the * cash: German Kapitalertragsteuer split into the tax and its * Solidaritätszuschlag (5.5 % of the tax), each on its own account. */ export function bookWithholdingTax(input: IWithholdingTaxInput, policy: IAccountPolicy): IJournalDraft { requireNonZero(input.amountCents, 'amountCents'); const cash = cashAccountOf(input.cashAccount); if (input.kind === 'capital_gains_tax') { const soli = input.soliCents ?? soliIn(input.amountCents); requireWhole(soli, 'soliCents'); if (Math.sign(soli) === -Math.sign(input.amountCents) || Math.abs(soli) > Math.abs(input.amountCents)) { throw invalid('soliCents', `soliCents ${soli} is a part of the amount ${input.amountCents}, of its sign`, soli); } return draftOf(input, policy, [ pair(securitiesAccountOf(policy, 'capital_gains_tax'), cash, input.amountCents - soli), pair(securitiesAccountOf(policy, 'capital_gains_tax_soli'), cash, soli), ]); } if (input.soliCents !== undefined) { throw invalid('soliCents', `soliCents belongs to the German Kapitalertragsteuer, not to ${input.kind}`); } const role: TSecuritiesRole = input.kind === 'foreign_creditable' ? 'foreign_withholding_tax' : input.kind === 'foreign_on_exempt_income' ? 'foreign_tax_exempt_income' : 'foreign_tax_refund'; return draftOf(input, policy, [pair(securitiesAccountOf(policy, role), cash, input.amountCents)]); } /** Interest and charges around a depot (`TDepotInterestKind`), against its cash. */ export function bookDepotInterest(input: IDepotInterestInput, policy: IAccountPolicy): IJournalDraft { requireNonZero(input.amountCents, 'amountCents'); const cash = cashAccountOf(input.cashAccount); switch (input.kind) { case 'credit_interest': case 'lending_fee': return draftOf(input, policy, [pair(cash, otherIncomeAccount(policy, 'interest'), input.amountCents)]); case 'compensation_received': return draftOf(input, policy, [pair(cash, OTHER_OPERATING[chartOf(policy)].income, input.amountCents)]); case 'margin_interest': return draftOf(input, policy, [pair(securitiesAccountOf(policy, 'margin_interest'), cash, input.amountCents)]); case 'borrow_fee': return draftOf(input, policy, [pair(securitiesAccountOf(policy, 'borrow_fees'), cash, input.amountCents)]); case 'compensation_paid': return draftOf(input, policy, [pair(securitiesAccountOf(policy, 'compensation_paid'), cash, input.amountCents)]); } } /** * A bond's accrued interest (Stückzinsen): paid with a purchase, a claim * beside the bond, not its cost; received with a sale or a coupon, first the * claim set off, the rest interest earned on the income account of the bond's * classification. */ export function bookAccruedInterest(input: IAccruedInterestInput, policy: IAccountPolicy): IJournalDraft { requireNonNegative(input.paidCents, 'paidCents'); requireNonNegative(input.setOffCents, 'setOffCents'); requireWhole(input.incomeCents, 'incomeCents'); if (input.paidCents === 0 && input.setOffCents === 0 && input.incomeCents === 0) { throw invalid('paidCents', 'the accrued interest moves nothing: paid, set off and income are 0'); } const claim = securitiesAccountOf(policy, 'accrued_interest_claim'); const cash = cashAccountOf(input.cashAccount); return draftOf(input, policy, [ pair(claim, cash, input.paidCents), pair(cash, claim, input.setOffCents), pair(cash, incomeAccountOf(policy, input.classification), input.incomeCents), ]); } /** A bond's interest accrued at a closing date (§ 252 Abs. 1 Nr. 5 HGB), a claim the next coupon sets off. */ export function bookInterestAccrual(input: IInterestAccrualInput, policy: IAccountPolicy): IJournalDraft { requirePositive(input.amountCents, 'amountCents'); return draftOf(input, policy, [pair(securitiesAccountOf(policy, 'accrued_interest_claim'), incomeAccountOf(policy, input.classification), input.amountCents)]); } /** * A bond's book value moved toward what it repays, against its interest * income: a premium paid above par spread to maturity lowers it * (`amortisation`), a zero bond's interest accrued raises it (`accretion`). */ export function bookBondInterestAdjustment(input: IBondInterestAdjustmentInput, policy: IAccountPolicy): IJournalDraft { requirePositive(input.amountCents, 'amountCents'); const holding = securitiesHoldingAccountOf(policy, input.classification, 'bond'); const income = incomeAccountOf(policy, input.classification); return draftOf(input, policy, [input.kind === 'amortisation' ? pair(income, holding, input.amountCents) : pair(holding, income, input.amountCents)]); } /** * A write-down at a closing date (§ 253 HGB): a current asset to its lower * market price (Abs. 4), a fixed asset for a lasting decline (Abs. 3 Satz 5) * or, a Finanzanlage, for a temporary one by choice (Satz 6, on DATEV's * account it marks "HB"), options bought on the write-downs of current assets * other than securities. A share's on the § 8b accounts (§ 8b Abs. 3 KStG), * except the temporary one, which tax law does not follow anyway. */ export function bookSecuritiesWriteDown(input: ISecuritiesWriteDownInput, policy: IAccountPolicy): IJournalDraft { requirePositive(input.amountCents, 'amountCents'); if (input.held === 'option') { return draftOf(input, policy, [ pair(securitiesAccountOf(policy, 'writedown_other_current'), securitiesAccountOf(policy, 'options_held'), input.amountCents), ]); } if ((input.classification === 'fixed') !== (input.decline !== undefined)) { throw invalid('decline', input.classification === 'fixed' ? 'a fixed asset\'s write-down states whether its decline lasts' : 'a current asset is written down to its market price whatever its decline'); } const taxRule = input.held === 'share' ? EIGHT_B : undefined; const expense = input.classification === 'current' ? securitiesAccountOf(policy, 'writedown_current', taxRule) : input.decline === 'lasting' ? securitiesAccountOf(policy, 'writedown_fixed_lasting', taxRule) : securitiesAccountOf(policy, 'writedown_fixed_temporary'); return draftOf(input, policy, [pair(expense, securitiesHoldingAccountOf(policy, input.classification, input.held), input.amountCents)]); } /** * A write-up at a closing date: a lower value whose reason has gone is not * kept (§ 253 Abs. 5 HGB), up to what the units cost. A share's on the one § * 8b account of write-ups, options bought on the write-ups of current assets. */ export function bookSecuritiesWriteUp(input: ISecuritiesWriteUpInput, policy: IAccountPolicy): IJournalDraft { requirePositive(input.amountCents, 'amountCents'); if (input.held === 'option') { return draftOf(input, policy, [pair(securitiesAccountOf(policy, 'options_held'), securitiesAccountOf(policy, 'writeup_current'), input.amountCents)]); } const income = input.held === 'share' ? securitiesAccountOf(policy, 'writeup', EIGHT_B) : securitiesAccountOf(policy, input.classification === 'fixed' ? 'writeup_fixed' : 'writeup_current'); return draftOf(input, policy, [pair(securitiesHoldingAccountOf(policy, input.classification, input.held), income, input.amountCents)]); } /** Securities moved between fixed and current assets (Umwidmung) at their book value. */ export function bookSecuritiesReclassification(input: ISecuritiesReclassificationInput, policy: IAccountPolicy): IJournalDraft { requirePositive(input.bookCents, 'bookCents'); if (input.from === input.to) { throw invalid('to', `a reclassification moves securities from one classification to the other, not within ${input.from} assets`); } return draftOf(input, policy, [pair(securitiesHoldingAccountOf(policy, input.to, input.kind), securitiesHoldingAccountOf(policy, input.from, input.kind), input.bookCents)]); } /** * Securities received in a corporate action that carries the book value of the * securities given over to them (a spin-off or a merger at book value, as a * person decided: the depot's allocation): the part each takes over moves from * the holding of the securities given to the holding of its kind, in the same * classification; nothing is realised. Where the securities received are held * on the account of the securities given (a current asset's always), nothing * moves: the draft has no lines, and the caller posts nothing. */ export function bookSecuritiesAllocation(input: ISecuritiesAllocationInput, policy: IAccountPolicy): IJournalDraft { if (!Array.isArray(input.received) || input.received.length === 0) { throw invalid('received', 'an allocation names the securities received'); } const given = securitiesHoldingAccountOf(policy, input.classification, input.kind); const moved = new Map(); for (const received of input.received) { requireNonNegative(received.bookCents, 'received.bookCents'); const account = securitiesHoldingAccountOf(policy, input.classification, received.kind); if (account !== given) moved.set(account, (moved.get(account) ?? 0) + received.bookCents); } return draftOf(input, policy, [...moved].map(([accountArg, centsArg]) => pair(accountArg, given, centsArg))); } /** * Securities given for others in a corporate action that realises them (an * exchange at the gemeiner Wert, § 6 Abs. 6 Satz 1 EStG, as a person decided: * the depot's realizing decision with the securities received): the securities * given leave as in a sale (`bookSecuritiesSale`: a current asset net, a fixed * asset gross, by default a share's on the § 8b accounts), and what they * brought is the securities received, at their cost, with money received alongside or less * money paid for them; no costs. The securities received come in on the * holding of their classification and kind; money paid for them is part of * their cost. An explicit `taxTreatment` selects the tax accounts of the * securities given, never the holding accounts. Securities received on the * holding of the securities given at their book value, without money, move * nothing: the draft has no lines. */ export function bookSecuritiesExchange(input: ISecuritiesExchangeInput, policy: IAccountPolicy): IJournalDraft { requireNonNegative(input.bookCents, 'bookCents'); requireNonNegative(input.received.valueCents, 'received.valueCents'); const cashCents = input.cashCents ?? 0; requireWhole(cashCents, 'cashCents'); const brought = input.received.valueCents + cashCents; if (brought < 0) { throw invalid('cashCents', `the money paid, ${-cashCents}, exceeds the value of the securities received, ${input.received.valueCents}: the securities given brought less than nothing`, cashCents); } const received = securitiesHoldingAccountOf(policy, input.received.classification, input.received.kind); const cash = cashCents === 0 ? undefined : cashAccountOf(input.cashAccount ?? ''); const variant = brought - input.bookCents >= 0 ? 'gain' : 'loss'; const sources = cash === undefined ? [{ account: received, cents: input.received.valueCents }] : cashCents > 0 ? [{ account: received, cents: input.received.valueCents }, { account: cash, cents: cashCents }] : [{ account: received, cents: brought }]; const pairs = disposalPairsOf(policy, input, variant, sources); if (cash !== undefined && cashCents < 0) pairs.push(pair(received, cash, -cashCents)); // a security received on the holding of the securities given books nothing against itself return draftOf(input, policy, pairs.filter((pairArg) => pairArg.debit !== pairArg.credit)); } /** * A currency conversion between two cash accounts of a depot, at the euros * of the conversion: both legs are worth them on the day, so nothing is * gained or lost; its commission is a fee of its own (`bookPaymentFee`), and * what the foreign balance is worth later the currency revaluation's. */ export function bookCurrencyConversion(input: ICurrencyConversionInput, policy: IAccountPolicy): IJournalDraft { requirePositive(input.amountCents, 'amountCents'); const from = cashAccountOf(input.fromAccount, 'fromAccount'); const to = cashAccountOf(input.toAccount, 'toAccount'); if (from === to) throw invalid('toAccount', `a conversion moves money between two accounts, not within ${from}`); return draftOf(input, policy, [pair(to, from, input.amountCents)]); } // ------------------------------------------------------------------ helpers /** * The Solidaritätszuschlag in an amount of Kapitalertragsteuer with its Solidaritätszuschlag: 5.5 % of the tax, * fractions of a cent dropped (§ 4 Sätze 1 and 3 SolZG), so the tax with it rises by one or two cents a cent of tax * and every amount is one tax's or none. Refuses an amount no tax gives. */ function soliIn(amountCents: TCents): TCents { const total = Math.abs(amountCents); const soliOf = (taxArg: number): number => Math.floor((taxArg * 55) / 1000); for (let tax = Math.max(Math.floor((total * 1000) / 1055) - 2, 0); tax <= total; tax++) { const sum = tax + soliOf(tax); if (sum === total) return Math.sign(amountCents) * soliOf(tax); if (sum > total) break; } throw invalid('amountCents', `no Kapitalertragsteuer gives ${amountCents} cents with its Solidaritätszuschlag (§ 4 SolZG): state soliCents`, amountCents); } function incomeAccountOf(policy: IAccountPolicy, classification: TSecuritiesClassification): string { return securitiesAccountOf(policy, classification === 'fixed' ? 'income_fixed' : 'income_current'); } /** A booking of an amount on a debit account against a credit account; a negative amount books the other way. */ interface IPair { debit: string; credit: string; amountCents: TCents; } function pair(debit: string, credit: string, amountCents: TCents): IPair { return { debit, credit, amountCents }; } function draftOf(input: ISecuritiesBookingBase, policy: IAccountPolicy, pairs: IPair[]): IJournalDraft { const lineOf = (accountArg: string, counterArg: string, sideArg: 'debit' | 'credit', centsArg: TCents): IJournalLineDraft => ({ accountNumber: accountArg, counterAccount: counterArg, side: sideArg, amountCents: centsArg, buKey: '', buchungstext: input.description, ...(input.reference !== undefined ? { belegfeld1: input.reference } : {}), ...(input.docLink !== undefined ? { docLink: input.docLink } : {}), }); const lines: IJournalLineDraft[] = []; for (const { debit, credit, amountCents } of pairs) { if (amountCents === 0) continue; const [to, from, cents] = amountCents > 0 ? [debit, credit, amountCents] : [credit, debit, -amountCents]; lines.push(lineOf(to, from, 'debit', cents), lineOf(from, to, 'credit', cents)); } return { date: input.date, description: input.description, ...(input.reference !== undefined ? { reference: input.reference } : {}), skrType: chartOf(policy), currency: 'EUR', lines, }; } function cashAccountOf(account: string, field = 'cashAccount'): string { if (typeof account !== 'string' || account.trim() === '') { throw invalid(field, `${field} names no account`); } return account; } function invalid(field: string, message: string, amountCents?: number): RecipeRefusalError { return new RecipeRefusalError('securities_input_invalid', message, { field, ...(amountCents !== undefined ? { amountCents } : {}) }); } function requireWhole(amountCents: TCents, field: string): void { if (!Number.isSafeInteger(amountCents)) { throw new RecipeRefusalError('amount_not_whole_cents', `${field} must be whole cents, got ${amountCents}`, { field, amountCents }); } } function requirePositive(amountCents: TCents, field: string): void { if (!Number.isSafeInteger(amountCents) || amountCents <= 0) { throw new RecipeRefusalError('amount_not_positive', `${field} must be a positive integer cent amount, got ${amountCents}`, { field, amountCents }); } } function requireNonNegative(amountCents: TCents, field: string): void { requireWhole(amountCents, field); if (amountCents < 0) throw invalid(field, `${field} cannot be negative, got ${amountCents}`, amountCents); } function requireNonZero(amountCents: TCents, field: string): void { requireWhole(amountCents, field); if (amountCents === 0) throw invalid(field, `${field} is 0: nothing to book`, amountCents); }