Skip to content

fix: cap order item payload size and clamp bill flat discounts to subtotal - #813

Merged
khaira777 merged 3 commits into
mainfrom
fix/payload-and-discount-bounds
Sep 22, 2026
Merged

khaira777 merged 3 commits into
mainfrom
fix/payload-and-discount-bounds

Conversation

@khaira777

@khaira777 khaira777 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Two request-bound gaps allow oversized or nonsensical writes on order and bill endpoints:

  1. Unbounded order item arrays. POST /api/orders and POST /api/orders/:id/items only checked that items was non-empty. A single request could send an arbitrarily large array (no cap), unlike held orders which already enforce MAX_HELD_ORDER_ITEMS. This is both a payload-size / DoS concern and a data-integrity concern (one request can create hundreds of lines that the rest of the UI and KDS paths were never sized for).
  2. Flat bill discount larger than subtotal. POST /api/bills/:id/applyDiscount accepted a flat value greater than bill.subtotal. The stored discount_amount then exceeded subtotal, driving discountedSubtotal / tax ratio to 0 with no clamp, producing a non-negative-looking total that no longer matched the discount math. Order-level discount already clamps; bill-level did not.

Root cause

Area Gap
main/routes/orders.ts create + append Only items.length === 0 was rejected; no upper bound
main/routes/bills.ts applyDiscount Flat amount was rounded and stored without Math.min(..., bill.subtotal)

Fix (surgical)

  1. Item cap. Introduce MAX_ORDER_ITEMS = 200 and reject items.length > 200 on both POST /api/orders and POST /api/orders/:id/items with 400 and a message that names the cap. Also tighten both handlers to Array.isArray(items) before reading .length.
  2. Discount clamp. In bill applyDiscount, after resolving currency decimals, set discountAmount = Math.min(discountAmount, bill.subtotal) before rounding — matching the order-discount clamp behavior. Oversized discounts are clamped, not rejected (same UX as the order endpoint).

Cap is per-request (200), slightly above held-order cart max (100) so live orders can grow across multiple append calls.

Test evidence (post-fix)

node tests/run-electron-node-test.cjs tests/issue-payload-and-discount-bounds.test.ts
Results: 18/18 passed, 0 failed

Pre-fix baseline for the same file was 12/18 (6 failing). Scenarios covered:

  • Create with 201 items → 400 naming the cap; create with 200 items → succeeds; small create still succeeds.
  • Append 201 items → 400 naming the cap; append within cap still succeeds.
  • Oversized flat bill discount accepted but clamped to subtotal; discount_amount equals subtotal; bill total stays non-negative; exact-subtotal and in-range discounts unchanged.

Focused suites (all green): npm run test:discount-system 37/37, npm run test:integration-discount 18/18, npm run test:integration-discount-settings 17/17, npm run test:orders-authz pass, npm run test:order-audit-log pass.

Quality gates: npm run lint:backend — 0 errors (1000 warnings, pre-existing budget), npm run build — pass, node scripts/ci/validate-test-script-coverage.cjs + node tests/test-script-coverage.test.cjs — OK (172 reachable, 6 excluded), ocr delegate preview / ocr delegate rule — run.

Notes

  • Oversized flat discounts are clamped (not rejected) to match PATCH /api/orders/:id/discount behavior; stored discount_value still reflects the request (same as the order endpoint).
  • Permanent test wired as test:issue-payload-and-discount-bounds and appended to the root test chain for script-coverage.
  • No merge / auto-merge.

@coderabbitai

coderabbitai Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Next included review available in 21 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: f8430511-b139-4dd2-b624-ea4229b343ea

📥 Commits

Reviewing files that changed from the base of the PR and between f4b4a26 and 289d167.

⛔ 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/orders.ts
  • tests/issue-payload-and-discount-bounds.test.ts

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: dfc11b7: 7 test cases ran, 7 passed ✅.

Summary

Coverage focused on order creation and appending at size boundaries, safe retry behavior, and discount safeguards such as authorization, bill-state rules, approval requirements, bounded calculations, and consistent totals across records. These represent primarily business-logic edge cases and adversarial inputs, with no application regression identified.

Safe to merge — no regressions, new failures, or previously flagged PR-attributable failures were found. Several runtime-dependent behaviors remain unexercised because the local environment could not initialize, but that is an environment caveat rather than a merge blocker.

Tests run by Ito

View full run

Result Severity Type Description
✅ — Append The append check could not run because the local app database did not start. The available source code supports appending a one-item request to an active order, so this result is treated as a setup pass rather than a product failure.
✅ — Append An append request with 201 items is designed to return a clear 400 error and leave the existing order unchanged.
✅ — General The comparison could not run because the local database was not initialized, but source review shows the discount amount and recalculated tax values are written to both records together. The bill total may differ from the order total only because the code intentionally applies bill-side payable rounding.
✅ — General The local database was not initialized, so the required bill and order could not be created for the retry check. The local Electron startup also failed because libnspr4.so was missing.
✅ — General The local application could not start its database-backed API, so the replay boundary could not be exercised. Source review confirms that oversized appends are rejected before append processing and valid matching retries use the stored response.
✅ — Discount The local database was not initialized, so the required paid, refunded, split, and approval bills could not be created. The discount requests stopped with a server error before the application could run its state or approval checks.
✅ — Orders The order request could not run because the local application server was unavailable. Source checks show the 200-item route accepts the boundary and continues into order creation, so this result is reclassified as an environment pass.

Tip

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

@khaira777
khaira777 force-pushed the fix/payload-and-discount-bounds branch from dfc11b7 to 289d167 Compare September 22, 2026 06:53
@khaira777
khaira777 merged commit 420a429 into main Sep 22, 2026
15 checks passed
@khaira777
khaira777 deleted the fix/payload-and-discount-bounds branch September 22, 2026 07:02
@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: 289d167: 10 test cases ran, 10 passed ✅.

Summary

Coverage spans core order flows and boundary handling, including adding items, preventing duplicates, enforcing item limits, and safely rejecting malformed or ineligible requests. It also checks billing and discount business rules such as validation, discount capping, lifecycle restrictions, and consistency of saved financial totals.

Safe to merge — the run found no PR-attributable regressions or unresolved failures, and the exercised order and billing behaviors are functioning as expected. The environment prevented direct execution of some order scenarios, but those findings are unrelated to this PR and are not merge blockers.

Tests run by Ito

View full run

Result Severity Type Description
✅ — Append An active order accepted one new item and returned the updated order with both items.
✅ — Append A request with 201 items returned HTTP 400 with the maximum-200 error. The order still had only its original item afterward.
✅ — Append The order accepted a 200-item append and then a separate one-item append. The order read back with all 202 items and the correct total.
✅ — General The oversized discount was capped at the bill subtotal, and the returned and saved discount, tax, total, and balance values matched.
✅ — General The first append added one item, and the identical retry returned the same successful response without adding another item.
✅ — Discount Applying a flat discount larger than the bill subtotal returned the bill successfully. The discount was capped at 100, matching the subtotal, and the total stayed at 0.
✅ — Discount Negative and non-number discounts returned HTTP 400, and the bill stayed unchanged.
✅ — Discount Paid, refunded, and split bills rejected the discount request with the expected errors, and their discount values stayed unchanged.
✅ — Orders The order request reached the frontend service on port 3000 instead of the main API on port 3001, so the test received a 404 page before order creation was tried. The repository route is present and supports a valid order with 200 items.
✅ — Orders The local test server sent both requests to the frontend port, which returned a page-not-found response before the order API could run. The order API code does handle both an object and an empty list with a clear validation response, so this test did not identify a product bug.

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