Shipmind Labs

Renumbering a validation error into the XPath a receiver quotes

· 9 min read

A validator that reports failures by model field gives whoever fixes a rejection a second job. They have to translate a location like lines[2].charges[1].amount into the XPath the receiving platform will quote back at them. That translation is not a rename. XPath counts from one, and the document merges discounts and surcharges into a single list where the model keeps two, so the second surcharge on a line is not the second element of anything.

We ran into this building invoicerules, a library of ours that checks an invoice against the EN 16931 business rules before a tax platform does. Under a clearance model an invoice that fails validation was never issued, so the useful output of a check is not a boolean but a place, and a place is only useful if it is the same place the other end names. Our own README puts it as a failure is a place, not a boolean: every rule outcome carries both at, the model field it looked at, and path, the element that field has in the document that gets sent.

typescript
validate(invoice).coverage.find((c) => c.rule === "BR-CO-16");
// { rule: "BR-CO-16", outcome: "fail",
//   at: "totals.payable", path: "/Invoice/LegalMonetaryTotal/PayableAmount",
//   message: "the amount due 330.00 does not match the total with VAT 300.00" }

For a fixed field that is a lookup in a table. For anything inside a list it turns into arithmetic, and the arithmetic depends on the invoice.

Two lists in the model, one run of elements in the document#

The model keeps allowances and charges apart, because to a caller they are different things and both amounts are stated positively. Which list an item sits in decides whether it comes off or goes on.

typescript
export type Line = {
  /** BT-126: line identifier, unique within the invoice. */
  readonly id: string;
  /** BT-131: line net amount, quantity × price less the line's allowances and plus its charges. */
  readonly netAmount: Amount;
  /** BG-27: line level allowances. */
  readonly allowances?: readonly LineAllowanceCharge[];
  /** BG-28: line level charges. */
  readonly charges?: readonly LineAllowanceCharge[];
};

UBL has no such split. It has one element for both, plus a boolean that says which it is:

