Repository navigation
CS-634 discount rounding inconsistency between client and server - #1584
SnehaShahAzrachIT wants to merge 2 commits into
Conversation
yuryyas
left a comment
There was a problem hiding this comment.
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:
- At tax rates other than 10%, about 9% of rounded Percent/Dollar lines save a cent higher than the client shows (
financial.tsL89). The server discards the client's tax on save. - A discount on a credit line (negative price) now zeroes the whole line (
discounts/utilsL111). - Discount min/max never reaches invoice/quote lines, so "min/max like the server" doesn't hold there (
discounts/utilsL109). - The discount lock rewrites read-only amounts on saved invoices (
InvoiceLines.tsxL380). This is from #1574 and is already onmain. 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)) |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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())); |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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])( |
There was a problem hiding this comment.
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.
c9feada to
6270373
Compare
…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>
Summary
The invoice line discount now follows server
DiscountUtils. The line total is calculated the wayInvoiceApiService.updateInvoiceLinessaves it, so the total shown before saving is the total that gets saved.getRoundingByType: matchesMoney.round. This fixes "Nearest 50 cents" under $1 and for negative amounts.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
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
DiscountUtilsTestcases. With sampled grids plus boundary values, both suites run in about 36 s with coverage. Before,financial.test.tsalone 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.
🤖 Generated with Claude Code