Skip to content

CS-634 discount rounding inconsistency between client and server - #1584

Open
SnehaShahAzrachIT wants to merge 2 commits into
mainfrom
CS-634_Discount_Rounding_Inconsistency_Between_Client_and_Server
Open

SnehaShahAzrachIT wants to merge 2 commits into
mainfrom
CS-634_Discount_Rounding_Inconsistency_Between_Client_and_Server

Conversation

@SnehaShahAzrachIT

@SnehaShahAzrachIT SnehaShahAzrachIT commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The invoice line discount now follows server DiscountUtils. The line total is calculated the way InvoiceApiService.updateInvoiceLines saves it, so the total shown before saving is the total that gets saved.

 getTotalAndDeductionsByPrice(price, rate, discount)
-  discountEach = price - rounding(price ex tax after discount)       // rounding on ex tax amount
-  total        = round(price - discountEach) * (1 + rate)
+  discountEach = price - getDiscountedFee(discount, rate, price) / (1 + rate)
+                 // like DiscountUtils: min/max, cap at price, rounding on total inc tax
+  total, taxEach = getInvoiceLineTotalAndTax(price, discountEach, rate)
+                 // like the server save: tax = (price - discount) * rate, total rounded half even
  • getRoundingByType: matches Money.round. This fixes "Nearest 50 cents" under $1 and for negative amounts.
  • Fee override: no longer a special case. A line without a price gets its total from the same save rule.
  • Credit lines (negative price): keep their discount. Before, the whole line was discounted.
  • Discount min/max: loaded for invoice and quote line discounts, so they apply the way they do in checkout.
  • Discount lock: disabled on saved invoices, so it no longer rewrites read-only amounts.
  • Class budget: the discount is calculated from the class fee ex tax, as the server does.

Not in this PR: the CS-609 follow-ups from the review (discount state when lines shift, detecting an override-derived price, a typed total after a Fee override), and the "Final class fee" display in the class budget.

Why the total is built from the saved parts: price and discount are saved in cents, and the server works out tax itself. At 10% (AU GST) and 20% (UK VAT), any rounded total survives that (e.g. 34.55 × 1.1 = 38.005, which rounds half-even to $38.00). At 15% some can't: 9.56 gives 10.99 and 9.57 gives 11.01, so nothing gives $11.00. There the client now shows the cent the server will save, instead of showing $11.00 and saving $11.01.

Evidence

Line Before After
$100 ex tax, 15% off, Nearest dollar, 10% GST 93.50 (checkout charges 94.00) 94.00
$100, 50% off with max $20, 10% GST 55.00 (checkout 88.00) 88.00
−$100 credit line, 10% off, 10% GST 0.00 (whole line discounted) −99.00
$11.11, 15% off, Nearest dollar, 15% tax shows 11.00, saved as 11.01 shows 11.01 = saved
Saved invoice, click discount lock line amounts rewritten lock disabled
npx jest src/tests/common/utils/financial.test.ts src/tests/entities/invoices/InvoiceLineDiscountRecalculation.test.ts
Test Suites: 2 passed, 2 total
Tests:       150 passed, 150 total

The tests check every total against a separate copy of the server save formula at 0, 5, 10, 12.5, 15, 20 and 25% tax, and against the server DiscountUtilsTest cases. With sampled grids plus boundary values, both suites run in about 36 s with coverage. Before, financial.test.ts alone took about 60 s.

Merge Danger

Door: two-way. Client only, with no API or schema change. Discounted lines saved while this is live keep their amounts if it's reverted.

Blast Radius: discounted invoice/quote lines and class budget discounts.

  • At 10% GST, discounts with rounding now round the total inc tax, not the ex-tax price (e.g. 93.50 becomes 94.00), so they match checkout.
  • Discounts with min/max now apply them on invoice and quote lines.

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Unit Test Results

408 tests   408 ✔️  10m 23s ⏱️
241 suites      0 💤
    1 files        0 ❌

Results for commit 4f36e95.

♻️ This comment has been updated with latest results.

@yuryyas yuryyas left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. At 10% GST the new shared helper matches the server: I sampled 5,379 prices per discount type, and the total the client shows always matched what the server saves.

Please rebase onto main first. This branch still carries #1574's original commits (5b38807, 41c55e2, c1f3c69). #1574 has been rebase-merged as 35242f1, 074404e, 58bf579, so after a rebase only c9feadab should be left. It may conflict in financial.ts.

Requesting changes for:

  1. At tax rates other than 10%, about 9% of rounded Percent/Dollar lines save a cent higher than the client shows (financial.ts L89). The server discards the client's tax on save.
  2. A discount on a credit line (negative price) now zeroes the whole line (discounts/utils L111).
  3. Discount min/max never reaches invoice/quote lines, so "min/max like the server" doesn't hold there (discounts/utils L109).
  4. The discount lock rewrites read-only amounts on saved invoices (InvoiceLines.tsx L380). This is from #1574 and is already on main. It's in the same flow, so please fix it here.

