Skip to content

[Payment due @suneox] Prevent unnecessary openPolicyExpensifyCardsPage reload after spend rule changes#88365

Merged
cead22 merged 5 commits intomainfrom
claude-fixSpendRuleCardPageReload
Apr 30, 2026
Merged

[Payment due @suneox] Prevent unnecessary openPolicyExpensifyCardsPage reload after spend rule changes#88365
cead22 merged 5 commits intomainfrom
claude-fixSpendRuleCardPageReload

Conversation

@MelvinBot
Copy link
Copy Markdown
Contributor

@MelvinBot MelvinBot commented Apr 20, 2026

Explanation of Change

After SetExpensifyCardRule, the backend returns onyxMethod: set which replaces the entire expensifyCardSettings object, wiping hasOnceLoaded. This causes the useEffect guard in SpendRuleCardPage to fail, triggering an unnecessary openPolicyExpensifyCardsPage API call every time a spend rule is added or edited.

This PR adds a useRef to track whether openPolicyExpensifyCardsPage was already called during the current mount, making the guard immune to Onyx state resets from backend SET responses.

Fixed Issues

$ https://github.com/Expensify/Expensify/issues/624064

Tests

  1. Ensure that e-cards are enabled on the policy
  2. Navigate to Workspaces > Rules
  3. Open the browser console
  4. Create or change an existing card rule
  5. Reopen the rule to edit it, then select the Choose Cards option to open SpendRuleCardPage
  6. Verify that there is no OpenPolicyExpensifyCardsPage API call and no loading status is displayed
  7. Verify that there is no API request to OpenPolicyExpensifyCardsPage after creating/changing a rule (step 3)
  • Verify that no errors appear in the JS console

Offline tests

N/A

QA Steps

N/A

  • 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
  • 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 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

Screen.Recording.2026-04-21.at.12.47.48.PM.mov
Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

…nsifyCardRule

After SetExpensifyCardRule, the backend returns onyxMethod: set which replaces
the entire expensifyCardSettings object, wiping hasOnceLoaded. The useEffect
guard then fails and triggers an unnecessary API call.

Add a useRef to track whether openPolicyExpensifyCardsPage was already called
during this mount, making the guard immune to Onyx state resets.

Co-authored-by: Carlos Martins <luacmartins@users.noreply.github.com>
@MelvinBot MelvinBot requested a review from a team April 20, 2026 23:13
@MelvinBot
Copy link
Copy Markdown
Contributor Author

The typecheck failure is not related to this PR's code changes. It's a transient GitHub Actions infrastructure error — the job failed during git checkout before any typecheck ran:

error: RPC failed; curl 56 GnuTLS recv error (-24): Decryption has failed.
fatal: early EOF
fatal: fetch-pack: invalid index-pack output

All three retry attempts failed with the same TLS error. Please re-run the failed job to get a clean run.

@MelvinBot
Copy link
Copy Markdown
Contributor Author

The typecheck failure is not related to this PR's code changes. The GitHub Actions runner failed during the actions/checkout step with a transient TLS/network error:

error: RPC failed; curl 56 GnuTLS recv error (-24): Decryption has failed.
fatal: early EOF
fatal: fetch-pack: invalid index-pack output

The typecheck itself never ran — the job couldn't even clone the repo. Please re-run the failed workflow to resolve this.

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 20, 2026

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
...s/workspace/rules/SpendRules/SpendRuleCardPage.tsx 0.00% <ø> (ø)
src/libs/actions/Card.ts 0.00% <0.00%> (ø)
... and 244 files with indirect coverage changes

@luacmartins luacmartins requested a review from suneox April 21, 2026 18:49
@luacmartins luacmartins marked this pull request as ready for review April 21, 2026 18:49
@luacmartins luacmartins requested a review from a team as a code owner April 21, 2026 18:49
@melvin-bot melvin-bot Bot requested review from aimane-chnaif and removed request for a team April 21, 2026 18:49
@melvin-bot
Copy link
Copy Markdown

