// SPDX-License-Identifier: EUPL-1.2 // Shared UBL predicates used by several rule sets. import type { Dec } from "./decimal"; import { parseDec, sum } from "./decimal"; import { all, stringValue, value } from "./query"; import type { XmlNode } from "./xml"; export const LINE = "cac:InvoiceLine|cac:CreditNoteLine"; export const SUPPLIER_PARTY = "cac:AccountingSupplierParty/cac:Party"; export const CUSTOMER_PARTY = "cac:AccountingCustomerParty/cac:Party"; /** `cac:TaxScheme/normalize-space(upper-case(cbc:ID)) = 'VAT'` on a tax category or party tax scheme. */ export function isVat(node: XmlNode): boolean { return all(node, "cac:TaxScheme").some((scheme) => value(all(scheme, "cbc:ID")[0]).toUpperCase() === "VAT"); } /** * xs:boolean value of cbc:ChargeIndicator, as in `cbc:ChargeIndicator = false()`. * Returns null when the element is absent or not a valid boolean. */ export function chargeFlag(allowanceCharge: XmlNode): boolean | null { const node = all(allowanceCharge, "cbc:ChargeIndicator")[0]; if (!node) return null; const text = stringValue(node).trim(); if (text === "true" || text === "1") return true; if (text === "false" || text === "0") return false; return null; } export const isAllowance = (node: XmlNode): boolean => chargeFlag(node) === false; export const isCharge = (node: XmlNode): boolean => chargeFlag(node) === true; /** VAT category code of a tax category: `normalize-space(cbc:ID)`. */ export function categoryCode(category: XmlNode): string { return value(all(category, "cbc:ID")[0]); } /** Sum of the decimals found at `path` below each node; missing or invalid values add nothing. */ export function sumAt(nodes: readonly XmlNode[], path: string): Dec { const values: Dec[] = []; for (const node of nodes) { for (const target of all(node, path)) { const parsed = parseDec(stringValue(target)); if (parsed) values.push(parsed); } } return sum(values); } /** True when the lexical value has at most two digits after the decimal point. */ export function atMostTwoDecimals(node: XmlNode | undefined): boolean { if (!node) return true; const text = stringValue(node); const dot = text.indexOf("."); return dot === -1 || text.length - dot - 1 <= 2; } /** XPath general comparison `a = b` over two node sequences, comparing raw string values. */ export function anyEqual(left: readonly XmlNode[], right: readonly XmlNode[]): boolean { if (left.length === 0 || right.length === 0) return false; const values = new Set(right.map((node) => stringValue(node))); return left.some((node) => values.has(stringValue(node))); } /** XPath general comparison `a != b`: true when some pair of values differs. */ export function anyDifferent(left: readonly XmlNode[], right: readonly XmlNode[]): boolean { for (const a of left) { const text = stringValue(a); for (const b of right) if (stringValue(b) !== text) return true; } return false; }