The other comments marked "Already on main" are about #1574 code that's in this diff. Fix them here or in a follow-up, whichever is easier. Comments marked nit don't block.

taxEach: bankRounding(tax)
total,
discountEach,
taxEach: bankRounding(new Decimal(total).sub(afterDiscount))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The rounded total doesn't survive the save at tax rates other than 10%.

This puts the rounding difference into taxEach, but InvoiceApiService.updateInvoiceLines ignores the client's taxEach for manual invoices and quotes. It computes a taxAdjustment and then calls InvoiceUtil.calculateTaxEachForInvoiceLine(price, discount, rate, taxAdjustment), which drops the adjustment and returns (price − discount) × rate. That has been the case since CS-244 (2ec785854). The line total is then price − discount + taxEach, rounded half-even.

Comparing this function's total with what that save path produces, over 5,379 prices from $10 to $2000:

  • 10% GST: no differences for any discount type.
  • 15% tax: 470 of 5,379 lines differ for a 15% Percent or $7.30 Dollar discount with 'Nearest dollar'. Example: price 11.11, 15% off, 'Nearest dollar' → client discount 1.54, tax 1.43, total 11.00. Saved: (11.11 − 1.54) × 1.15 = 11.0055 → 11.01.
  • Already on main: a Fee override with 'Nearest dollar' at 15% has the same problem (467 of 5,379), so it isn't new with this PR.

This needs a decision on which side keeps the rounding: either the server applies taxAdjustment again for manual lines (CS-244 removed it on purpose, so please check why), or the client doesn't round totals the server can't keep. Let's agree on that before changing the code.


amount = new Decimal(applyDiscountMinMax(discount, amount.toNumber()));

return priceExTax.lt(amount) ? priceExTax : amount;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A discount on a credit line (negative price) now wipes out the whole line.

For a negative price, priceExTax.lt(amount) is true for any discount. Example: price −100, 10% Percent → amount −10, and −100 < −10, so the discount becomes −100. Then getDiscountedFee returns 0 (discount ≥ price), and getTotalAndDeductionsByPrice gives { total: 0, discountEach: -100, taxEach: 0 } instead of the previous total −99. A $10 Dollar discount does the same.

The server copies this cap from DiscountUtils, but checkout never sees negative prices. Manual invoices do (InvoiceApiService allows them), and on save the server takes the client's discountEachExTax as-is, so the zeroed line gets saved. Suggest capping only when priceExTax is positive, e.g. priceExTax.gt(0) && priceExTax.lt(amount) ? priceExTax : amount, and adding a credit-line test.

amount = new Decimal(0);
}

amount = new Decimal(applyDiscountMinMax(discount, amount.toNumber()));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Min/max never reaches invoice and quote lines.

applyDiscountMinMax is applied here, but invoice-line discounts are built by plainDiscountToAPIModel (L11–23) from INVOICE_LINE_DISCOUNT_COLUMNS = 'name,discountType,discountDollar,discountPercent,rounding'. That model has no discountMin/discountMax, so on invoice and quote lines this is always a no-op.

Example: a 50% Percent discount with discountMax 20 on a quote line priced 100 → the invoice editor applies 50 (total 55), while checkout and the server's DiscountUtils apply 20 (total 88). The new min/max tests use hand-built Discount objects, so this path isn't covered.

Please add discountMin,discountMax to the columns and map them in plainDiscountToAPIModel, plus a test that goes through that mapping.