typescript
function allowanceCharge(
  item: AllowanceCharge | LineAllowanceCharge,
  isCharge: boolean,
  currency: string,
  indent: string,
): string {
  const parts = [
    `${indent}<cac:AllowanceCharge>`,
    `${indent}  <cbc:ChargeIndicator>${isCharge}</cbc:ChargeIndicator>`,
  ];
  // ...

toUBL writes them as one run of AllowanceCharge elements, allowances first and charges after, at document level and again inside each line. So on a line that carries two allowances, the first charge is not AllowanceCharge[1]. It is AllowanceCharge[3]. Nothing in the model location lines[2].charges[0] knows that, and that is the whole problem: the offset is a property of the invoice, not of the location string.

A path needs to know what came before it#

So the path builder takes the counts as an argument. src/paths.ts names exactly what it needs and nothing else:

typescript
/** What is needed to count two model lists into the one list UBL writes. */
export type PathContext = {
  /** How many document level allowances precede the document level charges. */
  readonly allowances?: number;
  /** How many allowances each line carries, in line order. */
  readonly lineAllowances?: readonly number[];
  /** Which document the paths point into. */
  readonly creditNote?: boolean;
};

validate in src/rules.ts builds it once, up front, from the invoice it was handed:

typescript
const context = {
  allowances: invoice.allowances?.length ?? 0,
  lineAllowances: invoice.lines.map((line) => line.allowances?.length ?? 0),
  creditNote,
};

and then every outcome in the run goes through one recorder, so there is no second route by which a rule could report a place:

typescript
const record = (rule: string, outcome: Outcome, message: string, at?: string): void => {
  coverage.push({
    rule,
    outcome,
    at,
    path: ublPath(at, context),
    message: outcome === "pass" ? undefined : message,
  });
};

The rules themselves never mention XPath. They state a model location, "totals.payable", "seller.identification.vatId", `lines[${index}].vatCategory`, and the translation happens in one function that has the counts. Two invoices with the same failure in the same model location legitimately produce different paths, and that is why we pass data instead of hardcoding a table.

The renumbering, in the one place that does it#

Line level locations are caught by a pattern before any table lookup, because they are the case where counting happens:

typescript
const WITHIN_LINE = /^lines\[(\d+)\]\.(allowances|charges)\[(\d+)\](?:\.([a-zA-Z]+))?$/;
typescript
const withinLine = WITHIN_LINE.exec(at);
if (withinLine) {
  const [, lineIndex, list, index, field] = withinLine;
  const before = list === "charges" ? lineAllowances[Number(lineIndex)] ?? 0 : 0;
  const base = `${root}/${syntax.line}[${Number(lineIndex) + 1}]/AllowanceCharge[${Number(index) + 1 + before}]`;
  return element(base, LINE_ADJUSTMENT_FIELDS, field);
}

Three separate conversions sit in that expression. They are worth naming separately, because each one is a different mistake if you skip it. Number(lineIndex) + 1 turns a zero-based model index into the one-based position XPath uses, the same conversion that makes lines[2].netPrice come out as /Invoice/InvoiceLine[3]/Price/PriceAmount. Number(index) + 1 does it again for the adjustment's own position. And before adds the preceding allowances, but only when the list is charges: an allowance does not get displaced, because allowances are written first. The ternary could have been written as an unconditional lookup with a subtraction somewhere else. Keeping it as a conditional makes the asymmetry visible, and the asymmetry belongs to the document.

Document level adjustments are the same shape one level up: a location under charges resolves to the AllowanceCharge at its position plus allowances. The fixed table is honest about why that is necessary, since both model lists point at the same element name:

typescript
      allowances: `${root}/AllowanceCharge`,
      charges: `${root}/AllowanceCharge`,

A location with no element of its own gets no path#

The field suffix is looked up in a table too, and there are two of them. A document level allowance belongs to a VAT breakdown group, so it carries a category and a rate. A line level one does not: the line states the category once, in its Item.

typescript
/** A line level allowance has no tax category of its own; the line carries it. */
const LINE_ADJUSTMENT_FIELDS: Record<string, string> = {
  amount: "/Amount",
  baseAmount: "/BaseAmount",
  percentage: "/MultiplierFactorNumeric",
  reason: "/AllowanceChargeReason",
  reasonCode: "/AllowanceChargeReasonCode",
};

ADJUSTMENT_FIELDS has vatCategory and vatRate entries. This one has neither, and the omission mirrors the model type, which has no such field either. The writer agrees from the other side: allowanceCharge emits a TaxCategory block only if ("vatCategory" in item).

So the table is also a refusal. ublPath returns undefined for an empty location, and for one that fits no table and no pattern. It does not fall back to the nearest ancestor, and it does not assemble something plausible out of the segments it recognises. A guessed path is worse than no path, because a plausible-looking XPath that does not exist in the document sends the person fixing the invoice looking for an element that was never written. The caller gets both fields and decides:

typescript
for (const v of result.fatal) console.error(`${v.rule} at ${v.path ?? v.at}: ${v.message}`);

This is the same discipline the coverage report already follows for outcomes. A rule with nothing to check (there is no seller VAT identifier whose prefix could be tested) is absent from the report rather than counted as a pass. Silence where there is nothing to say, in both the outcome and the place.

The tables carry one more detail of the same kind. PAYMENT_MEANS_FIELDS maps name to /PaymentMeansCode/@name, an attribute rather than an element, because that is how a receiver quotes it. We are not after a tidy path, we are after the string the other end will use.

Both document types from the same set of locations#

The third field in the context is creditNote, which selects CREDIT_NOTE_TABLES over INVOICE_TABLES. Both are built by the same tables(syntax) function from a syntax descriptor that supplies the root element, the line element and the quantity element, so the root and line names in every path, including the renumbered AllowanceCharge positions above, come out right for whichever document is being written.

typescript
const INVOICE_TABLES = tables(INVOICE_SYNTAX);
const CREDIT_NOTE_TABLES = tables(CREDIT_NOTE_SYNTAX);

No rule branches on document type to report a place. A rule that checks a line net amount says lines[0].netAmount and gets the correct element in either document. The one flag computed from isCreditNote(invoice) at the top of validate carries it.

What it costs to run#

The context is rebuilt on every validate call and is linear in the number of lines, which is nothing next to the rules themselves. The real cost is a convention the rules have to keep: a rule must report a location string that either appears in a table or matches a pattern, and a model field added later needs a table entry or its outcomes come back with path: undefined, quietly incomplete rather than wrong. We pin that with golden fixtures. Each scenario has an expected outcomes file next to its expected XML, so an outcome that loses its path, or points one element off, shows up as a diff rather than as a support conversation.

The payoff is narrow and we think it is worth it. When a platform refuses a document and quotes an element, the refusal and our own report name the same string, in the same counting scheme, for the same document type. Nobody has to hold the allowance-before-charge merge in their head at the moment they are least able to, the moment an invoice has already been rejected.

Was this useful?

Building something similar?

or email hello@shipmindlabs.com