/** * Tax scenario detection — a pure, confidence-scored cascade: * document text patterns → counterparty country → amount plausibility → * default. Ported from the finance.plus VatRuleDetector design, with the * scenario vocabulary of core.types. */ import type { TBuKey, TCents, TTaxScenario } from './core.types.js'; import { suggestBuKey } from './core.bukeys.js'; export interface ITaxScenarioInput { direction: 'inbound' | 'outbound'; /** ISO 3166-1 alpha-2, defaults to 'DE' */ homeCountry?: string; counterpartyCountry?: string; counterpartyVatId?: string; documentText?: string; netCents?: TCents; vatCents?: TCents; vatRatePercent?: number; } export interface ITaxScenarioDetection { scenario: TTaxScenario; confidence: number; // 0-100 detectedBy: 'text' | 'country' | 'amounts' | 'default'; reasoning: string; suggestedBuKey: TBuKey; } /** * Today's member states of the EU beside Germany (ISO 3166-1 alpha-2; Greece * as `GR`), undated. A booking of a past day asks `isEuMemberOn`. */ export const EU_COUNTRIES = new Set([ 'AT', 'BE', 'BG', 'CY', 'CZ', 'DK', 'EE', 'ES', 'FI', 'FR', 'GR', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK', ]); /** * The changes of membership the books' days can reach, as ISO days: the first * day a state was a member (`from`), the last (`until`). * - HR from 2013-07-01, the entry into force of its Treaty of Accession. * - GB until 2020-12-31: it left on 2020-02-01, but Union law, the VAT * directive included, applied to it through the transition period of the * Withdrawal Agreement (Art. 126, 127), which ended on 2020-12-31. * A year of 2013 can still be assessed (ten years for evaded tax, § 169 * Abs. 2 Satz 2 AO, starting up to three years late, § 170 Abs. 2 AO); * earlier accessions (BG and RO on 2007-01-01, and before) precede any year * that can, so their states count as members on every day. */ const EU_MEMBERSHIP_CHANGES: Readonly> = { HR: { from: '2013-07-01' }, GB: { until: '2020-12-31' }, }; /** A day `isEuMemberOn` reads: a Date by its UTC day, as the recipes read booking dates; a text as an ISO day `YYYY-MM-DD`. */ function isoDayOf(dayArg: Date | string): string { if (dayArg instanceof Date) { if (Number.isNaN(dayArg.getTime())) { throw new Error('isEuMemberOn: the day is an Invalid Date'); } return dayArg.toISOString().slice(0, 10); } const parsed = /^\d{4}-\d{2}-\d{2}$/.test(dayArg) ? new Date(`${dayArg}T00:00:00.000Z`) : undefined; if (parsed === undefined || Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== dayArg) { throw new Error(`isEuMemberOn: ${JSON.stringify(dayArg)} is no ISO day (YYYY-MM-DD)`); } return dayArg; } /** * Whether a country (ISO 3166-1 alpha-2, any case) was a member state of the * EU on a day, as the EU's VAT law treats it: Germany and today's members * (`EU_COUNTRIES`) from the day they joined, the United Kingdom through * 2020-12-31 (`EU_MEMBERSHIP_CHANGES`). Undated, `EU_COUNTRIES` answers for * today only: a seat or supply of a past day asks this. Throws on a day that * is none. */ export function isEuMemberOn(country: string, day: Date | string): boolean { const isoDay = isoDayOf(day); const code = country.toUpperCase(); const change = EU_MEMBERSHIP_CHANGES[code]; if (change !== undefined) { return (change.from === undefined || isoDay >= change.from) && (change.until === undefined || isoDay <= change.until); } return code === 'DE' || EU_COUNTRIES.has(code); } const REVERSE_CHARGE_PATTERN = /reverse[\s-]?charge|steuerschuldnerschaft\s+des\s+leistungsempfängers|§\s*13\s*b/i; const INTRA_EU_PATTERN = /innergemeinschaftlich|intra[\s-]?community|steuerfreie\s+ig[\s-]?lieferung/i; const TAX_FREE_PATTERN = /steuerfrei|tax[\s-]?free|umsatzsteuerbefreit|§\s*4\s+ustg/i; /** * The zero rate of § 12 Abs. 3 UStG as an invoice states it: the paragraph, * with or without its number ("§ 12 Abs. 3 Nr. 1 UStG"), or the * "Nullsteuersatz". The words alone decide nothing: a document at 19 % may * name the paragraph too (a PV installation with a wallbox, "nicht nach § 12 * Abs. 3 UStG begünstigt"), so they count only on a document at 0 %. */ const ZERO_RATE_PATTERN = /§\s*12\s*Abs(?:atz|\.)?\s*3(?:\s*(?:Nr\.|Nummer)\s*\d+)?\s*UStG|Nullsteuersatz|Null-Steuersatz/iu; const EXPORT_PATTERN = /ausfuhr|ausfuhrlieferung|export\s+delivery/i; function rateOf(input: ITaxScenarioInput): number { if (typeof input.vatRatePercent === 'number') return input.vatRatePercent; if ( typeof input.netCents === 'number' && typeof input.vatCents === 'number' && input.netCents > 0 ) { const ratio = (input.vatCents / input.netCents) * 100; if (Math.abs(ratio - 19) <= 0.5) return 19; if (Math.abs(ratio - 7) <= 0.5) return 7; if (ratio < 0.5) return 0; return ratio; } return 19; } function detection( scenario: TTaxScenario, confidence: number, detectedBy: ITaxScenarioDetection['detectedBy'], reasoning: string, input: ITaxScenarioInput, ): ITaxScenarioDetection { return { scenario, confidence, detectedBy, reasoning, suggestedBuKey: suggestBuKey({ direction: input.direction, scenario, ratePercent: rateOf(input) === 7 ? 7 : rateOf(input) === 0 ? 0 : 19, targetIsAutomatik: false, hasExplicitVatLines: true, }), }; } export function detectTaxScenario(input: ITaxScenarioInput): ITaxScenarioDetection { const home = (input.homeCountry ?? 'DE').toUpperCase(); const text = input.documentText ?? ''; const rate = rateOf(input); // Stage 1: explicit wording on the document if (text) { if (REVERSE_CHARGE_PATTERN.test(text)) { return detection( 'reverse_charge_13b', 90, 'text', 'Document mentions reverse charge / §13b UStG', input, ); } if (INTRA_EU_PATTERN.test(text)) { return detection( input.direction === 'inbound' ? 'intra_eu_acquisition' : 'intra_eu_supply', 90, 'text', 'Document mentions an intra-community transaction', input, ); } if (ZERO_RATE_PATTERN.test(text) && input.direction === 'outbound' && rate === 0) { return detection('domestic_zero_rate', 90, 'text', 'Document mentions the zero rate of § 12 Abs. 3 UStG', input); } if (EXPORT_PATTERN.test(text) && input.direction === 'outbound') { return detection('export_third_country', 90, 'text', 'Document mentions Ausfuhr/export', input); } if (TAX_FREE_PATTERN.test(text)) { return detection('domestic_tax_free', 85, 'text', 'Document mentions tax exemption', input); } } // Stage 2: counterparty country (B2B assumed when a VAT ID is present) const country = input.counterpartyCountry?.toUpperCase(); if (country && country !== home) { if (EU_COUNTRIES.has(country)) { const b2b = !!input.counterpartyVatId; return detection( input.direction === 'inbound' ? 'intra_eu_acquisition' : 'intra_eu_supply', b2b ? 80 : 60, 'country', `Counterparty in EU country ${country}${b2b ? ' with VAT ID' : ' without VAT ID'}`, input, ); } return detection( input.direction === 'inbound' ? 'reverse_charge_13b' : 'export_third_country', 75, 'country', `Counterparty in third country ${country}`, input, ); } // Stage 3: amount plausibility if (typeof input.netCents === 'number' && typeof input.vatCents === 'number') { if (input.netCents > 0 && input.vatCents === 0) { return detection('domestic_tax_free', 60, 'amounts', 'Positive net with zero VAT', input); } if (rate === 7) { return detection('domestic_reduced', 70, 'amounts', 'VAT/net ratio matches 7 %', input); } if (rate === 19) { return detection('domestic_standard', 70, 'amounts', 'VAT/net ratio matches 19 %', input); } } // Default return detection( rate === 7 ? 'domestic_reduced' : 'domestic_standard', 50, 'default', 'No signals — assuming domestic transaction at standard assumptions', input, ); }