Three faults were leaving restaurant days out of balance — one in the data, two in the arithmetic. This is what they were, what they cost, and what fixing them is worth, measured by running the real job over ninety days of real trading.
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.
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.
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.
For the business: two arithmetic faults, both of which overstated or understated a 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.
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.
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.
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.
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.
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.
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.
| 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.
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 |
| 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.
Both arithmetic fixes add exactly one credit line. Nothing else in a summary moves — no sales figure, no payment, no tax.
| 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.
| 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 |
| 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.
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.
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.
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.
| 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 |
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.
;; 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.