return !prev;
});
if (!discountEachExTaxLocked && selectedDiscount) {
applyDiscount(selectedDiscount);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already on main (merged with #1574), but it shows up in this diff. Please fix it in this PR, though, since it's the same flow.

Locking the discount now always calls applyDiscount(selectedDiscount), and for a line with a price that goes to byPrice for every discount type. Before #1574, only a Fee override recalculated here. Other types went through recalculate(), which did nothing without a focused field. The lock button (L545) is only disabled while loading, not by disableFinanceFileds, and discountEachExTaxLocked starts as false, so the first click on a saved invoice recalculates its read-only line.

Repro: open a saved invoice whose line came from checkout with a Percent discount that has a discountMax or a class discount override, then click the lock. New discountEachExTax, taxEach and total are written into the form without the max or override. The form becomes dirty and shows amounts that differ from the database (the server ignores line changes on saved invoices).

Suggest disabling the lock button when disableFinanceFileds, or skipping applyDiscount in that case.

setLoading(false);
});
} else {
} else if (!row.discountId) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already on main (merged with #1574), but it shows up in this diff.

The fallback changed from else { setCurrentDiscount(null) } to else if (!row.discountId). When row.discountId changes to another non-null id while currentDiscount is a number (a manually typed discount), nothing is fetched or reset. The previous line's currentDiscount, selectedDiscount and feeOverridePriceEachExTax then stay attached to a different line.

Repro: two unsaved lines (rendered by index): L0 with discount A; L1 with discount B and a typed discount of 5. Add a line, which inserts at index 0 and shifts the rows. The component that held L1's state now renders the line with discount A, currentDiscount is 5, so no fetch runs. Blurring the price applies the manual 5, and re-locking applies discount B to a line whose discountId is A.

Suggest fetching whenever row.discountId doesn't match the loaded discount, including when currentDiscount is a number, and resetting feeOverridePriceEachExTax there too.

const applyFeeOverride = (
line: Line,
previousDiscount: Discount,
discount: Discount,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already on main (merged with #1574), but it shows up in this diff. nit: applyFeeOverride reimplements applyDiscount ("mirrors applyDiscount in InvoiceLines.tsx") instead of exercising it. It always uses quantity 1, passes lastEditedField as undefined, and skips the byLastEditedField branch, so changes to the real applyDiscount won't be caught. Extracting applyDiscount's dispatch logic into a pure function that both the component and the test call would fix that.

COURSE_CLASS_COST_DIALOG_FORM,
"perUnitAmountExTax",
bankRounding(getDiscountAmountExTax(discount, currentTax.rate, classFee))
bankRounding(getDiscountAmountExTax(discount, currentTax.rate, classFeeExTax))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While you're in this component: 'Final class fee' (discountTotalFee, L180–185) is still computed separately: classFee − perUnit − bankRounding(perUnit × rate), then rounded again. CourseClassEditView.tsx:204 has its own local getDiscountedFee that does the same. With 'No Rounding' the shown final fee can be a cent off the server's DiscountUtils.getDiscountedFee, and the local function now shares a name with the new helper in discounts/utils.

Suggest using the new getDiscountedFee(discount, rate, classFeeExTax) in both places. Not blocking.

? discount
: discount && getDiscountAmountExTax(discount, taxRate, priceEachExTax)) || 0;
const discountAmount = discountEntity
? getDiscountAmountExTax(discountEntity, taxRate, priceEachExTax)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: getDiscountAmountExTax already calls getDiscountedFee (discounts/utils L146), and L83 calls it again for the total, so the discounted fee is computed twice per call. Computing it once and deriving the discount as toMoney(price − toMoney(fee / taxMul)) would simplify this.

case "Nearest dollar":
return value.toDecimalPlaces(0).toNumber();
// server drops fraction of cents before rounding to dollar
return value.toDecimalPlaces(2, Decimal.ROUND_DOWN).toDecimalPlaces(0, Decimal.ROUND_HALF_UP).toNumber();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: truncating to cents before ROUND_HALF_UP to dollars never changes the result. Truncating can't move a value across the .50 boundary (anything ≥ x.50 still truncates to ≥ x.50). value.toDecimalPlaces(0, Decimal.ROUND_HALF_UP) gives the same result, and the comment suggests a difference that doesn't exist.

];

describe.each(discountsByTotal)('with %s', (_, discount) => {
it.each([0, 0.05, 0.1, 0.125, 0.15, 0.2, 0.25])(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: these loops are large: 10,000 totals × 7 rates × 5 discounts here, plus the price × discount × rate × rounding and Fee override grids below. financial.test.ts takes about 60 s locally, on every CI run. A sampled grid plus the known boundary values (the .5 ties, the 15% cases above) would give the same confidence.

@SnehaShahAzrachIT
SnehaShahAzrachIT force-pushed the CS-634_Discount_Rounding_Inconsistency_Between_Client_and_Server branch from c9feada to 6270373 Compare November 18, 2026 04:16
…ount min/max and lock on saved invoices

- Calculate invoice line total and tax from rounded price and discount the way
  InvoiceApiService saves them (tax = (price - discount) * rate, total rounded half even).
  Discount rounding still gets into the total through the discount amount, so totals are
  unchanged at 10% and 20%, and at rates like 15% the client shows what the server saves
- Fee override line without price uses the same total
- Credit line (negative price) keeps its discount instead of being zeroed, and is treated
  as a line with price when a discount is picked
- Load discountMin/discountMax for invoice line discounts so min/max apply as on checkout
- Disable discount lock on saved invoices so it doesn't rewrite read-only amounts
- Drop no-op cent truncation in 'Nearest dollar' rounding
- Tests: check against server save formula, credit lines, min/max mapping, smaller grids

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

2 participants