import * as plugins from './core.plugins.js'; import { BU_KEY_RULES } from './core.bukeys.js'; import { ledgerLinesOf, ledgerPeriodOf, type ILedgerEntryInput, type ITrialBalance } from './core.ledger.js'; import { reportAccount, reportCents, reportSum, reportTrialBalance } from './core.reports.js'; import { ReportError, type IReportOptions } from './core.reports.types.js'; export interface IMonthlyTrialBalance { month: string; balance: ITrialBalance; } export interface IUstVerprobungReturn { month: string; kennzahlen: Array<{ kennzahl: number; kind: 'baseEur' | 'taxCents'; value: number }>; } export interface IUstVerprobungOptions extends IReportOptions { returns?: readonly IUstVerprobungReturn[]; taxationMethod?: 'soll' | 'ist'; } export interface IUstVerprobungRate { month: string; ratePercent: number; revenueCents: number; expectedVatCents: number; bookedVatCents: number; bookedDifferenceCents: number; mappedBaseCents: number; mappedVatCents: number; mappedDifferenceCents: number; filedBaseCents: number | null; filedVatCents: number | null; filedDifferenceCents: number | null; filedBaseDifferenceCents: number | null; revenueAccounts: Array<{ accountNumber: string; cents: number }>; vatAccounts: Array<{ accountNumber: string; cents: number }>; } /** Why an amount of revenue or output VAT takes no rate; stable, for callers to branch on. */ export type TUstVerprobungUnresolvedCode = /** revenue without a rate in the chart, a BU key or the journal's VAT metadata */ | 'revenue_rate_unknown' /** output VAT on an account the policy assigns no domestic sales rate */ | 'output_vat_unassigned'; export interface IUstVerprobungUnresolved { month: string; accountNumber: string; cents: number; code: TUstVerprobungUnresolvedCode; /** the code in words, for a reader; branch on `code` */ reason: string; } export interface IUstVerprobung { taxationMethod: 'soll' | 'ist'; rates: IUstVerprobungRate[]; differences: IUstVerprobungRate[]; unresolved: IUstVerprobungUnresolved[]; isComplete: boolean; } const requireMonth = (month: string): { from: string; to: string } => { if (!/^\d{4}-(0[1-9]|1[0-2])$/u.test(month)) throw new ReportError('report_input_invalid', 'A report month must be YYYY-MM', { month }); const from = `${month}-01`; const lastDay = new Date(`${from}T00:00:00.000Z`); lastDay.setUTCMonth(lastDay.getUTCMonth() + 1, 0); const to = lastDay.toISOString().slice(0, 10); ledgerPeriodOf({ periodFrom: from, periodTo: to }); return { from, to }; }; const mappedRate = (account: plugins.chartdata.IChartAccount): number | null => { if (account.automatikFunction?.taxType === 'ust') return account.automatikFunction.ratePercent; if (account.automatikFunction?.taxType === 'free') return 0; if (account.ustva?.role === 'base') { if (account.ustva.kennzahl === 81) return 19; if (account.ustva.kennzahl === 86) return 7; if ([41, 43, 45, 48, 60, 87].includes(account.ustva.kennzahl)) return 0; } return null; }; /** * An entry with each line on the account it counts as in the VAT return: * `declaresAs` where the line gives one (a correction of a closed year carried * onto the periodenfremde account or the VAT of past years), else its own. */ const declaredEntryOf = (entry: ILedgerEntryInput): ILedgerEntryInput => entry.lines.some((line) => line.declaresAs !== undefined && line.declaresAs !== null) ? { ...entry, lines: entry.lines.map((line) => (line.declaresAs === undefined || line.declaresAs === null ? line : { ...line, accountNumber: line.declaresAs })) } : entry; /** Whether a period begins or ends inside a month, so it takes only part of it. */ const slicesMonth = (period: { from?: string; to?: string }, span: { from: string; to: string }): boolean => (period.from !== undefined && period.from > span.from && period.from <= span.to) || (period.to !== undefined && period.to >= span.from && period.to < span.to); /** * An entry in the VAT month it is declared in (`ILedgerEntryInput.vatPeriod`, * else the month of its date). One declared in the month of its date stays as * it is, day and all. One declared in another month has no day in it: it * stands in that month as a whole, on its first day, so a period that takes * only part of that month is refused. */ const vatMonthEntryOf = (period: { from?: string; to?: string }) => (entry: ILedgerEntryInput): ILedgerEntryInput => { if (entry.vatPeriod === undefined || entry.vatPeriod === null) return entry; const span = requireMonth(entry.vatPeriod); if (entry.opening === true || entry.date.toISOString().slice(0, 7) === entry.vatPeriod) return entry; if (slicesMonth(period, span)) { throw new ReportError('report_input_invalid', 'An entry declared in another VAT month cannot be sliced inside that month', { entryId: entry.id, vatPeriod: entry.vatPeriod }); } return { ...entry, date: new Date(`${span.from}T00:00:00.000Z`) }; }; /** * The USt-Verprobung: per month and rate, the revenue against the output VAT * booked for the rate, against the base of the rate's Kennzahl as the chart * maps the accounts, and against an advance return handed in. Entries count * each line as the account it declares as in the VAT return * (`IJournalLineDraft.declaresAs`), in the VAT month the entry is declared in * (`ILedgerEntryInput.vatPeriod`, else the month of its date): its revenue, * its VAT and the period's bounds alike. Monthly trial balances, which have * no lines, count by their accounts in their month. */ export function computeUstVerprobung( input: readonly ILedgerEntryInput[] | readonly IMonthlyTrialBalance[], options: IUstVerprobungOptions, ): IUstVerprobung { const period = ledgerPeriodOf(options); const monthly = new Map(); const revenueByMonth = new Map>(); const monthlyInput = input.length > 0 && 'balance' in input[0]; reportTrialBalance(monthlyInput ? [] : input as readonly ILedgerEntryInput[], monthlyInput ? { policy: options.policy } : options); if (monthlyInput) { if (options.opening !== undefined) throw new ReportError('report_input_invalid', 'Monthly trial balances already own their opening balances'); for (const item of input as readonly IMonthlyTrialBalance[]) { const span = requireMonth(item.month); if (slicesMonth(period, span)) { throw new ReportError('report_input_invalid', 'A monthly trial balance cannot be sliced inside its month'); } if (monthly.has(item.month)) throw new ReportError('report_input_invalid', 'Duplicate monthly trial balance', { month: item.month }); const balance = reportTrialBalance(item.balance, { policy: options.policy, periodFrom: span.from, periodTo: span.to }); if ((period.from !== undefined && span.to < period.from) || (period.to !== undefined && span.from > period.to)) continue; monthly.set(item.month, balance); const revenues = new Map(); for (const row of balance.accounts) { const account = reportAccount(options, row.accountNumber); if (account?.accountType !== 'revenue') continue; revenues.set(row.accountNumber, { accountNumber: row.accountNumber, rate: mappedRate(account), cents: reportSum([row.periodCreditCents, -row.periodDebitCents]) }); } revenueByMonth.set(item.month, revenues); } } else { const entries = (input as readonly ILedgerEntryInput[]).map(declaredEntryOf).map(vatMonthEntryOf(period)); const lines = ledgerLinesOf(entries); for (const line of lines) { if (line.opening || (period.from !== undefined && line.date < period.from) || (period.to !== undefined && line.date > period.to)) continue; const month = line.date.slice(0, 7); if (!monthly.has(month)) { const span = requireMonth(month); monthly.set(month, reportTrialBalance(entries, { policy: options.policy, periodFrom: span.from > (period.from ?? '') ? span.from : period.from, periodTo: span.to < (period.to ?? '9999-12-31') ? span.to : period.to })); } } for (const entry of entries) { if (entry.opening) continue; const date = entry.date.toISOString().slice(0, 10); if ((period.from !== undefined && date < period.from) || (period.to !== undefined && date > period.to)) continue; const month = date.slice(0, 7); const revenues = revenueByMonth.get(month) ?? new Map(); for (const line of entry.lines) { const account = reportAccount(options, line.accountNumber); if (account?.accountType !== 'revenue') continue; const rule = line.buKey === '' ? undefined : BU_KEY_RULES[line.buKey]; const rate = line.vatRatePercent !== undefined ? Number(line.vatRatePercent) : rule?.taxType === 'ust' ? rule.ratePercent : mappedRate(account); if (rate !== null && (!Number.isFinite(rate) || rate < 0 || rate > 100)) throw new ReportError('report_input_invalid', 'Invalid revenue VAT rate', { accountNumber: line.accountNumber }); if (line.vatRatePercent !== undefined && !/^\d+(?:\.\d+)?$/u.test(line.vatRatePercent)) throw new ReportError('report_input_invalid', 'Invalid revenue VAT rate text'); const cents = reportCents(line.amountCents * (line.side === 'credit' ? 1 : -1) * (entry.generalumkehr ? -1 : 1)); const key = `${line.accountNumber}:${rate}`; const figure = revenues.get(key) ?? { accountNumber: line.accountNumber, rate, cents: 0 }; figure.cents = reportSum([figure.cents, cents]); revenues.set(key, figure); } revenueByMonth.set(month, revenues); } } const returns = new Map(); for (const submitted of options.returns ?? []) { requireMonth(submitted.month); if (returns.has(submitted.month)) throw new ReportError('report_input_invalid', 'Duplicate VAT return month'); const seen = new Set(); for (const figure of submitted.kennzahlen) { reportCents(figure.value); if (!Number.isSafeInteger(figure.kennzahl) || figure.kennzahl <= 0 || seen.has(figure.kennzahl) || !['baseEur', 'taxCents'].includes(figure.kind)) { throw new ReportError('report_input_invalid', 'Invalid or duplicate VAT return Kennzahl'); } seen.add(figure.kennzahl); if ([81, 86, 87].includes(figure.kennzahl) && figure.kind !== 'baseEur') throw new ReportError('report_input_invalid', 'A sales base Kennzahl must be baseEur'); } returns.set(submitted.month, submitted); if (!monthly.has(submitted.month) && (period.from === undefined || `${submitted.month}-31` >= period.from) && (period.to === undefined || `${submitted.month}-01` <= period.to)) { monthly.set(submitted.month, reportTrialBalance([], { policy: options.policy })); } } const rates: IUstVerprobungRate[] = []; const unresolved: IUstVerprobungUnresolved[] = []; for (const [month, balance] of [...monthly].sort(([left], [right]) => left.localeCompare(right))) { const figures = new Map(); const figureOf = (rate: number): IUstVerprobungRate => { let figure = figures.get(rate); if (figure === undefined) { figure = { month, ratePercent: rate, revenueCents: 0, expectedVatCents: 0, bookedVatCents: 0, bookedDifferenceCents: 0, mappedBaseCents: 0, mappedVatCents: 0, mappedDifferenceCents: 0, filedBaseCents: null, filedVatCents: null, filedDifferenceCents: null, filedBaseDifferenceCents: null, revenueAccounts: [], vatAccounts: [] }; figures.set(rate, figure); } return figure; }; for (const revenue of revenueByMonth.get(month)?.values() ?? []) { if (revenue.cents === 0) continue; if (revenue.rate === null) { unresolved.push({ month, accountNumber: revenue.accountNumber, cents: revenue.cents, code: 'revenue_rate_unknown', reason: 'No rate in the chart, BU key or journal VAT metadata' }); continue; } const figure = figureOf(revenue.rate); figure.revenueCents = reportSum([figure.revenueCents, revenue.cents]); figure.revenueAccounts.push({ accountNumber: revenue.accountNumber, cents: revenue.cents }); } for (const row of balance.accounts) { const cents = reportSum([row.periodCreditCents, -row.periodDebitCents]); if (cents === 0) continue; const account = reportAccount(options, row.accountNumber); const standardNumber = account?.parentAccountNumber ?? row.accountNumber; if (standardNumber === options.policy.vat.outputStandard || standardNumber === options.policy.vat.outputReduced) { const figure = figureOf(standardNumber === options.policy.vat.outputStandard ? 19 : 7); figure.bookedVatCents = reportSum([figure.bookedVatCents, cents]); figure.vatAccounts.push({ accountNumber: row.accountNumber, cents }); } else if (account?.balanceRule?.vatNetGroup !== undefined && account.accountType === 'liability' && ![options.policy.vat.intraEuAcqOutput, options.policy.vat.reverseChargeOutput, options.policy.vatSettlement.prepayment, options.policy.vatSettlement.specialPrepayment].includes(standardNumber)) { unresolved.push({ month, accountNumber: row.accountNumber, cents, code: 'output_vat_unassigned', reason: 'Output VAT cannot be assigned to a domestic sales rate from the policy' }); } if (account?.ustva?.role === 'base' && [81, 86, 87].includes(account.ustva.kennzahl)) { const figure = figureOf(account.ustva.kennzahl === 81 ? 19 : account.ustva.kennzahl === 86 ? 7 : 0); figure.mappedBaseCents = reportSum([figure.mappedBaseCents, cents]); } } const submitted = returns.get(month); if (submitted !== undefined) { for (const value of submitted.kennzahlen) { if ([81, 86, 87].includes(value.kennzahl)) figureOf(value.kennzahl === 81 ? 19 : value.kennzahl === 86 ? 7 : 0); } } for (const figure of [...figures.values()].sort((left, right) => left.ratePercent - right.ratePercent)) { figure.expectedVatCents = reportCents(plugins.calculation.vatFromNetCents(figure.revenueCents, figure.ratePercent)); figure.mappedVatCents = reportCents(plugins.calculation.vatFromNetCents(figure.mappedBaseCents, figure.ratePercent)); figure.bookedDifferenceCents = reportSum([figure.bookedVatCents, -figure.expectedVatCents]); figure.mappedDifferenceCents = reportSum([figure.bookedVatCents, -figure.mappedVatCents]); const kennzahl = figure.ratePercent === 19 ? 81 : figure.ratePercent === 7 ? 86 : figure.ratePercent === 0 ? 87 : null; if (submitted !== undefined && kennzahl !== null) { figure.filedBaseCents = reportCents((submitted.kennzahlen.find((value) => value.kennzahl === kennzahl)?.value ?? 0) * 100); figure.filedVatCents = reportCents(plugins.calculation.vatFromNetCents(figure.filedBaseCents, figure.ratePercent)); figure.filedDifferenceCents = reportSum([figure.bookedVatCents, -figure.filedVatCents]); figure.filedBaseDifferenceCents = reportSum([figure.mappedBaseCents, -figure.filedBaseCents]); } rates.push(figure); } } return { taxationMethod: options.taxationMethod ?? 'soll', rates, differences: rates.filter((figure) => figure.bookedDifferenceCents !== 0 || figure.mappedDifferenceCents !== 0 || (figure.filedDifferenceCents !== null && figure.filedDifferenceCents !== 0) || (figure.filedBaseDifferenceCents !== null && figure.filedBaseDifferenceCents !== 0)), unresolved, isComplete: unresolved.length === 0 }; }