Skip to content

fix(billing): zero-balance settlement, zero-total split siblings, refunded sibling completion - #812

Merged
khaira777 merged 9 commits into
mainfrom
fix/zero-balance-bill-settlement
Sep 22, 2026
Merged

khaira777 merged 9 commits into
mainfrom
fix/zero-balance-bill-settlement

Conversation

@khaira777

@khaira777 khaira777 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Three settlement edge cases leave bills stuck unpaid (or leave the parent order stuck incomplete) after a legitimate discount or split-check mutation. In every case the data is correct on the bill row, but the settle path or the order-completion path treats the row as already finished (or still outstanding) and refuses to move forward.

  1. Discounts that drive balance to 0 cannot be settled. Order discount, bill applyDiscount, and item discount can each reduce balance to 0 while payment_status is still unpaid / partial. The follow-up settle then hits preparePaymentBatch's remainingCents <= 0 branch and throws 400 "Bill is already fully paid", even though the bill was never marked paid. The order never completes and the table never frees.
  2. Zero-total split siblings block completion forever. Cancelling an item after split-check can zero one guest check. That sibling has payment_status = 'paid' with paid_amount = 0 (or stays unpayable), so:
    • syncUnpaidBillsForOrder rejects further modifications with 409 ("split check is paid").
    • The unpaid-sibling query for order completion never sees a clear path to complete the parent order.
    • Subsequent item cancels on the order are blocked by the paid-order guard.
  3. Refunded / partially refunded siblings block order completion forever. A refunded (or partially refunded) guest check matches payment_status != 'paid', so when the remaining sibling is paid the parent order still looks incomplete and never flips to completed.
  4. Restore after all-zero-closed splits does not re-sync. If every split bill was zero-closed (paid, paid_amount = 0) while the order was still open, restoring an item hits the early return in syncUnpaidBillsForOrder and leaves the zero-closed bills stuck.
  5. Settle attempt on a refunded bill corrupts payment_status. Refunds never reduce paid_amount, so a fully paid then fully refunded bill still has remainingCents = 0. The empty-batch settle path then lets applyPaymentBatch overwrite refunded back to paid.

Root cause

Area Gap
preparePaymentBatch remainingCents <= 0 always threw already fully paid when paid_amount was 0, with no path for "discount zeroed the rest with no money in"; no guard for refunded / partially_refunded before the empty-batch return
syncUnpaidBillsForOrder Treated any payment_status !== 'unpaid' || paid_amount > 0 split bill as paid, so zero-closed siblings locked modifications; also never auto-closed a total-0 sibling; early-returned when all bills were paid even if they were zero-closed
Restore / cancel / paid-order guards Any non-unpaid status (including zero-closed paid with paid_amount = 0) blocked legitimate mutations
Order completion sibling query payment_status != 'paid' includes refunded and partially_refunded, so those siblings permanently blocked completion

Fix (surgical)

  1. Zero-balance settle path. When remainingCents <= 0, return an empty prepared batch (instead of throwing) so applyPaymentBatch can mark the bill paid and complete the order. Applies whether or not any money was previously paid.
  2. Zero-total sibling auto-close. During unpaid-bill re-sync, a bill with total <= 0 && balance <= 0 is marked paid (with paid_at). A previously zero-closed bill whose total returns is reversed to unpaid. The split-modify guard, restore's paid-order check, and the cancel-item paid-order check all ignore zero-closed bills (paid_amount = 0). Zero-closed bills are included in the unpaid-bill filter so restore re-syncs them.
  3. Refunded / partially refunded sibling exclusion. Order-completion sibling query uses payment_status NOT IN ('paid', 'refunded', 'partially_refunded') so a refunded or partially refunded guest check no longer blocks completing the order when the remaining check is paid.
  4. Refunded settle guard. preparePaymentBatch rejects refunded / partially_refunded bills with 400 "Bill has been refunded" before the empty-batch path, so a settle attempt can no longer overwrite the refund status.

Test evidence (post-fix)

node tests/run-electron-node-test.cjs tests/issue-zero-balance-settlement.test.ts
Results: 80/80 passed, 0 failed
ALL PASSED

