Three-way match compares a purchase order, what was actually received and the supplier invoice before the bill is paid. The useful output is not "mismatch: yes" but why, in amounts a supplier can answer.

The decomposition

For one line:

  • invoiced = invQty × invPrice
  • accepted = receivedQty × poPrice (what you agreed to pay for what arrived)
  • quantity variance = (invQty − receivedQty) × invPrice
  • price variance = (invPrice − poPrice) × receivedQty

and invoiced − accepted = quantity variance + price variance, exactly. That identity is the whole test suite.

function matchLine({ poQty, poPriceCents, receivedQty, invQty, invPriceCents }) { const rcv = BigInt(receivedQty), iq = BigInt(invQty); const pp = BigInt(poPriceCents), ip = BigInt(invPriceCents); const invoiced = iq * ip; const accepted = rcv * pp; const qtyVariance = (iq - rcv) * ip; const priceVariance = (ip - pp) * rcv; const query = invoiced - accepted; if (query !== qtyVariance + priceVariance) throw new Error('decomposition broken'); return { invoiced, accepted, qtyVariance, priceVariance, query, overReceived: rcv > BigInt(poQty) }; } 

Example

Ordered 120 at $4.10, received 112, invoiced 120 at $4.25:

  • invoiced $510.00, accepted $459.20, difference $50.80
  • quantity: 8 × $4.25 = $34.00 (billed, not received)
  • price: 112 × $0.15 = $16.80 (price change on what arrived)

Two questions for the supplier instead of one vague "your invoice is wrong".

Why BigInt

All amounts are integer cents, so the identity holds exactly. With floats, 120 * 4.25 - 112 * 4.10 is 50.80000000000007, and an equality check on the decomposition starts failing at random. With BigInt there is nothing to round and nothing to tolerate.

Property test

for (let i = 0; i < 100000; i++) { const q = 1 + Math.floor(Math.random() * 500), p = 1 + Math.floor(Math.random() * 100000); const rcv = Math.floor(Math.random() * (q + 5)), iq = Math.floor(Math.random() * (q + 5)); const ip = 1 + Math.floor(Math.random() * 100000); matchLine({ poQty: q, poPriceCents: p, receivedQty: rcv, invQty: iq, invPriceCents: ip }); // throws if broken if (matchLine({ poQty: q, poPriceCents: p, receivedQty: q, invQty: q, invPriceCents: p }).query !== 0n) throw new Error('exact match must be zero'); } 

100,000 random lines pass in a fraction of a second. Watch which price goes with which quantity: if you use the invoice price in the quantity variance AND the invoice quantity in the price variance, the overlap is counted twice and the parts no longer add up to the difference. The identity check catches that immediately.

This is the core of a purchasing-control tool we sell (one-time $19, free demo): https://gettidycents.com/product/purchase-invoice-match