App icon indicating copy to clipboard operation
App copied to clipboard

[$175] Rules - Category tax rule created offline is not grayed out.

Open applause-bot[bot] opened this issue 2 months ago • 34 comments

If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.


Version Number: 9.5.1-1 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://github.com/Expensify/App/pull/100389 Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Pull Request QA execution Device used: Motorola MotoG60 / Android 12 (Hybrid app) - Windows 11 / Chrome App Component: Workspace Settings

Action Performed:

Prerequisite: User is owner of a "Control" workspace with "Rules" enabled.

  1. Open the staging.new.expensify.com website.
  2. Navigate to "Workspaces" > Workspace > "Rules" > "Expense Defaults"
  3. Turn off internet connection.
  4. Click on "Add Rule" > "Apply expense defaults" > "Category"
  5. Select any category and any tax and save the rule.
  6. Note that rule is created, but is not displayed grayed out, despite being created offline.
  7. Turn on internet connection.
  8. Note that rule remains.
  9. Turn off internet connection again.
  10. Select and delete the rule.
  11. Note that rule disappears automatically instead of being grayed out.

Expected Result:

Rule created offline should be displayed grayed out. Same behavior with a strikethrough should be experienced when deleting it offline.

Actual Result:

Category tax rule created offline is not displayed grayed out and it disappears automatically when deleted offline.

Workaround:

Unknown

Platforms:

  • [x] Android: App
  • [ ] Android: mWeb Chrome
  • [ ] iOS: App
  • [ ] iOS: mWeb Safari
  • [ ] iOS: mWeb Chrome
  • [x] Windows: Chrome
  • [ ] MacOS: Chrome Safari

Screenshots/Videos

https://github.com/user-attachments/assets/10b39902-f87f-4321-b3ea-67b03ec761fc

View all open jobs on GitHub

Applause Internal Information Exported by: Julia Ponikarchuk Bug ID: 7274866

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @ahmedGaber93

applause-bot[bot] avatar Oct 02 '26 11:10 applause-bot[bot]

While Applause doesn't embed attachments for this bug, here are the links for quick view: https://platform.applause.com/services/links/v1/external/17ba54cf58a51c2d5888b23c4da658521d8a6bea3a4467fa0a4eb5152f06e255

applause-bot[bot] avatar Oct 02 '26 11:10 applause-bot[bot]

Proposal

What is the root cause of that problem?

This isn't a regression from Add rules engine types and merchant rule AST helpers, and it already happens in production. It was a deliberate choice made in Add category tax defaults to Expense defaults.

Category tax rules live in a plain array (policy.rules.expenseRules), so a single rule has nowhere to store a pendingAction:

The reviewer reported both bugs on PR #99420. The author called them a "known tradeoff": clearing a flag inside the array needs successData that rewrites the whole array, and queued writes can then replay stale arrays over each other. JS00001 agreed to keep it "for now until we migrate to the new rules format".

What changes do you think we should make in order to solve the problem?

Put this issue on hold, or close it as a known limitation, until category tax defaults move into the keyed rules_ collection. Merchant rules already use that collection, and they gray out and strike through correctly through per-key pendingAction (see Rules.ts:259-283). Category rules get the same behavior once they move.

What alternative solutions did you explore? (Optional)

Here is a possible App-only stopgap, which I haven't tested:

  1. Track pending state in a separate keyed object outside the array, for example pendingCategoryTaxRules: {[categoryName]: {pendingAction, taxID}}.
  2. When you add, update, or delete a rule, set that category's pendingAction. Set it back to null in both successData and failureData. Because each write touches only one key, this avoids the stale-array replay problem.
  3. In getCategoryTaxRulesTableData, read the pending state from that object. While offline, keep rendering rows that are pending deletion.

This is more work than the planned migration covers, so it needs an internal decision first.

Investigation details
  • The row component is correct. WorkspaceExpenseDefaultsTableRow.tsx:113 passes item.pendingAction to offlineWithFeedback with shouldHideOnDelete: false. It just never gets a value for category rows.
  • The ExpenseRule type has no pendingAction or errors field (Policy.ts:3256-3271). An earlier commit in PR #99420 added these fields, and commit dc9c34f9a97 removed them before merge. The comment above deletePolicyCategoryTaxes explains why.
  • PR #100389 doesn't touch Category.ts or CategoryTaxRulesUtils.ts. It's linked only because QA found the bug while testing it.