Scenarios covered:

  • Order-discount / bill-discount / item-discount each drive balance to 0, then settle succeeds (paid + order completed + table freed).
  • Full discount with no prior payment (paid_amount = 0) settles and completes the order.
  • Zero-total split sibling auto-closes as paid; paying the remaining sibling completes the order and frees the table.
  • Item cancels remain possible after a sibling zero-closes.
  • Refunded split sibling does not block parent order completion once the other sibling is paid.
  • Partially refunded split sibling does not block parent order completion once the other sibling is paid.
  • Restore re-syncs zero-closed split bills back to unpaid with a positive total when an item is restored on an open order.
  • Settle attempt on a fully refunded bill returns 400 and leaves payment_status = 'refunded'.

Focused suites (all green): refunds 59/59, refund-completed-orders 18/18, integration-payments 33/33, discount-system 37/37, issue-24-cancel-item-checkout 25/25.

Quality gates: npm run lint:backend → 0 errors (1000/1000 budget), npm run build → green, node scripts/ci/validate-test-script-coverage.cjs → 172 reachable / 6 excluded.

Notes / residual risks

  • Auto-mark on discount (vs allow-settle) was intentionally not used: it would make the subsequent settle call return already paid and break the proven repro path.
  • Permanent test wired as test:issue-zero-balance-settlement and appended to the root test chain.
  • No merge / auto-merge.

Base: f7cc3f32 (origin/main).

Summary by CodeRabbit

  • Bug Fixes
    • Improved bill settlement for refunded and partially refunded checks.
    • Zero-balance bills now settle and close correctly, including split bills and fully discounted orders.
    • Split-bill synchronization now correctly handles checks marked paid with no payment amount.
    • Refunded checks no longer prevent orders from completing.
    • Cancellation and item restoration now correctly account for zero-balance and partially paid bills.
    • Payments are blocked for refunded bills, while already-settled balances return without errors.

@coderabbitai

coderabbitai Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • package.json is excluded by !package.json

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

⚙️ Run configuration

Configuration used: Repository: FreeOpenSourcePOS/FloCafe/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: d40cba00-fba4-4779-b582-a99801aef9a1

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: FreeOpenSourcePOS/FloCafe/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 4354c2fc-d3fd-46f7-ba89-a1791e2dd1ff

📥 Commits

Reviewing files that changed from the base of the PR and between 9fdd192 and 5eb9d22.

⛔ Files ignored due to path filters (1)
  • package.json is excluded by !package.json
📒 Files selected for processing (3)
  • main/routes/bills.ts
  • main/routes/index.ts
  • tests/issue-zero-balance-settlement.test.ts

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

Bill settlement now handles zero balances, refunded states, and partial payments. Split-bill synchronization, order completion, cancellation, restoration, and payment validation use the updated status rules. An Electron integration test covers these workflows.

Changes

Billing and Order Settlement

Layer / File(s) Summary
Billing state and settlement rules
main/routes/bills.ts
Split-bill synchronization updates zero-balance checks. Refunded bills reject payment preparation. Refunded siblings no longer block order completion.
Item cancellation and restoration validation
main/routes/index.ts
Cancellation and restoration now evaluate payment status together with positive paid amounts.
Settlement workflow integration coverage
tests/issue-zero-balance-settlement.test.ts
The Electron integration test covers zero-balance settlement, split checks, refunds, discounts, cancellation, restoration, partial payments, and cleanup.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~30 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 5eb9d

Billing now supports legitimate zero-balance settlement while rejecting refunded payments and unsafe restoration after positive partial payment. No unresolved merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the problem, root cause, fix, test coverage, and verification results. However, it omits several required template sections, including Scope, Compatibility & data safety, Cros… Add the missing template sections. Document the intentional scope, database and migration impact, user-visible and offline/network impact, affected cross-cutting surfaces, screenshots status if not applicable, and completed contributor chec…
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 18 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main billing and split-sibling settlement fixes. It is specific and concise enough for repository history.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description explains the problem, root cause, fix, test coverage, and verification results. However, it omits several required template sections, including Scope, Compatibility & data safety, Cross-cutting surfaces, and the Contributor checklist.

Resolution

Add the missing template sections. Document the intentional scope, database and migration impact, user-visible and offline/network impact, affected cross-cutting surfaces, screenshots status if not applicable, and completed contributor checklist items. Include the related issue or state that none exists.

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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.

@itoqa

itoqa Bot commented Sep 22, 2026

Copy link
Copy Markdown

Ito QA test results
Commit: edb3e58: 18 test cases ran, 1 failed ❌, 17 passed ✅.

Summary

Coverage spans core order and billing workflows, including split bills, payments, refunds, discounts, cancellations, restoration, table availability, and concurrent settlement. It exercises both normal customer flows and edge-case protections around paid, refunded, zero-value, and partially paid orders, with overall behavior healthy except for a payment-state protection gap.

