Skip to content

Apply category tax rules to distance expenses without a rate tax - #101674

Open
Krishna2323 wants to merge 17 commits into
Expensify:mainfrom
Krishna2323:krishna2323/fix/100544-distance-category-tax-rule
Open

Krishna2323 wants to merge 17 commits into
Expensify:mainfrom
Krishna2323:krishna2323/fix/100544-distance-category-tax-rule

Conversation

@Krishna2323

@Krishna2323 Krishna2323 commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

Fixed Issues

$ #100544
PROPOSAL:

Tests

Prerequisites:

  1. Use an Expensifail account with a workspace that has Taxes, Distance rates, and Rules enabled.
  2. Under Taxes, create a non-default rate TaxA at 10%. Leave the workspace default as Tax exempt (0%).
  3. Under Distance rates, enable Track tax and create a rate Rate-NoTax, leaving its tax rate unset.
  4. Under Rules > Add rule > Apply expense defaults, add a rule with Category Car and Tax TaxA. Save.

Steps:

  1. Open the workspace chat and start a distance expense.
  2. Set a route and continue to the confirm page.
  3. Set Rate to Rate-NoTax.
  4. Set Category to Car.
  5. Verify the Tax field shows TaxA (10%) and Tax amount is 10% of the expense amount, not 0.
  6. Tap Create expense, then open the created expense.
  7. Verify the Tax field still shows TaxA (10%), so the confirm page matched what was created.
  • Verify that no errors appear in the JS console

Offline tests

  • Same as tests

QA Steps

  • Same as tests

  • [c] Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I verified there are no new alerts related to the canBeMissing param for useOnyx
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
android_hybrid.mp4
Android: mWeb Chrome
android_mWeb.mp4
iOS: Native
ios_hybrid.mp4
iOS: mWeb Safari
ios_mWeb.mp4
MacOS: Chrome / Safari
web_chrome.mp4

@Krishna2323

Copy link
Copy Markdown
Contributor Author

@MelvinBot review

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 Reviewed — the approach is right, but there are two blockers.

1. CI is red — three existing tests fail

Jest shards job 6 and job 7:

  • TransactionUtils › getCategoryTaxDetails › should return undefined tax › if the transaction type is distance — Expected: undefined, Received: "id_TAX_RATE_1"
  • actions/IOU/UpdateMoneyRequest › updateMoneyRequestCategory › should not update the tax › if the transaction type is distance
  • actions/IOU › setMoneyRequestCategory › should not change the tax › if the transaction type is distance

These encode the old "distance never picks up a category tax rule" behavior, so they need to change. But don't just flip the expectations — see below, because those three tests are set up in exactly the scenario that this PR now gets wrong.

2. Nothing guards the "Track tax is off for distance" case

The old guard was isDistanceRequest(transaction). The replacement at src/libs/TransactionUtils/index.ts:3362 only trips when the rate carries its own tax code. It never checks whether distance tax tracking is enabled at all.

When the workspace has Taxes on, a category tax rule exists, but Track tax is off on distance rates:

  • getDefaultTaxCode returns undefined (it only falls back to the workspace default when taxEnabled is true), so defaultTaxCode is ''.
  • categoryTaxCode therefore wins at index.ts:2823, and getCategoryTaxDetails returns a real code with a truthy taxValue.
  • setMoneyRequestCategory then writes taxCode/taxAmount/taxValue onto the transaction — while isTaxTrackingEnabled returns false for distance, so the Tax field is hidden and the user never sees it.

Every pre-existing getDistanceRateTaxUpdates call site is wrapped in an isTaxTrackingEnabled check (MoneyRequest.ts:1122, UpdateMoneyRequest.ts:272, DynamicIOURequestStepDistanceRate.tsx:210). The new one is the only one without it.

Suggested fix — bail when distance tax tracking is off, not just when the rate has its own code:

const distanceCustomUnit = customUnitRateID === undefined ? undefined : getDistanceRateCustomUnit(policy);
const shouldSkipDistanceTax = customUnitRateID !== undefined && (!distanceCustomUnit?.attributes?.taxEnabled || !!getDistanceRateCustomUnitRate(policy, customUnitRateID)?.attributes?.taxRateExternalID);
if (!taxRules || taxRules.length === 0 || shouldSkipDistanceTax) {
    return {categoryTaxCode: undefined, categoryTaxAmount: undefined, categoryTaxValue: undefined};
}

The three failing tests all use createRandomPolicy, which has customUnits: {} — so they are the Track-tax-off case. With this guard they keep passing as-is, and you'd add new cases for track-tax-on.

Smaller things
  • Unannounced change to the rate-change flow. Defaulting category to transaction?.category in getDistanceRateTaxUpdates also changes the three existing callers: switching to a rate with no tax now resolves to the category rule instead of the workspace default. That looks intentional and correct, but it isn't in the test plan and has no test. Worth a Tests step: set Category Car, then change Rate to another rate with no tax, and verify Tax stays TaxA (10%).
  • Dead fallback. getRateID(transaction) ?? '' at index.ts:3360 — getRateID returns string (falls back to FAKE_P2P_ID itself), so ?? '' never fires. Drop it, or the '' will read as a meaningful sentinel to the next person.
  • Unit tests. The author checklist has "I added unit tests" ticked, but the diff has none. Both precedence rules (rate tax beats category rule, category rule beats workspace default) and the track-tax-off case are cheap to cover in TransactionUtilsTest.ts.
  • /* eslint-disable max-lines */. Matches precedent (ReportUtils.ts, SearchUIUtils.ts), so not a blocker — just noting it's the file's first one, added for 18 net lines.
  • Screenshots. All platform sections are empty.

I didn't run the app test steps — worth doing once CI is green.


Reply with @MelvinBot <your feedback> if you want me to dig into any of this further.


view run

@Krishna2323
Krishna2323 marked this pull request as ready for review October 12, 2026 13:26
@Krishna2323
Krishna2323 requested review from a team as code owners October 12, 2026 13:26
@melvin-bot
melvin-bot Bot requested review from JmillsExpensify and situchan and removed request for a team October 12, 2026 13:27
@melvin-bot

melvin-bot Bot commented Oct 12, 2026

Copy link
Copy Markdown

@situchan Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-19T17:30:55.875517Z 54d2665 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@JmillsExpensify JmillsExpensify left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@Krishna2323

Copy link
Copy Markdown
Contributor Author

@situchan friendly bump

@situchan

situchan commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified any copy / text that was added to the app is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If the PR adds or modifies the UI:
    • I asked an AI agent to review the changes for accessibility issues and addressed its findings.
    • I tested with a screen reader (VoiceOver on macOS) and verified all new/changed elements are reachable with a logical focus order.
    • I verified all new/changed elements have meaningful accessible names and roles.
    • I verified state changes are announced (e.g. checked/unchecked, expanded/collapsed, selected).
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: HybridApp
Android: mWeb Chrome
iOS: HybridApp
iOS: mWeb Safari
MacOS: Chrome / Safari
test.mov

Comment thread src/components/MoneyRequestConfirmationList/hooks/useTaxAmount.ts Outdated
Comment thread src/libs/TransactionUtils/tax.ts Outdated
@MelvinBot

MelvinBot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🤖 Web test steps verification results: ⚠️ partial

The core fix works on web. The category rule sets TaxA on a no-tax rate, and a rate's own tax still wins. Step 1 failed only because Tax amount shows $0.00. That comes from the test setup, not the PR (see the note below the table). I found one real behavior change, a tax reset on category change, described after the table.

Rate-WithTax sets Tax to TaxB (20%)

Step Status
1. Distance, Rate-NoTax + Category Car → Tax TaxA (10%), non-zero Tax amountTax showed TaxA (10%), but Tax amount was $0.00 on a $3.29 expense. Rate-WithTax, which the PR does not touch, also showed $0.00. The cause is setup: the tester never set "Tax reclaimable on", and getTaxableAmount defaults that to 0.
Confirm page: Tax TaxA (10%), Tax amount $0.00
❌
2. Create it and open it → Tax still TaxA (10%)The created expense shows TaxA (10%).
Created expense showing Tax TaxA (10%)
✅
3. Distance, Rate-WithTax (TaxB) + Car → Tax stays TaxB (20%)Tax showed TaxB (20%). The rate's tax wins over the category rule.
Rate-WithTax + Car shows TaxB (20%)
✅
4. Category Car first, then Rate NoTax → WithTax → NoTaxTax went TaxA → TaxB → TaxA, following each rate change.
Rate-NoTax shows TaxA (10%)Rate-WithTax shows TaxB (20%)Back to Rate-NoTax shows TaxA (10%)
✅
5. Manual expense + Car → TaxA; manually picking Tax exempt sticksTax showed TaxA (10%), with a $0.91 Tax amount on $10.00. Picking Tax exempt stuck and did not revert.
✅
6. Manual expense + Other (no rule) → workspace defaultTax showed Tax exempt (0%) • Default.
✅
7. Edit the created distance expense: Category → Other, then change RateCategory Other reset Tax to Tax exempt (0%). The history logged "the tax rate to 0% (previously 10%)". Changing Rate to Rate-WithTax then set Tax to TaxB (20%).
Category Other resets Tax to Tax exemptRate-WithTax sets Tax to TaxB (20%)
✅
8. No console errors or re-render loopsThe web harness cannot read the browser console. All network requests returned 200 or 204, and no render loops showed up in code review.
✅

Regression found in code review

Changing the category on a distance expense now overwrites the tax with the workspace default, even when the new category has no rule. Step 7 shows this live.

  • This happens when distance Track tax is on, the rate has no tax of its own, and the policy has any category tax rule.
  • On main, distance always returned undefined here, so a tax the user picked survived a category change.
  • Now getCategoryTaxDetails returns the result of getDistanceRateTaxUpdates. That calls getCategoryDefaultTaxRate, which falls back to the workspace default for a category with no rule.
  • The result is then written in getUpdatedTransaction.ts:409-415 for edits and split drafts, and by setMoneyRequestCategory on create.
  • Repro: rule on Car, rate with no tax. Pick TaxB by hand, then change the category to Other. Tax resets to Tax exempt.

Manual expenses already behave this way on main, so this may be intended parity. If it is, add a test and a Tests step. If it is not, return undefined for distance when the category has no rule.

Lower-risk items
  • Optimistic vs server mismatch (unverified). updateMoneyRequestCategory sends only category. The new distance tax on category edit is client-side only. If Auth does not apply category rules to distance, the tax will show the rule's rate and then revert. Step 7's history entry suggests it persisted, but I could not check Auth.
  • Rate changes now use the category rule. The category ?? transaction?.category fallback changes all three existing getDistanceRateTaxUpdates callers: the rate picker, date edits, and the create-flow date change. Step 4 confirms this looks correct. No unit test covers it.
  • Currency edge case. On a manual expense with a category rule, suppose the user picks the workspace default and then changes the currency. The tax is no longer reset to the new currency's default, because previousDefaultTaxCode is now the rule's code. This is narrow.
  • Disabled rule tax. A category rule that points at a disabled tax still beats a selectable workspace default for distance. The rate tax gets an isSelectableTaxCode check, but the rule tax does not.
  • Test steps. Step 5 of the PR's Tests says the tax amount is 10% of the expense amount. For distance, it is 10% of the reclaimable portion, so testers must set "Tax reclaimable on" first.

Ruled out: per diem, time, and manual expenses with no rule (unchanged), and render loops. CI jest, typecheck, and lint pass. The only failing check is "Check independent approval".


view run · view recording

@Krishna2323
Krishna2323 requested a review from situchan October 19, 2026 14:14
@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 No blockers at 54d2665. Both of situchan's inline bugs are fixed, and CI is green apart from "Check independent approval."

  • Snap-back to the rule's tax: fixed. previousDefaultTaxCode now resolves the rule first, so picking the workspace default sticks. A test covers it.
  • Disabled rate tax depends on order: fixed. Both paths now use isSelectableTaxCode, so either order gives TaxA. A test covers it.

One question is still open from my last review. Please confirm it is intended.

A category change on a distance expense resets a hand-picked tax. Suppose you pick TaxB and then switch to a category with no rule. getCategoryTaxDetails returns the workspace default, and the default overwrites TaxB. Manual expenses already work this way on main, so this is probably intended parity. If it is, add a Tests step for it.

Nits
  • Partial guard. The distance check at tax.ts:234-235 reads only the distance unit's taxEnabled. isTaxTrackingEnabled also needs policy.tax.trackingEnabled. If workspace Taxes are off and old tax rules still exist, the code can write a tax to a hidden field. Manual expenses behave the same on main, so this is low risk. I have not reproduced it.
  • Dead fallback. getRateID(transaction) ?? '' at tax.ts:228 never uses the '', because getRateID always returns a string.
  • Rate-change path has no test. The category ?? transaction?.category fallback means the rate picker and date edits now apply the category rule. That works in manual testing, but no unit test covers it.
  • Tests step 5 needs a setup step. For distance, the tax amount stays at 0 until "Tax reclaimable on" is set on the rate. Add that to the prerequisites.

@situchan

Copy link
Copy Markdown
Contributor

Regression found in code review

Changing the category on a distance expense now overwrites the tax with the workspace default, even when the new category has no rule.

I don't think the category change reset is a regression. The repro needs "pick TaxB by hand", but Tax is read-only on distance expenses, both on confirm and on the expense view. A distance tax always comes from the rate, the category rule or the workspace default. So in step 7, moving from Car to Other drops the rule and Tax exempt is the correct value.

@situchan situchan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A few nab comments for code optimization