Next Steps for Contributor+ team: To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/102878) to create a draft PR. To refine: @MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.


view run

MelvinBot avatar Oct 02 '26 11:10 MelvinBot

Triggered auto assignment to Contributor-plus team member for initial proposal review - @aimane-chnaif (External)

melvin-bot[bot] avatar Oct 02 '26 11:10 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022105983619827816635

melvin-bot[bot] avatar Oct 02 '26 11:10 melvin-bot[bot]

Hi there! We saw the issue with the offline category tax rule not being grayed out and disappearing on delete. Our React Native experts can fix this behavior quickly and ensure it works across Android and web. Could we discuss the scope and timeline via the Upwork job link you shared?

ProjectsNexus avatar Oct 02 '26 11:10 ProjectsNexus

📣 @ProjectsNexus! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:

  1. Make sure you've read and understood the contributing guidelines.
  2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
  3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Oct 02 '26 11:10 melvin-bot[bot]

Proposal

Problem

When a category tax rule is created while offline, the newly added row in the Expense defaults table is not grayed out. In contrast, other offline-created entities display the expected grayed-out offline feedback styling.

Root Cause

  1. Missing pendingAction in ExpenseRule type & payload: In src/types/onyx/Policy.ts:3256-3271, the ExpenseRule type does not define pendingAction. In src/libs/actions/Policy/Category.ts:1819-1847, setPolicyCategoryTaxes builds optimisticExpenseRules using withCategoryTaxRates, but newly constructed rules in that array carry no pendingAction.

  2. Table item ignores rule-level pending state: In src/libs/CategoryTaxRulesUtils.ts:152-172, getCategoryTaxRulesTableData calculates pendingAction solely from getPendingAction(rule) (which only inspects if the category or tax rate itself is being deleted via getRuleDeletionPendingAction). It never passes rule.pendingAction to item.pendingAction. Consequently, WorkspaceExpenseDefaultsTableRow.tsx:112-117 receives pendingAction: undefined inside offlineWithFeedback, so the row is rendered with full opacity instead of the grayed-out offline style.


Proposed Solution

  1. Add pendingAction & errors to ExpenseRule: In src/types/onyx/Policy.ts, extend ExpenseRule:

    type ExpenseRule = {
        // ... existing fields
        pendingAction?: PendingAction;
        errors?: OnyxErrors;
    };
    
  2. Propagate Pending Action in Category.ts:

    • Update withCategoryTaxRates to accept an optional pendingAction?: PendingAction: When adding or updating a rule in the array, attach pendingAction.
    • In setPolicyCategoryTaxes:
      • In optimisticData: pass withCategoryTaxRates(expenseRules, requested, CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD).
      • In successData: pass withCategoryTaxRates(expenseRules, requested, null) so once the server request resolves, the pending flag is cleanly cleared.
  3. Pass Rule Pending Action in CategoryTaxRulesUtils.ts: In getCategoryTaxRulesTableData:

    const pendingAction = rule.pendingAction ?? getPendingAction(rule);
    

    This passes 'add' to WorkspaceExpenseDefaultsTableRow, which passes it directly to offlineWithFeedback, correctly applying grayed-out styling while offline.

  4. Unit Tests:

    • Add unit test in tests/unit/CategoryTaxRulesUtilsTest.ts: Verify that an ExpenseRule with pendingAction: 'add' produces table item data with pendingAction: 'add'.
    • Add action test in tests/unit/CategoryTest.ts: Verify that setPolicyCategoryTaxes produces optimistic expense rules with pendingAction: 'add' and successData with pendingAction: null.

camesenin avatar Oct 02 '26 11:10 camesenin

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0170d6b02e9440e604

camesenin avatar Oct 02 '26 11:10 camesenin

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 02 '26 11:10 melvin-bot[bot]

Proposal

What is the root cause of that problem?

Agreeing with the root cause already established on this issue: ExpenseRule has no pendingAction field. setPolicyCategoryTaxes writes the new rule into the array with no pending flag, and deletePolicyCategoryTaxes removes it immediately, so there's nothing pending left to render. getCategoryTaxRulesTableData only derives pendingAction from whether the category/tax rate itself is being deleted elsewhere, never from this rule's own add/delete.

