Diagnostic Bank transfers and statement matching
One bank transfer for several WooCommerce orders: finding the exact split
A customer with two unpaid orders pays them with one transfer. Or pays part of an order now and the rest later. The statement shows a single amount that matches no single order. Here is how to find which orders add up to it, why you stop the moment two answers fit, and a small script that does it in whole cents.
One transfer can pay several orders, and a payment smaller than an order is a part payment. To find a split, look only at one customer's unpaid orders, in whole cents, for sets of 2 to 4 orders that add up exactly, and refuse past 30 orders because the search grows exponentially. If two different sets fit, the answer is ambiguous and a person decides. The script takes an amount and a list of orders and says exact, ambiguous, none or too many.
The problem in plain words
A customer has orders 1042 for 49.90, 1043 for 25.00 and 1044 for 10.00, all unpaid. A transfer of 74.90 arrives. No single order is 74.90, but 1042 and 1043 add up to it exactly. The customer meant to pay both and sent one payment.
The opposite case: a transfer of 30.00 against the 49.90 order is a part payment. It pays something and does not settle the order, and the 19.90 still owed is not an unmatched payment, it is a balance.
Why it happens
Four things make this harder than it looks:
- Subset-sum grows exponentially. Every extra order doubles the combinations, so the search has to be bounded: one customer's orders only, at most 30 of them, at most 4 in a set. Transferproof's author measured about 7 ms for the worst case at 30 orders and 86 ms at 60.
- Floating point is the wrong tool for money: 0.10 plus 0.20 is 0.30000000000000004 in binary floating point, which is not 0.30. Work in whole cents.
- Two sets that fit are two answers. With three orders of 25.00, a transfer of 50.00 fits three different pairs. The search stops at the second fitting set and reports ambiguity.
- A part payment or an overpayment is a different case from a split. Less than an order is a part payment; more than an order is an overpayment, unless the excess adds up exactly to the customer's other orders.
Stop at two. The moment a second set fits you already know the answer is "ask a person", and you save the rest of the search.
The fix, as a flow
The script takes the payment and one customer's unpaid orders, converts every amount to whole cents, sorts the orders largest first so a partial sum passes the target early, and walks the combinations of up to four orders. It stops as soon as it has found two.
Build it step by step
Nothing to install
Run it on any two numbers. It needs no network, no credentials and no store.
# Python 3.8 or later. Standard library only: nothing to install, no keys, no network.
# Node 18 or later. Built-in modules only: nothing to install, no keys, no network.
Search with one pure function
find_splits takes the orders as (id, cents) pairs and the target in cents, and returns up to two fitting sets, or nothing at all past 30 orders. decide turns that into exact, ambiguous, none or too many.
def find_splits(dues, target, must_include=None):
"""dues: [(order_id, cents)], all positive. Up to two fitting sets of order ids, or None past the cap."""
if len(dues) > CAP:
return None
ordered = sorted(dues, key=lambda d: -d[1]) # largest first, so a partial sum passes the target early
hits = []
def walk(start, total, picked):
for i in range(start, len(ordered)):
if len(hits) >= 2:
return # two sets: ambiguous already
order_id, cents = ordered[i]
s = total + cents
if s > target:
continue
p = picked + [order_id]
if s == target:
if len(p) >= 2 and (must_include is None or must_include in p):
hits.append(sorted(p))
continue # every amount is positive: adding more can only overshoot
if len(p) < MAX_PARTS:
walk(i + 1, s, p)
walk(0, 0, [])
return hits
def decide(dues, target, must_include=None):
"""-> ('one', [set]) | ('ambiguous', [set, set]) | ('none', []) | ('too_many', [])"""
found = find_splits(dues, target, must_include)
if found is None:
return "too_many", []
return {0: "none", 1: "one", 2: "ambiguous"}[len(found)], found
export function findSplits(dues, target, mustInclude = null) {
if (dues.length > CAP) return null;
const ordered = [...dues].sort((a, b) => b[1] - a[1]); // largest first; the sort is stable
const hits = [];
const walk = (start, total, picked) => {
for (let i = start; i < ordered.length; i++) {
if (hits.length >= 2) return; // two sets: ambiguous already
const [id, cents] = ordered[i];
const s = total + cents;
if (s > target) continue;
const p = [...picked, id];
if (s === target) {
if (p.length >= 2 && (mustInclude === null || p.includes(mustInclude))) hits.push([...p].sort((x, y) => x - y));
continue; // every amount is positive: adding more can only overshoot
}
if (p.length < MAX_PARTS) walk(i + 1, s, p);
}
};
walk(0, 0, []);
return hits;
}
export function decide(dues, target, mustInclude = null) {
const found = findSplits(dues, target, mustInclude);
if (found === null) return ["too_many", []];
return [["none", "one", "ambiguous"][found.length], found];
}
Feed it one customer's orders only
Searching every unpaid order in the shop would find splits across strangers. Pass only the orders of the customer the payment is already tied to, by a reference or by a payer you have confirmed.
python3 find_split_payments.py 74.90 1042=49.90 1043=25.00 1044=10.00
node find-split-payments.mjs 74.90 1042=49.90 1043=25.00 1044=10.00
The script never writes anything and never touches the network: it reads the files or numbers you give it and prints. Confirming a payment against an order is a decision for a person.
The full code
The complete script in one file for each language. It takes the amount and the orders on the command line.
"""Find which of a customer's unpaid orders one bank transfer pays exactly.
Give it the amount that arrived and the customer's unpaid orders. It finds the sets
of 2 to 4 orders whose amounts add up to the payment to the cent, and says
"ambiguous" when two different sets fit, because choosing one is a guess. It never
searches more than 30 orders (the search grows exponentially) and works in whole
cents, so 0.10 + 0.20 never misses 0.30. Pure: no network, no store, no writes.
python3 find_split_payments.py 74.90 1042=49.90 1043=25.00 1044=10.00
Guide: https://www.allanninal.dev/woocommerce/one-bank-transfer-pays-several-orders/
"""
import re
import sys
CAP = 30
MAX_PARTS = 4
def to_minor(text):
"""'49.90' -> 4990. Refuses a third decimal, a sign or anything that is not a plain amount."""
m = re.fullmatch(r"(\d+)(?:\.(\d{1,2}))?", str(text).strip())
cents = int(m.group(1)) * 100 + int((m.group(2) or "").ljust(2, "0")) if m else 0
if cents <= 0:
raise ValueError(f"not a positive amount with at most two decimals: {text!r}")
return cents
def find_splits(dues, target, must_include=None):
"""dues: [(order_id, cents)], all positive. Up to two fitting sets of order ids, or None past the cap."""
if len(dues) > CAP:
return None
ordered = sorted(dues, key=lambda d: -d[1]) # largest first, so a partial sum passes the target early
hits = []
def walk(start, total, picked):
for i in range(start, len(ordered)):
if len(hits) >= 2:
return # two sets: ambiguous already
order_id, cents = ordered[i]
s = total + cents
if s > target:
continue
p = picked + [order_id]
if s == target:
if len(p) >= 2 and (must_include is None or must_include in p):
hits.append(sorted(p))
continue # every amount is positive: adding more can only overshoot
if len(p) < MAX_PARTS:
walk(i + 1, s, p)
walk(0, 0, [])
return hits
def decide(dues, target, must_include=None):
"""-> ('one', [set]) | ('ambiguous', [set, set]) | ('none', []) | ('too_many', [])"""
found = find_splits(dues, target, must_include)
if found is None:
return "too_many", []
return {0: "none", 1: "one", 2: "ambiguous"}[len(found)], found
def main(argv):
if len(argv) < 3:
print("usage: find_split_payments.py AMOUNT ORDER_ID=AMOUNT [ORDER_ID=AMOUNT ...]", file=sys.stderr)
return 2
target = to_minor(argv[1])
dues = []
for arg in argv[2:]:
order_id, _, amount = arg.partition("=")
dues.append((int(order_id), to_minor(amount)))
if len({o for o, _ in dues}) != len(dues):
print("an order id appears twice", file=sys.stderr)
return 2
single = [o for o, c in dues if c == target]
if single:
print(f"order {single[0]} alone is exactly {target / 100:.2f}: that is a plain match, not a split.")
verdict, sets = decide(dues, target)
label = lambda s: " + ".join(str(o) for o in s)
if verdict == "one":
print(f"exact: {label(sets[0])} adds up to {target / 100:.2f}")
elif verdict == "ambiguous":
print(f"ambiguous: {label(sets[0])} and {label(sets[1])} both add up to {target / 100:.2f}; a person decides.")
elif verdict == "too_many":
print(f"{len(dues)} orders is more than the {CAP} this searches; narrow it to one customer's orders.")
else:
print(f"no set of 2 to {MAX_PARTS} orders adds up to {target / 100:.2f}.")
return 0 if verdict == "one" else 1
if __name__ == "__main__":
sys.exit(main(sys.argv))
/**
* Find which of a customer's unpaid orders one bank transfer pays exactly.
*
* Give it the amount that arrived and the customer's unpaid orders. It finds the sets of 2
* to 4 orders whose amounts add up to the payment to the cent, and says "ambiguous" when two
* different sets fit, because choosing one is a guess. It never searches more than 30 orders
* (the search grows exponentially) and works in whole cents. Pure: no network, no writes.
*
* node find-split-payments.mjs 74.90 1042=49.90 1043=25.00 1044=10.00
*
* Guide: https://www.allanninal.dev/woocommerce/one-bank-transfer-pays-several-orders/
*/
import { pathToFileURL } from "node:url";
export const CAP = 30;
export const MAX_PARTS = 4;
/** "49.90" -> 4990. Refuses a third decimal, a sign or anything that is not a plain amount. */
export function toMinor(text) {
const m = /^(\d+)(?:\.(\d{1,2}))?$/.exec(String(text).trim());
if (!m) throw new Error(`not a positive amount with at most two decimals: ${text}`);
const cents = Number(m[1]) * 100 + Number((m[2] || "").padEnd(2, "0"));
if (cents <= 0) throw new Error(`not a positive amount with at most two decimals: ${text}`);
return cents;
}
/** dues: [[orderId, cents]], all positive. Up to two fitting sets of order ids, or null past the cap. */
export function findSplits(dues, target, mustInclude = null) {
if (dues.length > CAP) return null;
const ordered = [...dues].sort((a, b) => b[1] - a[1]); // largest first; the sort is stable
const hits = [];
const walk = (start, total, picked) => {
for (let i = start; i < ordered.length; i++) {
if (hits.length >= 2) return; // two sets: ambiguous already
const [id, cents] = ordered[i];
const s = total + cents;
if (s > target) continue;
const p = [...picked, id];
if (s === target) {
if (p.length >= 2 && (mustInclude === null || p.includes(mustInclude))) hits.push([...p].sort((x, y) => x - y));
continue; // every amount is positive: adding more can only overshoot
}
if (p.length < MAX_PARTS) walk(i + 1, s, p);
}
};
walk(0, 0, []);
return hits;
}
export function decide(dues, target, mustInclude = null) {
const found = findSplits(dues, target, mustInclude);
if (found === null) return ["too_many", []];
return [["none", "one", "ambiguous"][found.length], found];
}
export async function run(argv = process.argv.slice(2)) {
if (argv.length < 2) {
console.error("usage: find-split-payments.mjs AMOUNT ORDER_ID=AMOUNT [ORDER_ID=AMOUNT ...]");
return 2;
}
const target = toMinor(argv[0]);
const dues = argv.slice(1).map((arg) => {
const [id, amount] = arg.split("=");
return [Number(id), toMinor(amount)];
});
if (new Set(dues.map((d) => d[0])).size !== dues.length) {
console.error("an order id appears twice");
return 2;
}
const money = (c) => (c / 100).toFixed(2);
const single = dues.find((d) => d[1] === target);
if (single) console.log(`order ${single[0]} alone is exactly ${money(target)}: that is a plain match, not a split.`);
const [verdict, sets] = decide(dues, target);
const label = (s) => s.join(" + ");
if (verdict === "one") console.log(`exact: ${label(sets[0])} adds up to ${money(target)}`);
else if (verdict === "ambiguous") console.log(`ambiguous: ${label(sets[0])} and ${label(sets[1])} both add up to ${money(target)}; a person decides.`);
else if (verdict === "too_many") console.log(`${dues.length} orders is more than the ${CAP} this searches; narrow it to one customer's orders.`);
else console.log(`no set of 2 to ${MAX_PARTS} orders adds up to ${money(target)}.`);
return verdict === "one" ? 0 : 1;
}
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
run().then((code) => process.exit(code)).catch((err) => { console.error(err); process.exit(2); });
}
Add a test
The decision is the part most worth testing, and because it is a pure function the tests need no store and no network: they feed in plain objects and check the answer.
import pytest
from find_split_payments import CAP, decide, find_splits, to_minor
def test_two_orders_that_add_up_exactly():
assert decide([(1, 4990), (2, 2500), (3, 1000)], 7490) == ("one", [[1, 2]])
def test_three_orders():
assert decide([(1, 4990), (2, 2500), (3, 1000)], 8490) == ("one", [[1, 2, 3]])
def test_two_different_sets_are_ambiguous_not_first_wins():
verdict, sets = decide([(1, 2500), (2, 2500), (3, 2500)], 5000)
assert verdict == "ambiguous" and len(sets) == 2
def test_no_set_fits():
assert decide([(1, 4990), (2, 2500)], 7000) == ("none", [])
def test_a_single_order_is_not_a_split():
assert decide([(1, 2500), (2, 900)], 2500) == ("none", [])
def test_never_more_than_four_orders():
assert decide([(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)], 500) == ("none", [])
def test_the_named_order_must_be_in_the_set():
dues = [(1, 3000), (2, 2000), (3, 1000), (4, 4000)]
assert decide(dues, 5000)[0] == "ambiguous" # 1+2 and 3+4 both fit
assert decide(dues, 5000, must_include=4) == ("one", [[3, 4]])
assert decide(dues, 5000, must_include=1) == ("one", [[1, 2]])
def test_past_the_cap_it_refuses_instead_of_searching():
assert decide([(i, 100 + i) for i in range(CAP + 1)], 300) == ("too_many", [])
def test_cents_are_exact_where_floats_are_not():
assert to_minor("0.10") + to_minor("0.20") == to_minor("0.30")
assert decide([(1, to_minor("0.10")), (2, to_minor("0.20"))], to_minor("0.30")) == ("one", [[1, 2]])
@pytest.mark.parametrize("bad", ["0", "-5.00", "1.005", "abc", "nan", "inf"])
def test_amounts_that_are_not_plain_money_are_refused(bad):
with pytest.raises(ValueError):
to_minor(bad)
import { test } from "node:test";
import assert from "node:assert/strict";
import { CAP, decide, toMinor } from "./find-split-payments.mjs";
test("two orders that add up exactly", () => assert.deepEqual(decide([[1, 4990], [2, 2500], [3, 1000]], 7490), ["one", [[1, 2]]]));
test("three orders", () => assert.deepEqual(decide([[1, 4990], [2, 2500], [3, 1000]], 8490), ["one", [[1, 2, 3]]]));
test("two different sets are ambiguous, not first wins", () => {
const [verdict, sets] = decide([[1, 2500], [2, 2500], [3, 2500]], 5000);
assert.equal(verdict, "ambiguous");
assert.equal(sets.length, 2);
});
test("no set fits", () => assert.deepEqual(decide([[1, 4990], [2, 2500]], 7000), ["none", []]));
test("a single order is not a split", () => assert.deepEqual(decide([[1, 2500], [2, 900]], 2500), ["none", []]));
test("never more than four orders", () => assert.deepEqual(decide([[1, 100], [2, 100], [3, 100], [4, 100], [5, 100]], 500), ["none", []]));
test("the named order must be in the set", () => {
const dues = [[1, 3000], [2, 2000], [3, 1000], [4, 4000]];
assert.equal(decide(dues, 5000)[0], "ambiguous");
assert.deepEqual(decide(dues, 5000, 4), ["one", [[3, 4]]]);
assert.deepEqual(decide(dues, 5000, 1), ["one", [[1, 2]]]);
});
test("past the cap it refuses instead of searching", () =>
assert.deepEqual(decide(Array.from({ length: CAP + 1 }, (_, i) => [i, 100 + i]), 300), ["too_many", []]));
test("cents are exact where floats are not", () => {
assert.equal(toMinor("0.10") + toMinor("0.20"), toMinor("0.30"));
assert.deepEqual(decide([[1, toMinor("0.10")], [2, toMinor("0.20")]], toMinor("0.30")), ["one", [[1, 2]]]);
});
test("amounts that are not plain money are refused", () => {
for (const bad of ["0", "-5.00", "1.005", "abc", "NaN", "Infinity"]) assert.throws(() => toMinor(bad), bad);
});
Worked example
What it found
Four runs of the same script. 74.90 against orders of 49.90, 25.00 and 10.00 found one exact pair. 50.00 against three orders of 25.00 fits three different pairs, so it stopped at the second and said ambiguous. 60.00 against 50.00, 30.00 and 30.00 found 30.00 plus 30.00, which taking the largest order first would have missed. 30.00 against 49.90 and 25.00 found nothing: that is a part payment, not a split.
exact: 1042 + 1043 adds up to 74.90
ambiguous: 1 + 2 and 1 + 3 both add up to 50.00; a person decides.
exact: 2 + 3 adds up to 60.00
no set of 2 to 4 orders adds up to 30.00.
(exit status 1)
exact: 1042 + 1043 adds up to 74.90
ambiguous: 1 + 2 and 1 + 3 both add up to 50.00; a person decides.
exact: 2 + 3 adds up to 60.00
no set of 2 to 4 orders adds up to 30.00.
(exit status 1)
Python and Node.js printed identical lines. The exit status is 0 only for an exact fit, so the last line of output below ends with status 1.
FAQ
Why not just take the largest orders first until the amount is reached?
A greedy pick can miss an exact fit. For 60.00 from orders of 50.00, 30.00 and 30.00, taking 50.00 first leaves 10.00 and nothing fits, while 30.00 plus 30.00 is exact. The search tries combinations.
Why only 2 to 4 orders?
One order is a plain match, not a split. Longer sets multiply the chance that a coincidence fits, and the search cost with them. The limits are a policy; change them for your shop, but keep a cap.
What about a payment that is a little off?
An exact search will not find it, on purpose. A payment 1.50 short is a part payment or a fee, which is a decision for a person; widening a tolerance until something fits is how wrong matches are made.
Related field notes
Citations
- WooCommerce docs: Direct bank transfer (BACS). New orders are set On hold and you confirm the deposit yourself. woocommerce.com/document/bacs
- WooCommerce REST API: listing orders, their status, payment method, totals and dates. woocommerce.github.io/woocommerce-rest-api-docs
Transferproof searches only one identified customer's open orders, at most 30 of them, for sets of 2 to 4 that add up to the cent. Two fitting sets are reported as ambiguous, never the first one. Part payments and overpayments are suggested for a person to confirm, never confirmed automatically.
Did this save you a morning with the bank statement?
If it did, you can buy me a coffee. It is the best way to keep these field notes free and growing.
Buy me a coffee on Ko-fi