Comment thread src/libs/TransactionUtils/tax.ts Outdated
Comment thread src/components/MoneyRequestConfirmationList/hooks/useTaxAmount.ts
Comment thread src/libs/TransactionUtils/tax.ts Outdated
Comment thread tests/unit/TransactionUtilsTest.ts Outdated
@melvin-bot
melvin-bot Bot requested review from JS00001 and MariaHCD October 19, 2026 17:27

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 54d2665dc4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/libs/TransactionUtils/tax.ts Outdated
Comment thread src/libs/TransactionUtils/tax.ts Outdated
@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 I found one regression and two older bugs that this PR now reaches on distance expenses. Manual expenses look clean. I traced this in code and did not run the app.

situchan is right about my earlier "category change resets the tax" item. Tax is read-only on distance expenses, so it is not a regression. I've dropped it.

1. Regression: commuter exclusion is ignored when you pick a category

getDistanceRateTaxUpdates calculates tax on the full trip. The confirm page calculates it on the reimbursable distance after the commuter exclusion (useTaxAmount.ts:79-87). getCategoryTaxDetails now calls the first helper for distance expenses, so picking a category writes a full-trip tax amount.

To reproduce:

  1. Turn on Track tax and a commuter exclusion, add any category tax rule, and use a rate with no tax of its own.
  2. Create a map distance expense. Make the exclusion leave 20 of 30 miles reimbursable.
  3. On the confirm page, pick a category whose tax has the same percentage as the current one. For example, pick a category with no rule.

Expected: the tax amount stays based on 20 miles, as on main.
Actual: the tax amount is based on 30 miles, and that amount is submitted.

The category setter writes the larger amount. Nothing corrects it, because TaxController only rewrites the amount when the hook's own value changes. With a different percentage, the hook's value changes and the amount is corrected.

Fix: in getDistanceRateTaxUpdates, use the reimbursable distance from getCommuterExclusionDisplayData, as useTaxAmount does. That also fixes the same bug on the rate picker and on date edits, which already exists on main.

2. Older bugs this PR now reaches on distance expenses

  • Category edits on saved expenses. getUpdatedTransaction.ts:409-415 now updates the distance tax amount on screen before the server responds. On expense reports it skips the sign flip that L382-L384 applies, so the tax may show as negative until the server responds. Manual expenses already have this bug on main.
  • A rule that points at a disabled tax. The rate's tax is checked with isSelectableTaxCode, but the rule's tax is not (tax.ts:124). A distance expense can get the disabled tax, and you can't change it because the field is read-only. Main used the selectable workspace default.
Lower-confidence items and what I ruled out

Plausible, but the outcome depends on the backend:

  • Hidden tax. If workspace Taxes are off but distance Track tax is still on, the distance check lets a category rule write a tax amount to a hidden field. isTaxTrackingEnabled also requires policy.tax.trackingEnabled. Turning Taxes off does not reset the distance attribute.
  • Server and screen may disagree. updateMoneyRequestCategory sends only category. If the server does not apply the rule to distance expenses, the tax shown on screen won't match what the server saved.

Ruled out:

  • Manual expenses. The only change: a category with a rule now opens on the rule's tax, which is the intended fix.
  • Prefilled categories, workspace switches, moving a tracked expense, per diem, time, P2P, and clearing the category.

Test gap: three existing "distance never gets category tax" tests pass only because createRandomPolicy has customUnits: {}. No test covers category edits on saved distance expenses, commuter exclusion, or disabled rule taxes.

@Krishna2323

Copy link
Copy Markdown
Contributor Author

@MelvinBot review

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 I found no blockers at 7b0df50. The new commits fix the two main items from my last review. Some Jest shards are still running.

  • Commuter exclusion: fixed. getDistanceRateTaxUpdates now taxes only the reimbursable distance, the same way useTaxAmount does. This also fixes the rate picker and date edits. A test covers it.
  • Rule that points at a disabled tax: fixed. getSelectableCategoryTaxCode falls back to the default. This applies to manual expenses too, so they no longer save a disabled tax. A test covers it.
  • getDefaultTaxCode refactor: I checked every branch, and it returns the same values as before.

Two low-risk items are still open. Both already happen on manual expenses on main.

Open items
  • Sign on optimistic category edits. On a saved expense, the category branch at getUpdatedTransaction.ts:413 writes a positive taxAmount. It skips the sign flip at L384, so on expense reports the tax may show with the wrong sign until the server responds. This PR now reaches that path for distance expenses.
  • Hidden tax when workspace Taxes are off. The distance check at tax.ts:250 reads only the distance unit's taxEnabled. isTaxTrackingEnabled also needs policy.tax.trackingEnabled. If Taxes are off but old rules remain, the code can write a tax to a hidden field. I have not reproduced this.

