Skip to content

fix(billing): remediate loyalty re-award and zero-balance idempotency - #1249

Merged
khaira777 merged 2 commits into
mainfrom
fm/remediate-f1-f2-settlement
Oct 20, 2026
Merged

khaira777 merged 2 commits into
mainfrom
fm/remediate-f1-f2-settlement

Conversation

@khaira777

Copy link
Copy Markdown
Contributor

Summary

Fixes financial settlement defects F1 and F2 in main/routes/bills.ts and adds deterministic regression coverage including owner-reject/waiter-payment concurrency checks.

Closes #1241
Closes #1205

What Failed and Why

Defect F1 (#1241): Loyalty Cashback Re-awarded & Kitchen Delivery Check Repeated on Already-Paid Bills

In applyPaymentBatch (main/routes/bills.ts), when a payment request was submitted with no positive payment lines (prepared.length === 0), the code branched into the zero-amount settlement path without verifying whether the bill was already paid (bill.payment_status === 'paid'). If loyalty cashback was enabled subsequent to the bill's initial settlement (or if the bill lacked an initial loyalty_ledger entry), the zero-amount call on an already-paid bill recomputed cashback against the bill's historical total, inserted duplicate loyalty_ledger rows, and credited customers.loyalty_points. Furthermore, it invoked checkKitchenDeliveryStatus and recorded duplicate kitchen delivery override audit rows, potentially failing with 409 if kitchen items were undelivered even though the bill had already been settled.

Defect F2 (#1205): Idempotency Record Not Persisted for Zero-Balance Settlements & Missing Kitchen Override Flag

When settling an unpaid or partially paid bill whose remaining balance was zero (e.g., fully discounted), applyPaymentBatch returned immediately at line 3425. It bypassed line 3565 where payment_idempotency records are inserted, leaving payment_idempotency empty for legitimate zero-balance settlements. Consequently, any network retry or replay with the same Idempotency-Key was treated as a fresh payment request; if an override PIN was rotated or a manager deactivated, subsequent replays failed with 403 instead of returning the cached idempotent response (200 with idempotent_replay: true). In addition, the initial zero-balance settlement response failed to propagate kitchenDeliveryOverridden: true when a kitchen override had occurred.

How It Was Reproduced (Red-to-Green)

A comprehensive integration test suite was created in tests/bills-settlement-idempotency.test.ts covering:

  1. F1 Tests:
    • Single payment zero-amount and null-amount calls on already-paid bills with loyalty enabled post-settlement (with and without idempotency keys). Verified zero points earned and zero loyalty_ledger insertions.
    • Batch payments zero-amount and null-amount calls on already-paid bills.
    • Database mutation checks confirming bills, orders, and tables are untouched by no-op calls on paid bills.
    • Kitchen delivery check bypass confirming no override PIN is demanded on already-paid bill retries.
  2. F2 Tests:
    • Single and batch zero-balance settlements with manager override PIN. Confirmed payment_idempotency record persistence and kitchenDeliveryOverridden: true in response.
    • Replay with rotated/invalid manager PIN verifying idempotent 200 replay.
  3. Concurrency Test:
    • Deterministic test for owner cancellation during waiter async PIN verification, verifying order status stays cancelled and is not flipped to completed by payment transaction.
    • Concurrent in-flight payment race verifying atomicity and proper serialization.
  • Red Step: Verified on untouched main, capturing 20 failing assertions in /Users/gurkiratkhaira/tools/firstmate/data/remediate-f1-f2-settlement/repro-red.txt.
  • Green Step: Verified all 64 assertions passing in /Users/gurkiratkhaira/tools/firstmate/data/remediate-f1-f2-settlement/repro-green.txt.

Minimal Fix Details

  1. main/routes/bills.ts (validatePaymentFields):
    • Allow amount === 0 and amount === '0' so zero-amount requests reach preparePaymentBatch (which validates that positive balances cannot tender zero, while zero-balance/paid bills proceed to batch processing).
  2. main/routes/bills.ts (applyPaymentBatch):
    • Capture wasAlreadyPaid = bill.payment_status === 'paid'.
    • If wasAlreadyPaid && prepared.length === 0: return cached bill with loyaltyPointsEarned: 0, persist idempotency response if an idempotency key was supplied and not yet recorded, and skip kitchen delivery checks and database mutations.
    • If !wasAlreadyPaid && prepared.length === 0: include ...(kitchenStatus.overridden ? { kitchenDeliveryOverridden: true } : {}) in the result and persist the payment_idempotency row inside the transaction before returning.
  3. main/routes/bills.ts (POST /:id/payment and POST /:id/payments):
    • Add isAlreadyPaidNoOp checks skipping checkKitchenDeliveryStatus and preVerifyKitchenDeliveryPin when billRow.payment_status === 'paid' and no positive payment amount is submitted.

Invariant and Safety Disclosures

  • Database migrations: None. Schema remains unchanged.
  • Permissions: Unchanged. Role and authorization checks are preserved (including open order visibility invariant).
  • API payloads: Backward compatible. Zero-balance settlement now persists idempotency records and returns kitchenDeliveryOverridden: true when a kitchen delivery override was performed.
  • Financial calculations: Unchanged for active settlements. Already-paid no-op requests no longer re-award loyalty points or insert redundant ledger rows.
  • Telemetry behavior: Unchanged.

Verification

  • npx oxfmt --write and npx oxfmt --check passed cleanly across modified and new files.
  • npm run lint (0 errors)
  • npm run lint:budget (backend: 998/1000, frontend: 0/5)
  • npm run build (compiled clean)
  • npm run test:script-coverage (245 reachable scripts verified)
  • npm run test:bills-settlement-idempotency (64/64 passed, 0 failed)
  • npm test (full suite executed and passed)

@coderabbitai

coderabbitai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration
  • Configuration used: Repository: FreeOpenSourcePOS/FloCafe/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a456dc4f-3a9b-4e3b-ae2f-821047d65a44

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@khaira777

Copy link
Copy Markdown
Contributor Author

@greptile review

@greptile-apps

greptile-apps Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The changes affect bill settlement and loyalty within the payment workflow.

The PR appears safe to merge, with two non-blocking improvements needed in the regression tests.

Findings

  1. P2 Replay checks miss changed responses ▶
  2. P2 Failed-attempt recovery goes untested ▶

Summary

The PR stops zero-amount calls on paid bills from repeating loyalty and kitchen work. It also saves zero-balance settlement responses for safe retries.

  • Zero-amount requests on paid bills return without repeating settlement work.
  • Zero-balance settlements save keyed replies and report kitchen overrides.
  • Concurrency tests check that canceled orders stay canceled during payment.

Review was based on code inspection. Tests were not run.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Payment request] --> B{Saved response exists?}
  B -->|Yes| C[Return saved response]
  B -->|No| D[Validate payment]
  D --> E{Already paid with no tender?}
  E -->|Yes| F[Save and return no-op response]
  E -->|No| G[Check kitchen delivery and approval]
  G --> H[Settle bill inside transaction]
  H --> I[Save and return settlement response]
Loading

Reviews (1) · Last reviewed commit: "fix(billing): remediate loyalty re-award..." · Reviewed by Greptile

@khaira777 khaira777 changed the title fix(billing): remediate loyalty re-award and zero-balance idempotency (#1241, #1205) fix(billing): remediate loyalty re-award and zero-balance idempotency Oct 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant