Skip to content

fix(billing): expose payment correction eligibility before approval - #1417

Merged
khaira777 merged 1 commit into
mainfrom
codex/audit-payment-correction
Oct 31, 2026
Merged

khaira777 merged 1 commit into
mainfrom
codex/audit-payment-correction

Conversation

@khaira777

Copy link
Copy Markdown
Contributor

Summary

Addresses release audit finding F-5 for payment method correction UX and safety:

  • Exposes can_correct_payment_method and reason (shift_closed, day_closed, bill_refunded, bill_not_paid, etc.) directly on bill and order hydration payloads so the frontend can check eligibility before prompting for manager PIN approval.
  • Hardens business-day and timezone calculation to fall back safely to configured timezone or UTC when store regional settings are unconfigured, preventing 500 errors on minimal/unconfigured databases.
  • Updates OrderDetailPanel and CorrectPaymentMethodModal to provide clear, disabled-state feedback rather than requesting credentials only to fail after submission.

Changes

  • main/routes/bills.ts: Implement paymentMethodCorrectionEligibility(db, bill) returning correctable boolean and per-line eligibility. Gracefully handle unconfigured regional settings in resolveBillBusinessDate.
  • main/routes/orders.ts: Wire correction eligibility into batchHydrateOrders.
  • frontend/src/components/orders/OrderDetailPanel.tsx & CorrectPaymentMethodModal.tsx: Check eligibility before manager override prompt.
  • frontend/src/lib/types.ts: Add payment_method_correction types.
  • frontend/src/locales/*.json: Add translation keys across all 24 locales.
  • tests/payment-method-correction.test.ts: Add unit assertions for correction eligibility, role gating, and unconfigured regional fallback.

Stack

Verification

  • npm run test:payment-method-correction: Passed (154/154)
  • npm run test:customer-display-feed: Passed
  • Playwright payment correction test (e2e/orders-master-detail.spec.ts): Passed

@coderabbitai

coderabbitai Bot commented Oct 31, 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

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

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Expose payment correction eligibility before manager approval

🐞 Bug fix ✨ Enhancement 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Exposes bill- and payment-line eligibility on bill reads and hydrated orders, with reasons for
 ineligibility.
• Disables unavailable corrections and checks fresh bill eligibility before requesting a manager
 PIN.
• Falls back to configured timezone or UTC when regional settings are missing.
Diagram

sequenceDiagram
    actor Staff
    participant Panel as Order Panel
    participant Orders as Orders API
    participant Check as Eligibility Check
    participant Data as Billing Data
    participant Modal as Correction Modal
    participant Bills as Bills API
    Panel->>Orders: Load hydrated order
    Orders->>Check: Evaluate embedded bills
    Check->>Data: Check refunds and shifts
    Check-->>Orders: Return line eligibility
    Orders-->>Panel: Return eligible bills
    Staff->>Panel: Open correction
    Panel->>Modal: Show available bills
    Modal->>Bills: Fetch fresh bill
    Bills->>Check: Recheck eligibility
    Bills-->>Modal: Return current eligibility
    Staff->>Modal: Submit approved change
    Modal->>Bills: Patch payment method
    Bills->>Check: Validate within write
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Fetch eligibility only when correction is opened
  • ➕ Avoids eligibility queries for bills in routine order hydration.
  • ➖ Cannot disable the order-panel action before opening the modal.
  • ➖ Requires an additional request to show initial availability.

Recommendation: Keep the shared eligibility check across reads and writes: it lets the UI warn early without treating read-time results as authorization. Consider on-demand eligibility if the added queries materially affect large order-list reads.

Files changed (32) +491 / -221

Enhancement (2) +7 / -0
types.tsType bill correction eligibility +5/-0

Type bill correction eligibility

• Adds optional bill-level eligibility, a nullable reason, and indexed per-line eligibility to the frontend Bill type.

frontend/src/lib/types.ts

orders.tsInclude correction eligibility in hydrated orders +2/-0

Include correction eligibility in hydrated orders

• Computes eligibility for each hydrated bill so order detail responses can indicate correction availability before opening the modal.

main/routes/orders.ts

Bug fix (3) +316 / -220
CorrectPaymentMethodModal.tsxGate correction inputs on fresh bill eligibility +58/-24

Gate correction inputs on fresh bill eligibility

• Fetches current bill eligibility before enabling approval inputs, selects an eligible original payment-line index, and disables ineligible bills and lines. Clears loaded eligibility and refreshes it after a failed correction.

frontend/src/components/orders/CorrectPaymentMethodModal.tsx

OrderDetailPanel.tsxShow disabled correction actions for ineligible bills +25/-17

Show disabled correction actions for ineligible bills

• Uses hydrated bill eligibility to disable correction controls and display an unavailable message while retaining the owner/manager role gate.

frontend/src/components/orders/OrderDetailPanel.tsx

bills.tsShare correction eligibility between bill reads and writes +233/-179

Share correction eligibility between bill reads and writes

• Computes bill and line eligibility from payment, refund, business-day, shift, and split-sibling state; includes it in bill detail responses and reuses it during correction writes. Falls back to the configured timezone or UTC when regional settings are unconfigured.

main/routes/bills.ts

Tests (2) +142 / -1
orders-master-detail.spec.tsTest fresh eligibility and mixed-line selection +77/-0

Test fresh eligibility and mixed-line selection

• Verifies approval inputs stay disabled during a fresh bill fetch, an eligible second line keeps its original index, and a failed correction triggers another eligibility read.

frontend/e2e/orders-master-detail.spec.ts

payment-method-correction.test.tsCover eligibility reasons and read payloads +65/-1

Cover eligibility reasons and read payloads

• Tests eligible and ineligible bill reads, indexed mixed payment lines, hydrated order bills, and missing regional configuration. Retains correction-flow and role-gating coverage.

tests/payment-method-correction.test.ts

Documentation (1) +2 / -0
api.mdDocument advisory correction eligibility metadata +2/-0

Document advisory correction eligibility metadata

• Describes bill-level and indexed payment-line eligibility on bill detail and hydrated orders. Clarifies that writes still enforce current eligibility, permissions, and approval.

docs/reference/api.md

Other (24) +24 / -0
ar.jsonAdd Arabic correction-unavailable message +1/-0

Add Arabic correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/ar.json

bn.jsonAdd Bengali correction-unavailable message +1/-0

Add Bengali correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/bn.json

de.jsonAdd German correction-unavailable message +1/-0

Add German correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/de.json

en.jsonAdd English correction-unavailable message +1/-0

Add English correction-unavailable message

• Adds guidance to check refunds, wallet payments, business days, and shifts across split bills.

frontend/src/lib/i18n/messages/en.json

es.jsonAdd Spanish correction-unavailable message +1/-0

Add Spanish correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/es.json

fa.jsonAdd Persian correction-unavailable message +1/-0

Add Persian correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/fa.json

fil.jsonAdd Filipino correction-unavailable message +1/-0

Add Filipino correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/fil.json

fr.jsonAdd French correction-unavailable message +1/-0

Add French correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/fr.json

hi.jsonAdd Hindi correction-unavailable message +1/-0

Add Hindi correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/hi.json

id.jsonAdd Indonesian correction-unavailable message +1/-0

Add Indonesian correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/id.json

it.jsonAdd Italian correction-unavailable message +1/-0

Add Italian correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/it.json

ja.jsonAdd Japanese correction-unavailable message +1/-0

Add Japanese correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/ja.json

ko.jsonAdd Korean correction-unavailable message +1/-0

Add Korean correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/ko.json

ne.jsonAdd Nepali correction-unavailable message +1/-0

Add Nepali correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/ne.json

nl.jsonAdd Dutch correction-unavailable message +1/-0

Add Dutch correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/nl.json

pt.jsonAdd Portuguese correction-unavailable message +1/-0

Add Portuguese correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/pt.json

ru.jsonAdd Russian correction-unavailable message +1/-0

Add Russian correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/ru.json

sq.jsonAdd Albanian correction-unavailable message +1/-0

Add Albanian correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/sq.json

th.jsonAdd Thai correction-unavailable message +1/-0

Add Thai correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/th.json

tr.jsonAdd Turkish correction-unavailable message +1/-0

Add Turkish correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/tr.json

ur.jsonAdd Urdu correction-unavailable message +1/-0

Add Urdu correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/ur.json

vi.jsonAdd Vietnamese correction-unavailable message +1/-0

Add Vietnamese correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/vi.json

zh-tw.jsonAdd Traditional Chinese correction-unavailable message +1/-0

Add Traditional Chinese correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/zh-tw.json

zh.jsonAdd Simplified Chinese correction-unavailable message +1/-0

Add Simplified Chinese correction-unavailable message

• Adds localized guidance for an unavailable payment correction.

frontend/src/lib/i18n/messages/zh.json

@qodo-code-review

qodo-code-review Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Malformed payment lines break order reads ✓ Resolved
Description
paymentMethodCorrectionEligibility marks a null payment entry as invalid but later accesses
line.method without guarding against null. A paid bill with payment_details containing [null]
makes its bill read fail with HTTP 500, can fail an entire hydrated order page, and makes a
correction request return 500 instead of the former validation error.
Code

main/routes/bills.ts[R5966-5967]

+    if (!reason && String(line.method || "").toLowerCase() === "wallet")
+      reason = "wallet_method_immutable";
Relevance

●●● Strong

Null is explicitly classified invalid, but later dereferenced; this is a direct reliability bug.

PR-#1019
PR-#1392

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The parser retains array elements, including null. The new read and write callers both invoke the
helper, whose final method check dereferences the entry despite the earlier invalid-line check.

main/routes/bills.ts[5834-5844]
main/routes/bills.ts[5912-5916]
main/routes/bills.ts[5966-5968]
main/routes/bills.ts[1049-1053]
main/routes/orders.ts[1322-1328]
main/routes/bills.ts[6263-6265]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Parsed payment arrays can contain null entries. Eligibility detects an invalid entry but later dereferences it, causing bill and order reads and correction requests to fail.
## Fix Focus Areas
- main/routes/bills.ts[5912-5968]
## Recommended Fix
Stop processing invalid payment entries after assigning `payment_line_not_found`, or use a null-safe method lookup. Preserve each original payment index and add coverage for `[null]` on both read and correction paths.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Cash corrections can falsely report success ✓ Resolved
Description
The modal wraps an object-shaped payment_details value for display, but its fresh-bill effect
treats that same value as having no lines and defaults the replacement method to cash. For an
eligible single cash payment stored as an object, submitting the untouched default can take the
server’s same-method replay path, leaving the payment unchanged while the modal displays a success
toast.
Code

frontend/src/components/orders/CorrectPaymentMethodModal.tsx[R87-90]

+      const index = bill.payment_method_correction.lines.find((line) => line.correctable)?.index ?? 0;
+      const lines = Array.isArray(bill.payment_details) ? bill.payment_details : [];
+      setLoadedBill(bill);
+      setSelectedIndex(index);
Relevance

●●● Strong

Clear deterministic defaulting bug can trigger same-method replay and falsely show success.

PR-#1210
PR-#733

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The frontend explicitly supports an object for rendering, while the new effect excludes it when
choosing defaults. The server accepts that object shape for eligibility and returns a replay without
changing the bill when method and transaction details match.

frontend/src/components/orders/CorrectPaymentMethodModal.tsx[47-65]
frontend/src/components/orders/CorrectPaymentMethodModal.tsx[87-95]
frontend/src/components/orders/CorrectPaymentMethodModal.tsx[170-187]
main/routes/bills.ts[5834-5843]
main/routes/bills.ts[6476-6534]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The fresh-bill effect ignores a single payment object when choosing the replacement-method default. An eligible cash line can consequently submit as an unchanged cash payment and appear successful.
## Fix Focus Areas
- frontend/src/components/orders/CorrectPaymentMethodModal.tsx[78-95]
- frontend/src/components/orders/CorrectPaymentMethodModal.tsx[47-50]
## Recommended Fix
Use index-preserving normalization of fetched payment details in both the effect and rendering path. Initialize the replacement method and transaction ID from the eligible line, including when `payment_details` is one object, and test that shape.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Order list loads slow down with many paid bills 🐞 Bug ➹ Performance
Description
batchHydrateOrders calls paymentMethodCorrectionEligibility for each bill instead of batching
its refund, split-sibling, cash-session, settings, and closed-day lookups. On GET /orders pages of
up to 500 orders, paid bills can add hundreds or thousands of synchronous SQLite queries, and
websocket- or polling-triggered refreshes repeat that work on the single-threaded server.
Code

main/routes/orders.ts[1325]

+    parsed.payment_method_correction = paymentMethodCorrectionEligibility(db, parsed);
Relevance

●● Moderate

Performance concern is plausible, but history lacks a closely matching rejection or acceptance
precedent.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
batchHydrateOrders loads bills and other order data with batched IN (...) queries, but its new
per-bill call invokes a helper that performs multiple database and settings lookups. The order
endpoint permits up to 500 orders per page, and the orders page re-fetches the list after websocket
events and polling ticks, so those per-bill lookups recur on large pages and refreshes.

main/routes/orders.ts[1282-1330]
main/routes/bills.ts[5846-5911]
main/routes/orders.ts[832-884]
main/routes/orders.ts[804-832]
main/routes/orders.ts[1307-1328]
main/routes/bills.ts[5850-5858]
main/routes/bills.ts[5871-5909]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`batchHydrateOrders` calls `paymentMethodCorrectionEligibility(db, parsed)` once per bill. Its refund, split-sibling, session, settings, and closed-day lookups turn batched order reads into repeated synchronous queries, including on list refreshes.

## Fix Focus Areas
- main/routes/orders.ts[1307-1330]
- main/routes/bills.ts[5846-5978]

## Recommended Fix
Add a batched eligibility variant that loads refunds for all bill IDs, split-group siblings, and referenced `cash_sessions` using batched `IN (...)` queries, then computes each bill’s result in memory. Compute shared inputs once, including `isPerStaffShiftsEnabled`, `getOpenSession`, today’s business date, timezone, and business-day start time, and memoize `closedDayExists` by date. Use the batched variant from `batchHydrateOrders`; keep the single-bill helper as a thin wrapper for bill detail reads and PATCH write-time validation. Eligibility may be computed only for bills with `payment_status === 'paid'`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #1416
✅ Compliance rules (platform): 5 rules
✅ Cross-repo context — repo relationships
Review mode: Auto: 🧠 Deep: Payment eligibility logic spans billing, orders, UI, concurrency, and timezone paths.

Grey Divider

Tip of the day
💡 Did you know, you can keep summaries lean with Findings visible per group, which tucks the rest behind a View link

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread main/routes/bills.ts Resolved
Comment thread main/routes/orders.ts Resolved
@khaira777
khaira777 force-pushed the codex/audit-payment-correction branch from 408bb22 to d8f53c0 Compare October 31, 2026 21:26
@khaira777
khaira777 force-pushed the codex/audit-payment-queue branch 2 times, most recently from d873237 to c3f5745 Compare October 31, 2026 23:08
@khaira777
khaira777 changed the base branch from codex/audit-payment-queue to main October 31, 2026 23:08
@khaira777
khaira777 force-pushed the codex/audit-payment-correction branch from d8f53c0 to 7a325df Compare October 31, 2026 23:17
@khaira777
khaira777 merged commit 2779a62 into main Oct 31, 2026
23 checks passed
@khaira777
khaira777 deleted the codex/audit-payment-correction branch October 31, 2026 23:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant