Production today $75,228.78 1,280 days out of balance · 85.34% clean
→
After all three fixes $1,995.36 108 days out of balance · 98.76% clean
1,172client-days brought into balance
0days knocked out of balance
97.3%of the variance removed
1.6%of card payments renamed so far

In one sentence: a day's sales summary should show the money taken and the money earned agreeing to the penny, and on roughly one day in seven it did not — because two clients were fighting over the same records, tips that had been refunded were still counted as income, and service charges customers paid were credited to nothing.

## The three problems

#### 1. Two client records sharing one Square location

For the business: ten restaurant locations were set up twice in the system, as two separate clients. Both were importing from Square. Because the two records competed for the same payments and refunds, a refund would belong to one client for twenty minutes, then the other — so a day's books could gain or lose a refund depending on nothing but timing. On 2026-07-23 one client's summary was missing a $71.94 refund entirely, and was out of balance by exactly that amount.

technical Sales orders scoped their identifier by client (`square/order/<code>-<loc>-<id>`), but refunds, card charges, payouts and cash-drawer shifts did not — they used the bare Square id. Those attributes are `:db.unique/identity`, so both clients' imports resolved to a single entity and the last writer won.

Reading ownership out of the database's own history, this had actually happened to 3,387 refunds, 4,069 payouts and 2,628 cash-drawer shifts. And it has involved 19 client pairs, of which only 10 are visible in today's configuration — nine more contended in the past and the configuration has since changed, so no point-in-time check would find them.

#### 2. One payment record owned by two orders

For the business: the same collision meant a single card payment could be attached to both clients' copies of an order. That is worse than untidy. The nightly import removes orders Square reports as voided, and removing an order also removes its payments — so cancelling one client's order could silently delete the other client's payment, leaving a day showing sales with no money against them.

technical `:sales-order/charges` is declared `:db/isComponent true`, so `[:db/retractEntity <order>]` cascades into the charges. In a 20,000-order sample of the affected clients, 11,469 charges had two parent orders. This is why `remove-voided-orders` was left switched off during testing.

#### 3. Tips refunded, and service charges credited nowhere

For the business: two arithmetic faults, both of which overstated or understated a day.

- Refunded tips stayed on the books. When a guest was refunded, the tip came back too — but the summary still counted the original tip as income. On one NGLK day the books credited $482.94 of tips beside a $60.00 refund of that very tip.
- Service charges were collected but never earned. A catering or auto-gratuity charge is inside the card payment the customer makes, so it arrived as money taken — but no line recorded it as money earned. One NTPT order carried $427.10 that was credited to nothing at all; the largest single instance was $1,344.86 in one day.

technical `get-tip` summed tips by joining through `:sales-order/charges`, so a return-only order — which has no tender to join through — contributed nothing, while its reversal sat unread on `:sales-order/tip`. Nothing at all read `:sales-order/service-charge`.

## What the fixes actually are

Five changes. The first three stop two clients from sharing a record; the last two record money that was being collected but not booked. Each is small — the difficulty was knowing which line to change, not writing it.

### 1 · Put the client in the record's name

Every imported record has an identifier the importer uses to decide "have I seen this before?". Sales orders already included the client; refunds, card payments, payouts and cash-drawer shifts did not, which is precisely why two clients could land on one record.

    ;; before — the bare Square id, identical for both clients
    (str "square/refund/" (:id r))          ;; square/refund/NOkQOTIiJULWN6…

    ;; after
    (scoped-key "square/refund/" client location (:id r))
    ;; square/refund/NGCD-CD-NOkQOTIiJULWN6…

    (defn scoped-key [prefix client location id]
      (str prefix (:client/code client) "-"
           (:square-location/client-location location) "-" id))

Applied at five places in the Square importer: order payments, refunds, payouts (twice — the record itself and the lookup that finds it) and cash-drawer shifts. ezCater orders already did this and needed no change.

### 2 · Find the existing record before writing, under either name

This is the one that makes the change safe to deploy. The identifiers are unique keys, so the importer relies on "same id, same record". Rename them and the next import matches nothing — and would quietly create a second copy of every refund and payment in the system, leaving the originals orphaned. So the importer looks up the record explicitly, new name first, old name second, and writes to whichever it finds.

    (defn existing-id [db attr prefix client location id]
      (when id
        (or (dc/entid db [attr (scoped-key prefix client location id)])   ;; new scheme
            (dc/entid db [attr (str prefix id)]))))                       ;; legacy scheme

The result is pinned as the record's id on the way in, so the write lands on the existing row regardless of which name it currently carries. The proof this worked: after re-naming 213,943 records, the totals for refunds, payouts and shifts were identical before and after. Had the fallback been missing they would have doubled.

### 3 · Give every order its own payment record

Renaming stops new collisions but does not undo old ones: a payment already shared by two orders is still one row with two owners. The migration walks each order's payments and, where another order has already claimed one, makes that order its own copy with the same amounts and points the order at the copy.

    ;; for each order, for each of its payments:
    :keep   → first order to claim it; rename in place
    :clone  → copy type, total, tip, tax, date, processor, note, receipt link
               set the copy's client and location to this order's
               retract this order's link to the shared payment
               link it to the copy instead

On the restored data that was 189,167 renamed and 77,599 copied, and payments owned by two orders went from 11,469 to zero. The record count rose by exactly 77,599 — the number of copies it reported making, which is the check that it created what it meant to and nothing else.

One subtlety worth recording, because it bit us: the Square id has to be recovered from the record's current owner rather than by trimming a fixed prefix. Client codes contain dashes — N-30003 — so a pattern cannot tell where the client name ends and the Square id begins. Getting this wrong scoped some records twice and doubled their tender.

### 4 · Count tips that were handed back

Tips were summed by walking from the order to its payments. A refund-only order has no payment attached, so its negative tip was invisible. The fix adds those tips rather than replacing the calculation.

    ;; before
    :ledger-mapped/amount (tendered-tip c date)

    ;; after
    :ledger-mapped/amount (+ (tendered-tip c date)
                             (untendered-tip c date))

    ;; untendered-tip — tips on orders with no payment attached
    [?e :sales-order/tip ?tip]
    (not [?e :sales-order/charges])

Adding rather than replacing is deliberate. Where an order does have a payment, the payment is the correct source: real orders exist whose payment carries a tip the order does not — an auto-gratuity recorded as a service charge, or a wallet tip missing from the order totals. Reading the order instead would have dropped those. Three tests hold this in place: the refund case must change, and the tendered and ordinary cases must not.

### 5 · Credit Square service charges, both signs

Nothing read the service-charge field at all. A new line credits it, for Square orders only and for negative amounts as well as positive.

    [?e :sales-order/service-charge ?service-charge]
    (or-join [?e]
             [?e :sales-order/vendor :vendor/ccp-square]
             (and (not [?e :sales-order/vendor])
                  [?e :sales-order/external-id ?external-id]
                  [(clojure.string/starts-with? ?external-id "square/order/")]))

Why the vendor test has two branches. ezCater service charges are commission the platform deducts from the restaurant, not money the diner hands over, so crediting them would make a day worse rather than better — hence the Square-only condition. But whole eras of Square orders carry no vendor field at all, and a test on vendor alone would silently credit nothing. The second branch falls back to the order's own identifier.

Why negatives matter. A returned catering fee arrives as a negative service charge and is already deducted from the day's returns; dropping negatives would lose the reversal. The line sits behind a per-client switch, off by default, so it can be turned on a few restaurants at a time.

### Supporting changes

Change | Why
--- | ---
Log each day's imbalance and its suspect lines | an out-of-balance day was only visible by opening the screen; now it can be queried
Stop the dirty-summary scan at the client boundary | it read every later client's summaries too — 1,321 ms to 5.6 ms per client
Split the recompute driver into a per-client function | lets a backfill spread clients across threads instead of grinding one at a time
Install schema attributes before the tuples that compose them | the test suite could not build an empty database at all, so no test could run

That last one is worth a sentence for engineers: `transact-schema` installed schema.edn then cloud-migration-schema.edn, but a composite tuple in the first file is built from an attribute in the second. Datomic will not create a tuple before its members exist, so every test fixture died in setup. It is very likely why sales summaries had no tests before this work.

## What each fix is worth

The job was run over the same ninety days at each stage, writing real summaries every time, so these are measured outcomes rather than estimates.

Stage | Days out of balance | Clean | Total variance
--- | --- | --- | ---
Production today | 1,280 | 85.34% | $75,228.78
+ deduplication | 1,087 | 87.55% | $63,764.92
+ refunded tips | 800 | 90.84% | $60,619.21
+ service charges | 108 | 98.76% | $1,995.36

### Day-by-day effect of each change

Change | Unchanged | Into balance | Out of balance | Balanced days altered | Money moved
--- | --- | --- | --- | --- | ---
Deduplication | 7,447 balanced already | 199 | 6 | — | —
Refunded tips | 8,421 | 287 | 0 | 0 | $3,777.67
Service charges | 8,037 | 692 | 0 | 0 | $58,923.85
All three, end to end | 7,453 | 1,172 | 0 | 0 | —

Neither arithmetic fix touched a day that was already correct. Across 8,733 client-days, no balanced day was knocked out of balance and no balanced day had a single figure altered — every day they changed was already wrong. Service charges are by far the larger of the two, moving $58,923.85 against the tip fix's $3,777.67.

Deduplication is the one step that puts six days out of balance. That is expected: those days were previously balanced only because a summary was empty, and filling it in exposes the same arithmetic faults every other day had. Both later fixes then close them, which is why the end-to-end figure is zero.

Excluding the ten now-deactivated duplicate records, which should not be reported on at all, the population is 8,350 client-days and the movement is 1,217 days and $69,995.61 down to 105 days and $852.38.

## What it looks like on the page

Both arithmetic fixes add exactly one credit line. Nothing else in a summary moves — no sales figure, no payment, no tax.

### A refunded tip — NGLK, 2026-08-04

Line | Before | After
--- | --- | ---
Tip | 482.94 | 422.94
Card Refunds | 60.00 | 60.00
Total money taken | 10,094.81 | 10,094.81
Total money earned | 10,154.81 | 10,094.81
Out of balance by | −60.00 | 0.00

The day already carried a $60.00 card refund — the guest was given their money back, tip included — while the tip line still credited the full $482.94. The corrected figure matches the refund to the penny. The order behind it is square/order/NGLK-SM-OxSX9gpXJV394qqT8mnBGypUwKNZY: a tip of −60.00 on an order with no payment attached at all.

### A service charge — NTPT, 2026-08-06

Line | Before | After
--- | --- | ---
Service Charges | not shown | 427.10
Card Payments | 4,975.89 | 4,975.89
Total money taken | 7,777.20 | 7,777.20
Total money earned | 7,350.10 | 7,777.20
Out of balance by | +427.10 | 0.00

### The largest repairs of each kind

Client | Date | Line | Before | After | Day closed
--- | --- | --- | --- | --- | ---
NGPA | 2026-06-04 | Service Charges | not shown | 1,344.86 | +1,344.86 → 0
NTPT | 2026-08-06 | Service Charges | not shown | 427.10 | +427.10 → 0
N-30003 | 2026-05-27 | Service Charges | not shown | 405.83 | +405.83 → 0
NGFL | 2026-05-19 | Tip | 238.46 | 70.42 | −168.04 → 0
NGMI | 2026-07-09 | Tip | 230.01 | 80.01 | −150.00 → 0
NGVA | 2026-07-03 | Tip | 152.66 | 40.12 | −112.54 → 0

In every case the correction equals the imbalance exactly, which is what you would expect if the fix is recording something real that was recorded nowhere. On NGNP 2026-06-25 both fixes land on one day and pull opposite ways — $301.40 credited, $1.80 removed, $299.60 closed — a useful check that they are independent.

## What was done to the data, and how it was checked

Every step below was performed against a restored copy of the production database. Production itself was never touched.

Step | Result
--- | ---
Deactivate the duplicate client at each shared location | 10 locations · shared locations remaining: 0
Give every order its own payment record | 189,167 re-keyed · 77,599 copied
Payments owned by two orders | 11,469 → 0
Client-scope refunds, payouts and cash-drawer shifts | counts unchanged · 0 collisions
Live Square import afterwards | 0 orders with duplicated payment · 0 shared payments
Ownership changes after the change | 0 refunds · 0 payouts · 0 shifts

The count checks are the ones that matter. If re-keying had gone wrong it would have created a second copy of every record rather than updating the existing one, and the totals would have doubled. They did not move. The payment-copy step is the exception and is meant to add records — it added exactly 77,599, matching the number of copies it reported making.

A bug in this work, found by measuring rather than reading

The first attempt at copying shared payments derived each payment's Square identifier by stripping a fixed prefix. That is right the first time a payment is seen, but once it has been re-keyed to one client, a second order meeting it later read the already-scoped key as the identifier and scoped it twice — NGCD-CD-NGCC-CC-<id>. The importer then created a fresh payment, doubling the tender on five clients by $3,000–$7,000 each. It was caught because the totals were absurd, not because the code looked wrong. The fix recovers the scope from the record itself; client codes contain dashes, so it cannot be done by pattern. A test now runs the step one order at a time, which is the arrangement that exposes it.

## What is still out of balance

Fifteen client-days across ninety days and 8,350 client-days, totalling $850.12. Everything else — 90 further days — comes to $2.26, the largest being 9.00¢, which is till rounding.

Client | Date | Variance | What it is
--- | --- | --- | ---
NGBK | 2026-08-06 | +299.42 | Square recorded more payment than the orders account for
NGMV | May 20–26 | +259.38 | five days, undiagnosed
NGEB | May 13 – Jul 29 | −199.09 | four days, ezCater fee treatment — an open question
NGDA | 2026-08-01 | −50.00 | auto-gratuity recorded as a service charge
N-30012 | May 20–21 | +30.31 | two days, undiagnosed
NG4S | 2026-05-29 | −11.78 | undiagnosed
PNSP | 2026-07-12 | −0.14 | till rounding, just over the threshold

The ten deactivated duplicate records contribute a further $1,142.98 across three days. They are excluded above and should be excluded from reporting generally, since they are now dormant copies.

Two clusters — NGMV and N-30012, both in late May — are new and unexplained. They only became visible because the window was widened to ninety days; a thirty-day view did not reach them. They are worth a look before this ships.

## How complete is this, really

The importer deliberately understands both the old and new record names, so the change can be deployed before the renaming finishes. That tolerance is a bridge, not a destination — while any record still carries an unscoped name, two clients can still land on it, and the guarantee rests on a convention rather than on the data.

Measuring the whole database rather than the part that was migrated gives an honest picture, and it is not a flattering one.

Record type | Client-scoped | Still unscoped | No owner to scope by
--- | --- | --- | ---
Refunds | 51,986 | 0 | 0
Payouts | 144,652 | 0 | 36
Cash-drawer shifts | 69,291 | 0 | 0
Card payments | 259,763 (1.6%) | 14,241,890 | 2,122,161

Refunds, payouts and shifts are done. Card payments are not — the migration described above covered the ten clients sharing a location today, within the reporting window, which is 1.6% of them. And sampling 2% of the orders belonging to every client that has ever contended found 12,954 payments still owned by two orders, which extrapolates to roughly 650,000 across that population.

So the correct reading of the balance figures earlier in this report is: they are what the calculation fixes are worth, measured on data where the sharing had been resolved for the clients and period in question. They are not a claim that the whole database is clean.

What finishing it requires

Renaming has to be driven from orders, because a payment's rightful owner is whichever order refers to it — so completing it means walking all 19,040,296 orders, not just the clients that look shared today. Nine client pairs contended in the past without sharing a location now, and a migration scoped to the current configuration misses every one of them.

On the test machine this ran at roughly 15,000 orders an hour once the database no longer fitted in memory, which puts a full pass in days rather than hours. That is a hardware characteristic of a swapping 29 GB restore, not a property of the work: the same code completed 267,012 orders in 100 seconds when the cache was warm. It belongs in a maintenance window on properly sized hardware, and it is resumable and safe to re-run — a second pass over already-renamed records does nothing at all.

The finish line is measurable, not a judgement call. `unscoped-report` counts, for every record type, how many names are client-scoped, how many are still unscoped, and how many have no owner. Two things follow from it:

- While the unscoped count is above zero, keep the importer's understanding of both name forms. Removing it early would strand every record that had not yet been renamed.
- Once it reaches zero and stays there across a full import cycle, delete the fallback. At that point two clients sharing a location is structurally incapable of producing a shared record, rather than merely unlikely to.

## Decisions and risks still open

Item | Who decides | Why it matters
--- | --- | ---
Which client record survives at each shared location | the business | the newer record generally has no history before the split, so keeping it loses years of the location's books
Which revenue account service charges post to | accounting | currently 49000 Service Income, chosen so the work could be measured; it affects reporting, never whether a day balances
Whether to correct records the wrong client already owns | the business | the fix stops future mix-ups; it does not retrospectively move records claimed while the configuration was shared
`remove-voided-orders` | engineering | safe once no payment has two parent orders; worth guarding regardless so it detaches rather than deletes

Two operational findings, unrelated to the summaries

The production backup had not written a restore point since 2025-03-10 — roughly seventeen months — even though data files were still uploading daily. A backup you cannot restore from is not a backup. A fresh one was taken on 2026-08-14 and is what this work used.

The database server was sized for a toy dataset: a 2 GB cache against 27 GB of data. A recompute was crawling at about 35 client-days a minute; after raising the cache to 8 GB the remaining 7,958 finished in 90 seconds. Worth checking what production is set to.

## How to check any of this technical

    ;; the restored database, untouched production as of 2026-08-14 22:52
    (def conn (d/connect "datomic:dev://localhost:4337/integreat-prod-restore"))

    ;; the two orders behind the worked examples
    (d/pull (d/db conn) '[*] [:sales-order/external-id
                              "square/order/NGLK-SM-OxSX9gpXJV394qqT8mnBGypUwKNZY"])
    (d/pull (d/db conn) '[*] [:sales-order/external-id
                              "square/order/NTPT-PT-KrMZzcon1cpQEJUyetErkBIpcdEZY"])

    ;; the gate: no payment may have two parent orders
    (rk/charges-with-multiple-parents (d/db conn) orders)   ;; => 0

    ;; ownership history — which records ever changed client
    (->> (d/datoms (d/history (d/db conn)) :aevt :sales-refund/client)
         (filter :added)
         (reduce (fn [m d] (update m (:e d) (fnil conj #{}) (:v d))) {})
         (filter (fn [[_ owners]] (> (count owners) 1)))
         count)

The comparison tool is committed as `auto-ap.jobs.compare-sales-summaries`, which diffs summaries between two points in the same database using `as-of` — so "before" is production's own stored figures rather than a re-simulation. Unit tests: `lein test auto-ap.jobs.sales-summaries-test auto-ap.square.core3-test auto-ap.jobs.rekey-square-external-ids-test`.