// SPDX-License-Identifier: EUPL-1.2 // UBL syntax binding rules of EN 16931 (families UBL-SR, UBL-DT, UBL-CR), re-implemented // from pattern "UBL-syntax" of the CEN validation artefacts 1.3.17 (1.3.16 differs in UBL-SR-25 // and has no UBL-SR-57 or UBL-SR-58). import { all, first, has, stringValue } from "./query"; import type { RuleContext, RuleRow } from "./types"; import { CUSTOMER_PARTY, SUPPLIER_PARTY, anyDifferent, atMostTwoDecimals, isAllowance, isCharge } from "./ubl"; import { UBL_CR_TABLE } from "./ubl-cr-table"; import type { XmlNode } from "./xml"; const F = "fatal" as const; const W = "warning" as const; /** Attributes that EN 16931 does not use (UBL-DT-08 to UBL-DT-28, except -18). */ const UNUSED_ATTRIBUTES: readonly (readonly [string, string])[] = [ ["08", "schemeName"], ["09", "schemeAgencyName"], ["10", "schemeDataURI"], ["11", "schemeURI"], ["12", "format"], ["13", "unitCodeListIdentifier"], ["14", "unitCodeListAgencyIdentifier"], ["15", "unitCodeListAgencyName"], ["16", "listAgencyName"], ["17", "listName"], ["19", "languageID"], ["20", "listURI"], ["21", "listSchemeURI"], ["22", "languageLocaleID"], ["23", "uri"], ["24", "currencyCodeListVersionID"], ["25", "characterSetCode"], ["26", "encodingCode"], ["27", "schemeAgencyID"], ["28", "listAgencyID"] ]; function expandSegment(segment: string): string { if (segment.startsWith("a:")) return `cac:${segment.slice(2)}`; if (segment.startsWith("b:")) return `cbc:${segment.slice(2)}`; if (segment.startsWith("e:")) return `ext:${segment.slice(2)}`; return segment; } interface Restriction { readonly ruleId: string; readonly attribute: string | undefined; } interface DeepRestriction extends Restriction { readonly path: string; } // The 673 restrictions are evaluated in one walk of the document instead of 673 path // queries. Keys are child paths from the root; a root-level invoice line is the step "L". const EXACT_RESTRICTIONS = new Map(); const RESTRICTION_PREFIXES = new Set(); const DEEP_RESTRICTIONS: DeepRestriction[] = []; /** Attribute name -> rule for attributes that are unused wherever they occur. */ const ATTRIBUTE_RULES = new Map(UNUSED_ATTRIBUTES.map(([number, attribute]) => [attribute, `UBL-DT-${number}`])); const RESTRICTION_DISPLAY: (readonly [string, string])[] = []; for (const entry of UBL_CR_TABLE) { const ruleId = `UBL-CR-${entry.id}`; const deep = entry.path.startsWith("//"); const segments = (deep ? entry.path.slice(2) : entry.path).split("/"); const last = segments[segments.length - 1] ?? ""; const attribute = last.startsWith("@") ? last.slice(1) : undefined; if (attribute !== undefined) segments.pop(); const expanded = segments.map((segment) => (segment === "L" ? "L" : expandSegment(segment))); const readable = expanded.map((segment) => (segment === "L" ? "cac:InvoiceLine" : segment)).join("/"); RESTRICTION_DISPLAY.push([ruleId, `${deep ? "//" : ""}${readable}${attribute === undefined ? "" : `${readable === "" ? "" : "/"}@${attribute}`}`]); if (deep) { if (expanded.length === 0 && attribute !== undefined) ATTRIBUTE_RULES.set(attribute, ruleId); else DEEP_RESTRICTIONS.push({ ruleId, attribute, path: expanded.join("/") }); continue; } const key = expanded.join("/"); const list = EXACT_RESTRICTIONS.get(key); if (list) list.push({ ruleId, attribute }); else EXACT_RESTRICTIONS.set(key, [{ ruleId, attribute }]); for (let depth = 1; depth < expanded.length; depth += 1) RESTRICTION_PREFIXES.add(expanded.slice(0, depth).join("/")); } const DOCUMENT_REFERENCE_COUNTS: readonly (readonly [string, string, string])[] = [ ["UBL-SR-01", "cac:ContractDocumentReference/cbc:ID", "contract reference (BT-12)"], ["UBL-SR-02", "cac:ReceiptDocumentReference/cbc:ID", "receiving advice reference (BT-15)"], ["UBL-SR-03", "cac:DespatchDocumentReference/cbc:ID", "despatch advice reference (BT-16)"], ["UBL-SR-05", "cac:PaymentTerms/cbc:Note", "payment terms (BT-20)"], ["UBL-SR-08", "cac:InvoicePeriod", "invoicing period (BG-14)"], ["UBL-SR-09", `${SUPPLIER_PARTY}/cac:PartyLegalEntity/cbc:RegistrationName`, "seller name (BT-27)"], ["UBL-SR-10", `${SUPPLIER_PARTY}/cac:PartyName/cbc:Name`, "seller trading name (BT-28)"], ["UBL-SR-11", `${SUPPLIER_PARTY}/cac:PartyLegalEntity/cbc:CompanyID`, "seller legal registration identifier (BT-30)"], ["UBL-SR-14", `${SUPPLIER_PARTY}/cac:PartyLegalEntity/cbc:CompanyLegalForm`, "seller additional legal information (BT-33)"], ["UBL-SR-15", `${CUSTOMER_PARTY}/cac:PartyLegalEntity/cbc:RegistrationName`, "buyer name (BT-44)"], ["UBL-SR-16", `${CUSTOMER_PARTY}/cac:PartyIdentification/cbc:ID`, "buyer identifier (BT-46)"], ["UBL-SR-17", `${CUSTOMER_PARTY}/cac:PartyLegalEntity/cbc:CompanyID`, "buyer legal registration identifier (BT-47)"], ["UBL-SR-24", "cac:Delivery", "delivery information (BG-13)"], ["UBL-SR-39", "cac:ProjectReference/cbc:ID", "project reference (BT-11)"], ["UBL-SR-40", `${CUSTOMER_PARTY}/cac:PartyName/cbc:Name`, "buyer trading name (BT-45)"], ["UBL-SR-45", "cac:PaymentMeans/cbc:PaymentDueDate", "payment due date (BT-9)"], ["UBL-SR-49", "cac:InvoicePeriod/cbc:DescriptionCode", "VAT point date code (BT-8)"], ["UBL-SR-54", "cac:PaymentMeans/cac:CardAccount", "payment card information (BG-18)"], ["UBL-SR-55", "cac:PaymentMeans/cac:PaymentMandate", "direct debit information (BG-19)"], ["UBL-SR-56", "cac:OriginatorDocumentReference/cbc:ID", "tender or lot reference (BT-17)"] ]; function buildRows(): RuleRow[] { const rows: RuleRow[] = DOCUMENT_REFERENCE_COUNTS.map(([id, , label]) => [id, F, `Only one ${label} is allowed.`] as const); rows.push( ["UBL-SR-04", F, "Only one invoiced object identifier (BT-18, document type code 130) is allowed."], ["UBL-SR-06", F, "Each billing reference allows only one preceding invoice reference (BT-25)."], ["UBL-SR-07", F, "A billing reference must contain the preceding invoice number (BT-25)."], ["UBL-SR-12", F, "Only one seller VAT identifier (BT-31) is allowed."], ["UBL-SR-13", F, "Only one seller tax registration identifier (BT-32) is allowed."], ["UBL-SR-18", F, "Only one buyer VAT identifier (BT-48) is allowed."], ["UBL-SR-19", F, "The payee allows one name (BT-59), and it must differ from the seller name (BT-27)."], ["UBL-SR-20", F, "The payee allows one identifier (BT-60), and the payee name must differ from the seller name (BT-27)."], ["UBL-SR-21", F, "The payee allows one legal registration identifier (BT-61), and the payee name must differ from the seller name (BT-27)."], ["UBL-SR-22", F, "Only one seller tax representative name (BT-62) is allowed."], ["UBL-SR-23", F, "Only one seller tax representative VAT identifier (BT-63) is allowed."], ["UBL-SR-25", F, "A deliver-to party must have exactly one name (BT-70); release 1.3.16 only forbids more than one."], ["UBL-SR-26", F, "Each payment instruction allows only one payment reference (BT-83)."], ["UBL-SR-27", F, "Each payment instruction allows only one payment means code (BT-81)."], ["UBL-SR-28", F, "Only one mandate reference identifier (BT-89) is allowed."], ["UBL-SR-29", F, "Only one bank assigned creditor identifier (BT-90, scheme SEPA) is allowed."], ["UBL-SR-30", F, "A document level allowance allows only one reason (BT-97)."], ["UBL-SR-31", F, "A document level charge allows only one reason (BT-104)."], ["UBL-SR-32", F, "A VAT breakdown allows only one exemption reason text (BT-120)."], ["UBL-SR-33", F, "A supporting document allows only one description (BT-123)."], ["UBL-SR-34", F, "An invoice line allows only one note (BT-127)."], ["UBL-SR-35", F, "An invoice line allows only one referenced purchase order line (BT-132)."], ["UBL-SR-36", F, "An invoice line allows only one line period (BG-26)."], ["UBL-SR-37", F, "An invoice line allows only one item price discount (BT-147)."], ["UBL-SR-42", F, "The seller allows at most two tax scheme registrations (VAT identifier and tax registration identifier)."], ["UBL-SR-43", F, "A scheme identifier or document type code on a supporting document is allowed only for the invoiced object (type code 130), or type code 50 in a credit note."], ["UBL-SR-44", F, "All payment instructions must carry the same payment reference (BT-83)."], ["UBL-SR-46", F, "Only one payment means text (BT-82) is allowed."], ["UBL-SR-47", F, "All payment instructions must use the same payment means code (BT-81)."], ["UBL-SR-48", F, "An invoice line must have exactly one classified tax category."], ["UBL-SR-50", F, "An invoice line allows only one item description (BT-154)."], ["UBL-SR-51", F, "A postal address allows at most one address line element (third address line)."], ["UBL-SR-52", F, "An invoice line allows only one object identifier (BT-128)."], ["UBL-SR-53", F, "A party tax scheme must contain a company identifier and a tax scheme identifier."], ["UBL-SR-57", F, "Seller, buyer, payee and tax representative each allow only one legal entity element."], ["UBL-SR-58", F, "A payment service provider (BT-86) must be given as exactly one financial institution branch identifier."], ["UBL-DT-01", F, "Amounts allow at most 2 decimals (prices and price discounts are exempt)."], ["UBL-DT-06", F, "An embedded document must state its MIME code (mimeCode)."], ["UBL-DT-07", F, "An embedded document must state its file name (filename)."], ["UBL-DT-18", W, "The name attribute should be used only on the payment means code."] ); for (const [number, attribute] of UNUSED_ATTRIBUTES) { rows.push([`UBL-DT-${number}`, W, `The attribute "${attribute}" is not used by EN 16931 and should be removed.`]); } rows.push( ["UBL-CR-002", W, "cbc:UBLVersionID should be omitted or set to 2.1."], ["UBL-CR-412", W, "cac:PaymentMeans/cbc:PaymentDueDate is not used in an invoice; use cbc:DueDate."], ["UBL-CR-665", W, "A scheme identifier on a supporting document reference should be used only for the invoiced object (type code 130)."], ["UBL-CR-666", F, "An invoiced object reference (type code 130) must not carry an attachment."], ["UBL-CR-673", F, "An invoiced object reference (type code 130) must not carry a document description."] ); for (const [ruleId, display] of RESTRICTION_DISPLAY) { rows.push([ruleId, W, `${display} is not used by EN 16931 and should be removed.`]); } return rows; } export const UBL_SYNTAX_RULES: readonly RuleRow[] = buildRows(); const isVatUpper = (scheme: XmlNode): boolean => all(scheme, "cac:TaxScheme").some((taxScheme) => stringValue(first(taxScheme, "cbc:ID")).toUpperCase() === "VAT"); export function runSyntaxRules(context: RuleContext): void { const { root, index, emit, isCreditNote, cen } = context; const current = cen === "1.3.17"; const check = (ok: boolean, id: string, node: XmlNode): void => { if (!ok) emit(id, node); }; const atMostOne = (id: string, origin: XmlNode, path: string): void => { const found = all(origin, path); if (found.length > 1) emit(id, found[1] ?? origin); }; // --- Root cardinalities --------------------------------------------------------------- for (const [id, path] of DOCUMENT_REFERENCE_COUNTS) atMostOne(id, root, path); const objectIds = all(root, "cac:AdditionalDocumentReference") .filter((reference) => all(reference, "cbc:DocumentTypeCode").some((code) => stringValue(code) === "130")) .flatMap((reference) => all(reference, "cbc:ID")); check(objectIds.length <= 1, "UBL-SR-04", objectIds[1] ?? root); const sellerSchemes = all(root, `${SUPPLIER_PARTY}/cac:PartyTaxScheme`); const companyIds = (schemes: readonly XmlNode[]): XmlNode[] => schemes.flatMap((scheme) => all(scheme, "cbc:CompanyID")); check(companyIds(sellerSchemes.filter(isVatUpper)).length <= 1, "UBL-SR-12", root); check(companyIds(sellerSchemes.filter((scheme) => !isVatUpper(scheme) && has(scheme, "cac:TaxScheme"))).length <= 1, "UBL-SR-13", root); check(companyIds(all(root, `${CUSTOMER_PARTY}/cac:PartyTaxScheme`).filter(isVatUpper)).length <= 1, "UBL-SR-18", root); const sepaIds = index.deep("cac:PartyIdentification/cbc:ID").filter((id) => (id.attrs["schemeID"] ?? "").toUpperCase() === "SEPA"); check(sepaIds.length <= 1, "UBL-SR-29", sepaIds[1] ?? root); check(new Set(index.named("cbc:PaymentID").map((node) => stringValue(node))).size <= 1, "UBL-SR-44", root); check( all(root, "cac:PaymentMeans/cbc:PaymentMeansCode").filter((code) => code.attrs["name"] !== undefined).length <= 1, "UBL-SR-46", root ); check(new Set(index.named("cbc:PaymentMeansCode").map((node) => stringValue(node))).size <= 1, "UBL-SR-47", root); if (current) { check( [`${SUPPLIER_PARTY}/cac:PartyLegalEntity`, `${CUSTOMER_PARTY}/cac:PartyLegalEntity`, "cac:PayeeParty/cac:PartyLegalEntity", "cac:TaxRepresentativeParty/cac:PartyLegalEntity"].every( (path) => all(root, path).length <= 1 ), "UBL-SR-57", root ); } // --- Unused attributes: one pass over all elements; each rule reports its first offender ---- const fired = new Set(); const fireOnce = (ruleId: string, node: XmlNode): void => { if (fired.has(ruleId)) return; fired.add(ruleId); emit(ruleId, node); }; for (const node of index.elements) { for (const name in node.attrs) { const ruleId = ATTRIBUTE_RULES.get(name); if (ruleId !== undefined) fireOnce(ruleId, node); else if (name === "name" && node.q !== "cbc:PaymentMeansCode") fireOnce("UBL-DT-18", node); } } // --- Elements outside the EN 16931 subset ------------------------------------------------ const versionId = first(root, "cbc:UBLVersionID"); if (versionId && !all(root, "cbc:UBLVersionID").some((node) => stringValue(node) === "2.1")) emit("UBL-CR-002", versionId); if (!isCreditNote) { const dueDate = first(root, "cac:PaymentMeans/cbc:PaymentDueDate"); if (dueDate) emit("UBL-CR-412", dueDate); } for (const reference of index.named("cac:AdditionalDocumentReference")) { const typeCodes = all(reference, "cbc:DocumentTypeCode"); const isObject = typeCodes.some((code) => stringValue(code) === "130"); const notObject = typeCodes.length === 0 || typeCodes.some((code) => stringValue(code) !== "130"); if (notObject) { const schemed = all(reference, "cbc:ID").find((id) => id.attrs["schemeID"] !== undefined); if (schemed) emit("UBL-CR-665", schemed); } if (isObject) { const attachment = first(reference, "cac:Attachment"); if (attachment) emit("UBL-CR-666", attachment); const description = first(reference, "cbc:DocumentDescription"); if (description) emit("UBL-CR-673", description); } } const pending: (readonly [XmlNode, string])[] = []; for (let position = root.children.length - 1; position >= 0; position -= 1) { const child = root.children[position]; if (child) pending.push([child, child.q === "cac:InvoiceLine" || child.q === "cac:CreditNoteLine" ? "L" : child.q]); } while (pending.length > 0) { const item = pending.pop(); if (!item) break; const [node, key] = item; const restrictions = EXACT_RESTRICTIONS.get(key); if (restrictions) { for (const restriction of restrictions) { if (restriction.attribute === undefined || node.attrs[restriction.attribute] !== undefined) fireOnce(restriction.ruleId, node); } } if (RESTRICTION_PREFIXES.has(key)) { for (let position = node.children.length - 1; position >= 0; position -= 1) { const child = node.children[position]; if (child) pending.push([child, `${key}/${child.q}`]); } } } for (const restriction of DEEP_RESTRICTIONS) { const candidates = index.deep(restriction.path); const attribute = restriction.attribute; const offender = attribute === undefined ? candidates[0] : candidates.find((node) => node.attrs[attribute] !== undefined); if (offender) fireOnce(restriction.ruleId, offender); } // --- Other contexts ------------------------------------------------------------------------- for (const address of [...index.named("cac:PostalAddress"), ...index.named("cac:Address")]) { atMostOne("UBL-SR-51", address, "cac:AddressLine"); } for (const party of all(root, SUPPLIER_PARTY)) check(all(party, "cac:PartyTaxScheme").length <= 2, "UBL-SR-42", party); for (const reference of index.named("cac:AdditionalDocumentReference")) { atMostOne("UBL-SR-33", reference, "cbc:DocumentDescription"); const typeCodes = all(reference, "cbc:DocumentTypeCode").map((code) => stringValue(code)); const noScheme = !all(reference, "cbc:ID").some((id) => id.attrs["schemeID"] !== undefined); check( typeCodes.includes("130") || (isCreditNote && typeCodes.includes("50")) || (noScheme && typeCodes.length === 0), "UBL-SR-43", reference ); } for (const node of index.elements) { if (node.local.endsWith("Amount") && !node.local.endsWith("PriceAmount")) { let insidePriceAllowance = false; for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) { if (ancestor.q === "cac:Price" && has(ancestor, "cac:AllowanceCharge")) insidePriceAllowance = true; } if (!insidePriceAllowance) check(atMostTwoDecimals(node), "UBL-DT-01", node); } if (node.local.endsWith("BinaryObject")) { check(node.attrs["mimeCode"] !== undefined, "UBL-DT-06", node); check(node.attrs["filename"] !== undefined, "UBL-DT-07", node); } } for (const delivery of index.named("cac:Delivery")) { const names = all(delivery, "cac:DeliveryParty/cac:PartyName/cbc:Name").length; // 1.3.16 only caps the count; 1.3.17 also requires a name when a deliver-to party exists. check(current ? !has(delivery, "cac:DeliveryParty") || names === 1 : names <= 1, "UBL-SR-25", delivery); } for (const allowanceCharge of index.named("cac:AllowanceCharge")) { if (isAllowance(allowanceCharge)) atMostOne("UBL-SR-30", allowanceCharge, "cbc:AllowanceChargeReason"); else if (isCharge(allowanceCharge)) atMostOne("UBL-SR-31", allowanceCharge, "cbc:AllowanceChargeReason"); } for (const scheme of index.named("cac:PartyTaxScheme")) { check(has(scheme, "cac:TaxScheme/cbc:ID") && has(scheme, "cbc:CompanyID"), "UBL-SR-53", scheme); } for (const line of [...index.named("cac:InvoiceLine"), ...index.named("cac:CreditNoteLine")]) { atMostOne("UBL-SR-34", line, "cbc:Note"); atMostOne("UBL-SR-35", line, "cac:OrderLineReference/cbc:LineID"); atMostOne("UBL-SR-36", line, "cac:InvoicePeriod"); atMostOne("UBL-SR-37", line, "cac:Price/cac:AllowanceCharge/cbc:Amount"); check(all(line, "cac:Item/cac:ClassifiedTaxCategory").length === 1, "UBL-SR-48", line); atMostOne("UBL-SR-50", line, "cac:Item/cbc:Description"); atMostOne("UBL-SR-52", line, "cac:DocumentReference"); } for (const payee of index.named("cac:PayeeParty")) { const names = all(payee, "cac:PartyName/cbc:Name"); const differs = anyDifferent(names, all(payee.parent, `${SUPPLIER_PARTY}/cac:PartyLegalEntity/cbc:RegistrationName`)); check(names.length <= 1 && differs, "UBL-SR-19", payee); check( all(payee, "cac:PartyIdentification/cbc:ID").filter((id) => (id.attrs["schemeID"] ?? "").toUpperCase() !== "SEPA").length <= 1 && differs, "UBL-SR-20", payee ); check(all(payee, "cac:PartyLegalEntity/cbc:CompanyID").length <= 1 && differs, "UBL-SR-21", payee); } for (const means of index.named("cac:PaymentMeans")) { atMostOne("UBL-SR-26", means, "cbc:PaymentID"); atMostOne("UBL-SR-27", means, "cbc:PaymentMeansCode"); atMostOne("UBL-SR-28", means, "cac:PaymentMandate/cbc:ID"); if (current) { check( !has(means, "cac:PayeeFinancialAccount/cac:FinancialInstitutionBranch") || all(means, "cac:PayeeFinancialAccount/cac:FinancialInstitutionBranch/cbc:ID").length === 1, "UBL-SR-58", means ); } } for (const reference of index.named("cac:BillingReference")) { atMostOne("UBL-SR-06", reference, "cac:InvoiceDocumentReference"); check(has(reference, "cac:InvoiceDocumentReference/cbc:ID"), "UBL-SR-07", reference); } for (const representative of index.named("cac:TaxRepresentativeParty")) { atMostOne("UBL-SR-22", representative, "cac:PartyName/cbc:Name"); atMostOne("UBL-SR-23", representative, "cac:PartyTaxScheme/cbc:CompanyID"); } for (const subtotal of index.named("cac:TaxSubtotal")) { atMostOne("UBL-SR-32", subtotal, "cac:TaxCategory/cbc:TaxExemptionReason"); } }