Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';

import {getLinkedPolicyName} from '@libs/CardFeedUtils';
import {getCompanyFeeds, getCustomOrFormattedFeedName, getPlaidCountry, getPlaidInstitutionId, isCustomFeed} from '@libs/CardUtils';
import {getCompanyFeeds, getCustomOrFormattedFeedName, isCustomFeed, isDirectFeed} from '@libs/CardUtils';

import Navigation from '@navigation/Navigation';

import {setAddNewCompanyCardStepAndData, setAssignCardStepAndData} from '@userActions/CompanyCards';
import {startCardFeedRefresh} from '@userActions/CompanyCards';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
Expand Down Expand Up @@ -73,30 +73,18 @@ function WorkspaceCompanyCardsTableHeaderButtons({policyID, feedName, isLoading,
const hasOtherFeedWithRBR = Object.keys(companyFeeds ?? {}).some((feed) => feed !== feedName && shouldShowRbrForFeedNameWithDomainID[feed]);
const shouldShowFeedSelectorRBR = hasOtherFeedWithRBR || !!feedErrors?.hasWorkspaceErrors;
const shouldShowBrokenConnectionError = getShouldShowBrokenConnectionError(feedName, feedErrors);
// Only direct feeds can be reconnected in-app, so other feeds get the message without the bank login link.
const brokenConnectionMessage = isDirectFeed(feedName) ? translate('workspace.companyCards.brokenConnectionError') : `<rbr>${translate('personalCard.brokenConnection')}</rbr>`;

const openBankConnection = () => {
if (!feedName) {
return;
}

const institutionId = getPlaidInstitutionId(feedName);
const initialStep = institutionId ? CONST.COMPANY_CARD.STEP.PLAID_CONNECTION : CONST.COMPANY_CARD.STEP.BANK_CONNECTION;

// For Plaid feeds, seed selectedCountry so PlaidConnectionStep can start the login flow
if (institutionId) {
const country = getPlaidCountry(policy?.outputCurrency, currencyList, countryByIp);
setAddNewCompanyCardStepAndData({
data: {
selectedCountry: country,
},
});
}

setAssignCardStepAndData({currentStep: initialStep});

Navigation.setNavigationActionToMicrotaskQueue(() => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot startCardFeedRefresh doesn't have setNavigationActionToMicrotaskQueue. Is it safe removal? Which PR introduced this to fix what bug?

Navigation.navigate(ROUTES.WORKSPACE_COMPANY_CARDS_BROKEN_CARD_FEED_CONNECTION.getRoute(policyID ?? String(CONST.DEFAULT_NUMBER_ID), feedName));
});
// The refresh flow keeps the bank login open until the reconnect completes: expiration change for OAuth,
// import finishing for Plaid. The broken-connection page would treat a feed that only has feed-level errors
// as already reconnected and close at once.
startCardFeedRefresh(policyID, feedName, policy?.outputCurrency, currencyList, countryByIp);
Comment thread
jmusial marked this conversation as resolved.
Resolved
Comment thread
jmusial marked this conversation as resolved.
Resolved
Comment thread
jmusial marked this conversation as resolved.
Resolved
};

const isCsvFeed = feedName?.includes(CONST.COMPANY_CARD.FEED_BANK_NAME.CSV);
Expand Down Expand Up @@ -157,7 +145,7 @@ function WorkspaceCompanyCardsTableHeaderButtons({policyID, feedName, isLoading,
/>
<View style={[styles.offlineFeedbackText, styles.pr5, styles.flexRow, styles.w100]}>
<RenderHTML
html={translate('workspace.companyCards.brokenConnectionError')}
html={brokenConnectionMessage}
onLinkPress={openBankConnection}
/>
</View>
Expand Down
2 changes: 2 additions & 0 deletions src/libs/actions/CompanyCards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1383,6 +1383,8 @@ function startCardFeedRefresh(policyID: string, feed: CompanyCardFeedWithDomainI
Onyx.merge(ONYXKEYS.ADD_NEW_COMPANY_CARD, {data: {selectedCountry}});
}

// An abandoned assign flow can leave errors or cardToAssign behind, which BankConnection would read as a failed import or as a Plaid token.
clearAssignCardStepAndData();
setAssignCardStepAndData({
currentStep,
isRefreshing: true,
Expand Down
4 changes: 3 additions & 1 deletion src/libs/actions/Plaid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type {AddPersonalPlaidCardParams, ImportPlaidAccountsParams, OpenPlaidBan
import type OpenPlaidCompanyCardLoginParams from '@libs/API/parameters/OpenPlaidCompanyCardLoginParams';
import {READ_COMMANDS, WRITE_COMMANDS} from '@libs/API/types';
import {getCardFeedWithoutDomainID} from '@libs/CardUtils';
import {getMicroSecondOnyxErrorWithTranslationKey} from '@libs/ErrorUtils';
import getPlaidLinkTokenParameters from '@libs/getPlaidLinkTokenParameters';

import CONST from '@src/CONST';
Expand Down Expand Up @@ -151,6 +152,7 @@ function importPlaidAccounts(
plaidAccounts: string,
plaidAccessToken: string | undefined,
domainAccountID?: number,
isRepairingFeed = false,
) {
const parameters: ImportPlaidAccountsParams = {
publicToken,
Expand Down Expand Up @@ -178,7 +180,7 @@ function importPlaidAccounts(
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.ASSIGN_CARD,
value: {isRefreshing: null},
value: {isRefreshing: null, ...(isRepairingFeed ? {errors: getMicroSecondOnyxErrorWithTranslationKey('common.genericErrorMessage')} : {})},

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Scope refresh completion to repair imports

The new isRepairingFeed flag scopes only the error, while every failed import still clears the shared ASSIGN_CARD.isRefreshing flag. For example, useAssignCard starts a non-repair import with the default false; if that request is still pending when the user starts the banner refresh, its failure produces a true → null transition with no error, and RefreshCardFeedConnectionPage closes the RHP before the new reauthentication completes. Only repair imports should update refresh state, ideally tied to the active attempt; the unchanged success path has the same overlapping-request problem.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Race predates the PR: importPlaidAccounts has cleared isRefreshing unconditionally on both success and failure before. This PR only scopes the new errors write.

},
],
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import ActivityIndicator from '@components/ActivityIndicator';
import FullPageOfflineBlockingView from '@components/BlockingViews/FullPageOfflineBlockingView';
import ConfirmationPage from '@components/ConfirmationPage';
import HeaderWithBackButton from '@components/HeaderWithBackButton';
import ScreenWrapper from '@components/ScreenWrapper';

import useCardFeeds from '@hooks/useCardFeeds';
import useDuplicateFeedDetection from '@hooks/useDuplicateFeedDetection';
import useImportPlaidAccounts from '@hooks/useImportPlaidAccounts';
import useIsBlockedToAddFeed from '@hooks/useIsBlockedToAddFeed';
import {useMemoizedLazyIllustrations} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
import useOnyx from '@hooks/useOnyx';
import usePrevious from '@hooks/usePrevious';
import useThemeStyles from '@hooks/useThemeStyles';
import useUpdateFeedBrokenConnection from '@hooks/useUpdateFeedBrokenConnection';

import {updateSelectedFeed} from '@libs/actions/Card';
import {setAssignCardStepAndData} from '@libs/actions/CompanyCards';
import {checkIfNewFeedConnected, getBankName, getCompanyCardFeed, isSelectedFeedExpired} from '@libs/CardUtils';
import getUAForWebView from '@libs/getUAForWebView';
import Navigation from '@libs/Navigation/Navigation';
Expand All @@ -28,6 +29,7 @@ import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {CompanyCardFeedWithDomainID} from '@src/types/onyx';
import {isEmptyObject} from '@src/types/utils/EmptyObject';

import type {WebViewNavigation} from 'react-native-webview';

Expand Down Expand Up @@ -71,6 +73,9 @@ function BankConnection({policyID, feed, title}: BankConnectionProps) {
const onImportPlaidAccounts = useImportPlaidAccounts(policyID);
const {updateBrokenConnection, isFeedConnectionBroken} = useUpdateFeedBrokenConnection({policyID, feed});
const isNewFeedHasError = !!(newFeed && cardFeeds?.[newFeed]?.errors);
// importPlaidAccounts only writes these errors while repairing an existing feed, so the add-card flow ignores them
const hasImportError = !!feed && !isEmptyObject(assignCard?.errors);
const illustrations = useMemoizedLazyIllustrations(['BrokenCompanyCardBankConnection']);
const {isBlockedToAddNewFeeds, isAllFeedsResultLoading} = useIsBlockedToAddFeed(policyID);
const {checkForDuplicateFeed} = useDuplicateFeedDetection({policyID, isPlaid});

Expand Down Expand Up @@ -104,6 +109,11 @@ function BankConnection({policyID, feed, title}: BankConnectionProps) {
return;
}

// A failed import is rendered instead. Clearing isRefreshing must not fall through to the healthy feed close below.
if (hasImportError) {
return;
}

// Handle assign card flow
if (feed) {
if (!isFeedExpired) {
Expand All @@ -112,13 +122,11 @@ function BankConnection({policyID, feed, title}: BankConnectionProps) {
Navigation.goBack(ROUTES.WORKSPACE_COMPANY_CARDS.getRoute(policyID));
return;
}
// When refreshing the feed, a healthy connection must not short-circuit into the assignee step.
// RefreshCardFeedConnectionPage can't render it and the modal would spin forever.
// The host pages only render the connection steps, so an assign flow that detoured here is not resumed.
// The panel closes and the admin assigns the card again on the reconnected feed. During a refresh the
// panel stays open because RefreshCardFeedConnectionPage closes it once the reconnect completes.
if (!assignCard?.isRefreshing) {
setAssignCardStepAndData({
currentStep: assignCard?.cardToAssign?.dateOption ? CONST.COMPANY_CARD.STEP.CONFIRMATION : CONST.COMPANY_CARD.STEP.ASSIGNEE,
isEditing: false,
});
Navigation.goBack(ROUTES.WORKSPACE_COMPANY_CARDS.getRoute(policyID));
return;
}
}
Expand Down Expand Up @@ -155,13 +163,13 @@ function BankConnection({policyID, feed, title}: BankConnectionProps) {
url,
feed,
isFeedExpired,
assignCard?.cardToAssign?.dateOption,
assignCard?.isRefreshing,
isPlaid,
onImportPlaidAccounts,
isFeedConnectionBroken,
updateBrokenConnection,
isNewFeedHasError,
hasImportError,
checkForDuplicateFeed,
]);

Expand Down Expand Up @@ -200,12 +208,24 @@ function BankConnection({policyID, feed, title}: BankConnectionProps) {
renderLoading={renderLoading}
/>
)}
{(isAllFeedsResultLoading || (isBlockedToAddNewFeeds && !feed) || isConnectionCompleted || isPlaid) && !isNewFeedHasError && (
{(isAllFeedsResultLoading || (isBlockedToAddNewFeeds && !feed) || isConnectionCompleted || isPlaid) && !isNewFeedHasError && !hasImportError && (
<ActivityIndicator
size={CONST.ACTIVITY_INDICATOR_SIZE.LARGE}
style={styles.flex1}
/>
)}
{hasImportError && (
<ConfirmationPage
heading={translate('workspace.companyCards.error.feedCouldNotBeLoadedTitle')}
description={translate('common.genericErrorMessage')}
illustration={illustrations.BrokenCompanyCardBankConnection}
illustrationStyle={styles.errorStateCardIllustration}
containerStyle={styles.h100}
shouldShowButton
buttonText={translate('common.buttonConfirm')}
onButtonPress={() => Navigation.goBack(ROUTES.WORKSPACE_COMPANY_CARDS.getRoute(policyID))}
/>
)}
{isNewFeedHasError && (
<WorkspaceCompanyCardsErrorConfirmation
policyID={policyID}
Expand Down
39 changes: 30 additions & 9 deletions src/pages/workspace/companyCards/BankConnection/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import ActivityIndicator from '@components/ActivityIndicator';
import BlockingView from '@components/BlockingViews/BlockingView';
import FullPageOfflineBlockingView from '@components/BlockingViews/FullPageOfflineBlockingView';
import ConfirmationPage from '@components/ConfirmationPage';
import HeaderWithBackButton from '@components/HeaderWithBackButton';
import ScreenWrapper from '@components/ScreenWrapper';
import Text from '@components/Text';
Expand All @@ -18,7 +19,6 @@ import usePrevious from '@hooks/usePrevious';
import useThemeStyles from '@hooks/useThemeStyles';
import useUpdateFeedBrokenConnection from '@hooks/useUpdateFeedBrokenConnection';

import {setAssignCardStepAndData} from '@libs/actions/CompanyCards';
import {checkIfNewFeedConnected, getBankName, getCompanyCardFeed, isSelectedFeedExpired} from '@libs/CardUtils';
import Navigation from '@libs/Navigation/Navigation';

Expand All @@ -32,6 +32,7 @@ import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {CompanyCardFeedWithDomainID} from '@src/types/onyx';
import {isEmptyObject} from '@src/types/utils/EmptyObject';

import React, {useCallback, useEffect, useMemo, useState} from 'react';

Expand All @@ -56,7 +57,7 @@ function BankConnection({policyID, feed, title}: BankConnectionProps) {
const [assignCard] = useOnyx(ONYXKEYS.ASSIGN_CARD);
const [cardFeeds] = useCardFeeds(policyID);
const prevFeedsData = usePrevious(cardFeeds);
const illustrations = useMemoizedLazyIllustrations(['PendingBank']);
const illustrations = useMemoizedLazyIllustrations(['PendingBank', 'BrokenCompanyCardBankConnection']);
const [shouldBlockWindowOpen, setShouldBlockWindowOpen] = useState(false);
const selectedBank = addNewCard?.data?.selectedBank;
const bankName = feed ? getBankName(getCompanyCardFeed(feed)) : (addNewCard?.data?.plaidConnectedFeed ?? selectedBank);
Expand All @@ -74,6 +75,8 @@ function BankConnection({policyID, feed, title}: BankConnectionProps) {
const headerTitleAddCards = translate('workspace.companyCards.addCards');
const headerTitle = feed ? translate('workspace.companyCards.assignCard') : headerTitleAddCards;
const isNewFeedHasError = !!(newFeed && cardFeeds?.[newFeed]?.errors);
// importPlaidAccounts only writes these errors while repairing an existing feed, so the add-card flow ignores them
const hasImportError = !!feed && !isEmptyObject(assignCard?.errors);
const onImportPlaidAccounts = useImportPlaidAccounts(policyID);
const {isBlockedToAddNewFeeds, isAllFeedsResultLoading} = useIsBlockedToAddFeed(policyID);
const {checkForDuplicateFeed} = useDuplicateFeedDetection({policyID, isPlaid});
Expand Down Expand Up @@ -118,6 +121,12 @@ function BankConnection({policyID, feed, title}: BankConnectionProps) {
return;
}

// A failed import is rendered instead. Clearing isRefreshing must not fall through to the healthy feed close below.
if (hasImportError) {
customWindow?.close();
return;
}

// Handle assign card flow
if (feed) {
if (!isFeedExpired) {
Expand All @@ -127,13 +136,11 @@ function BankConnection({policyID, feed, title}: BankConnectionProps) {
Navigation.closeRHPFlow();
return;
}
// When refreshing the feed, a healthy connection must not short-circuit into the assignee step.
// RefreshCardFeedConnectionPage can't render it and the modal would spin forever.
// The host pages only render the connection steps, so an assign flow that detoured here is not resumed.
// The panel closes and the admin assigns the card again on the reconnected feed. During a refresh the
// panel stays open because RefreshCardFeedConnectionPage closes it once the reconnect completes.
if (!assignCard?.isRefreshing) {
setAssignCardStepAndData({
currentStep: assignCard?.cardToAssign?.dateOption ? CONST.COMPANY_CARD.STEP.CONFIRMATION : CONST.COMPANY_CARD.STEP.ASSIGNEE,
isEditing: false,
});
Navigation.closeRHPFlow();
return;
}
}
Expand Down Expand Up @@ -183,17 +190,31 @@ function BankConnection({policyID, feed, title}: BankConnectionProps) {
feed,
isFeedExpired,
isOffline,
assignCard?.cardToAssign?.dateOption,
assignCard?.isRefreshing,
isPlaid,
onImportPlaidAccounts,
isFeedConnectionBroken,
updateBrokenConnection,
isNewFeedHasError,
hasImportError,
checkForDuplicateFeed,
]);

const getContent = () => {
if (hasImportError) {
return (
<ConfirmationPage
heading={translate('workspace.companyCards.error.feedCouldNotBeLoadedTitle')}
description={translate('common.genericErrorMessage')}
illustration={illustrations.BrokenCompanyCardBankConnection}
illustrationStyle={styles.errorStateCardIllustration}
containerStyle={styles.h100}
shouldShowButton
buttonText={translate('common.buttonConfirm')}
onButtonPress={() => Navigation.closeRHPFlow()}
/>
);
}
if (isNewFeedHasError) {
return (
<WorkspaceCompanyCardsErrorConfirmation
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import useLocalize from '@hooks/useLocalize';
import useCardFeeds from '@hooks/useCardFeeds';
import useOnyx from '@hooks/useOnyx';

import {isDirectFeed} from '@libs/CardUtils';
import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types';

import type {SettingsNavigatorParamList} from '@navigation/types';

import LoadingPage from '@pages/LoadingPage';
import NotFoundPage from '@pages/ErrorPage/NotFoundPage';
import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper';
import type {WithPolicyAndFullscreenLoadingProps} from '@pages/workspace/withPolicyAndFullscreenLoading';
import withPolicyAndFullscreenLoading from '@pages/workspace/withPolicyAndFullscreenLoading';
Expand All @@ -28,17 +29,21 @@ function BrokenCardFeedConnectionPage({route, policy}: BrokenCardFeedConnectionP
const feed = route.params?.feed;
const policyID = policy?.id;

const {translate} = useLocalize();

const [assignCard] = useOnyx(ONYXKEYS.ASSIGN_CARD);
const currentStep = assignCard?.currentStep;

const [cardFeeds] = useCardFeeds(policyID);

useEffect(() => {
return () => {
clearAssignCardStepAndData();
};
}, []);

if (!isDirectFeed(feed) || !cardFeeds?.[feed] || !currentStep) {
return <NotFoundPage />;
}

let content: React.ReactNode;
switch (currentStep) {
case CONST.COMPANY_CARD.STEP.BANK_CONNECTION:
Expand All @@ -58,7 +63,7 @@ function BrokenCardFeedConnectionPage({route, policy}: BrokenCardFeedConnectionP
);
break;
default:
content = <LoadingPage title={translate('workspace.companyCards.assignCard')} />;
content = <NotFoundPage />;
}

return (
Expand Down
Loading
Loading