melvin-bot Bot commented Apr 21, 2026

@aimane-chnaif 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]

@melvin-bot melvin-bot Bot requested review from trjExpensify and removed request for a team April 21, 2026 18:49
@luacmartins
Copy link
Copy Markdown
Contributor

@codex review

@luacmartins luacmartins removed the request for review from aimane-chnaif April 21, 2026 18:49
// We use a ref to track this because SetExpensifyCardRule returns onyxMethod: set, which replaces the entire
// expensifyCardSettings object and wipes hasOnceLoaded, causing an unnecessary reload.
if (hasLoadedCardSettingsRef.current || !expensifyCardSettings || expensifyCardSettings?.isLoading || expensifyCardSettings?.hasOnceLoaded) {
return;
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.

❌ PERF-16 (docs)

The ref-based guard does not fully prevent double execution. The ref hasLoadedCardSettingsRef is only set to true when openPolicyExpensifyCardsPage is actually called (line 143). In the most common scenario described in the PR -- where the parent already loaded the data (hasOnceLoaded is true) -- the effect returns early and the ref stays false. When the backend SET response later wipes hasOnceLoaded, the ref is still false, so the guard falls through and the unnecessary API call fires anyway. The fix only prevents a second unnecessary reload, not the first one.

Restructure the effect so the ref is set to true whenever data is already loaded, not just when the API call is made:

useEffect(() => {
    if (hasLoadedCardSettingsRef.current || !expensifyCardSettings || expensifyCardSettings?.isLoading) {
        return;
    }
    hasLoadedCardSettingsRef.current = true;
    if (expensifyCardSettings?.hasOnceLoaded) {
        return;
    }
    openPolicyExpensifyCardsPage(policyID, defaultFundID);
}, [defaultFundID, expensifyCardSettings, policyID]);

This way, once the effect observes that data has been loaded (either by the parent or by this effect), the ref prevents any future invocations from triggering the API call even if hasOnceLoaded gets wiped by a backend SET response.


Reviewed at: 0ba2f9e | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

@aimane-chnaif
Copy link
Copy Markdown
Contributor

Is this regression/follow-up of previous PR?

@luacmartins
Copy link
Copy Markdown
Contributor

@aimane-chnaif yes

Copy link
Copy Markdown

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

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: 0ba2f9ef64

ℹ️ 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 on lines 145 to 146
hasLoadedCardSettingsRef.current = true;
openPolicyExpensifyCardsPage(policyID, defaultFundID);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reset one-shot load guard after failed cards fetch

Setting hasLoadedCardSettingsRef.current = true before dispatching openPolicyExpensifyCardsPage makes loading a one-shot attempt for the entire mount. If OPEN_POLICY_EXPENSIFY_CARDS_PAGE fails (its failureData in src/libs/actions/Policy/Policy.ts clears isLoading but does not mark hasOnceLoaded), this guard still blocks every later retry even though settings never loaded. In transient online failure scenarios, the page can remain stuck with no cards until the user leaves and re-enters.

Useful? React with 👍 / 👎.

trjExpensify
trjExpensify previously approved these changes Apr 22, 2026
Copy link
Copy Markdown
Contributor

@trjExpensify trjExpensify left a comment

Choose a reason for hiding this comment

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

Ecard spend rules follow up 👍

@suneox
Copy link
Copy Markdown
Contributor

suneox commented Apr 22, 2026

I'll take a look at this one soon

@luacmartins luacmartins requested review from JS00001 and cead22 April 22, 2026 15:03
Copy link
Copy Markdown
Contributor

@JS00001 JS00001 left a comment

Choose a reason for hiding this comment

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

Is a ref the correct solution here? Can we store a var in the finallyData that we can access via the onyx data?

If we use a ref, wouldnt the refs value get cleared when navigating away & navigating backl?

if (!expensifyCardSettings || expensifyCardSettings?.isLoading || expensifyCardSettings?.hasOnceLoaded) {
// We use a ref to track this because SetExpensifyCardRule returns onyxMethod: set, which replaces the entire
// expensifyCardSettings object and wipes hasOnceLoaded, causing an unnecessary reload.
if (hasLoadedCardSettingsRef.current || !expensifyCardSettings || expensifyCardSettings?.isLoading || expensifyCardSettings?.hasOnceLoaded) {
Copy link
Copy Markdown
Contributor

@suneox suneox Apr 22, 2026

Choose a reason for hiding this comment

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

Current fix can not resolve an issue

CleanShot.2026-04-23.at.01.12.41.1.mp4

If we decide to fix this on the client I think we can simplify the condition to only open openPolicyExpensifyCardsPage when expensifyCardSettings is undefined.

        if (!expensifyCardSettings) {
            openPolicyExpensifyCardsPage(policyID, defaultFundID);
        }

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.

@luacmartins I just referenced the initial change, and it looks like there’s a mismatch in the return condition when expensifyCardSettings is undefined and the suggested update only prevent infinity request 😄

@MelvinBot
Copy link
Copy Markdown
Contributor Author

The only failing check is checklist (PR Author/Reviewer Checklist), which is not a code issue — it's an administrative check that requires manual completion. All code checks (ESLint, TypeScript, tests, builds, prettier, spellcheck, etc.) are passing.

@MelvinBot
Copy link
Copy Markdown
Contributor Author

Implemented the proposed fix. Added hasOnceLoaded: true to both optimisticData and successData in setExpensifyCardRule, matching the pattern deleteExpensifyCardRule already uses. This prevents SpendRulesSection from triggering an unnecessary openPolicyExpensifyCardsPage call when the server SET response wipes the Onyx key.

@suneox
Copy link
Copy Markdown
Contributor

suneox commented Apr 28, 2026

@MelvinBot missed updating hasOnceLoaded: true in the deleteExpensifyCardRule function. Let apply the same update as in setExpensifyCardRule func

CleanShot.2026-04-28.at.18.00.06.1.mp4

@MelvinBot
Copy link
Copy Markdown
Contributor Author

Good catch — deleteExpensifyCardRule is missing hasOnceLoaded: true in its successData and failureData, while setExpensifyCardRule correctly includes it in all three Onyx updates. The same backend SET response would wipe hasOnceLoaded after deleting a rule, triggering an unnecessary OpenPolicyExpensifyCardsPage reload.

The fix is to add hasOnceLoaded: true to both the successData and failureData blocks in deleteExpensifyCardRule, matching the pattern in setExpensifyCardRule.

I can only make code changes when directed by the PR author, an assignee, or an existing co-author. To have me implement this, the PR assignee or author should reply with a request tagging me.

@suneox
Copy link
Copy Markdown
Contributor

suneox commented Apr 28, 2026

@MelvinBot implement this one

@MelvinBot
Copy link
Copy Markdown
Contributor Author

The fix for deleteExpensifyCardRule (adding hasOnceLoaded: true to successData and failureData) is ready to implement — see my earlier analysis.

However, I can only make code changes when directed by the PR author, an assignee, or an existing co-author. suneox is not currently in any of those roles on this PR. To have me implement this, luacmartins (the assignee) should reply with a request tagging me.

@suneox
Copy link
Copy Markdown
Contributor

suneox commented Apr 28, 2026

The fix for deleteExpensifyCardRule (adding hasOnceLoaded: true to successData and failureData) is ready to implement — see my earlier analysis.

However, I can only make code changes when directed by the PR author, an assignee, or an existing co-author. suneox is not currently in any of those roles on this PR. To have me implement this, luacmartins (the assignee) should reply with a request tagging me.

cc: @luacmartins

@luacmartins
Copy link
Copy Markdown
Contributor

@MelvinBot implement #88365 (comment)

The deleteExpensifyCardRule function was missing hasOnceLoaded: true
in its successData and failureData blocks. When the backend returns
an onyxMethod: set response after deleting a rule, it wipes
hasOnceLoaded, triggering an unnecessary OpenPolicyExpensifyCardsPage
reload — the same bug that setExpensifyCardRule already guards against.

Co-authored-by: luacmartins <luacmartins@users.noreply.github.com>
Co-authored-by: Carlos Martins <luacmartins@users.noreply.github.com>
@MelvinBot
Copy link
Copy Markdown
Contributor Author

Added hasOnceLoaded: true to both successData and failureData in deleteExpensifyCardRule, matching the pattern already used in setExpensifyCardRule. This prevents the backend SET response from wiping hasOnceLoaded after a rule deletion, which would otherwise trigger an unnecessary OpenPolicyExpensifyCardsPage reload.

Copy link
Copy Markdown
Contributor

@suneox suneox left a comment

Choose a reason for hiding this comment

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

The remaining issue with reloading Expensify Cards after deleting a rule has been fixed.

CleanShot.2026-04-28.at.18.11.13.1.mp4

@melvin-bot melvin-bot Bot changed the title Prevent unnecessary openPolicyExpensifyCardsPage reload after spend rule changes [Payment due @suneox] Prevent unnecessary openPolicyExpensifyCardsPage reload after spend rule changes Apr 29, 2026
@melvin-bot
Copy link
Copy Markdown

melvin-bot Bot commented Apr 29, 2026

🎯 @suneox, thanks for reviewing and testing this PR! 🎉

A payment issue will be created for your review once this PR is deployed to production.
E/E issue linked to the PR - https://www.github.com/Expensify/Expensify/issues/624064.

If payment is not needed (e.g., regression PR review fix etc), react with 👎 to this comment to prevent the payment issue from being created.

Comment thread src/pages/workspace/rules/SpendRules/SpendRuleCardPage.tsx
@cead22 cead22 merged commit fe97528 into main Apr 30, 2026
60 checks passed
@cead22 cead22 deleted the claude-fixSpendRuleCardPageReload branch April 30, 2026 15:01
@OSBotify
Copy link
Copy Markdown
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@github-actions
Copy link
Copy Markdown
Contributor

🚧 @cead22 has triggered a test Expensify/App build. You can view the workflow run here.

@OSBotify
Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/cead22 in version: 9.3.65-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Bundle Size Analysis (Sentry):

@MelvinBot
Copy link
Copy Markdown
Contributor Author

I reviewed the changes in this PR. It's a purely internal bug fix that prevents an unnecessary openPolicyExpensifyCardsPage API call after spend rule changes by preserving the hasOnceLoaded flag in Onyx state.

No help site documentation changes are required — there are no user-facing changes (no new features, UI changes, renamed settings, or altered workflows). The existing help site articles that reference card rules remain accurate.

@lanitochka17
Copy link
Copy Markdown

lanitochka17 commented May 1, 2026

Hello @JS00001 @luacmartins
How can I find Choose Cards option to open SpendRuleCardPage in step 2?
Do we have some precondition?
image

@JS00001
Copy link
Copy Markdown
Contributor

JS00001 commented May 1, 2026

@lanitochka17 sorry, this should be for card rules, not merchant rules

@izarutskaya
Copy link
Copy Markdown

@JS00001 We can see only Expenses and Merchant rules. Did we miss anything?

Recording.3736.mp4

@JS00001
Copy link
Copy Markdown
Contributor

JS00001 commented May 1, 2026

You have to have expensify cards enabled on the policy, let me update the test steps

@OSBotify
Copy link
Copy Markdown
Contributor

OSBotify commented May 4, 2026

🚀 Deployed to production by https://github.com/mountiny in version: 9.3.65-6 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

@melvin-bot
Copy link
Copy Markdown

melvin-bot Bot commented May 4, 2026

🤖 Payment issue created: #89505

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.

10 participants