// SPDX-License-Identifier: EUPL-1.2 // EN 16931 VAT category rule families (BR-S, BR-Z, BR-E, BR-AE, BR-IC, BR-G, BR-O, BR-IG, // BR-IP, BR-B), re-implemented from the CEN validation artefacts 1.3.17. Release 1.3.16 names // the L and M families BR-AF and BR-AG with identical tests; both names are registered. The published // assertions differ in small ways between categories (whether the tax scheme is checked, // whether the code is whitespace-normalised, where allowances are looked up); those // differences are kept on purpose so results match the official artefact. import type { Dec } from "./decimal"; import { abs, add, cmp, div100, eq, fromInt, mul, round2, sub } from "./decimal"; import { all, dec, decAt, first, has, stringValue, value } from "./query"; import type { CenRelease, RuleContext, RuleRow } from "./types"; import { CUSTOMER_PARTY, SUPPLIER_PARTY, chargeFlag, isVat, sumAt } from "./ubl"; import type { XmlNode } from "./xml"; type Category = "S" | "Z" | "E" | "AE" | "K" | "G" | "O" | "L" | "M"; const FAMILY: Readonly> = { S: "BR-S", Z: "BR-Z", E: "BR-E", AE: "BR-AE", K: "BR-IC", G: "BR-G", O: "BR-O", L: "BR-IG", M: "BR-IP" }; /** Family names in release 1.3.16 where they differ from 1.3.17. */ const FAMILY_1316: Readonly>> = { L: "BR-AF", M: "BR-AG" }; const familyOf = (category: Category, cen: CenRelease): string => (cen === "1.3.16" ? FAMILY_1316[category] : undefined) ?? FAMILY[category]; const LABEL: Readonly> = { S: "S (standard rated)", Z: "Z (zero rated)", E: "E (exempt from VAT)", AE: "AE (reverse charge)", K: "K (intra-community supply)", G: "G (export outside the EU)", O: "O (not subject to VAT)", L: "L (IGIC, Canary Islands)", M: "M (IPSI, Ceuta and Melilla)" }; const CATEGORIES: readonly Category[] = ["S", "Z", "E", "AE", "K", "G", "O", "L", "M"]; const RATED: readonly Category[] = ["S", "L", "M"]; function sellerRequirement(category: Category): string { switch (category) { case "AE": return "require a seller VAT or tax registration identifier (BT-31, BT-32) or tax representative VAT identifier (BT-63), and a buyer VAT identifier (BT-48) or legal registration identifier (BT-47)"; case "K": return "require a seller VAT identifier (BT-31) or tax representative VAT identifier (BT-63), and a buyer VAT identifier (BT-48)"; case "G": return "require a seller VAT identifier (BT-31) or tax representative VAT identifier (BT-63)"; case "O": return "do not allow a seller VAT identifier (BT-31), tax representative VAT identifier (BT-63) or buyer VAT identifier (BT-48)"; default: return "require a seller VAT identifier (BT-31), seller tax registration identifier (BT-32) or tax representative VAT identifier (BT-63)"; } } function rateRequirement(category: Category): string { if (category === "S") return "must have a VAT rate greater than zero"; if (category === "L" || category === "M") return "must have a tax rate of zero or greater"; if (category === "O") return "must not have a VAT rate"; return "must have a VAT rate of 0"; } function buildRows(): RuleRow[] { const rows: RuleRow[] = []; for (const category of CATEGORIES) { const families = [FAMILY[category], FAMILY_1316[category]].filter((name): name is string => name !== undefined); const label = LABEL[category]; const rated = RATED.includes(category); const push = (suffix: string, message: string): void => { for (const family of families) rows.push([`${family}-${suffix}`, "fatal", message]); }; push( "01", rated ? `An invoice with a line, allowance or charge in VAT category ${label} must have at least one VAT breakdown (BG-23) with that category, and none otherwise.` : `An invoice that uses VAT category ${label} must have exactly one VAT breakdown (BG-23) with that category.` ); push("02", `Invoice lines in VAT category ${label} ${sellerRequirement(category)}.`); push("03", `Document level allowances in VAT category ${label} ${sellerRequirement(category)}.`); push("04", `Document level charges in VAT category ${label} ${sellerRequirement(category)}.`); push("05", `An invoice line in VAT category ${label} ${rateRequirement(category)} (BT-152).`); push("06", `A document level allowance in VAT category ${label} ${rateRequirement(category)} (BT-96).`); push("07", `A document level charge in VAT category ${label} ${rateRequirement(category)} (BT-103).`); push( "08", rated ? `For each rate in VAT category ${label}, the taxable amount (BT-116) must equal line net amounts plus charges minus allowances at that rate, within 1 currency unit.` : `The taxable amount (BT-116) of VAT category ${label} must equal its line net amounts plus charges minus allowances.` ); push( "09", rated ? `The tax amount (BT-117) of VAT category ${label} must equal the taxable amount (BT-116) times the rate (BT-119) / 100, within 1 currency unit.` : `The tax amount (BT-117) of VAT category ${label} must be 0.` ); push( "10", rated || category === "Z" ? `A VAT breakdown in category ${label} must not have an exemption reason (BT-120) or exemption reason code (BT-121).` : `A VAT breakdown in category ${label} must have an exemption reason (BT-120) or exemption reason code (BT-121).` ); if (category === "K") { push("11", "An intra-community supply (category K) requires an actual delivery date (BT-72) or an invoicing period (BG-14)."); push("12", "An intra-community supply (category K) requires a deliver-to country code (BT-80)."); } if (category === "O") { push("11", "An invoice with a VAT breakdown in category O must not contain any other VAT breakdown."); push("12", "An invoice with a VAT breakdown in category O must not contain invoice lines in another VAT category."); push("13", "An invoice with a VAT breakdown in category O must not contain document level allowances in another VAT category."); push("14", "An invoice with a VAT breakdown in category O must not contain document level charges in another VAT category."); } } rows.push(["BR-B-01", "fatal", "VAT category B (split payment) is allowed only on a domestic Italian invoice: every country code must be IT."]); rows.push(["BR-B-02", "fatal", "An invoice using VAT category B (split payment) must not also use category S (standard rated)."]); return rows; } export const EN16931_VAT_RULES: readonly RuleRow[] = buildRows(); const ONE = fromInt(1); function decEq(a: Dec | null, b: Dec | null): boolean { return a !== null && b !== null && eq(a, b); } /** `value - 1 < expected and value + 1 > expected` */ function withinOne(amount: Dec | null, expected: Dec): boolean { return amount !== null && cmp(sub(amount, ONE), expected) < 0 && cmp(add(amount, ONE), expected) > 0; } /** Facts about one cac:TaxCategory or cac:ClassifiedTaxCategory, read once per document. */ interface CategoryFacts { readonly node: XmlNode; /** `normalize-space(cbc:ID)` of the first identifier. */ readonly code: string; readonly normalizedCodes: readonly string[]; readonly rawCodes: readonly string[]; readonly vat: boolean; readonly rates: readonly Dec[]; } function readFacts(node: XmlNode): CategoryFacts { const ids = all(node, "cbc:ID"); const rates: Dec[] = []; for (const percent of all(node, "cbc:Percent")) { const parsed = dec(percent); if (parsed) rates.push(parsed); } return { node, code: value(ids[0]), normalizedCodes: ids.map((id) => value(id)), rawCodes: ids.map((id) => stringValue(id)), vat: isVat(node), rates }; } interface AllowanceChargeFacts { readonly node: XmlNode; readonly charge: boolean | null; readonly atRoot: boolean; readonly categories: readonly CategoryFacts[]; } interface LineFacts { readonly node: XmlNode; readonly categories: readonly CategoryFacts[]; } export function runVatRules(context: RuleContext): void { const { root, index, emit } = context; const check = (ok: boolean, id: string, node: XmlNode): void => { if (!ok) emit(id, node); }; const classified = index.named("cac:ClassifiedTaxCategory").map(readFacts); const everyTaxCategory = index.named("cac:TaxCategory").map(readFacts); const factsByNode = new Map(everyTaxCategory.map((facts) => [facts.node, facts])); const classifiedByNode = new Map(classified.map((facts) => [facts.node, facts])); const factsOf = (nodes: readonly XmlNode[], lookup: ReadonlyMap): CategoryFacts[] => { const out: CategoryFacts[] = []; for (const node of nodes) { const facts = lookup.get(node); if (facts) out.push(facts); } return out; }; const allowanceCharges: AllowanceChargeFacts[] = index.named("cac:AllowanceCharge").map((node) => ({ node, charge: chargeFlag(node), atRoot: node.parent === root, categories: factsOf(all(node, "cac:TaxCategory"), factsByNode) })); const anyAcCategories = allowanceCharges.flatMap((item) => item.categories); const acCategories = (charge: boolean): CategoryFacts[] => allowanceCharges.filter((item) => item.charge === charge).flatMap((item) => item.categories); const allowanceCategories = acCategories(false); const chargeCategories = acCategories(true); const rootAc = (charge: boolean): AllowanceChargeFacts[] => allowanceCharges.filter((item) => item.atRoot && item.charge === charge); const rootAllowances = rootAc(false); const rootCharges = rootAc(true); const breakdownCategories = factsOf(all(root, "cac:TaxTotal/cac:TaxSubtotal/cac:TaxCategory"), factsByNode); const linesNamed = (name: string): LineFacts[] => all(root, name).map((node) => ({ node, categories: factsOf(all(node, "cac:Item/cac:ClassifiedTaxCategory"), classifiedByNode) })); const rootInvoiceLines = linesNamed("cac:InvoiceLine"); const rootCreditLines = linesNamed("cac:CreditNoteLine"); /** Classified categories that sit directly in a line item, the context of rule 05. */ const lineItemCategories = classified.filter((facts) => { const item = facts.node.parent; const line = item?.parent; return item?.q === "cac:Item" && (line?.q === "cac:InvoiceLine" || line?.q === "cac:CreditNoteLine"); }); const deepLineUse = (name: string, matches: (facts: CategoryFacts) => boolean): boolean => index.named(name).some((line) => factsOf(all(line, "cac:Item/cac:ClassifiedTaxCategory"), classifiedByNode).some(matches)); const sellerAnyTaxId = index.deep(`${SUPPLIER_PARTY}/cac:PartyTaxScheme/cbc:CompanyID`).length > 0; const vatIdOf = (path: string): boolean => index.deep(path).some((scheme) => isVat(scheme) && has(scheme, "cbc:CompanyID")); const sellerVat = vatIdOf(`${SUPPLIER_PARTY}/cac:PartyTaxScheme`); const representativeVat = vatIdOf("cac:TaxRepresentativeParty/cac:PartyTaxScheme"); const buyerVat = vatIdOf(`${CUSTOMER_PARTY}/cac:PartyTaxScheme`); const buyerLegal = index.deep(`${CUSTOMER_PARTY}/cac:PartyLegalEntity/cbc:CompanyID`).length > 0; const hasInvoiceLines = index.named("cac:InvoiceLine").length > 0; const hasCreditLines = index.named("cac:CreditNoteLine").length > 0; /** Seller/buyer identifier condition shared by rules 02, 03 and 04 of a category. */ const partiesOk = (category: Category): boolean => { switch (category) { case "AE": return (sellerAnyTaxId || representativeVat) && (buyerVat || buyerLegal); case "K": return (sellerVat || representativeVat) && buyerVat; case "G": return sellerVat || representativeVat; case "O": return !sellerVat && !representativeVat && !buyerVat; default: return sellerAnyTaxId || representativeVat; } }; const rateOk = (category: Category, facts: CategoryFacts): boolean => { const percents = all(facts.node, "cbc:Percent"); if (category === "O") return percents.length === 0; const parsed = dec(percents[0]); if (parsed === null) return false; if (category === "S") return parsed.n > 0n; if (category === "L" || category === "M") return parsed.n >= 0n; return parsed.n === 0n; }; const hasRate = (facts: CategoryFacts, rate: Dec): boolean => facts.rates.some((candidate) => eq(candidate, rate)); for (const category of CATEGORIES) { const family = familyOf(category, context.cen); const rated = RATED.includes(category); const is = (facts: CategoryFacts): boolean => facts.code === category; const isVatCategory = (facts: CategoryFacts): boolean => facts.code === category && facts.vat; const hasCode = (facts: CategoryFacts): boolean => facts.normalizedCodes.includes(category); const hasRawCode = (facts: CategoryFacts): boolean => facts.rawCodes.includes(category); // --- 01: breakdown presence ----------------------------------------------------------- let rule01: boolean; if (category === "S") { const used = anyAcCategories.filter(is).length + classified.filter(is).length; const breakdowns = breakdownCategories.filter(is).length; rule01 = (used > 0 && breakdowns > 0) || (used === 0 && breakdowns === 0); } else if (category === "L" || category === "M") { const used = anyAcCategories.filter(isVatCategory).length + classified.filter(isVatCategory).length; const rawBreakdowns = breakdownCategories.filter((facts) => hasRawCode(facts) && (category === "L" || facts.vat)).length; const vatBreakdowns = breakdownCategories.filter(isVatCategory).length; rule01 = (used > 0 && rawBreakdowns > 0) || (used === 0 && vatBreakdowns === 0); } else { const used = everyTaxCategory.some((facts) => facts.vat && hasCode(facts)) || classified.some((facts) => facts.vat && hasCode(facts)); let breakdownIds = 0; for (const facts of breakdownCategories) { if (facts.vat) breakdownIds += facts.normalizedCodes.filter((code) => code === category).length; } rule01 = !used || breakdownIds === 1; } check(rule01, `${family}-01`, root); // --- 02: lines ------------------------------------------------------------------------ const lineUse = classified.some(isVatCategory); const lineUseForNegative = category === "S" ? classified.some(is) : lineUse; check((lineUse && partiesOk(category)) || !lineUseForNegative, `${family}-02`, root); // --- 03 / 04: document level allowances and charges ------------------------------------- for (const charge of [false, true]) { const suffix = charge ? "04" : "03"; let positive: boolean; let negative: boolean; if (category === "O") { positive = (charge ? rootCharges : rootAllowances).flatMap((item) => item.categories).some(isVatCategory); negative = positive; } else { const candidates = charge ? chargeCategories : allowanceCategories; const withVat = candidates.some(isVatCategory); positive = category === "G" ? candidates.some(is) : withVat; negative = category === "L" && charge ? candidates.some((facts) => hasRawCode(facts) && facts.vat) : withVat; } check((positive && partiesOk(category)) || !negative, `${family}-${suffix}`, root); } // --- 05 / 06 / 07: rate on lines, allowances and charges ---------------------------------- for (const facts of lineItemCategories) if (isVatCategory(facts)) check(rateOk(category, facts), `${family}-05`, facts.node); for (const facts of allowanceCategories) if (isVatCategory(facts)) check(rateOk(category, facts), `${family}-06`, facts.node); for (const facts of chargeCategories) if (isVatCategory(facts)) check(rateOk(category, facts), `${family}-07`, facts.node); // --- 08 / 09 / 10: VAT breakdown ------------------------------------------------------------ for (const facts of breakdownCategories) { if (!isVatCategory(facts)) continue; const node = facts.node; const subtotal = node.parent ?? root; const taxable = decAt(subtotal, "cbc:TaxableAmount"); const taxAmount = decAt(subtotal, "cbc:TaxAmount"); const rate = dec(first(node, "cbc:Percent")); /** Root lines, charges and allowances in this category (and rate, when given). */ const baseFor = (lines: readonly LineFacts[], forRate: Dec | null): Dec => { const matches = (candidate: CategoryFacts): boolean => is(candidate) && (forRate === null || hasRate(candidate, forRate)); const pick = (items: readonly AllowanceChargeFacts[]): XmlNode[] => items.filter((item) => item.categories.some(matches)).map((item) => item.node); const lineNodes = lines.filter((line) => line.categories.some(matches)).map((line) => line.node); return sub(add(sumAt(lineNodes, "cbc:LineExtensionAmount"), sumAt(pick(rootCharges), "cbc:Amount")), sumAt(pick(rootAllowances), "cbc:Amount")); }; if (rated) { let rule08 = true; if (rate !== null) { const toleranceInvoice = withinOne(taxable, baseFor(rootInvoiceLines, rate)); const toleranceCredit = withinOne(taxable, baseFor(rootCreditLines, rate)); if (category === "S") { const matches = (candidate: CategoryFacts): boolean => is(candidate) && hasRate(candidate, rate); const acUse = anyAcCategories.some(matches); rule08 = ((deepLineUse("cac:InvoiceLine", matches) || acUse) && toleranceInvoice) || ((deepLineUse("cac:CreditNoteLine", matches) || acUse) && toleranceCredit); } else { rule08 = (hasInvoiceLines && toleranceInvoice) || (hasCreditLines && toleranceCredit); } } check(rule08, `${family}-08`, node); const expectedTax = rate !== null && taxable !== null ? round2(mul(abs(taxable), div100(rate))) : null; check(expectedTax !== null && taxAmount !== null && withinOne(abs(taxAmount), expectedTax), `${family}-09`, node); check(!has(node, "cbc:TaxExemptionReason") && !has(node, "cbc:TaxExemptionReasonCode"), `${family}-10`, node); } else { check( (hasInvoiceLines && decEq(taxable, baseFor(rootInvoiceLines, null))) || (hasCreditLines && decEq(taxable, baseFor(rootCreditLines, null))), `${family}-08`, node ); check(taxAmount !== null && taxAmount.n === 0n, `${family}-09`, node); const hasExemption = has(node, "cbc:TaxExemptionReason") || has(node, "cbc:TaxExemptionReasonCode"); check(category === "Z" ? !hasExemption : hasExemption, `${family}-10`, node); } } } // --- Category K and O document conditions ------------------------------------------------- const breakdownHas = (code: string): boolean => breakdownCategories.some((facts) => facts.vat && facts.normalizedCodes.includes(code)); if (breakdownHas("K")) { check( stringValue(first(root, "cac:Delivery/cbc:ActualDeliveryDate")).length > 1 || all(root, "cac:InvoicePeriod").some((period) => period.children.length > 0), "BR-IC-11", root ); check( stringValue(first(root, "cac:Delivery/cac:DeliveryLocation/cac:Address/cac:Country/cbc:IdentificationCode")).length > 1, "BR-IC-12", root ); } if (breakdownHas("O")) { const otherVat = (facts: CategoryFacts): boolean => facts.code !== "O" && facts.vat; check(!breakdownCategories.some(otherVat), "BR-O-11", root); check(!classified.some(otherVat), "BR-O-12", root); check(!allowanceCategories.some(otherVat), "BR-O-13", root); check(!chargeCategories.some(otherVat), "BR-O-14", root); } // --- Category B (split payment) -------------------------------------------------------------- const rawUse = (list: readonly CategoryFacts[], code: string): boolean => list.some((facts) => facts.rawCodes.includes(code)); if (rawUse(everyTaxCategory, "B") || rawUse(classified, "B")) { check(!index.named("cbc:IdentificationCode").some((code) => stringValue(code) !== "IT"), "BR-B-01", root); } const rootAcCategories = allowanceCharges.filter((item) => item.atRoot).flatMap((item) => item.categories); const usedInDocument = (code: string): boolean => rawUse(breakdownCategories, code) || rawUse(rootAcCategories, code) || rawUse(classified, code); if (usedInDocument("B")) check(!usedInDocument("S"), "BR-B-02", root); }