DEV Community

eth shihao
eth shihao

Posted on

Benchmarking AP three-way matching with partial receipts in JavaScript

A purchase order calls for 100 units. The warehouse receives 60 and returns 10. AP has already billed 40, leaving 10 units available now. A new invoice bills eight units on one line and seven on another. Each line fits by itself. Together they exceed the receipt balance by five and route to hold_qty_variance.

Enforce the two quantity limits on the total billed

Resolve each invoice line to a PO line. A SKU is sufficient when it occurs once. If a PO repeats the SKU, the invoice must name the PO line explicitly. Sum the current invoice quantities per PO line, add the posted invoice quantities, then compare with both the ordered quantity and the net received quantity.

Case Ordered Net received Prior billed This invoice Route
Partial receipt 100 50 40 15 hold_qty_variance
Five more units arrive 100 55 40 15 auto_approve
Sixteen units on order, enough received 16 55 2 15 hold_qty_variance

The second case can clear even though the PO still has 45 units on backorder. The last case exceeds the PO by one, so additional receipts would leave the quantity hold in place.

Use inclusive cent and percentage limits

The PO unit price is $12.50. The fixture allows two cents of absolute variance and 20 basis points. Two cents is within both limits. Three cents exceeds both limits, because 20 bps of $12.50 is 2.5 cents. The code compares abs(delta) * 10000 <= expected * basisPoints with integer arithmetic, avoiding a rounded allowance.

Compare each unit price independently, then apply the separate freight and tax gates. Here a $5.00 freight allocation billed at $5.05 passes a five-cent and 100 bps policy exactly. With a percentage gate and an expected charge of zero, only an actual charge of zero passes. When more than one check fails, the matcher retains the exceptions and routes quantity ahead of price.

Duplicate detection keys on vendor ID and normalized invoice number across POs. It runs first so an already-posted invoice routes to reject_duplicate even if the receipt budget has changed since posting.

Run the benchmark

Run the block from the source checkout with Node.js 20 or later. The benchmark checks the four routes, exact totals, and quantity headroom, then measures the full calculation on one-line and 128-line purchase orders. MIT source repository

node --input-type=module <<'JS'
import assert from 'node:assert/strict';
import { performance } from 'node:perf_hooks';
import { matchInvoice } from './src/index.js';

const scope = { vendorId: 'SUP-42', currency: 'USD' };
const purchaseOrderId = 'PO-1';
const receipt = (id, quantity) => ({ id, purchaseOrderId, lines: [{ lineId: '10', quantity }] });
const partial = {
  purchaseOrder: { ...scope, id: purchaseOrderId, freightCents: 500, taxCents: 800,
    lines: [{ lineId: '10', sku: 'WIDGET', quantity: 100, unitCents: 1_250 }] },
  receipts: [receipt('GR1', 60), receipt('RET1', -10)],
  history: [{ vendorId: scope.vendorId, invoiceNumber: 'INV-001', purchaseOrderId,
    lines: [{ lineId: '10', quantity: 40 }] }],
  invoice: { ...scope, purchaseOrderId, invoiceNumber: 'INV-209', freightCents: 505, taxCents: 808,
    lines: [{ sku: 'WIDGET', quantity: 8, unitCents: 1_250 },
      { lineId: '10', sku: 'WIDGET', quantity: 7, unitCents: 1_252 }] },
  tolerances: {
    price: { absoluteCents: 2, basisPoints: 20 },
    freight: { absoluteCents: 5, basisPoints: 100 },
    tax: { absoluteCents: 8, basisPoints: 100 },
  },
};
const approved = { ...partial, receipts: [...partial.receipts, receipt('GR2', 5)] };
const priceHold = { ...approved, invoice: { ...approved.invoice, lines: [
  approved.invoice.lines[0], { ...approved.invoice.lines[1], unitCents: 1_253 },
] } };
const duplicate = { ...partial, history: [...partial.history, {
  vendorId: scope.vendorId, invoiceNumber: ' inv-209 ', purchaseOrderId: 'PO-OTHER',
}] };

const poLines = Array.from({ length: 128 }, (_, index) => ({
  lineId: String(index + 1), sku: 'ITEM-' + (index + 1), quantity: 10, unitCents: 125,
}));
const larger = {
  purchaseOrder: { ...scope, id: purchaseOrderId, lines: poLines },
  receipts: [{ id: 'GR3', purchaseOrderId,
    lines: poLines.map(({ lineId }) => ({ lineId, quantity: 6 })) }],
  invoice: { ...scope, purchaseOrderId, invoiceNumber: 'INV-588',
    lines: poLines.map(({ lineId, sku, unitCents }) => ({ lineId, sku, unitCents, quantity: 5 })) },
};

assert.deepEqual(matchInvoice(partial).issues, [{ code: 'over_received', lineId: '10' }]);
assert.equal(matchInvoice(partial).quantities[0].availableToBill, 10);
assert.equal(matchInvoice(approved).quantities[0].backorder, 45);
assert.equal(matchInvoice(priceHold).lines[1].price.withinBasisPoints, false);

const fixtures = [
  ['Partial receipt', partial, 'hold_qty_variance', 20_077, 10_000],
  ['Receipt catch-up', approved, 'auto_approve', 20_077, 10_000],
  ['Price out of tolerance', priceHold, 'hold_price_variance', 20_084, 10_000],
  ['Duplicate across POs', duplicate, 'reject_duplicate', undefined, 10_000],
  ['128 PO lines', larger, 'auto_approve', 80_000, 2_000],
];
const measurements = [];
for (const [fixture, input, status, total, iterations] of fixtures) {
  const result = matchInvoice(input);
  assert.equal(result.status, status);
  assert.equal(result.totalCents, total);

  for (let i = 0; i < 500; i++) matchInvoice(input);
  const samples = [];
  for (let round = 0; round < 5; round++) {
    let checksum = 0;
    const start = performance.now();
    for (let i = 0; i < iterations; i++) {
      const run = matchInvoice(input);
      checksum += run.status === status ? (run.totalCents ?? 1) : 0;
    }
    samples.push(performance.now() - start);
    assert.equal(checksum, (total ?? 1) * iterations);
  }
  const median = samples.sort((a, b) => a - b)[2];
  measurements.push({ fixture, iterations, medianMs: Number(median.toFixed(2)),
    callsPerSecond: Math.round(1000 * iterations / median) });
}
console.log(process.version, process.platform, process.arch);
console.table(measurements);
JS
Enter fullscreen mode Exit fullscreen mode

One run on macOS arm64 with Node.js v24.14.1 produced these medians across five samples.

Fixture Calls per sample Median Calls per second
Partial receipt 10,000 25.15 ms 397,573
Receipt catch-up 10,000 16.03 ms 623,774
Price out of tolerance 10,000 16.05 ms 623,048
Duplicate across POs 10,000 3.66 ms 2,731,619
128 PO lines 2,000 99.29 ms 20,142

The matcher indexes PO lines and accumulates receipt and invoice quantities in a single pass through each collection. The timings include validation and diagnostic construction. Database reads, JSON parsing, and posting are outside the measured loop. For a live AP workflow, enforce the duplicate key and reserve the receipt quantity in the same posting transaction so concurrent bills cannot consume the same receipt.

Try each route in the GitHub Pages demo. Related tools include ThreeWayMatchPack and StatementPack.

Top comments (0)