@JS00001

JS00001 commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

is this ready @Krishna2323 ?

@JS00001 JS00001 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@situchan can you review the latest changes before we merge as well please?

@Krishna2323
Krishna2323 requested a review from situchan October 20, 2026 01:34
@MariaHCD
MariaHCD removed their request for review October 20, 2026 07:41
@Krishna2323

Copy link
Copy Markdown
Contributor Author

@situchan friendly bump

@situchan

Copy link
Copy Markdown
Contributor

I had found bug in latest changes. Will confirm again and post

@situchan situchan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

1 regression and some nits

Comment on lines +73 to 76
const previousCategoryTaxCode = getCategoryTaxCode(transaction?.category ?? '', transaction, policy, previousTransactionCurrency);
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const previousDefaultTaxCode = previousCategoryTaxCode || getDefaultTaxCode(policy, transaction, previousTransactionCurrency);
const shouldKeepCurrentTaxSelection = hasTaxRateWithMatchingValue(policy, transaction) && transaction?.taxCode !== previousDefaultTaxCode;

@situchan situchan Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Bug: Picking the workspace default tax no longer follows a currency change when the category has a rule

  1. Workspace with Taxes and Rules on. Workspace currency default Tax exempt (0%), Foreign currency default TaxF. Rule: Category Car → Tax TaxA.
  2. Create expense → Manual → 100 in the workspace currency → pick the workspace → continue to confirm.
  3. Set Category to Car. Tax shows TaxA.
  4. Tap Tax → pick Tax exempt (0%).
  5. Tap Amount → change to a foreign currency → save.

Expected: Tax switches to TaxF, same as main.
Actual: Tax stays Tax exempt (0%).

bug.mov

}

if (isDistanceRequest(transaction)) {
const customUnitRateID = getRateID(transaction) ?? '';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: getRateID(transaction) ?? '' never uses the '' because getRateID always returns a string.

// Distance tax is charged on the taxable portion of the mileage rate rather than the full amount, so reuse the
// rate-aware calculation instead of taxing the expense amount.
if (isDistanceRequest(transaction)) {
const {taxCode, taxAmount, taxValue} = getDistanceRateTaxUpdates(policy, transaction, getRateID(transaction) ?? '', getCurrencyDecimals, undefined, category);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Same here

if (!getDistanceRateCustomUnit(policy)?.attributes?.taxEnabled || hasSelectableRateTaxCode(policy, customUnitRateID)) {
return undefined;
}
return getSelectableCategoryTaxCode(policy, taxRules, category, getDefaultTaxCode(policy, transaction, undefined, customUnitRateID) ?? '');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

?? '' passed into getSelectableCategoryTaxCode is the only reason useTaxAmount needs || and two eslint-disable lines.
Drop it and both can use ??.

const defaultTaxCode = getDefaultTaxCode(policy, transaction, undefined, customUnitRateID) ?? '';
// A rate's own tax rate wins over a category rule, because vehicle types coded to the same category can each
// reclaim at a different rate.
const taxRules = policy?.rules?.expenseRules?.filter((rule) => rule.tax) ?? [];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

taxRules is filtered separately in both helpers.

const taxRules = policy?.rules?.expenseRules?.filter((rule) => rule.tax);

Comment on lines +274 to +276
const {taxCode, taxAmount, taxValue} = getDistanceRateTaxUpdates(policy, transaction, getRateID(transaction) ?? '', getCurrencyDecimals, undefined, category);
return {categoryTaxCode: taxCode, categoryTaxAmount: taxAmount, categoryTaxValue: taxValue};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

For distance, getCategoryTaxDetails resolves the code with getCategoryTaxCode, then getDistanceRateTaxUpdates resolves it again.

currency?: string,
) {
const categoryTaxCode = getCategoryTaxCode(category, transaction, policy, currency);
if (!categoryTaxCode) {
return {categoryTaxCode: undefined, categoryTaxAmount: undefined, categoryTaxValue: undefined};
}
// Distance tax is charged on the taxable portion of the mileage rate rather than the full amount, so reuse the
// rate-aware calculation instead of taxing the expense amount.
if (isDistanceRequest(transaction)) {
const {taxCode, taxAmount, taxValue} = getDistanceRateTaxUpdates(policy, transaction, getRateID(transaction) ?? '', getCurrencyDecimals, undefined, category);
return {categoryTaxCode: taxCode, categoryTaxAmount: taxAmount, categoryTaxValue: taxValue};
}

@situchan
situchan self-requested a review October 21, 2026 20:06

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.

5 participants