import * as plugins from './core.plugins.js'; import { booksChartOf } from './core.booksaccounts.js'; import { isCreditorAccount, isDebtorAccount } from './core.accountpolicy.js'; import { ledgerLinesOf, ledgerPeriodOf, trialBalanceOf, type ILedgerEntryInput, type ITrialBalance, type ITrialBalanceAccount } from './core.ledger.js'; import { ReportError, type IBilanz, type IBilanzOptions, type IBwa, type IBwaColumn, type IBwaOptions, type IBwaPeriods, type IGuv, type IReportFigure, type IReportOptions, type TReportInput } from './core.reports.types.js'; export const reportCents = (value: number): number => { if (!Number.isSafeInteger(value)) throw new ReportError('report_input_invalid', 'Report amounts must be safe integer cents', { value }); return value; }; export const reportSum = (values: readonly number[]): number => values.reduce((total, value) => reportCents(total + reportCents(value)), 0); export function reportTrialBalance(input: TReportInput, options: IReportOptions): ITrialBalance { ledgerPeriodOf(options); booksChartOf(options.policy); if (Array.isArray(input)) return reportTrialBalance(trialBalanceOf(input, options), { policy: options.policy }); const balance = input as ITrialBalance; ledgerPeriodOf(balance); if (options.opening !== undefined || (options.periodFrom !== undefined && options.periodFrom !== balance.periodFrom) || (options.periodTo !== undefined && options.periodTo !== balance.periodTo)) { throw new ReportError('report_input_invalid', 'A supplied trial balance already owns its period and opening balances'); } const seen = new Set(); for (const row of balance.accounts) { if (seen.has(row.accountNumber)) throw new ReportError('report_input_invalid', 'Duplicate trial-balance account', { accountNumber: row.accountNumber }); seen.add(row.accountNumber); for (const value of [row.openingCents ?? 0, row.priorDebitCents, row.priorCreditCents, row.periodDebitCents, row.periodCreditCents, row.cumulativeDebitCents, row.cumulativeCreditCents, row.balanceCents]) reportCents(value); if (row.cumulativeDebitCents !== reportSum([row.priorDebitCents, row.periodDebitCents]) || row.cumulativeCreditCents !== reportSum([row.priorCreditCents, row.periodCreditCents]) || row.balanceCents !== reportSum([row.openingCents ?? 0, row.cumulativeDebitCents, -row.cumulativeCreditCents])) { throw new ReportError('report_input_invalid', 'Trial-balance columns do not reconcile', { accountNumber: row.accountNumber }); } } const debit = reportSum(balance.accounts.map((row) => row.cumulativeDebitCents)); const credit = reportSum(balance.accounts.map((row) => row.cumulativeCreditCents)); const opening = reportSum(balance.accounts.map((row) => row.openingCents ?? 0)); if (debit !== balance.totalDebitCents || credit !== balance.totalCreditCents || opening !== balance.openingDifferenceCents || balance.isBalanced !== (debit === credit && opening === 0)) { throw new ReportError('report_input_invalid', 'Trial-balance totals do not reconcile'); } if (!balance.isBalanced) throw new ReportError('report_balance_unbalanced', 'Reports require a balanced trial balance'); return balance; } const periodFields = (balance: ITrialBalance): { periodFrom?: string; periodTo?: string } => ({ ...(balance.periodFrom !== undefined ? { periodFrom: balance.periodFrom } : {}), ...(balance.periodTo !== undefined ? { periodTo: balance.periodTo } : {}), }); const isProfit = (account: plugins.chartdata.IChartAccount): boolean => account.accountType === 'expense' || account.accountType === 'revenue'; export function reportAccount(options: IReportOptions, number: string): plugins.chartdata.IChartAccount | null { const account = booksChartOf(options.policy).getAccount(number); if (account === null && !isDebtorAccount(options.policy, number) && !isCreditorAccount(options.policy, number)) { throw new ReportError('report_mapping_missing', 'Account is absent from the books chart', { accountNumber: number }); } return account; } const creditMovement = (row: ITrialBalanceAccount): number => reportSum([row.periodCreditCents, -row.periodDebitCents]); const EXPENSE_POSITIONS = new Set(['GuV 5', 'GuV 6a', 'GuV 6b', 'GuV 7', 'GuV 8', 'GuV 12', 'GuV 13', 'GuV 14', 'GuV 16']); export function computeGuv(input: TReportInput, options: IReportOptions): IGuv { const balance = reportTrialBalance(input, options); const figures = new Map(plugins.chartdata.HGB_275_GKV_POSITIONS.map((position) => [position.key, { ...position, cents: 0, sign: EXPENSE_POSITIONS.has(position.key) ? -1 : 1, subtotal: position.key === 'GuV 15' || position.key === 'GuV 17', accounts: [], }])); for (const row of balance.accounts) { if (row.periodDebitCents === 0 && row.periodCreditCents === 0) continue; const account = reportAccount(options, row.accountNumber); if (account === null || !isProfit(account)) continue; const figure = account.hgb275Position === undefined ? undefined : figures.get(account.hgb275Position); if (figure === undefined || figure.subtotal) throw new ReportError('report_mapping_missing', 'P&L account has no posting GuV position', { accountNumber: row.accountNumber }); const cents = creditMovement(row) * figure.sign; figure.cents = reportSum([figure.cents, cents]); figure.accounts.push({ accountNumber: row.accountNumber, cents }); } const sum = (keys: string[]): number => reportSum(keys.map((key) => figures.get(key)!.cents * figures.get(key)!.sign)); const operatingResultCents = sum(['GuV 1', 'GuV 2', 'GuV 3', 'GuV 4', 'GuV 5', 'GuV 6a', 'GuV 6b', 'GuV 7', 'GuV 8']); const financialResultCents = sum(['GuV 9', 'GuV 10', 'GuV 11', 'GuV 12', 'GuV 13']); const resultBeforeTaxesCents = reportSum([operatingResultCents, financialResultCents]); figures.get('GuV 15')!.cents = reportSum([resultBeforeTaxesCents, -figures.get('GuV 14')!.cents]); const resultCents = reportSum([figures.get('GuV 15')!.cents, -figures.get('GuV 16')!.cents]); figures.get('GuV 17')!.cents = resultCents; const subtotal = (key: string, label: string, cents: number): IReportFigure => ({ key, label, cents, sign: 1, subtotal: true, accounts: [] }); return { ...periodFields(balance), lines: [...figures.values(), subtotal('operating_result', 'Betriebsergebnis', operatingResultCents), subtotal('financial_result', 'Finanzergebnis', financialResultCents), subtotal('result_before_taxes', 'Ergebnis vor Steuern', resultBeforeTaxesCents)], operatingResultCents, financialResultCents, resultBeforeTaxesCents, resultCents, }; } export function computeBilanz(input: TReportInput, options: IBilanzOptions): IBilanz { const balance = reportTrialBalance(input, options); if (options.legalForm !== undefined && !['sole_trader', 'partnership', 'corporation'].includes(options.legalForm)) { throw new ReportError('report_input_invalid', 'Unknown report legal form'); } const figures = new Map(plugins.chartdata.HGB_266_POSITIONS.map((position) => [position.key, { ...position, cents: 0, sign: 1, subtotal: false, accounts: [] }])); const vatGroups = new Map }>(); const resultAccounts: Array<{ accountNumber: string; cents: number }> = []; // the Saldenvortragskonten (`bookOpeningBalances`): each carries the opposite of what it opened, only their sum nets to zero const vortrag = new Set([options.policy.openingBalance.generalLedger, options.policy.openingBalance.debtors, options.policy.openingBalance.creditors]); const vortragAccounts: Array<{ accountNumber: string; balanceCents: number }> = []; const put = (position: string | undefined, number: string, signed: number): void => { const figure = position === undefined ? undefined : figures.get(position); if (figure === undefined) throw new ReportError('report_mapping_missing', 'Account has no balance-sheet position', { accountNumber: number, position }); const cents = signed * (figure.key.startsWith('Aktiva ') ? 1 : -1); figure.cents = reportSum([figure.cents, cents]); figure.accounts.push({ accountNumber: number, cents }); }; for (const row of balance.accounts) { if (row.balanceCents === 0) continue; if (vortrag.has(row.accountNumber)) { vortragAccounts.push({ accountNumber: row.accountNumber, balanceCents: row.balanceCents }); continue; } const account = reportAccount(options, row.accountNumber); if (account === null) { put(row.balanceCents > 0 ? 'Aktiva B.II.1' : 'Passiva C.4', row.accountNumber, row.balanceCents); continue; } if (isProfit(account)) { if (account.hgb275Position === undefined) throw new ReportError('report_mapping_missing', 'P&L account has no GuV position', { accountNumber: row.accountNumber }); resultAccounts.push({ accountNumber: row.accountNumber, cents: -row.balanceCents }); continue; } if (account.hgb266Exclusion !== undefined) { throw new ReportError('report_technical_balance', 'A technical account has a nonzero balance; complete the opening or closing bookings first', { accountNumber: row.accountNumber, balanceCents: row.balanceCents }); } const rule = account.balanceRule; if (rule?.legalForms !== undefined) { if (options.legalForm === undefined) throw new ReportError('report_legal_form_required', 'This balance account requires the business legal form', { accountNumber: row.accountNumber }); if (!rule.legalForms.includes(options.legalForm)) throw new ReportError('report_legal_form_incompatible', 'This account is not equity for the business legal form', { accountNumber: row.accountNumber, legalForm: options.legalForm }); } if (rule?.vatNetGroup !== undefined) { const positions = { ...rule, debitPosition: rule.debitPosition ?? (account.hgb266Position?.startsWith('Aktiva ') ? account.hgb266Position : undefined), creditPosition: rule.creditPosition ?? (account.hgb266Position?.startsWith('Passiva ') ? account.hgb266Position : undefined), }; const group = vatGroups.get(rule.vatNetGroup) ?? { rule: positions, accounts: [] }; if (group.rule.debitPosition !== positions.debitPosition || group.rule.creditPosition !== positions.creditPosition) { throw new ReportError('report_mapping_missing', 'VAT net-group positions disagree', { group: rule.vatNetGroup }); } group.accounts.push({ accountNumber: row.accountNumber, cents: row.balanceCents }); vatGroups.set(rule.vatNetGroup, group); continue; } const position = (row.balanceCents > 0 ? rule?.debitPosition : rule?.creditPosition) ?? account.hgb266Position; put(position, row.accountNumber, row.balanceCents); } const vortragCents = reportSum(vortragAccounts.map((account) => account.balanceCents)); if (vortragCents !== 0) { throw new ReportError('report_technical_balance', 'The Saldenvortragskonten do not net to zero; complete the opening bookings first', { accounts: vortragAccounts, balanceCents: vortragCents }); } for (const group of vatGroups.values()) { const net = reportSum(group.accounts.map((account) => account.cents)); const position = net >= 0 ? group.rule.debitPosition : group.rule.creditPosition; for (const account of group.accounts) put(position, account.accountNumber, account.cents); } const resultCents = reportSum(resultAccounts.map((account) => account.cents)); const annual = figures.get(plugins.chartdata.HGB_ANNUAL_RESULT_POSITION)!; annual.cents = reportSum([annual.cents, resultCents]); annual.accounts.push(...resultAccounts); const aktiva = [...figures.values()].filter((figure) => figure.key.startsWith('Aktiva ')); const passiva = [...figures.values()].filter((figure) => figure.key.startsWith('Passiva ')); const aktivaCents = reportSum(aktiva.map((figure) => figure.cents)); const passivaCents = reportSum(passiva.map((figure) => figure.cents)); if (aktivaCents !== passivaCents) throw new ReportError('report_balance_unbalanced', 'Aktiva and Passiva do not reconcile', { aktivaCents, passivaCents }); const withSubtotals = (lines: IReportFigure[], groups: string[]): IReportFigure[] => [ ...lines, ...groups.map((key): IReportFigure => ({ key, label: key, cents: reportSum(lines.filter((line) => line.key === key || line.key.startsWith(`${key}.`)).map((line) => line.cents)), sign: 1, subtotal: true, accounts: [] })), ]; return { ...periodFields(balance), aktiva: withSubtotals(aktiva, ['Aktiva A.I', 'Aktiva A.II', 'Aktiva A.III', 'Aktiva A', 'Aktiva B.I', 'Aktiva B.II', 'Aktiva B.III', 'Aktiva B']), passiva: withSubtotals(passiva, ['Passiva A', 'Passiva B', 'Passiva C']), aktivaCents, passivaCents, resultCents, periodResultCents: computeGuv(balance, { policy: options.policy }).resultCents, isBalanced: true }; } const bwaSpan = (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 BWA month must be YYYY-MM'); const from = `${month}-01`; const end = new Date(`${from}T00:00:00.000Z`); end.setUTCMonth(end.getUTCMonth() + 1, 0); return { from, to: end.toISOString().slice(0, 10) }; }; const previousYearDay = (day: string): string => { const previous = new Date(`${day}T00:00:00.000Z`); const year = previous.getUTCFullYear() - 1; previous.setUTCFullYear(year); if (previous.getUTCFullYear() !== year || previous.toISOString().slice(5, 10) !== day.slice(5, 10)) { throw new ReportError('report_input_invalid', 'The fiscal-year start has no corresponding prior-year day'); } return previous.toISOString().slice(0, 10); }; const bwaColumns = (balance: ITrialBalance, options: IReportOptions): Map => { reportTrialBalance(balance, options); const figures = new Map(plugins.chartdata.BWA_LINES.map((line) => [line.key, { cents: 0, percentOfTotalOutput: null, accounts: [] }])); const definitions = new Map(plugins.chartdata.BWA_LINES.map((line) => [line.key, line])); for (const row of balance.accounts) { if (row.periodDebitCents === 0 && row.periodCreditCents === 0) continue; const account = reportAccount(options, row.accountNumber); if (account === null || !isProfit(account)) continue; const definition = account.bwaLine === undefined ? undefined : definitions.get(account.bwaLine); if (definition?.kind !== 'posting') throw new ReportError('report_mapping_missing', 'P&L account has no posting BWA line', { accountNumber: row.accountNumber }); const figure = figures.get(definition.key)!; const cents = creditMovement(row) * (definition.normalSide === 'credit' ? 1 : -1); figure.cents = reportSum([figure.cents, cents]); figure.accounts.push({ accountNumber: row.accountNumber, cents }); } const computed = new Set(); for (const definition of plugins.chartdata.BWA_LINES) { if (definition.kind === 'subtotal') { if (definition.terms.some((term) => !computed.has(term.line))) throw new ReportError('report_mapping_missing', 'BWA subtotal references a later or unknown line'); figures.get(definition.key)!.cents = reportSum(definition.terms.map((term) => figures.get(term.line)!.cents * term.factor)); } computed.add(definition.key); } const total = figures.get('total_output')!.cents; for (const figure of figures.values()) figure.percentOfTotalOutput = total === 0 ? null : figure.cents / total * 100; const guv = computeGuv(balance, { policy: options.policy }); if (figures.get('provisional_result')!.cents !== guv.resultCents) throw new ReportError('report_mapping_missing', 'BWA result does not reconcile to the GuV'); return figures; }; export function computeBwa(input: readonly ILedgerEntryInput[] | IBwaPeriods, options: IBwaOptions): IBwa { const span = bwaSpan(options.month); const fiscalYearStart = options.fiscalYearStart ?? `${options.month.slice(0, 4)}-01-01`; ledgerPeriodOf({ periodFrom: fiscalYearStart, periodTo: span.to }); if (fiscalYearStart > span.from) throw new ReportError('report_input_invalid', 'The fiscal year must begin on or before the BWA month'); const priorMonth = `${Number(options.month.slice(0, 4)) - 1}${options.month.slice(4)}`; const priorSpan = bwaSpan(priorMonth); const priorStart = previousYearDay(fiscalYearStart); let periods: IBwaPeriods; if (Array.isArray(input)) { const entries = input as readonly ILedgerEntryInput[]; const lines = ledgerLinesOf(entries); const hasPriorYear = lines.some((line) => !line.opening && line.date >= priorStart && line.date <= priorSpan.to); periods = { month: trialBalanceOf(entries, { periodFrom: span.from, periodTo: span.to }), yearToDate: trialBalanceOf(entries, { periodFrom: fiscalYearStart, periodTo: span.to }), ...(hasPriorYear ? { previousMonth: trialBalanceOf(entries, { periodFrom: priorSpan.from, periodTo: priorSpan.to }), previousYearToDate: trialBalanceOf(entries, { periodFrom: priorStart, periodTo: priorSpan.to }) } : {}), }; } else periods = input as IBwaPeriods; const month = bwaColumns(periods.month, { policy: options.policy, periodFrom: span.from, periodTo: span.to }); const cumulative = bwaColumns(periods.yearToDate, { policy: options.policy, periodFrom: fiscalYearStart, periodTo: span.to }); const previousMonth = periods.previousMonth === undefined ? null : bwaColumns(periods.previousMonth, { policy: options.policy, periodFrom: priorSpan.from, periodTo: priorSpan.to }); const previousCumulative = periods.previousYearToDate === undefined ? null : bwaColumns(periods.previousYearToDate, { policy: options.policy, periodFrom: priorStart, periodTo: priorSpan.to }); return { month: options.month, fiscalYearStart, lines: plugins.chartdata.BWA_LINES.map((line) => ({ key: line.key, label: line.label, subtotal: line.kind === 'subtotal', month: month.get(line.key)!, yearToDate: cumulative.get(line.key)!, previousMonth: previousMonth?.get(line.key) ?? null, previousYearToDate: previousCumulative?.get(line.key) ?? null })), resultCents: month.get('provisional_result')!.cents, cumulativeResultCents: cumulative.get('provisional_result')!.cents, }; }