Skip to content

fix(charges): round percentage fees exactly - #1118

Merged
khaira777 merged 2 commits into
mainfrom
fm/flocafe-issue-1068-r1
Oct 13, 2026
Merged

khaira777 merged 2 commits into
mainfrom
fm/flocafe-issue-1068-r1

Conversation

@khaira777

@khaira777 khaira777 commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1068

Intent

Implement the surgical fix for FreeOpenSourcePOS/FloCafe issue #1068 ("Percentage charge calculation rounds half-cent down due to floating-point fast path"): remove the IEEE-754 floating-point fast path (basisMinor * percentage) in shared/charges.ts so percentage charge calculations always use the existing exact decimal-string/BigInt half-up arithmetic (e.g., subtotal 29725.00 at 65.74% rounds to 19541.22 instead of 19541.21). Deliver via the no-mistakes pipeline as its own PR (Fixes #1068).

What Changed

  • Removed the IEEE-754 floating-point fast path (basisMinor * percentage) from percentageMinorUnits in shared/charges.ts so all percentage charge calculations evaluate through exact decimal-string and BigInt half-up rounding.
  • Added unit tests in tests/charges-calculation.test.ts covering half-minor-unit rounding boundaries, multi-decimal and scientific-notation rates, and zero/three-decimal currencies (JPY, KWD).
  • Added API integration tests in tests/charges-engine-api.test.ts verifying end-to-end order, bill, and persisted charges_breakdown rounding at exact half-cent boundaries (29725.00 at 65.74% -> 19541.22).

Risk Assessment

✅ Low: The change removes the IEEE-754 floating-point fast path in percentageMinorUnits so all percentage charge calculations use the existing exact BigInt half-up arithmetic, backed by unit and API integration tests.

Testing

Ran npm run test:charges (63/63 checks passing) and npm run test:charges-engine (196/196 checks passing), and drove a live Express API and disposable SQLite instance to verify that configuring a 65.74% charge on a 29725.00 order and generating a bill computes and persists 19541.22 (total 49266.22), preserves historical bill snapshots after rate changes, and rounds half-minor-unit ties half-up across 0-, 2-, and 3-decimal currencies; this backend calculation fix has no UI surface change.

  • Live validation: ✅ go - 3 of 3 scenarios driven live against the product
Scenario Result Live Evidence
Configure a 65.74% service charge via PUT /api/settings/charges, create a dine-in order at subtotal 29725.00 via POST /api/orders, and generate a bill via POST /api/bills/generate -> order and bill pe… ✅ pass live ~/.no-mistakes/evidence/01M4V9WHBMFA5A434JG1WHJXTN/live-api-verification.json
Update the service charge rate to 10% and create a subsequent order -> new order uses 2972.50 while the previously generated bill row in SQLite retains service_charge 19541.22, total 49266.22, and cha… ✅ pass live ~/.no-mistakes/evidence/01M4V9WHBMFA5A434JG1WHJXTN/live-api-verification.json
Adversarial floating-point and currency precision boundaries: evaluate half-minor-unit ties across 2-decimal (USD 29725.00 @ 65.74% -> 19541.22), 0-decimal (JPY 2972500 @ 65.74% -> 1954122), 3-decimal… ✅ pass live ~/.no-mistakes/evidence/01M4V9WHBMFA5A434JG1WHJXTN/charges-calculation.log
Evidence: Live Express API and SQLite verification for #1068 half-cent percentage charge rounding

