/** * Booking recipes of an expense claim — pure builders, like `core.recipes.ts`: * (input, policy) => IJournalDraft, integer cents. An employee or a guest laid * money out for the business (Auslagenersatz, Reisekostenabrechnung), and the * business owes it back: the claim books against the person's own creditor * account, or, where the books keep no account per person, against the Lohn- * und Gehaltsverrechnungskonto (@fin.cx/chartdata payroll role `clearing`: * SKR 03 1755, SKR 04 3790), always under the claim's number as Belegfeld 1, * the key of its open item. They book what the claim decided — the * allowances, the receipts, a business meal's part that is not deductible, as * @fin.cx/expenses computes them — on the accounts of the expense roles * (@fin.cx/chartdata `TExpenseRole`, `expenseAccountOf`): the account DATEV's * chart keeps for the role (DATEV Kontenrahmen SKR 03, Art.-Nr. 11174, and * SKR 04, Art.-Nr. 11175, gültig für 2026), which every role has in both * charts. * * A receipt books through `bookVendorDocument`, with the person in the place * of the supplier; the payout and the private use of a company card through * `bookBankPayment`. Every recipe takes the day the caller books on. */ import * as plugins from './core.plugins.js'; import type { IJournalDraft, IJournalLineDraft, TCents, TTaxScenario } from './core.types.js'; import type { IAccountPolicy } from './core.accountpolicy.js'; import { isCreditorAccount } from './core.accountpolicy.js'; import { booksChartOf } from './core.booksaccounts.js'; import { chartOf } from './core.chart.js'; import { RecipeRefusalError, type IRecipeRefusalDetails } from './core.errors.js'; import { bookBankPayment, bookVendorDocument, deductibleVatCentsOf, type IDocumentVatGroup } from './core.recipes.js'; import { payrollAccountOf } from './core.recipes.payroll.js'; const { splitGrossCents } = plugins.calculation; /** What an account books of the expenses a person lays out and claims back (@fin.cx/chartdata `TExpenseRole`). */ export type TExpenseRole = plugins.chartdata.TExpenseRole; /** * The account the books book an expense role on: the account DATEV's chart * keeps for it (`booksChartOf`; an individual account takes no expense role). * Refuses a role the chart keeps no account for (`expense_account_missing`), * which no role of a chart of this package's data is. */ export function expenseAccountOf(policy: IAccountPolicy, role: TExpenseRole): string { const account = booksChartOf(policy).getExpenseAccount(role); if (account === null || account === undefined) { throw new RecipeRefusalError('expense_account_missing', `${chartOf(policy)} keeps no account for the expense role ${String(role)}`, { field: String(role) }); } return account.accountNumber; } /** * Whom a claim is settled with: the person's own creditor account (a * Kreditor per person, in `policy.creditorRange`), or the books' Lohn- und * Gehaltsverrechnungskonto, which keeps no open items. */ export type TExpenseClaimSettlement = { kind: 'person'; account: string } | { kind: 'payroll_clearing' }; /** * The account a claim settles on: the person's creditor account, refused * where it is none (`personal_account_required`), or the account of the * payroll role `clearing` (`payrollAccountOf`). */ export function expenseClaimSettlementAccountOf(policy: IAccountPolicy, settlement: TExpenseClaimSettlement): string { if (settlement?.kind === 'payroll_clearing') { return payrollAccountOf(policy, 'clearing'); } if (settlement?.kind === 'person') { const account = settlement.account; if (typeof account !== 'string' || !/^\d+$/u.test(account) || !isCreditorAccount(policy, account)) { throw new RecipeRefusalError( 'personal_account_required', `settlement.account ${String(account)} is no creditor account of a person (${policy.creditorRange[0]}–${policy.creditorRange[1]}) in ${policy.skrType}`, { field: 'settlement.account', account: String(account) }, ); } return account; } throw invalid('settlement', `settlement is the person's account ({ kind: 'person', account }) or the payroll clearing account ({ kind: 'payroll_clearing' })`); } // ------------------------------------------------------------------ allowances /** An allowance of a claim, a line of its own rather than a receipt: per diems, mileage, a lodging flat. */ export type TExpenseClaimAllowanceKind = 'per_diem' | 'mileage' | 'lodging_flat'; /** The expense role of each allowance: Verpflegungsmehraufwand, Kilometergelderstattung, Übernachtungsaufwand of employees. */ export const EXPENSE_CLAIM_ALLOWANCE_ROLES: Readonly> = { per_diem: 'travel_employee_meals', mileage: 'mileage_employee', lodging_flat: 'travel_employee_lodging', }; /** One allowance of a claim, as @fin.cx/expenses computed it, with the cost centre and project of its line. */ export interface IExpenseClaimAllowance { kind: TExpenseClaimAllowanceKind; /** positive integer cents */ amountCents: TCents; /** KOST1, the cost centre */ costCenter1?: string; /** KOST2, the project */ costCenter2?: string; } /** What every booking of a claim states. */ export interface IExpenseClaimBookingBase { /** the booking day: of the allowances the day the claim was approved, of a receipt its voucher's day */ date: Date; description: string; /** the claim's number: Belegfeld 1 of every line and the entry's reference, the key of the claim's open item */ claimNumber: string; settlement: TExpenseClaimSettlement; /** the Beleg: of the allowances the claim's Eigenbeleg, of a receipt the receipt */ docLink?: string; } export interface IExpenseClaimAllowancesInput extends IExpenseClaimBookingBase { allowances: IExpenseClaimAllowance[]; } /** * A claim's allowances on its Eigenbeleg: each on the account of its role * (`EXPENSE_CLAIM_ALLOWANCE_ROLES`: SKR03 4664, 4668, 4666; SKR04 6664, 6668, * 6660) against the settlement account, one booking per allowance in the * order given, with its cost centres on both lines, without a key: a flat * amount carries no input tax. Refuses no allowance, an unknown kind * (`expense_claim_input_invalid`), an amount of no positive whole cents * (`amount_not_positive`, `amount_not_whole_cents`) and a claim without its * number. */ export function bookExpenseClaimAllowances(input: IExpenseClaimAllowancesInput, policy: IAccountPolicy): IJournalDraft { const claimNumber = claimNumberOf(input.claimNumber); const settlement = expenseClaimSettlementAccountOf(policy, input.settlement); if (!Array.isArray(input.allowances) || input.allowances.length === 0) { throw invalid('allowances', 'allowances lists no allowance: nothing to book'); } const lines: IJournalLineDraft[] = []; input.allowances.forEach((allowance, index) => { const field = `allowances[${index}]`; if (!Object.prototype.hasOwnProperty.call(EXPENSE_CLAIM_ALLOWANCE_ROLES, allowance?.kind)) { throw invalid(`${field}.kind`, `${String(allowance?.kind)} is no allowance (${Object.keys(EXPENSE_CLAIM_ALLOWANCE_ROLES).join(', ')})`); } requirePositive(allowance.amountCents, `${field}.amountCents`); const account = expenseAccountOf(policy, EXPENSE_CLAIM_ALLOWANCE_ROLES[allowance.kind]); const common = { amountCents: allowance.amountCents, buKey: '' as const, buchungstext: input.description, belegfeld1: claimNumber, ...(allowance.costCenter1 !== undefined ? { costCenter1: allowance.costCenter1 } : {}), ...(allowance.costCenter2 !== undefined ? { costCenter2: allowance.costCenter2 } : {}), ...(input.docLink !== undefined ? { docLink: input.docLink } : {}), }; lines.push( { accountNumber: account, counterAccount: settlement, side: 'debit', ...common }, { accountNumber: settlement, counterAccount: account, side: 'credit', ...common }, ); }); return { date: input.date, description: input.description, reference: claimNumber, skrType: chartOf(policy), currency: 'EUR', lines, }; } // ------------------------------------------------------------------ receipts /** The roles a receipt of a claim books on; the allowances' own roles, the non-deductible meals and the card's clearing are none. */ export type TExpenseClaimReceiptRole = Exclude; export const EXPENSE_CLAIM_RECEIPT_ROLES: readonly TExpenseClaimReceiptRole[] = [ 'travel_employee', 'travel_employee_transport', 'travel_employee_lodging', 'business_meals', 'vehicle_running_costs', 'office_supplies', 'postage', 'literature', 'training', 'software', 'other_operating_expenses', ]; /** * The scenarios of a receipt a person brings: German VAT at 19 or 7 %, or none * (`domestic_tax_free`: a receipt without German VAT, such as a hotel abroad, * whose foreign tax is cost). */ export type TExpenseClaimReceiptScenario = Extract; const EXPENSE_CLAIM_RECEIPT_SCENARIOS: readonly TExpenseClaimReceiptScenario[] = ['domestic_standard', 'domestic_reduced', 'domestic_tax_free']; /** One VAT group of a receipt, as its voucher states it (`IDocumentVatGroup`, positive). */ export interface IExpenseClaimReceiptGroup { /** the group's gross, positive integer cents; 0 books nothing */ amountCents: TCents; vatRatePercent?: number; /** `domestic_standard` where unset */ scenario?: TExpenseClaimReceiptScenario; /** the tax as the receipt states it (`IDocumentVatGroup.vatCents`) */ vatCents?: TCents; } /** * A business meal's split (§ 4 Abs. 5 Satz 1 Nr. 2 EStG), as `businessMealOf` * of @fin.cx/expenses computes it: the part of the meal's expense that is not * deductible, the tip included. */ export interface IExpenseClaimBusinessMeal { /** the non-deductible 30 % of the expense, positive integer cents */ nondeductibleCents: TCents; /** a tip paid on top of the invoice, which bears no VAT and is part of the expense; 0 where absent */ tipCents?: TCents; } export interface IExpenseClaimReceiptInput extends IExpenseClaimBookingBase { role: TExpenseClaimReceiptRole; groups: IExpenseClaimReceiptGroup[]; /** whether the receipt's input tax may be deducted (`inputVatOf` of @fin.cx/expenses); not: all of it is cost */ inputVat: 'deductible' | 'not_deductible'; /** * With `inputVat: 'deductible'`, for a receipt whose supply serves both * taxable and exempt sales: the key of § 15 Abs. 4 UStG, the deductible * part in percent, above 0 and below 100 with up to two places (62.5). Of * each group's tax only that part is deducted (`deductibleVatCentsOf`), the * rest is cost with its base. Absent: all of it is deducted. */ deductiblePercent?: number; /** a business meal's split: required on `business_meals`, refused on another role */ businessMeal?: IExpenseClaimBusinessMeal; /** KOST1, the cost centre */ costCenter1?: string; /** KOST2, the project */ costCenter2?: string; } /** * A receipt of a claim, booked as the vendor document it is * (`bookVendorDocument`) with the person's settlement account in the place of * the supplier's and the claim's number as the open item's: each VAT group on * the account of the receipt's role, its input tax by key; a tax that may not * be deducted as cost with its base (`nonDeductibleVatCents` of all of it), and * one deducted in part by a key (`deductiblePercent`) the rest of it. * A business meal books the part of its expense that is not deductible on * `business_meals_nondeductible` (SKR03 4654, SKR04 6644) beside * `business_meals` (4650, 6640), split over its groups and its tip, which is * a group without VAT of its own; its input tax is deducted in full as a * booking of its own, without a key (`IVendorDocumentInput.nondeductibleExpense`). * Returns the entries in the order of the groups, the tip's last. * * Refused (`expense_claim_input_invalid`): a role no receipt takes, a business * meal without its split or a split on another role, a group that is negative * or of another scenario, a negative tip, an unknown `inputVat`, a key beside * `inputVat: 'not_deductible'` and a claim without its number; a key that is * not above 0 and below 100 with up to two places (`non_deductible_vat_invalid`); a receipt without groups (`document_groups_missing`: a * tip alone is none); and whatever `bookVendorDocument` refuses. */ export function bookExpenseClaimReceipt(input: IExpenseClaimReceiptInput, policy: IAccountPolicy): IJournalDraft[] { const claimNumber = claimNumberOf(input.claimNumber); const settlement = expenseClaimSettlementAccountOf(policy, input.settlement); if (!EXPENSE_CLAIM_RECEIPT_ROLES.includes(input.role)) { throw invalid('role', `${String(input.role)} is no role of a receipt (${EXPENSE_CLAIM_RECEIPT_ROLES.join(', ')})`); } if (input.inputVat !== 'deductible' && input.inputVat !== 'not_deductible') { throw invalid('inputVat', `inputVat is 'deductible' or 'not_deductible', not ${String(input.inputVat)}`); } const deductiblePercent = input.deductiblePercent; if (deductiblePercent !== undefined && input.inputVat !== 'deductible') { throw invalid('deductiblePercent', "deductiblePercent is the key of a tax deducted in part, with inputVat 'deductible'; a tax not deducted is all cost"); } const meal = input.businessMeal; if ((input.role === 'business_meals') !== (meal !== undefined)) { throw invalid( 'businessMeal', input.role === 'business_meals' ? 'a business meal books the part of its expense that is not deductible (businessMeal.nondeductibleCents)' : `businessMeal is a business meal's split, not one of a receipt on ${input.role}`, ); } const tipCents = meal?.tipCents ?? 0; if (!Number.isSafeInteger(tipCents) || tipCents < 0) { throw invalid('businessMeal.tipCents', `businessMeal.tipCents must be whole cents, 0 or more, got ${tipCents}`, { amountCents: tipCents }); } if (!Array.isArray(input.groups) || input.groups.length === 0) { // a tip alone is no receipt throw new RecipeRefusalError('document_groups_missing', 'groups must list the VAT groups of the receipt', { field: 'groups' }); } const account = expenseAccountOf(policy, input.role); const groups: IDocumentVatGroup[] = input.groups.map((group) => { const scenario = group?.scenario ?? 'domestic_standard'; if (!EXPENSE_CLAIM_RECEIPT_SCENARIOS.includes(scenario)) { throw invalid('groups.scenario', `a receipt's group is taxed at 19 or 7 % or without German VAT (${EXPENSE_CLAIM_RECEIPT_SCENARIOS.join(', ')}), not under ${String(scenario)}`, { scenario }); } if (typeof group.amountCents === 'number' && group.amountCents < 0) { throw invalid('groups.amountCents', `a receipt's group is positive, got ${group.amountCents}; a claim is corrected by its reversal`, { amountCents: group.amountCents }); } return { amountCents: group.amountCents, ...(group.vatRatePercent !== undefined ? { vatRatePercent: group.vatRatePercent } : {}), scenario, ...(group.vatCents !== undefined ? { vatCents: group.vatCents } : {}), account, ...nonDeductibleOfGroup(group, scenario, input.inputVat, deductiblePercent), }; }); if (tipCents > 0) { // the tip is no consideration of the supply: no German VAT, booked as a group without it groups.push({ amountCents: tipCents, scenario: 'domestic_tax_free', account }); } return bookVendorDocument( { date: input.date, vendorAccount: settlement, document: { kind: 'invoice', invoiceNumber: claimNumber }, groups, ...(meal !== undefined ? { nondeductibleExpense: { account: expenseAccountOf(policy, 'business_meals_nondeductible'), amountCents: meal.nondeductibleCents } } : {}), description: input.description, ...(input.costCenter1 !== undefined ? { costCenter1: input.costCenter1 } : {}), ...(input.costCenter2 !== undefined ? { costCenter2: input.costCenter2 } : {}), ...(input.docLink !== undefined ? { docLink: input.docLink } : {}), }, policy, ); } /** * The part of a receipt's group's German tax that is cost * (`IDocumentVatGroup.nonDeductibleVatCents`): all of it where the input tax may * not be deducted, the rest beside the deductible part of a key, none otherwise. */ function nonDeductibleOfGroup( groupArg: IExpenseClaimReceiptGroup, scenarioArg: TExpenseClaimReceiptScenario, inputVatArg: IExpenseClaimReceiptInput['inputVat'], deductiblePercentArg: number | undefined, ): Pick { if (inputVatArg === 'not_deductible') { return { nonDeductibleVatCents: receiptGroupVatOf(groupArg, scenarioArg) }; } if (deductiblePercentArg === undefined) { return {}; } // the key is checked on every group, one without German tax too const vatCents = receiptGroupVatOf(groupArg, scenarioArg); return { nonDeductibleVatCents: vatCents - deductibleVatCentsOf(vatCents, deductiblePercentArg) }; } /** * The German tax of a receipt's group, all of which a receipt whose input tax * may not be deducted books as cost: the tax stated, else what the rate gives * (as `bookVendorDocument` books it); none without German VAT. A tax stated off * its rate is refused there. */ function receiptGroupVatOf(groupArg: IExpenseClaimReceiptGroup, scenarioArg: TExpenseClaimReceiptScenario): TCents { if (scenarioArg === 'domestic_tax_free' || !Number.isSafeInteger(groupArg.amountCents)) { return 0; } return groupArg.vatCents ?? splitGrossCents(groupArg.amountCents, groupArg.vatRatePercent ?? (scenarioArg === 'domestic_reduced' ? 7 : 19)).vatCents; } // ------------------------------------------------------------------ private use of a company card /** A payment by a company card that the holder made for themselves, which the holder owes back. */ export interface IPersonReceivableInput { /** the card payment's day */ date: Date; /** the holder's account, or the payroll clearing account */ settlement: TExpenseClaimSettlement; /** * the account the card payment left: a credit card's own account, or its * clearing account (`expenseAccountOf(policy, 'credit_card_settlement')`: * SKR03 1730, SKR04 3610), or for a debit card the bank account it pays from */ cardAccount: string; /** positive integer cents */ amountCents: TCents; description: string; /** Belegfeld 1: the receivable's own number, the key of its open item, never a claim's */ reference: string; } /** * Private use of a company card (not the books' Privatentnahme): the holder's * account debited — a receivable, which a payout sets off * (`bookPersonalAccountOffset`) or the holder repays — against the card's * account, through `bookBankPayment` (an outgoing payment of the amount to the * settlement account, from the card's account). Refused * (`expense_claim_input_invalid`): a card account that is blank or the * settlement account itself, a blank reference; an amount of no positive * whole cents (`amount_not_positive`, `amount_not_whole_cents`). */ export function bookPersonReceivable(input: IPersonReceivableInput, policy: IAccountPolicy): IJournalDraft { const settlement = expenseClaimSettlementAccountOf(policy, input.settlement); const cardAccount = input.cardAccount; if (typeof cardAccount !== 'string' || cardAccount.trim() === '') { throw invalid('cardAccount', 'cardAccount names no account the card payment left'); } if (cardAccount === settlement) { throw invalid('cardAccount', `cardAccount ${cardAccount} is the settlement account itself`, { account: cardAccount }); } if (typeof input.reference !== 'string' || input.reference.trim() === '') { throw invalid('reference', 'reference names no number of the receivable, the key of its open item'); } requirePositive(input.amountCents, 'amountCents'); return bookBankPayment( { date: input.date, direction: 'outgoing', bankAccount: cardAccount, counterpartyAccount: settlement, expectedCents: input.amountCents, paidCents: input.amountCents, description: input.description, reference: input.reference.trim(), }, policy, ); } // ------------------------------------------------------------------ helpers function claimNumberOf(claimNumberArg: string): string { const claimNumber = typeof claimNumberArg === 'string' ? claimNumberArg.trim() : ''; if (claimNumber === '') { throw invalid('claimNumber', "claimNumber names no number: it is Belegfeld 1, the key of the claim's open item"); } return claimNumber; } function requirePositive(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 }); } if (amountCents <= 0) { throw new RecipeRefusalError('amount_not_positive', `${field} must be a positive integer cent amount, got ${amountCents}`, { field, amountCents }); } } function invalid(field: string, message: string, detailsArg: Omit = {}): RecipeRefusalError { return new RecipeRefusalError('expense_claim_input_invalid', message, { field, ...detailsArg }); }