diff --git a/src/ROUTES.ts b/src/ROUTES.ts index 641a96731167..1c1c9ae7f564 100644 --- a/src/ROUTES.ts +++ b/src/ROUTES.ts @@ -2476,6 +2476,15 @@ const ROUTES = { route: 'workspaces/:policyID/company-cards/:feed/broken-card-feed-connection', getRoute: (policyID: string, feed: CompanyCardFeedWithDomainID) => `workspaces/${policyID}/company-cards/${encodeURIComponent(feed)}/broken-card-feed-connection` as const, }, + WORKSPACE_COMPANY_CARDS_REFRESH_CARD_FEED_CONNECTION: { + route: 'workspaces/:policyID/company-cards/:feed/refresh-card-feed-connection', + getRoute: (policyID: string, feed: CompanyCardFeedWithDomainID) => `workspaces/${policyID}/company-cards/${encodeURIComponent(feed)}/refresh-card-feed-connection` as const, + }, + WORKSPACE_COMPANY_CARDS_VERIFY_ACCOUNT: { + route: `workspaces/:policyID/company-cards/${VERIFY_ACCOUNT}`, + getRoute: (policyID: string, feed?: CompanyCardFeedWithDomainID) => + feed ? (`workspaces/${policyID}/company-cards/${VERIFY_ACCOUNT}?feed=${encodeURIComponent(feed)}` as const) : (`workspaces/${policyID}/company-cards/${VERIFY_ACCOUNT}` as const), + }, WORKSPACE_COMPANY_CARDS_ASSIGN_CARD_ASSIGNEE: { route: 'workspaces/:policyID/company-cards/:feed/assign-card/:cardID/assignee', getRoute: (params: WorkspaceCompanyCardsAssignCardParams, backTo?: string) => diff --git a/src/SCREENS.ts b/src/SCREENS.ts index defe5ca9d21b..dee5f9c17a77 100644 --- a/src/SCREENS.ts +++ b/src/SCREENS.ts @@ -640,6 +640,8 @@ const SCREENS = { PROFILE: 'Workspace_Overview', COMPANY_CARDS: 'Workspace_CompanyCards', COMPANY_CARDS_BROKEN_CARD_FEED_CONNECTION: 'Workspace_CompanyCards_BrokenCardFeedConnection', + COMPANY_CARDS_REFRESH_CARD_FEED_CONNECTION: 'Workspace_CompanyCards_RefreshCardFeedConnection', + COMPANY_CARDS_VERIFY_ACCOUNT: 'Workspace_CompanyCards_VerifyAccount', COMPANY_CARDS_ASSIGN_CARD_ASSIGNEE: 'Workspace_CompanyCards_AssignCard_Assignee', COMPANY_CARDS_ASSIGN_CARD_BANK_CONNECTION: 'Workspace_CompanyCards_AssignCard_Bank_Connection', COMPANY_CARDS_ASSIGN_CARD_PLAID_CONNECTION: 'Workspace_CompanyCards_AssignCard_Plaid_Connection', diff --git a/src/languages/de.ts b/src/languages/de.ts index e4686e8ccc44..d9230d62c3c9 100644 --- a/src/languages/de.ts +++ b/src/languages/de.ts @@ -5130,6 +5130,7 @@ _Für ausführlichere Anweisungen [besuchen Sie unsere Hilfeseite](${CONST.NETSU flipAmountSign: 'Betragsvorzeichen umkehren', importButton: 'Transaktionen importieren', }, + assignNewCards: {title: 'Neue Karten zuweisen', description: 'Holen Sie die neuesten Karten zum Zuweisen von Ihrer Bank'}, }, expensifyCard: { issueAndManageCards: 'Geben Sie Expensify Karten aus und verwalten Sie sie', diff --git a/src/languages/en.ts b/src/languages/en.ts index 755929c7c47c..220d223348b9 100644 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -5124,6 +5124,10 @@ const translations = { flipAmountSign: 'Flip amount sign', importButton: 'Import transactions', }, + assignNewCards: { + title: 'Assign new cards', + description: 'Get the latest cards to assign from your bank', + }, }, expensifyCard: { issueAndManageCards: 'Issue and manage your Expensify Cards', diff --git a/src/languages/es.ts b/src/languages/es.ts index 013fd7932c47..127b7afbed2d 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -5008,6 +5008,10 @@ ${amount} para ${merchant} - ${date}`, flipAmountSign: 'Invertir el signo del monto', importButton: 'Importar transacciones', }, + assignNewCards: { + title: 'Asignar nuevas tarjetas', + description: 'Obtén las últimas tarjetas para asignar desde tu banco', + }, }, expensifyCard: { issueAndManageCards: 'Emitir y gestionar Tarjetas Expensify', diff --git a/src/languages/fr.ts b/src/languages/fr.ts index eb5d60de345c..05b0caeb904f 100644 --- a/src/languages/fr.ts +++ b/src/languages/fr.ts @@ -5141,6 +5141,7 @@ _Pour des instructions plus détaillées, [visitez notre site d’aide](${CONST. flipAmountSign: 'Inverser le signe du montant', importButton: 'Importer des transactions', }, + assignNewCards: {title: 'Assigner de nouvelles cartes', description: 'Obtenez les dernières cartes à assigner depuis votre banque'}, }, expensifyCard: { issueAndManageCards: 'Émettre et gérer vos Cartes Expensify', diff --git a/src/languages/it.ts b/src/languages/it.ts index 4bdd413a9969..0f38d291a5af 100644 --- a/src/languages/it.ts +++ b/src/languages/it.ts @@ -5112,6 +5112,7 @@ _Per istruzioni più dettagliate, [visita il nostro sito di assistenza](${CONST. flipAmountSign: 'Inverti segno importo', importButton: 'Importa transazioni', }, + assignNewCards: {title: 'Assegna nuove carte', description: 'Ottieni le ultime carte da assegnare dalla tua banca'}, }, expensifyCard: { issueAndManageCards: 'Emetti e gestisci le tue Carte Expensify', diff --git a/src/languages/ja.ts b/src/languages/ja.ts index cd4bdd0436f7..9c18afaef79c 100644 --- a/src/languages/ja.ts +++ b/src/languages/ja.ts @@ -5064,6 +5064,7 @@ _詳しい手順については、[ヘルプサイトをご覧ください](${CO flipAmountSign: '金額の符号を反転', importButton: '取引をインポート', }, + assignNewCards: {title: '新しいカードを割り当てる', description: '銀行から割り当て可能な最新のカードを取得します'}, }, expensifyCard: { issueAndManageCards: 'Expensify カードを発行して管理する', diff --git a/src/languages/nl.ts b/src/languages/nl.ts index 9fdc172edb62..ee74081d515d 100644 --- a/src/languages/nl.ts +++ b/src/languages/nl.ts @@ -5103,6 +5103,7 @@ _Voor meer gedetailleerde instructies, [bezoek onze help-site](${CONST.NETSUITE_ flipAmountSign: 'Teken van bedrag omdraaien', importButton: 'Transacties importeren', }, + assignNewCards: {title: 'Nieuwe kaarten toewijzen', description: 'Haal de nieuwste kaarten op om toe te wijzen vanuit je bank'}, }, expensifyCard: { issueAndManageCards: 'Geef Expensify Kaarten uit en beheer ze', diff --git a/src/languages/pl.ts b/src/languages/pl.ts index 6442e4e4114b..92dc061eea37 100644 --- a/src/languages/pl.ts +++ b/src/languages/pl.ts @@ -5095,6 +5095,7 @@ _Aby uzyskać bardziej szczegółowe instrukcje, [odwiedź naszą stronę pomocy flipAmountSign: 'Odwróć znak kwoty', importButton: 'Importuj transakcje', }, + assignNewCards: {title: 'Przydziel nowe karty', description: 'Pobierz z banku najnowsze karty do przypisania'}, }, expensifyCard: { issueAndManageCards: 'Wydawaj i zarządzaj Kartami Expensify', diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts index 2490879e2dd9..28b41821322a 100644 --- a/src/languages/pt-BR.ts +++ b/src/languages/pt-BR.ts @@ -5095,6 +5095,7 @@ _Para instruções mais detalhadas, [visite nossa central de ajuda](${CONST.NETS flipAmountSign: 'Inverter sinal do valor', importButton: 'Importar transações', }, + assignNewCards: {title: 'Atribuir novos cartões', description: 'Obtenha do seu banco os cartões mais recentes para atribuir'}, }, expensifyCard: { issueAndManageCards: 'Emita e gerencie seus Cartões Expensify', diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts index 3c1c1ca5e3f9..e88d44d64c01 100644 --- a/src/languages/zh-hans.ts +++ b/src/languages/zh-hans.ts @@ -4984,6 +4984,7 @@ _如需更详细的说明,请[访问我们的帮助网站](${CONST.NETSUITE_IM flipAmountSign: '翻转金额符号', importButton: '导入交易', }, + assignNewCards: {title: '分配新卡', description: '从您的银行获取可分配的最新银行卡'}, }, expensifyCard: { issueAndManageCards: '发放并管理您的 Expensify 卡', diff --git a/src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx b/src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx index 338c3a655fab..0acbbe84fdc3 100644 --- a/src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx +++ b/src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx @@ -784,6 +784,8 @@ const SettingsModalStackNavigator = createModalStackNavigator require('../../../../pages/workspace/invoices/WorkspaceInvoicingDetailsWebsite').default, [SCREENS.WORKSPACE.INVOICES_VERIFY_ACCOUNT]: () => require('../../../../pages/workspace/invoices/WorkspaceInvoicesVerifyAccountPage').default, [SCREENS.WORKSPACE.COMPANY_CARDS_BROKEN_CARD_FEED_CONNECTION]: () => require('../../../../pages/workspace/companyCards/BrokenCardFeedConnectionPage').default, + [SCREENS.WORKSPACE.COMPANY_CARDS_REFRESH_CARD_FEED_CONNECTION]: () => require('../../../../pages/workspace/companyCards/RefreshCardFeedConnectionPage').default, + [SCREENS.WORKSPACE.COMPANY_CARDS_VERIFY_ACCOUNT]: () => require('../../../../pages/workspace/companyCards/WorkspaceCompanyCardsVerifyAccountPage').default, [SCREENS.WORKSPACE.COMPANY_CARDS_ASSIGN_CARD_ASSIGNEE]: () => require('../../../../pages/workspace/companyCards/assignCard/AssigneeStep').default, [SCREENS.WORKSPACE.COMPANY_CARDS_ASSIGN_CARD_CARD_SELECTION]: () => require('../../../../pages/workspace/companyCards/assignCard/CardSelectionStep').default, [SCREENS.WORKSPACE.COMPANY_CARDS_ASSIGN_CARD_TRANSACTION_START_DATE]: () => diff --git a/src/libs/Navigation/linkingConfig/config.ts b/src/libs/Navigation/linkingConfig/config.ts index 78afcc937dea..5f0bc02b09f9 100644 --- a/src/libs/Navigation/linkingConfig/config.ts +++ b/src/libs/Navigation/linkingConfig/config.ts @@ -878,6 +878,12 @@ const config: LinkingOptions['config'] = { [SCREENS.WORKSPACE.COMPANY_CARDS_BROKEN_CARD_FEED_CONNECTION]: { path: ROUTES.WORKSPACE_COMPANY_CARDS_BROKEN_CARD_FEED_CONNECTION.route, }, + [SCREENS.WORKSPACE.COMPANY_CARDS_REFRESH_CARD_FEED_CONNECTION]: { + path: ROUTES.WORKSPACE_COMPANY_CARDS_REFRESH_CARD_FEED_CONNECTION.route, + }, + [SCREENS.WORKSPACE.COMPANY_CARDS_VERIFY_ACCOUNT]: { + path: ROUTES.WORKSPACE_COMPANY_CARDS_VERIFY_ACCOUNT.route, + }, [SCREENS.WORKSPACE.COMPANY_CARDS_ASSIGN_CARD_ASSIGNEE]: { path: ROUTES.WORKSPACE_COMPANY_CARDS_ASSIGN_CARD_ASSIGNEE.route, }, diff --git a/src/libs/Navigation/types.ts b/src/libs/Navigation/types.ts index 51eca18e299d..c8618cdd5f10 100644 --- a/src/libs/Navigation/types.ts +++ b/src/libs/Navigation/types.ts @@ -1304,6 +1304,16 @@ type SettingsNavigatorParamList = { // eslint-disable-next-line no-restricted-syntax -- `backTo` usages in this file are legacy. Do not add new `backTo` params to screens. See contributingGuides/NAVIGATION.md backTo?: Routes; }; + [SCREENS.WORKSPACE.COMPANY_CARDS_REFRESH_CARD_FEED_CONNECTION]: { + policyID: string; + feed: CompanyCardFeedWithDomainID; + }; + [SCREENS.WORKSPACE.COMPANY_CARDS_VERIFY_ACCOUNT]: { + policyID: string; + + /** Present when verifying before a feed refresh; absent when verifying before adding a new feed */ + feed?: CompanyCardFeedWithDomainID; + }; [SCREENS.WORKSPACE.COMPANY_CARDS_ASSIGN_CARD_ASSIGNEE]: { policyID: string; feed: CompanyCardFeedWithDomainID; diff --git a/src/libs/actions/CompanyCards.ts b/src/libs/actions/CompanyCards.ts index c10f3cd381c3..a174690d4210 100644 --- a/src/libs/actions/CompanyCards.ts +++ b/src/libs/actions/CompanyCards.ts @@ -16,13 +16,15 @@ import type { } from '@libs/API/parameters'; import {READ_COMMANDS, WRITE_COMMANDS} from '@libs/API/types'; import * as CardUtils from '@libs/CardUtils'; -import {getCardFeedWithDomainID} from '@libs/CardUtils'; +import {getCardFeedWithDomainID, getPlaidCountry, getPlaidInstitutionId} from '@libs/CardUtils'; import * as ErrorUtils from '@libs/ErrorUtils'; +import Navigation from '@libs/Navigation/Navigation'; import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils'; import * as ReportUtils from '@libs/ReportUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Card, Policy} from '@src/types/onyx'; +import ROUTES from '@src/ROUTES'; +import type {Card, CurrencyList, Policy} from '@src/types/onyx'; import type {AssignCard, AssignCardData} from '@src/types/onyx/AssignCard'; import type { AddNewCardFeedData, @@ -48,8 +50,8 @@ type AddNewCompanyCardFlowData = { data?: Partial; }; -function setAssignCardStepAndData({cardToAssign, isEditing, currentStep}: Partial) { - Onyx.merge(ONYXKEYS.ASSIGN_CARD, {cardToAssign, isEditing, currentStep}); +function setAssignCardStepAndData({cardToAssign, isEditing, currentStep, isRefreshing}: Partial) { + Onyx.merge(ONYXKEYS.ASSIGN_CARD, {cardToAssign, isEditing, currentStep, isRefreshing}); } function setTransactionStartDate(startDate: string) { @@ -1061,6 +1063,32 @@ function clearErrorField(bankName: CompanyCardFeedWithNumber, domainAccountID: n }); } +/** + * Seeds the Onyx state required before entering the card feed refresh flow. + * Used as the onValidationSuccess callback in the verify account page, where + * VerifyAccountPageBase handles navigation separately via navigateForwardTo. + */ +function seedCardFeedRefresh(feed: CompanyCardFeedWithDomainID, outputCurrency?: string, currencyList?: CurrencyList, countryByIp?: string) { + const isPlaid = !!getPlaidInstitutionId(feed); + const currentStep = isPlaid ? CONST.COMPANY_CARD.STEP.PLAID_CONNECTION : CONST.COMPANY_CARD.STEP.BANK_CONNECTION; + + if (isPlaid) { + const country = getPlaidCountry(outputCurrency, currencyList, countryByIp); + setAddNewCompanyCardStepAndData({data: {selectedCountry: country}}); + } + + setAssignCardStepAndData({currentStep, isRefreshing: true}); +} + +/** Seeds the Onyx state and navigates to the card feed refresh flow. */ +function startCardFeedRefresh(policyID: string, feed: CompanyCardFeedWithDomainID, outputCurrency?: string, currencyList?: CurrencyList, countryByIp?: string) { + seedCardFeedRefresh(feed, outputCurrency, currencyList, countryByIp); + + Navigation.setNavigationActionToMicrotaskQueue(() => { + Navigation.navigate(ROUTES.WORKSPACE_COMPANY_CARDS_REFRESH_CARD_FEED_CONNECTION.getRoute(policyID, feed)); + }); +} + export { setWorkspaceCompanyCardFeedName, deleteWorkspaceCompanyCardFeed, @@ -1086,4 +1114,6 @@ export { setFeedStatementPeriodEndDay, clearErrorField, clearAssignCardErrors, + seedCardFeedRefresh, + startCardFeedRefresh, }; diff --git a/src/libs/actions/Plaid.ts b/src/libs/actions/Plaid.ts index 1bdd86ae8f82..8767997b1a49 100644 --- a/src/libs/actions/Plaid.ts +++ b/src/libs/actions/Plaid.ts @@ -141,7 +141,24 @@ function importPlaidAccounts( plaidAccessToken, }; - API.write(WRITE_COMMANDS.IMPORT_PLAID_ACCOUNTS, parameters); + const onyxData = { + successData: [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: ONYXKEYS.ASSIGN_CARD, + value: {isRefreshing: null}, + }, + ], + failureData: [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: ONYXKEYS.ASSIGN_CARD, + value: {isRefreshing: null}, + }, + ], + }; + + API.write(WRITE_COMMANDS.IMPORT_PLAID_ACCOUNTS, parameters, onyxData); } export {openPlaidBankAccountSelector, openPlaidBankLogin, openPlaidCompanyCardLogin, importPlaidAccounts}; diff --git a/src/pages/workspace/companyCards/BankConnection/index.native.tsx b/src/pages/workspace/companyCards/BankConnection/index.native.tsx index 870bc4928d32..4f79cf623cff 100644 --- a/src/pages/workspace/companyCards/BankConnection/index.native.tsx +++ b/src/pages/workspace/companyCards/BankConnection/index.native.tsx @@ -40,9 +40,12 @@ type BankConnectionProps = { /** Route params for add new card flow */ route?: PlatformStackRouteProp; + + /** Title of the header */ + title?: string; }; -function BankConnection({policyID: policyIDFromProps, feed, route}: BankConnectionProps) { +function BankConnection({policyID: policyIDFromProps, feed, route, title}: BankConnectionProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); const webViewRef = useRef(null); @@ -176,7 +179,7 @@ function BankConnection({policyID: policyIDFromProps, feed, route}: BankConnecti shouldEnableMaxHeight > diff --git a/src/pages/workspace/companyCards/BankConnection/index.tsx b/src/pages/workspace/companyCards/BankConnection/index.tsx index 79e91521b3ca..91aea689d9ae 100644 --- a/src/pages/workspace/companyCards/BankConnection/index.tsx +++ b/src/pages/workspace/companyCards/BankConnection/index.tsx @@ -44,9 +44,12 @@ type BankConnectionProps = { /** Route params for add new card flow */ route?: PlatformStackRouteProp; + + /** Title of the header */ + title?: string; }; -function BankConnection({policyID: policyIDFromProps, feed, route}: BankConnectionProps) { +function BankConnection({policyID: policyIDFromProps, feed, route, title}: BankConnectionProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); const [addNewCard] = useOnyx(ONYXKEYS.ADD_NEW_COMPANY_CARD); @@ -236,7 +239,7 @@ function BankConnection({policyID: policyIDFromProps, feed, route}: BankConnecti enableEdgeToEdgeBottomSafeAreaPadding > {getContent()} diff --git a/src/pages/workspace/companyCards/RefreshCardFeedConnectionPage.tsx b/src/pages/workspace/companyCards/RefreshCardFeedConnectionPage.tsx new file mode 100644 index 000000000000..057600c27d6d --- /dev/null +++ b/src/pages/workspace/companyCards/RefreshCardFeedConnectionPage.tsx @@ -0,0 +1,88 @@ +import React, {useEffect} from 'react'; +import useCardFeeds from '@hooks/useCardFeeds'; +import useLocalize from '@hooks/useLocalize'; +import useOnyx from '@hooks/useOnyx'; +import usePrevious from '@hooks/usePrevious'; +import {isDirectFeed} from '@libs/CardUtils'; +import Navigation from '@libs/Navigation/Navigation'; +import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; +import type {SettingsNavigatorParamList} from '@navigation/types'; +import NotFoundPage from '@pages/ErrorPage/NotFoundPage'; +import LoadingPage from '@pages/LoadingPage'; +import type {WithPolicyAndFullscreenLoadingProps} from '@pages/workspace/withPolicyAndFullscreenLoading'; +import withPolicyAndFullscreenLoading from '@pages/workspace/withPolicyAndFullscreenLoading'; +import {clearAssignCardStepAndData} from '@userActions/CompanyCards'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type SCREENS from '@src/SCREENS'; +import PlaidConnectionStep from './addNew/PlaidConnectionStep'; +import BankConnection from './BankConnection'; + +type RefreshCardFeedConnectionPageProps = PlatformStackScreenProps & + WithPolicyAndFullscreenLoadingProps; + +function RefreshCardFeedConnectionPage({route, policy}: RefreshCardFeedConnectionPageProps) { + const feed = route.params?.feed; + const policyID = policy?.id; + + const {translate} = useLocalize(); + + const [assignCard] = useOnyx(ONYXKEYS.ASSIGN_CARD); + const currentStep = assignCard?.currentStep; + const isRefreshing = assignCard?.isRefreshing; + const prevIsRefreshing = usePrevious(isRefreshing); + const title = translate('workspace.companyCards.assignNewCards.title'); + + const [cardFeeds] = useCardFeeds(policyID); + const feedExpiration = feed ? cardFeeds?.[feed]?.expiration : undefined; + const prevFeedExpiration = usePrevious(feedExpiration); + + useEffect(() => { + return () => { + clearAssignCardStepAndData(); + }; + }, []); + + // Plaid feeds: isRefreshing is cleared by importPlaidAccounts successData + useEffect(() => { + if (prevIsRefreshing !== true || isRefreshing) { + return; + } + Navigation.closeRHPFlow(); + }, [prevIsRefreshing, isRefreshing]); + + // OAuth feeds: expiration updates after bank re-authentication completes + useEffect(() => { + if (prevFeedExpiration === undefined || prevFeedExpiration === feedExpiration || !isRefreshing) { + return; + } + Navigation.closeRHPFlow(); + }, [prevFeedExpiration, feedExpiration, isRefreshing]); + + if (!isDirectFeed(feed) || !cardFeeds?.[feed] || !currentStep) { + return ; + } + + switch (currentStep) { + case CONST.COMPANY_CARD.STEP.BANK_CONNECTION: + return ( + + ); + case CONST.COMPANY_CARD.STEP.PLAID_CONNECTION: + return ( + + ); + default: + return ; + } +} + +export default withPolicyAndFullscreenLoading(RefreshCardFeedConnectionPage); diff --git a/src/pages/workspace/companyCards/WorkspaceCompanyCardFeedSelectorPage.tsx b/src/pages/workspace/companyCards/WorkspaceCompanyCardFeedSelectorPage.tsx index b41c11d73b62..55f766922240 100644 --- a/src/pages/workspace/companyCards/WorkspaceCompanyCardFeedSelectorPage.tsx +++ b/src/pages/workspace/companyCards/WorkspaceCompanyCardFeedSelectorPage.tsx @@ -1,3 +1,4 @@ +import {isUserValidatedSelector} from '@selectors/Account'; import {Str} from 'expensify-common'; import React from 'react'; import HeaderWithBackButton from '@components/HeaderWithBackButton'; @@ -49,6 +50,7 @@ function WorkspaceCompanyCardFeedSelectorPage({route}: WorkspaceCompanyCardFeedS const {translate} = useLocalize(); const [allDomains] = useOnyx(ONYXKEYS.COLLECTION.DOMAIN); + const [isUserValidated] = useOnyx(ONYXKEYS.ACCOUNT, {selector: isUserValidatedSelector}); const styles = useThemeStyles(); const illustrations = useThemeIllustrations(); const companyCardFeedIcons = useCompanyCardFeedIcons(); @@ -93,6 +95,10 @@ function WorkspaceCompanyCardFeedSelectorPage({route}: WorkspaceCompanyCardFeedS }); const onAddCardsPress = () => { + if (!isUserValidated) { + Navigation.navigate(ROUTES.WORKSPACE_COMPANY_CARDS_VERIFY_ACCOUNT.getRoute(policyID)); + return; + } clearAddNewCardFlow(); if (isBlockedToAddNewFeeds) { Navigation.navigate( diff --git a/src/pages/workspace/companyCards/WorkspaceCompanyCardPageEmptyState.tsx b/src/pages/workspace/companyCards/WorkspaceCompanyCardPageEmptyState.tsx index a987899c5aed..f3c68cd85873 100644 --- a/src/pages/workspace/companyCards/WorkspaceCompanyCardPageEmptyState.tsx +++ b/src/pages/workspace/companyCards/WorkspaceCompanyCardPageEmptyState.tsx @@ -1,3 +1,4 @@ +import {isUserValidatedSelector} from '@selectors/Account'; import React from 'react'; import {View} from 'react-native'; import {useDelegateNoAccessActions, useDelegateNoAccessState} from '@components/DelegateNoAccessModalProvider'; @@ -31,6 +32,7 @@ function WorkspaceCompanyCardPageEmptyState({policyID, shouldShowGBDisclaimer}: const {isActingAsDelegate} = useDelegateNoAccessState(); const {showDelegateNoAccessModal} = useDelegateNoAccessActions(); const [allWorkspaceCards] = useOnyx(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST); + const [isUserValidated] = useOnyx(ONYXKEYS.ACCOUNT, {selector: isUserValidatedSelector}); const policy = usePolicy(policyID); const workspaceAccountID = policy?.workspaceAccountID ?? CONST.DEFAULT_NUMBER_ID; @@ -90,6 +92,10 @@ function WorkspaceCompanyCardPageEmptyState({policyID, shouldShowGBDisclaimer}: showDelegateNoAccessModal(); return; } + if (!isUserValidated) { + Navigation.navigate(ROUTES.WORKSPACE_COMPANY_CARDS_VERIFY_ACCOUNT.getRoute(policy.id)); + return; + } clearAddNewCardFlow(); Navigation.navigate(ROUTES.WORKSPACE_COMPANY_CARDS_ADD_NEW.getRoute(policy.id)); }; diff --git a/src/pages/workspace/companyCards/WorkspaceCompanyCardsSettingsPage.tsx b/src/pages/workspace/companyCards/WorkspaceCompanyCardsSettingsPage.tsx index 655090ea74fd..078c635425c7 100644 --- a/src/pages/workspace/companyCards/WorkspaceCompanyCardsSettingsPage.tsx +++ b/src/pages/workspace/companyCards/WorkspaceCompanyCardsSettingsPage.tsx @@ -1,3 +1,4 @@ +import {isUserValidatedSelector} from '@selectors/Account'; import React, {useMemo, useState} from 'react'; import {InteractionManager, View} from 'react-native'; import ConfirmModal from '@components/ConfirmModal'; @@ -10,18 +11,20 @@ import ScrollView from '@components/ScrollView'; import Text from '@components/Text'; import useCardFeeds from '@hooks/useCardFeeds'; import useCardsList from '@hooks/useCardsList'; +import {useCurrencyListState} from '@hooks/useCurrencyList'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import usePolicy from '@hooks/usePolicy'; import useThemeStyles from '@hooks/useThemeStyles'; import {deleteWorkspaceCompanyCardFeed, setWorkspaceCompanyCardTransactionLiability} from '@libs/actions/CompanyCards'; -import {getCompanyCardFeed, getCompanyFeeds, getCustomOrFormattedFeedName, getDomainOrWorkspaceAccountID, getSelectedFeed} from '@libs/CardUtils'; +import {getCompanyCardFeed, getCompanyFeeds, getCustomOrFormattedFeedName, getDomainOrWorkspaceAccountID, getSelectedFeed, isDirectFeed} from '@libs/CardUtils'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; import type {SettingsNavigatorParamList} from '@libs/Navigation/types'; import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; import ToggleSettingOptionRow from '@pages/workspace/workflows/ToggleSettingsOptionRow'; +import {startCardFeedRefresh} from '@userActions/CompanyCards'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; @@ -43,12 +46,15 @@ function WorkspaceCompanyCardsSettingsPage({ const [cardFeeds] = useCardFeeds(policyID); const [lastSelectedFeed] = useOnyx(`${ONYXKEYS.COLLECTION.LAST_SELECTED_FEED}${policyID}`); + const [countryByIp] = useOnyx(ONYXKEYS.COUNTRY); + const [isUserValidated] = useOnyx(ONYXKEYS.ACCOUNT, {selector: isUserValidatedSelector}); + const {currencyList} = useCurrencyListState(); const selectedFeed = useMemo(() => getSelectedFeed(lastSelectedFeed, cardFeeds), [cardFeeds, lastSelectedFeed]); const feed = selectedFeed ? getCompanyCardFeed(selectedFeed) : undefined; const [cardsList] = useCardsList(selectedFeed); - const icons = useMemoizedLazyExpensifyIcons(['Trashcan'] as const); + const icons = useMemoizedLazyExpensifyIcons(['Sync', 'Trashcan'] as const); const feedName = selectedFeed ? getCustomOrFormattedFeedName(translate, feed, cardFeeds?.[selectedFeed]?.customFeedName) : undefined; const companyFeeds = getCompanyFeeds(cardFeeds); const selectedFeedData = selectedFeed ? companyFeeds[selectedFeed] : undefined; @@ -56,6 +62,7 @@ function WorkspaceCompanyCardsSettingsPage({ const isPersonal = liabilityType === CONST.COMPANY_CARDS.DELETE_TRANSACTIONS.ALLOW; const domainOrWorkspaceAccountID = getDomainOrWorkspaceAccountID(workspaceAccountID, selectedFeedData); const isPending = !!selectedFeedData?.pending; + const isDirectFeedType = isDirectFeed(feed); const statementCloseDate = useMemo(() => { if (!selectedFeedData?.statementPeriodEndDay) { return undefined; @@ -149,6 +156,23 @@ function WorkspaceCompanyCardsSettingsPage({ /> {translate('workspace.moreFeatures.companyCards.setTransactionLiabilityDescription')} + {isDirectFeedType && ( + { + if (!selectedFeed) { + return; + } + if (!isUserValidated) { + Navigation.navigate(ROUTES.WORKSPACE_COMPANY_CARDS_VERIFY_ACCOUNT.getRoute(policyID, selectedFeed)); + return; + } + startCardFeedRefresh(policyID, selectedFeed, policy?.outputCurrency, currencyList, countryByIp); + }} + /> + )} ; + +function WorkspaceCompanyCardsVerifyAccountPage({route}: WorkspaceCompanyCardsVerifyAccountPageProps) { + const {policyID, feed} = route.params; + const policy = usePolicy(policyID); + const [countryByIp] = useOnyx(ONYXKEYS.COUNTRY); + const {currencyList} = useCurrencyListState(); + + const companyCardsRoute = ROUTES.WORKSPACE_COMPANY_CARDS.getRoute(policyID); + + // Seeds Onyx state for the refresh flow; VerifyAccountPageBase handles navigation via navigateForwardTo + const onRefreshValidationSuccess = () => { + if (!feed) { + return; + } + seedCardFeedRefresh(feed, policy?.outputCurrency, currencyList, countryByIp); + }; + + if (feed) { + return ( + + ); + } + + return ( + + ); +} + +export default WorkspaceCompanyCardsVerifyAccountPage; diff --git a/src/pages/workspace/companyCards/addNew/PlaidConnectionStep.tsx b/src/pages/workspace/companyCards/addNew/PlaidConnectionStep.tsx index c6b9762af087..3af4bce12410 100644 --- a/src/pages/workspace/companyCards/addNew/PlaidConnectionStep.tsx +++ b/src/pages/workspace/companyCards/addNew/PlaidConnectionStep.tsx @@ -27,7 +27,14 @@ import type {CompanyCardFeedWithDomainID} from '@src/types/onyx'; import type {CardFeedWithNumber} from '@src/types/onyx/CardFeeds'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; -function PlaidConnectionStep({feed, policyID, onExit}: {feed?: CompanyCardFeedWithDomainID; policyID?: string; onExit?: () => void}) { +type PlaidConnectionStepProps = { + feed?: CompanyCardFeedWithDomainID; + policyID?: string; + onExit?: () => void; + title?: string; +}; + +function PlaidConnectionStep({feed, policyID, onExit, title}: PlaidConnectionStepProps) { const {translate} = useLocalize(); const styles = useThemeStyles(); const [addNewCard] = useOnyx(ONYXKEYS.ADD_NEW_COMPANY_CARD); @@ -218,7 +225,7 @@ function PlaidConnectionStep({feed, policyID, onExit}: {feed?: CompanyCardFeedWi shouldEnableMaxHeight > {isPlaidDisabled ? ( diff --git a/src/pages/workspace/withPolicy.tsx b/src/pages/workspace/withPolicy.tsx index f4ef4b7212a5..4a2e610b4e1d 100644 --- a/src/pages/workspace/withPolicy.tsx +++ b/src/pages/workspace/withPolicy.tsx @@ -53,6 +53,7 @@ type PolicyRouteName = | typeof SCREENS.WORKSPACE.RULES | typeof SCREENS.WORKSPACE.EXPENSIFY_CARD_ISSUE_NEW | typeof SCREENS.WORKSPACE.COMPANY_CARDS_BROKEN_CARD_FEED_CONNECTION + | typeof SCREENS.WORKSPACE.COMPANY_CARDS_REFRESH_CARD_FEED_CONNECTION | typeof SCREENS.WORKSPACE.ACCOUNTING.CLAIM_OFFER | typeof SCREENS.WORKSPACE.TIME_TRACKING; diff --git a/src/types/onyx/AssignCard.ts b/src/types/onyx/AssignCard.ts index 91a892733eb3..4cb7f4601893 100644 --- a/src/types/onyx/AssignCard.ts +++ b/src/types/onyx/AssignCard.ts @@ -85,6 +85,9 @@ type AssignCard = { /** Whether the card is assigning */ isAssigning?: boolean; + + /** Whether the feed connection is currently being refreshed */ + isRefreshing?: boolean; }; export type {AssignCard, AssignCardStep, AssignCardData}; diff --git a/tests/unit/RefreshCardFeedConnectionPageTest.tsx b/tests/unit/RefreshCardFeedConnectionPageTest.tsx new file mode 100644 index 000000000000..37b76556d5dd --- /dev/null +++ b/tests/unit/RefreshCardFeedConnectionPageTest.tsx @@ -0,0 +1,266 @@ +import {act, cleanup, render, screen} from '@testing-library/react-native'; +import React from 'react'; +import Onyx from 'react-native-onyx'; +import {clearAssignCardStepAndData} from '@libs/actions/CompanyCards'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import ROUTES from '@src/ROUTES'; +import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; + +// Bypass the HOC and render the inner component directly +jest.mock('@pages/workspace/withPolicyAndFullscreenLoading', () => (Component: React.ComponentType) => Component); + +const mockCloseRHPFlow = jest.fn(); + +jest.mock('@hooks/useCardFeeds', () => ({ + // eslint-disable-next-line @typescript-eslint/naming-convention + __esModule: true, + default: jest.fn(), +})); + +jest.mock('@pages/workspace/companyCards/BankConnection', () => ({ + // eslint-disable-next-line @typescript-eslint/naming-convention + __esModule: true, + // eslint-disable-next-line react/display-name + default: () => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-var-requires + const {View} = require('react-native'); + return ; + }, +})); + +jest.mock('@pages/workspace/companyCards/addNew/PlaidConnectionStep', () => ({ + // eslint-disable-next-line @typescript-eslint/naming-convention + __esModule: true, + // eslint-disable-next-line react/display-name + default: () => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-var-requires + const {View} = require('react-native'); + return ; + }, +})); + +jest.mock('@pages/LoadingPage', () => ({ + // eslint-disable-next-line @typescript-eslint/naming-convention + __esModule: true, + // eslint-disable-next-line react/display-name + default: () => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-var-requires + const {View} = require('react-native'); + return ; + }, +})); + +jest.mock('@pages/ErrorPage/NotFoundPage', () => ({ + // eslint-disable-next-line @typescript-eslint/naming-convention + __esModule: true, + // eslint-disable-next-line react/display-name + default: () => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-var-requires + const {View} = require('react-native'); + return ; + }, +})); + +jest.mock('@libs/Navigation/Navigation', () => ({ + closeRHPFlow: mockCloseRHPFlow, + navigate: jest.fn(), + goBack: jest.fn(), + setNavigationActionToMicrotaskQueue: jest.fn(), + getTopmostReportId: jest.fn(), +})); + +jest.mock('@libs/actions/CompanyCards', () => ({ + clearAssignCardStepAndData: jest.fn(), +})); + +jest.mock('@hooks/useLocalize', () => ({ + // eslint-disable-next-line @typescript-eslint/naming-convention + __esModule: true, + default: () => ({translate: (key: string) => key}), +})); + +// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-unsafe-member-access +const useCardFeeds = require('@hooks/useCardFeeds').default as jest.Mock; +// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access +const RefreshCardFeedConnectionPage = require('@pages/workspace/companyCards/RefreshCardFeedConnectionPage').default; + +const MOCK_FEED = 'oauth.chase_bank_card_99999' as const; +const MOCK_POLICY = {id: 'policy1'}; +const MOCK_ROUTE = {params: {feed: MOCK_FEED}}; + +describe('RefreshCardFeedConnectionPage', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + afterEach(async () => { + cleanup(); + await Onyx.clear(); + await waitForBatchedUpdates(); + jest.clearAllMocks(); + }); + + beforeEach(() => { + useCardFeeds.mockReturnValue([{[MOCK_FEED]: {expiration: '2024-01-01'}}, {status: 'loaded'}]); + }); + + it('renders NotFoundPage when currentStep is not set', async () => { + render( + , + ); + await act(async () => { + await waitForBatchedUpdates(); + }); + + expect(screen.getByTestId('NotFoundPage')).toBeTruthy(); + expect(screen.queryByTestId('BankConnection')).toBeNull(); + }); + + it('renders LoadingPage when currentStep is an unrecognized value', async () => { + await Onyx.merge(ONYXKEYS.ASSIGN_CARD, { + currentStep: 'UNKNOWN_STEP' as typeof CONST.COMPANY_CARD.STEP.BANK_CONNECTION, + isRefreshing: true, + }); + + render( + , + ); + await act(async () => { + await waitForBatchedUpdates(); + }); + + expect(screen.getByTestId('LoadingPage')).toBeTruthy(); + expect(screen.queryByTestId('BankConnection')).toBeNull(); + }); + + it('renders BankConnection when currentStep is BANK_CONNECTION', async () => { + await Onyx.merge(ONYXKEYS.ASSIGN_CARD, { + currentStep: CONST.COMPANY_CARD.STEP.BANK_CONNECTION, + isRefreshing: true, + }); + + render( + , + ); + await act(async () => { + await waitForBatchedUpdates(); + }); + + expect(screen.getByTestId('BankConnection')).toBeTruthy(); + }); + + it('renders PlaidConnectionStep when currentStep is PLAID_CONNECTION', async () => { + await Onyx.merge(ONYXKEYS.ASSIGN_CARD, { + currentStep: CONST.COMPANY_CARD.STEP.PLAID_CONNECTION, + isRefreshing: true, + }); + + render( + , + ); + await act(async () => { + await waitForBatchedUpdates(); + }); + + expect(screen.getByTestId('PlaidConnectionStep')).toBeTruthy(); + }); + + it('closes RHP flow when Plaid isRefreshing clears after successful import', async () => { + await Onyx.merge(ONYXKEYS.ASSIGN_CARD, { + currentStep: CONST.COMPANY_CARD.STEP.PLAID_CONNECTION, + isRefreshing: true, + }); + + render( + , + ); + await act(async () => { + await waitForBatchedUpdates(); + }); + + // Simulate importPlaidAccounts successData clearing isRefreshing (Plaid path) + await act(async () => { + await Onyx.merge(ONYXKEYS.ASSIGN_CARD, {isRefreshing: null}); + await waitForBatchedUpdates(); + }); + + expect(mockCloseRHPFlow).toHaveBeenCalledTimes(1); + }); + + it('closes RHP flow when OAuth feed expiration updates while refreshing', async () => { + await Onyx.merge(ONYXKEYS.ASSIGN_CARD, { + currentStep: CONST.COMPANY_CARD.STEP.BANK_CONNECTION, + isRefreshing: true, + }); + + const {rerender} = render( + , + ); + await act(async () => { + await waitForBatchedUpdates(); + }); + + // Simulate bank re-authentication updating the feed expiration (OAuth path). + // Re-render is needed to propagate the new mock return value. + useCardFeeds.mockReturnValue([{[MOCK_FEED]: {expiration: '2025-01-01'}}, {status: 'loaded'}]); + rerender( + , + ); + await waitForBatchedUpdates(); + + expect(mockCloseRHPFlow).toHaveBeenCalledTimes(1); + }); + + it('calls clearAssignCardStepAndData on unmount', async () => { + const {unmount} = render( + , + ); + await act(async () => { + await waitForBatchedUpdates(); + }); + + unmount(); + + expect(clearAssignCardStepAndData).toHaveBeenCalledTimes(1); + }); +}); + +describe('Related route getRoute helpers', () => { + it('WORKSPACE_COMPANY_CARDS_REFRESH_CARD_FEED_CONNECTION encodes feed in URL', () => { + const result = ROUTES.WORKSPACE_COMPANY_CARDS_REFRESH_CARD_FEED_CONNECTION.getRoute('pol1', 'oauth.chase 99999' as never); + expect(result).toBe('workspaces/pol1/company-cards/oauth.chase%2099999/refresh-card-feed-connection'); + }); + + it('WORKSPACE_COMPANY_CARDS_VERIFY_ACCOUNT returns route without feed when omitted', () => { + expect(ROUTES.WORKSPACE_COMPANY_CARDS_VERIFY_ACCOUNT.getRoute('pol1')).toBe('workspaces/pol1/company-cards/verify-account'); + }); + + it('WORKSPACE_COMPANY_CARDS_VERIFY_ACCOUNT returns route with encoded feed when provided', () => { + expect(ROUTES.WORKSPACE_COMPANY_CARDS_VERIFY_ACCOUNT.getRoute('pol1', 'oauth.amex 1001' as never)).toBe('workspaces/pol1/company-cards/verify-account?feed=oauth.amex%201001'); + }); +});