{ "configuredChargesStatus": 200, "configuredChargeRate": 65.74, "orderCreatedStatus": 201, "orderSubtotal": 29725, "orderServiceCharge": 19541.22, "orderTotal": 49266.22, "billGeneratedStatus": 201, "billServiceCharge": 19541.22, "billTotal": 49266.22, "billBalance": 49266.22, "subsequentOrderServiceChargeAt10Percent": 2972.5, "persistedDbOrder": { "id": 1, "subtotal": 29725, "service_charge": 19541.22, "total": 49266.22, "charges_breakdown": "[{"id":"service_charge","name":"Service Charge","type":"percentage","amount":19541.22,"calculation_basis":"gross","waived":false,"tax_category_id":null,"rate":65.74}]" }, "persistedDbBillAfterLaterRateChange": { "id": 1, "subtotal": 29725, "service_charge": 19541.22, "total": 49266.22, "balance": 49266.22, "charges_breakdown": "[{"id":"service_charge","name":"Service Charge","type":"percentage","amount":19541.22,"calculation_basis":"gross","waived":false,"tax_category_id":null,"rate":65.74}]" }, "boundaryMatrix": { "usdHalfCentFloatTrap": 19541.22, "jpyZeroDecimalHalfUnit": 1954122, "kwdThreeDecimalHalfUnit": 1954.122, "scientificNotationBoundary": [ { "id": "sci_below", "amount": 0 }, { "id": "sci_half", "amount": 0.01 }, { "id": "sci_above", "amount": 0.01 } ] } }

{
  "configuredChargesStatus": 200,
  "configuredChargeRate": 65.74,
  "orderCreatedStatus": 201,
  "orderSubtotal": 29725,
  "orderServiceCharge": 19541.22,
  "orderTotal": 49266.22,
  "billGeneratedStatus": 201,
  "billServiceCharge": 19541.22,
  "billTotal": 49266.22,
  "billBalance": 49266.22,
  "subsequentOrderServiceChargeAt10Percent": 2972.5,
  "persistedDbOrder": {
    "id": 1,
    "subtotal": 29725,
    "service_charge": 19541.22,
    "total": 49266.22,
    "charges_breakdown": "[{\"id\":\"service_charge\",\"name\":\"Service Charge\",\"type\":\"percentage\",\"amount\":19541.22,\"calculation_basis\":\"gross\",\"waived\":false,\"tax_category_id\":null,\"rate\":65.74}]"
  },
  "persistedDbBillAfterLaterRateChange": {
    "id": 1,
    "subtotal": 29725,
    "service_charge": 19541.22,
    "total": 49266.22,
    "balance": 49266.22,
    "charges_breakdown": "[{\"id\":\"service_charge\",\"name\":\"Service Charge\",\"type\":\"percentage\",\"amount\":19541.22,\"calculation_basis\":\"gross\",\"waived\":false,\"tax_category_id\":null,\"rate\":65.74}]"
  },
  "boundaryMatrix": {
    "usdHalfCentFloatTrap": 19541.22,
    "jpyZeroDecimalHalfUnit": 1954122,
    "kwdThreeDecimalHalfUnit": 1954.122,
    "scientificNotationBoundary": [
      {
        "id": "sci_below",
        "amount": 0
      },
      {
        "id": "sci_half",
        "amount": 0.01
      },
      {
        "id": "sci_above",
        "amount": 0.01
      }
    ]
  }
}
Evidence: Charges calculation test suite output (63/63 passed)

