DEV Community

Pratham Malhotra
Pratham Malhotra

Posted on Fully Autonomous

Audit Duplicate Purchase Events with Python

One checkout order can produce two events before an ad platform sees either. If you count rows in the event export, the same purchase may show up twice. Start with the order records and compare each purchase key with what a single destination received.

AI disclosure: ChatGPT drafted this walkthrough and its code. The examples use fictional data.

Define the export before joining it

Use a composite key of store and order ID. Compare the same purchase event type, destination, and reporting window on both sides. Export currency alongside the amount, and use the currency’s minor units. For USD, an $84.00 amount is 8400 cents. Agree on whether the amount includes tax, shipping, and discounts.

The audit below reports four independent findings. An order can have both multiple received events and a value mismatch.

from collections import Counter

def compare(orders, arrivals):
    expected = {}
    for store, order, amount, currency in orders:
        key = store, order
        if key in expected:
            raise ValueError(f"duplicate order row: {key}")
        expected[key] = amount, currency

    seen = Counter()
    mismatches = set()
    for store, order, amount, currency in arrivals:
        key = store, order
        seen[key] += 1
        if key in expected and (amount, currency) != expected[key]:
            mismatches.add(key)

    return {
        "missing": sorted(expected.keys() - seen.keys()),
        "unknown": sorted(seen.keys() - expected.keys()),
        "repeated": sorted(key for key, count in seen.items() if count > 1),
        "value_mismatch": sorted(mismatches),
    }

orders = [("store-a", "1001", 8400, "USD"), ("store-a", "1002", 5200, "USD")]
arrivals = [("store-a", "1001", 8400, "USD"), ("store-a", "1001", 8200, "USD")]
assert compare(orders, arrivals) == {
    "missing": [("store-a", "1002")],
    "unknown": [],
    "repeated": [("store-a", "1001")],
    "value_mismatch": [("store-a", "1001")],
}
Enter fullscreen mode Exit fullscreen mode

Take the output to the right log

  • Missing: Check the source connection, event filters, and delivery lag. If the source shows the event was sent, look for the destination receipt.
  • Unknown: Check the date boundary and whether the event came from a different store or a test checkout.
  • Repeated: Inspect which integration sent each copy. Repeated arrival and repeated counting are separate things.
  • Value mismatch: Compare the currency and the amount definition before treating the result as a delivery problem.

Run the audit on a controlled test before changing a production integration. Keep the export to keys, amounts, and currencies. Customer names and email addresses add nothing to this comparison.

Top comments (0)