From 94c7256b5067ca75761be59f37c04e125092cb60 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Thu, 3 Sep 2026 13:40:09 +0430 Subject: [PATCH 01/24] Keep showing a broken card's status past the 90-day grace period --- src/libs/actions/PaymentMethods.ts | 5 ++ .../settings/Wallet/PaymentMethodList.tsx | 5 +- tests/unit/useAccountIndicatorChecksTest.ts | 78 +++++++++++++++++++ 3 files changed, 86 insertions(+), 2 deletions(-) diff --git a/src/libs/actions/PaymentMethods.ts b/src/libs/actions/PaymentMethods.ts index 069c4ee40879..a6170e94a784 100644 --- a/src/libs/actions/PaymentMethods.ts +++ b/src/libs/actions/PaymentMethods.ts @@ -443,6 +443,11 @@ function hasPaymentMethodError( // sets the connection error even for scrape statuses that check treats as ignored (e.g. 434). return !CardUtils.isLastScrapePastDismissThreshold(card); } + // A company card follows the same grace period: past it we stop leading the user to the error, though the error + // itself stays on the card row and on the feed so it can still be fixed. + if (CardUtils.isLastScrapePastDismissThreshold(card)) { + return false; + } const workspaceAccountID = Number(card?.fundID); const policy = policyList.find((p) => p?.policyAccountID === workspaceAccountID); return !!policy && isPolicyUser(policy, currentUserLogin); diff --git a/src/pages/settings/Wallet/PaymentMethodList.tsx b/src/pages/settings/Wallet/PaymentMethodList.tsx index 6535eaabef22..2504cf657666 100644 --- a/src/pages/settings/Wallet/PaymentMethodList.tsx +++ b/src/pages/settings/Wallet/PaymentMethodList.tsx @@ -23,7 +23,6 @@ import { getCompanyCardFeedWithDomainIDForCard, getPlaidInstitutionIconUrl, isActionableVirtualExpensifyCard, - isBrokenConnectionPastDismissThreshold, isCardConnectionBroken, doesCardConnectionNeedReauthentication, isCardFrozen, @@ -322,7 +321,9 @@ function PaymentMethodList({ } const companyCardFeedForCard = getCompanyCardFeedWithDomainIDForCard(card); - const isCardBroken = isCardConnectionBroken(card) && !isBrokenConnectionPastDismissThreshold(card); + // The grace period only stops us from prompting the user (the RBR and the time-sensitive task); the status + // itself stays truthful, so a long-broken card still reads as Inactive with a message it can be fixed from. + const isCardBroken = isCardConnectionBroken(card); const isCardInactiveState = isCardInactive(card); const cardConnectionStatusDisplay = getCardConnectionStatusDisplay({ shouldShowConnectionStatus, diff --git a/tests/unit/useAccountIndicatorChecksTest.ts b/tests/unit/useAccountIndicatorChecksTest.ts index 602f01920c8c..0ea5381ca4ca 100644 --- a/tests/unit/useAccountIndicatorChecksTest.ts +++ b/tests/unit/useAccountIndicatorChecksTest.ts @@ -344,6 +344,84 @@ describe('useAccountIndicatorChecks', () => { expect(result.current.accountStatus).toBeUndefined(); }); + + // A company card follows the same grace period as a personal one: past it we stop leading the user to the error. + it('does not surface a company card broken connection on the Account button past the grace period', async () => { + await act(async () => { + await Onyx.multiSet( + createMock({ + [ONYXKEYS.USER_WALLET]: {}, + [ONYXKEYS.BANK_ACCOUNT_LIST]: {}, + [ONYXKEYS.REIMBURSEMENT_ACCOUNT]: {}, + [ONYXKEYS.LOGINS]: {}, + [ONYXKEYS.WALLET_TERMS]: {}, + [ONYXKEYS.PRIVATE_PERSONAL_DETAILS]: {}, + [ONYXKEYS.NVP_PRIVATE_BILLING_DISPUTE_PENDING]: 0, + [ONYXKEYS.CARD_LIST]: { + card1: { + cardID: 1, + bank: cardFeed.feedName, + fundID: String(cardFeed.policyAccountID), + lastScrapeResult: 403, + lastScrape: '2020-01-01 00:00:00', // Broken well beyond the grace period + errors: {connectionError: 'Your card connection is broken.'}, + }, + }, + [`${ONYXKEYS.COLLECTION.POLICY}1` as const]: { + id: '1', + policyAccountID: cardFeed.policyAccountID, + role: CONST.POLICY.ROLE.USER, + }, + [ONYXKEYS.SESSION]: {email: userID}, + }), + ); + await waitForBatchedUpdatesWithAct(); + }); + + const {result} = renderHook(() => useAccountIndicatorChecks()); + await waitForBatchedUpdatesWithAct(); + + expect(result.current.accountStatus).not.toBe(CONST.INDICATOR_STATUS.HAS_PAYMENT_METHOD_ERROR); + }); + + it('still surfaces a company card broken connection on the Account button within the grace period', async () => { + const recentScrape = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString().slice(0, 19).replace('T', ' '); + await act(async () => { + await Onyx.multiSet( + createMock({ + [ONYXKEYS.USER_WALLET]: {}, + [ONYXKEYS.BANK_ACCOUNT_LIST]: {}, + [ONYXKEYS.REIMBURSEMENT_ACCOUNT]: {}, + [ONYXKEYS.LOGINS]: {}, + [ONYXKEYS.WALLET_TERMS]: {}, + [ONYXKEYS.PRIVATE_PERSONAL_DETAILS]: {}, + [ONYXKEYS.NVP_PRIVATE_BILLING_DISPUTE_PENDING]: 0, + [ONYXKEYS.CARD_LIST]: { + card1: { + cardID: 1, + bank: cardFeed.feedName, + fundID: String(cardFeed.policyAccountID), + lastScrapeResult: 403, + lastScrape: recentScrape, // Broken only recently, still inside the grace period + errors: {connectionError: 'Your card connection is broken.'}, + }, + }, + [`${ONYXKEYS.COLLECTION.POLICY}1` as const]: { + id: '1', + policyAccountID: cardFeed.policyAccountID, + role: CONST.POLICY.ROLE.USER, + }, + [ONYXKEYS.SESSION]: {email: userID}, + }), + ); + await waitForBatchedUpdatesWithAct(); + }); + + const {result} = renderHook(() => useAccountIndicatorChecks()); + await waitForBatchedUpdatesWithAct(); + + expect(result.current.accountStatus).toBe(CONST.INDICATOR_STATUS.HAS_PAYMENT_METHOD_ERROR); + }); }); describe('info statuses', () => { From ae22701d2d26c16f7cea17b95e65bf3a9225f874 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Sat, 5 Sep 2026 09:08:46 +0430 Subject: [PATCH 02/24] Fix comment style --- src/pages/settings/Wallet/PaymentMethodList.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/settings/Wallet/PaymentMethodList.tsx b/src/pages/settings/Wallet/PaymentMethodList.tsx index 6a78d09ceb20..1a7ba67c1161 100644 --- a/src/pages/settings/Wallet/PaymentMethodList.tsx +++ b/src/pages/settings/Wallet/PaymentMethodList.tsx @@ -317,7 +317,7 @@ function PaymentMethodList({ } const companyCardFeedForCard = getCompanyCardFeedWithDomainIDForCard(card); - // The grace period only stops us from prompting the user (the RBR and the time-sensitive task); the status + // The grace period only stops us from prompting the user (the RBR and the time-sensitive task). The status // itself stays truthful, so a long-broken card still reads as Inactive with a message it can be fixed from. const isCardBroken = isCardConnectionBroken(card); const isCardInactiveState = isCardInactive(card); From 3f003fc00bb9582471556a89c6476e2c1ab424ae Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Wed, 9 Sep 2026 11:47:27 +0430 Subject: [PATCH 03/24] Fix broken status for ignored scrape statuses --- src/libs/CardUtils.ts | 21 +++++++++++++ .../settings/Wallet/PaymentMethodList.tsx | 7 +++-- .../Wallet/PersonalCardDetailsPage.tsx | 5 +-- .../useFixPersonalCardConnection.ts | 6 ++-- tests/unit/CardUtilsTest.ts | 31 +++++++++++++++++++ 5 files changed, 63 insertions(+), 7 deletions(-) diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index b40e4ccc5a58..b79e3b847a8c 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -1423,6 +1423,26 @@ function isCardConnectionBroken(card: Card): boolean { return !!card.lastScrapeResult && !CONST.COMPANY_CARDS.BROKEN_CONNECTION_IGNORED_STATUSES.includes(card.lastScrapeResult); } +/** + * Whether a card's connection has a problem worth reflecting in its status. This is broader than + * `isCardConnectionBroken`, which ignores some scrape statuses so we do not prompt about them (e.g. 434). The server + * still records a connection error for those, so keying the status off the narrower check leaves the card reading + * Active with that error shown right underneath it. Requiring an error as well as a failed scrape keeps this to cards + * that are visibly reporting a problem. + * + * @param card the card to check + * @returns true if the card's connection has a problem to show, false otherwise + */ +function hasCardConnectionIssue(card: Card): boolean { + if (card.pendingFields?.lastScrape) { + return false; + } + if (isCardConnectionBroken(card)) { + return true; + } + return !!card.lastScrapeResult && card.lastScrapeResult !== CONST.JSON_CODE.SUCCESS && !isEmptyObject(card.errors); +} + /** * Check if the card connection is broken specifically because the user needs to re-authenticate with their bank * @@ -2223,6 +2243,7 @@ export { getCSVFeedType, getFeedType, isCardConnectionBroken, + hasCardConnectionIssue, doesCardConnectionNeedReauthentication, getCardConnectionStatusDisplay, isBrokenConnectionPastDismissThreshold, diff --git a/src/pages/settings/Wallet/PaymentMethodList.tsx b/src/pages/settings/Wallet/PaymentMethodList.tsx index 09f72cef8a06..3a4e5fa85dd8 100644 --- a/src/pages/settings/Wallet/PaymentMethodList.tsx +++ b/src/pages/settings/Wallet/PaymentMethodList.tsx @@ -22,6 +22,7 @@ import { getCardFeedWithDomainID, getCompanyCardFeedWithDomainIDForCard, getPlaidInstitutionIconUrl, + hasCardConnectionIssue, isActionableVirtualExpensifyCard, isCardConnectionBroken, doesCardConnectionNeedReauthentication, @@ -305,9 +306,9 @@ function PaymentMethodList({ } const companyCardFeedForCard = getCompanyCardFeedWithDomainIDForCard(card); - // The grace period only stops us from prompting the user (the RBR and the time-sensitive task). The status - // itself stays truthful, so a long-broken card still reads as Inactive with a message it can be fixed from. - const isCardBroken = isCardConnectionBroken(card); + // The grace period and the ignored scrape statuses only stop us from prompting the user. The status itself + // stays truthful, so a card reporting a connection error still reads as Inactive with a way to fix it. + const isCardBroken = hasCardConnectionIssue(card); const isCardInactiveState = isCardInactive(card); const cardConnectionStatusDisplay = getCardConnectionStatusDisplay({ shouldShowConnectionStatus, diff --git a/src/pages/settings/Wallet/PersonalCardDetailsPage.tsx b/src/pages/settings/Wallet/PersonalCardDetailsPage.tsx index 64b88e83ab98..4eec4efb2fe2 100644 --- a/src/pages/settings/Wallet/PersonalCardDetailsPage.tsx +++ b/src/pages/settings/Wallet/PersonalCardDetailsPage.tsx @@ -21,7 +21,7 @@ import useThemeStyles from '@hooks/useThemeStyles'; import {getActiveServer} from '@libs/ApiUtils'; import navigateToCardTransactions from '@libs/CardNavigationUtils'; -import {getCardFeedIcon, getPlaidInstitutionIconUrl, isCardConnectionBroken, isPersonalCard} from '@libs/CardUtils'; +import {getCardFeedIcon, getPlaidInstitutionIconUrl, hasCardConnectionIssue, isPersonalCard} from '@libs/CardUtils'; import {getLatestErrorField} from '@libs/ErrorUtils'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; import type {SettingsNavigatorParamList} from '@libs/Navigation/types'; @@ -74,7 +74,8 @@ function PersonalCardDetailsPage({route}: PersonalCardDetailsPageProps) { const card = cardList?.[cardID]; const cardBank = card?.bank ?? ''; - const isCardBroken = card ? isCardConnectionBroken(card) : false; + // Matches the wallet row, so a card the wallet says to fix also offers the fix here. + const isCardBroken = card ? hasCardConnectionIssue(card) : false; const isUserPersonalCard = !!(card && isPersonalCard(card)); // Personal cards always belong to the current user, so fall back to the current user's personal details diff --git a/src/pages/settings/Wallet/PersonalCards/FixPersonalCardConnectionPage/useFixPersonalCardConnection.ts b/src/pages/settings/Wallet/PersonalCards/FixPersonalCardConnectionPage/useFixPersonalCardConnection.ts index d86828a7261c..96345f5d7a9f 100644 --- a/src/pages/settings/Wallet/PersonalCards/FixPersonalCardConnectionPage/useFixPersonalCardConnection.ts +++ b/src/pages/settings/Wallet/PersonalCards/FixPersonalCardConnectionPage/useFixPersonalCardConnection.ts @@ -2,7 +2,7 @@ import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import {updatePersonalCardConnection} from '@libs/actions/PersonalCards'; -import {getBankName, getPlaidInstitutionId, isCardConnectionBroken} from '@libs/CardUtils'; +import {getBankName, getPlaidInstitutionId, hasCardConnectionIssue} from '@libs/CardUtils'; import Navigation from '@libs/Navigation/Navigation'; import {getPersonalCardBankConnection} from '@userActions/getCompanyCardBankConnection'; @@ -24,7 +24,9 @@ function useFixPersonalCardConnection(cardID: string) { const isPlaid = !!(card?.bank && getPlaidInstitutionId(card.bank as CompanyCardFeed)); const url = isPlaid ? null : getPersonalCardBankConnection(bankDisplayName); const country = card?.nameValuePairs?.country ?? CONST.COUNTRY.US; - const isCardBroken = card ? isCardConnectionBroken(card) : false; + // Matches the wallet row and the card details page, so a card they offer a fix for takes the reconnect flow here + // rather than the auto-sync path meant for cards with nothing to fix. + const isCardBroken = card ? hasCardConnectionIssue(card) : false; useEffect(() => { if (isLoadingOnyxValue(cardListMetadata)) { diff --git a/tests/unit/CardUtilsTest.ts b/tests/unit/CardUtilsTest.ts index b836ad73d82a..32909f11f658 100644 --- a/tests/unit/CardUtilsTest.ts +++ b/tests/unit/CardUtilsTest.ts @@ -58,10 +58,12 @@ import { getTranslationKeyForCardStatus, getYearFromExpirationDateString, hasAssignedCardMatching, + hasCardConnectionIssue, hasIssuedExpensifyCard, hasOnlyOneCardToAssign, isBrokenConnectionPastDismissThreshold, isCardAlreadyAssigned, + isCardConnectionBroken, isCardFrozen, isLastScrapePastDismissThreshold, isCSVFeedOrExpensifyCard, @@ -4436,6 +4438,35 @@ describe('CardUtils', () => { }); }); + describe('hasCardConnectionIssue', () => { + it('returns true for a scrape status that is not ignored', () => { + const card: Card = {...createRandomCard(1), lastScrapeResult: 403, errors: undefined}; + expect(hasCardConnectionIssue(card)).toBe(true); + }); + + // 434 is an ignored status so isCardConnectionBroken is false for it, but the server still records the error. + it('returns true for an ignored scrape status that carries a server error', () => { + const card: Card = {...createRandomCard(1), lastScrapeResult: 434, errors: {connectionError: 'The account number appears to have changed at the bank.'}}; + expect(isCardConnectionBroken(card)).toBe(false); + expect(hasCardConnectionIssue(card)).toBe(true); + }); + + it('returns false for an ignored scrape status with no error to show', () => { + const card: Card = {...createRandomCard(1), lastScrapeResult: 434, errors: undefined}; + expect(hasCardConnectionIssue(card)).toBe(false); + }); + + it('returns false for a successful scrape', () => { + const card: Card = {...createRandomCard(1), lastScrapeResult: 200, errors: undefined}; + expect(hasCardConnectionIssue(card)).toBe(false); + }); + + it('returns false while a scrape is pending', () => { + const card: Card = {...createRandomCard(1), lastScrapeResult: 403, pendingFields: {lastScrape: 'update'}, errors: {connectionError: 'Broken'}}; + expect(hasCardConnectionIssue(card)).toBe(false); + }); + }); + describe('isLastScrapePastDismissThreshold', () => { afterEach(() => { jest.restoreAllMocks(); From 2883873e15c1e120eafcf4af68934212a05b163a Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Fri, 11 Sep 2026 10:40:51 +0430 Subject: [PATCH 04/24] Key card status on scrape result --- src/CONST/index.ts | 7 +++++++ src/libs/CardUtils.ts | 10 +++++----- tests/unit/CardUtilsTest.ts | 13 ++++++++++--- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 790a694ca44b..aa961bb687fa 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -120,6 +120,10 @@ const brokenConnectionScrapeStatuses: number[] = [200, 434, 531, 530, 500, 666]; const reauthScrapeStatuses: number[] = [438]; +// Statuses we do not prompt about, but which still mean the user has to do something. 434 is the bank changing the +// account number, so the card's status has to show it even though the broken-connection check ignores it. +const actionableIgnoredScrapeStatuses: number[] = [434]; + // Hide not issued or not activated cards (states 2, 4) from card filter options in search, as no transactions can be made on cards in these states const cardHiddenFromSearchStates: number[] = [2, 4]; @@ -5190,6 +5194,9 @@ const CONST = { COMPANY_CARDS: { BROKEN_CONNECTION_IGNORED_STATUSES: brokenConnectionScrapeStatuses, + // Ignored scrape result codes that still need the user to act, so they belong in the card's status + ACTIONABLE_IGNORED_SCRAPE_STATUSES: actionableIgnoredScrapeStatuses, + // Scrape result codes where the connection is broken because the user needs to re-authenticate with their bank REAUTH_SCRAPE_STATUSES: reauthScrapeStatuses, diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index b79e3b847a8c..2a7179516c1c 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -1425,10 +1425,10 @@ function isCardConnectionBroken(card: Card): boolean { /** * Whether a card's connection has a problem worth reflecting in its status. This is broader than - * `isCardConnectionBroken`, which ignores some scrape statuses so we do not prompt about them (e.g. 434). The server - * still records a connection error for those, so keying the status off the narrower check leaves the card reading - * Active with that error shown right underneath it. Requiring an error as well as a failed scrape keeps this to cards - * that are visibly reporting a problem. + * `isCardConnectionBroken`, which ignores some scrape statuses so we do not prompt about them. One of those, 434, + * still needs the user to act because the bank changed the account number, so a card reporting it would otherwise + * read as Active. This keys off the scrape result rather than the card's errors, which the user can dismiss and + * which would then leave a still-broken card reading as Active. * * @param card the card to check * @returns true if the card's connection has a problem to show, false otherwise @@ -1440,7 +1440,7 @@ function hasCardConnectionIssue(card: Card): boolean { if (isCardConnectionBroken(card)) { return true; } - return !!card.lastScrapeResult && card.lastScrapeResult !== CONST.JSON_CODE.SUCCESS && !isEmptyObject(card.errors); + return !!card.lastScrapeResult && CONST.COMPANY_CARDS.ACTIONABLE_IGNORED_SCRAPE_STATUSES.includes(card.lastScrapeResult); } /** diff --git a/tests/unit/CardUtilsTest.ts b/tests/unit/CardUtilsTest.ts index 32909f11f658..4b35980f7ea6 100644 --- a/tests/unit/CardUtilsTest.ts +++ b/tests/unit/CardUtilsTest.ts @@ -4444,15 +4444,22 @@ describe('CardUtils', () => { expect(hasCardConnectionIssue(card)).toBe(true); }); - // 434 is an ignored status so isCardConnectionBroken is false for it, but the server still records the error. - it('returns true for an ignored scrape status that carries a server error', () => { + // 434 is an ignored status, so isCardConnectionBroken is false for it even though the bank changed the account + // number and the user has to act. + it('returns true for an actionable ignored scrape status', () => { const card: Card = {...createRandomCard(1), lastScrapeResult: 434, errors: {connectionError: 'The account number appears to have changed at the bank.'}}; expect(isCardConnectionBroken(card)).toBe(false); expect(hasCardConnectionIssue(card)).toBe(true); }); - it('returns false for an ignored scrape status with no error to show', () => { + // Dismissing the row error clears card.errors, so keying off it would flip a still-broken card to Active. + it('stays true for an actionable ignored scrape status after its errors are dismissed', () => { const card: Card = {...createRandomCard(1), lastScrapeResult: 434, errors: undefined}; + expect(hasCardConnectionIssue(card)).toBe(true); + }); + + it('returns false for an ignored scrape status that needs no action', () => { + const card: Card = {...createRandomCard(1), lastScrapeResult: 530, errors: {someError: 'Transient server error'}}; expect(hasCardConnectionIssue(card)).toBe(false); }); From a7d3121c988ebe9a200f986a760e441a040f0f81 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Fri, 11 Sep 2026 17:45:52 +0430 Subject: [PATCH 05/24] Keep fresh card errors visible --- src/libs/CardUtils.ts | 56 +++++++++++++++---- .../settings/Wallet/PaymentMethodList.tsx | 5 +- tests/unit/CardUtilsTest.ts | 31 ++++++++++ 3 files changed, 79 insertions(+), 13 deletions(-) diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index 2a7179516c1c..58a20f24d07f 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -1496,6 +1496,47 @@ function getCardConnectionStatusDisplay({ }; } +/** + * Parses a card's last sync. `card.lastScrape` is usually the Expensify DB datetime format ("2024-11-27 11:00:53"), + * but a personal card's value can arrive as ISO 8601 ("2024-11-27T11:00:53Z"). The DB format is tried explicitly + * first because its `new Date()` handling is not portable across JS engines, then `new Date()` handles ISO 8601. + * + * @param card the card to read + * @returns the parsed date, or undefined when there is no usable value + */ +function parseCardLastScrape(card: Card): Date | undefined { + if (!card.lastScrape) { + return undefined; + } + let lastScrapeDate = parse(card.lastScrape, 'yyyy-MM-dd HH:mm:ss', new Date()); + if (Number.isNaN(lastScrapeDate.getTime())) { + lastScrapeDate = new Date(card.lastScrape); + } + return Number.isNaN(lastScrapeDate.getTime()) ? undefined : lastScrapeDate; +} + +/** + * Whether the card carries an error recorded after its last sync. The server writes a connection error at scrape + * time, so anything newer came from something the user just did (a failed unassignment, for example) and has to stay + * visible even when a connection message is already on the row. + * + * @param card the card to check + * @returns true if an error is newer than the last sync, false otherwise + */ +function hasErrorNewerThanLastScrape(card: Card): boolean { + const errorKeys = Object.keys(card.errors ?? {}); + if (errorKeys.length === 0) { + return false; + } + const lastScrapeDate = parseCardLastScrape(card); + if (!lastScrapeDate) { + return true; + } + // Error keys are microseconds, `lastScrape` is milliseconds. + const lastScrapeMicroseconds = lastScrapeDate.getTime() * 1000; + return errorKeys.some((errorKey) => Number(errorKey) > lastScrapeMicroseconds); +} + /** * Check whether a card's last successful sync is at least the dismiss threshold (90 days) old. * @@ -1509,18 +1550,8 @@ function getCardConnectionStatusDisplay({ * @returns true if the last successful sync is at least the grace period old */ function isLastScrapePastDismissThreshold(card: Card): boolean { - if (!card.lastScrape) { - return false; - } - // `card.lastScrape` is usually the Expensify DB datetime format ("2024-11-27 11:00:53"), but a personal card's value can - // arrive as ISO 8601 ("2024-11-27T11:00:53Z"). Try the DB format explicitly first (its `new Date()` handling isn't - // portable across JS engines), then fall back to `new Date()`, which parses ISO 8601 reliably. Without the fallback an - // ISO value fails the DB parse, the difference is NaN, and the connection is never dismissed (the RBR stays forever). - let lastScrapeDate = parse(card.lastScrape, 'yyyy-MM-dd HH:mm:ss', new Date()); - if (Number.isNaN(lastScrapeDate.getTime())) { - lastScrapeDate = new Date(card.lastScrape); - } - if (Number.isNaN(lastScrapeDate.getTime())) { + const lastScrapeDate = parseCardLastScrape(card); + if (!lastScrapeDate) { return false; } return DateUtils.getDifferenceInDaysFromNow(lastScrapeDate) >= CONST.COMPANY_CARDS.BROKEN_CONNECTION_DISMISS_AFTER_DAYS; @@ -2242,6 +2273,7 @@ export { isCardHiddenFromSearch, getCSVFeedType, getFeedType, + hasErrorNewerThanLastScrape, isCardConnectionBroken, hasCardConnectionIssue, doesCardConnectionNeedReauthentication, diff --git a/src/pages/settings/Wallet/PaymentMethodList.tsx b/src/pages/settings/Wallet/PaymentMethodList.tsx index 3a4e5fa85dd8..3c7fc17d998d 100644 --- a/src/pages/settings/Wallet/PaymentMethodList.tsx +++ b/src/pages/settings/Wallet/PaymentMethodList.tsx @@ -23,6 +23,7 @@ import { getCompanyCardFeedWithDomainIDForCard, getPlaidInstitutionIconUrl, hasCardConnectionIssue, + hasErrorNewerThanLastScrape, isActionableVirtualExpensifyCard, isCardConnectionBroken, doesCardConnectionNeedReauthentication, @@ -321,7 +322,9 @@ function PaymentMethodList({ policyID: policyIDForCard, }); const shouldShowCardConnectionMessage = !!cardConnectionStatusDisplay?.messageKey; - const shouldShowCardErrorMessages = !shouldShowCardConnectionMessage || !!card.pendingAction; + // The connection message replaces the server's own connection error, but an error recorded after the last + // sync came from something the user just did, so it is kept. + const shouldShowCardErrorMessages = !shouldShowCardConnectionMessage || !!card.pendingAction || hasErrorNewerThanLastScrape(card); const shouldShowCardLastSync = shouldShowConnectionStatus && !isExpensifyCard(card) && !isCSVCard; let cardLastSyncText: string | undefined; if (shouldShowCardLastSync) { diff --git a/tests/unit/CardUtilsTest.ts b/tests/unit/CardUtilsTest.ts index 4b35980f7ea6..14bd3669bcf2 100644 --- a/tests/unit/CardUtilsTest.ts +++ b/tests/unit/CardUtilsTest.ts @@ -59,6 +59,7 @@ import { getYearFromExpirationDateString, hasAssignedCardMatching, hasCardConnectionIssue, + hasErrorNewerThanLastScrape, hasIssuedExpensifyCard, hasOnlyOneCardToAssign, isBrokenConnectionPastDismissThreshold, @@ -4474,6 +4475,36 @@ describe('CardUtils', () => { }); }); + describe('hasErrorNewerThanLastScrape', () => { + it('returns false when the card has no errors', () => { + const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05 11:00:00', errors: undefined}; + expect(hasErrorNewerThanLastScrape(card)).toBe(false); + }); + + // The server records the connection error at scrape time, so an error with the same timestamp is that one. + it('returns false for an error recorded at the last sync', () => { + const lastScrapeMicroseconds = new Date('2025-10-05T11:00:00').getTime() * 1000; + const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05 11:00:00', errors: {[lastScrapeMicroseconds]: 'Connection broken'}}; + expect(hasErrorNewerThanLastScrape(card)).toBe(false); + }); + + // A failed unassignment is recorded now, long after the last sync, and has to stay visible. + it('returns true for an error recorded after the last sync', () => { + const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05 11:00:00', errors: {[Date.now() * 1000]: 'Failed to unassign this card'}}; + expect(hasErrorNewerThanLastScrape(card)).toBe(true); + }); + + it('returns true when there is an error but no last sync to compare against', () => { + const card: Card = {...createRandomCard(1), lastScrape: undefined, errors: {1700000000000000: 'Failed to unassign this card'}}; + expect(hasErrorNewerThanLastScrape(card)).toBe(true); + }); + + it('parses an ISO 8601 last sync', () => { + const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05T11:00:00', errors: {[Date.now() * 1000]: 'Failed to unassign this card'}}; + expect(hasErrorNewerThanLastScrape(card)).toBe(true); + }); + }); + describe('isLastScrapePastDismissThreshold', () => { afterEach(() => { jest.restoreAllMocks(); From 7384e3015e34374806e80dec8d6b75964b5029e4 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Sat, 12 Sep 2026 09:08:56 +0430 Subject: [PATCH 06/24] Read the card sync timestamp as UTC --- src/libs/CardUtils.ts | 9 +++++---- tests/unit/CardUtilsTest.ts | 11 +++++++++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index 05ce214cdcd4..39807289dc91 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -50,7 +50,7 @@ import type {Locale as DateFnsLocale} from 'date-fns'; import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import type {TupleToUnion, ValueOf} from 'type-fest'; -import {format, fromUnixTime, isBefore, parse} from 'date-fns'; +import {format, fromUnixTime, isBefore} from 'date-fns'; import groupBy from 'lodash/groupBy'; import lodashSortBy from 'lodash/sortBy'; @@ -1498,8 +1498,9 @@ function getCardConnectionStatusDisplay({ /** * Parses a card's last sync. `card.lastScrape` is usually the Expensify DB datetime format ("2024-11-27 11:00:53"), - * but a personal card's value can arrive as ISO 8601 ("2024-11-27T11:00:53Z"). The DB format is tried explicitly - * first because its `new Date()` handling is not portable across JS engines, then `new Date()` handles ISO 8601. + * which carries no offset but is UTC, so it is turned into ISO 8601 with a `Z` rather than read as device local time. + * That matches how the App reads a DB datetime elsewhere, see `DateUtils.getLocalDateFromDatetime`. A personal card's + * value can already be ISO 8601, which the fallback handles. * * @param card the card to read * @returns the parsed date, or undefined when there is no usable value @@ -1508,7 +1509,7 @@ function parseCardLastScrape(card: Card): Date | undefined { if (!card.lastScrape) { return undefined; } - let lastScrapeDate = parse(card.lastScrape, 'yyyy-MM-dd HH:mm:ss', new Date()); + let lastScrapeDate = new Date(`${card.lastScrape.replace(' ', 'T')}Z`); if (Number.isNaN(lastScrapeDate.getTime())) { lastScrapeDate = new Date(card.lastScrape); } diff --git a/tests/unit/CardUtilsTest.ts b/tests/unit/CardUtilsTest.ts index ed860ac5e105..7b1e18f9c3e4 100644 --- a/tests/unit/CardUtilsTest.ts +++ b/tests/unit/CardUtilsTest.ts @@ -4483,12 +4483,19 @@ describe('CardUtils', () => { }); // The server records the connection error at scrape time, so an error with the same timestamp is that one. + // `lastScrape` has no offset but is UTC, so the expected key is built from the UTC instant rather than a local one. it('returns false for an error recorded at the last sync', () => { - const lastScrapeMicroseconds = new Date('2025-10-05T11:00:00').getTime() * 1000; + const lastScrapeMicroseconds = Date.parse('2025-10-05T11:00:00Z') * 1000; const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05 11:00:00', errors: {[lastScrapeMicroseconds]: 'Connection broken'}}; expect(hasErrorNewerThanLastScrape(card)).toBe(false); }); + it('returns true for an error recorded one second after the last sync', () => { + const oneSecondAfterLastScrape = (Date.parse('2025-10-05T11:00:00Z') + 1000) * 1000; + const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05 11:00:00', errors: {[oneSecondAfterLastScrape]: 'Failed to unassign this card'}}; + expect(hasErrorNewerThanLastScrape(card)).toBe(true); + }); + // A failed unassignment is recorded now, long after the last sync, and has to stay visible. it('returns true for an error recorded after the last sync', () => { const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05 11:00:00', errors: {[Date.now() * 1000]: 'Failed to unassign this card'}}; @@ -4501,7 +4508,7 @@ describe('CardUtils', () => { }); it('parses an ISO 8601 last sync', () => { - const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05T11:00:00', errors: {[Date.now() * 1000]: 'Failed to unassign this card'}}; + const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05T11:00:00Z', errors: {[Date.now() * 1000]: 'Failed to unassign this card'}}; expect(hasErrorNewerThanLastScrape(card)).toBe(true); }); }); From d48ea544b4dcf4b5fe715f78ae3a226e6b6639e3 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Sat, 12 Sep 2026 09:17:10 +0430 Subject: [PATCH 07/24] Keep fresh card errors lighting the indicator --- src/libs/actions/PaymentMethods.ts | 20 +++--- tests/unit/useAccountIndicatorChecksTest.ts | 70 +++++++++++++++++++++ 2 files changed, 80 insertions(+), 10 deletions(-) diff --git a/src/libs/actions/PaymentMethods.ts b/src/libs/actions/PaymentMethods.ts index a6170e94a784..8d8634923752 100644 --- a/src/libs/actions/PaymentMethods.ts +++ b/src/libs/actions/PaymentMethods.ts @@ -436,18 +436,18 @@ function hasPaymentMethodError( const policyList = Object.values(policies ?? {}).filter(Boolean); const hasRelevantCardError = cardsWithErrors.some((card) => { - if (CardUtils.isPersonalCard(card)) { - // A personal card's connection error is surfaced as a card error too, so once the card has gone without a - // successful sync past the grace period we stop leading the user to it and it must no longer light the RBR. - // This is deliberately keyed on the last successful sync rather than `isCardConnectionBroken`: the server - // sets the connection error even for scrape statuses that check treats as ignored (e.g. 434). - return !CardUtils.isLastScrapePastDismissThreshold(card); - } - // A company card follows the same grace period: past it we stop leading the user to the error, though the error - // itself stays on the card row and on the feed so it can still be fixed. - if (CardUtils.isLastScrapePastDismissThreshold(card)) { + // A card's connection error is surfaced as a card error too, so once the card has gone without a successful + // sync past the grace period we stop leading the user to it and it must no longer light the RBR. The threshold + // is keyed on the last successful sync rather than `isCardConnectionBroken` because the server sets the + // connection error even for scrape statuses that check treats as ignored (e.g. 434). An error recorded after + // the last sync came from something the user just did, so it still has to light the RBR. + const isStaleConnectionErrorOnly = CardUtils.isLastScrapePastDismissThreshold(card) && !CardUtils.hasErrorNewerThanLastScrape(card); + if (isStaleConnectionErrorOnly) { return false; } + if (CardUtils.isPersonalCard(card)) { + return true; + } const workspaceAccountID = Number(card?.fundID); const policy = policyList.find((p) => p?.policyAccountID === workspaceAccountID); return !!policy && isPolicyUser(policy, currentUserLogin); diff --git a/tests/unit/useAccountIndicatorChecksTest.ts b/tests/unit/useAccountIndicatorChecksTest.ts index 0ea5381ca4ca..15104a50f2d6 100644 --- a/tests/unit/useAccountIndicatorChecksTest.ts +++ b/tests/unit/useAccountIndicatorChecksTest.ts @@ -384,6 +384,76 @@ describe('useAccountIndicatorChecks', () => { expect(result.current.accountStatus).not.toBe(CONST.INDICATOR_STATUS.HAS_PAYMENT_METHOD_ERROR); }); + // A failed action writes a fresh error long after the last sync, and it still has to lead the user to it. + it('surfaces a personal card error recorded after the grace period has passed', async () => { + await act(async () => { + await Onyx.multiSet( + createMock({ + [ONYXKEYS.USER_WALLET]: {}, + [ONYXKEYS.BANK_ACCOUNT_LIST]: {}, + [ONYXKEYS.REIMBURSEMENT_ACCOUNT]: {}, + [ONYXKEYS.LOGINS]: {}, + [ONYXKEYS.WALLET_TERMS]: {}, + [ONYXKEYS.PRIVATE_PERSONAL_DETAILS]: {}, + [ONYXKEYS.NVP_PRIVATE_BILLING_DISPUTE_PENDING]: 0, + [ONYXKEYS.CARD_LIST]: { + card1: { + cardID: 1, + lastScrapeResult: 403, + lastScrape: '2020-01-01 00:00:00', + errors: {[Date.now() * 1000]: 'Failed to unassign this card.'}, + }, + }, + [ONYXKEYS.SESSION]: {email: userID}, + }), + ); + await waitForBatchedUpdatesWithAct(); + }); + + const {result} = renderHook(() => useAccountIndicatorChecks()); + await waitForBatchedUpdatesWithAct(); + + expect(result.current.accountStatus).toBe(CONST.INDICATOR_STATUS.HAS_PAYMENT_METHOD_ERROR); + }); + + it('surfaces a company card error recorded after the grace period has passed', async () => { + await act(async () => { + await Onyx.multiSet( + createMock({ + [ONYXKEYS.USER_WALLET]: {}, + [ONYXKEYS.BANK_ACCOUNT_LIST]: {}, + [ONYXKEYS.REIMBURSEMENT_ACCOUNT]: {}, + [ONYXKEYS.LOGINS]: {}, + [ONYXKEYS.WALLET_TERMS]: {}, + [ONYXKEYS.PRIVATE_PERSONAL_DETAILS]: {}, + [ONYXKEYS.NVP_PRIVATE_BILLING_DISPUTE_PENDING]: 0, + [ONYXKEYS.CARD_LIST]: { + card1: { + cardID: 1, + bank: cardFeed.feedName, + fundID: String(cardFeed.policyAccountID), + lastScrapeResult: 403, + lastScrape: '2020-01-01 00:00:00', + errors: {[Date.now() * 1000]: 'Failed to unassign this card.'}, + }, + }, + [`${ONYXKEYS.COLLECTION.POLICY}1` as const]: { + id: '1', + policyAccountID: cardFeed.policyAccountID, + role: CONST.POLICY.ROLE.USER, + }, + [ONYXKEYS.SESSION]: {email: userID}, + }), + ); + await waitForBatchedUpdatesWithAct(); + }); + + const {result} = renderHook(() => useAccountIndicatorChecks()); + await waitForBatchedUpdatesWithAct(); + + expect(result.current.accountStatus).toBe(CONST.INDICATOR_STATUS.HAS_PAYMENT_METHOD_ERROR); + }); + it('still surfaces a company card broken connection on the Account button within the grace period', async () => { const recentScrape = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString().slice(0, 19).replace('T', ' '); await act(async () => { From 003ac01551255234c3c3a50e5269812d3cabf1a4 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Sat, 12 Sep 2026 09:35:43 +0430 Subject: [PATCH 08/24] Avoid stranding cards on the fix page --- .../useFixPersonalCardConnection.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/pages/settings/Wallet/PersonalCards/FixPersonalCardConnectionPage/useFixPersonalCardConnection.ts b/src/pages/settings/Wallet/PersonalCards/FixPersonalCardConnectionPage/useFixPersonalCardConnection.ts index 96345f5d7a9f..c0c554956398 100644 --- a/src/pages/settings/Wallet/PersonalCards/FixPersonalCardConnectionPage/useFixPersonalCardConnection.ts +++ b/src/pages/settings/Wallet/PersonalCards/FixPersonalCardConnectionPage/useFixPersonalCardConnection.ts @@ -34,12 +34,14 @@ function useFixPersonalCardConnection(cardID: string) { } // The Plaid flow drives its own SyncCard from onSuccess, so skip the auto-sync here // to avoid a duplicate call when our optimistic update flips isCardBroken before unmount. - if (!card || isCardBroken || isPlaid) { + // A broken card is only kept on this page when there is a bank connection to send it to. Without one the page + // has nothing to offer, so it falls through to the sync below rather than stranding the user here. + if (!card || isPlaid || (isCardBroken && !!url)) { return; } updatePersonalCardConnection(card.cardID.toString(), card.lastScrapeResult); Navigation.goBack(ROUTES.SETTINGS_WALLET_PERSONAL_CARD_DETAILS.getRoute(cardID)); - }, [isCardBroken, card, cardID, cardListMetadata, isPlaid]); + }, [isCardBroken, card, cardID, cardListMetadata, isPlaid, url]); return {card, bankDisplayName, url, isCardBroken, isOffline, isPlaid, country}; } From 3a0a8bbae509bf5957fdb19f51379527d4c610d1 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Sat, 12 Sep 2026 09:46:34 +0430 Subject: [PATCH 09/24] Link the broken card message like the wallet --- src/libs/CardUtils.ts | 5 ----- .../report/actionContents/CardBrokenConnectionContent.tsx | 5 +++-- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index 39807289dc91..221c5c6770a1 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -1787,10 +1787,6 @@ function isCardPendingReplace(card?: Card) { * * @param card personal card to check */ -function isPersonalCardBrokenConnection(card?: Card) { - return card?.lastScrapeResult && !CONST.COMPANY_CARDS.BROKEN_CONNECTION_IGNORED_STATUSES.includes(card?.lastScrapeResult); -} - function isExpensifyCardPendingAction(card?: Card, privatePersonalDetails?: PrivatePersonalDetails): boolean { return ( card?.bank === CONST.EXPENSIFY_CARD.BANK && @@ -2262,7 +2258,6 @@ export { isTravelCardTransaction, getCompanyFeeds, hasCompanyCardFeeds, - isPersonalCardBrokenConnection, isCustomFeed, isCSVUploadFeed, isCSVFeedOrExpensifyCard, diff --git a/src/pages/inbox/report/actionContents/CardBrokenConnectionContent.tsx b/src/pages/inbox/report/actionContents/CardBrokenConnectionContent.tsx index e7e0a0786327..f8efaca1c4a5 100644 --- a/src/pages/inbox/report/actionContents/CardBrokenConnectionContent.tsx +++ b/src/pages/inbox/report/actionContents/CardBrokenConnectionContent.tsx @@ -4,7 +4,7 @@ import useEnvironment from '@hooks/useEnvironment'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; -import {isPersonalCardBrokenConnection} from '@libs/CardUtils'; +import {hasCardConnectionIssue} from '@libs/CardUtils'; import {getCardConnectionBrokenMessage, getOriginalMessage} from '@libs/ReportActionsUtils'; import ReportActionItemBasicMessage from '@pages/inbox/report/ReportActionItemBasicMessage'; @@ -31,7 +31,8 @@ function CardBrokenConnectionContent({action}: CardBrokenConnectionContentProps) const [card] = useOnyx(ONYXKEYS.CARD_LIST, {selector: cardByIdSelector(String(cardID))}); - const connectionLink = cardID && isPersonalCardBrokenConnection(card) ? `${environmentURL}/${ROUTES.SETTINGS_WALLET_PERSONAL_CARD_DETAILS.getRoute(String(cardID))}` : undefined; + // Matches the wallet row, so a card the wallet offers a fix for is linked here too. + const connectionLink = cardID && !!card && hasCardConnectionIssue(card) ? `${environmentURL}/${ROUTES.SETTINGS_WALLET_PERSONAL_CARD_DETAILS.getRoute(String(cardID))}` : undefined; const is30DaysReminder = action.actionName === CONST.REPORT.ACTIONS.TYPE.PERSONAL_CARD_CONNECTION_BROKEN_30_DAYS; const brokenConnectionMessage = getCardConnectionBrokenMessage(card, cardName, translate, is30DaysReminder, connectionLink); From cc3beefcbd034d41a331d652762a19cd11d50f4f Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Sat, 12 Sep 2026 09:50:44 +0430 Subject: [PATCH 10/24] Skip error age for never-synced cards --- src/libs/CardUtils.ts | 4 +++- tests/unit/CardUtilsTest.ts | 5 +++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index 221c5c6770a1..166d18673701 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -1531,7 +1531,9 @@ function hasErrorNewerThanLastScrape(card: Card): boolean { } const lastScrapeDate = parseCardLastScrape(card); if (!lastScrapeDate) { - return true; + // A card that has never synced has nothing to compare against, so the error is left to the connection message + // rather than shown underneath it. + return false; } // Error keys are microseconds, `lastScrape` is milliseconds. const lastScrapeMicroseconds = lastScrapeDate.getTime() * 1000; diff --git a/tests/unit/CardUtilsTest.ts b/tests/unit/CardUtilsTest.ts index 7b1e18f9c3e4..0da411f8c198 100644 --- a/tests/unit/CardUtilsTest.ts +++ b/tests/unit/CardUtilsTest.ts @@ -4502,9 +4502,10 @@ describe('CardUtils', () => { expect(hasErrorNewerThanLastScrape(card)).toBe(true); }); - it('returns true when there is an error but no last sync to compare against', () => { + // A card that has never synced cannot be compared against, so its error stays with the connection message. + it('returns false when there is an error but no last sync to compare against', () => { const card: Card = {...createRandomCard(1), lastScrape: undefined, errors: {1700000000000000: 'Failed to unassign this card'}}; - expect(hasErrorNewerThanLastScrape(card)).toBe(true); + expect(hasErrorNewerThanLastScrape(card)).toBe(false); }); it('parses an ISO 8601 last sync', () => { From dcf38cda25a2a2eec6f2e9c360603f5f41cbb250 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Sat, 12 Sep 2026 10:24:19 +0430 Subject: [PATCH 11/24] Show only errors newer than the last sync --- src/libs/CardUtils.ts | 33 +++++++++++-------- .../settings/Wallet/PaymentMethodList.tsx | 13 ++++---- tests/unit/CardUtilsTest.ts | 9 +++++ 3 files changed, 35 insertions(+), 20 deletions(-) diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index 166d18673701..2a456f35a71c 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -41,6 +41,7 @@ import type { NonConnectableBankName, } from '@src/types/onyx/CardFeeds'; import type {CardFeedErrors} from '@src/types/onyx/DerivedValues'; +import type {Errors} from '@src/types/onyx/OnyxCommon'; import type {SelectedTimezone} from '@src/types/onyx/PersonalDetails'; import type {Connections} from '@src/types/onyx/Policy'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; @@ -1517,27 +1518,30 @@ function parseCardLastScrape(card: Card): Date | undefined { } /** - * Whether the card carries an error recorded after its last sync. The server writes a connection error at scrape - * time, so anything newer came from something the user just did (a failed unassignment, for example) and has to stay - * visible even when a connection message is already on the row. + * The card's errors recorded after its last sync. The server writes the connection error at scrape time, so anything + * newer came from something the user just did and has to stay visible even when a connection message already covers + * the connection itself. * - * @param card the card to check - * @returns true if an error is newer than the last sync, false otherwise + * @param card the card to read + * @returns the errors newer than the last sync */ -function hasErrorNewerThanLastScrape(card: Card): boolean { - const errorKeys = Object.keys(card.errors ?? {}); - if (errorKeys.length === 0) { - return false; - } +function getCardErrorsNewerThanLastScrape(card: Card): Errors { const lastScrapeDate = parseCardLastScrape(card); if (!lastScrapeDate) { - // A card that has never synced has nothing to compare against, so the error is left to the connection message - // rather than shown underneath it. - return false; + // A card that has never synced has nothing to compare against, so its errors are left to the connection message. + return {}; } // Error keys are microseconds, `lastScrape` is milliseconds. const lastScrapeMicroseconds = lastScrapeDate.getTime() * 1000; - return errorKeys.some((errorKey) => Number(errorKey) > lastScrapeMicroseconds); + return Object.fromEntries(Object.entries(card.errors ?? {}).filter(([errorKey]) => Number(errorKey) > lastScrapeMicroseconds)); +} + +/** + * @param card the card to check + * @returns true if an error is newer than the last sync, false otherwise + */ +function hasErrorNewerThanLastScrape(card: Card): boolean { + return !isEmptyObject(getCardErrorsNewerThanLastScrape(card)); } /** @@ -2287,6 +2291,7 @@ export { isCardHiddenFromSearch, getCSVFeedType, getFeedType, + getCardErrorsNewerThanLastScrape, hasErrorNewerThanLastScrape, isCardConnectionBroken, hasCardConnectionIssue, diff --git a/src/pages/settings/Wallet/PaymentMethodList.tsx b/src/pages/settings/Wallet/PaymentMethodList.tsx index 3c7fc17d998d..1bc7dab9bb2e 100644 --- a/src/pages/settings/Wallet/PaymentMethodList.tsx +++ b/src/pages/settings/Wallet/PaymentMethodList.tsx @@ -20,10 +20,10 @@ import { getCardConnectionStatusDisplay, getCardFeedIcon, getCardFeedWithDomainID, + getCardErrorsNewerThanLastScrape, getCompanyCardFeedWithDomainIDForCard, getPlaidInstitutionIconUrl, hasCardConnectionIssue, - hasErrorNewerThanLastScrape, isActionableVirtualExpensifyCard, isCardConnectionBroken, doesCardConnectionNeedReauthentication, @@ -322,9 +322,10 @@ function PaymentMethodList({ policyID: policyIDForCard, }); const shouldShowCardConnectionMessage = !!cardConnectionStatusDisplay?.messageKey; - // The connection message replaces the server's own connection error, but an error recorded after the last - // sync came from something the user just did, so it is kept. - const shouldShowCardErrorMessages = !shouldShowCardConnectionMessage || !!card.pendingAction || hasErrorNewerThanLastScrape(card); + // The connection message replaces the server's own connection error, so only errors recorded after the + // last sync are kept alongside it. + const cardErrors = shouldShowCardConnectionMessage && !card.pendingAction ? getCardErrorsNewerThanLastScrape(card) : card.errors; + const shouldShowCardErrorMessages = !isEmptyObject(cardErrors); const shouldShowCardLastSync = shouldShowConnectionStatus && !isExpensifyCard(card) && !isCSVCard; let cardLastSyncText: string | undefined; if (shouldShowCardLastSync) { @@ -420,7 +421,7 @@ function PaymentMethodList({ disabled: isDisabled, shouldShowRightIcon, shouldShowThreeDotsMenu: !isUserPersonalCard, - errors: isUserPersonalCard ? undefined : card.errors, + errors: isUserPersonalCard ? undefined : cardErrors, shouldShowErrorMessages: !isUserPersonalCard && shouldShowCardErrorMessages, canDismissError: false, pendingAction: card.pendingAction, @@ -498,7 +499,7 @@ function PaymentMethodList({ shouldShowRightIcon: true, interactive: !isDisabled, disabled: isDisabled, - errors: card.errors, + errors: cardErrors, shouldShowErrorMessages: shouldShowCardErrorMessages, canDismissError: true, pendingAction: card.pendingAction, diff --git a/tests/unit/CardUtilsTest.ts b/tests/unit/CardUtilsTest.ts index 0da411f8c198..9f8178c74f3d 100644 --- a/tests/unit/CardUtilsTest.ts +++ b/tests/unit/CardUtilsTest.ts @@ -59,6 +59,7 @@ import { getWalletProviderNameKey, getYearFromExpirationDateString, hasAssignedCardMatching, + getCardErrorsNewerThanLastScrape, hasCardConnectionIssue, hasErrorNewerThanLastScrape, hasIssuedExpensifyCard, @@ -4502,6 +4503,14 @@ describe('CardUtils', () => { expect(hasErrorNewerThanLastScrape(card)).toBe(true); }); + // Only the newer error is kept, so a stale connection error is not shown next to the connection message. + it('keeps only the errors recorded after the last sync', () => { + const staleKey = Date.parse('2025-10-05T11:00:00Z') * 1000; + const freshKey = Date.now() * 1000; + const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05 11:00:00', errors: {[staleKey]: 'Connection broken', [freshKey]: 'Failed to unassign this card'}}; + expect(getCardErrorsNewerThanLastScrape(card)).toEqual({[freshKey]: 'Failed to unassign this card'}); + }); + // A card that has never synced cannot be compared against, so its error stays with the connection message. it('returns false when there is an error but no last sync to compare against', () => { const card: Card = {...createRandomCard(1), lastScrape: undefined, errors: {1700000000000000: 'Failed to unassign this card'}}; From 3a3447a0711efaeeedb1b41e598073c4fe56b34a Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Sat, 12 Sep 2026 12:36:07 +0430 Subject: [PATCH 12/24] Remove the orphaned JSDoc --- src/libs/CardUtils.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index 2a456f35a71c..6e0ab7697448 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -1788,11 +1788,6 @@ function isCardPendingReplace(card?: Card) { ); } -/** - * Check if card has a broken connection - * - * @param card personal card to check - */ function isExpensifyCardPendingAction(card?: Card, privatePersonalDetails?: PrivatePersonalDetails): boolean { return ( card?.bank === CONST.EXPENSIFY_CARD.BANK && From ec8977f4ee2032492b1601718f3c40ad141527cb Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Sat, 12 Sep 2026 13:24:38 +0430 Subject: [PATCH 13/24] Document the error key shape and cover it --- src/libs/CardUtils.ts | 8 +++++--- tests/unit/CardUtilsTest.ts | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index 6e0ab7697448..d08df0d293fd 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -1518,9 +1518,11 @@ function parseCardLastScrape(card: Card): Date | undefined { } /** - * The card's errors recorded after its last sync. The server writes the connection error at scrape time, so anything - * newer came from something the user just did and has to stay visible even when a connection message already covers - * the connection itself. + * The card's errors recorded after its last sync. Something the user just did has to stay visible even when a + * connection message already covers the connection itself, and the two are told apart by how they are keyed: the + * server names its connection error `connectionError`, while a user action records its error under a microsecond + * timestamp. A named key is not a number, so it never reads as newer and the comparison only ever sees the second + * kind. That matters because `lastScrape` is the last successful sync, which a broken card never advances. * * @param card the card to read * @returns the errors newer than the last sync diff --git a/tests/unit/CardUtilsTest.ts b/tests/unit/CardUtilsTest.ts index 9f8178c74f3d..fc068037a07f 100644 --- a/tests/unit/CardUtilsTest.ts +++ b/tests/unit/CardUtilsTest.ts @@ -4483,6 +4483,23 @@ describe('CardUtils', () => { expect(hasErrorNewerThanLastScrape(card)).toBe(false); }); + // The server names its connection error rather than keying it by time, so it stays out of this filter however + // long the card has gone without a successful sync, which is the whole grace period for a broken card. + it('returns false for the server connection error on a card that stopped syncing long ago', () => { + const card: Card = {...createRandomCard(1), lastScrape: '2024-01-05 11:00:00', errors: {connectionError: 'Your card connection is broken.'}}; + expect(hasErrorNewerThanLastScrape(card)).toBe(false); + }); + + // A user action on that same stale card is keyed by timestamp, so it still has to come through. + it('returns true for a user action error on a card that stopped syncing long ago', () => { + const card: Card = { + ...createRandomCard(1), + lastScrape: '2024-01-05 11:00:00', + errors: {connectionError: 'Your card connection is broken.', [Date.now() * 1000]: 'Failed to unassign this card'}, + }; + expect(hasErrorNewerThanLastScrape(card)).toBe(true); + }); + // The server records the connection error at scrape time, so an error with the same timestamp is that one. // `lastScrape` has no offset but is UTC, so the expected key is built from the UTC instant rather than a local one. it('returns false for an error recorded at the last sync', () => { From d77c4691ae8b9e5b07159d292639c7ea23954d21 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Mon, 14 Sep 2026 15:13:37 +0430 Subject: [PATCH 14/24] Show one message per card row --- src/libs/CardUtils.ts | 32 +++----- src/libs/actions/PaymentMethods.ts | 6 +- .../settings/Wallet/PaymentMethodList.tsx | 28 ++++--- tests/unit/CardUtilsTest.ts | 81 +++++++------------ 4 files changed, 60 insertions(+), 87 deletions(-) diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index d08df0d293fd..226c07a712e4 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -1518,32 +1518,24 @@ function parseCardLastScrape(card: Card): Date | undefined { } /** - * The card's errors recorded after its last sync. Something the user just did has to stay visible even when a - * connection message already covers the connection itself, and the two are told apart by how they are keyed: the - * server names its connection error `connectionError`, while a user action records its error under a microsecond - * timestamp. A named key is not a number, so it never reads as newer and the comparison only ever sees the second - * kind. That matters because `lastScrape` is the last successful sync, which a broken card never advances. + * The card's errors that came from an action the user took, rather than from the connection itself. The two are told + * apart by how they are keyed: the server names its connection error `connectionError`, while a user action records + * its error under a microsecond timestamp. Keying on the shape rather than on the age matters because `lastScrape` is + * the last successful sync, which a broken card never advances, so every error on such a card looks recent. * * @param card the card to read - * @returns the errors newer than the last sync + * @returns the errors a user action recorded */ -function getCardErrorsNewerThanLastScrape(card: Card): Errors { - const lastScrapeDate = parseCardLastScrape(card); - if (!lastScrapeDate) { - // A card that has never synced has nothing to compare against, so its errors are left to the connection message. - return {}; - } - // Error keys are microseconds, `lastScrape` is milliseconds. - const lastScrapeMicroseconds = lastScrapeDate.getTime() * 1000; - return Object.fromEntries(Object.entries(card.errors ?? {}).filter(([errorKey]) => Number(errorKey) > lastScrapeMicroseconds)); +function getCardActionErrors(card: Card): Errors { + return Object.fromEntries(Object.entries(card.errors ?? {}).filter(([errorKey]) => !Number.isNaN(Number(errorKey)))); } /** * @param card the card to check - * @returns true if an error is newer than the last sync, false otherwise + * @returns true if an action the user took left an error on the card, false otherwise */ -function hasErrorNewerThanLastScrape(card: Card): boolean { - return !isEmptyObject(getCardErrorsNewerThanLastScrape(card)); +function hasCardActionErrors(card: Card): boolean { + return !isEmptyObject(getCardActionErrors(card)); } /** @@ -2288,8 +2280,8 @@ export { isCardHiddenFromSearch, getCSVFeedType, getFeedType, - getCardErrorsNewerThanLastScrape, - hasErrorNewerThanLastScrape, + getCardActionErrors, + hasCardActionErrors, isCardConnectionBroken, hasCardConnectionIssue, doesCardConnectionNeedReauthentication, diff --git a/src/libs/actions/PaymentMethods.ts b/src/libs/actions/PaymentMethods.ts index 8d8634923752..a466364bacc1 100644 --- a/src/libs/actions/PaymentMethods.ts +++ b/src/libs/actions/PaymentMethods.ts @@ -439,9 +439,9 @@ function hasPaymentMethodError( // A card's connection error is surfaced as a card error too, so once the card has gone without a successful // sync past the grace period we stop leading the user to it and it must no longer light the RBR. The threshold // is keyed on the last successful sync rather than `isCardConnectionBroken` because the server sets the - // connection error even for scrape statuses that check treats as ignored (e.g. 434). An error recorded after - // the last sync came from something the user just did, so it still has to light the RBR. - const isStaleConnectionErrorOnly = CardUtils.isLastScrapePastDismissThreshold(card) && !CardUtils.hasErrorNewerThanLastScrape(card); + // connection error even for scrape statuses that check treats as ignored (e.g. 434). An error left behind by + // something the user did is a separate problem from the connection, so it still has to light the RBR. + const isStaleConnectionErrorOnly = CardUtils.isLastScrapePastDismissThreshold(card) && !CardUtils.hasCardActionErrors(card); if (isStaleConnectionErrorOnly) { return false; } diff --git a/src/pages/settings/Wallet/PaymentMethodList.tsx b/src/pages/settings/Wallet/PaymentMethodList.tsx index 1bc7dab9bb2e..f6fc71773d77 100644 --- a/src/pages/settings/Wallet/PaymentMethodList.tsx +++ b/src/pages/settings/Wallet/PaymentMethodList.tsx @@ -20,7 +20,7 @@ import { getCardConnectionStatusDisplay, getCardFeedIcon, getCardFeedWithDomainID, - getCardErrorsNewerThanLastScrape, + getCardActionErrors, getCompanyCardFeedWithDomainIDForCard, getPlaidInstitutionIconUrl, hasCardConnectionIssue, @@ -321,11 +321,14 @@ function PaymentMethodList({ doesCardNeedReauthentication: doesCardConnectionNeedReauthentication(card), policyID: policyIDForCard, }); - const shouldShowCardConnectionMessage = !!cardConnectionStatusDisplay?.messageKey; - // The connection message replaces the server's own connection error, so only errors recorded after the - // last sync are kept alongside it. - const cardErrors = shouldShowCardConnectionMessage && !card.pendingAction ? getCardErrorsNewerThanLastScrape(card) : card.errors; + // An action the user just took that failed is what the row has to say, so its error replaces our + // connection copy rather than stacking with it. The server's own connection error is left out either + // way: the connection message says the same thing in copy we control, with a way to fix it. + const cardErrors = card.pendingAction ? card.errors : getCardActionErrors(card); const shouldShowCardErrorMessages = !isEmptyObject(cardErrors); + // A personal card row renders no card error of its own, so letting one replace the connection message + // there would leave the row with a status and nothing to explain it. + const doesCardErrorReplaceConnectionMessage = !isUserPersonalCard && shouldShowCardErrorMessages; const shouldShowCardLastSync = shouldShowConnectionStatus && !isExpensifyCard(card) && !isCSVCard; let cardLastSyncText: string | undefined; if (shouldShowCardLastSync) { @@ -339,7 +342,11 @@ function PaymentMethodList({ if (cardConnectionStatusDisplay) { const companyCardsRoute = policyIDForCard ? ROUTES.WORKSPACE_COMPANY_CARDS.getRoute(policyIDForCard) : undefined; let cardConnectionMessage: string | undefined; - if (cardConnectionStatusDisplay.shouldUseCompanyCardsLink && companyCardsRoute) { + // The row carries one message at a time, and a failed action wins it, since that is what the user + // just did. The badge still reads Inactive, so the connection is not misreported meanwhile. + if (doesCardErrorReplaceConnectionMessage) { + cardConnectionMessage = undefined; + } else if (cardConnectionStatusDisplay.shouldUseCompanyCardsLink && companyCardsRoute) { cardConnectionMessage = translate('walletPage.cardStatus.fixConnectionIn', `${environmentURL}/${companyCardsRoute}`); } else if (cardConnectionStatusDisplay.shouldUseReauthMessage) { cardConnectionMessage = translate('walletPage.cardStatus.reconnectBank'); @@ -353,10 +360,11 @@ function PaymentMethodList({ statusText: translate(cardConnectionStatusDisplay.statusKey), statusTone: cardConnectionStatusDisplay.statusTone, message: cardConnectionMessage, - actionText: cardConnectionStatusDisplay.actionKey ? translate(cardConnectionStatusDisplay.actionKey) : undefined, - onActionPress: cardConnectionStatusDisplay.shouldUsePersonalCardFix - ? () => Navigation.navigate(ROUTES.SETTINGS_WALLET_PERSONAL_CARD_FIX_CONNECTION.getRoute(String(card.cardID))) - : undefined, + actionText: cardConnectionMessage && cardConnectionStatusDisplay.actionKey ? translate(cardConnectionStatusDisplay.actionKey) : undefined, + onActionPress: + cardConnectionMessage && cardConnectionStatusDisplay.shouldUsePersonalCardFix + ? () => Navigation.navigate(ROUTES.SETTINGS_WALLET_PERSONAL_CARD_FIX_CONNECTION.getRoute(String(card.cardID))) + : undefined, onLinkPress: cardConnectionStatusDisplay.shouldUseCompanyCardsLink && companyCardsRoute ? () => { diff --git a/tests/unit/CardUtilsTest.ts b/tests/unit/CardUtilsTest.ts index fc068037a07f..4cc201ae4bfb 100644 --- a/tests/unit/CardUtilsTest.ts +++ b/tests/unit/CardUtilsTest.ts @@ -59,9 +59,9 @@ import { getWalletProviderNameKey, getYearFromExpirationDateString, hasAssignedCardMatching, - getCardErrorsNewerThanLastScrape, + getCardActionErrors, hasCardConnectionIssue, - hasErrorNewerThanLastScrape, + hasCardActionErrors, hasIssuedExpensifyCard, hasOnlyOneCardToAssign, isBrokenConnectionPastDismissThreshold, @@ -4477,66 +4477,39 @@ describe('CardUtils', () => { }); }); - describe('hasErrorNewerThanLastScrape', () => { - it('returns false when the card has no errors', () => { - const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05 11:00:00', errors: undefined}; - expect(hasErrorNewerThanLastScrape(card)).toBe(false); + describe('getCardActionErrors', () => { + it('returns nothing when the card has no errors', () => { + const card: Card = {...createRandomCard(1), errors: undefined}; + expect(hasCardActionErrors(card)).toBe(false); }); - // The server names its connection error rather than keying it by time, so it stays out of this filter however - // long the card has gone without a successful sync, which is the whole grace period for a broken card. - it('returns false for the server connection error on a card that stopped syncing long ago', () => { - const card: Card = {...createRandomCard(1), lastScrape: '2024-01-05 11:00:00', errors: {connectionError: 'Your card connection is broken.'}}; - expect(hasErrorNewerThanLastScrape(card)).toBe(false); + // The server names its connection error, so the row shows our own connection copy for it instead. + it('leaves out the server connection error', () => { + const card: Card = {...createRandomCard(1), errors: {connectionError: 'Your card connection is broken.'}}; + expect(getCardActionErrors(card)).toEqual({}); }); - // A user action on that same stale card is keyed by timestamp, so it still has to come through. - it('returns true for a user action error on a card that stopped syncing long ago', () => { - const card: Card = { - ...createRandomCard(1), - lastScrape: '2024-01-05 11:00:00', - errors: {connectionError: 'Your card connection is broken.', [Date.now() * 1000]: 'Failed to unassign this card'}, - }; - expect(hasErrorNewerThanLastScrape(card)).toBe(true); - }); - - // The server records the connection error at scrape time, so an error with the same timestamp is that one. - // `lastScrape` has no offset but is UTC, so the expected key is built from the UTC instant rather than a local one. - it('returns false for an error recorded at the last sync', () => { - const lastScrapeMicroseconds = Date.parse('2025-10-05T11:00:00Z') * 1000; - const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05 11:00:00', errors: {[lastScrapeMicroseconds]: 'Connection broken'}}; - expect(hasErrorNewerThanLastScrape(card)).toBe(false); - }); - - it('returns true for an error recorded one second after the last sync', () => { - const oneSecondAfterLastScrape = (Date.parse('2025-10-05T11:00:00Z') + 1000) * 1000; - const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05 11:00:00', errors: {[oneSecondAfterLastScrape]: 'Failed to unassign this card'}}; - expect(hasErrorNewerThanLastScrape(card)).toBe(true); - }); - - // A failed unassignment is recorded now, long after the last sync, and has to stay visible. - it('returns true for an error recorded after the last sync', () => { - const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05 11:00:00', errors: {[Date.now() * 1000]: 'Failed to unassign this card'}}; - expect(hasErrorNewerThanLastScrape(card)).toBe(true); - }); - - // Only the newer error is kept, so a stale connection error is not shown next to the connection message. - it('keeps only the errors recorded after the last sync', () => { - const staleKey = Date.parse('2025-10-05T11:00:00Z') * 1000; - const freshKey = Date.now() * 1000; - const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05 11:00:00', errors: {[staleKey]: 'Connection broken', [freshKey]: 'Failed to unassign this card'}}; - expect(getCardErrorsNewerThanLastScrape(card)).toEqual({[freshKey]: 'Failed to unassign this card'}); + // A user action records its error under a microsecond timestamp, and that is the message the row has to carry. + it('keeps an error a user action recorded', () => { + const recordedAt = Date.now() * 1000; + const card: Card = {...createRandomCard(1), errors: {[recordedAt]: 'Failed to unassign this card'}}; + expect(getCardActionErrors(card)).toEqual({[recordedAt]: 'Failed to unassign this card'}); }); - // A card that has never synced cannot be compared against, so its error stays with the connection message. - it('returns false when there is an error but no last sync to compare against', () => { - const card: Card = {...createRandomCard(1), lastScrape: undefined, errors: {1700000000000000: 'Failed to unassign this card'}}; - expect(hasErrorNewerThanLastScrape(card)).toBe(false); + // Both at once: the action error is kept and the connection error is left to the connection message. + it('keeps only the user action error when the card carries both', () => { + const recordedAt = Date.now() * 1000; + const card: Card = {...createRandomCard(1), errors: {connectionError: 'Your card connection is broken.', [recordedAt]: 'Failed to unassign this card'}}; + expect(getCardActionErrors(card)).toEqual({[recordedAt]: 'Failed to unassign this card'}); }); - it('parses an ISO 8601 last sync', () => { - const card: Card = {...createRandomCard(1), lastScrape: '2025-10-05T11:00:00Z', errors: {[Date.now() * 1000]: 'Failed to unassign this card'}}; - expect(hasErrorNewerThanLastScrape(card)).toBe(true); + // A broken card never advances `lastScrape`, so the age of an error says nothing about which kind it is. + it('keeps a user action error however old it is and whether or not the card ever synced', () => { + const longAgo = Date.parse('2024-01-05T11:00:00Z') * 1000; + const neverSynced: Card = {...createRandomCard(1), lastScrape: undefined, errors: {[longAgo]: 'Failed to remove this card'}}; + const syncedSince: Card = {...createRandomCard(2), lastScrape: '2025-10-05 11:00:00', errors: {[longAgo]: 'Failed to remove this card'}}; + expect(hasCardActionErrors(neverSynced)).toBe(true); + expect(hasCardActionErrors(syncedSince)).toBe(true); }); }); From 9ff6e46669e442f86bc239357136cba648a0a3a6 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Mon, 14 Sep 2026 16:20:06 +0430 Subject: [PATCH 15/24] Offer the fix for actionable scrape statuses --- .../getShouldShowBrokenConnectionError.ts | 6 ++++-- src/hooks/useCardFeedErrors.ts | 1 + .../actions/OnyxDerived/configs/cardFeedErrors.ts | 6 ++++++ src/types/onyx/DerivedValues.ts | 7 +++++++ .../YourSpendSection/useYourSpendDataTest.ts | 9 ++++++++- .../getShouldShowBrokenConnectionErrorTest.ts | 15 +++++++++++++++ ...seBrokenDirectCompanyCardFeedsForAdmin.test.ts | 1 + 7 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/components/Tables/WorkspaceCompanyCardsTable/getShouldShowBrokenConnectionError.ts b/src/components/Tables/WorkspaceCompanyCardsTable/getShouldShowBrokenConnectionError.ts index eed3ef383410..408dcfe30c12 100644 --- a/src/components/Tables/WorkspaceCompanyCardsTable/getShouldShowBrokenConnectionError.ts +++ b/src/components/Tables/WorkspaceCompanyCardsTable/getShouldShowBrokenConnectionError.ts @@ -8,10 +8,12 @@ import type {CardFeedErrorState} from '@src/types/onyx/DerivedValues'; * * A broken card-level scrape connection can only be fixed by logging into a bank on direct * OAuth/Plaid feeds, so commercial and other file-based feeds don't surface that error unless - * the feed itself has errors. + * the feed itself has errors. `hasFeedConnectionIssue` covers the statuses `isFeedConnectionBroken` + * ignores, such as 434, because the wallet sends those cards here to be fixed. */ function getShouldShowBrokenConnectionError(feedName: CompanyCardFeedWithDomainID, feedErrors: CardFeedErrorState | undefined): boolean { - return (!!feedErrors?.isFeedConnectionBroken && isDirectFeed(feedName)) || !!feedErrors?.hasFeedErrors; + const hasConnectionToFix = !!feedErrors?.isFeedConnectionBroken || !!feedErrors?.hasFeedConnectionIssue; + return (hasConnectionToFix && isDirectFeed(feedName)) || !!feedErrors?.hasFeedErrors; } export default getShouldShowBrokenConnectionError; diff --git a/src/hooks/useCardFeedErrors.ts b/src/hooks/useCardFeedErrors.ts index 1423c7cb7872..9a7a3b6a85ca 100644 --- a/src/hooks/useCardFeedErrors.ts +++ b/src/hooks/useCardFeedErrors.ts @@ -9,6 +9,7 @@ const DEFAULT_CARD_FEED_ERROR_STATE: CardFeedErrorState = { shouldPromptBrokenConnection: false, hasFeedErrors: false, hasWorkspaceErrors: false, + hasFeedConnectionIssue: false, }; const DEFAULT_CARD_FEED_ERRORS: CardFeedErrors = { diff --git a/src/libs/actions/OnyxDerived/configs/cardFeedErrors.ts b/src/libs/actions/OnyxDerived/configs/cardFeedErrors.ts index 0ece5f7b0ddc..33fbfabef497 100644 --- a/src/libs/actions/OnyxDerived/configs/cardFeedErrors.ts +++ b/src/libs/actions/OnyxDerived/configs/cardFeedErrors.ts @@ -4,6 +4,7 @@ import { forEachAssignedCard, getCardFeedWithDomainID, isBrokenConnectionPastDismissThreshold, + hasCardConnectionIssue, isCardConnectionBroken, isLastScrapePastDismissThreshold, isPersonalCard, @@ -26,6 +27,7 @@ const DEFAULT_CARD_FEED_ERROR_STATE: CardFeedErrorState = { hasWorkspaceErrors: false, isFeedConnectionBroken: false, shouldPromptBrokenConnection: false, + hasFeedConnectionIssue: false, }; function getShouldShowRBR(state: Partial): boolean { @@ -97,6 +99,7 @@ export default createOnyxDerivedValueConfig({ shouldPromptBrokenConnection: isFeedConnectionBroken, hasFeedErrors: !isEmptyObject(cardErrors), hasWorkspaceErrors: false, + hasFeedConnectionIssue: hasCardConnectionIssue(card), }; const shouldShowRBR = getShouldShowRBR(newFeedState); @@ -155,6 +158,7 @@ export default createOnyxDerivedValueConfig({ shouldPromptBrokenConnection: shouldPromptBrokenConnection || previousFeedErrors.shouldPromptBrokenConnection, hasFeedErrors: hasFeedErrors || previousFeedErrors.hasFeedErrors, hasWorkspaceErrors: hasWorkspaceErrors || previousFeedErrors.hasWorkspaceErrors, + hasFeedConnectionIssue: hasCardConnectionIssue(card) || previousFeedErrors.hasFeedConnectionIssue, }; const shouldShowRBR = getShouldShowRBR(newFeedState) || previousFeedErrors.shouldShowRBR; @@ -181,11 +185,13 @@ export default createOnyxDerivedValueConfig({ allFeedsState.shouldPromptBrokenConnection ||= newFeedState.shouldPromptBrokenConnection; allFeedsState.hasFeedErrors ||= newFeedState.hasFeedErrors; allFeedsState.hasWorkspaceErrors ||= newFeedState.hasWorkspaceErrors; + allFeedsState.hasFeedConnectionIssue ||= newFeedState.hasFeedConnectionIssue; cardTypeState.isFeedConnectionBroken ||= newFeedState.isFeedConnectionBroken; cardTypeState.shouldPromptBrokenConnection ||= newFeedState.shouldPromptBrokenConnection; cardTypeState.hasFeedErrors ||= newFeedState.hasFeedErrors; cardTypeState.hasWorkspaceErrors ||= newFeedState.hasWorkspaceErrors; + cardTypeState.hasFeedConnectionIssue ||= newFeedState.hasFeedConnectionIssue; shouldShowRbrForWorkspaceAccountID[workspaceAccountID] ||= shouldShowRBR; shouldShowRbrForFeedNameWithDomainID[feedNameWithDomainID] ||= shouldShowRBR; diff --git a/src/types/onyx/DerivedValues.ts b/src/types/onyx/DerivedValues.ts index 67731bdf65e7..7f27453a5ba0 100644 --- a/src/types/onyx/DerivedValues.ts +++ b/src/types/onyx/DerivedValues.ts @@ -136,6 +136,13 @@ type CardFeedErrorState = { * unresolved past the grace period, so we stop nagging without taking away the ability to fix it. */ shouldPromptBrokenConnection: boolean; + + /** + * Whether a card on the feed reports something its holder has to act on, which covers the scrape statuses + * `isFeedConnectionBroken` ignores (e.g. 434, the bank changing the account number). The wallet sends those + * cards to the Company cards page, so that page has to offer the same fix for them. + */ + hasFeedConnectionIssue: boolean; }; /** diff --git a/tests/unit/HomePage/YourSpendSection/useYourSpendDataTest.ts b/tests/unit/HomePage/YourSpendSection/useYourSpendDataTest.ts index 9e9b928cf2d3..e4c89a2c428b 100644 --- a/tests/unit/HomePage/YourSpendSection/useYourSpendDataTest.ts +++ b/tests/unit/HomePage/YourSpendSection/useYourSpendDataTest.ts @@ -210,7 +210,14 @@ function setupCardGroups(groups: CardGroupFixture[], searchOverrides: Partial = {}): CardFeedErrors { - const defaultState: CardFeedErrorState = {shouldShowRBR: false, isFeedConnectionBroken: false, shouldPromptBrokenConnection: false, hasFeedErrors: false, hasWorkspaceErrors: false}; + const defaultState: CardFeedErrorState = { + shouldShowRBR: false, + isFeedConnectionBroken: false, + shouldPromptBrokenConnection: false, + hasFeedErrors: false, + hasWorkspaceErrors: false, + hasFeedConnectionIssue: false, + }; return { cardFeedErrors: {}, cardsWithBrokenFeedConnection: {}, diff --git a/tests/unit/components/Tables/WorkspaceCompanyCardsTable/getShouldShowBrokenConnectionErrorTest.ts b/tests/unit/components/Tables/WorkspaceCompanyCardsTable/getShouldShowBrokenConnectionErrorTest.ts index 7a82f1cf0bf0..cc4cc5171826 100644 --- a/tests/unit/components/Tables/WorkspaceCompanyCardsTable/getShouldShowBrokenConnectionErrorTest.ts +++ b/tests/unit/components/Tables/WorkspaceCompanyCardsTable/getShouldShowBrokenConnectionErrorTest.ts @@ -17,6 +17,7 @@ function buildFeedErrors(overrides: Partial): CardFeedErrorS hasWorkspaceErrors: false, isFeedConnectionBroken: false, shouldPromptBrokenConnection: false, + hasFeedConnectionIssue: false, ...overrides, }; } @@ -46,6 +47,20 @@ describe('getShouldShowBrokenConnectionError', () => { expect(getShouldShowBrokenConnectionError(CSV_FEED, feedErrors)).toBe(false); }); + // A 434 card is left out of `isFeedConnectionBroken`, but the wallet still sends its holder here to fix it, so + // the page has to offer the fix. + it('shows the error for a direct feed whose only issue is an actionable scrape status', () => { + const feedErrors = buildFeedErrors({hasFeedConnectionIssue: true}); + + expect(getShouldShowBrokenConnectionError(DIRECT_FEED, feedErrors)).toBe(true); + }); + + it('does not show the error for a commercial feed whose only issue is an actionable scrape status', () => { + const feedErrors = buildFeedErrors({hasFeedConnectionIssue: true}); + + expect(getShouldShowBrokenConnectionError(COMMERCIAL_FEED, feedErrors)).toBe(false); + }); + it('does not show the error for a direct feed with no broken connection and no feed errors', () => { const feedErrors = buildFeedErrors({}); diff --git a/tests/unit/hooks/useBrokenDirectCompanyCardFeedsForAdmin.test.ts b/tests/unit/hooks/useBrokenDirectCompanyCardFeedsForAdmin.test.ts index 98118d3a6aed..2cb3416688dc 100644 --- a/tests/unit/hooks/useBrokenDirectCompanyCardFeedsForAdmin.test.ts +++ b/tests/unit/hooks/useBrokenDirectCompanyCardFeedsForAdmin.test.ts @@ -24,6 +24,7 @@ const DEFAULT_CARD_FEED_ERROR_STATE = { hasWorkspaceErrors: false, isFeedConnectionBroken: false, shouldPromptBrokenConnection: false, + hasFeedConnectionIssue: false, }; function createDefaultCardFeedErrors(): CardFeedErrors { From ecab18f5109ebcddd906957d49dcdc7cb776f819 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Mon, 14 Sep 2026 16:43:42 +0430 Subject: [PATCH 16/24] Exclude cards with a connection issue --- src/libs/CardUtils.ts | 6 ++++-- tests/unit/CardUtilsTest.ts | 8 ++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index 226c07a712e4..693b98fd54b6 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -2068,7 +2068,9 @@ function getDisplayableExpensifyCards(cardList: CardList | undefined): Card[] { /** * Active, non-Expensify, non-cash cards (employer feed or personal Plaid) that are not flagged - * as broken at the card- or feed-level, sorted by cardID ascending. + * as broken at the card- or feed-level, sorted by cardID ascending. The card-level check is + * `hasCardConnectionIssue` so that a card the wallet reports as Inactive is not counted as + * spendable here, which also covers the scrape statuses the broken check ignores (e.g. 434). * * No `domainName` dedupe: third-party cards don't share the Expensify "one domain ⇒ one * physical+virtual pair" invariant, so deduping would silently collapse distinct cards. @@ -2088,7 +2090,7 @@ function getDisplayableThirdPartyCards(cardList: CardList | undefined, cardFeedE !isExpensifyCard(card) && (!!card.domainName || isPersonalCard(card)) && card.cardName !== CONST.COMPANY_CARDS.CARD_NAME.CASH && - !isCardConnectionBroken(card) && + !hasCardConnectionIssue(card) && !cardsWithBrokenFeedConnection[card.cardID] && !personalCardsWithBrokenConnection[card.cardID], ); diff --git a/tests/unit/CardUtilsTest.ts b/tests/unit/CardUtilsTest.ts index 4cc201ae4bfb..6ad401dcb0e4 100644 --- a/tests/unit/CardUtilsTest.ts +++ b/tests/unit/CardUtilsTest.ts @@ -3185,6 +3185,14 @@ describe('CardUtils', () => { expect(getDisplayableThirdPartyCards(cardList, emptyCardFeedErrors)).toEqual([]); }); + // The wallet reports a 434 card as Inactive, so counting it as spendable here would contradict that. + it('excludes a card reporting an actionable scrape status the broken check ignores', () => { + const cardList = createMock({ + 51: makeCompanyCard({cardID: 51, lastScrapeResult: 434}), + }); + expect(getDisplayableThirdPartyCards(cardList, emptyCardFeedErrors)).toEqual([]); + }); + it('excludes a company card listed in cardFeedErrors.cardsWithBrokenFeedConnection', () => { const card = makeCompanyCard({cardID: 60}); const cardList = createMock({60: card}); From 04258112bc17d580d325c1b8dc07c11a2e591316 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Mon, 14 Sep 2026 16:50:27 +0430 Subject: [PATCH 17/24] Sync the card once on the fix page --- .../useFixPersonalCardConnection.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/pages/settings/Wallet/PersonalCards/FixPersonalCardConnectionPage/useFixPersonalCardConnection.ts b/src/pages/settings/Wallet/PersonalCards/FixPersonalCardConnectionPage/useFixPersonalCardConnection.ts index c0c554956398..dedf2779e9a8 100644 --- a/src/pages/settings/Wallet/PersonalCards/FixPersonalCardConnectionPage/useFixPersonalCardConnection.ts +++ b/src/pages/settings/Wallet/PersonalCards/FixPersonalCardConnectionPage/useFixPersonalCardConnection.ts @@ -13,7 +13,7 @@ import ROUTES from '@src/ROUTES'; import type {CompanyCardFeed} from '@src/types/onyx'; import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; -import {useEffect} from 'react'; +import {useEffect, useRef} from 'react'; function useFixPersonalCardConnection(cardID: string) { const {isOffline} = useNetwork(); @@ -27,18 +27,21 @@ function useFixPersonalCardConnection(cardID: string) { // Matches the wallet row and the card details page, so a card they offer a fix for takes the reconnect flow here // rather than the auto-sync path meant for cards with nothing to fix. const isCardBroken = card ? hasCardConnectionIssue(card) : false; + // The sync optimistically reports the card as synced, which changes `card` and re-runs the effect before it can + // navigate away. A second run would send the optimistic result as the card's real one, so it only ever runs once. + const hasSyncedRef = useRef(false); useEffect(() => { if (isLoadingOnyxValue(cardListMetadata)) { return; } - // The Plaid flow drives its own SyncCard from onSuccess, so skip the auto-sync here - // to avoid a duplicate call when our optimistic update flips isCardBroken before unmount. + // The Plaid flow drives its own SyncCard from onSuccess, so skip the auto-sync here. // A broken card is only kept on this page when there is a bank connection to send it to. Without one the page // has nothing to offer, so it falls through to the sync below rather than stranding the user here. - if (!card || isPlaid || (isCardBroken && !!url)) { + if (!card || isPlaid || (isCardBroken && !!url) || hasSyncedRef.current) { return; } + hasSyncedRef.current = true; updatePersonalCardConnection(card.cardID.toString(), card.lastScrapeResult); Navigation.goBack(ROUTES.SETTINGS_WALLET_PERSONAL_CARD_DETAILS.getRoute(cardID)); }, [isCardBroken, card, cardID, cardListMetadata, isPlaid, url]); From a2db189405015b3d50f59905f9a9321c752c35d7 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Wed, 16 Sep 2026 11:59:15 +0430 Subject: [PATCH 18/24] Replace the backend error with the connection message --- src/libs/CardUtils.ts | 24 ------------ src/libs/actions/PaymentMethods.ts | 7 ++-- .../settings/Wallet/PaymentMethodList.tsx | 28 +++++--------- tests/unit/CardUtilsTest.ts | 38 ------------------- tests/unit/useAccountIndicatorChecksTest.ts | 11 +++--- 5 files changed, 19 insertions(+), 89 deletions(-) diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index 314b97bc121b..6f7c391613fd 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -41,7 +41,6 @@ import type { NonConnectableBankName, } from '@src/types/onyx/CardFeeds'; import type {CardFeedErrors} from '@src/types/onyx/DerivedValues'; -import type {Errors} from '@src/types/onyx/OnyxCommon'; import type {SelectedTimezone} from '@src/types/onyx/PersonalDetails'; import type {Connections} from '@src/types/onyx/Policy'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; @@ -1530,27 +1529,6 @@ function parseCardLastScrape(card: Card): Date | undefined { return Number.isNaN(lastScrapeDate.getTime()) ? undefined : lastScrapeDate; } -/** - * The card's errors that came from an action the user took, rather than from the connection itself. The two are told - * apart by how they are keyed: the server names its connection error `connectionError`, while a user action records - * its error under a microsecond timestamp. Keying on the shape rather than on the age matters because `lastScrape` is - * the last successful sync, which a broken card never advances, so every error on such a card looks recent. - * - * @param card the card to read - * @returns the errors a user action recorded - */ -function getCardActionErrors(card: Card): Errors { - return Object.fromEntries(Object.entries(card.errors ?? {}).filter(([errorKey]) => !Number.isNaN(Number(errorKey)))); -} - -/** - * @param card the card to check - * @returns true if an action the user took left an error on the card, false otherwise - */ -function hasCardActionErrors(card: Card): boolean { - return !isEmptyObject(getCardActionErrors(card)); -} - /** * Check whether a card's last successful sync is at least the dismiss threshold (90 days) old. * @@ -2312,8 +2290,6 @@ export { isCardHiddenFromSearch, getCSVFeedType, getFeedType, - getCardActionErrors, - hasCardActionErrors, isCardConnectionBroken, hasCardConnectionIssue, doesCardConnectionNeedReauthentication, diff --git a/src/libs/actions/PaymentMethods.ts b/src/libs/actions/PaymentMethods.ts index a466364bacc1..afd9f7a7f929 100644 --- a/src/libs/actions/PaymentMethods.ts +++ b/src/libs/actions/PaymentMethods.ts @@ -439,10 +439,9 @@ function hasPaymentMethodError( // A card's connection error is surfaced as a card error too, so once the card has gone without a successful // sync past the grace period we stop leading the user to it and it must no longer light the RBR. The threshold // is keyed on the last successful sync rather than `isCardConnectionBroken` because the server sets the - // connection error even for scrape statuses that check treats as ignored (e.g. 434). An error left behind by - // something the user did is a separate problem from the connection, so it still has to light the RBR. - const isStaleConnectionErrorOnly = CardUtils.isLastScrapePastDismissThreshold(card) && !CardUtils.hasCardActionErrors(card); - if (isStaleConnectionErrorOnly) { + // connection error even for scrape statuses that check treats as ignored (e.g. 434). The threshold covers every + // error the card carries, because nothing tells that one apart from an error a user action left behind. + if (CardUtils.isLastScrapePastDismissThreshold(card)) { return false; } if (CardUtils.isPersonalCard(card)) { diff --git a/src/pages/settings/Wallet/PaymentMethodList.tsx b/src/pages/settings/Wallet/PaymentMethodList.tsx index 0a52389d5e21..06583067eb19 100644 --- a/src/pages/settings/Wallet/PaymentMethodList.tsx +++ b/src/pages/settings/Wallet/PaymentMethodList.tsx @@ -20,7 +20,6 @@ import { getCardConnectionStatusDisplay, getCardFeedIcon, getCardFeedWithDomainID, - getCardActionErrors, getCompanyCardFeedWithDomainIDForCard, getPlaidInstitutionIconUrl, hasCardConnectionIssue, @@ -326,14 +325,12 @@ function PaymentMethodList({ doesCardNeedReauthentication: doesCardConnectionNeedReauthentication(card), policyID: policyIDForCard, }); - // An action the user just took that failed is what the row has to say, so its error replaces our - // connection copy rather than stacking with it. The server's own connection error is left out either - // way: the connection message says the same thing in copy we control, with a way to fix it. - const cardErrors = card.pendingAction ? card.errors : getCardActionErrors(card); + // The connection message is the row's one line about a card we cannot import from, so it stands in for + // every error the card carries. The server's own connection error says the same thing in words we do + // not control and without a way to fix it, and nothing tells it apart from an error a user action left + // behind, so both wait until the connection is working again. + const cardErrors = cardConnectionStatusDisplay?.messageKey ? undefined : card.errors; const shouldShowCardErrorMessages = !isEmptyObject(cardErrors); - // A personal card row renders no card error of its own, so letting one replace the connection message - // there would leave the row with a status and nothing to explain it. - const doesCardErrorReplaceConnectionMessage = !isUserPersonalCard && shouldShowCardErrorMessages; const shouldShowCardLastSync = shouldShowConnectionStatus && !isUserExpensifyCard && !isCSVCard; let cardLastSyncText: string | undefined; if (shouldShowCardLastSync) { @@ -347,11 +344,7 @@ function PaymentMethodList({ if (cardConnectionStatusDisplay) { const companyCardsRoute = policyIDForCard ? ROUTES.WORKSPACE_COMPANY_CARDS.getRoute(policyIDForCard) : undefined; let cardConnectionMessage: string | undefined; - // The row carries one message at a time, and a failed action wins it, since that is what the user - // just did. The badge still reads Inactive, so the connection is not misreported meanwhile. - if (doesCardErrorReplaceConnectionMessage) { - cardConnectionMessage = undefined; - } else if (cardConnectionStatusDisplay.shouldUseCompanyCardsLink && companyCardsRoute) { + if (cardConnectionStatusDisplay.shouldUseCompanyCardsLink && companyCardsRoute) { cardConnectionMessage = translate('walletPage.cardStatus.fixConnectionIn', `${environmentURL}/${companyCardsRoute}`); } else if (cardConnectionStatusDisplay.shouldUseReauthMessage) { cardConnectionMessage = translate('walletPage.cardStatus.reconnectBank'); @@ -365,11 +358,10 @@ function PaymentMethodList({ statusText: translate(cardConnectionStatusDisplay.statusKey), statusTone: cardConnectionStatusDisplay.statusTone, message: cardConnectionMessage, - actionText: cardConnectionMessage && cardConnectionStatusDisplay.actionKey ? translate(cardConnectionStatusDisplay.actionKey) : undefined, - onActionPress: - cardConnectionMessage && cardConnectionStatusDisplay.shouldUsePersonalCardFix - ? () => Navigation.navigate(ROUTES.SETTINGS_WALLET_PERSONAL_CARD_FIX_CONNECTION.getRoute(String(card.cardID))) - : undefined, + actionText: cardConnectionStatusDisplay.actionKey ? translate(cardConnectionStatusDisplay.actionKey) : undefined, + onActionPress: cardConnectionStatusDisplay.shouldUsePersonalCardFix + ? () => Navigation.navigate(ROUTES.SETTINGS_WALLET_PERSONAL_CARD_FIX_CONNECTION.getRoute(String(card.cardID))) + : undefined, onLinkPress: cardConnectionStatusDisplay.shouldUseCompanyCardsLink && companyCardsRoute ? () => { diff --git a/tests/unit/CardUtilsTest.ts b/tests/unit/CardUtilsTest.ts index 28543f44a71b..def6c89ff921 100644 --- a/tests/unit/CardUtilsTest.ts +++ b/tests/unit/CardUtilsTest.ts @@ -59,9 +59,7 @@ import { getWalletProviderNameKey, getYearFromExpirationDateString, hasAssignedCardMatching, - getCardActionErrors, hasCardConnectionIssue, - hasCardActionErrors, hasIssuedExpensifyCard, hasOnlyOneCardToAssign, isBrokenConnectionPastDismissThreshold, @@ -4486,42 +4484,6 @@ describe('CardUtils', () => { }); }); - describe('getCardActionErrors', () => { - it('returns nothing when the card has no errors', () => { - const card: Card = {...createRandomCard(1), errors: undefined}; - expect(hasCardActionErrors(card)).toBe(false); - }); - - // The server names its connection error, so the row shows our own connection copy for it instead. - it('leaves out the server connection error', () => { - const card: Card = {...createRandomCard(1), errors: {connectionError: 'Your card connection is broken.'}}; - expect(getCardActionErrors(card)).toEqual({}); - }); - - // A user action records its error under a microsecond timestamp, and that is the message the row has to carry. - it('keeps an error a user action recorded', () => { - const recordedAt = Date.now() * 1000; - const card: Card = {...createRandomCard(1), errors: {[recordedAt]: 'Failed to unassign this card'}}; - expect(getCardActionErrors(card)).toEqual({[recordedAt]: 'Failed to unassign this card'}); - }); - - // Both at once: the action error is kept and the connection error is left to the connection message. - it('keeps only the user action error when the card carries both', () => { - const recordedAt = Date.now() * 1000; - const card: Card = {...createRandomCard(1), errors: {connectionError: 'Your card connection is broken.', [recordedAt]: 'Failed to unassign this card'}}; - expect(getCardActionErrors(card)).toEqual({[recordedAt]: 'Failed to unassign this card'}); - }); - - // A broken card never advances `lastScrape`, so the age of an error says nothing about which kind it is. - it('keeps a user action error however old it is and whether or not the card ever synced', () => { - const longAgo = Date.parse('2024-01-05T11:00:00Z') * 1000; - const neverSynced: Card = {...createRandomCard(1), lastScrape: undefined, errors: {[longAgo]: 'Failed to remove this card'}}; - const syncedSince: Card = {...createRandomCard(2), lastScrape: '2025-10-05 11:00:00', errors: {[longAgo]: 'Failed to remove this card'}}; - expect(hasCardActionErrors(neverSynced)).toBe(true); - expect(hasCardActionErrors(syncedSince)).toBe(true); - }); - }); - describe('isLastScrapePastDismissThreshold', () => { afterEach(() => { jest.restoreAllMocks(); diff --git a/tests/unit/useAccountIndicatorChecksTest.ts b/tests/unit/useAccountIndicatorChecksTest.ts index 15104a50f2d6..61b0033fcd17 100644 --- a/tests/unit/useAccountIndicatorChecksTest.ts +++ b/tests/unit/useAccountIndicatorChecksTest.ts @@ -384,8 +384,9 @@ describe('useAccountIndicatorChecks', () => { expect(result.current.accountStatus).not.toBe(CONST.INDICATOR_STATUS.HAS_PAYMENT_METHOD_ERROR); }); - // A failed action writes a fresh error long after the last sync, and it still has to lead the user to it. - it('surfaces a personal card error recorded after the grace period has passed', async () => { + // Past the grace period the wallet row shows only the connection message, so lighting the Account button + // would lead the user to a row with no error on it. + it('does not surface a personal card error recorded after the grace period has passed', async () => { await act(async () => { await Onyx.multiSet( createMock({ @@ -413,10 +414,10 @@ describe('useAccountIndicatorChecks', () => { const {result} = renderHook(() => useAccountIndicatorChecks()); await waitForBatchedUpdatesWithAct(); - expect(result.current.accountStatus).toBe(CONST.INDICATOR_STATUS.HAS_PAYMENT_METHOD_ERROR); + expect(result.current.accountStatus).not.toBe(CONST.INDICATOR_STATUS.HAS_PAYMENT_METHOD_ERROR); }); - it('surfaces a company card error recorded after the grace period has passed', async () => { + it('does not surface a company card error recorded after the grace period has passed', async () => { await act(async () => { await Onyx.multiSet( createMock({ @@ -451,7 +452,7 @@ describe('useAccountIndicatorChecks', () => { const {result} = renderHook(() => useAccountIndicatorChecks()); await waitForBatchedUpdatesWithAct(); - expect(result.current.accountStatus).toBe(CONST.INDICATOR_STATUS.HAS_PAYMENT_METHOD_ERROR); + expect(result.current.accountStatus).not.toBe(CONST.INDICATOR_STATUS.HAS_PAYMENT_METHOD_ERROR); }); it('still surfaces a company card broken connection on the Account button within the grace period', async () => { From 71f41442d213e1afb0c4fe638669e05a491d7e2a Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Sat, 19 Sep 2026 10:19:21 +0430 Subject: [PATCH 19/24] Remove unused card util imports --- src/pages/settings/Wallet/PaymentMethodList.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/pages/settings/Wallet/PaymentMethodList.tsx b/src/pages/settings/Wallet/PaymentMethodList.tsx index 5fc4f726a8e8..338949ef3308 100644 --- a/src/pages/settings/Wallet/PaymentMethodList.tsx +++ b/src/pages/settings/Wallet/PaymentMethodList.tsx @@ -24,14 +24,12 @@ import { getPlaidInstitutionIconUrl, hasCardConnectionIssue, isActionableVirtualExpensifyCard, - isCardConnectionBroken, doesCardConnectionNeedReauthentication, isCardFrozen, isCardInactive, isExpensifyCard, isExpensifyCardPendingAction, isExpiredCard, - isLastScrapePastDismissThreshold, isPersonalCard, isTravelCard, lastFourNumbersFromCardName, From c0d905787fcde9b8a1491244bc03921892aeaa04 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Tue, 22 Sep 2026 11:27:58 +0430 Subject: [PATCH 20/24] Resolve card workspace by fundID, not domain --- src/libs/PolicyUtils.ts | 20 ++++++++++ .../settings/Wallet/PaymentMethodList.tsx | 20 ++++------ src/selectors/Policy.ts | 20 +++++++--- tests/unit/PolicyUtilsTest.ts | 38 +++++++++++++++++++ 4 files changed, 80 insertions(+), 18 deletions(-) diff --git a/src/libs/PolicyUtils.ts b/src/libs/PolicyUtils.ts index 7b7a31179931..a6058341043a 100644 --- a/src/libs/PolicyUtils.ts +++ b/src/libs/PolicyUtils.ts @@ -8,6 +8,7 @@ import ROUTES from '@src/ROUTES'; import INPUT_IDS from '@src/types/form/NetSuiteCustomFieldForm'; import type {PolicyType} from '@src/types/form/WorkspaceConfirmationForm'; import type { + Card, OnyxInputOrEntry, PersonalDetailsList, Policy, @@ -3437,6 +3438,24 @@ function getMostFrequentEmailDomain(acceptedDomains: string[], policy?: Policy) const getPolicyIDFromDomainName = (domainName: string): string | undefined => domainName.match(CONST.REGEX.EXPENSIFY_POLICY_DOMAIN_NAME)?.[1]?.toUpperCase(); +/** + * Returns the workspace an assigned card belongs to. + * + * A card names its workspace with `fundID`, which is the policy's `policyAccountID`. That holds whatever the feed's + * domain looks like, so a card on a company's own domain resolves the same workspace as one on a workspace feed's + * `expensify-policy.exfy` domain. The domain is read only as a fallback, for a card that arrives without a `fundID`. + */ +const getPolicyForAssignedCard = (card: OnyxEntry>, policies: OnyxCollection): OnyxEntry => { + const workspaceAccountID = Number(card?.fundID); + const policyForFund = workspaceAccountID ? Object.values(policies ?? {}).find((policy) => policy?.policyAccountID === workspaceAccountID) : undefined; + if (policyForFund) { + return policyForFund; + } + + const policyID = card?.domainName ? getPolicyIDFromDomainName(card.domainName) : undefined; + return policyID ? policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`] : undefined; +}; + const getDescriptionForPolicyDomainCard = (domainName: string, policies: OnyxCollection): string => { // A domain name containing a policyID indicates that this is a workspace feed const policyID = getPolicyIDFromDomainName(domainName); @@ -3784,6 +3803,7 @@ export { getAdminsPrivateEmailDomains, getMostFrequentEmailDomain, getPolicyIDFromDomainName, + getPolicyForAssignedCard, getDescriptionForPolicyDomainCard, getManagerAccountID, isPreferredExporter, diff --git a/src/pages/settings/Wallet/PaymentMethodList.tsx b/src/pages/settings/Wallet/PaymentMethodList.tsx index 338949ef3308..540bcfbfdfac 100644 --- a/src/pages/settings/Wallet/PaymentMethodList.tsx +++ b/src/pages/settings/Wallet/PaymentMethodList.tsx @@ -39,7 +39,7 @@ import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/crea import Navigation from '@libs/Navigation/Navigation'; import {formatPaymentMethods} from '@libs/PaymentUtils'; import {areAddressAndPersonalDetailsMissing} from '@libs/PersonalDetailsUtils'; -import {getDescriptionForPolicyDomainCard, getPolicyIDFromDomainName, isPolicyAdmin} from '@libs/PolicyUtils'; +import {getDescriptionForPolicyDomainCard, getPolicyForAssignedCard, isPolicyAdmin} from '@libs/PolicyUtils'; import {getTravelBillingCard, isTravelCVVEligible} from '@libs/TravelBillingUtils'; import colors from '@styles/theme/colors'; @@ -62,7 +62,7 @@ import type {OnyxCollection} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; import {isActingAsDelegateSelector, isUserValidatedSelector} from '@selectors/Account'; -import {createPoliciesForDomainCardsSelector} from '@selectors/Policy'; +import {createPoliciesForAssignedCardsSelector} from '@selectors/Policy'; import {FlashList} from '@shopify/flash-list'; import lodashSortBy from 'lodash/sortBy'; import React from 'react'; @@ -208,14 +208,10 @@ function PaymentMethodList({ const isLoadingBankAccountList = isLoadingOnyxValue(bankAccountListResult); const [cardList = getEmptyObject(), cardListResult] = useOnyx(ONYXKEYS.CARD_LIST); const isLoadingCardList = isLoadingOnyxValue(cardListResult); - const cardDomains = shouldShowAssignedCards - ? Object.values(isLoadingCardList ? {} : (cardList ?? {})) - .filter((card) => !!card.domainName) - .map((card) => card.domainName) - : []; - const policiesForDomainCardsSelectorFactory = createPoliciesForDomainCardsSelector(cardDomains); + const cardsForPolicyLookup = shouldShowAssignedCards ? Object.values(isLoadingCardList ? {} : (cardList ?? {})).filter((card) => !!card.domainName || !!card.fundID) : []; + const policiesForAssignedCardsSelectorFactory = createPoliciesForAssignedCardsSelector(cardsForPolicyLookup); const [policiesForAssignedCards] = useOnyx(ONYXKEYS.COLLECTION.POLICY, { - selector: (policies: OnyxCollection) => policiesForDomainCardsSelectorFactory(policies), + selector: (policies: OnyxCollection) => policiesForAssignedCardsSelectorFactory(policies), }); // Temporarily disabled because P2P debit cards are disabled. // const [fundList = getEmptyObject()] = useOnyx(ONYXKEYS.FUND_LIST); @@ -269,9 +265,9 @@ function PaymentMethodList({ const isUserPersonalCard = isPersonalCard(card); const isCSVCard = card.bank === CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD || card.bank.includes(CONST.COMPANY_CARD.FEED_BANK_NAME.CSV); const assignedCardsGrouped = isUserPersonalCard ? personalCardsGrouped : companyCardsGrouped; - const policyIDForCard = shouldShowConnectionStatus && card.domainName ? getPolicyIDFromDomainName(card.domainName) : undefined; - const policyForCard = policyIDForCard ? policiesForAssignedCards?.[`${ONYXKEYS.COLLECTION.POLICY}${policyIDForCard}`] : undefined; - const isAdminForCardPolicy = shouldShowConnectionStatus ? isPolicyAdmin(policyForCard) : false; + const policyForCard = shouldShowConnectionStatus ? getPolicyForAssignedCard(card, policiesForAssignedCards) : undefined; + const policyIDForCard = policyForCard?.id; + const isAdminForCardPolicy = isPolicyAdmin(policyForCard); let icon; if (isUserPersonalCard && isCSVCard) { diff --git a/src/selectors/Policy.ts b/src/selectors/Policy.ts index 73486b637f71..ebf099ca9c24 100644 --- a/src/selectors/Policy.ts +++ b/src/selectors/Policy.ts @@ -24,7 +24,7 @@ import {getDefaultAvatarURL} from '@libs/UserAvatarUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Policy, PolicyConnectionSyncProgress, PolicyReportField} from '@src/types/onyx'; +import type {Card, Policy, PolicyConnectionSyncProgress, PolicyReportField} from '@src/types/onyx'; import type {PolicyConnectionName, PolicyDetailsForNonMembers} from '@src/types/onyx/Policy'; import ObjectUtils from '@src/types/utils/ObjectUtils'; @@ -262,16 +262,24 @@ const createAllPolicyReportFieldsSelector = (policies: OnyxCollection, l return Object.fromEntries(nonFormulaReportFields); }; -const createPoliciesForDomainCardsSelector = (domainNames: string[]) => { - const policyIDs = new Set(domainNames.map(getPolicyIDFromDomainName).filter((policyID): policyID is string => !!policyID)); +/** + * Creates a selector returning only the policies the given cards belong to. + * + * Cards are matched on `fundID`, which is the workspace's `policyAccountID`, so a card on a company's own domain + * finds its workspace just like one on an `expensify-policy.exfy` domain does. Domains are still read as well, + * to keep a card that arrives without a `fundID` resolving as it did before. + */ +const createPoliciesForAssignedCardsSelector = (cards: Array>) => { + const workspaceAccountIDs = new Set(cards.map((card) => Number(card.fundID)).filter((workspaceAccountID) => !!workspaceAccountID)); + const policyIDs = new Set(cards.map((card) => (card.domainName ? getPolicyIDFromDomainName(card.domainName) : undefined)).filter((policyID): policyID is string => !!policyID)); return (policies: OnyxCollection) => { - if (policyIDs.size === 0) { + if (workspaceAccountIDs.size === 0 && policyIDs.size === 0) { return {}; } return Object.entries(policies ?? {}).reduce>>((acc, [key, policy]) => { - if (policy?.id && policyIDs.has(policy.id.toUpperCase())) { + if ((!!policy?.policyAccountID && workspaceAccountIDs.has(policy.policyAccountID)) || (!!policy?.id && policyIDs.has(policy.id.toUpperCase()))) { acc[key] = policy; } return acc; @@ -559,7 +567,7 @@ export { createHasAdminPolicyWithXeroConnectionSelector, createTimeSensitiveAdminPoliciesSelector, createHasWorkspaceToSubmitToSelector, - createPoliciesForDomainCardsSelector, + createPoliciesForAssignedCardsSelector, createPoliciesByIDsSelector, policyTimeTrackingSelector, createIOURequestStartPoliciesSelector, diff --git a/tests/unit/PolicyUtilsTest.ts b/tests/unit/PolicyUtilsTest.ts index e0cbe2883c1d..fe0cc71ee027 100644 --- a/tests/unit/PolicyUtilsTest.ts +++ b/tests/unit/PolicyUtilsTest.ts @@ -43,6 +43,7 @@ import { getPolicyApproverLogins, getPolicyBrickRoadIndicatorStatus, getPolicyByCustomUnitID, + getPolicyForAssignedCard, getPolicyIDFromDomainName, getRateDisplayValue, getOwnerChangePayerSuccessData, @@ -5796,6 +5797,43 @@ describe('getPolicyIDFromDomainName', () => { }); }); +describe('getPolicyForAssignedCard', () => { + const policy: Policy = {...createRandomPolicy(0), id: 'A1B2C3', policyAccountID: 88801}; + const policies = {[`${ONYXKEYS.COLLECTION.POLICY}A1B2C3`]: policy}; + + // The workspace is what decides whether the cardholder is shown the fix link or told to ask an admin, so a card + // has to find it whatever the company named their domain. + it('finds the workspace for a card on a domain that is not a workspace feed', () => { + const card = {domainName: 'acme-corp.com', fundID: '88801'}; + + expect(getPolicyForAssignedCard(card, policies)).toEqual(policy); + }); + + it('finds the workspace for a card on a workspace-feed domain', () => { + const card = {domainName: 'expensify-policyA1B2C3.exfy', fundID: '88801'}; + + expect(getPolicyForAssignedCard(card, policies)).toEqual(policy); + }); + + it('falls back to the domain name for a card that has no fundID', () => { + const card = {domainName: 'expensify-policyA1B2C3.exfy'}; + + expect(getPolicyForAssignedCard(card, policies)).toEqual(policy); + }); + + it('returns undefined when no workspace matches the card', () => { + const card = {domainName: 'acme-corp.com', fundID: '99999'}; + + expect(getPolicyForAssignedCard(card, policies)).toBeUndefined(); + }); + + it('returns undefined when there are no policies', () => { + const card = {domainName: 'acme-corp.com', fundID: '88801'}; + + expect(getPolicyForAssignedCard(card, {})).toBeUndefined(); + }); +}); + describe('getDefaultWorkspacePlanType', () => { const submitPolicy = {...createRandomPolicy(1, CONST.POLICY.TYPE.SUBMIT), id: 'submit1'}; const teamPolicy = {...createRandomPolicy(2, CONST.POLICY.TYPE.TEAM), id: 'team1'}; From edf5af3f845c7c691ada4e1d144c8a6681d24c36 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Thu, 24 Sep 2026 09:35:47 +0430 Subject: [PATCH 21/24] Resolve a card's workspace from its feed --- src/libs/CardFeedUtils.ts | 81 +++++++++++++- .../settings/Wallet/PaymentMethodList.tsx | 15 ++- src/selectors/Policy.ts | 12 ++- tests/unit/CardFeedUtilsTest.ts | 100 +++++++++++++++++- 4 files changed, 195 insertions(+), 13 deletions(-) diff --git a/src/libs/CardFeedUtils.ts b/src/libs/CardFeedUtils.ts index fd0dfaebb53e..19d867ded544 100644 --- a/src/libs/CardFeedUtils.ts +++ b/src/libs/CardFeedUtils.ts @@ -9,7 +9,7 @@ import CONST from '@src/CONST'; import type {CombinedCardFeeds} from '@src/hooks/useCardFeeds'; import ONYXKEYS from '@src/ONYXKEYS'; import type {Card, CardFeeds, CardList, Domain, ExpensifyCardSettings, PersonalDetailsList, Policy, WorkspaceCardsList} from '@src/types/onyx'; -import type {CardFeedData, CardFeedsStatus, CardFeedsStatusByDomainID, CardFeedWithDomainID, CardFeedWithNumber, CombinedCardFeed} from '@src/types/onyx/CardFeeds'; +import type {CardFeedData, CardFeedsStatus, CardFeedsStatusByDomainID, CardFeedWithDomainID, CardFeedWithNumber, CombinedCardFeed, CustomCardFeedData} from '@src/types/onyx/CardFeeds'; import type {PendingAction} from '@src/types/onyx/OnyxCommon'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; @@ -26,6 +26,7 @@ import { feedHasCards, getCardFeedIcon, getCardFeedWithDomainID, + getCompanyCardFeed, getCustomOrFormattedFeedName, getDomainByFundID, getOriginalCompanyFeeds, @@ -39,7 +40,10 @@ import { isPersonalCard, } from './CardUtils'; import {getExpensifyCardFeedDescription} from './ExpensifyCardFeedSelectorUtils'; -import {isPolicyAdmin} from './PolicyUtils'; +import {getPolicyForAssignedCard, isPolicyAdmin} from './PolicyUtils'; + +/** The fields of an assigned card needed to resolve the workspace behind its feed */ +type AssignedCardForFeedAccess = Pick; type CardFilterItem = Partial & AdditionalCardProps & {isCardFeed?: boolean; correspondingCards?: string[]; cardFeedKey: string; plaidUrl?: string; keyForList: string}; type CardFeedForDisplay = { @@ -267,6 +271,77 @@ function getCardFeedsForDisplay( return cardFeedsForDisplay; } +/** + * The settings of the company card feed an assigned card belongs to. + * + * A direct feed keeps its credentials in `oAuthAccountDetails` but its settings, including the workspaces it is + * linked to, alongside a custom feed's in `companyCards`. The card's `bank` can carry the `#domainID` suffix, + * which is not part of the settings key. + */ +function getFeedSettingsForCard(card: AssignedCardForFeedAccess, allCardFeeds: OnyxCollection): CustomCardFeedData | undefined { + if (!card.fundID) { + return undefined; + } + + return allCardFeeds?.[`${ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER}${card.fundID}`]?.settings?.companyCards?.[getCompanyCardFeed(card.bank)]; +} + +/** + * The workspaces the given cards' feeds name, so a consumer can make sure those policies are loaded before it + * resolves a card to its workspace. A feed names them with `linkedPolicyIDs`, or with a single `preferredPolicy`. + */ +function getPolicyIDsNamedByCardFeeds(cards: AssignedCardForFeedAccess[], allCardFeeds: OnyxCollection): string[] { + const policyIDs = new Set(); + + for (const card of cards) { + const feedSettings = getFeedSettingsForCard(card, allCardFeeds); + for (const linkedPolicyID of feedSettings?.linkedPolicyIDs ?? []) { + if (linkedPolicyID) { + policyIDs.add(linkedPolicyID); + } + } + if (feedSettings?.preferredPolicy) { + policyIDs.add(feedSettings.preferredPolicy); + } + } + + return [...policyIDs]; +} + +/** + * The workspace an assigned company card sends its holder to, and whether they are allowed to fix its feed. + * + * The wallet offers a link to the Company cards page, so it has to agree with what that page already shows. The + * workspace comes from the feed's own `linkedPolicyIDs`, then its `preferredPolicy`, and only a feed naming neither + * falls back to the fund, as in `getCardFeedsForDisplayPerPolicy`. A domain feed's `fundID` is the domain's account + * ID rather than a workspace's, so that fallback cannot find the workspace for one on its own. Fixing a feed is a + * domain permission as well as a workspace one, so a domain admin is offered the link too, as in + * `getVisibleCompanyCardFeedsForSelector`. + */ +function getAssignedCardFeedAccess( + card: AssignedCardForFeedAccess, + allCardFeeds: OnyxCollection, + policies: OnyxCollection, + domains: OnyxCollection, + currentUserAccountID: number | undefined, +): {policyID: string | undefined; isAdmin: boolean} { + const fundID = Number(card.fundID); + if (!fundID) { + return {policyID: undefined, isAdmin: false}; + } + + const feedSettings = getFeedSettingsForCard(card, allCardFeeds); + const linkedPolicyIDs = feedSettings?.linkedPolicyIDs?.filter(Boolean) ?? []; + const namedPolicyIDs = linkedPolicyIDs.length ? linkedPolicyIDs : [feedSettings?.preferredPolicy].filter((policyID): policyID is string => !!policyID); + const namedPolicies = namedPolicyIDs.map((policyID) => policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`]).filter((policy) => !!policy); + + // A feed can name more than one workspace. Prefer one the cardholder administers, so the link lands somewhere + // they can act rather than on a workspace that would only show them the same problem again. + const policyForCard = namedPolicies.find((policy) => isPolicyAdmin(policy)) ?? namedPolicies.at(0) ?? getPolicyForAssignedCard(card, policies); + + return {policyID: policyForCard?.id, isAdmin: isAdminSelector(currentUserAccountID)(getDomainByFundID(domains, fundID)) || isPolicyAdmin(policyForCard)}; +} + /** * Given a collection of card feeds, return formatted card feeds grouped per policy. * @@ -616,6 +691,8 @@ export { getCardFeedsForDisplay, getExpensifyCardFeedsForDisplay, getCardFeedsForDisplayPerPolicy, + getPolicyIDsNamedByCardFeeds, + getAssignedCardFeedAccess, getVisibleCompanyCardFeedsForSelector, getCombinedCardFeedsFromAllFeeds, getWorkspaceCardFeedsStatus, diff --git a/src/pages/settings/Wallet/PaymentMethodList.tsx b/src/pages/settings/Wallet/PaymentMethodList.tsx index fe5cd6bf804b..562875736523 100644 --- a/src/pages/settings/Wallet/PaymentMethodList.tsx +++ b/src/pages/settings/Wallet/PaymentMethodList.tsx @@ -5,6 +5,7 @@ import Text from '@components/Text'; import useCardFeedErrors from '@hooks/useCardFeedErrors'; import {useCompanyCardFeedIcons} from '@hooks/useCompanyCardIcons'; +import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useEnvironment from '@hooks/useEnvironment'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; @@ -15,6 +16,7 @@ import useThemeStyles from '@hooks/useThemeStyles'; import {getBankAccountConnectionStatus, getBankAccountState, isPersonalBankAccountMissingInfo} from '@libs/BankAccountUtils'; import type {BankAccountConnectionStatus} from '@libs/BankAccountUtils'; +import {getAssignedCardFeedAccess, getPolicyIDsNamedByCardFeeds} from '@libs/CardFeedUtils'; import { getAssignedCardSortKey, getCardConnectionStatusDisplay, @@ -40,7 +42,7 @@ import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/crea import Navigation from '@libs/Navigation/Navigation'; import {formatPaymentMethods} from '@libs/PaymentUtils'; import {areAddressAndPersonalDetailsMissing} from '@libs/PersonalDetailsUtils'; -import {getDescriptionForPolicyDomainCard, getPolicyForAssignedCard, isPolicyAdmin} from '@libs/PolicyUtils'; +import {getDescriptionForPolicyDomainCard} from '@libs/PolicyUtils'; import {getTravelBillingCard, isTravelCVVEligible} from '@libs/TravelBillingUtils'; import colors from '@styles/theme/colors'; @@ -209,8 +211,11 @@ function PaymentMethodList({ const isLoadingBankAccountList = isLoadingOnyxValue(bankAccountListResult); const [cardList = getEmptyObject(), cardListResult] = useOnyx(ONYXKEYS.CARD_LIST); const isLoadingCardList = isLoadingOnyxValue(cardListResult); + const {accountID: currentUserAccountID} = useCurrentUserPersonalDetails(); + const [allCardFeeds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER); + const [allDomains] = useOnyx(ONYXKEYS.COLLECTION.DOMAIN); const cardsForPolicyLookup = shouldShowAssignedCards ? Object.values(isLoadingCardList ? {} : (cardList ?? {})).filter((card) => !!card.domainName || !!card.fundID) : []; - const policiesForAssignedCardsSelectorFactory = createPoliciesForAssignedCardsSelector(cardsForPolicyLookup); + const policiesForAssignedCardsSelectorFactory = createPoliciesForAssignedCardsSelector(cardsForPolicyLookup, getPolicyIDsNamedByCardFeeds(cardsForPolicyLookup, allCardFeeds)); const [policiesForAssignedCards] = useOnyx(ONYXKEYS.COLLECTION.POLICY, { selector: (policies: OnyxCollection) => policiesForAssignedCardsSelectorFactory(policies), }); @@ -266,9 +271,9 @@ function PaymentMethodList({ const isUserPersonalCard = isPersonalCard(card); const isCSVCard = card.bank === CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD || card.bank.includes(CONST.COMPANY_CARD.FEED_BANK_NAME.CSV); const assignedCardsGrouped = isUserPersonalCard ? personalCardsGrouped : companyCardsGrouped; - const policyForCard = shouldShowConnectionStatus ? getPolicyForAssignedCard(card, policiesForAssignedCards) : undefined; - const policyIDForCard = policyForCard?.id; - const isAdminForCardPolicy = isPolicyAdmin(policyForCard); + const {policyID: policyIDForCard, isAdmin: isAdminForCardPolicy} = shouldShowConnectionStatus + ? getAssignedCardFeedAccess(card, allCardFeeds, policiesForAssignedCards, allDomains, currentUserAccountID) + : {policyID: undefined, isAdmin: false}; let icon; if (isUserPersonalCard && isCSVCard) { diff --git a/src/selectors/Policy.ts b/src/selectors/Policy.ts index ebf099ca9c24..293638b022b6 100644 --- a/src/selectors/Policy.ts +++ b/src/selectors/Policy.ts @@ -265,13 +265,15 @@ const createAllPolicyReportFieldsSelector = (policies: OnyxCollection, l /** * Creates a selector returning only the policies the given cards belong to. * - * Cards are matched on `fundID`, which is the workspace's `policyAccountID`, so a card on a company's own domain - * finds its workspace just like one on an `expensify-policy.exfy` domain does. Domains are still read as well, - * to keep a card that arrives without a `fundID` resolving as it did before. + * A card's feed is what names its workspace, so `namedPolicyIDs` carries what the feeds point at. The fund and the + * domain name are matched as well, for a feed that names no workspace of its own. */ -const createPoliciesForAssignedCardsSelector = (cards: Array>) => { +const createPoliciesForAssignedCardsSelector = (cards: Array>, namedPolicyIDs: string[] = []) => { const workspaceAccountIDs = new Set(cards.map((card) => Number(card.fundID)).filter((workspaceAccountID) => !!workspaceAccountID)); - const policyIDs = new Set(cards.map((card) => (card.domainName ? getPolicyIDFromDomainName(card.domainName) : undefined)).filter((policyID): policyID is string => !!policyID)); + const policyIDs = new Set([ + ...namedPolicyIDs.map((policyID) => policyID.toUpperCase()), + ...cards.map((card) => (card.domainName ? getPolicyIDFromDomainName(card.domainName) : undefined)).filter((policyID): policyID is string => !!policyID), + ]); return (policies: OnyxCollection) => { if (workspaceAccountIDs.size === 0 && policyIDs.size === 0) { diff --git a/tests/unit/CardFeedUtilsTest.ts b/tests/unit/CardFeedUtilsTest.ts index d0f0e5c3eff1..0f77deab9292 100644 --- a/tests/unit/CardFeedUtilsTest.ts +++ b/tests/unit/CardFeedUtilsTest.ts @@ -1,4 +1,11 @@ -import {getCardFeedsForDisplay, getCardFeedsForDisplayPerPolicy, getExpensifyCardFeedsForDisplay, getFeedInfo, getVisibleCompanyCardFeedsForSelector} from '@libs/CardFeedUtils'; +import { + getAssignedCardFeedAccess, + getCardFeedsForDisplay, + getCardFeedsForDisplayPerPolicy, + getExpensifyCardFeedsForDisplay, + getFeedInfo, + getVisibleCompanyCardFeedsForSelector, +} from '@libs/CardFeedUtils'; import CONST from '@src/CONST'; import IntlStore from '@src/languages/IntlStore'; @@ -495,3 +502,94 @@ describe('getVisibleCompanyCardFeedsForSelector', () => { expect(result.at(0)?.linkedPolicyIDs).toEqual(['WS', 'WS2', 'WS3']); }); }); + +describe('getAssignedCardFeedAccess', () => { + const fundID = 1234; + const currentUserAccountID = 777; + const bank = cardFeedAmericaExpressMock; + const card = {bank, domainName: 'acme-corp.com', fundID: String(fundID)}; + + function createCompanyCardFeeds(companyCards: NonNullable['companyCards']>): OnyxCollection { + return { + [`sharedNVP_private_domain_member_${fundID}`]: { + settings: { + companyCardNicknames: {}, + companyCards, + }, + }, + }; + } + + function createAdminDomain(accountID: number, adminAccountID: number): Domain { + const domain: Domain = { + validated: true, + accountID, + email: '+@company.com', + domain_defaultSecurityGroupID: '0', + }; + // Set the prefixed admin-access key separately so the object literal isn't widened to a string index + // signature (which would force an unsafe `as unknown as Domain` assertion). + domain[`${CONST.DOMAIN.EXPENSIFY_ADMIN_ACCESS_PREFIX}0`] = adminAccountID; + return domain; + } + + // A domain feed's fundID is the domain's account ID, so the workspace can only come from the feed itself. + it('resolves the workspace a feed links to', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['WS']}}); + const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS'})}; + + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, {}, currentUserAccountID)).toEqual({policyID: 'WS', isAdmin: true}); + }); + + it('falls back to the preferred policy when the feed links to none', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {preferredPolicy: 'WS'}}); + const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS'})}; + + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, {}, currentUserAccountID)).toEqual({policyID: 'WS', isAdmin: true}); + }); + + // The link is only worth offering on a workspace the cardholder can act in, so an administered one wins over + // one that would show them the same problem again. + it('prefers a linked workspace the user administers', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['MEMBER', 'ADMIN']}}); + const policies: OnyxCollection = { + policy_MEMBER: createTestPolicy({id: 'MEMBER', role: CONST.POLICY.ROLE.USER}), + policy_ADMIN: createTestPolicy({id: 'ADMIN'}), + }; + + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, {}, currentUserAccountID)).toEqual({policyID: 'ADMIN', isAdmin: true}); + }); + + // Fixing a feed is a domain permission too, so a domain admin is offered the link even when the workspace the + // feed links to does not make them an admin of it. + it('treats a domain admin as able to fix the feed', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['WS']}}); + const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS', role: CONST.POLICY.ROLE.USER})}; + const domains: OnyxCollection = {[`domain_${fundID}`]: createAdminDomain(fundID, currentUserAccountID)}; + + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, domains, currentUserAccountID)).toEqual({policyID: 'WS', isAdmin: true}); + }); + + it('does not treat a plain member of both the domain and the workspace as able to fix the feed', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['WS']}}); + const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS', role: CONST.POLICY.ROLE.USER})}; + const domains: OnyxCollection = {[`domain_${fundID}`]: createAdminDomain(fundID, 999)}; + + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, domains, currentUserAccountID)).toEqual({policyID: 'WS', isAdmin: false}); + }); + + // An orphan feed names no workspace at all, so the fund is all that is left to go on. + it('falls back to the workspace backing the fund when the feed names none', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {}}); + const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS', policyAccountID: fundID})}; + + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, {}, currentUserAccountID)).toEqual({policyID: 'WS', isAdmin: true}); + }); + + it('returns nothing for a card without a fundID', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['WS']}}); + const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS'})}; + + expect(getAssignedCardFeedAccess({bank, domainName: '', fundID: undefined}, cardFeeds, policies, {}, currentUserAccountID)).toEqual({policyID: undefined, isAdmin: false}); + }); +}); From 7d91097b3d826012d5345167919c1f3f9102d0c2 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Thu, 24 Sep 2026 10:00:12 +0430 Subject: [PATCH 22/24] Match a feed's workspace ID to its Onyx key --- src/libs/CardFeedUtils.ts | 8 ++++++-- tests/unit/CardFeedUtilsTest.ts | 9 +++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/libs/CardFeedUtils.ts b/src/libs/CardFeedUtils.ts index 19d867ded544..61c2e85425fd 100644 --- a/src/libs/CardFeedUtils.ts +++ b/src/libs/CardFeedUtils.ts @@ -333,13 +333,17 @@ function getAssignedCardFeedAccess( const feedSettings = getFeedSettingsForCard(card, allCardFeeds); const linkedPolicyIDs = feedSettings?.linkedPolicyIDs?.filter(Boolean) ?? []; const namedPolicyIDs = linkedPolicyIDs.length ? linkedPolicyIDs : [feedSettings?.preferredPolicy].filter((policyID): policyID is string => !!policyID); - const namedPolicies = namedPolicyIDs.map((policyID) => policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`]).filter((policy) => !!policy); + // A feed spells its policy IDs however the back end sent them, while the Onyx key is upper case, so the ID is + // normalized here as it is wherever else a feed's workspace is looked up. + const namedPolicies = namedPolicyIDs.map((policyID) => policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID.toUpperCase()}`]).filter((policy) => !!policy); // A feed can name more than one workspace. Prefer one the cardholder administers, so the link lands somewhere // they can act rather than on a workspace that would only show them the same problem again. const policyForCard = namedPolicies.find((policy) => isPolicyAdmin(policy)) ?? namedPolicies.at(0) ?? getPolicyForAssignedCard(card, policies); - return {policyID: policyForCard?.id, isAdmin: isAdminSelector(currentUserAccountID)(getDomainByFundID(domains, fundID)) || isPolicyAdmin(policyForCard)}; + // The workspace role is already to hand, while finding the fund's domain can mean scanning every domain, so the + // cheaper check goes first and the scan only happens for someone who is not an admin of the workspace. + return {policyID: policyForCard?.id, isAdmin: isPolicyAdmin(policyForCard) || isAdminSelector(currentUserAccountID)(getDomainByFundID(domains, fundID))}; } /** diff --git a/tests/unit/CardFeedUtilsTest.ts b/tests/unit/CardFeedUtilsTest.ts index 0f77deab9292..8963c021d35d 100644 --- a/tests/unit/CardFeedUtilsTest.ts +++ b/tests/unit/CardFeedUtilsTest.ts @@ -541,6 +541,15 @@ describe('getAssignedCardFeedAccess', () => { expect(getAssignedCardFeedAccess(card, cardFeeds, policies, {}, currentUserAccountID)).toEqual({policyID: 'WS', isAdmin: true}); }); + // A feed's policy IDs come from the back end in whatever case it sent them, while the Onyx key is upper case. + // Missing the workspace here reads as the cardholder not being an admin, which is the bug this resolves. + it('resolves a workspace the feed names in a different case', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['ws']}}); + const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS'})}; + + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, {}, currentUserAccountID)).toEqual({policyID: 'WS', isAdmin: true}); + }); + it('falls back to the preferred policy when the feed links to none', () => { const cardFeeds = createCompanyCardFeeds({[bank]: {preferredPolicy: 'WS'}}); const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS'})}; From b7cff279ee4586492741d112fbcdfe6c0f9a4882 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Thu, 24 Sep 2026 10:08:34 +0430 Subject: [PATCH 23/24] Cover the workspace IDs a card's feed names --- src/libs/CardFeedUtils.ts | 4 +-- tests/unit/CardFeedUtilsTest.ts | 56 +++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/src/libs/CardFeedUtils.ts b/src/libs/CardFeedUtils.ts index 61c2e85425fd..2c45de8617f5 100644 --- a/src/libs/CardFeedUtils.ts +++ b/src/libs/CardFeedUtils.ts @@ -274,8 +274,8 @@ function getCardFeedsForDisplay( /** * The settings of the company card feed an assigned card belongs to. * - * A direct feed keeps its credentials in `oAuthAccountDetails` but its settings, including the workspaces it is - * linked to, alongside a custom feed's in `companyCards`. The card's `bank` can carry the `#domainID` suffix, + * Both direct and custom feeds keep their settings, including the workspaces they are linked to, in `companyCards`. + * `oAuthAccountDetails` only holds a direct feed's credentials. The card's `bank` can carry the `#domainID` suffix, * which is not part of the settings key. */ function getFeedSettingsForCard(card: AssignedCardForFeedAccess, allCardFeeds: OnyxCollection): CustomCardFeedData | undefined { diff --git a/tests/unit/CardFeedUtilsTest.ts b/tests/unit/CardFeedUtilsTest.ts index 8963c021d35d..7d0373c740b4 100644 --- a/tests/unit/CardFeedUtilsTest.ts +++ b/tests/unit/CardFeedUtilsTest.ts @@ -4,6 +4,7 @@ import { getCardFeedsForDisplayPerPolicy, getExpensifyCardFeedsForDisplay, getFeedInfo, + getPolicyIDsNamedByCardFeeds, getVisibleCompanyCardFeedsForSelector, } from '@libs/CardFeedUtils'; @@ -602,3 +603,58 @@ describe('getAssignedCardFeedAccess', () => { expect(getAssignedCardFeedAccess({bank, domainName: '', fundID: undefined}, cardFeeds, policies, {}, currentUserAccountID)).toEqual({policyID: undefined, isAdmin: false}); }); }); + +describe('getPolicyIDsNamedByCardFeeds', () => { + const fundID = 1234; + const bank = cardFeedAmericaExpressMock; + const card = {bank, domainName: 'acme-corp.com', fundID: String(fundID)}; + + function createCompanyCardFeeds(companyCards: NonNullable['companyCards']>): OnyxCollection { + return { + [`sharedNVP_private_domain_member_${fundID}`]: { + settings: { + companyCardNicknames: {}, + companyCards, + }, + }, + }; + } + + // These IDs decide which policies a consumer loads. Returning none leaves the workspace unresolved, which reads + // as the cardholder not being an admin of it. + it('collects every workspace a feed links to', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['WS1', 'WS2']}}); + + expect(getPolicyIDsNamedByCardFeeds([card], cardFeeds)).toEqual(['WS1', 'WS2']); + }); + + it('collects the preferred policy as well as the linked ones', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['WS1'], preferredPolicy: 'WS2'}}); + + expect(getPolicyIDsNamedByCardFeeds([card], cardFeeds)).toEqual(['WS1', 'WS2']); + }); + + it('lists a workspace two cards share only once', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['WS1']}}); + + expect(getPolicyIDsNamedByCardFeeds([card, {...card, bank}], cardFeeds)).toEqual(['WS1']); + }); + + it('skips the empty entries a feed can carry', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['', 'WS1'], preferredPolicy: ''}}); + + expect(getPolicyIDsNamedByCardFeeds([card], cardFeeds)).toEqual(['WS1']); + }); + + it('returns nothing for a feed that names no workspace', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {}}); + + expect(getPolicyIDsNamedByCardFeeds([card], cardFeeds)).toEqual([]); + }); + + it('returns nothing for a card without a fundID', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['WS1']}}); + + expect(getPolicyIDsNamedByCardFeeds([{bank, domainName: '', fundID: undefined}], cardFeeds)).toEqual([]); + }); +}); From 912528af8df431bc204b83c6996c8f0cda284140 Mon Sep 17 00:00:00 2001 From: Maruf Sharifi Date: Thu, 1 Oct 2026 10:19:11 +0430 Subject: [PATCH 24/24] Offer the fix link only to those who can use it --- src/libs/CardFeedUtils.ts | 31 +++++---- .../settings/Wallet/PaymentMethodList.tsx | 5 +- tests/unit/CardFeedUtilsTest.ts | 69 ++++++++++--------- 3 files changed, 56 insertions(+), 49 deletions(-) diff --git a/src/libs/CardFeedUtils.ts b/src/libs/CardFeedUtils.ts index 2c45de8617f5..eba005cd50e8 100644 --- a/src/libs/CardFeedUtils.ts +++ b/src/libs/CardFeedUtils.ts @@ -13,7 +13,7 @@ import type {CardFeedData, CardFeedsStatus, CardFeedsStatusByDomainID, CardFeedW import type {PendingAction} from '@src/types/onyx/OnyxCommon'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; -import type {OnyxCollection} from 'react-native-onyx'; +import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; import {isAdminSelector} from '@selectors/Domain'; @@ -40,7 +40,7 @@ import { isPersonalCard, } from './CardUtils'; import {getExpensifyCardFeedDescription} from './ExpensifyCardFeedSelectorUtils'; -import {getPolicyForAssignedCard, isPolicyAdmin} from './PolicyUtils'; +import {canMemberWrite, getPolicyForAssignedCard, isPolicyAdmin} from './PolicyUtils'; /** The fields of an assigned card needed to resolve the workspace behind its feed */ type AssignedCardForFeedAccess = Pick; @@ -314,16 +314,17 @@ function getPolicyIDsNamedByCardFeeds(cards: AssignedCardForFeedAccess[], allCar * The wallet offers a link to the Company cards page, so it has to agree with what that page already shows. The * workspace comes from the feed's own `linkedPolicyIDs`, then its `preferredPolicy`, and only a feed naming neither * falls back to the fund, as in `getCardFeedsForDisplayPerPolicy`. A domain feed's `fundID` is the domain's account - * ID rather than a workspace's, so that fallback cannot find the workspace for one on its own. Fixing a feed is a - * domain permission as well as a workspace one, so a domain admin is offered the link too, as in - * `getVisibleCompanyCardFeedsForSelector`. + * ID rather than a workspace's, so that fallback cannot find the workspace for one on its own. + * + * Whether the link is offered is the Company cards page's own write permission rather than the workspace role, so a + * card admin who can fix the feed is offered it, while a member or an auditor who would land on Not Found or a + * read-only page is told to ask an admin instead. */ function getAssignedCardFeedAccess( card: AssignedCardForFeedAccess, allCardFeeds: OnyxCollection, policies: OnyxCollection, - domains: OnyxCollection, - currentUserAccountID: number | undefined, + currentUserLogin: string | undefined, ): {policyID: string | undefined; isAdmin: boolean} { const fundID = Number(card.fundID); if (!fundID) { @@ -337,13 +338,17 @@ function getAssignedCardFeedAccess( // normalized here as it is wherever else a feed's workspace is looked up. const namedPolicies = namedPolicyIDs.map((policyID) => policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID.toUpperCase()}`]).filter((policy) => !!policy); - // A feed can name more than one workspace. Prefer one the cardholder administers, so the link lands somewhere - // they can act rather than on a workspace that would only show them the same problem again. - const policyForCard = namedPolicies.find((policy) => isPolicyAdmin(policy)) ?? namedPolicies.at(0) ?? getPolicyForAssignedCard(card, policies); + // The link goes to a workspace's Company cards page, which checks this same permission before it renders + // anything, so asking it here is what decides whether the link can do what it offers. A missing login falls back + // to the role the policy itself carries rather than hiding the link, because the personal details that hold the + // login load separately from the policy. + const canFixFeedOn = (policy: OnyxEntry) => canMemberWrite(policy, currentUserLogin ?? '', CONST.POLICY.POLICY_FEATURE.COMPANY_CARDS); + + // A feed can name more than one workspace. Prefer one the cardholder can fix the feed on, so the link lands + // somewhere they can act rather than on a workspace that would only show them the same problem again. + const policyForCard = namedPolicies.find(canFixFeedOn) ?? namedPolicies.at(0) ?? getPolicyForAssignedCard(card, policies); - // The workspace role is already to hand, while finding the fund's domain can mean scanning every domain, so the - // cheaper check goes first and the scan only happens for someone who is not an admin of the workspace. - return {policyID: policyForCard?.id, isAdmin: isPolicyAdmin(policyForCard) || isAdminSelector(currentUserAccountID)(getDomainByFundID(domains, fundID))}; + return {policyID: policyForCard?.id, isAdmin: canFixFeedOn(policyForCard)}; } /** diff --git a/src/pages/settings/Wallet/PaymentMethodList.tsx b/src/pages/settings/Wallet/PaymentMethodList.tsx index 4b3c686a1ab2..4805b5f65504 100644 --- a/src/pages/settings/Wallet/PaymentMethodList.tsx +++ b/src/pages/settings/Wallet/PaymentMethodList.tsx @@ -212,9 +212,8 @@ function PaymentMethodList({ const isLoadingBankAccountList = isLoadingOnyxValue(bankAccountListResult); const [cardList = getEmptyObject(), cardListResult] = useOnyx(ONYXKEYS.CARD_LIST); const isLoadingCardList = isLoadingOnyxValue(cardListResult); - const {accountID: currentUserAccountID} = useCurrentUserPersonalDetails(); + const {login: currentUserLogin} = useCurrentUserPersonalDetails(); const [allCardFeeds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER); - const [allDomains] = useOnyx(ONYXKEYS.COLLECTION.DOMAIN); const cardsForPolicyLookup = shouldShowAssignedCards ? Object.values(isLoadingCardList ? {} : (cardList ?? {})).filter((card) => !!card.domainName || !!card.fundID) : []; const policiesForAssignedCardsSelectorFactory = createPoliciesForAssignedCardsSelector(cardsForPolicyLookup, getPolicyIDsNamedByCardFeeds(cardsForPolicyLookup, allCardFeeds)); const [policiesForAssignedCards] = useOnyx(ONYXKEYS.COLLECTION.POLICY, { @@ -273,7 +272,7 @@ function PaymentMethodList({ const isCSVCard = card.bank === CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD || card.bank.includes(CONST.COMPANY_CARD.FEED_BANK_NAME.CSV); const assignedCardsGrouped = isUserPersonalCard ? personalCardsGrouped : companyCardsGrouped; const {policyID: policyIDForCard, isAdmin: isAdminForCardPolicy} = shouldShowConnectionStatus - ? getAssignedCardFeedAccess(card, allCardFeeds, policiesForAssignedCards, allDomains, currentUserAccountID) + ? getAssignedCardFeedAccess(card, allCardFeeds, policiesForAssignedCards, currentUserLogin) : {policyID: undefined, isAdmin: false}; let icon; diff --git a/tests/unit/CardFeedUtilsTest.ts b/tests/unit/CardFeedUtilsTest.ts index 7d0373c740b4..ea420f42b784 100644 --- a/tests/unit/CardFeedUtilsTest.ts +++ b/tests/unit/CardFeedUtilsTest.ts @@ -506,7 +506,7 @@ describe('getVisibleCompanyCardFeedsForSelector', () => { describe('getAssignedCardFeedAccess', () => { const fundID = 1234; - const currentUserAccountID = 777; + const currentUserLogin = 'admin@test.com'; const bank = cardFeedAmericaExpressMock; const card = {bank, domainName: 'acme-corp.com', fundID: String(fundID)}; @@ -521,71 +521,65 @@ describe('getAssignedCardFeedAccess', () => { }; } - function createAdminDomain(accountID: number, adminAccountID: number): Domain { - const domain: Domain = { - validated: true, - accountID, - email: '+@company.com', - domain_defaultSecurityGroupID: '0', - }; - // Set the prefixed admin-access key separately so the object literal isn't widened to a string index - // signature (which would force an unsafe `as unknown as Domain` assertion). - domain[`${CONST.DOMAIN.EXPENSIFY_ADMIN_ACCESS_PREFIX}0`] = adminAccountID; - return domain; - } - // A domain feed's fundID is the domain's account ID, so the workspace can only come from the feed itself. it('resolves the workspace a feed links to', () => { const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['WS']}}); const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS'})}; - expect(getAssignedCardFeedAccess(card, cardFeeds, policies, {}, currentUserAccountID)).toEqual({policyID: 'WS', isAdmin: true}); + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, currentUserLogin)).toEqual({policyID: 'WS', isAdmin: true}); }); // A feed's policy IDs come from the back end in whatever case it sent them, while the Onyx key is upper case. - // Missing the workspace here reads as the cardholder not being an admin, which is the bug this resolves. + // Missing the workspace here reads as the cardholder not being able to fix the feed, which is the bug this resolves. it('resolves a workspace the feed names in a different case', () => { const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['ws']}}); const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS'})}; - expect(getAssignedCardFeedAccess(card, cardFeeds, policies, {}, currentUserAccountID)).toEqual({policyID: 'WS', isAdmin: true}); + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, currentUserLogin)).toEqual({policyID: 'WS', isAdmin: true}); }); it('falls back to the preferred policy when the feed links to none', () => { const cardFeeds = createCompanyCardFeeds({[bank]: {preferredPolicy: 'WS'}}); const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS'})}; - expect(getAssignedCardFeedAccess(card, cardFeeds, policies, {}, currentUserAccountID)).toEqual({policyID: 'WS', isAdmin: true}); + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, currentUserLogin)).toEqual({policyID: 'WS', isAdmin: true}); }); - // The link is only worth offering on a workspace the cardholder can act in, so an administered one wins over - // one that would show them the same problem again. - it('prefers a linked workspace the user administers', () => { + // The link is only worth offering on a workspace the cardholder can act in, so one they can fix the feed on wins + // over one that would show them the same problem again. + it('prefers a linked workspace the user can fix the feed on', () => { const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['MEMBER', 'ADMIN']}}); const policies: OnyxCollection = { policy_MEMBER: createTestPolicy({id: 'MEMBER', role: CONST.POLICY.ROLE.USER}), policy_ADMIN: createTestPolicy({id: 'ADMIN'}), }; - expect(getAssignedCardFeedAccess(card, cardFeeds, policies, {}, currentUserAccountID)).toEqual({policyID: 'ADMIN', isAdmin: true}); + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, currentUserLogin)).toEqual({policyID: 'ADMIN', isAdmin: true}); }); - // Fixing a feed is a domain permission too, so a domain admin is offered the link even when the workspace the - // feed links to does not make them an admin of it. - it('treats a domain admin as able to fix the feed', () => { + // A card admin is not a workspace admin but is exactly who the Company cards page lets fix a feed, so the role + // alone would send them to ask somebody else to do what they can do themselves. + it('offers the link to a card admin who is not a workspace admin', () => { const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['WS']}}); - const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS', role: CONST.POLICY.ROLE.USER})}; - const domains: OnyxCollection = {[`domain_${fundID}`]: createAdminDomain(fundID, currentUserAccountID)}; + const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS', role: CONST.POLICY.ROLE.CARD_ADMIN, type: CONST.POLICY.TYPE.CORPORATE})}; + + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, currentUserLogin)).toEqual({policyID: 'WS', isAdmin: true}); + }); + + // The Company cards page is read-only for an auditor, so the link would open a page with the fix banner hidden. + it('does not offer the link to an auditor of the linked workspace', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['WS']}}); + const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS', role: CONST.POLICY.ROLE.AUDITOR, type: CONST.POLICY.TYPE.CORPORATE})}; - expect(getAssignedCardFeedAccess(card, cardFeeds, policies, domains, currentUserAccountID)).toEqual({policyID: 'WS', isAdmin: true}); + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, currentUserLogin)).toEqual({policyID: 'WS', isAdmin: false}); }); - it('does not treat a plain member of both the domain and the workspace as able to fix the feed', () => { + // A member cannot open the page at all, so the link would land on Not Found. + it('does not offer the link to a member of the linked workspace', () => { const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['WS']}}); const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS', role: CONST.POLICY.ROLE.USER})}; - const domains: OnyxCollection = {[`domain_${fundID}`]: createAdminDomain(fundID, 999)}; - expect(getAssignedCardFeedAccess(card, cardFeeds, policies, domains, currentUserAccountID)).toEqual({policyID: 'WS', isAdmin: false}); + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, currentUserLogin)).toEqual({policyID: 'WS', isAdmin: false}); }); // An orphan feed names no workspace at all, so the fund is all that is left to go on. @@ -593,14 +587,23 @@ describe('getAssignedCardFeedAccess', () => { const cardFeeds = createCompanyCardFeeds({[bank]: {}}); const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS', policyAccountID: fundID})}; - expect(getAssignedCardFeedAccess(card, cardFeeds, policies, {}, currentUserAccountID)).toEqual({policyID: 'WS', isAdmin: true}); + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, currentUserLogin)).toEqual({policyID: 'WS', isAdmin: true}); + }); + + // The personal details that hold the login load separately from the policies, so a row rendered before they + // arrive must still offer the link rather than telling an admin to ask themselves. + it('offers the link when the login has not loaded yet', () => { + const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['WS']}}); + const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS'})}; + + expect(getAssignedCardFeedAccess(card, cardFeeds, policies, undefined)).toEqual({policyID: 'WS', isAdmin: true}); }); it('returns nothing for a card without a fundID', () => { const cardFeeds = createCompanyCardFeeds({[bank]: {linkedPolicyIDs: ['WS']}}); const policies: OnyxCollection = {policy_WS: createTestPolicy({id: 'WS'})}; - expect(getAssignedCardFeedAccess({bank, domainName: '', fundID: undefined}, cardFeeds, policies, {}, currentUserAccountID)).toEqual({policyID: undefined, isAdmin: false}); + expect(getAssignedCardFeedAccess({bank, domainName: '', fundID: undefined}, cardFeeds, policies, currentUserLogin)).toEqual({policyID: undefined, isAdmin: false}); }); });