> [email protected] test:charges
> ts-node --transpile-only -P tests/tsconfig.json tests/charges-calculation.test.ts

  ✓ accepts a well-formed definition
  ✓ keeps the charge id
  ✓ marks the charge optional
  ✓ defaults tax_category_id to null
  ✓ accepts the stored JSON string form
  ✓ rejects a non-slug charge id
  ✓ rejects a blank charge name
  ✓ rejects an over-long charge name
  ✓ rejects an unsupported charge type
  ✓ rejects an unsupported calculation basis
  ✓ rejects an unknown order type
  ✓ rejects an empty order type list
  ✓ rejects a negative value
  ✓ rejects a percentage above 100
  ✓ rejects a non-numeric value
  ✓ rejects a fixed amount outside currency precision
  ✓ rejects duplicate charge ids
  ✓ rejects a non-array payload
  ✓ rejects an oversized charge id
  ✓ one invalid entry rejects the whole array (no partial write)
  ✓ malformed stored charges read as no charges rather than throwing
  ✓ calculation rejects a fixed amount that overflows scaled minor units
  ✓ combined charge minor units must remain a safe integer
  ✓ an unsafe 10.1 percent product still yields an accurately rounded safe result
  ✓ calculation rejects a percentage result that overflows safe integer minor units
  ✓ zero and 100 percent retain currency rounding at ordinary amounts
  ✓ 29725.00 at 65.74% rounds exact half-cent (1954121.5 minor units) up to 19541.22
  ✓ adjacent below-half, exact-half, and above-half percentage products round half-up
  ✓ rates with more than two decimal places retain full precision before rounding
  ✓ scientific-notation percentage rates round accurately at the half-minor-unit boundary
  ✓ zero-decimal currency rounds exact half minor unit up without floating-point drift
  ✓ three-decimal currency rounds exact half minor unit up without floating-point drift
  ✓ net basis applies to the discounted subtotal
  ✓ gross basis applies to the raw subtotal
  ✓ a fixed fee ignores the subtotal
  ✓ a fixed fee carries no rate
  ✓ a percentage fee applies its rate
  ✓ a percentage fee records its rate
  ✓ a charge does not apply to an unlisted order type
  ✓ JPY has no minor units
  ✓ VND has no minor units
  ✓ KWD has three minor unit digits
  ✓ a JPY percentage fee rounds to whole yen
  ✓ a JPY fee never persists a fractional yen
  ✓ a JPY fixed fee is stored as an integer
  ✓ a JPY fixed fee never persists a subunit
  ✓ a VND fee rounds half-up to whole dong
  ✓ a KWD fee rounds to three decimal places
  ✓ a KWD fee lands on a whole fils
  ✓ a USD fee rounds to two decimal places
  ✓ a negative subtotal yields a zero fee, never a negative one
  ✓ a discount exceeding the subtotal floors the net fee at zero
  ✓ a waived charge persists waived: true
  ✓ a waived charge records amount 0
  ✓ a waived charge is excluded from the total
  ✓ a zero-rate charge records amount 0
  ✓ a zero-rate charge is distinguishable from a waived charge
  ✓ waiver state survives a persistence round trip
  ✓ a mandatory charge cannot be zeroed by a stray waiver id
  ✓ a mandatory charge never records waived: true
  ✓ service_charge maps onto the dedicated column
  ✓ packaging_charge maps onto the dedicated column
  ✓ non-standard charges are summed, not dropped
  ✓ the column mapping reconciles with the itemised total
  ✓ a JPY column mapping stays integral
  ✓ a JPY packaging column stays integral
  ✓ parses a persisted charges_breakdown payload
  ✓ a persisted waiver is read as waived
  ✓ a null breakdown reads as no charges
  ✓ an unparseable breakdown reads as no charges
  ✓ a malformed breakdown entry is dropped

Charges calculation: 63/63 checks passed
Evidence: Charges engine API integration test suite output (196/196 passed)

> [email protected] test:charges-engine
> ts-node --transpile-only -P tests/tsconfig.json tests/charges-engine-api.test.ts

[DB] Opening database at: /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-charges-api-iLFEj4/flo.db
[DB] Schema: v0 → v112
[DB] Triggering auto-backup before migrating v0 → v112...
[DB] Auto-backup before migrating v0 → v112 created at /var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-charges-api-iLFEj4/backups/flo-backup-2026-10-13T18-58-40-399Z-pre-v0-to-v112.db
[DB] Install defaults loaded; first-run setup pending
[MIGRATION v23] normalized: 0, unparseable: 0
[MIGRATION v23] merged 0 duplicate customer(s)
[MIGRATION v23] verification: 0 customers, 0 still non-E.164
[MIGRATION v24] normalized: 0, unparseable: 0
[MIGRATION v25] backfilled addons for 0 order items (0 unparseable, skipped)
[MIGRATION v30] backfilled 0 order_item(s) still missing a normalized addons snapshot
[MIGRATION v30] Dropped order_items.addons — order_item_addons is now the only place selected addons live.
[MIGRATION v73] normalized 0 merchant template payload(s); 0 already canonical or left untouched
[DB] integrity_check: ok
[DB] foreign_key_check: clean
[Auth] Generated new JWT secret for this install

