Repository navigation
CS-609 fix: Total calculation issue after adding discount in invoice - #1574
Conversation
Unit Test Results 1 files - 86 241 suites +154 10m 56s ⏱️ + 6m 48s Results for commit 0e710fd. ± Comparison against base commit 5805408. This pull request removes 453 and adds 358 tests. Note that renamed tests count towards both.♻️ This comment has been updated with latest results. |
yuryyas
left a comment
There was a problem hiding this comment.
Code review checked against CS-609 (USyd manual invoice: $995.45 + GST + PLUSDEX).
Price path: fixed. The repro goes through the new price > 0 branch, so the total is $500.00 (not $499.99) and Discount each ExTax fills in immediately. The formula matches the server's DiscountUtils (price − round(feeIncTax)/(1+tax)), and the new tests check out by hand.
Not covered: the "$550 after Save" symptom from the ticket. This PR only changes front-end calculation and doesn't mention save. $550 is $500 × 1.1, so the bad discount may have caused it, but please check a save round-trip on the USyd steps and confirm the saved invoice stays at $500.
The inline comments are about the other paths in the same functions. Several of these bugs existed before this PR, but they work against its stated rule price − discount + tax = total. Line numbers outside the diff are given in the comment text.
| ? discount | ||
| : discount && getDiscountAmountExTax(discount, taxRate, priceEachExTax)) || 0; | ||
|
|
||
| if (typeof discount !== 'number' && discount?.discountType === 'Fee override') { |
There was a problem hiding this comment.
This fixes the price path, but the total path is still inconsistent. getPriceAndDeductionsByTotal (around line 49, outside the diff) still gets a 0 discount for Fee override (getDiscountAmountByFeeIncTaxAndDiscount returns 0). It then rebuilds the total through this function, which always returns the rounded override, and the whole difference ends up in tax.
Example: Fee override of 454.54 at 10%. The user unlocks the discount and edits the total to 600, or changes the tax code while lastEditedField === 'total'. Result: discountEachExTax 0, price 545.45, taxEach 154.55. At 0% tax with total 500, taxEach is 45 even though the rate is 0. So price − discount + tax = total doesn't hold here.
| dispatch(change(form, `${item}.discountName`, typeof apiDiscount !== 'number' && apiDiscount?.name || null)); | ||
|
|
||
| if (typeof apiDiscount !== 'number' && apiDiscount?.discountType === 'Fee override' && row.priceEachExTax > 0) { | ||
| recalculateByPrice(row.priceEachExTax, taxRate, apiDiscount, row.quantity); |
There was a problem hiding this comment.
Possible crash: onDiscountEachExTaxLock (around line 354, outside the diff) calls onDiscountIdChange(currentDiscount) again. That passes an API Discount that's already been converted back through plainDiscountToAPIModel. The API object has no discountDollar, so discountValue becomes undefined, and this new branch passes it to getDiscountAmountByFee, which calls new Decimal(undefined).
Repro: select a Fee override on a line that has a price, click the lock icon to unlock, then click it again to re-lock. decimal.js-light throws [DecimalError] Invalid argument: undefined inside the setState updater and the invoice editor crashes. Dollar discounts hit the same throw.
| } | ||
|
|
||
| if ( | ||
| (typeof apiDiscount !== 'number' && apiDiscount !== null && apiDiscount?.discountType === 'Fee override') || |
There was a problem hiding this comment.
The Fee override branch below (for lines with price <= 0) still computes the total as bankRounding(discountValue * (1 + tax)) (around line 337) and ignores discount.rounding. The new branch above does apply rounding (via getDiscountAmountByFee), so the same discount now gives different totals depending on the price.
Example: 'Nearest dollar' override of 454.54 at 10%. On a line with price 995.45 the total is 500.00 (matches the server). On a new line with price 0 the total is 499.99 with discount 0. That's the same 1¢ error as in CS-609, reached a different way.
|
|
||
| if ( | ||
| (typeof apiDiscount !== 'number' && apiDiscount !== null && apiDiscount?.discountType === 'Fee override') || | ||
| (!discount && typeof currentDiscount !== 'number' && currentDiscount?.discountType === 'Fee override' && lastEditedField.current !== 'priceEachExTax') |
There was a problem hiding this comment.
With the early return above, picking a Fee override now keeps the user's price. But this "discount removed" condition still resets the total to the override value whenever lastEditedField !== 'priceEachExTax'.
Repro: type the total (so lastEditedField = 'total'), pick a Fee override (the price stays 995.45, discount 540.90, total 500), then clear the discount. The total becomes 499.99 and the price is recalculated to 454.54. The 995.45 price is lost even though no discount applies any more.
84eac45 to
41c55e2
Compare
yuryyas
left a comment
There was a problem hiding this comment.
Re-review of the updated PR. The earlier comments are addressed: the re-lock crash, rounding on the no-price branch, and removing an override resetting the total. Thanks!
Requesting changes for two rounding regressions in the Fee override path (financial.ts L81 and L49–52). Comparing the old and new financial.ts over ranges of whole-dollar fees shows that at tax rates other than 10% some totals now come out a cent off the rounded fee, or price − discount + tax no longer adds up to the total. Repro numbers are inline. Fee override amounts in the repros are the inc-tax fee.
Also blocking: picking a second Fee override on a line with no price now gives a different saved price and discount than picking it directly (InvoiceLines.tsx L334). The other InvoiceLines.tsx comments are about behaviour that already existed before this PR but sits in the same flow. Comments marked pre-existing, not new, follow-up, latent or nit don't block this PR.
| if (typeof discount !== 'number' && discount?.discountType === 'Fee override') { | ||
| // fee override amount is the rounded fee inc tax, convert it to ex tax discount the same way as server does | ||
| const feeOverrideExTax = base.sub(discountAmount).div(taxRateDec.add(1)); | ||
| const result = getTotalAndDeductionsByPrice(priceEachExTax, taxRate, bankRounding(base.sub(feeOverrideExTax))); |
There was a problem hiding this comment.
Regression: the total can end up 1 cent off the Fee override amount.
The total is recomputed as bankRounding((price − discountEx) × (1 + t)), which rounds again after the override amount was already rounded. At 10% GST the numbers happen to line up, but at other rates they don't.
Example: tax 15%, Fee override with 'Nearest dollar' rounding that resolves to $11 inc tax, price 2000 → total 11.01, tax 1.44 (before this PR: 11.00). Across whole-dollar fees $1–$999 at 15%, 86 come out wrong now vs 0 before.
The server (DiscountUtils.applyDiscounts) keeps the total equal to the rounded fee and puts the rounding difference into tax, so the "same way as server does" comment doesn't hold here. Something like: total = rounded fee inc tax, discountEach = bankRounding(base − total / (1 + t)), taxEach = total − (base − discountEach).
| const { total: totalRecomposed } = getTotalAndDeductionsByPrice(bankRounding(priceEachExTax), taxRate, discountRounded); | ||
| const diff = totalDec.sub(totalRecomposed); | ||
| if (!diff.isZero()) { | ||
| taxEach = taxEach.add(diff); |
There was a problem hiding this comment.
The rounding difference is applied twice, so price − discount + tax ≠ total.
taxEach starts as the unrounded afterDiscount × t, and then total − totalRecomposed is added on top. But totalRecomposed already includes the rounding of the price, so the correction is counted twice. Since the L49 change, the new no-price Fee override path hits this.
Regression example: tax 15%, line with no price, Fee override whose inc-tax fee comes to $11 → price 9.57, tax 1.42, total 11 (9.57 + 1.42 = 10.99; before this PR tax was 1.43). 434 of 4,999 whole-dollar fees at 15% are affected, vs 0 before.
The same mismatch already existed before this PR when a total is typed in: total 100.15 at 10% → price 91.05, tax 9.09 (sum 100.14). About 9% of cent totals hit it.
Suggest deriving tax from the rounded parts instead: taxEach = total − (bankRounding(priceEachExTax) − discountRounded).
| @@ -342,14 +351,16 @@ const InvoiceLineBase = React.memo<InvoiceLineBaseProps>(({ | |||
|
|
|||
| recalculate(row.total, row.priceEachExTax, row.quantity, taxRate, apiDiscount); | |||
There was a problem hiding this comment.
Switching away from a Fee override doesn't recalculate. This isn't new in this PR, but it's in the same flow this ticket fixes.
Only Fee override selections (and now removing one) recalculate unconditionally. Every other case falls through to recalculate(), which does nothing unless the price or total field has been focused (lastEditedField.current is undefined).
Repro: line with no price → pick a Fee override (this fills price/total/tax without focusing either field) → change the discount to a $10 Dollar discount. The line keeps the Fee override's total/tax/discountEachExTax while discountName shows the Dollar discount, and the total field becomes editable again.
Calling recalculateByPrice directly when a discount is selected or removed on a line that has a price would avoid depending on lastEditedField.
| return; | ||
| } | ||
|
|
||
| if (apiDiscount?.discountType === 'Fee override' && row.priceEachExTax > 0) { |
There was a problem hiding this comment.
The result depends on the order discounts are picked in.
The no-price Fee override path below (L339–349) writes a derived priceEachExTax. Picking a second Fee override then takes this priceEachExTax > 0 branch and treats the first override's ex-tax amount as the list price.
Repro (10% GST, line with no price; amounts are the inc-tax fees): pick override A ($500) → price 454.55, discount 0. Then pick override B ($300) → price 454.55, discount 181.82, tax 27.27. Picking B directly gives price 272.73, discount 0. The total is $300 both ways, but the saved price and discount differ. Before this PR, picking a Fee override always went through the total path, so this is new.
This probably needs to track whether the price was entered by the user or derived from an override.
| if (apiDiscount?.discountType === 'Fee override') { | ||
| // apply discount rounding the same way as getDiscountAmountByFee does for lines with price | ||
| const total = bankRounding(getRoundingByType(apiDiscount.rounding, new Decimal(apiDiscount.discountValue).mul(new Decimal(taxRate).plus(1)))); | ||
| recalculateByTotal( |
There was a problem hiding this comment.
Pre-existing (this PR rewrote it): quantity > 1 on a line with no price.
recalculateByTotal divides the total by quantity (L250), but total here is already the per-unit fee, while L348 multiplies it by quantity for the line total.
Repro: quantity 2, 10% GST, no price, Fee override whose inc-tax fee is $500 → price 227.27, tax 22.73, line total 1000. A later quantity blur then gives discountEachExTax −227.28 with a total of 1000.
Fix: pass decimalMul(total, row.quantity) to recalculateByTotal here.
| const onDiscountIdChange = discount => { | ||
| const apiDiscount: Discount | number = typeof discount !== 'number' && discount ? plainDiscountToAPIModel(discount) : null; | ||
| const applyDiscount = (apiDiscount: Discount) => { | ||
| const removedFeeOverride = !apiDiscount && typeof currentDiscount !== 'number' && currentDiscount?.discountType === 'Fee override'; |
There was a problem hiding this comment.
removedFeeOverride and the re-lock path both depend on currentDiscount, which isn't always the discount object. It's loaded asynchronously for existing lines, and it becomes a number after a manual discount edit.
- Open a quote whose line has a Fee override and clear the discount before the discount fetch resolves →
currentDiscountis null → falls through torecalculate()(does nothing) → the line keeps the override's total/tax. - Unlock, type a discount, re-lock →
currentDiscountis a number, soonDiscountEachExTaxLock(L360) skipsapplyDiscount. The icon shows locked, but the discount isn't re-applied.
The same dependency existed before this PR. Lower priority than the rounding issues, but worth guarding.
| @@ -75,15 +75,27 @@ export function getTotalAndDeductionsByPrice( | |||
| ? discount | |||
| : discount && getDiscountAmountExTax(discount, taxRate, priceEachExTax)) || 0; | |||
There was a problem hiding this comment.
Follow-up: the root cause is wider than Fee override.
getDiscountAmountByFee / getDiscountAmountExTax apply the discount's rounding to the ex-tax amount, while the server rounds the inc-tax total and adjusts tax. Special-casing Fee override fixes that one type, but Percent and Dollar discounts with rounding still disagree with the server:
- Price 100 ex, 10% GST, 15% Percent discount with 'Nearest dollar' → client total 93.50, discount 15.00. The server (
getDiscountedFee+applyDiscounts) gives total 94.00, discount 14.55. - Dollar discount 7.30 with 'Nearest dollar' → client total 102.30, which isn't a whole dollar.
Fine as a separate ticket. If the shared helper matched the server, the Fee override branch here wouldn't be needed.
| : afterDiscount.add(tax); | ||
| if (typeof discount !== 'number' && discount?.discountType === 'Fee override') { | ||
| // fee override amount is the rounded fee inc tax, convert it to ex tax discount the same way as server does | ||
| const feeOverrideExTax = base.sub(discountAmount).div(taxRateDec.add(1)); |
There was a problem hiding this comment.
Latent (not reachable from InvoiceLines today): for Fee override, getDiscountAmountExTax applies discountMin/discountMax to a mixed value (ex-tax price − inc-tax fee). This line then converts the clamped value again, so the final ex-tax discount can exceed the configured max.
Example: price 1000, 10% tax, Fee override configured at 454.54 ex tax with 'Nearest dollar' ($500 inc tax), discountMax 100 → clamped to 100 → feeOverrideExTax 818.18 → discountEach 181.82 (> 100). plainDiscountToAPIModel currently drops min/max, so this only bites once a caller passes them.
| // adjust tax by rounding difference so that price minus discount plus tax equals total | ||
| return { | ||
| ...result, | ||
| taxEach: bankRounding(new Decimal(result.total).sub(base.sub(result.discountEach))) |
There was a problem hiding this comment.
nit: this override doesn't change anything. The recursive call already returns taxEach = bankRounding(total − (base − discountEach)) (L99), so return result does the same thing, and the "adjust tax by rounding difference" comment is misleading.
…sues from review - Keep Fee override total equal to the rounded fee and put rounding difference into tax - Derive tax from rounded price and discount when calculating by total - Recalculate invoice line when switching discounts, independent of picking order - Calculate no-price Fee override per unit so quantity > 1 is correct - Apply discount min/max to the ex tax Fee override discount like the server - Guard line discount loading and re-apply selected discount on re-lock Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
yuryyas
left a comment
There was a problem hiding this comment.
Re-checked c1f3c69: the review comments are addressed. Re-running the rounding checks: Fee override with and without a price, and typed-in totals, now give 0 wrong cases (previously 86/999 at 15%, 434/4999 at 15%, and 9091/100000 at 10%). Quantity > 1, picking one override after another, and discount min/max all come out right. The Percent/Dollar 'Nearest dollar' mismatch with the server is still open as a follow-up. LGTM.
Fix
financial.ts: for Fee override, convert the rounded inc-tax fee to an ex-tax discount the same way the server does (price − roundedFeeIncTax / (1 + taxRate)). Total and tax are then calculated with the existing numeric-discount logic. Tax is adjusted by any rounding difference so thatprice − discount + tax = total.InvoiceLines.tsx: when a Fee override is selected on a line with a positive price, recalculate from the price (existingrecalculateByPrice), so the discount fills in straight away and the price is kept.