Skip to content

fix(main): enforce order/bill settlement guards and flat-discount caps - #1312

Merged
khaira777 merged 8 commits into
mainfrom
fm/ship-c7755f35-order-bill-settlement-safety
Oct 23, 2026
Merged

khaira777 merged 8 commits into
mainfrom
fm/ship-c7755f35-order-bill-settlement-safety

Conversation

@khaira777

@khaira777 khaira777 commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Enforce backend order/bill settlement invariants and flat-discount caps in main/routes/orders.ts and main/routes/bills.ts (Issue #1295)

What Changed

  • Restrict POST /api/bills/generate and syncUnpaidBillsForOrder in main/routes/bills.ts to re-sync only unpaid, partial, and partially_paid bills (preserving paid, partially_refunded, and refunded bills except zero-total paid split siblings during split reallocation), and trigger completeExactBalanceSettlement when a re-synced partially paid bill reaches exact zero balance.
  • Enforce active-order and bill-settlement guards in main/routes/orders.ts on PATCH /api/orders/:id/customer, PATCH /api/orders/:id/convert-to-takeaway, and PATCH /api/orders/:orderId/items/:itemId/restore (including orderWriteRateLimit), recomputing non-terminal item taxes from saved tax_snapshot category and behavior rules on customer updates, re-resolving takeaway charges with below_collected_funds validation on dine-in conversion, and recording customer_updated and converted_to_takeaway audit log entries.
  • Add resolveOrderLevelDiscountAmount in main/routes/orders.ts so subtotal-changing mutations scale percentage order discounts while preserving flat order discounts from discount_value capped at the updated subtotal, and update tests/issue-terminal-state-guards.test.ts, docs/architecture/order-lifecycle.md, and docs/reference/api.md.

Risk Assessment

✅ Low: The settlement state guards, exact-balance auto-settlement hooks, customer tax recomputation, and flat order discount clamping/restoration are well-bounded, consistent across order and bill mutation routes, and covered by end-to-end integration assertions.

Testing

Ran the focused integration suites (npm run test:issue-terminal-state-guards and npm run test:issue-exact-balance-settlement), compiled the backend (npm run build), and stood up an isolated live FloCafe Express/SQLite server (http://127.0.0.1:4311) to drive all six settlement-guard, exact-balance auto-settlement, flat-discount clamping/restoration, and customer tax-recomputation scenarios end-to-end, capturing API and SQLite state evidence in live-settlement-safety-verification.json (no visual screenshot artifacts were captured because this change only modifies backend Express routes and docs with no UI or renderer changes).

  • Live validation: ✅ go - 6 of 6 scenarios driven live against the product
Scenario Result Live Evidence
Settled zero-paid and refunded bills resist resync overwrites during bill generation and order-to-bill synchronization ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-safety-verification.json (scenario1) and npm run test:issue-terminal-state-guards
Adversarial dine-in to takeaway conversion rejects refunded bills and conversions that drop total below collected payments (below_collected_funds) ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-safety-verification.json (scenario2) and npm run test:issue-terminal-state-guards
Exact-balance auto-settlement completes the bill and order when takeaway conversion, item edit, or bill re-generation brings a partially paid bill to zero balance ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-safety-verification.json (scenario3) and npm run test:issue-terminal-state-guards
Adversarial cancelled-item restore on a zero-total paid or refunded bill is rejected with 400 ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-safety-verification.json (scenario4) and npm run test:issue-terminal-state-guards
Flat order-level discount stays fixed across item price overrides/discounts, clamps to subtotal on item cancellation, and restores from discount_value on item restore ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-safety-verification.json (scenario5) and npm run test:issue-terminal-state-guards
Customer reassignment rejects orders with partial/settled/refunded bills and recomputes item/order/bill taxes from saved item tax snapshots on active unpaid orders ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-safety-verification.json (scenario6) and npm run test:issue-terminal-state-guards
Evidence: Live HTTP API and SQLite state verification transcript (Issue #1295)

{ "serverBaseUrl": "http://127.0.0.1:4311",
"scenario1": { "zeroPaidBill": { "id": 1, "payment_status": "paid", "total": 0, "balance": 0 }, "partiallyRefundedBill": { "id": 2, "payment_status": "partially_refunded", "total": 1000 } }, "scenario2": { "belowCollectedFundsResponse": { "status": 409, "data": { "error": "Cannot convert order below already collected payment amount", "code": "below_collected_funds", "display_code": "below_collected_funds" } }, "refundedBillResponse": { "status": 409, "data": { "error": "Cannot convert an order with a paid or refunded bill" } } }, "scenario3": { "convertToTakeawayExactSettle": { "bill": { "payment_status": "paid", "total": 1000, "paid_amount": 1000, "balance": 0 }, "order": { "status": "completed", "type": "takeaway", "table_id": null, "total": 1000 }, "tableStatus": "available", "audit": { "action": "converted_to_takeaway" } }, "itemEditExactSettle": { "bill": { "payment_status": "paid", "total": 400, "paid_amount": 400, "balance": 0 }, "order": { "status": "completed", "total": 400 } } }, "scenario4": { "restoreOnZeroPaidBill": { "status": 400, "data": { "error": "Cannot restore items on a paid order" } } }, "scenario5": { "afterPriceOverride": { "subtotal": 1200, "discount_amount": 600, "discount_value": 600, "total": 600 }, "afterCancelClamped": { "subtotal": 200, "discount_amount": 200, "discount_value": 600, "total": 0 }, "afterRestoreFromDiscountValue": { "subtotal": 1200, "discount_amount": 600, "discount_value": 600, "total": 600 } }, "scenario6": { "blockedOnPartialBill": { "status": 409, "data": { "error": "Cannot change customer once a bill has payments, a split, or a refund" } }, "recomputedOrder": { "id": 9, "customer_id": "cust-live-2", "tax_amount": 50, "total": 1050 }, "syncedBill": { "customer_id": "cust-live-2", "tax_amount": 50, "total": 1050, "balance": 1050 }, "audit": { "action": "customer_updated" } } }

{
  "startedAt": "2026-10-22T23:13:44.017Z",
  "serverBaseUrl": "http://127.0.0.1:4311",
  "scenarios": {
    "scenario1": {
      "zeroPaidBill": {
        "id": 1,
        "payment_status": "paid",
        "total": 0,
        "balance": 0
      },
      "partiallyRefundedBill": {
        "id": 2,
        "payment_status": "partially_refunded",
        "total": 1000
      }
    },
    "scenario2": {
      "belowCollectedFundsResponse": {
        "status": 409,
        "data": {
          "error": "Cannot convert order below already collected payment amount",
          "code": "below_collected_funds",
          "display_code": "below_collected_funds"
        }
      },
      "refundedBillResponse": {
        "status": 409,
        "data": {
          "error": "Cannot convert an order with a paid or refunded bill"
        }
      }
    },
    "scenario3": {
      "convertToTakeawayExactSettle": {
        "bill": {
          "payment_status": "paid",
          "total": 1000,
          "paid_amount": 1000,
          "balance": 0,
          "paid_at": "2026-10-22 23:13:44"
        },
        "order": {
          "status": "completed",
          "type": "takeaway",
          "table_id": null,
          "total": 1000
        },
        "tableStatus": "available",
        "audit": {
          "action": "converted_to_takeaway",
          "actor_user_id": "owner-test-001",
          "details_json": "{\"from_type\":\"dine_in\",\"to_type\":\"takeaway\",\"previous_table_id\":\"table-live-2\"}"
        }
      },
      "itemEditExactSettle": {
        "bill": {
          "payment_status": "paid",
          "total": 400,
          "paid_amount": 400,
          "balance": 0,
          "paid_at": "2026-10-22 23:13:44"
        },
        "order": {
          "status": "completed",
          "total": 400
        }
      }
    },
    "scenario4": {
      "restoreOnZeroPaidBill": {
        "status": 400,
        "data": {
          "error": "Cannot restore items on a paid order"
        }
      }
    },
    "scenario5": {
      "afterPriceOverride": {
        "subtotal": 1200,
        "discount_amount": 600,
        "discount_value": 600,
        "total": 600
      },
      "afterCancelClamped": {
        "subtotal": 200,
        "discount_amount": 200,
        "discount_value": 600,
        "total": 0
      },
      "afterRestoreFromDiscountValue": {
        "subtotal": 1200,
        "discount_amount": 600,
        "discount_value": 600,
        "total": 600
      }
    },
    "scenario6": {
      "blockedOnPartialBill": {
        "status": 409,
        "data": {
          "error": "Cannot change customer once a bill has payments, a split, or a refund"
        }
      },
      "recomputedOrder": {
        "id": 9,
        "customer_id": "cust-live-2",
        "tax_amount": 50,
        "total": 1050
      },
      "syncedBill": {
        "customer_id": "cust-live-2",
        "tax_amount": 50,
        "total": 1050,
        "balance": 1050
      },
      "audit": {
        "action": "customer_updated",
        "actor_user_id": "owner-test-001",
        "details_json": "{\"previous_customer_id\":\"cust-live-1\",\"customer_id\":\"cust-live-2\"}"
      }
    }
  },
  "health": {
    "status": "ok",
    "db": "ok",
    "service": "Flo Local API",
    "version": "2.4.7",
    "timestamp": "2026-10-22T23:13:44.346Z"
  },
  "completedAt": "2026-10-22T23:13:44.608Z"
}

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 5 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Adversarial: Triggering POST /api/bills/generate and syncUnpaidBillsForOrder against a zero-total paid bill, a partially_refunded bill, and a refunded bill preserves their settled/refunded status and… ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-and-discount-verification.json and npm run test:issue-terminal-state-guards
Adversarial: Converting a dine-in order to takeaway via PATCH /api/orders/:id/convert-to-takeaway is rejected with 409 when a bill is paid or refunded, or with 409 below_collected_funds when dropping… ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-and-discount-verification.json and npm run test:issue-terminal-state-guards
Converting a dine-in order to takeaway, reducing item quantity via PATCH /api/orders/:orderId/items/:itemId/edit, or re-syncing via POST /api/bills/generate when the updated total equals paid_amount a… ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-and-discount-verification.json and npm run test:issue-terminal-state-guards
Reassigning a customer via PATCH /api/orders/:id/customer rejects completed/cancelled orders (400) and bills with payments, splits, or refunds (409), while on an active unpaid order it recomputes item… ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-and-discount-verification.json and npm run test:issue-terminal-state-guards
Order mutations preserve a flat order discount without proportional scaling, clamp it to the new subtotal when item cancellations/discounts/price overrides drop the subtotal below discount_value, rest… ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-and-discount-verification.json and npm run test:issue-terminal-state-guards
  • npm run test:issue-terminal-state-guards
  • npm run test:issue-exact-balance-settlement
  • npm run test:order-item-cancel-restore
  • npm run test:order-item-edit
  • npm run test:item-price-override
  • npm run test:order-totals-recompute
  • npm run test:orders-authz
  • Live HTTP server verification against main/server.ts + SQLite in an isolated userData directory (~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-and-discount-verification.json)

✅ No issues found.

  • Live validation: ✅ go - 6 of 6 scenarios driven live against the product
Scenario Result Live Evidence
Settled zero-paid and refunded bills resist resync overwrites during bill generation and order-to-bill synchronization ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-safety-verification.json (scenario1) and npm run test:issue-terminal-state-guards
Adversarial dine-in to takeaway conversion rejects refunded bills and conversions that drop total below collected payments (below_collected_funds) ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-safety-verification.json (scenario2) and npm run test:issue-terminal-state-guards
Exact-balance auto-settlement completes the bill and order when takeaway conversion, item edit, or bill re-generation brings a partially paid bill to zero balance ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-safety-verification.json (scenario3) and npm run test:issue-terminal-state-guards
Adversarial cancelled-item restore on a zero-total paid or refunded bill is rejected with 400 ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-safety-verification.json (scenario4) and npm run test:issue-terminal-state-guards
Flat order-level discount stays fixed across item price overrides/discounts, clamps to subtotal on item cancellation, and restores from discount_value on item restore ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-safety-verification.json (scenario5) and npm run test:issue-terminal-state-guards
Customer reassignment rejects orders with partial/settled/refunded bills and recomputes item/order/bill taxes from saved item tax snapshots on active unpaid orders ✅ pass live ~/.no-mistakes/evidence/01M5JTPS1ZVTJTR1KKAGJPC3XD/live-settlement-safety-verification.json (scenario6) and npm run test:issue-terminal-state-guards
  • npm run test:issue-terminal-state-guards
  • npm run test:issue-exact-balance-settlement
  • npm run build
  • Live Express/SQLite server verification on http://127.0.0.1:4311 driving /api/orders, /api/bills/generate, /api/bills/:id/payment, /api/refunds, /api/orders/:id/convert-to-takeaway, /api/orders/:id/items/:itemId/edit, /api/orders/:id/items/:itemId/restore, /api/orders/:id/items/:itemId/price, and /api/orders/:id/customer
✅ **Document** - passed

✅ No issues found.

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

✅ No issues found.

@coderabbitai

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

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

@khaira777 khaira777 changed the title fix(main): enforce order and bill settlement guards and flat-discount caps fix(orders): guard settled bills & flat discounts Oct 22, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

@greptile-apps

greptile-apps Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5 Tier: apex

[Medium impact] The changes reach order and billing workflows that affect totals and payment status.

Preserve saved item tax rules during customer changes before merging.

Findings

  1. P1 Customer changes replace saved taxes ▶

Summary

Adds settled-bill guards, exact-balance settlement, and consistent flat-discount caps.

  • Order discounts keep their saved rule when the subtotal changes.
  • Bill updates preserve settled records and settle exact balances.
  • Customer changes recalculate order taxes and open bills.
  • Takeaway conversion checks bills and collected payments before changing an order.
  • Item restoration respects settled bills and restores the saved discount.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A["Order change or bill generation"] --> B["Read or recalculate order totals"]
  B --> C{"Unsplit bill state"}
  C -->|"unpaid / partial / partially_paid"| D["Sync payable total and balance"]
  C -->|"paid / partially_refunded / refunded"| E["Keep bill unchanged"]
  D --> F{"Positive collected amount equals total?"}
  F -->|No| G["Keep bill open"]
  F -->|Yes| H{"Kitchen allows settlement?"}
  H -->|No| G
  H -->|Yes| I["Mark bill paid"]
  I --> J["Complete order if all bills are settled"]
Loading

Reviews (2) · Last reviewed commit: "no-mistakes(document): Document order/bi..." · Reviewed by Greptile

Comment thread main/routes/orders.ts Resolved
@khaira777
khaira777 force-pushed the fm/ship-c7755f35-order-bill-settlement-safety branch from ab69dcb to 941e730 Compare October 22, 2026 21:37
@khaira777 khaira777 changed the title fix(orders): guard settled bills & flat discounts fix(main): enforce order and bill settlement guards and flat-discount caps Oct 22, 2026
@khaira777 khaira777 changed the title fix(main): enforce order and bill settlement guards and flat-discount caps fix(orders): guard settled bills & flat discounts Oct 22, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

1 similar comment
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

Comment thread main/routes/orders.ts Resolved
@khaira777
khaira777 force-pushed the fm/ship-c7755f35-order-bill-settlement-safety branch from 941e730 to 7a6975d Compare October 22, 2026 22:28
@khaira777 khaira777 changed the title fix(orders): guard settled bills & flat discounts fix(main): enforce order and bill settlement invariants and flat-discount caps Oct 22, 2026
@khaira777 khaira777 changed the title fix(main): enforce order and bill settlement invariants and flat-discount caps fix(orders): guard settled bills & flat discounts Oct 22, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

1 similar comment
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

Fixes #1295

- Restrict syncUnpaidBillsForOrder and POST /api/bills/generate resync to unpaid and partially paid bills so refunded, partially_refunded, and Rs.0 paid bills are not overwritten.
- Guard PATCH /api/orders/:id/convert-to-takeaway against settled, refunded, and split bills, enforce below_collected_funds when takeaway total drops below paid_amount, and record converted_to_takeaway audit entries.
- Invoke completeExactBalanceSettlement when convert-to-takeaway, item edit, or POST /api/bills/generate brings a partially paid bill to exact zero balance.
- Add orderWriteRateLimit and settled/refunded/Rs.0 paid bill guards to PATCH /api/orders/:orderId/items/:itemId/restore.
- Preserve flat order discounts (clamped to newSubtotal) instead of scaling proportionally in handleItemDiscount, handleItemPriceOverride, and item cancel.
- Guard PATCH /api/orders/:id/customer against settled, partial, refunded, and split bills, recompute customer-dependent taxes, sync unpaid bills, and record customer_updated audit entries.
@khaira777
khaira777 force-pushed the fm/ship-c7755f35-order-bill-settlement-safety branch from 7a6975d to 46df577 Compare October 22, 2026 23:19
@khaira777 khaira777 changed the title fix(orders): guard settled bills & flat discounts fix(main): enforce order/bill settlement guards and flat-discount caps Oct 22, 2026
@khaira777
khaira777 merged commit 5d791d4 into main Oct 23, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/ship-c7755f35-order-bill-settlement-safety branch October 23, 2026 01:12
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