/** * Booking recipes of a business's payroll — pure builders, like * `core.recipes.ts`: (input, policy) => IJournalDraft, integer cents. They book * what a payroll decided (a run's Buchungsbeleg: its totals per account, with * no person's line) on the accounts of the payroll roles (@fin.cx/chartdata * `TPayrollRole`), resolved for the books by `payrollAccountOf`: 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 run is booked as DATEV's payroll bookings are, through the Lohn- und * Gehaltsverrechnungskonto (role `clearing`: SKR 03 1755, SKR 04 3790): every * cost of the run on its expense account against the clearing account, and * every debt the run leaves out of it. What DATEV keeps no debt account for * (an insurer's premium for a company pension, the accident insurer's * contribution) stays on the clearing account until a payment from it settles * it; the run states that amount, so a run that does not add up is refused. * Its payments then settle the debts, one by one, from the bank account they * left. Every line pairs with its counter account (DATEV Gegenkonto). */ import * as plugins from './core.plugins.js'; import type { IJournalDraft, IJournalLineDraft, TBuKey, TCents } from './core.types.js'; import type { IAccountPolicy } from './core.accountpolicy.js'; import { booksChartOf } from './core.booksaccounts.js'; import { suggestBuKey } from './core.bukeys.js'; import { chartOf } from './core.chart.js'; import { RecipeRefusalError } from './core.errors.js'; /** What an account books of a business's payroll (@fin.cx/chartdata `TPayrollRole`). */ export type TPayrollRole = plugins.chartdata.TPayrollRole; /** * What a payroll run costs the employer, by the role of its expense account: * the pay and the flat wage taxes the employer bears (§ 275 Abs. 2 Nr. 6 a * HGB), and the employer's contributions (Nr. 6 b). */ export type TPayrollCostRole = Extract< TPayrollRole, | 'wages' | 'salaries' | 'managing_director_salaries' | 'temporary_wages' | 'minijob_wages' | 'benefits_in_kind' | 'capital_formation_benefits' | 'commuting_allowances' | 'minijob_flat_tax' | 'employee_flat_tax' | 'temporary_flat_tax' | 'employer_social_security' | 'minijob_social_security' | 'accident_insurance' | 'pension' | 'pension_flat_tax' >; /** What a payroll run leaves the business owing until it pays it, by the role of its debt account. */ export type TPayrollDebtRole = Extract< TPayrollRole, 'net_pay' | 'wage_tax' | 'social_security' | 'employee_withholdings' | 'capital_formation_payable' | 'estimated_contributions' >; /** What a payment settles: a debt of a run, or what a run left on the clearing account. */ export type TPayrollPaymentRole = TPayrollDebtRole | Extract; /** The costs in the order a run's lines book them: the pay first, then the employer's contributions. */ export const PAYROLL_COST_ROLES: readonly TPayrollCostRole[] = [ 'wages', 'salaries', 'managing_director_salaries', 'temporary_wages', 'minijob_wages', 'benefits_in_kind', 'capital_formation_benefits', 'commuting_allowances', 'minijob_flat_tax', 'employee_flat_tax', 'temporary_flat_tax', 'employer_social_security', 'minijob_social_security', 'accident_insurance', 'pension', 'pension_flat_tax', ]; /** The debts in the order a run's lines book them. */ export const PAYROLL_DEBT_ROLES: readonly TPayrollDebtRole[] = [ 'net_pay', 'wage_tax', 'social_security', 'employee_withholdings', 'capital_formation_payable', 'estimated_contributions', ]; /** * The account the books book a payroll role on: the account DATEV's chart * keeps for it (`booksChartOf`; an individual account takes no payroll role). * Refuses a role the chart keeps no account for (`payroll_account_missing`), * which a chart of this package's data never does. */ export function payrollAccountOf(policy: IAccountPolicy, role: TPayrollRole): string { const account = booksChartOf(policy).getPayrollAccount(role); if (account === null) { throw new RecipeRefusalError('payroll_account_missing', `${chartOf(policy)} keeps no account for the payroll role ${role}`, { field: role }); } return account.accountNumber; } // ------------------------------------------------------------------ inputs /** What every payroll booking states. */ export interface IPayrollBookingBase { /** the booking day: for a run, the last day of the month the pay is for; for a payment, the day it left the bank */ date: Date; description: string; /** Belegfeld 1 of the lines: the run's id, or the payment's reference */ reference?: string; /** the Beleg: the run's Buchungsbeleg, or the bank statement */ docLink?: string; } /** * A payroll run's Buchungsbeleg: its totals by account role over the people * it pays, each in whole cents (negative where the run corrects an earlier * one). What the run costs equals what it leaves owing, pays in kind and * leaves on the clearing account: `costs` = `debts` + * `companyCarBenefit.amountCents` + `leftOnClearingCents`. */ export interface IPayrollRunInput extends IPayrollBookingBase { /** what the run costs the employer, by role: the gross pay (benefits in kind included), the flat taxes, the employer's contributions */ costs: Partial>; /** what the run leaves owing, by role: the net pay, the wage and church tax with the Solidaritätszuschlag, the contributions of both sides, the rest withheld */ debts: Partial>; /** * The private use of a company car in the gross pay, a supply to the * employee with 19 % VAT (role `company_car_benefit`): `amountCents` as the * pay holds it, and of it the VAT the payroll computed on the supply, which * goes on the books' output VAT (`IAccountPolicy.vat.outputStandard`). */ companyCarBenefit?: { amountCents: TCents; vatCents: TCents }; /** * What the run leaves on the clearing account, to be settled by a payment * from it (`bookPayrollObligationPayment` with role `clearing`): a cost * whose payee DATEV keeps no debt account for, such as an insurer's premium * for a company pension. 0 where absent. */ leftOnClearingCents?: TCents; /** the refunds of the levies U1 and U2 the run claims from the health insurers (roles `levy_refund_claims` against `levy_refunds`) */ levyRefundClaimCents?: TCents; } /** * A payment that settles a payroll debt from the bank account it left: the * net pay to the people, the wage tax to the tax office, the contributions to * the insurer that collects them, a withholding to its creditor, the savings * to an employee's contract, or what a run left on the clearing account. */ export interface IPayrollObligationPaymentInput extends IPayrollBookingBase { /** what the payment settles */ role: TPayrollPaymentRole; /** what left the bank: positive paid, negative returned (a transfer the bank sent back, a refund of an overpayment) */ amountCents: TCents; /** the bank account the payment left */ cashAccount: string; /** * With `social_security` only: the refunds of the levies U1 and U2 the * insurer set off against the contributions it collects, which settle the * books' claim for them (role `levy_refund_claims`) in place of money paid. */ levyRefundSetOffCents?: TCents; } // ------------------------------------------------------------------ recipes /** * A payroll run: every cost on the account of its role against the clearing * account, every debt from the clearing account onto the account of its role, * the company-car benefit out of the clearing account onto its revenue * account net of its VAT (key 40: the VAT stands on its own line, which the * account's automatism would otherwise compute again) and onto the output VAT, * and the levy refunds claimed on the claim against the refunds. What the run * leaves on the clearing account takes no line. Refuses a run whose costs are * not its debts, its benefit in kind and what it leaves on the clearing * account (`payroll_run_unbalanced`, the difference in * `details.differenceCents`). */ export function bookPayrollRun(input: IPayrollRunInput, policy: IAccountPolicy): IJournalDraft { const costs = amountsOf(input.costs, PAYROLL_COST_ROLES, 'costs'); const debts = amountsOf(input.debts, PAYROLL_DEBT_ROLES, 'debts'); const car = input.companyCarBenefit; if (car !== undefined) { requireWhole(car.amountCents, 'companyCarBenefit.amountCents'); requireWhole(car.vatCents, 'companyCarBenefit.vatCents'); if (car.vatCents !== 0 && (Math.sign(car.vatCents) !== Math.sign(car.amountCents) || Math.abs(car.vatCents) > Math.abs(car.amountCents))) { throw invalid('companyCarBenefit.vatCents', `companyCarBenefit.vatCents ${car.vatCents} is the VAT in the amount ${car.amountCents}: of its sign and no larger`, car.vatCents); } } const leftOnClearing = input.leftOnClearingCents ?? 0; requireWhole(leftOnClearing, 'leftOnClearingCents'); const levyClaim = input.levyRefundClaimCents ?? 0; requireWhole(levyClaim, 'levyRefundClaimCents'); const costCents = costs.reduce((sum, [, cents]) => sum + cents, 0); const owedCents = debts.reduce((sum, [, cents]) => sum + cents, 0) + (car?.amountCents ?? 0) + leftOnClearing; if (costCents !== owedCents) { throw new RecipeRefusalError( 'payroll_run_unbalanced', `the run's costs (${costCents} cents) are not its debts, its benefit in kind and what it leaves on the clearing account (${owedCents} cents)`, { differenceCents: costCents - owedCents }, ); } if (costs.length === 0 && debts.length === 0 && (car?.amountCents ?? 0) === 0 && levyClaim === 0) { throw invalid('costs', 'the run states no amount: nothing to book'); } const clearing = payrollAccountOf(policy, 'clearing'); const pairs: IPair[] = [ ...costs.map(([role, cents]) => pair(payrollAccountOf(policy, role), clearing, cents)), ...debts.map(([role, cents]) => pair(clearing, payrollAccountOf(policy, role), cents)), ]; if (car !== undefined) { const revenue = payrollAccountOf(policy, 'company_car_benefit'); const key = suggestBuKey({ direction: 'outbound', scenario: 'domestic_standard', ratePercent: 19, targetIsAutomatik: true, hasExplicitVatLines: car.vatCents !== 0 }); pairs.push(pair(clearing, revenue, car.amountCents - car.vatCents, key), pair(clearing, policy.vat.outputStandard, car.vatCents)); } pairs.push(pair(payrollAccountOf(policy, 'levy_refund_claims'), payrollAccountOf(policy, 'levy_refunds'), levyClaim)); return draftOf(input, policy, pairs); } /** * A payment of a payroll debt: the debt's account (or the clearing account) * against the bank account, and with the contributions the levy refunds the * insurer set off, the debt's account against the claim for them. A negative * amount books the other way. */ export function bookPayrollObligationPayment(input: IPayrollObligationPaymentInput, policy: IAccountPolicy): IJournalDraft { if (input.role !== 'clearing' && !PAYROLL_DEBT_ROLES.includes(input.role)) { throw invalid('role', `${String(input.role)} is no payroll debt (${PAYROLL_DEBT_ROLES.join(', ')}) nor the clearing account`); } requireWhole(input.amountCents, 'amountCents'); const setOff = input.levyRefundSetOffCents ?? 0; requireWhole(setOff, 'levyRefundSetOffCents'); if (setOff !== 0 && input.role !== 'social_security') { throw invalid('levyRefundSetOffCents', `the levy refunds are set off against the contributions (social_security), not against ${input.role}`, setOff); } if (input.amountCents === 0 && setOff === 0) { throw invalid('amountCents', 'the payment is 0 and sets nothing off: nothing to book', 0); } const debt = payrollAccountOf(policy, input.role); return draftOf(input, policy, [ pair(debt, cashAccountOf(input.cashAccount), input.amountCents), pair(debt, payrollAccountOf(policy, 'levy_refund_claims'), setOff), ]); } // ------------------------------------------------------------------ helpers /** 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; /** the BU key of the line on the revenue account a VAT line stands beside */ creditKey?: TBuKey; } function pair(debit: string, credit: string, amountCents: TCents, creditKey?: TBuKey): IPair { return { debit, credit, amountCents, ...(creditKey ? { creditKey } : {}) }; } /** The amounts by role, in the roles' order, each whole cents and none of another role; zeros left out. */ function amountsOf(amountsArg: Partial>, rolesArg: readonly TRole[], fieldArg: string): Array<[TRole, TCents]> { if (typeof amountsArg !== 'object' || amountsArg === null) { throw invalid(fieldArg, `${fieldArg} states the amounts by role`); } for (const key of Object.keys(amountsArg)) { if (!(rolesArg as readonly string[]).includes(key)) { throw invalid(`${fieldArg}.${key}`, `${key} is no role of ${fieldArg} (${rolesArg.join(', ')})`); } } const amounts: Array<[TRole, TCents]> = []; for (const role of rolesArg) { const cents = amountsArg[role]; if (cents === undefined) continue; requireWhole(cents, `${fieldArg}.${role}`); if (cents !== 0) amounts.push([role, cents]); } return amounts; } function draftOf(input: IPayrollBookingBase, policy: IAccountPolicy, pairs: IPair[]): IJournalDraft { const lineOf = (accountArg: string, counterArg: string, sideArg: 'debit' | 'credit', centsArg: TCents, keyArg: TBuKey): IJournalLineDraft => ({ accountNumber: accountArg, counterAccount: counterArg, side: sideArg, amountCents: centsArg, buKey: keyArg, buchungstext: input.description, ...(input.reference !== undefined ? { belegfeld1: input.reference } : {}), ...(input.docLink !== undefined ? { docLink: input.docLink } : {}), }); const lines: IJournalLineDraft[] = []; for (const { debit, credit, amountCents, creditKey } of pairs) { if (amountCents === 0) continue; // a negative amount books the other way; the revenue account keeps its key on whichever side it stands const [to, from, cents, toKey, fromKey] = amountCents > 0 ? [debit, credit, amountCents, '' as TBuKey, creditKey ?? ''] : [credit, debit, -amountCents, creditKey ?? '', '' as TBuKey]; lines.push(lineOf(to, from, 'debit', cents, toKey), lineOf(from, to, 'credit', cents, fromKey)); } return { date: input.date, description: input.description, ...(input.reference !== undefined ? { reference: input.reference } : {}), skrType: chartOf(policy), currency: 'EUR', lines, }; } function cashAccountOf(account: string): string { if (typeof account !== 'string' || account.trim() === '') { throw invalid('cashAccount', 'cashAccount names no account'); } return account; } function invalid(field: string, message: string, amountCents?: number): RecipeRefusalError { return new RecipeRefusalError('payroll_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 }); } }