diff --git a/src/ONYXKEYS.ts b/src/ONYXKEYS.ts index d24042c76f45..6ed6bf06f807 100755 --- a/src/ONYXKEYS.ts +++ b/src/ONYXKEYS.ts @@ -987,6 +987,7 @@ const ONYXKEYS = { REPORT_ATTRIBUTES: 'reportAttributes', REPORT_TRANSACTIONS_AND_VIOLATIONS: 'reportTransactionsAndViolations', OUTSTANDING_REPORTS_BY_POLICY_ID: 'outstandingReportsByPolicyID', + NON_PERSONAL_AND_WORKSPACE_CARD_LIST: 'nonPersonalAndWorkspaceCardList', CARD_FEED_ERRORS: 'cardFeedErrors', }, @@ -1397,6 +1398,7 @@ type OnyxDerivedValuesMapping = { [ONYXKEYS.DERIVED.REPORT_ATTRIBUTES]: OnyxTypes.ReportAttributesDerivedValue; [ONYXKEYS.DERIVED.REPORT_TRANSACTIONS_AND_VIOLATIONS]: OnyxTypes.ReportTransactionsAndViolationsDerivedValue; [ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID]: OnyxTypes.OutstandingReportsByPolicyIDDerivedValue; + [ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST]: OnyxTypes.NonPersonalAndWorkspaceCardListDerivedValue; [ONYXKEYS.DERIVED.CARD_FEED_ERRORS]: OnyxTypes.CardFeedErrorsDerivedValue; }; diff --git a/src/components/EReceipt.tsx b/src/components/EReceipt.tsx index 3800de243fbc..1d7379b1605f 100644 --- a/src/components/EReceipt.tsx +++ b/src/components/EReceipt.tsx @@ -1,3 +1,4 @@ +import {filterPersonalCards} from '@selectors/Card'; import React, {useEffect, useRef} from 'react'; import {View} from 'react-native'; import useCurrencyList from '@hooks/useCurrencyList'; @@ -8,7 +9,7 @@ import useOnyx from '@hooks/useOnyx'; import useStyleUtils from '@hooks/useStyleUtils'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; -import {filterPersonalCards, getCardDescription, getCompanyCardDescription} from '@libs/CardUtils'; +import {getCardDescription, getCompanyCardDescription} from '@libs/CardUtils'; import {convertToDisplayString} from '@libs/CurrencyUtils'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import {getTransactionDetails} from '@libs/ReportUtils'; diff --git a/src/components/ReportActionItem/IssueCardMessage.tsx b/src/components/ReportActionItem/IssueCardMessage.tsx index 9adb3619602b..b15f9345f77f 100644 --- a/src/components/ReportActionItem/IssueCardMessage.tsx +++ b/src/components/ReportActionItem/IssueCardMessage.tsx @@ -1,4 +1,5 @@ import {useRoute} from '@react-navigation/native'; +import {filterPersonalCards} from '@selectors/Card'; import React from 'react'; import type {OnyxEntry} from 'react-native-onyx'; import Button from '@components/Button'; @@ -8,7 +9,6 @@ import useGetExpensifyCardFromReportAction from '@hooks/useGetExpensifyCardFromR import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import useThemeStyles from '@hooks/useThemeStyles'; -import {filterPersonalCards} from '@libs/CardUtils'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackRouteProp} from '@libs/Navigation/PlatformStackNavigation/types'; import type {ReportsSplitNavigatorParamList} from '@libs/Navigation/types'; diff --git a/src/components/ReportActionItem/MoneyRequestView.tsx b/src/components/ReportActionItem/MoneyRequestView.tsx index 08e907aa72bd..3391bb538dbb 100644 --- a/src/components/ReportActionItem/MoneyRequestView.tsx +++ b/src/components/ReportActionItem/MoneyRequestView.tsx @@ -35,7 +35,7 @@ import type {ViolationField} from '@hooks/useViolations'; import useViolations from '@hooks/useViolations'; import {initSplitExpense, updateMoneyRequestBillable, updateMoneyRequestReimbursable} from '@libs/actions/IOU/index'; import {getIsMissingAttendeesViolation} from '@libs/AttendeeUtils'; -import {filterPersonalCards, getCompanyCardDescription, mergeCardListWithWorkspaceFeeds} from '@libs/CardUtils'; +import {getCompanyCardDescription} from '@libs/CardUtils'; import {getDecodedCategoryName, isCategoryMissing} from '@libs/CategoryUtils'; import {convertToDisplayString} from '@libs/CurrencyUtils'; import DistanceRequestUtils from '@libs/DistanceRequestUtils'; @@ -231,9 +231,7 @@ function MoneyRequestView({ const targetPolicyID = updatedTransaction?.reportID ? parentReport?.policyID : policyID; const allPolicyTags = usePolicyTags(); const policyTagList = allPolicyTags?.[`${ONYXKEYS.COLLECTION.POLICY_TAGS}${targetPolicyID}`]; - const [cardList] = useOnyx(ONYXKEYS.CARD_LIST, {selector: filterPersonalCards, canBeMissing: true}); - const [companyCardList] = useOnyx(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST, {canBeMissing: true}); - const allCards = useMemo(() => mergeCardListWithWorkspaceFeeds(companyCardList ?? CONST.EMPTY_OBJECT, cardList), [companyCardList, cardList]); + const [nonPersonalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST, {canBeMissing: true}); const [transactionBackup] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION_BACKUP}${getNonEmptyStringOnyxID(linkedTransactionID)}`, {canBeMissing: true}); const transactionViolations = useTransactionViolations(transaction?.transactionID); @@ -303,7 +301,7 @@ function MoneyRequestView({ const transactionOriginalAmount = transaction && getOriginalAmountForDisplay(transaction, isExpenseReport(moneyRequestReport)); const formattedOriginalAmount = transactionOriginalAmount && transactionOriginalCurrency && convertToDisplayString(transactionOriginalAmount, transactionOriginalCurrency); const isManagedCardTransaction = isCardTransactionTransactionUtils(transaction); - const cardProgramName = getCompanyCardDescription(transaction?.cardName, transaction?.cardID, allCards); + const cardProgramName = getCompanyCardDescription(transaction?.cardName, transaction?.cardID, nonPersonalAndWorkspaceCards); const shouldShowCard = isManagedCardTransaction && cardProgramName; const taxRates = policy?.taxRates; diff --git a/src/components/Search/SearchAutocompleteList.tsx b/src/components/Search/SearchAutocompleteList.tsx index a72735b5385b..d6c4f88b1871 100644 --- a/src/components/Search/SearchAutocompleteList.tsx +++ b/src/components/Search/SearchAutocompleteList.tsx @@ -110,7 +110,7 @@ type SearchAutocompleteListProps = { allFeeds: Record | undefined; /** All cards */ - allCards: CardList; + allCards: CardList | undefined; /** Reference to the outer element */ ref?: ForwardedRef; @@ -183,7 +183,7 @@ function SearchAutocompleteList({ personalDetails, reports, allFeeds, - allCards, + allCards = CONST.EMPTY_OBJECT, ref, }: SearchAutocompleteListProps) { const styles = useThemeStyles(); diff --git a/src/components/Search/SearchPageHeader/SearchFiltersBar.tsx b/src/components/Search/SearchPageHeader/SearchFiltersBar.tsx index 73e73b81a97b..8d1bc9313f1d 100644 --- a/src/components/Search/SearchPageHeader/SearchFiltersBar.tsx +++ b/src/components/Search/SearchPageHeader/SearchFiltersBar.tsx @@ -38,7 +38,6 @@ import useThemeStyles from '@hooks/useThemeStyles'; import useWorkspaceList from '@hooks/useWorkspaceList'; import {close} from '@libs/actions/Modal'; import {handleBulkPayItemSelected, updateAdvancedFilters} from '@libs/actions/Search'; -import {filterPersonalCards, mergeCardListWithWorkspaceFeeds} from '@libs/CardUtils'; import DateUtils from '@libs/DateUtils'; import Navigation from '@libs/Navigation/Navigation'; import {getDisplayNameOrDefault} from '@libs/PersonalDetailsUtils'; @@ -106,9 +105,8 @@ function SearchFiltersBar({ const {currencyList, getCurrencySymbol} = useCurrencyList(); const [email] = useOnyx(ONYXKEYS.SESSION, {canBeMissing: true, selector: emailSelector}); - const [userCardList] = useOnyx(ONYXKEYS.CARD_LIST, {selector: filterPersonalCards, canBeMissing: true}); + const [nonPersonalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST, {canBeMissing: true}); const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {canBeMissing: true}); - const [workspaceCardFeeds] = useOnyx(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST, {canBeMissing: true}); const [allFeeds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER, {canBeMissing: true}); const {isAccountLocked, showLockedAccountModal} = useContext(LockedAccountContext); const expensifyIcons = useMemoizedLazyExpensifyIcons(['Filter', 'Columns']); @@ -137,7 +135,6 @@ function SearchFiltersBar({ })); }, [workspaces]); - const allCards = useMemo(() => mergeCardListWithWorkspaceFeeds(workspaceCardFeeds ?? CONST.EMPTY_OBJECT, userCardList), [userCardList, workspaceCardFeeds]); const selectedTransactionsKeys = useMemo(() => Object.keys(selectedTransactions ?? {}), [selectedTransactions]); const hasMultipleOutputCurrency = useMemo(() => { const policies = Object.values(allPolicies ?? {}).filter((policy): policy is Policy => isPaidGroupPolicy(policy)); @@ -199,10 +196,10 @@ function SearchFiltersBar({ const [feedOptions, feed] = useMemo(() => { const feedFilterValues = flatFilters.find((filter) => filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.FEED)?.filters?.map((filter) => filter.value); - const options = getFeedOptions(allFeeds, allCards); + const options = getFeedOptions(allFeeds, nonPersonalAndWorkspaceCards); const value = feedFilterValues ? options.filter((option) => feedFilterValues.includes(option.value)) : []; return [options, value]; - }, [flatFilters, allFeeds, allCards]); + }, [flatFilters, allFeeds, nonPersonalAndWorkspaceCards]); const [statusOptions, status] = useMemo(() => { const options = type ? getStatusOptions(translate, type.value) : []; diff --git a/src/components/Search/SearchPageHeader/SearchPageHeaderInput.tsx b/src/components/Search/SearchPageHeader/SearchPageHeaderInput.tsx index e4d910efba05..0eeaa34f1d2c 100644 --- a/src/components/Search/SearchPageHeader/SearchPageHeaderInput.tsx +++ b/src/components/Search/SearchPageHeader/SearchPageHeaderInput.tsx @@ -26,7 +26,6 @@ import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; import {navigateToAndOpenReport} from '@libs/actions/Report'; import {setSearchContext} from '@libs/actions/Search'; -import {filterPersonalCards, mergeCardListWithWorkspaceFeeds} from '@libs/CardUtils'; import Log from '@libs/Log'; import Navigation from '@libs/Navigation/Navigation'; import {getAllTaxRates} from '@libs/PolicyUtils'; @@ -62,13 +61,11 @@ function SearchPageHeaderInput({queryJSON, searchRouterListVisible, hideSearchRo const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {canBeMissing: true}); const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {canBeMissing: false}); const taxRates = useMemo(() => getAllTaxRates(policies), [policies]); - const [userCardList] = useOnyx(ONYXKEYS.CARD_LIST, {selector: filterPersonalCards, canBeMissing: true}); - const [workspaceCardFeeds] = useOnyx(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST, {canBeMissing: true}); - const allCards = useMemo(() => mergeCardListWithWorkspaceFeeds(workspaceCardFeeds ?? CONST.EMPTY_OBJECT, userCardList), [userCardList, workspaceCardFeeds]); + const [nonPersonalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST, {canBeMissing: true}); const [allFeeds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER, {canBeMissing: true}); const {inputQuery: originalInputQuery} = queryJSON; const [currentUserAccountID = -1] = useOnyx(ONYXKEYS.SESSION, {selector: accountIDSelector, canBeMissing: false}); - const queryText = buildUserReadableQueryString(queryJSON, personalDetails, reports, taxRates, allCards, allFeeds, policies, currentUserAccountID, true); + const queryText = buildUserReadableQueryString(queryJSON, personalDetails, reports, taxRates, nonPersonalAndWorkspaceCards, allFeeds, policies, currentUserAccountID, true); const [searchContext] = useOnyx(ONYXKEYS.SEARCH_CONTEXT, {canBeMissing: true}); const shouldShowQuery = searchContext?.shouldShowSearchQuery ?? false; @@ -115,9 +112,9 @@ function SearchPageHeaderInput({queryJSON, searchRouterListVisible, hideSearchRo }, [queryText, shouldShowQuery]); useEffect(() => { - const substitutionsMap = buildSubstitutionsMap(originalInputQuery, personalDetails, reports, taxRates, allCards, allFeeds, policies, currentUserAccountID); + const substitutionsMap = buildSubstitutionsMap(originalInputQuery, personalDetails, reports, taxRates, nonPersonalAndWorkspaceCards, allFeeds, policies, currentUserAccountID); setAutocompleteSubstitutions(substitutionsMap); - }, [allFeeds, allCards, originalInputQuery, personalDetails, reports, taxRates, policies, currentUserAccountID]); + }, [allFeeds, nonPersonalAndWorkspaceCards, originalInputQuery, personalDetails, reports, taxRates, policies, currentUserAccountID]); useEffect(() => { if (searchRouterListVisible) { @@ -400,7 +397,7 @@ function SearchPageHeaderInput({queryJSON, searchRouterListVisible, hideSearchRo ref={listRef} personalDetails={personalDetails} reports={reports} - allCards={allCards} + allCards={nonPersonalAndWorkspaceCards} allFeeds={allFeeds} textInputRef={textInputRef} /> @@ -475,7 +472,7 @@ function SearchPageHeaderInput({queryJSON, searchRouterListVisible, hideSearchRo shouldSubscribeToArrowKeyEvents={isAutocompleteListVisible} personalDetails={personalDetails} reports={reports} - allCards={allCards} + allCards={nonPersonalAndWorkspaceCards} allFeeds={allFeeds} textInputRef={textInputRef} /> diff --git a/src/components/Search/SearchRouter/SearchRouter.tsx b/src/components/Search/SearchRouter/SearchRouter.tsx index 023666896c5c..8bd3fbe6c7c7 100644 --- a/src/components/Search/SearchRouter/SearchRouter.tsx +++ b/src/components/Search/SearchRouter/SearchRouter.tsx @@ -1,5 +1,5 @@ import {deepEqual} from 'fast-equals'; -import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'; +import React, {useCallback, useEffect, useRef, useState} from 'react'; import type {TextInputProps} from 'react-native'; import {InteractionManager, View} from 'react-native'; import type {ValueOf} from 'type-fest'; @@ -25,7 +25,6 @@ import useOnyx from '@hooks/useOnyx'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useRootNavigationState from '@hooks/useRootNavigationState'; import useThemeStyles from '@hooks/useThemeStyles'; -import {filterPersonalCards, mergeCardListWithWorkspaceFeeds} from '@libs/CardUtils'; import {scrollToRight} from '@libs/InputUtils'; import Log from '@libs/Log'; import backHistory from '@libs/Navigation/helpers/backHistory'; @@ -73,9 +72,7 @@ function SearchRouter({onRouterClose, shouldHideInputCaret, isSearchRouterDispla const personalDetails = usePersonalDetails(); const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {canBeMissing: true}); const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {canBeMissing: true}); - const [workspaceCardFeeds] = useOnyx(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST, {canBeMissing: true}); - const [userCardList] = useOnyx(ONYXKEYS.CARD_LIST, {selector: filterPersonalCards, canBeMissing: true}); - const allCards = useMemo(() => mergeCardListWithWorkspaceFeeds(workspaceCardFeeds ?? CONST.EMPTY_OBJECT, userCardList), [userCardList, workspaceCardFeeds]); + const [nonPersonalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST, {canBeMissing: true}); const [allFeeds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER, {canBeMissing: true}); const {shouldUseNarrowLayout} = useResponsiveLayout(); const listRef = useRef(null); @@ -526,7 +523,7 @@ function SearchRouter({onRouterClose, shouldHideInputCaret, isSearchRouterDispla personalDetails={personalDetails} reports={reports} allFeeds={allFeeds} - allCards={allCards} + allCards={nonPersonalAndWorkspaceCards} /> )} {!shouldShowList && ( diff --git a/src/components/Search/SearchRouter/buildSubstitutionsMap.ts b/src/components/Search/SearchRouter/buildSubstitutionsMap.ts index 82d874cd706b..11502022c4d6 100644 --- a/src/components/Search/SearchRouter/buildSubstitutionsMap.ts +++ b/src/components/Search/SearchRouter/buildSubstitutionsMap.ts @@ -29,7 +29,7 @@ function buildSubstitutionsMap( personalDetails: PersonalDetailsList | undefined, reports: OnyxCollection, allTaxRates: Record, - cardList: CardList, + cardList: CardList | undefined, cardFeeds: OnyxCollection, policies: OnyxCollection, currentUserAccountID: number, diff --git a/src/hooks/useAdvancedSearchFilters.ts b/src/hooks/useAdvancedSearchFilters.ts index 1072798855a2..228db859d845 100644 --- a/src/hooks/useAdvancedSearchFilters.ts +++ b/src/hooks/useAdvancedSearchFilters.ts @@ -1,7 +1,6 @@ +import {filterCardsHiddenFromSearch} from '@selectors/Card'; import {emailSelector} from '@selectors/Session'; -import {useMemo} from 'react'; import type {OnyxCollection} from 'react-native-onyx'; -import {filterPersonalCards, mergeCardListWithWorkspaceFeeds} from '@libs/CardUtils'; import {getAllTaxRates, getTagNamesFromTagsLists, isPolicyFeatureEnabled} from '@libs/PolicyUtils'; import {getAllPolicyValues} from '@libs/SearchQueryUtils'; import CONST from '@src/CONST'; @@ -207,10 +206,7 @@ function useAdvancedSearchFilters() { const {localeCompare} = useLocalize(); const [searchAdvancedFilters = getEmptyObject()] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM, {canBeMissing: true}); const policyID = searchAdvancedFilters.policyID; - const [userCardList] = useOnyx(ONYXKEYS.CARD_LIST, {selector: filterPersonalCards, canBeMissing: false}); - const [workspaceCardFeeds] = useOnyx(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST, {canBeMissing: false}); - const allCards = useMemo(() => mergeCardListWithWorkspaceFeeds(workspaceCardFeeds ?? CONST.EMPTY_OBJECT, userCardList, true), [userCardList, workspaceCardFeeds]); - + const [searchCards] = useOnyx(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST, {canBeMissing: true, selector: filterCardsHiddenFromSearch}); const [policies = getEmptyObject>>()] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {canBeMissing: false}); const [allPolicyCategories = getEmptyObject>>()] = useOnyx(ONYXKEYS.COLLECTION.POLICY_CATEGORIES, { canBeMissing: false, @@ -253,7 +249,7 @@ function useAdvancedSearchFilters() { const shouldDisplayAttendeeFilter = isFeatureEnabledInPolicies(policies, CONST.POLICY.MORE_FEATURES.IS_ATTENDEE_TRACKING_ENABLED); const shouldDisplayCategoryFilter = shouldDisplayFilter(nonPersonalPolicyCategoryCount, areCategoriesEnabled, selectedPolicyCategories?.length > 0); const shouldDisplayTagFilter = shouldDisplayFilter(tagListsUnpacked.length, areTagsEnabled, !!selectedPolicyTagLists); - const shouldDisplayCardFilter = shouldDisplayFilter(Object.keys(allCards).length, areCardsEnabled); + const shouldDisplayCardFilter = shouldDisplayFilter(Object.keys(searchCards ?? {}).length, areCardsEnabled); const shouldDisplayTaxFilter = shouldDisplayFilter(Object.keys(taxRates).length, areTaxEnabled); const shouldDisplayWorkspaceFilter = workspaces.some((section) => section.data.length > 1); const shouldDisplayGroupCurrencyFilter = !!searchAdvancedFilters.groupBy; diff --git a/src/hooks/useCardFeedsForDisplay.ts b/src/hooks/useCardFeedsForDisplay.ts index 0248d41d9f6f..086eca344f36 100644 --- a/src/hooks/useCardFeedsForDisplay.ts +++ b/src/hooks/useCardFeedsForDisplay.ts @@ -1,8 +1,7 @@ import type {OnyxCollection} from 'react-native-onyx'; -import {getCardFeedsForDisplay, getCardFeedsForDisplayPerPolicy} from '@libs/CardFeedUtils'; -import {filterPersonalCards, isCustomFeed, mergeCardListWithWorkspaceFeeds} from '@libs/CardUtils'; +import {getCardFeedsForDisplayPerPolicy} from '@libs/CardFeedUtils'; +import {isCustomFeed} from '@libs/CardUtils'; import {isPaidGroupPolicy} from '@libs/PolicyUtils'; -import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {CompanyCardFeed, Policy} from '@src/types/onyx'; import useLocalize from './useLocalize'; @@ -59,13 +58,7 @@ const useCardFeedsForDisplay = () => { } } - const [userCardList] = useOnyx(ONYXKEYS.CARD_LIST, {selector: filterPersonalCards, canBeMissing: true}); - const [workspaceCardFeeds] = useOnyx(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST, {canBeMissing: true}); - const allCards = mergeCardListWithWorkspaceFeeds(workspaceCardFeeds ?? CONST.EMPTY_OBJECT, userCardList); - const expensifyCards = getCardFeedsForDisplay({}, allCards); - const defaultExpensifyCard = Object.values(expensifyCards)?.at(0); - - return {defaultCardFeed, cardFeedsByPolicy, defaultExpensifyCard}; + return {defaultCardFeed, cardFeedsByPolicy}; }; export default useCardFeedsForDisplay; diff --git a/src/hooks/useFilterFormValues.tsx b/src/hooks/useFilterFormValues.tsx index bd355d966b6d..9308005c66ad 100644 --- a/src/hooks/useFilterFormValues.tsx +++ b/src/hooks/useFilterFormValues.tsx @@ -1,3 +1,4 @@ +import {useMemo} from 'react'; import {usePersonalDetails} from '@components/OnyxListItemProvider'; import type {SearchQueryJSON} from '@components/Search/types'; import {mergeCardListWithWorkspaceFeeds} from '@libs/CardUtils'; @@ -21,8 +22,9 @@ const useFilterFormValues = (queryJSON?: SearchQueryJSON) => { const [policyCategories] = useOnyx(ONYXKEYS.COLLECTION.POLICY_CATEGORIES, {canBeMissing: true}); const [workspaceCardFeeds] = useOnyx(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST, {canBeMissing: true}); - const taxRates = getAllTaxRates(policies); - const allCards = mergeCardListWithWorkspaceFeeds(workspaceCardFeeds ?? CONST.EMPTY_OBJECT, userCardList); + // Helps to avoid unnecessary recalculations when user open report details screen. React Compiler does not provide same result. + const taxRates = useMemo(() => getAllTaxRates(policies), [policies]); + const allCards = useMemo(() => mergeCardListWithWorkspaceFeeds(workspaceCardFeeds ?? CONST.EMPTY_OBJECT, userCardList), [workspaceCardFeeds, userCardList]); const formValues = queryJSON ? buildFilterFormValuesFromQuery(queryJSON, policyCategories, policyTagsLists, currencyList, personalDetails, allCards, allReports, taxRates) diff --git a/src/hooks/useSearchTypeMenu.tsx b/src/hooks/useSearchTypeMenu.tsx index 3eeaaf89f6e9..c3b85abf6535 100644 --- a/src/hooks/useSearchTypeMenu.tsx +++ b/src/hooks/useSearchTypeMenu.tsx @@ -7,7 +7,6 @@ import {useSearchContext} from '@components/Search/SearchContext'; import type {SearchQueryJSON} from '@components/Search/types'; import ThreeDotsMenu from '@components/ThreeDotsMenu'; import {setSearchContext} from '@libs/actions/Search'; -import {filterPersonalCards, mergeCardListWithWorkspaceFeeds} from '@libs/CardUtils'; import Navigation from '@libs/Navigation/Navigation'; import {getAllTaxRates} from '@libs/PolicyUtils'; import {buildSearchQueryJSON, buildUserReadableQueryString, shouldSkipSuggestedSearchNavigation as shouldSkipSuggestedSearchNavigationForQuery} from '@libs/SearchQueryUtils'; @@ -46,8 +45,7 @@ export default function useSearchTypeMenu(queryJSON: SearchQueryJSON) { const personalDetails = usePersonalDetails(); const [reports = getEmptyObject>>()] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {canBeMissing: true}); const taxRates = getAllTaxRates(allPolicies); - const [userCardList] = useOnyx(ONYXKEYS.CARD_LIST, {selector: filterPersonalCards, canBeMissing: true}); - const [workspaceCardFeeds] = useOnyx(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST, {canBeMissing: true}); + const [nonPersonalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST, {canBeMissing: true}); const [savedSearches] = useOnyx(ONYXKEYS.SAVED_SEARCHES, {canBeMissing: true}); const [currentUserAccountID = -1] = useOnyx(ONYXKEYS.SESSION, {selector: accountIDSelector, canBeMissing: false}); const expensifyIcons = useMemoizedLazyExpensifyIcons([ @@ -65,7 +63,6 @@ export default function useSearchTypeMenu(queryJSON: SearchQueryJSON) { const [isPopoverVisible, setIsPopoverVisible] = useState(false); - const allCards = useMemo(() => mergeCardListWithWorkspaceFeeds(workspaceCardFeeds ?? CONST.EMPTY_OBJECT, userCardList), [userCardList, workspaceCardFeeds]); const [allFeeds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER, {canBeMissing: true}); const flattenedMenuItems = useMemo(() => typeMenuSections.flatMap((section) => section.menuItems), [typeMenuSections]); @@ -109,7 +106,7 @@ export default function useSearchTypeMenu(queryJSON: SearchQueryJSON) { if (savedSearchTitle === item.query) { const jsonQuery = buildSearchQueryJSON(item.query) ?? ({} as SearchQueryJSON); - savedSearchTitle = buildUserReadableQueryString(jsonQuery, personalDetails, reports, taxRates, allCards, allFeeds, allPolicies, currentUserAccountID); + savedSearchTitle = buildUserReadableQueryString(jsonQuery, personalDetails, reports, taxRates, nonPersonalAndWorkspaceCards, allFeeds, allPolicies, currentUserAccountID); } const isItemFocused = Number(key) === hash; @@ -148,7 +145,7 @@ export default function useSearchTypeMenu(queryJSON: SearchQueryJSON) { savedSearchesMenuItems: menuItems, isSavedSearchActive: savedSearchFocused, }; - }, [savedSearches, hash, getOverflowMenu, expensifyIcons.Bookmark, personalDetails, reports, taxRates, allCards, allFeeds, allPolicies, currentUserAccountID]); + }, [savedSearches, hash, getOverflowMenu, expensifyIcons.Bookmark, personalDetails, reports, taxRates, nonPersonalAndWorkspaceCards, allFeeds, allPolicies, currentUserAccountID]); const activeItemIndex = useMemo(() => { // If we have a suggested search, then none of the menu items are active diff --git a/src/hooks/useSearchTypeMenuSections.ts b/src/hooks/useSearchTypeMenuSections.ts index ba142357dbba..005e64ee03d9 100644 --- a/src/hooks/useSearchTypeMenuSections.ts +++ b/src/hooks/useSearchTypeMenuSections.ts @@ -1,3 +1,4 @@ +import {defaultExpensifyCardSelector} from '@selectors/Card'; import {createPoliciesSelector} from '@selectors/Policy'; import {useCallback, useEffect, useMemo, useState} from 'react'; import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; @@ -39,12 +40,15 @@ const currentUserLoginAndAccountIDSelector = (session: OnyxEntry) => ({ email: session?.email, accountID: session?.accountID, }); + /** * Get a list of all search groupings, along with their search items. Also returns the * currently focused search, based on the hash */ const useSearchTypeMenuSections = () => { - const {defaultCardFeed, cardFeedsByPolicy, defaultExpensifyCard} = useCardFeedsForDisplay(); + const [defaultExpensifyCard] = useOnyx(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST, {canBeMissing: true, selector: defaultExpensifyCardSelector}); + + const {defaultCardFeed, cardFeedsByPolicy} = useCardFeedsForDisplay(); const icons = useMemoizedLazyExpensifyIcons(['Document', 'Pencil', 'ThumbsUp']); const {isOffline} = useNetwork(); diff --git a/src/libs/CardFeedUtils.ts b/src/libs/CardFeedUtils.ts index d2bc5e88d16a..9186fee79a9f 100644 --- a/src/libs/CardFeedUtils.ts +++ b/src/libs/CardFeedUtils.ts @@ -432,7 +432,7 @@ const generateSelectedCards = ( * * The `allCards` parameter is only used to determine if we should add the "Expensify Card" feeds. */ -function getCardFeedsForDisplay(allCardFeeds: OnyxCollection, allCards: CardList): CardFeedsForDisplay { +function getCardFeedsForDisplay(allCardFeeds: OnyxCollection, allCards: CardList | undefined): CardFeedsForDisplay { const cardFeedsForDisplay = {} as CardFeedsForDisplay; for (const [domainKey, cardFeeds] of Object.entries(allCardFeeds ?? {})) { @@ -460,7 +460,7 @@ function getCardFeedsForDisplay(allCardFeeds: OnyxCollection, allCard } } - for (const card of Object.values(allCards)) { + for (const card of Object.values(allCards ?? {})) { if (card.bank !== CONST.EXPENSIFY_CARD.BANK || !card.fundID) { continue; } diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index ca1fad5c377d..1fb4da2007b2 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -142,10 +142,10 @@ function isCardClosed(card: Card) { return card?.state === CONST.EXPENSIFY_CARD.STATE.CLOSED; } -function mergeCardListWithWorkspaceFeeds(workspaceFeeds: Record, cardList: CardList | undefined, shouldExcludeCardHiddenFromSearch = false) { +function mergeCardListWithWorkspaceFeeds(workspaceFeeds: Record, cardList: CardList | undefined, shouldFilterOutPersonalCards = false) { const feedCards: CardList = {}; for (const card of Object.values(cardList ?? {})) { - if (!isCard(card) || (shouldExcludeCardHiddenFromSearch && isCardHiddenFromSearch(card))) { + if (!isCard(card) || (shouldFilterOutPersonalCards && !isPersonalCard(card))) { continue; } @@ -154,7 +154,7 @@ function mergeCardListWithWorkspaceFeeds(workspaceFeeds: Record isPersonalCard(card)); -} - type SplitMaskedCardNumberResult = { firstDigits?: string; lastDigits?: string; @@ -941,7 +934,6 @@ export { getCompanyCardFeed, getCompanyCardFeedWithDomainID, getEligibleBankAccountsForUkEuCard, - filterPersonalCards, isPersonalCard, COMPANY_CARD_FEED_ICON_NAMES, COMPANY_CARD_BANK_ICON_NAMES, diff --git a/src/libs/SearchQueryUtils.ts b/src/libs/SearchQueryUtils.ts index 6c030db4568a..255d7c8f1e25 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -768,7 +768,7 @@ function buildFilterFormValuesFromQuery( policyTags: OnyxCollection, currencyList: OnyxTypes.CurrencyList, personalDetails: OnyxTypes.PersonalDetailsList | undefined, - cardList: OnyxTypes.CardList, + cardList: OnyxTypes.CardList | undefined, reports: OnyxCollection, taxRates: Record, ) { @@ -814,7 +814,7 @@ function buildFilterFormValuesFromQuery( ); } if (filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.CARD_ID) { - filtersForm[key as typeof filterKey] = filterValues.filter((card) => cardList[card]); + filtersForm[key as typeof filterKey] = filterValues.filter((card) => cardList?.[card]); } if (filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.FEED) { filtersForm[key as typeof filterKey] = filterValues.filter((feed) => feed); @@ -1042,7 +1042,7 @@ function getFilterDisplayValue( filterValue: string, personalDetails: OnyxTypes.PersonalDetailsList | undefined, reports: OnyxCollection, - cardList: OnyxTypes.CardList, + cardList: OnyxTypes.CardList | undefined, cardFeeds: OnyxCollection, policies: OnyxCollection, currentUserAccountID: number, @@ -1092,7 +1092,7 @@ function getDisplayQueryFiltersForKey( personalDetails: OnyxTypes.PersonalDetailsList | undefined, reports: OnyxCollection, taxRates: Record, - cardList: OnyxTypes.CardList, + cardList: OnyxTypes.CardList | undefined, cardFeeds: OnyxCollection, policies: OnyxCollection, currentUserAccountID: number, @@ -1227,7 +1227,7 @@ function buildUserReadableQueryString( PersonalDetails: OnyxTypes.PersonalDetailsList | undefined, reports: OnyxCollection, taxRates: Record, - cardList: OnyxTypes.CardList, + cardList: OnyxTypes.CardList | undefined, cardFeeds: OnyxCollection, policies: OnyxCollection, currentUserAccountID: number, diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts index c6d9e447daa7..b1b1e35d1593 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -3159,7 +3159,7 @@ function getGroupCurrencyOptions(currencyList: OnyxTypes.CurrencyList, getCurren ); } -function getFeedOptions(allCardFeeds: OnyxCollection, allCards: OnyxTypes.CardList) { +function getFeedOptions(allCardFeeds: OnyxCollection, allCards: OnyxTypes.CardList | undefined) { return Object.values(getCardFeedsForDisplay(allCardFeeds, allCards)).map>((cardFeed) => ({ text: cardFeed.name, value: cardFeed.id, diff --git a/src/libs/actions/OnyxDerived/ONYX_DERIVED_VALUES.ts b/src/libs/actions/OnyxDerived/ONYX_DERIVED_VALUES.ts index 19b2735be76d..af219af05716 100644 --- a/src/libs/actions/OnyxDerived/ONYX_DERIVED_VALUES.ts +++ b/src/libs/actions/OnyxDerived/ONYX_DERIVED_VALUES.ts @@ -1,6 +1,7 @@ import type {ValueOf} from 'type-fest'; import ONYXKEYS from '@src/ONYXKEYS'; import cardFeedErrorsConfig from './configs/cardFeedErrors'; +import nonPersonalAndWorkspaceCardListConfig from './configs/nonPersonalAndWorkspaceCardList'; import outstandingReportsByPolicyIDConfig from './configs/outstandingReportsByPolicyID'; import reportAttributesConfig from './configs/reportAttributes'; import reportTransactionsAndViolationsConfig from './configs/reportTransactionsAndViolations'; @@ -14,6 +15,7 @@ const ONYX_DERIVED_VALUES = { [ONYXKEYS.DERIVED.REPORT_ATTRIBUTES]: reportAttributesConfig, [ONYXKEYS.DERIVED.REPORT_TRANSACTIONS_AND_VIOLATIONS]: reportTransactionsAndViolationsConfig, [ONYXKEYS.DERIVED.OUTSTANDING_REPORTS_BY_POLICY_ID]: outstandingReportsByPolicyIDConfig, + [ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST]: nonPersonalAndWorkspaceCardListConfig, [ONYXKEYS.DERIVED.CARD_FEED_ERRORS]: cardFeedErrorsConfig, } as const satisfies { // eslint-disable-next-line @typescript-eslint/no-explicit-any diff --git a/src/libs/actions/OnyxDerived/configs/nonPersonalAndWorkspaceCardList.ts b/src/libs/actions/OnyxDerived/configs/nonPersonalAndWorkspaceCardList.ts new file mode 100644 index 000000000000..0bd8118e2293 --- /dev/null +++ b/src/libs/actions/OnyxDerived/configs/nonPersonalAndWorkspaceCardList.ts @@ -0,0 +1,17 @@ +import {mergeCardListWithWorkspaceFeeds} from '@libs/CardUtils'; +import createOnyxDerivedValueConfig from '@userActions/OnyxDerived/createOnyxDerivedValueConfig'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {CardList} from '@src/types/onyx'; + +export default createOnyxDerivedValueConfig({ + key: ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST, + dependencies: [ONYXKEYS.CARD_LIST, ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST], + compute: ([cardList, workspaceCardFeeds], {areAllConnectionsSet, currentValue}) => { + if (!areAllConnectionsSet) { + return currentValue ?? (CONST.EMPTY_OBJECT as CardList); + } + + return mergeCardListWithWorkspaceFeeds(workspaceCardFeeds ?? CONST.EMPTY_OBJECT, cardList, true); + }, +}); diff --git a/src/pages/Search/AdvancedSearchFilters.tsx b/src/pages/Search/AdvancedSearchFilters.tsx index 9873883e84d6..ba254dd159d3 100644 --- a/src/pages/Search/AdvancedSearchFilters.tsx +++ b/src/pages/Search/AdvancedSearchFilters.tsx @@ -1,3 +1,4 @@ +import {filterCardsHiddenFromSearch} from '@selectors/Card'; import {emailSelector} from '@selectors/Session'; import React, {useMemo} from 'react'; import {View} from 'react-native'; @@ -23,7 +24,7 @@ import type {WorkspaceListItem} from '@hooks/useWorkspaceList'; import useWorkspaceList from '@hooks/useWorkspaceList'; import {saveSearch} from '@libs/actions/Search'; import {createCardFeedKey, getCardFeedKey, getCardFeedNamesWithType, getWorkspaceCardFeedKey} from '@libs/CardFeedUtils'; -import {filterPersonalCards, getCardDescription, mergeCardListWithWorkspaceFeeds} from '@libs/CardUtils'; +import {getCardDescription} from '@libs/CardUtils'; import {convertToDisplayStringWithoutCurrency} from '@libs/CurrencyUtils'; import Navigation from '@libs/Navigation/Navigation'; import {createDisplayName} from '@libs/PersonalDetailsUtils'; @@ -270,10 +271,10 @@ function getFilterWorkspaceDisplayTitle(filters: SearchAdvancedFiltersForm, poli .join(', '); } -function getFilterCardDisplayTitle(filters: Partial, cards: CardList, translate: LocaleContextProps['translate']) { +function getFilterCardDisplayTitle(filters: Partial, cards: CardList | undefined, translate: LocaleContextProps['translate']) { const cardIdsFilter = filters[CONST.SEARCH.SYNTAX_FILTER_KEYS.CARD_ID] ?? []; const feedFilter = filters[CONST.SEARCH.SYNTAX_FILTER_KEYS.FEED] ?? []; - const workspaceCardFeeds = Object.entries(cards).reduce>((workspaceCardsFeed, [cardID, card]) => { + const workspaceCardFeeds = Object.entries(cards ?? {}).reduce>((workspaceCardsFeed, [cardID, card]) => { const feedKey = `${createCardFeedKey(card.fundID, card.bank)}`; const workspaceFeedKey = getWorkspaceCardFeedKey(feedKey); /* eslint-disable no-param-reassign */ @@ -288,7 +289,7 @@ function getFilterCardDisplayTitle(filters: Partial, translate, }); - const cardNames = Object.values(cards) + const cardNames = Object.values(cards ?? {}) .filter((card) => cardIdsFilter.includes(card.cardID.toString()) && !feedFilter.includes(createCardFeedKey(card.fundID, card.bank))) .map((card) => getCardDescription(card, translate)); @@ -554,9 +555,7 @@ function AdvancedSearchFilters() { const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {canBeMissing: false}); const [savedSearches] = useOnyx(ONYXKEYS.SAVED_SEARCHES, {canBeMissing: true}); const [searchAdvancedFilters = getEmptyObject()] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM, {canBeMissing: true}); - const [userCardList] = useOnyx(ONYXKEYS.CARD_LIST, {selector: filterPersonalCards, canBeMissing: false}); - const [workspaceCardFeeds] = useOnyx(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST, {canBeMissing: false}); - const allCards = useMemo(() => mergeCardListWithWorkspaceFeeds(workspaceCardFeeds ?? CONST.EMPTY_OBJECT, userCardList, true), [userCardList, workspaceCardFeeds]); + const [searchCards] = useOnyx(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST, {canBeMissing: true, selector: filterCardsHiddenFromSearch}); const personalDetails = usePersonalDetails(); const [policies = getEmptyObject>>()] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {canBeMissing: false}); @@ -615,7 +614,7 @@ function AdvancedSearchFilters() { const onPress = singleExecution(waitForNavigate(() => Navigation.navigate(baseFilterConfig[key].route))); let filterTitle; if (key === CONST.SEARCH.SYNTAX_FILTER_KEYS.CARD_ID) { - filterTitle = baseFilterConfig[key].getTitle(searchAdvancedFilters, allCards, translate); + filterTitle = baseFilterConfig[key].getTitle(searchAdvancedFilters, searchCards, translate); } else if (key === CONST.SEARCH.SYNTAX_FILTER_KEYS.TAX_RATE) { filterTitle = baseFilterConfig[key].getTitle(searchAdvancedFilters, taxRates); } else if (key === CONST.SEARCH.SYNTAX_FILTER_KEYS.EXPENSE_TYPE) { diff --git a/src/pages/Search/SearchAdvancedFiltersPage/SearchFiltersCardPage.tsx b/src/pages/Search/SearchAdvancedFiltersPage/SearchFiltersCardPage.tsx index 0305b0ac4bb2..6962976b52d8 100644 --- a/src/pages/Search/SearchAdvancedFiltersPage/SearchFiltersCardPage.tsx +++ b/src/pages/Search/SearchAdvancedFiltersPage/SearchFiltersCardPage.tsx @@ -1,3 +1,4 @@ +import {filterPersonalCards} from '@selectors/Card'; import React, {useCallback, useEffect, useMemo, useState} from 'react'; import {View} from 'react-native'; import HeaderWithBackButton from '@components/HeaderWithBackButton'; @@ -16,7 +17,6 @@ import useThemeStyles from '@hooks/useThemeStyles'; import {updateAdvancedFilters} from '@libs/actions/Search'; import type {CardFilterItem} from '@libs/CardFeedUtils'; import {buildCardFeedsData, buildCardsData, generateSelectedCards, getDomainFeedData, getSelectedCardsFromFeeds} from '@libs/CardFeedUtils'; -import {filterPersonalCards} from '@libs/CardUtils'; import Navigation from '@navigation/Navigation'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; diff --git a/src/pages/Search/SearchTypeMenu.tsx b/src/pages/Search/SearchTypeMenu.tsx index d58ad796ebad..8ec3bf897034 100644 --- a/src/pages/Search/SearchTypeMenu.tsx +++ b/src/pages/Search/SearchTypeMenu.tsx @@ -23,7 +23,6 @@ import useSingleExecution from '@hooks/useSingleExecution'; import useSuggestedSearchDefaultNavigation from '@hooks/useSuggestedSearchDefaultNavigation'; import useThemeStyles from '@hooks/useThemeStyles'; import {setSearchContext} from '@libs/actions/Search'; -import {filterPersonalCards, mergeCardListWithWorkspaceFeeds} from '@libs/CardUtils'; import Navigation from '@libs/Navigation/Navigation'; import {getAllTaxRates} from '@libs/PolicyUtils'; import {buildSearchQueryJSON, buildUserReadableQueryString, shouldSkipSuggestedSearchNavigation as shouldSkipSuggestedSearchNavigationForQuery} from '@libs/SearchQueryUtils'; @@ -74,9 +73,7 @@ function SearchTypeMenu({queryJSON}: SearchTypeMenuProps) { const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {canBeMissing: true}); const personalDetails = usePersonalDetails(); const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {canBeMissing: true}); - const [userCardList] = useOnyx(ONYXKEYS.CARD_LIST, {selector: filterPersonalCards, canBeMissing: true}); - const [workspaceCardFeeds] = useOnyx(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST, {canBeMissing: true}); - const allCards = useMemo(() => mergeCardListWithWorkspaceFeeds(workspaceCardFeeds ?? CONST.EMPTY_OBJECT, userCardList), [userCardList, workspaceCardFeeds]); + const [nonPersonalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST, {canBeMissing: true}); const [allFeeds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER, {canBeMissing: true}); const taxRates = getAllTaxRates(allPolicies); const [currentUserAccountID = -1] = useOnyx(ONYXKEYS.SESSION, {selector: accountIDSelector, canBeMissing: false}); @@ -101,7 +98,7 @@ function SearchTypeMenu({queryJSON}: SearchTypeMenuProps) { let title = item.name; if (title === item.query) { const jsonQuery = buildSearchQueryJSON(item.query) ?? ({} as SearchQueryJSON); - title = buildUserReadableQueryString(jsonQuery, personalDetails, reports, taxRates, allCards, allFeeds, allPolicies, currentUserAccountID); + title = buildUserReadableQueryString(jsonQuery, personalDetails, reports, taxRates, nonPersonalAndWorkspaceCards, allFeeds, allPolicies, currentUserAccountID); } const isItemFocused = Number(key) === hash; @@ -146,7 +143,7 @@ function SearchTypeMenu({queryJSON}: SearchTypeMenuProps) { personalDetails, reports, taxRates, - allCards, + nonPersonalAndWorkspaceCards, allFeeds, currentUserAccountID, allPolicies, diff --git a/src/pages/settings/InitialSettingsPage.tsx b/src/pages/settings/InitialSettingsPage.tsx index 45eb5373f7fa..ee42d4466900 100755 --- a/src/pages/settings/InitialSettingsPage.tsx +++ b/src/pages/settings/InitialSettingsPage.tsx @@ -1,4 +1,5 @@ import {findFocusedRoute, useNavigationState, useRoute} from '@react-navigation/native'; +import {filterPersonalCards} from '@selectors/Card'; import {differenceInDays} from 'date-fns'; import {stopLocationUpdatesAsync} from 'expo-location'; import React, {useContext, useEffect, useLayoutEffect, useRef, useState} from 'react'; @@ -36,7 +37,7 @@ import useThemeStyles from '@hooks/useThemeStyles'; import {resetExitSurveyForm} from '@libs/actions/ExitSurvey'; import {closeReactNativeApp} from '@libs/actions/HybridApp'; import {hasPartiallySetupBankAccount} from '@libs/BankAccountUtils'; -import {filterPersonalCards, hasPendingExpensifyCardAction} from '@libs/CardUtils'; +import {hasPendingExpensifyCardAction} from '@libs/CardUtils'; import {convertToDisplayString} from '@libs/CurrencyUtils'; import useIsSidebarRouteActive from '@libs/Navigation/helpers/useIsSidebarRouteActive'; import Navigation from '@libs/Navigation/Navigation'; diff --git a/src/pages/settings/Wallet/ActivatePhysicalCardPageBase.tsx b/src/pages/settings/Wallet/ActivatePhysicalCardPageBase.tsx index 5a37c60b378f..9a97e935cd69 100644 --- a/src/pages/settings/Wallet/ActivatePhysicalCardPageBase.tsx +++ b/src/pages/settings/Wallet/ActivatePhysicalCardPageBase.tsx @@ -1,3 +1,4 @@ +import {filterPersonalCards} from '@selectors/Card'; import React, {useCallback, useEffect, useRef, useState} from 'react'; import {View} from 'react-native'; import Button from '@components/Button'; @@ -13,7 +14,6 @@ import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; import {activatePhysicalExpensifyCard, clearCardListErrors} from '@libs/actions/Card'; -import {filterPersonalCards} from '@libs/CardUtils'; import {getLatestErrorMessage} from '@libs/ErrorUtils'; import Navigation from '@libs/Navigation/Navigation'; import NotFoundPage from '@pages/ErrorPage/NotFoundPage'; diff --git a/src/pages/settings/Wallet/ExpensifyCardPage/ExpensifyCardContextProvider.tsx b/src/pages/settings/Wallet/ExpensifyCardPage/ExpensifyCardContextProvider.tsx index 0568ca3781ea..a1b089abcc80 100644 --- a/src/pages/settings/Wallet/ExpensifyCardPage/ExpensifyCardContextProvider.tsx +++ b/src/pages/settings/Wallet/ExpensifyCardPage/ExpensifyCardContextProvider.tsx @@ -1,7 +1,7 @@ +import {filterPersonalCards} from '@selectors/Card'; import type {PropsWithChildren} from 'react'; import React, {createContext, useEffect, useMemo, useState} from 'react'; import useOnyx from '@hooks/useOnyx'; -import {filterPersonalCards} from '@libs/CardUtils'; import ONYXKEYS from '@src/ONYXKEYS'; import type {CardList, ExpensifyCardDetails} from '@src/types/onyx/Card'; import type {Errors} from '@src/types/onyx/OnyxCommon'; diff --git a/src/pages/settings/Wallet/ExpensifyCardPage/index.tsx b/src/pages/settings/Wallet/ExpensifyCardPage/index.tsx index df4fbbbfbc0d..f83432493727 100644 --- a/src/pages/settings/Wallet/ExpensifyCardPage/index.tsx +++ b/src/pages/settings/Wallet/ExpensifyCardPage/index.tsx @@ -1,4 +1,5 @@ import {useFocusEffect} from '@react-navigation/native'; +import {filterPersonalCards} from '@selectors/Card'; import React, {useCallback, useContext, useEffect, useMemo, useState} from 'react'; import {View} from 'react-native'; import type {OnyxEntry} from 'react-native-onyx'; @@ -23,7 +24,7 @@ import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import useThemeStyles from '@hooks/useThemeStyles'; import {resetValidateActionCodeSent} from '@libs/actions/User'; -import {filterPersonalCards, formatCardExpiration, getDomainCards, maskCard, maskPin} from '@libs/CardUtils'; +import {formatCardExpiration, getDomainCards, maskCard, maskPin} from '@libs/CardUtils'; import {convertToDisplayString, getCurrencyKeyByCountryCode} from '@libs/CurrencyUtils'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; diff --git a/src/pages/settings/Wallet/PaymentMethodList.tsx b/src/pages/settings/Wallet/PaymentMethodList.tsx index 2ddcf6dd0788..0eb1b3b2ba56 100644 --- a/src/pages/settings/Wallet/PaymentMethodList.tsx +++ b/src/pages/settings/Wallet/PaymentMethodList.tsx @@ -1,4 +1,5 @@ import {isUserValidatedSelector} from '@selectors/Account'; +import {filterPersonalCards} from '@selectors/Card'; import {FlashList} from '@shopify/flash-list'; import lodashSortBy from 'lodash/sortBy'; import type {ReactElement} from 'react'; @@ -21,7 +22,6 @@ import useOnyx from '@hooks/useOnyx'; import useThemeIllustrations from '@hooks/useThemeIllustrations'; import useThemeStyles from '@hooks/useThemeStyles'; import { - filterPersonalCards, getAssignedCardSortKey, getCardFeedIcon, getCompanyCardFeedWithDomainID, diff --git a/src/pages/settings/Wallet/ReportCardLostPage.tsx b/src/pages/settings/Wallet/ReportCardLostPage.tsx index 7655eefe8c6b..d3589a900fae 100644 --- a/src/pages/settings/Wallet/ReportCardLostPage.tsx +++ b/src/pages/settings/Wallet/ReportCardLostPage.tsx @@ -1,3 +1,4 @@ +import {filterPersonalCards} from '@selectors/Card'; import React, {useEffect, useState} from 'react'; import {View} from 'react-native'; import FormAlertWithSubmitButton from '@components/FormAlertWithSubmitButton'; @@ -12,7 +13,6 @@ import useSafeAreaPaddings from '@hooks/useSafeAreaPaddings'; import useThemeStyles from '@hooks/useThemeStyles'; import type {ReplacementReason} from '@libs/actions/Card'; import {setErrors} from '@libs/actions/FormActions'; -import {filterPersonalCards} from '@libs/CardUtils'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; import type {SettingsNavigatorParamList} from '@libs/Navigation/types'; diff --git a/src/pages/settings/Wallet/ReportVirtualCardFraudPage.tsx b/src/pages/settings/Wallet/ReportVirtualCardFraudPage.tsx index ced6c8ca7051..196b871df965 100644 --- a/src/pages/settings/Wallet/ReportVirtualCardFraudPage.tsx +++ b/src/pages/settings/Wallet/ReportVirtualCardFraudPage.tsx @@ -1,3 +1,4 @@ +import {filterPersonalCards} from '@selectors/Card'; import React, {useCallback, useEffect} from 'react'; import {View} from 'react-native'; import DelegateNoAccessWrapper from '@components/DelegateNoAccessWrapper'; @@ -8,7 +9,6 @@ import Text from '@components/Text'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import useThemeStyles from '@hooks/useThemeStyles'; -import {filterPersonalCards} from '@libs/CardUtils'; import {getLatestErrorMessage} from '@libs/ErrorUtils'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; diff --git a/src/pages/settings/Wallet/ReportVirtualCardFraudVerifyAccountPage.tsx b/src/pages/settings/Wallet/ReportVirtualCardFraudVerifyAccountPage.tsx index caf22c52115a..072a7fd046b6 100644 --- a/src/pages/settings/Wallet/ReportVirtualCardFraudVerifyAccountPage.tsx +++ b/src/pages/settings/Wallet/ReportVirtualCardFraudVerifyAccountPage.tsx @@ -1,3 +1,4 @@ +import {filterPersonalCards} from '@selectors/Card'; import React, {useEffect} from 'react'; import ValidateCodeActionContent from '@components/ValidateCodeActionModal/ValidateCodeActionContent'; import useLocalize from '@hooks/useLocalize'; @@ -5,7 +6,6 @@ import useOnyx from '@hooks/useOnyx'; import usePrevious from '@hooks/usePrevious'; import {clearCardListErrors, reportVirtualExpensifyCardFraud} from '@libs/actions/Card'; import {requestValidateCodeAction, resetValidateActionCodeSent} from '@libs/actions/User'; -import {filterPersonalCards} from '@libs/CardUtils'; import {getLatestErrorFieldForAnyField} from '@libs/ErrorUtils'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; diff --git a/src/pages/settings/Wallet/WalletPage/index.tsx b/src/pages/settings/Wallet/WalletPage/index.tsx index cb87a2b8ee83..202994673777 100644 --- a/src/pages/settings/Wallet/WalletPage/index.tsx +++ b/src/pages/settings/Wallet/WalletPage/index.tsx @@ -1,3 +1,4 @@ +import {filterPersonalCards} from '@selectors/Card'; import debounce from 'lodash/debounce'; import isEmpty from 'lodash/isEmpty'; import type {ForwardedRef, RefObject} from 'react'; @@ -30,7 +31,7 @@ import type {FormattedSelectedPaymentMethod} from '@hooks/usePaymentMethodState/ import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; -import {filterPersonalCards, maskCardNumber} from '@libs/CardUtils'; +import {maskCardNumber} from '@libs/CardUtils'; import {convertToDisplayString} from '@libs/CurrencyUtils'; import Navigation from '@libs/Navigation/Navigation'; import {formatPaymentMethods, getPaymentMethodDescription} from '@libs/PaymentUtils'; diff --git a/src/selectors/Card.ts b/src/selectors/Card.ts new file mode 100644 index 000000000000..06852c1017cf --- /dev/null +++ b/src/selectors/Card.ts @@ -0,0 +1,39 @@ +import type {OnyxEntry} from 'react-native-onyx'; +import {getCardFeedsForDisplay} from '@libs/CardFeedUtils'; +import {isCard, isCardHiddenFromSearch, isPersonalCard} from '@libs/CardUtils'; +import {filterObject} from '@libs/ObjectUtils'; +import type {CardList, NonPersonalAndWorkspaceCardListDerivedValue} from '@src/types/onyx'; + +/** + * Filter out cards that are hidden from search. + * Cards are hidden if they are not virtual and have a state that is in HIDDEN_FROM_SEARCH_STATES. + */ +const filterCardsHiddenFromSearch = (cardList: OnyxEntry): CardList => { + const filteredCardList: CardList = {}; + for (const card of Object.values(cardList ?? {})) { + if (!isCard(card) || isCardHiddenFromSearch(card)) { + continue; + } + filteredCardList[card.cardID] = card; + } + return filteredCardList; +}; + +/** + * Filter out personal cards from the card list. + * Personal cards have fundID === '0' or no fundID. + * This selector keeps non-personal cards (fundID !== '0'). + */ +const filterPersonalCards = (cards: OnyxEntry): CardList => { + return filterObject(cards ?? {}, (key, card) => isPersonalCard(card)); +}; + +/** + * Selects the Expensify Card feed from the card list and returns the first one. + */ +const defaultExpensifyCardSelector = (allCards: OnyxEntry) => { + const cards = getCardFeedsForDisplay({}, allCards); + return Object.values(cards)?.at(0); +}; + +export {filterCardsHiddenFromSearch, filterPersonalCards, defaultExpensifyCardSelector}; diff --git a/src/types/onyx/DerivedValues.ts b/src/types/onyx/DerivedValues.ts index 7d4bf828ba47..44d1df867c42 100644 --- a/src/types/onyx/DerivedValues.ts +++ b/src/types/onyx/DerivedValues.ts @@ -2,6 +2,7 @@ import type {OnyxCollection} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; import type CONST from '@src/CONST'; import type {Card} from '.'; +import type {CardList} from './Card'; import type {CompanyCardFeedWithDomainID, CompanyCardFeedWithNumber} from './CardFeeds'; import type {Errors} from './OnyxCommon'; import type Report from './Report'; @@ -199,6 +200,11 @@ type CardFeedErrors = { */ type CardFeedErrorsDerivedValue = CardFeedErrors; +/** + * The derived value for merged non-personal and workspace card feeds. + */ +type NonPersonalAndWorkspaceCardListDerivedValue = CardList; + export default ReportAttributesDerivedValue; export type { ReportAttributes, @@ -206,6 +212,7 @@ export type { ReportTransactionsAndViolationsDerivedValue, ReportTransactionsAndViolations, OutstandingReportsByPolicyIDDerivedValue, + NonPersonalAndWorkspaceCardListDerivedValue, CardFeedErrorsDerivedValue, AllCardFeedErrorsMap, CardFeedErrorsObject, diff --git a/src/types/onyx/index.ts b/src/types/onyx/index.ts index 698337f0a3f3..5f71f9a32e64 100644 --- a/src/types/onyx/index.ts +++ b/src/types/onyx/index.ts @@ -28,7 +28,13 @@ import type Credentials from './Credentials'; import type Currency from './Currency'; import type {CurrencyList} from './Currency'; import type CustomStatusDraft from './CustomStatusDraft'; -import type {CardFeedErrorsDerivedValue, OutstandingReportsByPolicyIDDerivedValue, ReportAttributesDerivedValue, ReportTransactionsAndViolationsDerivedValue} from './DerivedValues'; +import type { + CardFeedErrorsDerivedValue, + NonPersonalAndWorkspaceCardListDerivedValue, + OutstandingReportsByPolicyIDDerivedValue, + ReportAttributesDerivedValue, + ReportTransactionsAndViolationsDerivedValue, +} from './DerivedValues'; import type DismissedProductTraining from './DismissedProductTraining'; import type DismissedReferralBanners from './DismissedReferralBanners'; import type Domain from './Domain'; @@ -309,6 +315,7 @@ export type { LastSearchParams, ReportTransactionsAndViolationsDerivedValue, OutstandingReportsByPolicyIDDerivedValue, + NonPersonalAndWorkspaceCardListDerivedValue, CardFeedErrorsDerivedValue, ScheduleCallDraft, ValidateUserAndGetAccessiblePolicies, diff --git a/tests/unit/OnyxDerivedTest.tsx b/tests/unit/OnyxDerivedTest.tsx index 2ea3148a11f2..235078030fe8 100644 --- a/tests/unit/OnyxDerivedTest.tsx +++ b/tests/unit/OnyxDerivedTest.tsx @@ -13,6 +13,7 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {Report} from '@src/types/onyx'; import type {ReportActions} from '@src/types/onyx/ReportAction'; +import {createRandomCompanyCard, createRandomExpensifyCard} from '../utils/collections/card'; import {createRandomReport} from '../utils/collections/reports'; import createRandomTransaction from '../utils/collections/transaction'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; @@ -25,17 +26,22 @@ const renderLocaleContextProvider = () => { ); }; -describe('OnyxDerived', () => { - beforeAll(() => { - Onyx.init({keys: ONYXKEYS}); - initOnyxDerivedValues(); - }); +const onyxDerivedTestSetup = () => { + Onyx.clear(); + Onyx.init({keys: ONYXKEYS}); + initOnyxDerivedValues(); +}; - beforeEach(async () => { - await Onyx.clear(); +describe('OnyxDerived', () => { + beforeEach(() => { + Onyx.clear(); }); describe('reportAttributes', () => { + beforeAll(() => { + onyxDerivedTestSetup(); + }); + const mockReport: Report = { reportID: `test_1`, reportName: 'Test Report', @@ -416,4 +422,110 @@ describe('OnyxDerived', () => { }); }); }); + + describe('nonPersonalAndWorkspaceCardList', () => { + beforeAll(async () => { + onyxDerivedTestSetup(); + }); + + it('returns empty object when dependencies are not set', async () => { + await waitForBatchedUpdates(); + const derivedCardList = await OnyxUtils.get(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST); + expect(derivedCardList).toEqual({}); + }); + + it('merges cardList and workspaceCardFeeds when dependencies are set', async () => { + // Non-personal cards (fundID !== '0') from cardList are kept, workspace cards are always included + const nonPersonalCard1 = createRandomExpensifyCard(1, {fundID: '123'}); + const nonPersonalCard2 = createRandomExpensifyCard(2, {fundID: '456'}); + const workspaceCard3 = createRandomCompanyCard(3, {bank: 'vcf'}); + + await Onyx.set(ONYXKEYS.CARD_LIST, { + '1': nonPersonalCard1, + '2': nonPersonalCard2, + }); + await Onyx.set(`${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}workspace_123`, { + '3': workspaceCard3, + }); + await waitForBatchedUpdates(); + const derivedCardList = await OnyxUtils.get(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST); + + expect(derivedCardList).toMatchObject({ + '1': expect.objectContaining({cardID: 1}), + '2': expect.objectContaining({cardID: 2}), + '3': expect.objectContaining({cardID: 3}), + }); + }); + + it('filters out personal cards from cardList when dependencies are set', async () => { + const nonPersonalCard = createRandomExpensifyCard(1, {fundID: '123'}); + const personalCard = createRandomExpensifyCard(2, {fundID: '0'}); + const workspaceCard = createRandomCompanyCard(3, {bank: 'vcf'}); + + await Onyx.set(ONYXKEYS.CARD_LIST, { + '1': nonPersonalCard, + '2': personalCard, + }); + await Onyx.set(`${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}workspace_123`, { + '3': workspaceCard, + }); + await waitForBatchedUpdates(); + const derivedCardList = await OnyxUtils.get(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST); + + expect(derivedCardList?.['1']).toBeDefined(); + expect(derivedCardList?.['1']).toMatchObject({cardID: 1}); + expect(derivedCardList?.['2']).toBeUndefined(); + expect(derivedCardList?.['3']).toBeDefined(); + expect(derivedCardList?.['3']).toMatchObject({cardID: 3}); + }); + + it('handles empty cardList when workspaceCardFeeds are set', async () => { + const workspaceCard = createRandomCompanyCard(1, {bank: 'vcf'}); + + await Onyx.set(ONYXKEYS.CARD_LIST, {}); + await Onyx.set(`${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}workspace_123`, { + '1': workspaceCard, + }); + await waitForBatchedUpdates(); + const derivedCardList = await OnyxUtils.get(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST); + + expect(derivedCardList).toMatchObject({ + '1': expect.objectContaining({cardID: 1}), + }); + }); + + it('handles empty workspaceCardFeeds when cardList is set', async () => { + const nonPersonalCard = createRandomExpensifyCard(1, {fundID: '123'}); + + await Onyx.set(ONYXKEYS.CARD_LIST, { + '1': nonPersonalCard, + }); + await waitForBatchedUpdates(); + const derivedCardList = await OnyxUtils.get(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST); + + expect(derivedCardList).toMatchObject({ + '1': expect.objectContaining({cardID: 1}), + }); + }); + + it('includes cards from multiple workspace feeds when dependencies are set', async () => { + const card1 = createRandomCompanyCard(1, {bank: 'vcf'}); + const card2 = createRandomCompanyCard(2, {bank: 'stripe'}); + + await Onyx.set(ONYXKEYS.CARD_LIST, {}); + await Onyx.set(`${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}workspace_123`, { + '1': card1, + }); + await Onyx.set(`${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}workspace_456`, { + '2': card2, + }); + await waitForBatchedUpdates(); + const derivedCardList = await OnyxUtils.get(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST); + + expect(derivedCardList).toMatchObject({ + '1': expect.objectContaining({cardID: 1}), + '2': expect.objectContaining({cardID: 2}), + }); + }); + }); }); diff --git a/tests/unit/selectors/CardTest.ts b/tests/unit/selectors/CardTest.ts new file mode 100644 index 000000000000..395ce3b10da5 --- /dev/null +++ b/tests/unit/selectors/CardTest.ts @@ -0,0 +1,189 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +import {defaultExpensifyCardSelector, filterCardsHiddenFromSearch} from '@selectors/Card'; +import type {ValueOf} from 'type-fest'; +import CONST from '@src/CONST'; +import type {Card, CardList} from '@src/types/onyx'; +import createRandomCard, {createRandomCompanyCard, createRandomExpensifyCard} from '../../utils/collections/card'; + +describe('filterCardsHiddenFromSearch', () => { + it('returns empty object when cardList is undefined or empty', () => { + expect(filterCardsHiddenFromSearch(undefined)).toEqual({}); + expect(filterCardsHiddenFromSearch({})).toEqual({}); + }); + + it('keeps cards that are not hidden from search', () => { + const card1 = createRandomExpensifyCard(1, {state: CONST.EXPENSIFY_CARD.STATE.OPEN}); + const card2 = createRandomCard(2, {state: CONST.EXPENSIFY_CARD.STATE.OPEN, bank: 'vcf'}); + + const cardList: CardList = { + '1': card1, + '2': card2, + }; + + const result = filterCardsHiddenFromSearch(cardList); + + expect(result).toMatchObject({ + '1': expect.objectContaining({cardID: 1}), + '2': expect.objectContaining({cardID: 2}), + }); + }); + + it('filters out non-virtual cards with state 2 (hidden from search)', () => { + const visibleCard = createRandomExpensifyCard(1, {state: CONST.EXPENSIFY_CARD.STATE.OPEN}); + const hiddenCard = createRandomExpensifyCard(2, {state: 2 as ValueOf}); + + const cardList: CardList = { + '1': visibleCard, + '2': hiddenCard, + }; + + const result = filterCardsHiddenFromSearch(cardList); + + expect(result?.['1']).toBeDefined(); + expect(result?.['2']).toBeUndefined(); + }); + + it('filters out non-virtual cards with state 4 (hidden from search)', () => { + const visibleCard = createRandomExpensifyCard(1, {state: CONST.EXPENSIFY_CARD.STATE.OPEN}); + const hiddenCard = createRandomExpensifyCard(2, {state: 4 as ValueOf}); + + const cardList: CardList = { + '1': visibleCard, + '2': hiddenCard, + }; + + const result = filterCardsHiddenFromSearch(cardList); + + expect(result?.['1']).toBeDefined(); + expect(result?.['2']).toBeUndefined(); + }); + + it('keeps virtual cards even if they have hidden state', () => { + const virtualCardWithHiddenState = { + ...createRandomExpensifyCard(1, {state: 2 as ValueOf}), + nameValuePairs: {isVirtual: true}, + } as Card; + + const cardList: CardList = { + '1': virtualCardWithHiddenState, + }; + + const result = filterCardsHiddenFromSearch(cardList); + + expect(result?.['1']).toBeDefined(); + }); + + it('filters out invalid card objects (missing cardID or bank)', () => { + const validCard = createRandomExpensifyCard(1, {state: CONST.EXPENSIFY_CARD.STATE.OPEN}); + const invalidCard1 = {cardID: 2} as Card; + const invalidCard2 = {bank: 'vcf'} as Card; + + const cardList: CardList = { + '1': validCard, + '2': invalidCard1, + '3': invalidCard2, + }; + + const result = filterCardsHiddenFromSearch(cardList); + + expect(result?.['1']).toBeDefined(); + expect(result?.['2']).toBeUndefined(); + expect(result?.['3']).toBeUndefined(); + }); + + it('handles mixed visible and hidden cards', () => { + const visibleCard1 = createRandomExpensifyCard(1, {state: CONST.EXPENSIFY_CARD.STATE.OPEN}); + const visibleCard2 = createRandomCard(2, {state: CONST.EXPENSIFY_CARD.STATE.OPEN, bank: 'vcf', fundID: undefined}); + const hiddenCard1 = createRandomExpensifyCard(3, {state: 2 as ValueOf}); + const hiddenCard2 = createRandomExpensifyCard(4, {state: 4 as ValueOf}); + const virtualHiddenCard: Card = { + ...createRandomExpensifyCard(5, {state: 2 as ValueOf}), + nameValuePairs: {isVirtual: true} as Card['nameValuePairs'], + }; + + const cardList: CardList = { + '1': visibleCard1, + '2': visibleCard2, + '3': hiddenCard1, + '4': hiddenCard2, + '5': virtualHiddenCard, + }; + + const result = filterCardsHiddenFromSearch(cardList); + + expect(result?.['1']).toBeDefined(); + expect(result?.['2']).toBeDefined(); + expect(result?.['3']).toBeUndefined(); + expect(result?.['4']).toBeUndefined(); + expect(result?.['5']).toBeDefined(); // Virtual cards are kept even with hidden state + }); +}); + +describe('defaultExpensifyCardSelector', () => { + it('Should return undefined if allCards is undefined or empty', () => { + expect(defaultExpensifyCardSelector(undefined)).toBeUndefined(); + expect(defaultExpensifyCardSelector({})).toBeUndefined(); + }); + + it('Should return undefined if cards do not have Expensify Card bank', () => { + const allCards: CardList = { + '1': createRandomCompanyCard(1, {bank: 'vcf'}), + '2': createRandomCompanyCard(2, {bank: 'stripe'}), + }; + + expect(defaultExpensifyCardSelector(allCards)).toBeUndefined(); + }); + + it('Should return undefined if Expensify Card does not have fundID', () => { + const allCards: CardList = { + '1': createRandomExpensifyCard(1, {fundID: undefined}), + '2': createRandomExpensifyCard(2, {fundID: ''}), + }; + + expect(defaultExpensifyCardSelector(allCards)).toBeUndefined(); + }); + + it('Should return the first Expensify Card feed when multiple Expensify Cards exist', () => { + const allCards: CardList = { + '1': createRandomExpensifyCard(1, {fundID: '5555'}), + '2': createRandomExpensifyCard(2, {fundID: '6666'}), + }; + const result = defaultExpensifyCardSelector(allCards); + expect(result).toEqual({ + id: '5555_Expensify Card', + feed: CONST.EXPENSIFY_CARD.BANK, + fundID: '5555', + name: CONST.EXPENSIFY_CARD.BANK, + }); + }); + + it('Should return the first Expensify Card feed when mixed cards exist (some Expensify, some not)', () => { + const allCards: CardList = { + '1': createRandomCompanyCard(1, {bank: 'vcf'}), + '2': createRandomExpensifyCard(2, {fundID: '5555'}), + '3': createRandomExpensifyCard(3, {fundID: '6666'}), + }; + + const result = defaultExpensifyCardSelector(allCards); + expect(result).toEqual({ + id: '5555_Expensify Card', + feed: CONST.EXPENSIFY_CARD.BANK, + fundID: '5555', + name: CONST.EXPENSIFY_CARD.BANK, + }); + }); + + it('Should ignore Expensify Cards without fundID when other Expensify Cards with fundID exist', () => { + const allCards: CardList = { + '1': createRandomExpensifyCard(1, {fundID: undefined}), + '2': createRandomExpensifyCard(2, {fundID: '5555'}), + }; + const result = defaultExpensifyCardSelector(allCards); + expect(result).toEqual({ + id: '5555_Expensify Card', + feed: CONST.EXPENSIFY_CARD.BANK, + fundID: '5555', + name: CONST.EXPENSIFY_CARD.BANK, + }); + }); +}); diff --git a/tests/unit/useSearchTypeMenuSectionsTest.ts b/tests/unit/useSearchTypeMenuSectionsTest.ts index 0047d6188cd5..6cb4ba3c4f53 100644 --- a/tests/unit/useSearchTypeMenuSectionsTest.ts +++ b/tests/unit/useSearchTypeMenuSectionsTest.ts @@ -16,7 +16,7 @@ jest.mock('@userActions/Report', () => ({ createNewReport: jest.fn(() => ({reportID: 'mock-report-id'})), })); -jest.mock('@hooks/useCardFeedsForDisplay', () => jest.fn(() => ({defaultCardFeed: null, cardFeedsByPolicy: {}, defaultExpensifyCard: null}))); +jest.mock('@hooks/useCardFeedsForDisplay', () => jest.fn(() => ({defaultCardFeed: null, cardFeedsByPolicy: {}}))); jest.mock('@hooks/useCreateEmptyReportConfirmation', () => jest.fn(() => ({openCreateReportConfirmation: jest.fn(), CreateReportConfirmationModal: null}))); jest.mock('@hooks/useNetwork', () => jest.fn(() => ({isOffline: false}))); jest.mock('@hooks/usePermissions', () => jest.fn(() => ({isBetaEnabled: jest.fn(() => false)}))); diff --git a/tests/utils/collections/card.ts b/tests/utils/collections/card.ts new file mode 100644 index 000000000000..01cc89285ced --- /dev/null +++ b/tests/utils/collections/card.ts @@ -0,0 +1,97 @@ +import {rand, randAmount, randNumber, randPastDate, randWord} from '@ngneat/falso'; +import {format} from 'date-fns'; +import type {ValueOf} from 'type-fest'; +import CONST from '@src/CONST'; +import type {Card} from '@src/types/onyx'; + +export default function createRandomCard( + index: number, + options?: { + bank?: string; + fundID?: string; + state?: ValueOf; + fraud?: ValueOf; + accountID?: number; + domainName?: string; + }, +): Card { + const cardID = index > 0 ? index : randNumber(); + const bank = options?.bank ?? rand([CONST.EXPENSIFY_CARD.BANK, 'vcf', 'stripe', 'oauth.chase.com', 'oauth.capitalone.com']); + const state = options?.state ?? rand(Object.values(CONST.EXPENSIFY_CARD.STATE)); + const fraud = options?.fraud ?? rand(Object.values(CONST.EXPENSIFY_CARD.FRAUD_TYPES)); + const accountID = options?.accountID ?? randNumber(); + const domainName = options?.domainName ?? `expensify-policy${randNumber()}.exfy`; + + // Only generate fundID if not explicitly set (including undefined) and it's an Expensify Card + let fundID: string | undefined; + if (options && 'fundID' in options) { + fundID = options.fundID; + } else if (bank === CONST.EXPENSIFY_CARD.BANK) { + fundID = randNumber().toString(); + } else { + fundID = undefined; + } + + return { + cardID, + state, + bank, + domainName, + lastUpdated: format(randPastDate(), CONST.DATE.FNS_DB_FORMAT_STRING), + fraud, + availableSpend: randAmount(), + unapprovedSpend: -randAmount(), + totalSpend: -randAmount(), + lastFourPAN: randNumber().toString(), + cardName: `${randWord()}...${randNumber()}`, + fundID: bank === CONST.EXPENSIFY_CARD.BANK ? fundID : undefined, + accountID, + isLoading: false, + isLoadingLastUpdated: false, + lastScrape: format(randPastDate(), CONST.DATE.FNS_DB_FORMAT_STRING), + lastScrapeResult: randNumber(), + scrapeMinDate: format(randPastDate(), CONST.DATE.FNS_DB_FORMAT_STRING), + errors: {}, + errorFields: {}, + }; +} + +/** + * Creates a random Expensify Card (with bank === 'Expensify Card') + */ +function createRandomExpensifyCard( + index: number, + options?: { + fundID?: string; + state?: ValueOf; + fraud?: ValueOf; + accountID?: number; + domainName?: string; + }, +): Card { + return createRandomCard(index, { + ...options, + bank: CONST.EXPENSIFY_CARD.BANK, + }); +} + +/** + * Creates a random company card (non-Expensify card) + */ +function createRandomCompanyCard( + index: number, + options?: { + bank?: string; + accountID?: number; + domainName?: string; + }, +): Card { + const banks = ['vcf', 'stripe', 'oauth.chase.com', 'oauth.capitalone.com', 'oauth.citibank.com']; + return createRandomCard(index, { + ...options, + bank: options?.bank ?? rand(banks), + fundID: undefined, // Company cards don't have fundID + }); +} + +export {createRandomExpensifyCard, createRandomCompanyCard};