Skip to content

fix(tax): round document tax after order discounts - #1293

Merged
khaira777 merged 12 commits into
mainfrom
fm/ship-t1-discount-document-tax-rounding
Oct 22, 2026
Merged

khaira777 merged 12 commits into
mainfrom
fm/ship-t1-discount-document-tax-rounding

Conversation

@khaira777

@khaira777 khaira777 commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1288

Intent

Fix issue #1288: apply order discounts before document-scope tax rounding allocation, preserve Decimal discount ratio for line-scoped snapshots, and normalize override unit prices in preview and cart

What Changed

  • Added allocateDocumentTaxRounding, rollupOrderTaxes, and 40-digit Decimal computeDiscountTaxRatio in main/services/tax.ts so recomputeOrderTotals and calculateTaxPreview scale raw unrounded document-scope item tax components (amount + roundingRemainder) by the order-discount ratio before running largest_remainder document rounding across combined item and charge tax components, while persisting un-order-discounted document tax allocations on order_items.
  • Preserved Decimal discount ratios through scaleTaxBreakdowns, scaleTaxSnapshots, combineItemAndChargeTaxes, and projectOrderItems alongside Decimal subtotal/total accumulation, and updated projectOrderItems in main/routes/bills.ts to project discounted document line allocations from order.tax_snapshot with a fallback to allocateDocumentTaxRounding.
  • Added half-up normalizeOverridePrice across backend override parsing (main/services/item-price-override.ts), tax preview quoting (main/services/tax.ts, frontend/src/hooks/use-tax-preview.ts), and frontend cart pricing, identity, and order payload helpers (frontend/src/lib/cart-price.ts, frontend/src/lib/cart-identity.ts, frontend/src/lib/cart-order-item.ts, frontend/src/store/cart.ts), with matching architecture docs and regression tests.

Risk Assessment

✅ Low: The changes cleanly address issue #1288 across backend tax calculation, order total recomputation, bill item projection, and frontend/backend price-override normalization. Document-scoped tax rounding now scales raw item tax components by the high-precision Decimal discount ratio before largest-remainder allocation while keeping persisted item rows un-order-discounted and charges unscaled; line-scoped snapshot scaling preserves the Decimal ratio and tie-break order; bill item projection reuses saved order snapshot entries; and override unit prices are normalized consistently using half-up decimal rounding in preview, cart, and order creation. All 16 changed files were inspected and verified with no defects found.

Testing

Ran the six targeted test suites (test:cart-price-override, test:item-price-override, test:tax-engine, test:order-totals-recompute, test:tax-components, and test:integration-tax), then stood up the compiled FloCafe server and static Next.js frontend against an isolated SQLite database and drove all four scenarios live through headless Chromium and the HTTP API, capturing POS checkout and cart screenshots plus a structured JSON evidence transcript; all checks and scenarios passed.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
Apply order and bill discounts on document-scoped taxes across items and taxable charges, then clear the discount back to 0%: discounted raw item tax components are scaled before document largest_rema… ✅ pass live ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/pos-payment-modal-discount-tax-rounding.png; ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/live-validati…
Apply a flat discount with a repeating-decimal ratio (87.90 off 104.00 with 0.10 taxable packaging charge) under line-scoped and document-scoped dual 2.5% taxes: 40-digit Decimal ratio precision is pr… ✅ pass live ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/live-validation-evidence.json; npm run test:tax-engine; npm run test:integration-tax; npm run test:tax-components
Override cart item unit prices with fractional sub-cent values (10.005, 3.333, 0.015) at quantity 3 in the POS cart and tax preview, place the order, generate the bill, and settle by card: unit prices… ✅ pass live ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/pos-cart-price-override-normalized.png; ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/live-validation-ev…
Exercise adversarial float, null, clamp, and historical-snapshot boundaries (20.20 flat discount off 100.10 item, discount > subtotal / negative discount / zero subtotal, order.discount_amount = NULL… ✅ pass live ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/live-validation-evidence.json; npm run test:order-totals-recompute; npm run test:integration-tax

POS Checkout Modal - 50% discount on two ₹100.10 items allocates ₹5.01 document tax and ₹105.11 total
POS Cart - Fractional override unit price 10.005 normalized half-up to ₹10.01 with ₹30.03 subtotal at qty 3

Evidence: Live validation evidence JSON (API, DB, and browser scenario outputs)
{
  "baseUrl": "http://127.0.0.1:3411",
  "timestamp": "2026-10-22T21:57:28.753Z",
  "scenarios": {
    "scenario1_document_discount_tax_rounding": {
      "ce1_100_10_x2_at_50pct": {
        "previewTax": 5.01,
        "previewTotal": 105.11,
        "previewItemTaxes": [
          5.01,
          5
        ],
        "screenshot": "~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/pos-payment-modal-discount-tax-rounding.png"
      },
      "ce2_100_05_x2_at_50pct": {
        "previewTax": 5,
        "orderTax": 5,
        "orderTotal": 105.05
      },
      "ce3_100_20_item_plus_100_10_charge_at_100pct_and_restored": {
        "undiscountedTax": 10.02,
        "discountedTaxAt100Pct": 5.01,
        "discountedTotalAt100Pct": 105.11,
        "restoredTaxAt0Pct": 10.02,
        "restoredTotalAt0Pct": 210.32
      }
    },
    "scenario2_line_scoped_decimal_discount_ratio": {
      "itemPrice": 104,
      "packagingCharge": 0.1,
      "flatDiscount": 87.9,
      "discountedSubtotal": 16.1,
      "orderTaxAmount": 0.81,
      "orderSnapshotTaxSum": 0.81,
      "billTaxAmount": 0.81,
      "resolvedComponentsSum": 0.81,
      "reportTaxAmount": 15.84,
      "reportComponentsSum": 15.84
    },
    "scenario3_override_price_normalization": {
      "cases": [
        {
          "rawPrice": 10.005,
          "normalizedUnitPrice": 10.01,
          "previewTotal": 30.03,
          "orderTotal": 30.03,
          "billTotal": 30.03,
          "paymentStatus": "paid"
        },
        {
          "rawPrice": 3.333,
          "normalizedUnitPrice": 3.33,
          "previewTotal": 9.99,
          "orderTotal": 9.99,
          "billTotal": 9.99,
          "paymentStatus": "paid"
        },
        {
          "rawPrice": 0.015,
          "normalizedUnitPrice": 0.02,
          "previewTotal": 0.06,
          "orderTotal": 0.06,
          "billTotal": 0.06,
          "paymentStatus": "paid"
        }
      ],
      "screenshot": "~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/pos-cart-price-override-normalized.png"
    },
    "scenario4_adversarial_float_and_null_boundaries": {
      "flat20_20Off100_10": {
        "orderTax": 4,
        "orderTotal": 83.9,
        "billTax": 4,
        "billTotal": 83.9
      },
      "nullOrderDiscountBillReadStatus": 200
    }
  }
}

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
Apply order and bill discounts on document-scoped taxes across items and taxable charges, then clear the discount back to 0%: discounted raw item tax components are scaled before document largest_rema… ✅ pass live ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/pos-payment-modal-discount-tax-rounding.png; ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/live-validati…
Apply a flat discount with a repeating-decimal ratio (87.90 off 104.00 with 0.10 taxable packaging charge) under line-scoped and document-scoped dual 2.5% taxes: 40-digit Decimal ratio precision is pr… ✅ pass live ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/live-validation-evidence.json; npm run test:tax-engine; npm run test:integration-tax; npm run test:tax-components
Override cart item unit prices with fractional sub-cent values (10.005, 3.333, 0.015) at quantity 3 in the POS cart and tax preview, place the order, generate the bill, and settle by card: unit prices… ✅ pass live ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/pos-cart-price-override-normalized.png; ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/live-validation-ev…
Exercise adversarial float, null, clamp, and historical-snapshot boundaries (20.20 flat discount off 100.10 item, discount > subtotal / negative discount / zero subtotal, order.discount_amount = NULL… ✅ pass live ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/live-validation-evidence.json; npm run test:order-totals-recompute; npm run test:integration-tax
  • npm run test:cart-price-override
  • npm run test:item-price-override
  • npm run test:tax-engine
  • npm run test:order-totals-recompute
  • npm run test:tax-components
  • npm run test:integration-tax
  • npm run build && npm run build:frontend (for live server + browser execution)
  • Live Chromium POS + Express API + SQLite scenario run capturing ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/pos-payment-modal-discount-tax-rounding.png, ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/pos-cart-price-override-normalized.png, and ~/.no-mistakes/evidence/01M5JRZBTDMEPQH86Q1AHM45HY/live-validation-evidence.json
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ 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): apply order discounts before document-scope tax rounding allocation fix(tax): discount before document tax rounding 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

[High impact] The changes reach tax amounts shown in order previews, saved orders, bills, and tax reports.

Fix the line-scoped snapshot precision mismatch before merging, because receipts and reports can overstate saved tax.

Findings

  1. P1 Reports add an extra cent ▶

Summary

Applies order discounts before rounding document-scoped tax across items and charges.

  • Order discounts are applied before document-level tax rounding.
  • Bill items show the discounted tax allocation used in the bill total.

Verification: git diff --check passed. Standalone arithmetic confirmed the rounding boundary. Application suites, build, lint, and documentation checks were not run; required application dependencies, including decimal.js, are absent.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Item tax snapshots] --> B[Undiscounted document allocation]
  B --> C[Stored item taxes]
  B --> D[Apply order discount to raw item tax]
  E[Unchanged charge tax] --> D
  D --> F[Round document tax]
  F --> G[Preview and saved order totals]
  F --> H[Saved order tax allocation]
  H --> I[Projected bill items]
Loading

Reviews (4) · Last reviewed commit: "fix(tax): match preview and order line s..." · Reviewed by Greptile

Comment thread main/services/orders.ts Resolved
Comment thread main/services/tax.ts Resolved
Comment thread main/services/tax.ts Resolved
@khaira777
khaira777 force-pushed the fm/ship-t1-discount-document-tax-rounding branch from b4963e1 to 211ba44 Compare October 22, 2026 18:39
@khaira777 khaira777 changed the title fix(tax): discount before document tax rounding fix(main): scale raw item tax components by order discount before document rounding Oct 22, 2026
@khaira777 khaira777 changed the title fix(main): scale raw item tax components by order discount before document rounding fix(tax): discount before document tax rounding Oct 22, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

Comment thread main/services/tax.ts Resolved
Comment thread main/routes/bills.ts Resolved
Comment thread main/routes/bills.ts Resolved
@khaira777
khaira777 force-pushed the fm/ship-t1-discount-document-tax-rounding branch from 211ba44 to d2d888d Compare October 22, 2026 19:50
@khaira777 khaira777 changed the title fix(tax): discount before document tax rounding chore: update pull request Oct 22, 2026
@khaira777 khaira777 changed the title chore: update pull request fix(tax): round document tax after order discounts Oct 22, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

Comment thread main/services/tax.ts Resolved
@khaira777
khaira777 force-pushed the fm/ship-t1-discount-document-tax-rounding branch from d2d888d to 122dd27 Compare October 22, 2026 20:44
@khaira777 khaira777 changed the title fix(tax): round document tax after order discounts fix(main): scale document-scoped item taxes by discount before document rounding Oct 22, 2026
@khaira777 khaira777 changed the title fix(main): scale document-scoped item taxes by discount before document rounding fix(tax): round document tax after order discounts Oct 22, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

Comment thread main/services/tax.ts Resolved
Fixes #1288

Apply the exact Decimal order-discount ratio to raw item tax components before running document-scope largest_remainder rounding across combined discounted-item and unchanged-charge components in recomputeOrderTotals and calculateTaxPreview, while persisting order_items with their un-order-discounted document tax allocation so subsequent discount edits never compound.
@khaira777
khaira777 force-pushed the fm/ship-t1-discount-document-tax-rounding branch from 122dd27 to b2d716e Compare October 22, 2026 22:02
@khaira777 khaira777 changed the title fix(tax): round document tax after order discounts fix(main): apply discounts before document tax rounding and normalize override prices Oct 22, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

@khaira777 khaira777 changed the title fix(main): apply discounts before document tax rounding and normalize override prices fix(tax): round document tax after order discounts Oct 22, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

@khaira777
khaira777 merged commit 57f5900 into main Oct 22, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/ship-t1-discount-document-tax-rounding branch October 22, 2026 22:52
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.

fix(tax): apply order discounts before document-scope tax rounding allocation

1 participant