Not safe to merge yet — a high-severity business-logic defect allows order contents and balances to change after a partial payment, creating incorrect amounts that may require manual correction. No unrelated findings alter this merge-blocking assessment.

Tests run by Ito

View full run

Result Severity Type Description
❌ High severity Protection The restore request returned HTTP 200. The cancelled item changed to pending, and the bill total changed from 60 to 380 while paid_amount stayed at 30; the expected response was HTTP 400 with the item still cancelled.
✅ — General After one split bill was refunded and the order was refreshed, paying the remaining bill completed the order and made the dine-in table available. The refunded sibling stayed refunded and unchanged.
✅ — General After one split-order item was paid, cancelling another item was rejected with a clear conflict response. A follow-up restore changed nothing because the item was never cancelled, and the order, bill, payment, and item states stayed the same.
✅ — General Two sessions tried to pay the same zero-balance bill at the same time. One request succeeded, the other was rejected as already paid, and the final bill and order stayed consistent.
✅ — General Two payment requests were sent at the same time. One succeeded and the other was rejected, while the bill stayed paid with a zero balance and the order was completed without a duplicate payment.
✅ — Cancel After one split item was cancelled, the order stayed open while the other item remained active. Cancelling the remaining item returned success instead of a conflict, and the order was cancelled only after both items were cancelled.
✅ — Protection Cancelling the other item was rejected with HTTP 409 after a sibling received a positive payment. The order items and bill totals stayed unchanged.
✅ — Protection Cancelling an item was rejected with HTTP 409 when the other split bill had been refunded, and the refunded bill and order totals stayed unchanged.
✅ — Protection After a 10% discount, the bill total fell from 380 to 342, the 100 payment stayed recorded, and the remaining balance became 242.
✅ — Refund The refunded split bill stayed terminal. Paying the remaining bill completed the order and made table-zb available.
✅ — Refund The partially refunded guest check stayed terminal, and paying the remaining check completed the order and freed table-zb.
✅ — Restore The restore flow could not be run because the local app stopped before the browser or API could connect.
✅ — Rev Verified acceptable by independent adversarial review: the reported expectation does not match what the code actually promises. Review notes: The code confirms the reported HTTP 200 mechanism, but not the claimed obligation: exact matching transaction requests are an explicit idempotent-replay case, whereas the PR test and refunded guard cover a new settlement request without a transaction ID. Nothing cited requires the replay exception to be discarded after a refund, and the replay branch itself is not shown as introduced by this PR, s…
✅ — Settlement A fully discounted dine-in bill settled successfully with no positive payment. The bill was marked paid with paid_amount 0, the order was completed, and table-zb became available.
✅ — Settlement A second payment attempt was rejected with HTTP 400 and the message 'Bill is already paid'. The bill stayed paid and its paid amount stayed at 1000.
✅ — Settlement The refunded bill rejected the owner's repeat settlement request with HTTP 400 and kept its refunded status and paid amount unchanged.
✅ — Split Cancelling the 400-unit item made its sibling a zero-total paid bill without a payment. Paying the 1000-unit sibling completed the order and made the table available.
✅ — Split After one split item was cancelled, the other 1000-unit sibling stayed unpaid and the parent order remained pending.

Tip

Reply with @itoqa to send us feedback on this test run.

Comment thread main/routes/index.ts Resolved
@itoqa

itoqa Bot commented Sep 22, 2026

Copy link
Copy Markdown

Ito QA test results
Ito Diff Report — edb3e58 → 3706624: 8 test cases ran, 1 fixed ✅, 7 passing ✅.

Diff Summary

Coverage focuses on order-item restoration and payment protection, including successful restoration for zero-balance cases, rejection of restores for paid or partially paid orders, retry safety, preservation of related order and bill state, and isolation between separate orders. These are primarily business-logic happy paths and edge or adversarial cases around payments and repeated actions.

Safe to merge — the exercised payment and restoration behaviors are passing, including the previously failing paid-order protection, with no PR-attributable regressions or unresolved failures. Broader previously passing scenarios were not exercised in this run, but they are a coverage caveat rather than a merge blocker.

Tests run by Ito

View full run