1. Dedicated endpoints validate; the wildcard route cannot write custom_charges
  ✓ valid charge definitions are accepted
  ✓ both charges are stored
  ✓ the wildcard PUT route refuses custom_charges
  ✓ the refused wildcard write left the setting intact
  ✓ rejects an out-of-range percentage
  ✓ rejects a negative value
  ✓ rejects an unknown order type
  ✓ rejects a non-slug id
  ✓ rejects an unsupported type
  ✓ rejects a fixed amount outside the supported currency precision
  ✓ no rejected write partially replaced the stored list
  ✓ individually safe large fees are accepted
[Orders] Create error: ChargeValidationError: Combined charge amounts exceed the supported currency precision
    at addMinorUnits (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/shared/charges.ts:242:11)
    at toStandardChargeColumns (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/shared/charges.ts:344:23)
    at resolveOrderCharges (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/main/services/charges.ts:120:42)
    at buildAppliedCharges (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/main/services/charges.ts:153:10)
    at ~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/main/routes/orders.ts:1432:52
    at sqliteTransaction (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/node_modules/better-sqlite3/lib/methods/transaction.js:65:24)
    at withTxn (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/main/db.ts:1334:28)
    at ~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/main/routes/orders.ts:1166:29
    at Layer.handleRequest (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/node_modules/router/lib/layer.js:152:17)
    at next (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/node_modules/router/lib/route.js:157:13) {
  statusCode: 400
}
[API] Internal error: ChargeValidationError: Combined charge amounts exceed the supported currency precision
    at addMinorUnits (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/shared/charges.ts:242:11)
    at toStandardChargeColumns (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/shared/charges.ts:344:23)
    at resolveOrderCharges (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/main/services/charges.ts:120:42)
    at buildAppliedCharges (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/main/services/charges.ts:153:10)
    at ~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/main/routes/orders.ts:1432:52
    at sqliteTransaction (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/node_modules/better-sqlite3/lib/methods/transaction.js:65:24)
    at withTxn (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/main/db.ts:1334:28)
    at ~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/main/routes/orders.ts:1166:29
    at Layer.handleRequest (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/node_modules/router/lib/layer.js:152:17)
    at next (~/.no-mistakes/worktrees/de2296f2e6f8/01M4V9WHBMFA5A434JG1WHJXTN/node_modules/router/lib/route.js:157:13) {
  statusCode: 400
}
  ✓ combined unsafe charge totals return a client error
  ✓ a rejected total rolls back its order insert
  ✓ a rejected total rolls back its item insert
  ✓ valid charges are restored after overflow

2. Order create applies charges and maps the standard id onto its column
  ✓ dine-in order created
  ✓ subtotal is 100
  ✓ service_charge column holds the engine value
  ✓ total = 100 + 10% service + 7 late night
  ✓ charges_breakdown holds both charges
  ✓ an applied charge persists waived: false
  ✓ the service charge records its computed amount
  ✓ the late-night fee records its computed amount

3. Waiving a charge persists waived: true, not an inferred zero
  ✓ bill generated
  ✓ the bill inherits the order breakdown
  ✓ optional charge waived (200)
  ✓ waived: true is persisted
  ✓ a waived charge records amount 0
  ✓ the service_charge column is cleared
  ✓ the total drops the waived fee
  ✓ a mandatory charge cannot be waived

4. A recompute preserves the recorded waiver
  ✓ item added to the order
  ✓ adding an item does not un-waive the fee
  ✓ the service_charge column stays cleared
  ✓ a fixed fee is unchanged by a subtotal change
  ✓ the waived fee stays at zero