This was deliberate, not an oversight: the comments on those two functions explain that expenseRules is a plain array, Onyx replaces arrays wholesale (it can't patch one element), and a bulk save enqueues one API.write per category sharing the same array snapshot — so a per-rule pending flag cleared by successData would let one category's success clobber a sibling's still-in-flight state. That path is real, not theoretical: MerchantRulePageBase.tsx#L424 lets a user apply one tax to several categories at once, each its own write against that same shared array.

What changes do you think we should make in order to solve the problem?

Giving ExpenseRule back its own pendingAction and clearing it with a new successData (as proposed earlier in this thread) reopens exactly that hazard: because the array is shared across every category in a bulk save, the first category to succeed would clear the pending flag for every other category too, including ones still in flight or about to fail.

Move pending state out of the array instead. Track it in a plain object keyed by category name, e.g. policy.rules.expenseRulesPendingActions: {[categoryName]: PendingAction}, written with Onyx.METHOD.MERGE touching only the categories in that specific write. Onyx merges plain objects key-by-key, unlike arrays which it replaces wholesale, so one category's success or failure only ever touches its own key — a sibling category in the same bulk save is untouched until its own write resolves. getCategoryTaxRulesTableData would then read expenseRulesPendingActions[categoryName] first, falling back to the existing deletion-borrowing check. deletePolicyCategoryTaxes would set that category's key to delete and keep the row in the array until the key confirms, instead of dropping it immediately — which also fixes the "disappears instead of greying out" half of this report.

What alternative solutions did you explore? (Optional)

The simpler fix proposed earlier (pendingAction back on the array element, plus successData) works fine for a single-category save, since there's nothing else in that batch to clobber — it only breaks under the real bulk-apply path above. If bulk-apply races are judged acceptable collateral, that simpler version is less work, but it should be a conscious tradeoff rather than an untested assumption.

amar-sheikh avatar Oct 02 '26 12:10 amar-sheikh

Proposal

Please re-state the problem that we are trying to solve in this issue.

When a category tax rule is created offline, the new row in the Expense defaults table is rendered with full opacity instead of displaying the standard grayed-out offline feedback. Conversely, when a category tax rule is deleted offline, the row instantly disappears from the UI rather than remaining visible with strikethrough styling until connectivity is restored.


What is the root cause of that problem?

  1. Array Clobbering Tradeoff in expenseRules: In src/libs/actions/Policy/Category.ts:1860-1870, policy.rules.expenseRules is stored as a plain array. Because Onyx replaces arrays wholesale rather than merging element-by-element, commit dc9c34f9a97 stripped pendingAction from ExpenseRule to prevent bulk writes (which enqueue multiple parallel API.write calls against the same array snapshot) from overwriting and replaying stale snapshots upon successData resolution.
  2. Missing Rule-Level Offline Feedback on Creation: In setPolicyCategoryTaxes, newly constructed rules inside optimisticExpenseRules carry no pending indicator, and CategoryTaxRulesUtils.ts:152 derives pendingAction exclusively from getRuleDeletionPendingAction (which only checks if the underlying category or tax rate entity itself is pending deletion).
  3. Instant Deletion on Offline Delete: In deletePolicyCategoryTaxes, rules are aggressively filtered out of the array immediately in optimisticData (rules: {expenseRules: optimisticExpenseRules}), leaving nothing for the table to render with a pending deletion strikethrough.

What changes do you think we should make in order to solve the problem?

To avoid reintroducing the array-snapshot clobbering bug while providing robust offline feedback, we should decouple the pending state from the array and track it in a keyed map:

1. Define Keyed Pending Actions in Policy Onyx Type (src/types/onyx/Policy.ts)

Under PolicyRules:

type PolicyRules = {
    expenseRules?: ExpenseRule[];
    pendingCategoryTaxRules?: Record<string, PendingAction | null>;
    // ...
};

Because Onyx merges keyed objects key-by-key, individual category operations only touch their respective category key, entirely eliminating race conditions during parallel bulk updates.

2. Update setPolicyCategoryTaxes (src/libs/actions/Policy/Category.ts)

  • In optimisticData: Attach pendingCategoryTaxRules: {[categoryName]: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD} using Onyx.METHOD.MERGE.
  • In successData: Set pendingCategoryTaxRules: {[categoryName]: null}.
  • In failureData: Set pendingCategoryTaxRules: {[categoryName]: null} and revert expenseRules.

3. Update deletePolicyCategoryTaxes (src/libs/actions/Policy/Category.ts)

  • In optimisticData:
    • Do NOT remove the rule from expenseRules immediately. Keep the rule in the array so the UI can continue rendering it.
    • Set pendingCategoryTaxRules: {[categoryName]: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE}.
  • In successData:
    • Remove the rule from expenseRules (the server write has confirmed deletion).
    • Clear pendingCategoryTaxRules: {[categoryName]: null}.
  • In failureData:
    • Retain the rule in expenseRules.
    • Clear pendingCategoryTaxRules: {[categoryName]: null}.

4. Update Table Data Mapping (src/libs/CategoryTaxRulesUtils.ts)

In getCategoryTaxRulesTableData:

const categoryPendingAction = policy.rules?.pendingCategoryTaxRules?.[categoryName];
const pendingAction = categoryPendingAction ?? getPendingAction(rule);
  • In the filter step (line 160): Keep the row visible when pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE && isOffline.
  • Pass pendingAction to ExpenseDefaultTableItem, which WorkspaceExpenseDefaultsTableRow passes directly into offlineWithFeedback.

5. Unit Tests

  • In tests/unit/CategoryTaxRulesUtilsTest.ts:
    • Verify that a category with pendingCategoryTaxRules[category] = 'add' returns table item data with pendingAction: 'add'.
    • Verify that a category with pendingCategoryTaxRules[category] = 'delete' returns table item data with pendingAction: 'delete'.
  • In tests/unit/CategoryTest.ts:
    • Verify that setPolicyCategoryTaxes optimistic data sets pendingCategoryTaxRules[category]: 'add' and successData clears it to null.
    • Verify that deletePolicyCategoryTaxes keeps the rule in expenseRules optimistically with 'delete' pending action, and only strips it upon successData.

What alternative solutions did you explore? (Optional)

  • Adding pendingAction directly to ExpenseRule: Re-opens the known bug where bulk saves enqueueing multiple API.write calls share the same array snapshot, allowing the first category to succeed to prematurely wipe out sibling in-flight states.
  • Dropping rows immediately on delete without offline feedback: Fails the expected UX requirement for offline deletions across NewDot.

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0146a4de0ca9fff602

tuananh4865 avatar Oct 03 '26 00:10 tuananh4865

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 03 '26 00:10 melvin-bot[bot]

@aimane-chnaif, @situchan Whoops! This issue is 2 days overdue. Let's get this updated quick!

melvin-bot[bot] avatar Oct 05 '26 22:10 melvin-bot[bot]

Not overdue

aimane-chnaif avatar Oct 06 '26 07:10 aimane-chnaif

@aimane-chnaif, @situchan Whoops! This issue is 2 days overdue. Let's get this updated quick!

melvin-bot[bot] avatar Oct 09 '26 21:10 melvin-bot[bot]

@aimane-chnaif, @situchan Still overdue 6 days?! Let's take care of this!

melvin-bot[bot] avatar Oct 13 '26 21:10 melvin-bot[bot]

@aimane-chnaif, @situchan Now this issue is 8 days overdue. Are you sure this should be a Daily? Feel free to change it!

melvin-bot[bot] avatar Oct 15 '26 21:10 melvin-bot[bot]

@aimane-chnaif @situchan this issue was created 2 weeks ago. Are we close to approving a proposal? If not, what's blocking us from getting this issue assigned? Don't hesitate to create a thread in #expensify-open-source to align faster in real time. Thanks!

melvin-bot[bot] avatar Oct 16 '26 21:10 melvin-bot[bot]

@aimane-chnaif, @situchan 12 days overdue. Walking. Toward. The. Light...

melvin-bot[bot] avatar Oct 19 '26 21:10 melvin-bot[bot]

Not overdue

aimane-chnaif avatar Oct 22 '26 10:10 aimane-chnaif