Result State Severity Type Description
✅ ❌->✅ Fixed — Protection The restore request was rejected with HTTP 400, and the cancelled item and paid order state stayed unchanged.
✅ Passing — General Restoring the cancelled item was rejected when one associated bill had a positive partial payment, even though another bill had no collected amount. The item and all associated bills stayed unchanged.
✅ Passing — General The restore request was rejected, and the cancelled item, order totals, inventory, and positive partial bill stayed unchanged.
✅ Passing — General A second restore attempt was rejected, and the cancelled item and partial bill stayed unchanged.
✅ Passing — Restore A cancelled item could not be restored after the order received a positive partial payment. The request returned HTTP 400 and the bill stayed partial.
✅ Passing — Restore Restoring a cancelled item succeeded when the bill was marked partial with either zero or no collected amount. The item was restored and the bill was recalculated.
✅ Passing — Rev Trying to restore an item after the order was fully paid returned HTTP 400. The item stayed cancelled, and the bill stayed paid with its positive amount.
✅ Passing — Rev A partial payment on the first order did not block restoring a cancelled item on the second order. The second item became pending, and its bill stayed unpaid with no collected amount.
⏸️ Skipped — General After one split bill was refunded and the order was refreshed, paying the remaining bill completed the order and made the dine-in table available. The refunded sibling stayed refunded and unchanged.
⏸️ Skipped — General After one split-order item was paid, cancelling another item was rejected with a clear conflict response. A follow-up restore changed nothing because the item was never cancelled, and the order, bill, payment, and item states stayed the same.
⏸️ Skipped — General Two sessions tried to pay the same zero-balance bill at the same time. One request succeeded, the other was rejected as already paid, and the final bill and order stayed consistent.
⏸️ Skipped — General Two payment requests were sent at the same time. One succeeded and the other was rejected, while the bill stayed paid with a zero balance and the order was completed without a duplicate payment.
⏸️ Skipped — Cancel After one split item was cancelled, the order stayed open while the other item remained active. Cancelling the remaining item returned success instead of a conflict, and the order was cancelled only after both items were cancelled.
⏸️ Skipped — Protection Cancelling the other item was rejected with HTTP 409 after a sibling received a positive payment. The order items and bill totals stayed unchanged.
⏸️ Skipped — Protection Cancelling an item was rejected with HTTP 409 when the other split bill had been refunded, and the refunded bill and order totals stayed unchanged.
⏸️ Skipped — Protection After a 10% discount, the bill total fell from 380 to 342, the 100 payment stayed recorded, and the remaining balance became 242.
⏸️ Skipped — Refund The refunded split bill stayed terminal. Paying the remaining bill completed the order and made table-zb available.
⏸️ Skipped — Refund The partially refunded guest check stayed terminal, and paying the remaining check completed the order and freed table-zb.
⏸️ Skipped — Restore The restore flow could not be run because the local app stopped before the browser or API could connect.
⏸️ Skipped — Rev Verified acceptable by independent adversarial review: the reported expectation does not match what the code actually promises. Review notes: The code confirms the reported HTTP 200 mechanism, but not the claimed obligation: exact matching transaction requests are an explicit idempotent-replay case, whereas the PR test and refunded guard cover a new settlement request without a transaction ID. Nothing cited requires the replay exception to be discarded after a refund, and the replay branch itself is not shown as introduced by this PR, s…
⏸️ Skipped — Settlement A fully discounted dine-in bill settled successfully with no positive payment. The bill was marked paid with paid_amount 0, the order was completed, and table-zb became available.
⏸️ Skipped — Settlement A second payment attempt was rejected with HTTP 400 and the message 'Bill is already paid'. The bill stayed paid and its paid amount stayed at 1000.
⏸️ Skipped — Settlement The refunded bill rejected the owner's repeat settlement request with HTTP 400 and kept its refunded status and paid amount unchanged.
⏸️ Skipped — Split Cancelling the 400-unit item made its sibling a zero-total paid bill without a payment. Paying the 1000-unit sibling completed the order and made the table available.
⏸️ Skipped — Split After one split item was cancelled, the other 1000-unit sibling stayed unpaid and the parent order remained pending.

Tip

Reply with @itoqa to send us feedback on this test run.

- Allow settle when remaining balance is 0 regardless of paid_amount
- Exclude zero-closed bills from cancel-item paid-order guard
- Treat partially_refunded siblings as settled for order completion
- Include zero-closed bills in unpaid-bill re-sync so restore flips them back
The restore guard checked `payment_status = 'paid'` but a partially paid
bill has `payment_status = 'partial'` with `paid_amount > 0`, so the guard
was silently skipped and the cancelled item was restored while a payment
was already recorded against the bill.