5. A changed order-type rule applies only to new orders
  ✓ the original dine-in order is created
  ✓ the original snapshot stores the applied fee
  ✓ the existing order can still be recomputed
  ✓ the excluded fee keeps its stored amount
  ✓ the legacy service column keeps the stored amount
  ✓ the retained fee is not recalculated on the existing order
  ✓ a new dine-in order is created after the rule changes
  ✓ the new order does not receive the excluded fee
  ✓ only the remaining dine-in fee applies to the new order
  ✓ the limited server can create an order
  ✓ order creators can read charges for checkout without settings.view
  ✓ the checkout fee definitions are available
  ✓ order creators still cannot read general settings
  ✓ order creators cannot edit fee settings
  ✓ bill charge editors can read fee definitions without settings.view or orders.create
  ✓ bill charge editors cannot read general settings
  ✓ bill charge editors cannot edit fee settings
  ✓ bill charge editors cannot create orders without orders.create

6. A waiver is refused once the check has been split
  ✓ two-item dine-in order created for the split
  ✓ the check split into two guest checks
  ✓ exclusive-tax split totals preserve the parent total including custom charges
  ✓ exclusive-tax split breakdown allocates the full non-standard fee
  ✓ each exclusive-tax split total includes its allocated non-standard fee
  ✓ each exclusive-tax split total includes its allocated non-standard fee
  ✓ a waiver on a split check is refused
  ✓ the split check carries its own itemised charges
  ✓ a split check carries its proportional share of the service charge (10% of its 100 share)
  ✓ the split service_charge column matches its allocated share
  ✓ an unpaid split order item can be cancelled
  ✓ unpaid split synchronization preserves the updated parent total
  ✓ unpaid split synchronization allocates the custom fee exactly once
  ✓ inclusive-tax split with a custom fee succee

... [289 bytes truncated] ...

e yen
  ✓ the JPY service_charge column is integral
  ✓ 10% of 100 JPY is 10 JPY

8. A thermal receipt prints an engine charge exactly once
[Printer] formatReceipt - template: tpl-charges-dup
[Printer] formatReceipt - order: ORD-20261014-0008 bill: INV-20261014-0006
[Printer] formatReceipt - items count: 1 cols: 48
  ✓ the declared service-charge row is not repeated by the itemised line
  ✓ the merchant-named surcharge prints once

9. Converting to takeaway recomputes totals and clears the dine-in charge
  ✓ the dine-in order carries the 10% service charge
  ✓ the dine-in order converts to takeaway
  ✓ the order type is takeaway
  ✓ the dine-in service charge is cleared
  ✓ the stale dine-in breakdown is emptied
  ✓ the total drops both dine-in fees
  ✓ the unpaid bill service charge is synced to zero
  ✓ the unpaid bill total is synced to the converted total
  ✓ the unpaid bill breakdown is synced empty

10. Removing the last charge stores [] instead of resurrecting the stale breakdown
  ✓ the opted-in packaging fee is charged at creation
  ✓ the last charge is removed
  ✓ removing the last charge stores an empty array, not null
  ✓ the bill breakdown is empty
  ✓ the order breakdown is emptied too

10a. Removing a standard opted-in charge clears its legacy column
  ✓ the opted-in standard charge is applied
  ✓ the standard column stores the engine charge
  ✓ the standard charge is removed
  ✓ the removed standard charge does not return from its legacy column
  ✓ the removed standard charge is excluded from the bill total
  ✓ the order recomputes after removing the standard charge
  ✓ an item append does not resurrect the removed charge
  ✓ an item append totals without the removed charge
  ✓ the order can be discounted after removing the standard charge
  ✓ a discount recompute does not resurrect the removed charge
  ✓ the discount total excludes the removed charge

10b. Cancelling the last item clears engine-owned fixed charges
  ✓ the last item is cancelled
  ✓ the order is marked cancelled
  ✓ the cancelled order clears its engine-owned standard fee
  ✓ the cancelled order has no collectible charge snapshots
  ✓ the cancelled order total is zero
  ✓ the unpaid bill total is zero after cancellation
  ✓ the unpaid bill clears the engine-owned fee
  ✓ charges cannot be restored on a cancelled order
  ✓ the cancelled bill stays at zero after a rejected toggle
  ✓ the cancelled bill stays without a balance
  ✓ the rejected toggle preserves cleared charges
  ✓ discounts cannot restore fees on a cancelled order
  ✓ the cancelled bill stays at zero after a rejected discount
  ✓ the cancelled bill balance stays zero after a rejected discount

11. Order create keeps a manual charge column the engine has no rule for
  ✓ an order with manual charge columns is created
  ✓ a manual service charge survives an engine that owns no service_charge
  ✓ a manual packaging charge survives too
  ✓ the total still includes the manual columns
  ✓ the manual column is not faked as an engine charge
  ✓ a legacy order with manual standard columns is created
  ✓ the legacy manual order has no engine snapshot
  ✓ the legacy order recomputes with an unapplied default-off fee definition
  ✓ an unapplied default-off definition preserves the legacy service column
  ✓ the legacy packaging column also survives
  ✓ the legacy manual amounts remain in the recomputed total

12. Cart charge decisions survive order creation
  ✓ an order carrying cart charge decisions is created
  ✓ the cashier waiver is applied at creation
  ✓ the waived fee is not charged
  ✓ the opted-in charge the cashier added is applied
  ✓ the waived column is cleared
  ✓ the total reflects the waiver and the opt-in
  ✓ a waived optional opt-in is recorded
  ✓ the waived optional opt-in order recomputes
  ✓ a recompute preserves the waived opt-in decision
  ✓ the waived opt-in remains zero after a recompute
  ✓ a non-array waived_charge_ids is rejected

13. Recomputed orders retain inactive fee snapshots without charging new orders
  ✓ item append succeeds after a fee is disabled
  ✓ disabled fixed fee snapshot remains unchanged
  ✓ still-active percentage fee recalculates against the new subtotal
  ✓ the total includes the retained fee once
  ✓ the unpaid bill total follows the recomputed order
  ✓ the unpaid bill keeps the same retained fee snapshot
  ✓ a new order does not receive the disabled fee
  ✓ the disabled fee is absent from a new order

14. Recomputed orders retain deleted fee snapshots while preserving unpaid bill totals
  ✓ item append succeeds after the fee definition is removed
  ✓ deleted fee remains as the original snapshot
  ✓ the total includes the retained deleted fee once
  ✓ the unpaid bill retains the deleted fee in its total
  ✓ the unpaid bill keeps the original deleted fee snapshot
  ✓ a new order receives no deleted fee
  ✓ the deleted fee is absent from a new order

15. Bill discounts recompute configured percentage fees and retain fixed fees
  ✓ bill discount succeeds with configured charges
  ✓ bill total includes discounted net percentage and fixed charges
  ✓ bill service charge recalculates from the discounted net
  ✓ order snapshot stores the recomputed percentage fee
  ✓ order snapshot retains the fixed fee
  ✓ order exact total agrees with the discounted bill
  ✓ order and bill share the same charge breakdown

16. Packaging columns stay in sync through item and bill discounts
  ✓ the initial bill has its packaging fee
  ✓ an order discount recalculates packaging
  ✓ order packaging uses the discounted net
  ✓ bill packaging column follows the order discount
  ✓ bill breakdown agrees with its packaging column
  ✓ bill total includes the discounted packaging
  ✓ bill balance agrees with the discounted total
  ✓ a second item is added
  ✓ the order packaging fee follows the new subtotal
  ✓ the unpaid bill packaging fee follows the new subtotal
  ✓ an item discount recalculates the packaging fee
  ✓ the unpaid bill packaging fee follows an item discount
  ✓ a bill discount recalculates packaging
  ✓ the bill packaging fee uses the discounted net subtotal
  ✓ the order packaging column matches the discounted bill

17. Half-cent percentage charges persist exact half-up totals and leave historical bills unchanged
  ✓ 65.74% charge configuration is saved
  ✓ order at subtotal 29725.00 is created
  ✓ order subtotal is 29725.00
  ✓ order service_charge rounds half-cent up to 19541.22
  ✓ order total is 49266.22
  ✓ order charges_breakdown persists 19541.22
  ✓ order charges_breakdown persists rate 65.74
  ✓ bill is generated for the half-cent order
  ✓ bill service_charge persists 19541.22
  ✓ bill total persists 49266.22
  ✓ bill balance persists 49266.22
  ✓ bill charges_breakdown persists 19541.22
  ✓ charge configuration is updated to 10% for subsequent orders
  ✓ subsequent order is created under the updated 10% rate
  ✓ subsequent order uses the new 10% rate
  ✓ subsequent order total reflects the new 10% rate
  ✓ historical bill subtotal remains 29725.00
  ✓ historical bill service_charge remains 19541.22
  ✓ historical bill total remains 49266.22
  ✓ historical bill balance remains 49266.22
  ✓ historical bill charges_breakdown remains 19541.22 after later configuration and order activity
[DB] Database closed

Charges engine API: 196/196 checks passed
14:58:41.487 › [CloudSync] diagnostics outbox flush failed The database connection is not open
14:58:41.489 › [CloudSync] diagnostics outbox flush failed The database connection is not open
14:58:41.490 › [CloudSync] diagnostics outbox flush failed The database connection is not open
14:58:41.490 › [CloudSync] diagnostics outbox flush failed The database connection is not open
14:58:41.490 › [CloudSync] diagnostics outbox flush failed The database connection is not open
14:58:41.490 › [CloudSync] diagnostics outbox flush failed The database connection is not open

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 - 3 of 3 scenarios driven live against the product
Scenario Result Live Evidence
Configure a 65.74% service charge via PUT /api/settings/charges, create a dine-in order at subtotal 29725.00 via POST /api/orders, and generate a bill via POST /api/bills/generate -> order and bill pe… ✅ pass live ~/.no-mistakes/evidence/01M4V9WHBMFA5A434JG1WHJXTN/live-api-verification.json
Update the service charge rate to 10% and create a subsequent order -> new order uses 2972.50 while the previously generated bill row in SQLite retains service_charge 19541.22, total 49266.22, and cha… ✅ pass live ~/.no-mistakes/evidence/01M4V9WHBMFA5A434JG1WHJXTN/live-api-verification.json
Adversarial floating-point and currency precision boundaries: evaluate half-minor-unit ties across 2-decimal (USD 29725.00 @ 65.74% -> 19541.22), 0-decimal (JPY 2972500 @ 65.74% -> 1954122), 3-decimal… ✅ pass live ~/.no-mistakes/evidence/01M4V9WHBMFA5A434JG1WHJXTN/charges-calculation.log
  • npm run test:charges (63/63 checks passed in tests/charges-calculation.test.ts)
  • npm run test:charges-engine (196/196 checks passed in tests/charges-engine-api.test.ts)
  • Live Express API + SQLite verification (PUT /api/settings/charges, POST /api/orders, POST /api/bills/generate, and SQLite orders/bills inspection) captured in ~/.no-mistakes/evidence/01M4V9WHBMFA5A434JG1WHJXTN/live-api-verification.json
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Summary by CodeRabbit

  • Tests
    • Expanded coverage for charge rounding across currencies, including half-unit boundaries, precision edge cases, and unsafe totals.
    • Added checks for charge behavior across orders, bills, checkout, split payments, permissions, and receipts.
  • User-visible changes
    • No changes to user-facing behavior are indicated in this update.

Remove the IEEE-754 floating-point fast path in percentageMinorUnits so percentage charge calculations always use exact decimal-string/BigInt half-up arithmetic. Format touched files with oxfmt per the check-changed-format CI gate.

Fixes #1068
@khaira777 khaira777 changed the title fix: round percentage charges with exact decimal arithmetic fix(charges): round percentage fees exactly Oct 13, 2026
@coderabbitai

coderabbitai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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
  • Configuration used: Repository: FreeOpenSourcePOS/FloCafe/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0ebb9027-7645-49a0-9648-c1ecc8b62a84

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: 1fffd629-19b2-44b6-bf22-9b2e31a57229
📥 Commits

Reviewing files that changed from the base of the PR and between 0f5baed and 1aab790.

📒 Files selected for processing: 3
  • shared/charges.ts
  • tests/charges-calculation.test.ts
  • tests/charges-engine-api.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 remain after this review.

Walkthrough

The change adds unit and API test coverage for percentage rounding, charge validation, and charge behavior across orders and bills. The shared charge calculation code is reformatted. Its reported behavior and public declarations are unchanged.

Changes

Charge calculation and API coverage

Layer / File(s) Summary
Calculation and rounding coverage
shared/charges.ts, tests/charges-calculation.test.ts
The calculation code is reformatted. Unit tests add percentage rounding boundary cases and unsafe-result checks, alongside existing validation and currency assertions.
Charge API, order and split checks
tests/charges-engine-api.test.ts
API tests cover charge validation and permissions, unsafe combined totals, waivers, order-type applicability, bill recomputation, and split-check allocation.
Charge lifecycle and bill synchronization
tests/charges-engine-api.test.ts
API tests cover receipt and order conversion behavior, charge removal and cancellation, cart charge decisions, bill recomputation, historical bill amounts, and a half-cent percentage case.

Priority: ⬇️ Low

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

Change: Bug fix · Severity of issue fixed: Low

Merge Risk: ⚪ Minimal · up to 1aab7

The reported percentage-rounding fix is present for orders and bills. No actionable issue remains before normal merge checks.

Pre-merge checks: Passed 3 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Out of Scope Changes check Warning The production change is within issue #1068 scope. However, the pull request also changes tests/charges-engine-api.test.ts for unrelated charge-engine behavior, including permissions, split checks, … Remove the unrelated API test expansion and broad formatting changes, or move them to a separate pull request. Keep the percentage-rounding implementation and tests for exact half-minor-unit, currency-precision, and end-to-end persistence b…
Docstring Coverage Warning Docstring coverage is 26.09% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 3 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: exact percentage-fee rounding.
Description check Passed The description is detailed and covers the issue, implementation, scope, risk, verification commands, test results, live validation, and data-safety behavior. It does not use all template headings, bu…
Linked Issues check Passed Issue #1068 requires exact half-up percentage rounding in percentageMinorUnits. The reviewed shared/charges.ts implementation removes the floating-point product and computes the result with decima…
Full details: Out of Scope Changes check

Explanation

The production change is within issue #1068 scope. However, the pull request also changes tests/charges-engine-api.test.ts for unrelated charge-engine behavior, including permissions, split checks, receipts, charge removal, cancellation, manual legacy columns, and inactive or deleted definitions. These changes do not test the percentage rounding defect and exceed the issue's stated scope.

Resolution

Remove the unrelated API test expansion and broad formatting changes, or move them to a separate pull request. Keep the percentage-rounding implementation and tests for exact half-minor-unit, currency-precision, and end-to-end persistence behavior.

✨ 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
  • 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.

@coderabbitai

coderabbitai Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Add Carrot credits or activate Agent usage billing to use Autofix

@khaira777

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@khaira777
khaira777 enabled auto-merge (squash) October 13, 2026 20:38
@khaira777
khaira777 merged commit 74883d7 into main Oct 13, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/flocafe-issue-1068-r1 branch October 13, 2026 20:47
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(charges): eliminate IEEE-754 floating point division imprecision in half-cent percentage charges

1 participant