Skip to content

Harden payment settlement, retries, reporting, and demo authentication - #215

Merged
khaira777 merged 16 commits into
mainfrom
fix/issue-214-payment-accounting-demo-credentials
Aug 4, 2026
Merged

khaira777 merged 16 commits into
mainfrom
fix/issue-214-payment-accounting-demo-credentials

Conversation

@khaira777

@khaira777 khaira777 commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR started from Issue #214 and now provides a broader payment-integrity and recovery hardening pass:

  • validate and apply split-payment batches atomically with cent-precise allocations
  • preserve legacy single-payment omitted/null amount compatibility
  • record cash tender/change metadata and reject invalid non-cash overfunding
  • keep ordinary repeated partial payments distinct; replay only explicit idempotency keys or transaction references
  • scope new retry/idempotency records to authenticated users, with exact-hash compatibility for unrecoverable historical records
  • preserve method-scoped transaction-reference uniqueness and audit historical conflicts during migrations v49–v54
  • make prepaid/postpaid retries durable, user-scoped, and safe around stale discounts and lost responses
  • make payment reports correctly flatten split and legacy records across UTC half-open ranges
  • migrate bundled demo identities to inactive randomized credentials and invalidate inactive sessions
  • enforce active-PIN and waiter ownership checks on sensitive order mutations
  • require explicit user action to install downloaded updates and fail closed when a migration backup cannot be created

Verification

Release notes

The updater no longer installs on app quit automatically; installation requires the explicit Restart/Install action. Migration backups are required before schema changes, and rollback should use the generated pre-migration backup rather than opening the migrated database with an older binary.

Fixes #214

@khaira777 khaira777 self-assigned this Aug 4, 2026
@khaira777
khaira777 marked this pull request as draft August 4, 2026 04:50
@khaira777 khaira777 changed the title Fix split-payment accounting and retire reusable demo credentials Harden payment settlement, retries, reporting, and demo authentication Aug 4, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

Follow-up review completed after the initial blockers:

  • Removed request-hash idempotency fallback; identical legacy partial payments remain separate.
  • Added user-scoped retry records plus exact-hash compatibility for ownerless historical records.
  • Rebuilt transaction references from bill snapshots in v52/v54 so cross-method references survive and same-method conflicts are audited.
  • Made prepaid discount retries compare server-side order/bill state and avoid mutating settled bills.
  • Moved add-item idempotency replay ahead of terminal-order rejection.
  • Added waiter ownership checks for order status and item cancellation.
  • Removed recovery-email logging and persisted PINs.
  • Disabled automatic install-on-quit and made migration backups fail closed.

Independent review found no remaining release blockers. Added migration fixture coverage and reran the full test/build/lint/E2E gates.

@khaira777 khaira777 added bug area:backend Backend (Express/SQLite) area:frontend Frontend (React/Next.js) labels Aug 4, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

Final follow-up verification

A final review pass added a few hardening and verification details beyond the original summary:

  • Fixed historical payment retry ownership so unrecoverable legacy records remain explicitly legacy instead of being attributed to the order creator.
  • Added POS add-item idempotency and reset partial-payment idempotency keys after confirmed settlement.
  • Updated vulnerable transitive dependencies within compatible ranges; root and frontend npm audit both report 0 vulnerabilities.
  • Preserved escaped client-side 4xx responses in the global server error handler while keeping malformed JSON responses distinct.

Final verification completed:

  • Full test suite with isolated ports — passed
  • Main and frontend builds — passed
  • Lint — passed with 0 errors (708 existing warnings)
  • Playwright E2E — 4/4 passed
  • Database audit and git diff --check — passed
  • Alibaba OCR findings were manually triaged; the actionable server-handler finding was fixed, and the final review of that fix returned 0 findings.

Requesting final review from @itsbkm.

@khaira777
khaira777 marked this pull request as ready for review August 4, 2026 06:22
@silasfrostx

Copy link
Copy Markdown

I filed #214, so I read this PR properly rather than just confirming the original case. Most of it holds up under the checks I'd expect to break it — noting those first, then one edge case I think is worth a test.

Verified sound (read from the diff, not run):

  • Both settlement routes wrap in withTxn(...), so the loyalty_ledger debit → payment_transaction_refs insert → bills UPDATE sequence can't half-apply. That was my main worry: the wallet debit is written before the bill update, and without the wrapper a mid-batch constraint failure would burn customer points against an unpaid bill.
  • paymentAmountCents closes the float path — regex-gated to ≤2dp, rejects scientific notation, negatives, and zero before Math.round(x*100).
  • Wallet units are consistent: debits insert amountCents, cashback credits are floor(currency) * LOYALTY_REDEMPTION_RATE with the rate at 100, so both sides of the ledger are in cents.
  • Non-cash is capped at remainingCents and cash allocates against the residual, so newPaidCents can't exceed the total. Cash overfunding becomes change rather than an overpayment.

The edge case: I think malformed legacy payment_details converts an idempotent retry into a permanent 409.

In preparePaymentBatch, the unparseable-JSON branch sets existingPayments = [], which leaves existingTransactionPayments empty. But the payment_transaction_refs lookup a few lines down still adds the key to existingTransactionKeys. So for a bill whose JSON has gone bad after a ref row was already written:

  1. replay requires transactionPaymentMatches(existingTransactionPayments.get(key), ...) — get() returns undefined, so it's false.
  2. replay is therefore false, and the dedup loop below sees existingTransactionKeys.has(key) and throws 409 Payment transaction_id has already been used for this bill.

A client resending the identical request — the exact case the Idempotency-Key path is for — gets a hard conflict instead of a no-op, and it never recovers for that bill/transaction_id pair. The comment on that catch says settlement compatibility is preserved for malformed JSON; that's true for appending a new line, but the replay path specifically loses it.

The v49 backfill skips invalid JSON, so this shouldn't arrive via migration. The path I'd expect is a bill settled normally (ref row + valid JSON) whose payment_details is corrupted afterwards — which is presumably why that catch block exists at all.

Two directions, depending on which you consider correct: treat a ref-matched line on unparseable JSON as a replay and return current bill state, or keep the 409 but distinguish "already applied" from "conflicting reuse" so the caller can tell them apart.

Caveat worth stating plainly: this is a diff read, not a reproduction — I haven't run it against your fixtures, and if payment_details can't realistically go bad post-write in your deployments then it's academic. Happy to be told I've misread the ordering.

Separately, and much smaller: a partially-overlapping batch (one line already applied, one new) also fails the .every() replay check and 409s, so the client's only recovery is to strip the applied line and resend. Probably intended, but it isn't stated anywhere.

@khaira777

Copy link
Copy Markdown
Contributor Author

@silasfrostx Thanks for the careful review. The malformed-JSON scenario is technically possible, but only with an already inconsistent or manually corrupted database. Normal settlement writes the transaction reference and payment details atomically, and Idempotency-Key retries replay the stored response before reaching this path. Keeping the 409 is safer because the reference does not contain the original payment amount.

Partial-overlap batches are intentionally rejected to preserve whole-batch idempotency.

@khaira777
khaira777 merged commit e2d8140 into main Aug 4, 2026
5 checks passed
@khaira777
khaira777 deleted the fix/issue-214-payment-accounting-demo-credentials branch August 4, 2026 16:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:backend Backend (Express/SQLite) area:frontend Frontend (React/Next.js)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Split-tender: card/upi lines silently capped to remaining balance, corrupting reconciliation and receipts

2 participants