Expanded the query to `payment_status IN ('paid', 'partial')` so any
positive-payment state blocks the restore.

Added focused regression test: cancel item → partial pay → restore must
return 400.
@khaira777
khaira777 force-pushed the fix/zero-balance-bill-settlement branch from 3706624 to fe79e7d Compare September 22, 2026 06:03
@khaira777
khaira777 merged commit 88f9fd8 into main Sep 22, 2026
15 checks passed
@khaira777
khaira777 deleted the fix/zero-balance-bill-settlement branch September 22, 2026 06:31
@itoqa

itoqa Bot commented Sep 22, 2026

Copy link
Copy Markdown

Ito QA test results

History reset (rebase or force-push detected). Starting test narrative over.

Commit: cff1fc5: 18 test cases ran, 18 passed ✅.

Summary

Coverage focuses on payment and billing business rules across normal completion flows, zero-balance and refund edge cases, split-bill changes, item cancellation and restoration, and concurrent operations. It also checks that invalid or conflicting actions are rejected while valid orders still complete and tables become available.

Safe to merge — the exercised behaviors are healthy, with no regressions, new failures, or previously reported PR-attributable failures. The reviewed concurrency and cancellation findings are documented intended behavior rather than merge blockers.

Tests run by Ito

View full run

Result Severity Type Description
✅ — General The bill was paid successfully after a full discount reduced its total to zero. The existing 400 payment remained exactly once, and the order was completed.
✅ — General Verified acceptable by independent adversarial review: the observed behavior is intended and documented in this codebase. Review notes: The API obligation is directional: payment already present blocks a new cancellation. These synchronous Express handlers share one better-sqlite3 connection and each completes its transaction without yielding, so nominally simultaneous requests execute in one order; if payment runs first, the cancellation guard rejects it, while if cancellation runs first, the later sibling payment is permitted. T…
✅ — General The refund and the final payment both succeeded when submitted together. The refunded bill stayed refunded, the other bill became paid, and the order completed while the table became available.
✅ — General Two final payment requests were sent at the same time. One succeeded, the other was rejected as already paid, and the order finished with the table available.
✅ — Cancellation Both items were cancelled successfully after one split sibling reached zero. The requests returned HTTP 200 and the split bills stayed paid with zero amounts.
✅ — Cancellation Cancelling an item after a sibling received a positive payment returned HTTP 409, and the target item stayed pending.
✅ — Payment After a bill was fully refunded, a second payment returned HTTP 400 and the bill stayed refunded with only its original payment.
✅ — Payment The second payment was rejected with HTTP 400, and the bill stayed partially refunded without adding another payment.
✅ — Refunds The fully refunded check stayed marked as refunded, the other check was paid, and the order completed with table-zb available.
✅ — Refunds The partially refunded bill stayed marked as partially refunded, the other bill was paid, and the order finished with the table available.
✅ — Restore Restoring the cancelled item returned HTTP 200 and changed it back to pending. Its zero-closed split bill recalculated to 1000, became unpaid, and cleared its paid time.
✅ — Restore Restoring the cancelled item was rejected with HTTP 400, and the item and partial bill stayed unchanged.
✅ — Restore Restoring the cancelled item succeeded with HTTP 200 when the sibling bill was paid with a zero amount. The item returned to pending and the order total recalculated to 1400.
✅ — Rev Verified acceptable by independent adversarial review: the observed behavior is intended and documented in this codebase. Review notes: The mechanism is real and reachable, but the finding turns the downstream synchronization function's error text into an endpoint-wide exact-message requirement. The PR description expressly distinguishes the two guards and says subsequent item cancellations are blocked by the paid-order guard, while the diff deliberately preserves that generic guard and message. The behavior is therefore documente…
✅ — Settlement A fully discounted dine-in order was settled without a positive payment amount. The bill was marked paid, the order was completed, and table-zb became available.
✅ — Settlement A full bill discount reduced the unpaid bill to zero, and settling it succeeded without a positive payment amount. The bill was marked paid with a payment time, while total, paid amount, and balance stayed at zero.
✅ — Split The zero-value sibling was closed after its item was cancelled. The recorded failure came from calling an outdated payment URL; the repository's implemented payment route is POST /api/bills/:id/payment, which is the route used by the focused regression test and the neighboring split checks.
✅ — Split After one split sibling was paid, cancelling an item in the split order returned HTTP 409 as expected.

Tip

Reply with @itoqa to send us feedback on this test run.

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