// SPDX-License-Identifier: EUPL-1.2 // EN 16931 business rules bound to UBL 2.1: families BR, BR-CO, BR-DEC and BR-CL. // Re-implemented from the assertions of the CEN validation artefacts 1.3.17 and 1.3.16 (EUPL-1.2), // patterns "UBL-model" and "Codesmodel". Each check mirrors the XPath test of the assertion // with the same identifier; rule texts are this project's own wording. import { ALLOWANCE_REASON_CODES, ATTACHMENT_MIME_CODES, CHARGE_REASON_CODES, COUNTRY_CODES, CREDIT_NOTE_TYPE_CODES, INVOICE_TYPE_CODES, ITEM_CLASSIFICATION_SCHEMES, OBJECT_IDENTIFIER_SCHEMES, PAYMENT_MEANS_CODES, TAX_CATEGORY_CODES, TAX_POINT_DATE_CODES, RELEASE_CODE_LISTS, VAT_ID_PREFIXES, VAT_ID_PREFIXES_1316, inCodeList } from "./codelists"; import { UNIT_CODES } from "./codelists-units"; import type { Dec } from "./decimal"; import { abs, add, cmp, div100, eq, fromInt, mul, parseIsoDate, round0, round2, sub } from "./decimal"; import { all, dec, decAt, first, has, hasAncestor, normalizeSpace, stringValue, value, valueAt } from "./query"; import type { RuleContext, RuleRow } from "./types"; import { CUSTOMER_PARTY, SUPPLIER_PARTY, anyEqual, atMostTwoDecimals, categoryCode, isAllowance, isCharge, isVat, sumAt } from "./ubl"; import type { XmlNode } from "./xml"; const F = "fatal" as const; const W = "warning" as const; export const EN16931_MODEL_RULES: readonly RuleRow[] = [ ["BR-01", F, "The invoice must have a specification identifier (BT-24, cbc:CustomizationID)."], ["BR-02", F, "The invoice must have an invoice number (BT-1, cbc:ID)."], ["BR-03", F, "The invoice must have an issue date (BT-2, cbc:IssueDate)."], ["BR-04", F, "The invoice must have an invoice type code (BT-3)."], ["BR-05", F, "The invoice must have an invoice currency code (BT-5, cbc:DocumentCurrencyCode)."], ["BR-06", F, "The seller name (BT-27) is required in PartyLegalEntity/RegistrationName."], ["BR-07", F, "The buyer name (BT-44) is required in PartyLegalEntity/RegistrationName."], ["BR-08", F, "The seller postal address (BG-5) is required."], ["BR-09", F, "The seller postal address must contain a country code (BT-40)."], ["BR-10", F, "The buyer postal address (BG-8) is required."], ["BR-11", F, "The buyer postal address must contain a country code (BT-55)."], ["BR-12", F, "The sum of invoice line net amounts (BT-106, LineExtensionAmount) is required."], ["BR-13", F, "The invoice total without VAT (BT-109, TaxExclusiveAmount) is required."], ["BR-14", F, "The invoice total with VAT (BT-112, TaxInclusiveAmount) is required."], ["BR-15", F, "The amount due for payment (BT-115, PayableAmount) is required."], ["BR-16", F, "The invoice must have at least one invoice line (BG-25)."], ["BR-17", F, "The payee (BG-10) needs a name (BT-59) and must differ from the seller by name and identifier."], ["BR-18", F, "The seller tax representative (BG-11) must have a name (BT-62)."], ["BR-19", F, "The seller tax representative must have a postal address (BG-12)."], ["BR-20", F, "The tax representative postal address must contain a country code (BT-69)."], ["BR-21", F, "Each invoice line must have an identifier (BT-126)."], ["BR-22", F, "Each invoice line must have an invoiced quantity (BT-129)."], ["BR-23", F, "Each invoiced quantity must have a unit of measure code (BT-130, unitCode)."], ["BR-24", F, "Each invoice line must have a line net amount (BT-131)."], ["BR-25", F, "Each invoice line must have an item name (BT-153)."], ["BR-26", F, "Each invoice line must have an item net price (BT-146)."], ["BR-27", F, "The item net price (BT-146) must be present and must not be negative."], ["BR-28", F, "The item gross price (BT-148) must not be negative."], ["BR-29", F, "The invoicing period end date (BT-74) must not be earlier than its start date (BT-73)."], ["BR-30", F, "The invoice line period end date (BT-135) must not be earlier than its start date (BT-134)."], ["BR-31", F, "Each document level allowance must have an amount (BT-92)."], ["BR-32", F, "Each document level allowance must have a VAT category code (BT-95)."], ["BR-33", F, "Each document level allowance must have a reason (BT-97) or a reason code (BT-98)."], ["BR-36", F, "Each document level charge must have an amount (BT-99)."], ["BR-37", F, "Each document level charge must have a VAT category code (BT-102)."], ["BR-38", F, "Each document level charge must have a reason (BT-104) or a reason code (BT-105)."], ["BR-41", F, "Each invoice line allowance must have an amount (BT-136)."], ["BR-42", F, "Each invoice line allowance must have a reason (BT-139) or a reason code (BT-140)."], ["BR-43", F, "Each invoice line charge must have an amount (BT-141)."], ["BR-44", F, "Each invoice line charge must have a reason (BT-144) or a reason code (BT-145)."], ["BR-45", F, "Each VAT breakdown must have a taxable amount (BT-116)."], ["BR-46", F, "Each VAT breakdown must have a tax amount (BT-117)."], ["BR-47", F, "Each VAT breakdown must have a VAT category code (BT-118)."], ["BR-48", F, "Each VAT breakdown must have a VAT rate (BT-119), unless the category is O (not subject to VAT)."], ["BR-49", F, "Each payment instruction must have a payment means type code (BT-81)."], ["BR-50", F, "A credit transfer (payment means 30 or 58) must state the payment account identifier (BT-84)."], ["BR-51", W, "Only the last 4 to 6 digits of a card number (BT-87) should be given; the value is longer than 10 characters."], ["BR-52", F, "Each additional supporting document must have a reference (BT-122)."], ["BR-53", F, "When a VAT accounting currency (BT-6) is given, the total VAT amount in that currency (BT-111) is required."], ["BR-54", F, "Each item attribute must have a name (BT-160) and a value (BT-161)."], ["BR-55", F, "Each preceding invoice reference must contain the preceding invoice number (BT-25)."], ["BR-56", F, "The seller tax representative must have a VAT identifier (BT-63)."], ["BR-57", F, "A deliver-to address must contain a country code (BT-80)."], ["BR-61", F, "Payment means 30 or 58 (credit transfer) requires the payment account identifier (BT-84)."], ["BR-62", F, "The seller electronic address (BT-34) must have a scheme identifier (schemeID)."], ["BR-63", F, "The buyer electronic address (BT-49) must have a scheme identifier (schemeID)."], ["BR-64", F, "The item standard identifier (BT-157) must have a scheme identifier (schemeID)."], ["BR-65", F, "The item classification identifier (BT-158) must have a scheme identifier (listID)."], ["BR-CO-03", F, "The VAT point date (BT-7) and the VAT point date code (BT-8) must not both be present."], ["BR-CO-04", F, "Each invoice line must have an item VAT category code (BT-151) under tax scheme VAT."], ["BR-CO-05", F, "Allowance reason code and reason must describe the same allowance (not machine-checked)."], ["BR-CO-06", F, "Charge reason code and reason must describe the same charge (not machine-checked)."], ["BR-CO-07", F, "Line allowance reason code and reason must describe the same allowance (not machine-checked)."], ["BR-CO-08", F, "Line charge reason code and reason must describe the same charge (not machine-checked)."], ["BR-CO-09", F, "A VAT identifier (BT-31, BT-48, BT-63) must start with an ISO 3166-1 alpha-2 country prefix."], ["BR-CO-10", F, "Sum of line net amounts (BT-106) must equal the sum of all invoice line net amounts (BT-131)."], ["BR-CO-11", F, "Sum of allowances (BT-107) must equal the sum of document level allowance amounts (BT-92)."], ["BR-CO-12", F, "Sum of charges (BT-108) must equal the sum of document level charge amounts (BT-99)."], ["BR-CO-13", F, "Total without VAT (BT-109) must equal BT-106 minus allowances (BT-107) plus charges (BT-108)."], ["BR-CO-14", F, "Total VAT amount (BT-110) must equal the sum of the VAT breakdown tax amounts (BT-117)."], ["BR-CO-15", F, "Total with VAT (BT-112) must equal total without VAT (BT-109) plus total VAT (BT-110), with exactly one VAT total in the invoice currency."], ["BR-CO-16", F, "Amount due (BT-115) must equal total with VAT (BT-112) minus paid amount (BT-113) plus rounding (BT-114)."], ["BR-CO-17", F, "VAT breakdown tax amount (BT-117) must equal taxable amount (BT-116) times rate (BT-119) / 100, within 1 currency unit."], ["BR-CO-18", F, "The invoice must have at least one VAT breakdown group (BG-23)."], ["BR-CO-19", F, "An invoicing period (BG-14) must have a start date, an end date, or both."], ["BR-CO-20", F, "An invoice line period (BG-26) must have a start date, an end date, or both."], ["BR-CO-21", F, "Each document level allowance must have a reason (BT-97) or reason code (BT-98)."], ["BR-CO-22", F, "Each document level charge must have a reason (BT-104) or reason code (BT-105)."], ["BR-CO-23", F, "Each invoice line allowance must have a reason (BT-139) or reason code (BT-140)."], ["BR-CO-24", F, "Each invoice line charge must have a reason (BT-144) or reason code (BT-145)."], ["BR-CO-26", F, "The seller must be identifiable by a seller identifier (BT-29), legal registration identifier (BT-30) or VAT identifier (BT-31)."], ["BR-DEC-01", F, "Document level allowance amount (BT-92) allows at most 2 decimals."], ["BR-DEC-02", F, "Document level allowance base amount (BT-93) allows at most 2 decimals."], ["BR-DEC-05", F, "Document level charge amount (BT-99) allows at most 2 decimals."], ["BR-DEC-06", F, "Document level charge base amount (BT-100) allows at most 2 decimals."], ["BR-DEC-09", F, "Sum of line net amounts (BT-106) allows at most 2 decimals."], ["BR-DEC-10", F, "Sum of allowances (BT-107) allows at most 2 decimals."], ["BR-DEC-11", F, "Sum of charges (BT-108) allows at most 2 decimals."], ["BR-DEC-12", F, "Total without VAT (BT-109) allows at most 2 decimals."], ["BR-DEC-13", F, "Total VAT amount (BT-110) allows at most 2 decimals. The published test cannot fail; UBL-DT-01 enforces the limit."], ["BR-DEC-14", F, "Total with VAT (BT-112) allows at most 2 decimals."], ["BR-DEC-15", F, "Total VAT in accounting currency (BT-111) allows at most 2 decimals. The published test cannot fail; UBL-DT-01 enforces the limit."], ["BR-DEC-16", F, "Paid amount (BT-113) allows at most 2 decimals."], ["BR-DEC-17", F, "Rounding amount (BT-114) allows at most 2 decimals."], ["BR-DEC-18", F, "Amount due for payment (BT-115) allows at most 2 decimals."], ["BR-DEC-19", F, "VAT category taxable amount (BT-116) allows at most 2 decimals."], ["BR-DEC-20", F, "VAT category tax amount (BT-117) allows at most 2 decimals."], ["BR-DEC-23", F, "Invoice line net amount (BT-131) allows at most 2 decimals."], ["BR-DEC-24", F, "Invoice line allowance amount (BT-136) allows at most 2 decimals."], ["BR-DEC-25", F, "Invoice line allowance base amount (BT-137) allows at most 2 decimals."], ["BR-DEC-27", F, "Invoice line charge amount (BT-141) allows at most 2 decimals."], ["BR-DEC-28", F, "Invoice line charge base amount (BT-142) allows at most 2 decimals."], ["BR-CL-01", F, "The document type code must be an invoice or credit note code of UNTDID 1001."], ["BR-CL-03", F, "Every currencyID attribute must be an ISO 4217 alpha-3 code."], ["BR-CL-04", F, "The invoice currency code (BT-5) must be an ISO 4217 alpha-3 code."], ["BR-CL-05", F, "The VAT accounting currency code (BT-6) must be an ISO 4217 alpha-3 code."], ["BR-CL-06", F, "The VAT point date code (BT-8) must be 3, 35 or 432 (UNTDID 2005)."], ["BR-CL-07", F, "The invoiced object identifier scheme must be a UNTDID 1153 code."], ["BR-CL-08", F, "A note subject code written as #CODE# (BT-21) must be a UNTDID 4451 code."], ["BR-CL-10", F, "A party identifier scheme must be an ISO 6523 ICD code (SEPA is allowed for seller and payee)."], ["BR-CL-11", F, "A legal registration identifier scheme must be an ISO 6523 ICD code."], ["BR-CL-13", F, "An item classification scheme (listID) must be a UNTDID 7143 code."], ["BR-CL-14", F, "A country code must be an ISO 3166-1 alpha-2 code."], ["BR-CL-15", F, "The item country of origin (BT-159) must be an ISO 3166-1 alpha-2 code."], ["BR-CL-16", F, "The payment means code (BT-81) must be a UNCL 4461 code."], ["BR-CL-17", F, "A VAT category code must be one of AE, L, M, E, S, Z, G, O, K, B (UNCL 5305)."], ["BR-CL-18", F, "An invoiced item VAT category code (BT-151) must be one of AE, L, M, E, S, Z, G, O, K, B."], ["BR-CL-19", F, "An allowance reason code must be in the UNCL 5189 subset."], ["BR-CL-20", F, "A charge reason code must be a UNCL 7161 code."], ["BR-CL-21", F, "An item standard identifier scheme must be an ISO 6523 ICD code."], ["BR-CL-22", F, "A VAT exemption reason code (BT-121) must be a VATEX code."], ["BR-CL-23", F, "A unit code must be a UN/ECE Recommendation 20 or 21 code."], ["BR-CL-24", F, "An attachment MIME code must be PDF, PNG, JPEG, CSV, XLSX or ODS."], ["BR-CL-25", F, "An electronic address scheme (BT-34-1, BT-49-1) must be an EAS code."], ["BR-CL-26", F, "A delivery location identifier scheme must be an ISO 6523 ICD code."] ]; /** `xs:decimal(a) = xs:decimal(b)`: false when either side is missing. */ function decEq(a: Dec | null, b: Dec | null): boolean { return a !== null && b !== null && eq(a, b); } function vatCategories(parent: XmlNode, path: string): XmlNode[] { return all(parent, path).filter(isVat); } function hasReason(allowanceCharge: XmlNode): boolean { return has(allowanceCharge, "cbc:AllowanceChargeReason") || has(allowanceCharge, "cbc:AllowanceChargeReasonCode"); } /** `xs:date(end) >= xs:date(start)` when both are present; true when either is absent. */ function periodOrdered(period: XmlNode): boolean { const start = first(period, "cbc:StartDate"); const end = first(period, "cbc:EndDate"); if (!start || !end) return true; const startDay = parseIsoDate(stringValue(start)); const endDay = parseIsoDate(stringValue(end)); return startDay !== null && endDay !== null && endDay >= startDay; } export function runModelRules(context: RuleContext): void { const { root, index, emit, cen } = context; const lists = RELEASE_CODE_LISTS[cen]; const check = (ok: boolean, id: string, node: XmlNode): void => { if (!ok) emit(id, node); }; const lines = [...index.named("cac:InvoiceLine"), ...index.named("cac:CreditNoteLine")]; // --- Document root ------------------------------------------------------------------- check(valueAt(root, "cbc:CustomizationID") !== "", "BR-01", root); check(valueAt(root, "cbc:ID") !== "", "BR-02", root); check(valueAt(root, "cbc:IssueDate") !== "", "BR-03", root); check(valueAt(root, "cbc:InvoiceTypeCode") !== "" || valueAt(root, "cbc:CreditNoteTypeCode") !== "", "BR-04", root); check(valueAt(root, "cbc:DocumentCurrencyCode") !== "", "BR-05", root); check(valueAt(root, `${SUPPLIER_PARTY}/cac:PartyLegalEntity/cbc:RegistrationName`) !== "", "BR-06", root); check(valueAt(root, `${CUSTOMER_PARTY}/cac:PartyLegalEntity/cbc:RegistrationName`) !== "", "BR-07", root); check(has(root, `${SUPPLIER_PARTY}/cac:PostalAddress`), "BR-08", root); check(has(root, `${CUSTOMER_PARTY}/cac:PostalAddress`), "BR-10", root); check(has(root, "cac:InvoiceLine") || has(root, "cac:CreditNoteLine"), "BR-16", root); const allTaxAmounts = index.deep("cac:TaxTotal/cbc:TaxAmount"); for (const taxCurrency of all(root, "cbc:TaxCurrencyCode")) { const code = stringValue(taxCurrency); check( allTaxAmounts.some((amount) => amount.attrs["currencyID"] === code), "BR-53", root ); } check(!(has(root, "cbc:TaxPointDate") && has(root, "cac:InvoicePeriod/cbc:DescriptionCode")), "BR-CO-03", root); const monetaryTotal = first(root, "cac:LegalMonetaryTotal"); for (const currency of all(root, "cbc:DocumentCurrencyCode")) { const code = stringValue(currency); const matching = all(root, "cac:TaxTotal/cbc:TaxAmount").filter((amount) => amount.attrs["currencyID"] === code); const exclusive = decAt(monetaryTotal, "cbc:TaxExclusiveAmount"); const inclusive = decAt(monetaryTotal, "cbc:TaxInclusiveAmount"); const vatTotal = dec(matching[0]); const totalsAgree = exclusive !== null && inclusive !== null && vatTotal !== null && eq(inclusive, round2(add(exclusive, vatTotal))); check(matching.length === 1 && totalsAgree, "BR-CO-15", root); } check(has(root, "cac:TaxTotal/cac:TaxSubtotal"), "BR-CO-18", root); // BR-DEC-13 and BR-DEC-15: the published predicates compare @currencyID with a child of // cbc:TaxAmount that cannot exist, so the assertions always hold. Nothing to evaluate. // BR-CO-05 to BR-CO-08 are published as `true()`. for (const note of all(root, "cbc:Note")) { const text = stringValue(note); const afterHash = text.indexOf("#") === -1 ? "" : text.slice(text.indexOf("#") + 1); const code = afterHash.indexOf("#") === -1 ? "" : afterHash.slice(0, afterHash.indexOf("#")); const hasHash = text.includes("#"); check(!hasHash || [...code].length !== 3 || lists.noteSubjects.includes(code), "BR-CL-08", note); } // --- Monetary totals ------------------------------------------------------------------ for (const total of index.named("cac:LegalMonetaryTotal")) { const owner = total.parent ?? root; const lineExtension = decAt(total, "cbc:LineExtensionAmount"); const allowanceTotal = decAt(total, "cbc:AllowanceTotalAmount"); const chargeTotal = decAt(total, "cbc:ChargeTotalAmount"); const taxExclusive = decAt(total, "cbc:TaxExclusiveAmount"); const taxInclusive = decAt(total, "cbc:TaxInclusiveAmount"); const prepaid = decAt(total, "cbc:PrepaidAmount"); const rounding = decAt(total, "cbc:PayableRoundingAmount"); const payable = decAt(total, "cbc:PayableAmount"); const hasAllowanceTotal = has(total, "cbc:AllowanceTotalAmount"); const hasChargeTotal = has(total, "cbc:ChargeTotalAmount"); const hasPrepaid = has(total, "cbc:PrepaidAmount"); const hasRounding = has(total, "cbc:PayableRoundingAmount"); const documentAllowances = all(owner, "cac:AllowanceCharge").filter(isAllowance); const documentCharges = all(owner, "cac:AllowanceCharge").filter(isCharge); check(has(total, "cbc:LineExtensionAmount"), "BR-12", total); check(has(total, "cbc:TaxExclusiveAmount"), "BR-13", total); check(has(total, "cbc:TaxInclusiveAmount"), "BR-14", total); check(has(total, "cbc:PayableAmount"), "BR-15", total); check(decEq(lineExtension, round2(sumAt(lines, "cbc:LineExtensionAmount"))), "BR-CO-10", total); check( decEq(allowanceTotal, round2(sumAt(documentAllowances, "cbc:Amount"))) || (!hasAllowanceTotal && documentAllowances.length === 0), "BR-CO-11", total ); check( decEq(chargeTotal, round2(sumAt(documentCharges, "cbc:Amount"))) || (!hasChargeTotal && documentCharges.length === 0), "BR-CO-12", total ); let expectedExclusive: Dec | null = null; if (lineExtension !== null) { if (hasChargeTotal && hasAllowanceTotal) { expectedExclusive = chargeTotal !== null && allowanceTotal !== null ? round2(sub(add(lineExtension, chargeTotal), allowanceTotal)) : null; } else if (!hasChargeTotal && hasAllowanceTotal) { expectedExclusive = allowanceTotal !== null ? round2(sub(lineExtension, allowanceTotal)) : null; } else if (hasChargeTotal && !hasAllowanceTotal) { expectedExclusive = chargeTotal !== null ? round2(add(lineExtension, chargeTotal)) : null; } else { expectedExclusive = lineExtension; } } check(decEq(taxExclusive, expectedExclusive), "BR-CO-13", total); let payableAgrees = false; if (payable !== null && taxInclusive !== null) { if (hasPrepaid && !hasRounding) { payableAgrees = prepaid !== null && eq(payable, round2(sub(taxInclusive, prepaid))); } else if (!hasPrepaid && !hasRounding) { payableAgrees = eq(payable, taxInclusive); } else if (hasPrepaid && hasRounding) { payableAgrees = prepaid !== null && rounding !== null && eq(round2(sub(payable, rounding)), round2(sub(taxInclusive, prepaid))); } else { payableAgrees = rounding !== null && eq(round2(sub(payable, rounding)), taxInclusive); } } check(payableAgrees, "BR-CO-16", total); check(atMostTwoDecimals(first(total, "cbc:LineExtensionAmount")), "BR-DEC-09", total); check(atMostTwoDecimals(first(total, "cbc:AllowanceTotalAmount")), "BR-DEC-10", total); check(atMostTwoDecimals(first(total, "cbc:ChargeTotalAmount")), "BR-DEC-11", total); check(atMostTwoDecimals(first(total, "cbc:TaxExclusiveAmount")), "BR-DEC-12", total); check(atMostTwoDecimals(first(total, "cbc:TaxInclusiveAmount")), "BR-DEC-14", total); check(atMostTwoDecimals(first(total, "cbc:PrepaidAmount")), "BR-DEC-16", total); check(atMostTwoDecimals(first(total, "cbc:PayableRoundingAmount")), "BR-DEC-17", total); check(atMostTwoDecimals(first(total, "cbc:PayableAmount")), "BR-DEC-18", total); } // --- Document level allowances and charges --------------------------------------------- for (const allowanceCharge of all(root, "cac:AllowanceCharge")) { const allowance = isAllowance(allowanceCharge); if (!allowance && !isCharge(allowanceCharge)) continue; const ids = allowance ? (["BR-31", "BR-32", "BR-33", "BR-CO-21", "BR-DEC-01", "BR-DEC-02"] as const) : (["BR-36", "BR-37", "BR-38", "BR-CO-22", "BR-DEC-05", "BR-DEC-06"] as const); check(has(allowanceCharge, "cbc:Amount"), ids[0], allowanceCharge); check( vatCategories(allowanceCharge, "cac:TaxCategory").some((category) => has(category, "cbc:ID")), ids[1], allowanceCharge ); check(hasReason(allowanceCharge), ids[2], allowanceCharge); check(hasReason(allowanceCharge), ids[3], allowanceCharge); check(atMostTwoDecimals(first(allowanceCharge, "cbc:Amount")), ids[4], allowanceCharge); check(atMostTwoDecimals(first(allowanceCharge, "cbc:BaseAmount")), ids[5], allowanceCharge); } // --- Invoice lines --------------------------------------------------------------------- for (const line of lines) { check(valueAt(line, "cbc:ID") !== "", "BR-21", line); const quantities = [...all(line, "cbc:InvoicedQuantity"), ...all(line, "cbc:CreditedQuantity")]; check(quantities.length > 0, "BR-22", line); check( quantities.some((quantity) => quantity.attrs["unitCode"] !== undefined), "BR-23", line ); check(has(line, "cbc:LineExtensionAmount"), "BR-24", line); check(valueAt(line, "cac:Item/cbc:Name") !== "", "BR-25", line); const prices = all(line, "cac:Price/cbc:PriceAmount"); check(prices.length > 0, "BR-26", line); check( prices.some((price) => { const parsed = dec(price); return parsed !== null && parsed.n >= 0n; }), "BR-27", line ); const grossPrices = all(line, "cac:Price/cac:AllowanceCharge/cbc:BaseAmount"); check( grossPrices.length === 0 || grossPrices.some((price) => { const parsed = dec(price); return parsed !== null && parsed.n >= 0n; }), "BR-28", line ); check( vatCategories(line, "cac:Item/cac:ClassifiedTaxCategory").some((category) => has(category, "cbc:ID")), "BR-CO-04", line ); check(atMostTwoDecimals(first(line, "cbc:LineExtensionAmount")), "BR-DEC-23", line); for (const allowanceCharge of all(line, "cac:AllowanceCharge")) { const allowance = isAllowance(allowanceCharge); if (!allowance && !isCharge(allowanceCharge)) continue; const ids = allowance ? (["BR-41", "BR-42", "BR-CO-23", "BR-DEC-24", "BR-DEC-25"] as const) : (["BR-43", "BR-44", "BR-CO-24", "BR-DEC-27", "BR-DEC-28"] as const); check(has(allowanceCharge, "cbc:Amount"), ids[0], allowanceCharge); check(hasReason(allowanceCharge), ids[1], allowanceCharge); check(hasReason(allowanceCharge), ids[2], allowanceCharge); check(atMostTwoDecimals(first(allowanceCharge, "cbc:Amount")), ids[3], allowanceCharge); check(atMostTwoDecimals(first(allowanceCharge, "cbc:BaseAmount")), ids[4], allowanceCharge); } for (const code of all(line, "cac:Item/cac:CommodityClassification/cbc:ItemClassificationCode")) { check(code.attrs["listID"] !== undefined, "BR-65", code); } for (const identifier of all(line, "cac:Item/cac:StandardItemIdentification/cbc:ID")) { check(identifier.attrs["schemeID"] !== undefined, "BR-64", identifier); } } // Line periods match the earlier rule of the pattern; every other period the later one. for (const period of index.named("cac:InvoicePeriod")) { const parentName = period.parent?.q; const hasStart = has(period, "cbc:StartDate"); const hasEnd = has(period, "cbc:EndDate"); if (parentName === "cac:InvoiceLine" || parentName === "cac:CreditNoteLine") { check(periodOrdered(period), "BR-30", period); check(hasStart || hasEnd, "BR-CO-20", period); } else { check(periodOrdered(period), "BR-29", period); check(hasStart || hasEnd || has(period, "cbc:DescriptionCode"), "BR-CO-19", period); } } for (const property of index.named("cac:AdditionalItemProperty")) { check(has(property, "cbc:Name") && has(property, "cbc:Value"), "BR-54", property); } // --- Parties --------------------------------------------------------------------------- for (const supplier of index.named("cac:AccountingSupplierParty")) { check( vatCategories(supplier, "cac:Party/cac:PartyTaxScheme").some((scheme) => has(scheme, "cbc:CompanyID")) || all(supplier, "cac:Party/cac:PartyIdentification/cbc:ID").some((id) => id.attrs["schemeID"] !== "SEPA") || has(supplier, "cac:Party/cac:PartyLegalEntity/cbc:CompanyID"), "BR-CO-26", supplier ); for (const endpoint of all(supplier, "cac:Party/cbc:EndpointID")) check(endpoint.attrs["schemeID"] !== undefined, "BR-62", endpoint); for (const address of all(supplier, "cac:Party/cac:PostalAddress")) { check(valueAt(address, "cac:Country/cbc:IdentificationCode") !== "", "BR-09", address); } } for (const customer of index.named("cac:AccountingCustomerParty")) { for (const endpoint of all(customer, "cac:Party/cbc:EndpointID")) check(endpoint.attrs["schemeID"] !== undefined, "BR-63", endpoint); for (const address of all(customer, "cac:Party/cac:PostalAddress")) { check(valueAt(address, "cac:Country/cbc:IdentificationCode") !== "", "BR-11", address); } } for (const payee of index.named("cac:PayeeParty")) { const owner = payee.parent; const names = all(payee, "cac:PartyName/cbc:Name"); check( names.length > 0 && !anyEqual(names, all(owner, `${SUPPLIER_PARTY}/cac:PartyName/cbc:Name`)) && !anyEqual(all(payee, "cac:PartyIdentification/cbc:ID"), all(owner, `${SUPPLIER_PARTY}/cac:PartyIdentification/cbc:ID`)), "BR-17", payee ); } for (const representative of index.named("cac:TaxRepresentativeParty")) { check(valueAt(representative, "cac:PartyName/cbc:Name") !== "", "BR-18", representative); check(has(representative, "cac:PostalAddress"), "BR-19", representative); check( vatCategories(representative, "cac:PartyTaxScheme").some((scheme) => has(scheme, "cbc:CompanyID")), "BR-56", representative ); for (const address of all(representative, "cac:PostalAddress")) { check(valueAt(address, "cac:Country/cbc:IdentificationCode") !== "", "BR-20", address); } } for (const scheme of index.named("cac:PartyTaxScheme")) { if (!isVat(scheme)) continue; const prefix = [...stringValue(first(scheme, "cbc:CompanyID"))].slice(0, 2).join(""); // 1.3.16 tests contains(LIST, prefix) without delimiters, so an empty or one-character // prefix passes there; 1.3.17 wraps the prefix in spaces. check(cen === "1.3.16" ? VAT_ID_PREFIXES_1316.includes(prefix) : VAT_ID_PREFIXES.includes(` ${prefix} `), "BR-CO-09", scheme); } // --- References, delivery, payment ------------------------------------------------------ for (const reference of index.named("cac:AdditionalDocumentReference")) { check(valueAt(reference, "cbc:ID") !== "", "BR-52", reference); } for (const reference of index.named("cac:BillingReference")) { check(has(reference, "cac:InvoiceDocumentReference/cbc:ID"), "BR-55", reference); } for (const address of index.deep("cac:Delivery/cac:DeliveryLocation/cac:Address")) { check(has(address, "cac:Country/cbc:IdentificationCode"), "BR-57", address); } for (const means of index.named("cac:PaymentMeans")) { const codes = all(means, "cbc:PaymentMeansCode"); const code = value(codes[0]); const creditTransfer = code === "30" || code === "58"; check(codes.length > 0, "BR-49", means); check((has(means, "cac:PayeeFinancialAccount/cbc:ID") && creditTransfer) || !creditTransfer, "BR-61", means); if (codes.some((node) => stringValue(node) === "30" || stringValue(node) === "58")) { for (const account of all(means, "cac:PayeeFinancialAccount")) check(valueAt(account, "cbc:ID") !== "", "BR-50", account); } for (const pan of all(means, "cac:CardAccount/cbc:PrimaryAccountNumberID")) check(value(pan).length <= 10, "BR-51", pan); } // --- VAT totals ------------------------------------------------------------------------- for (const taxTotal of all(root, "cac:TaxTotal")) { const subtotals = all(taxTotal, "cac:TaxSubtotal"); check( subtotals.length === 0 || decEq(decAt(taxTotal, "cbc:TaxAmount"), round2(sumAt(subtotals, "cbc:TaxAmount"))), "BR-CO-14", taxTotal ); } for (const subtotal of index.deep("cac:TaxTotal/cac:TaxSubtotal")) { const categories = vatCategories(subtotal, "cac:TaxCategory"); check(has(subtotal, "cbc:TaxableAmount"), "BR-45", subtotal); check(has(subtotal, "cbc:TaxAmount"), "BR-46", subtotal); check( categories.some((category) => has(category, "cbc:ID")), "BR-47", subtotal ); check( categories.some((category) => has(category, "cbc:Percent")) || categories.some((category) => categoryCode(category) === "O"), "BR-48", subtotal ); const taxAmount = decAt(subtotal, "cbc:TaxAmount"); const taxable = decAt(subtotal, "cbc:TaxableAmount"); const percentNode = categories.flatMap((category) => all(category, "cbc:Percent"))[0]; const percent = dec(percentNode); let rateAgrees: boolean; if (percentNode === undefined) { rateAgrees = taxAmount !== null && round0(taxAmount).n === 0n; } else if (percent === null || taxAmount === null) { rateAgrees = false; } else if (round0(percent).n === 0n) { rateAgrees = round0(taxAmount).n === 0n; } else if (taxable === null) { rateAgrees = false; } else { const expected = round2(mul(abs(taxable), div100(percent))); const magnitude = abs(taxAmount); rateAgrees = cmp(sub(magnitude, fromInt(1)), expected) < 0 && cmp(add(magnitude, fromInt(1)), expected) > 0; } check(rateAgrees, "BR-CO-17", subtotal); check(atMostTwoDecimals(first(subtotal, "cbc:TaxableAmount")), "BR-DEC-19", subtotal); check(atMostTwoDecimals(first(subtotal, "cbc:TaxAmount")), "BR-DEC-20", subtotal); } runCodeListRules(context); } const CURRENCY_BEARING = [ "cbc:Amount", "cbc:BaseAmount", "cbc:PriceAmount", "cbc:TaxAmount", "cbc:TaxableAmount", "cbc:LineExtensionAmount", "cbc:TaxExclusiveAmount", "cbc:TaxInclusiveAmount", "cbc:AllowanceTotalAmount", "cbc:ChargeTotalAmount", "cbc:PrepaidAmount", "cbc:PayableRoundingAmount", "cbc:PayableAmount" ] as const; function runCodeListRules(context: RuleContext): void { const { index, emit } = context; const lists = RELEASE_CODE_LISTS[context.cen]; const check = (ok: boolean, id: string, node: XmlNode): void => { if (!ok) emit(id, node); }; const attribute = (node: XmlNode, name: string): string => normalizeSpace(node.attrs[name] ?? ""); const childOf = (node: XmlNode, parentName: string): boolean => node.parent?.q === parentName; for (const code of index.named("cbc:InvoiceTypeCode")) check(inCodeList(INVOICE_TYPE_CODES, value(code)), "BR-CL-01", code); for (const code of index.named("cbc:CreditNoteTypeCode")) check(inCodeList(CREDIT_NOTE_TYPE_CODES, value(code)), "BR-CL-01", code); for (const name of CURRENCY_BEARING) { for (const amount of index.named(name)) check(inCodeList(lists.currencies, attribute(amount, "currencyID")), "BR-CL-03", amount); } for (const code of index.named("cbc:DocumentCurrencyCode")) check(inCodeList(lists.currencies, value(code)), "BR-CL-04", code); for (const code of index.named("cbc:TaxCurrencyCode")) check(inCodeList(lists.currencies, value(code)), "BR-CL-05", code); for (const code of index.deep("cac:InvoicePeriod/cbc:DescriptionCode")) check(inCodeList(TAX_POINT_DATE_CODES, value(code)), "BR-CL-06", code); for (const reference of [...index.named("cac:AdditionalDocumentReference"), ...index.named("cac:DocumentReference")]) { if (!all(reference, "cbc:DocumentTypeCode").some((code) => stringValue(code) === "130")) continue; for (const id of all(reference, "cbc:ID")) { if (id.attrs["schemeID"] !== undefined) check(inCodeList(OBJECT_IDENTIFIER_SCHEMES, attribute(id, "schemeID")), "BR-CL-07", id); } } for (const id of index.deep("cac:PartyIdentification/cbc:ID")) { if (id.attrs["schemeID"] === undefined) continue; const scheme = attribute(id, "schemeID"); const sepaAllowed = scheme === "SEPA" && (hasAncestor(id, "cac:AccountingSupplierParty") || hasAncestor(id, "cac:PayeeParty")); check(inCodeList(lists.icd, scheme) || sepaAllowed, "BR-CL-10", id); } for (const id of index.deep("cac:PartyLegalEntity/cbc:CompanyID")) { if (id.attrs["schemeID"] !== undefined) check(inCodeList(lists.icd, attribute(id, "schemeID")), "BR-CL-11", id); } for (const code of index.deep("cac:CommodityClassification/cbc:ItemClassificationCode")) { if (code.attrs["listID"] !== undefined) check(inCodeList(ITEM_CLASSIFICATION_SCHEMES, attribute(code, "listID")), "BR-CL-13", code); } for (const code of index.named("cbc:IdentificationCode")) { if (childOf(code, "cac:Country")) check(inCodeList(COUNTRY_CODES, value(code)), "BR-CL-14", code); else if (childOf(code, "cac:OriginCountry")) check(inCodeList(COUNTRY_CODES, value(code)), "BR-CL-15", code); } for (const code of index.deep("cac:PaymentMeans/cbc:PaymentMeansCode")) check(inCodeList(PAYMENT_MEANS_CODES, value(code)), "BR-CL-16", code); for (const id of index.deep("cac:TaxCategory/cbc:ID")) check(inCodeList(TAX_CATEGORY_CODES, value(id)), "BR-CL-17", id); for (const id of index.deep("cac:ClassifiedTaxCategory/cbc:ID")) check(inCodeList(TAX_CATEGORY_CODES, value(id)), "BR-CL-18", id); for (const allowanceCharge of index.named("cac:AllowanceCharge")) { const allowance = isAllowance(allowanceCharge); if (!allowance && !isCharge(allowanceCharge)) continue; for (const code of all(allowanceCharge, "cbc:AllowanceChargeReasonCode")) { if (allowance) check(inCodeList(ALLOWANCE_REASON_CODES, value(code)), "BR-CL-19", code); else check(inCodeList(CHARGE_REASON_CODES, value(code)), "BR-CL-20", code); } } for (const id of index.deep("cac:StandardItemIdentification/cbc:ID")) { if (id.attrs["schemeID"] !== undefined) check(inCodeList(lists.icd, attribute(id, "schemeID")), "BR-CL-21", id); } for (const code of index.named("cbc:TaxExemptionReasonCode")) { const text = value(code); check(!text.includes(" ") && inCodeList(lists.vatex, text.toUpperCase()), "BR-CL-22", code); } for (const name of ["cbc:InvoicedQuantity", "cbc:BaseQuantity", "cbc:CreditedQuantity"] as const) { for (const quantity of index.named(name)) { if (quantity.attrs["unitCode"] !== undefined) check(inCodeList(UNIT_CODES, attribute(quantity, "unitCode")), "BR-CL-23", quantity); } } for (const attachment of index.named("cbc:EmbeddedDocumentBinaryObject")) { const mime = attachment.attrs["mimeCode"]; if (mime !== undefined) check(ATTACHMENT_MIME_CODES.includes(mime), "BR-CL-24", attachment); } for (const endpoint of index.named("cbc:EndpointID")) { if (endpoint.attrs["schemeID"] !== undefined) check(inCodeList(lists.eas, attribute(endpoint, "schemeID")), "BR-CL-25", endpoint); } for (const id of index.deep("cac:DeliveryLocation/cbc:ID")) { if (id.attrs["schemeID"] !== undefined) check(inCodeList(lists.icd, attribute(id, "schemeID")), "BR-CL-26", id); } }