/** * UStVA period extraction: one period's account movements plus the EXACT * scenario Bemessungsgrundlagen (igE / §13b) taken from taxScenario-tagged * journal entries. The result feeds @fin.cx/tax `computeUstva()` directly — * movements as `IAccountMovementInput[]`, scenarioBases as * `IScenarioBaseInput`. * * Base extraction per tagged entry: sum of (debit - credit) over the lines * with the scenario's key (94/91, 19/18) where the entry has any, else over * the lines that sit neither on a policy VAT account nor on a personal * account (>= 10000) (a tax booked as stated, whose base has no key); never * a line against a policy VAT account (the key-less correction of a * deduction excluded in part or wholly, expense against input tax). For the recipe * shapes that is exactly the net expense line; Stornos flip sides and cancel. * A § 13b base goes into the field of its line's paragraph * (`reverseChargeParagraph`): Abs. 1 Kz 46, Abs. 2 Nr. 3 Kz 73, Abs. 2 Kz 84; * a line without one into Kz 46, as before the paragraph was recorded. Every * extracted base is cross-checked against the entry's own pair of input and * output VAT — disagreement lands in `warnings`. An entry without the tag * (a payment whose Skonto lowers a § 13b or intra-Community base) gives the * lines with the scenario's key: 19 Kz 89, 18 Kz 93, 94 and 91 by paragraph. * The query loads only those two kinds of entry: the tagged ones and those * with a line keyed 19, 18, 94 or 91. * * The policy's individual accounts (`individualAccounts`) come along, so * `computeUstva()` counts a movement on one where its UStVA mapping places it. */ import type * as plugins from './plugins.js'; import { vatFromNetCents } from '@fin.cx/calculation'; import { JournalEntry } from './skr.classes.journalentry.js'; import { aggregateTrialBalance } from './skr.balances.js'; import type { IAccountPolicy, TReverseChargeParagraph } from './core/index.js'; import type { TSKRType } from './skr.types.js'; export interface IUstvaMovement { accountNumber: string; /** debitCents - creditCents over the period */ signedCents: number; } export interface IUstvaScenarioBases { /** igE 19 % net bases (Kz 89) */ intraEuAcquisitionStandardCents: number; /** igE 7 % net bases (Kz 93) */ intraEuAcquisitionReducedCents: number; /** * § 13b Abs. 1 bases (Kz 46): the lines with `reverseChargeParagraph` * `abs_1`, and every § 13b base line without a paragraph, which an entry * posted before the paragraph was recorded, or one whose tax was booked as * stated (no key, so no paragraph), carries; reclassify those manually * where they fall under Abs. 2. */ reverseChargeServicesEuCents: number; /** § 13b Abs. 2 Nr. 3 bases, Umsätze under the GrEStG (Kz 73): the lines with `reverseChargeParagraph` `abs_2_nr_3` */ reverseChargeRealEstateCents: number; /** the other § 13b Abs. 2 bases, Nr. 1, 2, 4 to 12 (Kz 84): the lines with `reverseChargeParagraph` `abs_2` */ reverseChargeOtherCents: number; } export interface IUstvaPeriodData { movements: IUstvaMovement[]; scenarioBases: IUstvaScenarioBases; /** * the policy's individual accounts (`IAccountPolicy.individualAccounts`; the * books' declarations under `SkrApi`), empty where it has none: @fin.cx/tax * `computeUstva()` takes them as `individualAccounts` and counts a movement * on one where its UStVA mapping places it */ individualAccounts: plugins.chartdata.IIndividualAccountDeclaration[]; /** tagged igE/§13b entries examined */ taggedEntryCount: number; /** extraction anomalies — review before filing */ warnings: string[]; } function isPersonalAccount(accountNumber: string): boolean { const numeric = Number.parseInt(accountNumber, 10); return numeric >= 10000 && numeric <= 99999; } export async function getUstvaPeriodData( skrType: TSKRType, policy: IAccountPolicy, options: { dateFrom: Date; dateTo: Date }, ): Promise { const trialBalance = await aggregateTrialBalance(skrType, options); const movements: IUstvaMovement[] = trialBalance.accounts .filter((account) => account.balanceCents !== 0) .map((account) => ({ accountNumber: account.accountNumber, signedCents: account.balanceCents, })); const vatAccounts = new Set(Object.values(policy.vat)); const warnings: string[] = []; const scenarioBases: IUstvaScenarioBases = { intraEuAcquisitionStandardCents: 0, intraEuAcquisitionReducedCents: 0, reverseChargeServicesEuCents: 0, reverseChargeRealEstateCents: 0, reverseChargeOtherCents: 0, }; const reverseChargeFieldOf = (paragraphArg: TReverseChargeParagraph | undefined): 'reverseChargeServicesEuCents' | 'reverseChargeRealEstateCents' | 'reverseChargeOtherCents' => paragraphArg === 'abs_2_nr_3' ? 'reverseChargeRealEstateCents' : paragraphArg === 'abs_2' ? 'reverseChargeOtherCents' : 'reverseChargeServicesEuCents'; const cursor = await JournalEntry.getCursor({ schemaVersion: 2, skrType, status: { $in: ['posted', 'finalized'] }, date: { $gte: options.dateFrom, $lte: options.dateTo }, // the entries the UStVA reads: the tagged ones, and those with a line keyed for the scenarios (a payment's Skonto) $or: [ { taxScenario: { $in: ['intra_eu_acquisition', 'reverse_charge_13b'] } }, { 'lines.buKey': { $in: ['19', '18', '94', '91'] } }, ], }); const entries = await cursor.toArray(); const isTagged = (entryArg: JournalEntry): boolean => entryArg.taxScenario === 'intra_eu_acquisition' || entryArg.taxScenario === 'reverse_charge_13b'; const tagged = entries.filter(isTagged); // an entry without the tag, such as a payment with a Skonto on a § 13b or intra-Community purchase (§ 17 Abs. 1 // Satz 5 UStG): its bases are the lines with the scenario's key, which DATEV books the pair from, each in its field for (const entry of entries) { if (isTagged(entry)) continue; for (const line of entry.lines) { const amount = line.amountCents ?? 0; const signed = line.side === 'debit' ? amount : -amount; if (line.buKey === '19') scenarioBases.intraEuAcquisitionStandardCents += signed; else if (line.buKey === '18') scenarioBases.intraEuAcquisitionReducedCents += signed; else if (line.buKey === '94' || line.buKey === '91') scenarioBases[reverseChargeFieldOf(line.reverseChargeParagraph)] += signed; } } for (const entry of tagged) { const label = entry.journalNumber ?? `seq ${entry.sequenceNumber}`; const inputVatAccount = entry.taxScenario === 'intra_eu_acquisition' ? policy.vat.intraEuAcqInput : policy.vat.reverseChargeInput; const outputVatAccount = entry.taxScenario === 'intra_eu_acquisition' ? policy.vat.intraEuAcqOutput : policy.vat.reverseChargeOutput; let baseCents = 0; let inputVatCents = 0; const reverseChargeBases = new Map, number>(); // where a line carries the scenario's key, the keyed lines are the base: the line against the provider's account, // which need not be a personal account (a fee kept from a bank or depot balance), is then none const scenarioKeys = entry.taxScenario === 'intra_eu_acquisition' ? ['19', '18'] : ['94', '91']; const keyed = entry.lines.some((lineArg) => scenarioKeys.includes(lineArg.buKey ?? '')); for (const line of entry.lines) { const amount = line.amountCents ?? 0; const signed = line.side === 'debit' ? amount : -amount; if (line.accountNumber === inputVatAccount) { // the pair the tax owed and deducted is booked in; a correction of the deduction stands against the expense if (line.counterAccount === undefined || line.counterAccount === outputVatAccount) inputVatCents += signed; continue; } if (vatAccounts.has(line.accountNumber)) continue; if (isPersonalAccount(line.accountNumber)) continue; // the correction of a deduction excluded in part or wholly is cost, no base if (line.counterAccount !== undefined && vatAccounts.has(line.counterAccount)) continue; if (keyed && !scenarioKeys.includes(line.buKey ?? '')) continue; baseCents += signed; const field = reverseChargeFieldOf(line.reverseChargeParagraph); reverseChargeBases.set(field, (reverseChargeBases.get(field) ?? 0) + signed); } if (baseCents === 0 && inputVatCents !== 0) { warnings.push( `entry ${label}: no base extractable (counterparty not a personal account?) — VAT line is ${inputVatCents} cents`, ); continue; } if (baseCents === 0) continue; // rate detection from the entry's own VAT line (19 % vs 7 %) const absBase = Math.abs(baseCents); const absVat = Math.abs(inputVatCents); const reduced = Math.abs(absVat * 100 - 7 * absBase) < Math.abs(absVat * 100 - 19 * absBase); const rate = reduced ? 7 : 19; const expectedVat = vatFromNetCents(baseCents, rate); if (Math.abs(inputVatCents - expectedVat) > 2) { warnings.push( `entry ${label}: base ${baseCents} cents at ${rate} % expects VAT ${expectedVat}, ledger line says ${inputVatCents}`, ); } if (entry.taxScenario === 'intra_eu_acquisition') { if (reduced) scenarioBases.intraEuAcquisitionReducedCents += baseCents; else scenarioBases.intraEuAcquisitionStandardCents += baseCents; } else { for (const [field, cents] of reverseChargeBases) scenarioBases[field] += cents; } } return { movements, scenarioBases, individualAccounts: structuredClone([...(policy.individualAccounts ?? [])]), taggedEntryCount: tagged.length, warnings, }; }