diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 4ac18cb26da7..2fe3759b64fa 100755 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -3555,6 +3555,7 @@ const CONST = { AMEX_FILE_DOWNLOAD: 'americanexpressfd.us', CSV: 'ccupload', MOCK_BANK: 'oauth.mockbank.com', + UPLOAD: 'upload', }, FEED_KEY_SEPARATOR: '#', CARD_NUMBER_MASK_CHAR: 'X', @@ -3659,6 +3660,13 @@ const CONST = { STRIPE: 'stripe', CSV: 'CSV', }, + CARD_TYPE_NAMES: { + AMEX: 'American Express', + VISA: 'Visa', + MASTERCARD: 'Mastercard', + STRIPE: 'Stripe', + CSV: 'CSV', + }, FEED_TYPE: { CUSTOM: 'customFeed', DIRECT: 'directFeed', @@ -3673,6 +3681,8 @@ const CONST = { STRIPE: 'Stripe', WELLS_FARGO: 'Wells Fargo', MOCK_BANK: 'Mock Bank', + PEX: 'PEX', + EXPENSIFY: 'Expensify', OTHER: 'Other', }, BANK_CONNECTIONS: { @@ -3702,9 +3712,6 @@ const CONST = { CARD_NAME: { CASH: '__CASH__', }, - BANK_NAME: { - UPLOAD: 'upload', - }, CARD_LIST_THRESHOLD: 8, DEFAULT_EXPORT_TYPE: 'default', EXPORT_CARD_TYPES: { @@ -8157,6 +8164,7 @@ const CONST = { PURE_REPORT_ACTION_ITEM: 'Report-PureReportActionItem', MODERATION_BUTTON: 'Report-ModerationButton', MONEY_REQUEST_REPORT_ACTIONS_LIST_SELECT_ALL: 'MoneyRequestReportActionsList-SelectAll', + REPORT_ACTION_AVATAR: 'Report-ReportActionAvatar', }, SIDEBAR: { SIGN_IN_BUTTON: 'Sidebar-SignInButton', @@ -8309,6 +8317,9 @@ const CONST = { WORKSPACE: { TOGGLE_SETTINGS_ROW: 'Workspace-ToggleSettingsRow', WORKSPACE_MENU_ITEM: 'Workspace-WorkspaceMenuItem', + COMPANY_CARDS: { + TABLE_ITEM: 'Workspace-CompanyCards-TableItem', + }, }, ACCOUNT_SWITCHER: { SHOW_ACCOUNTS: 'AccountSwitcher-ShowAccounts', diff --git a/src/components/CardFeedIcon.tsx b/src/components/CardFeedIcon.tsx index fc32a3745d08..425d4c9d4a3d 100644 --- a/src/components/CardFeedIcon.tsx +++ b/src/components/CardFeedIcon.tsx @@ -3,14 +3,14 @@ import {useCompanyCardFeedIcons} from '@hooks/useCompanyCardIcons'; import {useMemoizedLazyIllustrations} from '@hooks/useLazyAsset'; import useThemeIllustrations from '@hooks/useThemeIllustrations'; import {getCardFeedIcon, getPlaidInstitutionIconUrl, getPlaidInstitutionId} from '@libs/CardUtils'; -import type {CompanyCardFeed, CompanyCardFeedWithDomainID} from '@src/types/onyx'; +import type {CardFeedWithDomainID} from '@src/types/onyx'; import type {IconProps} from './Icon'; import Icon from './Icon'; import PlaidCardFeedIcon from './PlaidCardFeedIcon'; type CardFeedIconProps = { isExpensifyCardFeed?: boolean; - selectedFeed?: CompanyCardFeedWithDomainID | undefined; + selectedFeed?: CardFeedWithDomainID | undefined; iconProps?: Partial; useSkeletonLoader?: boolean; }; @@ -45,7 +45,7 @@ function CardFeedIcon({iconProps, selectedFeed, isExpensifyCardFeed = false, use return ( diff --git a/src/components/ReportActionAvatars/ReportActionAvatar.tsx b/src/components/ReportActionAvatars/ReportActionAvatar.tsx index 6650f7bdb204..aed43d750fee 100644 --- a/src/components/ReportActionAvatars/ReportActionAvatar.tsx +++ b/src/components/ReportActionAvatars/ReportActionAvatar.tsx @@ -26,7 +26,7 @@ import variables from '@styles/variables'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; -import type {CompanyCardFeed} from '@src/types/onyx'; +import type {CardFeed} from '@src/types/onyx/CardFeeds'; import type {Icon as IconType} from '@src/types/onyx/OnyxCommon'; type SortingOptions = ValueOf; @@ -96,6 +96,7 @@ function ProfileAvatar(props: Parameters[0] & {useProfileNavigati onPress={onPress} accessibilityLabel={translate(isWorkspace ? 'common.workspaces' : 'common.profile')} accessibilityRole={CONST.ROLE.BUTTON} + sentryLabel={CONST.SENTRY_LABEL.REPORT.REPORT_ACTION_AVATAR} > {/* eslint-disable-next-line react/jsx-props-no-spreading */} @@ -179,7 +180,7 @@ function ReportActionAvatarSubscript({ shouldShowTooltip: boolean; noRightMarginOnContainer?: boolean; subscriptAvatarBorderColor?: ColorValue; - subscriptCardFeed?: CompanyCardFeed | typeof CONST.EXPENSIFY_CARD.BANK; + subscriptCardFeed?: CardFeed; fallbackDisplayName?: string; useProfileNavigationWrapper?: boolean; reportID?: string; diff --git a/src/components/ReportActionAvatars/index.tsx b/src/components/ReportActionAvatars/index.tsx index 44aac0a14d73..23eb986f4a9a 100644 --- a/src/components/ReportActionAvatars/index.tsx +++ b/src/components/ReportActionAvatars/index.tsx @@ -5,7 +5,8 @@ import type {ValueOf} from 'type-fest'; import useOnyx from '@hooks/useOnyx'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {CompanyCardFeed, InvitedEmailsToAccountIDs, Policy, Report, ReportAction} from '@src/types/onyx'; +import type {InvitedEmailsToAccountIDs, Policy, Report, ReportAction} from '@src/types/onyx'; +import type {CardFeed} from '@src/types/onyx/CardFeeds'; import type {HorizontalStacking} from './ReportActionAvatar'; import ReportActionAvatar from './ReportActionAvatar'; import useReportActionAvatars from './useReportActionAvatars'; @@ -56,7 +57,7 @@ type ReportActionAvatarsProps = { subscriptAvatarBorderColor?: ColorValue; /** Subscript card feed to display instead of the second avatar */ - subscriptCardFeed?: CompanyCardFeed | typeof CONST.EXPENSIFY_CARD.BANK; + subscriptCardFeed?: CardFeed; /** Whether we want to be redirected to profile on avatars click */ useProfileNavigationWrapper?: boolean; diff --git a/src/hooks/useCardFeedsForDisplay.ts b/src/hooks/useCardFeedsForDisplay.ts index c8bdeb31b41a..762a00e43cb4 100644 --- a/src/hooks/useCardFeedsForDisplay.ts +++ b/src/hooks/useCardFeedsForDisplay.ts @@ -3,7 +3,8 @@ import {getCardFeedsForDisplayPerPolicy} from '@libs/CardFeedUtils'; import {isCustomFeed} from '@libs/CardUtils'; import {isPaidGroupPolicy} from '@libs/PolicyUtils'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {CompanyCardFeed, Policy} from '@src/types/onyx'; +import type {Policy} from '@src/types/onyx'; +import type {CardFeedWithNumber} from '@src/types/onyx/CardFeeds'; import useLocalize from './useLocalize'; import useOnyx from './useOnyx'; @@ -52,7 +53,7 @@ const useCardFeedsForDisplay = () => { // Commercial feeds don't have preferred policies, so we need to include these in the list const commercialFeeds = Object.values(cardFeedsByPolicy) .flat() - .filter((feed) => !isCustomFeed(feed.name as CompanyCardFeed)); + .filter((feed) => !isCustomFeed(feed.name as CardFeedWithNumber)); defaultCardFeed = commercialFeeds.sort((a, b) => localeCompare(a.name, b.name)).at(0); } diff --git a/src/hooks/useCardsList.tsx b/src/hooks/useCardsList.tsx index 1a65b7a033c5..fc157291febb 100644 --- a/src/hooks/useCardsList.tsx +++ b/src/hooks/useCardsList.tsx @@ -1,14 +1,14 @@ import type {ResultMetadata} from 'react-native-onyx'; -import {filterInactiveCards} from '@libs/CardUtils'; -import CONST from '@src/CONST'; +import {filterInactiveCards, splitCardFeedWithDomainID} from '@libs/CardUtils'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {CompanyCardFeedWithDomainID, WorkspaceCardsList} from '@src/types/onyx'; +import type {CardFeedWithDomainID, WorkspaceCardsList} from '@src/types/onyx'; import useOnyx from './useOnyx'; /* Custom hook that retrieves a list of company cards for the given selected feed. */ -const useCardsList = (selectedFeed: CompanyCardFeedWithDomainID | undefined): [WorkspaceCardsList | undefined, ResultMetadata] => { - const [feed, domainOrWorkspaceAccountID] = selectedFeed?.split(CONST.COMPANY_CARD.FEED_KEY_SEPARATOR) ?? []; - const [cardsList, cardsListMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}${domainOrWorkspaceAccountID}_${feed}`, { +const useCardsList = (selectedFeed: CardFeedWithDomainID | undefined): [WorkspaceCardsList | undefined, ResultMetadata] => { + const splitFeedName = splitCardFeedWithDomainID(selectedFeed); + + const [cardsList, cardsListMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}${splitFeedName?.domainID}_${splitFeedName?.feedName}`, { selector: filterInactiveCards, canBeMissing: true, }); diff --git a/src/hooks/useCompanyCards.ts b/src/hooks/useCompanyCards.ts index 6f06b2086cc0..8583f55d728d 100644 --- a/src/hooks/useCompanyCards.ts +++ b/src/hooks/useCompanyCards.ts @@ -4,7 +4,7 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {CardFeeds, CardList} from '@src/types/onyx'; import type {AssignableCardsList, WorkspaceCardsList} from '@src/types/onyx/Card'; -import type {CardFeedsStatusByDomainID, CombinedCardFeeds, CompanyCardFeed, CompanyCardFeedWithDomainID, CompanyFeeds} from '@src/types/onyx/CardFeeds'; +import type {CardFeedsStatusByDomainID, CombinedCardFeeds, CompanyCardFeedWithDomainID, CompanyCardFeedWithNumber, CompanyFeeds} from '@src/types/onyx/CardFeeds'; import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; import useCardFeeds from './useCardFeeds'; import type {CombinedCardFeed} from './useCardFeeds'; @@ -17,7 +17,7 @@ type UseCompanyCardsProps = { }; type UseCompanyCardsResult = Partial<{ - bankName: CompanyCardFeed; + bankName: CompanyCardFeedWithNumber; feedName: CompanyCardFeedWithDomainID; cardList: AssignableCardsList; assignedCards: CardList; diff --git a/src/libs/API/parameters/AssignCompanyCardParams.ts b/src/libs/API/parameters/AssignCompanyCardParams.ts index 188e5a7d5145..3365ecbbe2df 100644 --- a/src/libs/API/parameters/AssignCompanyCardParams.ts +++ b/src/libs/API/parameters/AssignCompanyCardParams.ts @@ -1,7 +1,9 @@ +import type {CardFeedWithNumber} from '@src/types/onyx/CardFeeds'; + type AssignCompanyCardParams = { domainAccountID?: number; policyID: string; - bankName: string; + bankName: CardFeedWithNumber | undefined; cardName: string; encryptedCardNumber: string; email: string; diff --git a/src/libs/API/parameters/OpenPolicyCompanyCardsFeedParams.ts b/src/libs/API/parameters/OpenPolicyCompanyCardsFeedParams.ts index 85c881baf55b..0aa6c93e5a42 100644 --- a/src/libs/API/parameters/OpenPolicyCompanyCardsFeedParams.ts +++ b/src/libs/API/parameters/OpenPolicyCompanyCardsFeedParams.ts @@ -1,7 +1,9 @@ +import type {CompanyCardFeedWithNumber} from '@src/types/onyx/CardFeeds'; + type OpenPolicyCompanyCardsFeedParams = { domainAccountID?: number; policyID: string; - feed: string; + feed: CompanyCardFeedWithNumber; }; export default OpenPolicyCompanyCardsFeedParams; diff --git a/src/libs/CardFeedUtils.ts b/src/libs/CardFeedUtils.ts index c97376bdfa31..9a265bc795d8 100644 --- a/src/libs/CardFeedUtils.ts +++ b/src/libs/CardFeedUtils.ts @@ -5,13 +5,13 @@ import type IllustrationsType from '@styles/theme/illustrations/types'; import CONST from '@src/CONST'; import type {CombinedCardFeeds} from '@src/hooks/useCardFeeds'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Card, CardFeeds, CardList, CompanyCardFeed, PersonalDetailsList, Policy, WorkspaceCardsList} from '@src/types/onyx'; -import type {CardFeedsStatus, CardFeedsStatusByDomainID, CombinedCardFeed} from '@src/types/onyx/CardFeeds'; +import type {Card, CardFeeds, CardList, PersonalDetailsList, Policy, WorkspaceCardsList} from '@src/types/onyx'; +import type {CardFeedsStatus, CardFeedsStatusByDomainID, CardFeedWithNumber, CombinedCardFeed} from '@src/types/onyx/CardFeeds'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; import { getBankName, getCardFeedIcon, - getCompanyCardFeedWithDomainID, + getCardFeedWithDomainID, getCustomOrFormattedFeedName, getOriginalCompanyFeeds, getPlaidInstitutionIconUrl, @@ -25,10 +25,10 @@ import {getDescriptionForPolicyDomainCard} from './PolicyUtils'; import type {OptionData} from './ReportUtils'; type CardFilterItem = Partial & AdditionalCardProps & {isCardFeed?: boolean; correspondingCards?: string[]; cardFeedKey: string; plaidUrl?: string; keyForList: string}; -type DomainFeedData = {bank: string; domainName: string; correspondingCardIDs: string[]; fundID?: string}; +type DomainFeedData = {bank: CardFeedWithNumber; domainName: string; correspondingCardIDs: string[]; fundID?: string}; type ItemsGroupedBySelection = {selected: CardFilterItem[]; unselected: CardFilterItem[]}; type CardFeedNamesWithType = Record; -type CardFeedData = {cardName: string; bank: string; label?: string; type: 'domain' | 'workspace'}; +type CardFeedData = {cardName: string; bank: CardFeedWithNumber; label?: string; type: 'domain' | 'workspace'}; type GetCardFeedData = { workspaceCardFeeds: Record | undefined; translate: LocaleContextProps['translate']; @@ -36,7 +36,7 @@ type GetCardFeedData = { }; type CardFeedForDisplay = { id: string; - feed: CompanyCardFeed | typeof CONST.EXPENSIFY_CARD.BANK; + feed: CardFeedWithNumber; fundID: string; name: string; }; @@ -92,7 +92,7 @@ function createCardFilterItem( ): CardFilterItem { const personalDetails = personalDetailsList[card?.accountID ?? CONST.DEFAULT_NUMBER_ID]; const isSelected = selectedCards.includes(card.cardID.toString()); - const icon = getCardFeedIcon(card?.bank as CompanyCardFeed, illustrations, companyCardIcons); + const icon = getCardFeedIcon(card?.bank, illustrations, companyCardIcons); const cardName = card?.nameValuePairs?.cardTitle; const text = personalDetails?.displayName ?? cardName; const plaidUrl = getPlaidInstitutionIconUrl(card?.bank); @@ -205,7 +205,7 @@ function getWorkspaceCardFeedData( const correspondingPolicy = policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID?.toUpperCase()}`]; const cardFeedLabel = isBankRepeating ? correspondingPolicy?.name : undefined; const isPlaid = !!getPlaidInstitutionId(bank); - const companyCardBank = isPlaid && cardName ? cardName : getBankName(bank as CompanyCardFeed); + const companyCardBank = isPlaid && cardName ? cardName : getBankName(bank); const cardFeedBankName = bank === CONST.EXPENSIFY_CARD.BANK ? translate('search.filters.card.expensify') : companyCardBank; const fullCardName = @@ -224,7 +224,7 @@ function getWorkspaceCardFeedData( function getDomainCardFeedData(domainFeed: DomainFeedData, policies: OnyxCollection, repeatingBanks: string[], translate: LocaleContextProps['translate']): CardFeedData { const {domainName, bank} = domainFeed; const isBankRepeating = repeatingBanks.includes(bank); - const cardFeedBankName = bank === CONST.EXPENSIFY_CARD.BANK ? translate('search.filters.card.expensify') : getBankName(bank as CompanyCardFeed); + const cardFeedBankName = bank === CONST.EXPENSIFY_CARD.BANK ? translate('search.filters.card.expensify') : getBankName(bank); const cardFeedLabel = isBankRepeating ? getDescriptionForPolicyDomainCard(domainName, policies) : undefined; const cardName = cardFeedBankName === CONST.COMPANY_CARDS.CARD_TYPE.CSV @@ -299,7 +299,7 @@ function createCardFeedItem({ companyCardIcons, }: { cardName: string; - bank: string; + bank: CardFeedWithNumber; keyForList: string; cardFeedKey: string; correspondingCardIDs: string[]; @@ -310,7 +310,7 @@ function createCardFeedItem({ const isSelected = correspondingCardIDs.every((card) => selectedCards.includes(card)); const plaidUrl = getPlaidInstitutionIconUrl(bank); - const icon = getCardFeedIcon(bank as CompanyCardFeed, illustrations, companyCardIcons); + const icon = getCardFeedIcon(bank, illustrations, companyCardIcons); return { text: cardName, keyForList, @@ -446,7 +446,7 @@ function getCardFeedsForDisplay(allCardFeeds: OnyxCollection, allCard } for (const key of Object.keys(getOriginalCompanyFeeds(cardFeeds))) { - const feed = key as CompanyCardFeed; + const feed = key as CardFeedWithNumber; const id = `${fundID}_${feed}`; if (cardFeedsForDisplay[id]) { @@ -500,8 +500,8 @@ function getCardFeedsForDisplayPerPolicy(allCardFeeds: OnyxCollection } for (const [key, feedData] of Object.entries(getOriginalCompanyFeeds(cardFeeds))) { - const preferredPolicy = 'preferredPolicy' in feedData ? (feedData.preferredPolicy ?? '') : ''; - const feed = key as CompanyCardFeed; + const preferredPolicy = feedData && 'preferredPolicy' in feedData ? (feedData.preferredPolicy ?? '') : ''; + const feed = key as CardFeedWithNumber; const id = `${fundID}_${feed}`; (cardFeedsForDisplayPerPolicy[preferredPolicy] ||= []).push({ @@ -542,7 +542,7 @@ function getCombinedCardFeedsFromAllFeeds(allFeeds: OnyxCollection | return acc; } - for (const feedName of Object.keys(companyCards) as CompanyCardFeed[]) { + for (const feedName of Object.keys(companyCards) as CardFeedWithNumber[]) { const feedSettings = companyCards?.[feedName]; const oAuthAccountDetails = workspaceFeedsSettings?.oAuthAccountDetails?.[feedName]; const customFeedName = workspaceFeedsSettings?.companyCardNicknames?.[feedName]; @@ -565,7 +565,7 @@ function getCombinedCardFeedsFromAllFeeds(allFeeds: OnyxCollection | continue; } - const combinedFeedKey = getCompanyCardFeedWithDomainID(feedName, domainID); + const combinedFeedKey = getCardFeedWithDomainID(feedName, domainID); acc[combinedFeedKey] = combinedCardFeed; } @@ -575,6 +575,7 @@ function getCombinedCardFeedsFromAllFeeds(allFeeds: OnyxCollection | } export type {CardFilterItem, CardFeedNamesWithType, CardFeedForDisplay}; +export type {DomainFeedData}; export { buildCardsData, getCardFeedNamesWithType, diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index c3d7179140a1..6f68ee0c191a 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -23,7 +23,17 @@ import type { WorkspaceCardsList, } from '@src/types/onyx'; import type {UnassignedCard} from '@src/types/onyx/Card'; -import type {CardFeedData, CompanyCardFeedWithDomainID, CompanyCardFeedWithNumber, CompanyFeeds} from '@src/types/onyx/CardFeeds'; +import type { + BankName, + CardFeed, + CardFeedData, + CardFeedWithDomainID, + CardFeedWithNumber, + CardTypeName, + CompanyCardFeedWithDomainID, + CompanyCardFeedWithNumber, + CompanyFeeds, +} from '@src/types/onyx/CardFeeds'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; import type IconAsset from '@src/types/utils/IconAsset'; import {filterObject} from './ObjectUtils'; @@ -109,7 +119,7 @@ function getCardDescription(card: Card | undefined, translate: LocalizedTranslat return ''; } const isPlaid = !!getPlaidInstitutionId(card.bank); - const bankName = isPlaid ? card?.cardName : getBankName(card.bank as CompanyCardFeed); + const bankName = isPlaid ? card?.cardName : getBankName(card.bank); const cardDescriptor = card.state === CONST.EXPENSIFY_CARD.STATE.NOT_ACTIVATED ? translate('cardTransactions.notActivated') : card.lastFourPAN; const humanReadableBankName = card.bank === CONST.EXPENSIFY_CARD.BANK ? CONST.EXPENSIFY_CARD.BANK : bankName; return cardDescriptor && !isPlaid ? `${humanReadableBankName} - ${cardDescriptor}` : `${humanReadableBankName}`; @@ -236,7 +246,7 @@ function maskCardNumber(cardName?: string, feed?: string, showOriginalName?: boo } // CSV imported cards use user-provided display names, not card numbers - return as-is - if (feed === CONST.COMPANY_CARDS.BANK_NAME.UPLOAD) { + if (feed === CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD) { return cardName; } @@ -387,7 +397,11 @@ function filterCardsByPersonalDetails(card: Card, searchQuery: string, personalD ); } -function getCardFeedIcon(cardFeed: CompanyCardFeed | typeof CONST.EXPENSIFY_CARD.BANK, illustrations: IllustrationsType, companyCardIllustrations: CompanyCardFeedIcons): IconAsset { +function getCardFeedIcon(cardFeed: CardFeedWithNumber | CardFeedWithDomainID | undefined, illustrations: IllustrationsType, companyCardIllustrations: CompanyCardFeedIcons): IconAsset { + if (cardFeed === undefined) { + return illustrations.GenericCompanyCardLarge; + } + const feedIcons = { [CONST.COMPANY_CARD.FEED_BANK_NAME.VISA]: companyCardIllustrations.VisaCompanyCardDetailLarge, [CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX]: companyCardIllustrations.AmexCardCompanyCardDetailLarge, @@ -412,12 +426,13 @@ function getCardFeedIcon(cardFeed: CompanyCardFeed | typeof CONST.EXPENSIFY_CARD return Illustrations.ExpensifyCardImage; } - if (feedIcons[cardFeed]) { - return feedIcons[cardFeed]; + const feedIcon = feedIcons[cardFeed as keyof typeof feedIcons]; + if (feedIcon) { + return feedIcon; } // In existing OldDot setups other variations of feeds could exist, ex: vcf2, vcf3, cdfbmo - const feedKey = (Object.keys(feedIcons) as CompanyCardFeed[]).find((feed) => cardFeed.startsWith(feed)); + const feedKey = (Object.keys(feedIcons) as Array).find((feed) => cardFeed.startsWith(feed)); if (feedKey) { return feedIcons[feedKey]; @@ -433,7 +448,7 @@ function getCardFeedIcon(cardFeed: CompanyCardFeed | typeof CONST.EXPENSIFY_CARD /** * Verify if the feed is a custom feed. Those are also referred to as commercial feeds. */ -function isCustomFeed(feed: CompanyCardFeedWithNumber | undefined): boolean { +function isCustomFeed(feed: CardFeedWithNumber | CardFeedWithDomainID | undefined): boolean { if (!feed) { return false; } @@ -453,7 +468,7 @@ function isCSVFeedOrExpensifyCard(feedKey: string): boolean { function getOriginalCompanyFeeds(cardFeeds: OnyxEntry): CompanyFeeds { return Object.fromEntries( Object.entries(cardFeeds?.settings?.companyCards ?? {}).filter(([key, value]) => { - if (value.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || value.pending) { + if (value?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || value?.pending) { return false; } return key !== CONST.EXPENSIFY_CARD.BANK; @@ -475,28 +490,29 @@ function getCompanyFeeds(cardFeeds: OnyxEntry, shouldFilterOu ); } -function getBankName(feedType: CompanyCardFeed): string { +function getBankName(feedType: CardFeedWithNumber | CardFeedWithDomainID): string { const feedNamesMapping = { - [CONST.COMPANY_CARD.FEED_BANK_NAME.VISA]: 'Visa', - [CONST.COMPANY_CARD.FEED_BANK_NAME.MASTER_CARD]: 'Mastercard', - [CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX]: 'American Express', - [CONST.COMPANY_CARD.FEED_BANK_NAME.STRIPE]: 'Stripe', - [CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX_DIRECT]: 'American Express', - [CONST.COMPANY_CARD.FEED_BANK_NAME.BANK_OF_AMERICA]: 'Bank of America', - [CONST.COMPANY_CARD.FEED_BANK_NAME.CAPITAL_ONE]: 'Capital One', - [CONST.COMPANY_CARD.FEED_BANK_NAME.CHASE]: 'Chase', - [CONST.COMPANY_CARD.FEED_BANK_NAME.CITIBANK]: 'Citibank', - [CONST.COMPANY_CARD.FEED_BANK_NAME.WELLS_FARGO]: 'Wells Fargo', - [CONST.COMPANY_CARD.FEED_BANK_NAME.BREX]: 'Brex', - [CONST.COMPANY_CARD.FEED_BANK_NAME.CSV]: CONST.COMPANY_CARDS.CARD_TYPE.CSV, - [CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX_1205]: 'American Express', - [CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX_FILE_DOWNLOAD]: 'American Express', - [CONST.COMPANY_CARD.FEED_BANK_NAME.PEX]: 'PEX', + [CONST.COMPANY_CARD.FEED_BANK_NAME.CSV]: CONST.COMPANY_CARDS.CARD_TYPE_NAMES.CSV, + [CONST.COMPANY_CARD.FEED_BANK_NAME.VISA]: CONST.COMPANY_CARDS.CARD_TYPE_NAMES.VISA, + [CONST.COMPANY_CARD.FEED_BANK_NAME.MASTER_CARD]: CONST.COMPANY_CARDS.CARD_TYPE_NAMES.MASTERCARD, + [CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX]: CONST.COMPANY_CARDS.BANKS.AMEX, + [CONST.COMPANY_CARD.FEED_BANK_NAME.STRIPE]: CONST.COMPANY_CARDS.BANKS.STRIPE, + [CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX_DIRECT]: CONST.COMPANY_CARDS.BANKS.AMEX, + [CONST.COMPANY_CARD.FEED_BANK_NAME.BANK_OF_AMERICA]: CONST.COMPANY_CARDS.BANKS.BANK_OF_AMERICA, + [CONST.COMPANY_CARD.FEED_BANK_NAME.CAPITAL_ONE]: CONST.COMPANY_CARDS.BANKS.CAPITAL_ONE, + [CONST.COMPANY_CARD.FEED_BANK_NAME.CHASE]: CONST.COMPANY_CARDS.BANKS.CHASE, + [CONST.COMPANY_CARD.FEED_BANK_NAME.CITIBANK]: CONST.COMPANY_CARDS.BANKS.CITI_BANK, + [CONST.COMPANY_CARD.FEED_BANK_NAME.WELLS_FARGO]: CONST.COMPANY_CARDS.BANKS.WELLS_FARGO, + [CONST.COMPANY_CARD.FEED_BANK_NAME.BREX]: CONST.COMPANY_CARDS.BANKS.BREX, + [CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX_1205]: CONST.COMPANY_CARDS.BANKS.AMEX, + [CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX_FILE_DOWNLOAD]: CONST.COMPANY_CARDS.BANKS.AMEX, + [CONST.COMPANY_CARD.FEED_BANK_NAME.PEX]: CONST.COMPANY_CARDS.BANKS.PEX, + [CONST.EXPENSIFY_CARD.BANK]: CONST.COMPANY_CARDS.BANKS.AMEX, [CONST.COMPANY_CARD.FEED_BANK_NAME.MOCK_BANK]: CONST.COMPANY_CARDS.BANKS.MOCK_BANK, - }; + } satisfies Partial>; // In existing OldDot setups other variations of feeds could exist, ex: vcf2, vcf3, oauth.americanexpressfdx.com 2003 - const feedKey = (Object.keys(feedNamesMapping) as CompanyCardFeed[]).find((feed) => feedType?.startsWith(feed)); + const feedKey = (Object.keys(feedNamesMapping) as Array).find((feed) => feedType?.startsWith(feed)); if (feedType?.includes(CONST.COMPANY_CARD.FEED_BANK_NAME.CSV)) { return CONST.COMPANY_CARDS.CARD_TYPE.CSV; @@ -520,12 +536,19 @@ const getBankCardDetailsImage = (bank: ValueOf [CONST.COMPANY_CARDS.BANKS.BREX]: companyCardIllustrations.BrexCompanyCardDetail, [CONST.COMPANY_CARDS.BANKS.STRIPE]: companyCardIllustrations.StripeCompanyCardDetail, [CONST.COMPANY_CARDS.BANKS.MOCK_BANK]: illustrations.GenericCompanyCard, + [CONST.COMPANY_CARDS.BANKS.PEX]: illustrations.GenericCompanyCard, + [CONST.COMPANY_CARDS.BANKS.EXPENSIFY]: Illustrations.ExpensifyCardImage, [CONST.COMPANY_CARDS.BANKS.OTHER]: illustrations.GenericCompanyCard, }; return iconMap[bank]; }; -function getCustomOrFormattedFeedName(translate: LocalizedTranslate, feed?: CompanyCardFeed, customFeedName?: string, shouldAddCardsSuffix = true): string | undefined { +function getCustomOrFormattedFeedName( + translate: LocalizedTranslate, + feed?: CardFeedWithNumber | CardFeedWithDomainID, + customFeedName?: string, + shouldAddCardsSuffix = true, +): string | undefined { if (!feed) { return; } @@ -606,7 +629,7 @@ function getFeedNameForDisplay( return getCustomOrFormattedFeedName(translate, feed, customName, shouldAddCardsSuffix) ?? ''; } -function getPlaidInstitutionIconUrl(feedName?: string) { +function getPlaidInstitutionIconUrl(feedName?: CardFeedWithNumber | CardFeedWithDomainID) { const institutionId = getPlaidInstitutionId(feedName); if (!institutionId) { return ''; @@ -614,8 +637,8 @@ function getPlaidInstitutionIconUrl(feedName?: string) { return `${CONST.COMPANY_CARD_PLAID}${institutionId}.png`; } -function getPlaidInstitutionId(feedName?: string) { - const feedNameWithoutDomainID = getCompanyCardFeed(feedName ?? ''); +function getPlaidInstitutionId(feedName?: CardFeedWithNumber | CardFeedWithDomainID) { + const feedNameWithoutDomainID = getCompanyCardFeed(feedName); const feed = feedNameWithoutDomainID?.split('.'); if (!feed || feed?.at(0) !== CONST.BANK_ACCOUNT.SETUP_TYPE.PLAID) { return ''; @@ -669,10 +692,32 @@ function getSelectedFeed(lastSelectedFeed: OnyxEntry !key.includes(CONST.EXPENSIFY_CARD.BANK))); +} + /** * Takes the list of cards divided by workspaces and feeds and returns the flattened non-Expensify cards related to the provided workspace * @@ -828,15 +887,14 @@ function getFeedType(feedKey: CompanyCardFeed, cardFeeds: OnyxEntry, workspaceAccountID: number, domainIDs?: number[]): Record | undefined { +function flattenWorkspaceCardsList(allCardsList: OnyxCollection, workspaceAccountID: number): CardList | undefined { if (!allCardsList) { return; } return Object.entries(allCardsList).reduce((acc, [key, cards]) => { - const isWorkspaceAccountCards = key.includes(workspaceAccountID.toString()); - const isDomainCards = domainIDs?.some((domainID) => key.includes(domainID.toString())); - if ((!isWorkspaceAccountCards && !isDomainCards) || key.includes(CONST.EXPENSIFY_CARD.BANK)) { + const isWorkspaceAccountCard = key.includes(workspaceAccountID.toString()); + if (!isWorkspaceAccountCard || key.includes(CONST.EXPENSIFY_CARD.BANK)) { return acc; } const {cardList, ...feedCards} = cards ?? {}; @@ -934,12 +992,13 @@ function getFeedConnectionBrokenCard(feedCards: CardList | undefined, feedToExcl } /** Extract feed from feed with domainID */ -function getCompanyCardFeed(feedWithDomainID: string | undefined): CompanyCardFeed { +function getCompanyCardFeed(feedWithDomainID: CardFeedWithNumber | CardFeedWithDomainID | undefined): CompanyCardFeedWithNumber { if (!feedWithDomainID) { - return '' as CompanyCardFeed; + return '' as CompanyCardFeedWithNumber; } + const [feed] = feedWithDomainID.split(CONST.COMPANY_CARD.FEED_KEY_SEPARATOR); - return feed as CompanyCardFeed; + return feed as CompanyCardFeedWithNumber; } /** @@ -979,15 +1038,26 @@ function splitMaskedCardNumber(cardNumber: string | undefined, maskChar: string }; } -function isCardAlreadyAssigned(cardNumberToCheck: string, workspaceCardFeeds: OnyxCollection): boolean { +function isCardAlreadyAssigned(cardNumberToCheck: string, workspaceCardFeeds: OnyxCollection, domainOrWorkspaceAccountID: number): boolean { if (!cardNumberToCheck || !workspaceCardFeeds) { return false; } - return Object.values(workspaceCardFeeds).some((workspaceCards) => { + return Object.entries(workspaceCardFeeds).some(([key, workspaceCards]) => { if (!workspaceCards) { return false; } + + const cardFeedKeyParts = key.split('_'); + const feedDomainID = Number(cardFeedKeyParts.at(1)); + if (cardFeedKeyParts.length !== 3 || cardFeedKeyParts.at(0) !== ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST || Number.isNaN(feedDomainID)) { + return false; + } + + if (feedDomainID !== domainOrWorkspaceAccountID) { + return false; + } + const {cardList, ...assignedCards} = workspaceCards; return Object.values(assignedCards).some( (card) => card && card.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE && isMatchingCard(card, cardNumberToCheck, cardNumberToCheck), @@ -1061,16 +1131,18 @@ export { getDomainOrWorkspaceAccountID, mergeCardListWithWorkspaceFeeds, isCard, + filterCardsByNonExpensify, getAllCardsForWorkspace, isCardHiddenFromSearch, getFeedType, - flatAllCardsList, + flattenWorkspaceCardsList, isCardConnectionBroken, isSmartLimitEnabled, lastFourNumbersFromCardName, isMatchingCard, hasIssuedExpensifyCard, isExpensifyCardFullySetUp, + filterAllInactiveCards, filterInactiveCards, isCardPendingIssue, isCardPendingActivate, @@ -1087,7 +1159,8 @@ export { getCorrectStepForPlaidSelectedBank, getOriginalCompanyFeeds, getCompanyCardFeed, - getCompanyCardFeedWithDomainID, + getCardFeedWithDomainID, + splitCardFeedWithDomainID, getEligibleBankAccountsForUkEuCard, isPersonalCard, COMPANY_CARD_FEED_ICON_NAMES, diff --git a/src/libs/PolicyUtils.ts b/src/libs/PolicyUtils.ts index 3f4ab7dbcbf4..49b9ce58fa0b 100644 --- a/src/libs/PolicyUtils.ts +++ b/src/libs/PolicyUtils.ts @@ -127,7 +127,8 @@ function getActivePoliciesWithExpenseChatAndTimeEnabled(policies: OnyxCollection /** * Checks if the current user is an admin of the policy. */ -const isPolicyAdmin = (policy: OnyxInputOrEntry, currentUserLogin?: string): boolean => getPolicyRole(policy, currentUserLogin) === CONST.POLICY.ROLE.ADMIN; +const isPolicyAdmin = (policy: OnyxInputOrEntry, login?: string, shouldCheckGlobalPolicyRole = true): boolean => + getPolicyRole(policy, login, shouldCheckGlobalPolicyRole) === CONST.POLICY.ROLE.ADMIN; /** * Checks if we have any errors stored within the policy?.employeeList. Determines whether we should show a red brick road error or not. @@ -366,8 +367,8 @@ function getPolicyBrickRoadIndicatorStatus(policy: OnyxEntry, isConnecti return undefined; } -function getPolicyRole(policy: OnyxInputOrEntry, currentUserLogin: string | undefined): string | undefined { - if (policy?.role) { +function getPolicyRole(policy: OnyxInputOrEntry, currentUserLogin?: string, shouldCheckGlobalPolicyRole = true): string | undefined { + if (shouldCheckGlobalPolicyRole && policy?.role) { return policy.role; } @@ -445,11 +446,6 @@ function isExpensifyTeam(email: string | undefined): boolean { return emailDomain === CONST.EXPENSIFY_PARTNER_NAME || emailDomain === CONST.EMAIL.GUIDES_DOMAIN; } -/** - * Checks if the user with login is an admin of the policy. - */ -const isUserPolicyAdmin = (policy: OnyxInputOrEntry, login?: string) => !!(policy && policy.employeeList && login && policy.employeeList[login]?.role === CONST.POLICY.ROLE.ADMIN); - /** * Checks if the current user is of the role "user" on the policy. */ @@ -2003,7 +1999,6 @@ export { getCorrectedAutoReportingFrequency, isPaidGroupPolicy, isPendingDeletePolicy, - isUserPolicyAdmin, isPolicyAdmin, isPolicyUser, isPolicyAuditor, diff --git a/src/libs/TransactionUtils/index.ts b/src/libs/TransactionUtils/index.ts index b81d2370f640..1243feeca88a 100644 --- a/src/libs/TransactionUtils/index.ts +++ b/src/libs/TransactionUtils/index.ts @@ -1403,7 +1403,7 @@ function isFromCreditCardImport(transaction: OnyxEntry): boolean { return true; } - if (transaction?.bank === CONST.COMPANY_CARDS.BANK_NAME.UPLOAD) { + if (transaction?.bank === CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD) { return false; } diff --git a/src/libs/actions/CompanyCards.ts b/src/libs/actions/CompanyCards.ts index 08f16588d0b8..55bdcdd26708 100644 --- a/src/libs/actions/CompanyCards.ts +++ b/src/libs/actions/CompanyCards.ts @@ -16,7 +16,7 @@ import type { } from '@libs/API/parameters'; import {READ_COMMANDS, WRITE_COMMANDS} from '@libs/API/types'; import * as CardUtils from '@libs/CardUtils'; -import {getCompanyCardFeedWithDomainID} from '@libs/CardUtils'; +import {getCardFeedWithDomainID} from '@libs/CardUtils'; import * as ErrorUtils from '@libs/ErrorUtils'; import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils'; import * as ReportUtils from '@libs/ReportUtils'; @@ -90,7 +90,7 @@ function addNewCompanyCardsFeed( } const feedType = CardUtils.getFeedType(cardFeed, cardFeeds); - const newSelectedFeed = getCompanyCardFeedWithDomainID(feedType as CompanyCardFeed, workspaceAccountID); + const newSelectedFeed = getCardFeedWithDomainID(feedType, workspaceAccountID) as CompanyCardFeedWithDomainID; const optimisticData: Array> = [ { @@ -158,7 +158,7 @@ function addNewCompanyCardsFeed( API.write(WRITE_COMMANDS.REQUEST_FEED_SETUP, parameters, {optimisticData, failureData, finallyData}); } -function setWorkspaceCompanyCardFeedName(policyID: string, domainOrWorkspaceAccountID: number, bankName: CompanyCardFeed, userDefinedName: string) { +function setWorkspaceCompanyCardFeedName(policyID: string, domainOrWorkspaceAccountID: number, bankName: CompanyCardFeedWithNumber, userDefinedName: string) { const onyxData: OnyxData = { optimisticData: [ { @@ -185,7 +185,7 @@ function setWorkspaceCompanyCardFeedName(policyID: string, domainOrWorkspaceAcco API.write(WRITE_COMMANDS.SET_COMPANY_CARD_FEED_NAME, parameters, onyxData); } -function setWorkspaceCompanyCardTransactionLiability(domainOrWorkspaceAccountID: number, policyID: string, bankName: CompanyCardFeed, liabilityType: string) { +function setWorkspaceCompanyCardTransactionLiability(domainOrWorkspaceAccountID: number, policyID: string, bankName: CompanyCardFeedWithNumber, liabilityType: string) { const feedUpdates = { [bankName]: {liabilityType}, }; @@ -211,7 +211,13 @@ function setWorkspaceCompanyCardTransactionLiability(domainOrWorkspaceAccountID: API.write(WRITE_COMMANDS.SET_COMPANY_CARD_TRANSACTION_LIABILITY, parameters, onyxData); } -function deleteWorkspaceCompanyCardFeed(policyID: string, domainOrWorkspaceAccountID: number, bankName: CompanyCardFeed, cardIDs: string[], feedToOpen?: CompanyCardFeedWithDomainID) { +function deleteWorkspaceCompanyCardFeed( + policyID: string, + domainOrWorkspaceAccountID: number, + bankName: CompanyCardFeedWithNumber, + cardIDs: string[], + feedToOpen?: CompanyCardFeedWithDomainID, +) { const isCustomFeed = CardUtils.isCustomFeed(bankName); const optimisticFeedUpdates = {[bankName]: {pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE}}; const successFeedUpdates = {[bankName]: null}; @@ -311,17 +317,11 @@ function deleteWorkspaceCompanyCardFeed(policyID: string, domainOrWorkspaceAccou API.write(WRITE_COMMANDS.DELETE_COMPANY_CARD_FEED, parameters, {optimisticData, successData, failureData}); } -function assignWorkspaceCompanyCard( - policy: OnyxEntry, - domainOrWorkspaceAccountID: number, - translate: LocaleContextProps['translate'], - feed: CompanyCardFeedWithDomainID, - data?: Partial, -) { - if (!data || !policy?.id) { +function assignWorkspaceCompanyCard(policy: OnyxEntry, domainOrWorkspaceAccountID: number, translate: LocaleContextProps['translate'], data: Partial) { + if (!policy?.id) { return; } - const {bankName = '', email = '', encryptedCardNumber = '', startDate = '', customCardName = ''} = data; + const {bankName, email = '', encryptedCardNumber = '', startDate = '', customCardName = ''} = data; const assigneeDetails = PersonalDetailsUtils.getPersonalDetailByEmail(email); const optimisticCardAssignedReportAction = ReportUtils.buildOptimisticCardAssignedReportAction(assigneeDetails?.accountID ?? CONST.DEFAULT_NUMBER_ID); @@ -388,7 +388,7 @@ function assignWorkspaceCompanyCard( API.write(WRITE_COMMANDS.ASSIGN_COMPANY_CARD, parameters, onyxData); } -function unassignWorkspaceCompanyCard(domainOrWorkspaceAccountID: number, bankName: CompanyCardFeed, card: Card) { +function unassignWorkspaceCompanyCard(domainOrWorkspaceAccountID: number, bankName: CompanyCardFeedWithNumber, card: Card) { const cardID = card.cardID; const onyxData: OnyxData = { @@ -464,7 +464,7 @@ function unassignWorkspaceCompanyCard(domainOrWorkspaceAccountID: number, bankNa API.write(WRITE_COMMANDS.UNASSIGN_CARD, parameters, onyxData); } -function resetFailedWorkspaceCompanyCardUnassignment(domainOrWorkspaceAccountID: number, bankName: CompanyCardFeed | undefined, cardID: number | undefined) { +function resetFailedWorkspaceCompanyCardUnassignment(domainOrWorkspaceAccountID: number, bankName: CompanyCardFeedWithNumber | undefined, cardID: number | undefined) { if (!bankName || !cardID) { return; } @@ -482,7 +482,7 @@ function resetFailedWorkspaceCompanyCardUnassignment(domainOrWorkspaceAccountID: }); } -function updateWorkspaceCompanyCard(domainOrWorkspaceAccountID: number, cardID: string, bankName: CompanyCardFeed, lastScrapeResult?: number, breakConnection?: boolean) { +function updateWorkspaceCompanyCard(domainOrWorkspaceAccountID: number, cardID: string, bankName: CompanyCardFeedWithNumber, lastScrapeResult?: number, breakConnection?: boolean) { const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, @@ -592,7 +592,7 @@ function updateWorkspaceCompanyCard(domainOrWorkspaceAccountID: number, cardID: API.write(WRITE_COMMANDS.SYNC_CARD, parameters, {optimisticData, finallyData, failureData}); } -function updateCompanyCardName(domainOrWorkspaceAccountID: number, cardID: string, newCardTitle: string, bankName: CompanyCardFeed, oldCardTitle?: string) { +function updateCompanyCardName(domainOrWorkspaceAccountID: number, cardID: string, newCardTitle: string, bankName: CompanyCardFeedWithNumber, oldCardTitle?: string) { const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, @@ -665,7 +665,7 @@ function updateCompanyCardName(domainOrWorkspaceAccountID: number, cardID: strin API.write(WRITE_COMMANDS.UPDATE_COMPANY_CARD_NAME, parameters, {optimisticData, finallyData, failureData}); } -function updateCardTransactionStartDate(domainOrWorkspaceAccountID: number, cardID: string, newStartDate: string, bankName: CompanyCardFeed, oldStartDate?: string) { +function updateCardTransactionStartDate(domainOrWorkspaceAccountID: number, cardID: string, newStartDate: string, bankName: CompanyCardFeedWithNumber, oldStartDate?: string) { const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, @@ -724,7 +724,7 @@ function updateCardTransactionStartDate(domainOrWorkspaceAccountID: number, card API.write(WRITE_COMMANDS.UPDATE_CARD_TRANSACTION_START_DATE, parameters, {optimisticData, finallyData, failureData}); } -function setCompanyCardExportAccount(policyID: string, domainOrWorkspaceAccountID: number, cardID: string, accountKey: string, newAccount: string, bank: CompanyCardFeed) { +function setCompanyCardExportAccount(policyID: string, domainOrWorkspaceAccountID: number, cardID: string, accountKey: string, newAccount: string, bank: CompanyCardFeedWithNumber) { const optimisticData: Array> = [ { onyxMethod: Onyx.METHOD.MERGE, @@ -787,7 +787,7 @@ function setCompanyCardExportAccount(policyID: string, domainOrWorkspaceAccountI API.write(WRITE_COMMANDS.SET_CARD_EXPORT_ACCOUNT, parameters, {optimisticData, finallyData, failureData}); } -function clearCompanyCardErrorField(domainOrWorkspaceAccountID: number, cardID: string, bankName: CompanyCardFeed, fieldName: string, isRootLevel?: boolean) { +function clearCompanyCardErrorField(domainOrWorkspaceAccountID: number, cardID: string, bankName: CompanyCardFeedWithNumber, fieldName: string, isRootLevel?: boolean) { if (isRootLevel) { Onyx.merge(`${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}${domainOrWorkspaceAccountID}_${bankName}`, { [cardID]: { @@ -918,7 +918,7 @@ function openPolicyCompanyCardsFeed(domainAccountID: number, policyID: string, f API.read(READ_COMMANDS.OPEN_POLICY_COMPANY_CARDS_FEED, parameters, {optimisticData, successData, failureData}); } -function openAssignFeedCardPage(policyID: string, feed: CompanyCardFeed, domainOrWorkspaceAccountID: number) { +function openAssignFeedCardPage(policyID: string, feed: CompanyCardFeedWithNumber, domainOrWorkspaceAccountID: number) { const parameters: OpenPolicyCompanyCardsFeedParams = { policyID, feed, @@ -961,7 +961,7 @@ function openPolicyAddCardFeedPage(policyID: string | undefined) { function setFeedStatementPeriodEndDay( policyID: string, - bankName: CompanyCardFeed, + bankName: CompanyCardFeedWithNumber, domainAccountID: number, newStatementPeriodEnd: StatementPeriodEnd | undefined, newStatementPeriodEndDay: StatementPeriodEndDay | undefined, @@ -1040,7 +1040,7 @@ function setFeedStatementPeriodEndDay( API.write(WRITE_COMMANDS.SET_FEED_STATEMENT_PERIOD_END_DAY, parameters, {optimisticData, successData, failureData}); } -function clearErrorField(bankName: CompanyCardFeed, domainAccountID: number, fieldName: keyof CardFeedData) { +function clearErrorField(bankName: CompanyCardFeedWithNumber, domainAccountID: number, fieldName: keyof CardFeedData) { Onyx.merge(`${ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER}${domainAccountID}`, { settings: { companyCards: { diff --git a/src/libs/actions/OnyxDerived/configs/cardFeedErrors.ts b/src/libs/actions/OnyxDerived/configs/cardFeedErrors.ts index aaff635ba951..baaf2ffffff2 100644 --- a/src/libs/actions/OnyxDerived/configs/cardFeedErrors.ts +++ b/src/libs/actions/OnyxDerived/configs/cardFeedErrors.ts @@ -1,10 +1,9 @@ import {getCombinedCardFeedsFromAllFeeds, getWorkspaceCardFeedsStatus} from '@libs/CardFeedUtils'; -import {filterInactiveCards, getCompanyCardFeedWithDomainID, isCardConnectionBroken} from '@libs/CardUtils'; +import {filterInactiveCards, getCardFeedWithDomainID, isCardConnectionBroken} from '@libs/CardUtils'; import createOnyxDerivedValueConfig from '@userActions/OnyxDerived/createOnyxDerivedValueConfig'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {Card} from '@src/types/onyx'; -import type {CompanyCardFeed, CompanyCardFeedWithNumber} from '@src/types/onyx/CardFeeds'; import type {CardErrors, CardFeedErrorsObject, CardFeedErrorState} from '@src/types/onyx/DerivedValues'; import type {Errors} from '@src/types/onyx/OnyxCommon'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; @@ -45,7 +44,7 @@ export default createOnyxDerivedValueConfig({ const cardsWithBrokenFeedConnection: Record = {}; function addErrorsForCard(card: Card) { - const bankName = card.bank as CompanyCardFeedWithNumber | typeof CONST.EXPENSIFY_CARD.BANK; + const bankName = card.bank; const workspaceAccountID = Number(card.fundID); const isExpensifyCard = bankName === CONST.EXPENSIFY_CARD.BANK; @@ -54,7 +53,7 @@ export default createOnyxDerivedValueConfig({ return; } - const feedNameWithDomainID = getCompanyCardFeedWithDomainID(bankName as CompanyCardFeed, workspaceAccountID); + const feedNameWithDomainID = getCardFeedWithDomainID(bankName, workspaceAccountID); const previousFeedErrors = cardFeedErrors[feedNameWithDomainID] ?? DEFAULT_CARD_FEED_ERROR_STATE; const feed = combinedCompanyCardFeeds?.[feedNameWithDomainID]; diff --git a/src/libs/actions/Plaid.ts b/src/libs/actions/Plaid.ts index fe65a3b73497..1bdd86ae8f82 100644 --- a/src/libs/actions/Plaid.ts +++ b/src/libs/actions/Plaid.ts @@ -7,7 +7,7 @@ import {getCompanyCardFeed} from '@libs/CardUtils'; import getPlaidLinkTokenParameters from '@libs/getPlaidLinkTokenParameters'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {StatementPeriodEnd, StatementPeriodEndDay} from '@src/types/onyx/CardFeeds'; +import type {CardFeedWithDomainID, CardFeedWithNumber, CompanyCardFeedWithDomainID, StatementPeriodEnd, StatementPeriodEndDay} from '@src/types/onyx/CardFeeds'; /** * Gets the Plaid Link token used to initialize the Plaid SDK @@ -49,7 +49,7 @@ function openPlaidBankLogin(allowDebit: boolean, bankAccountID: number) { /** * Gets the Plaid Link token used to initialize the Plaid SDK for Company card */ -function openPlaidCompanyCardLogin(country: string, domain?: string, feed?: string) { +function openPlaidCompanyCardLogin(country: string, domain?: string, feed?: CardFeedWithNumber | CompanyCardFeedWithDomainID) { const {redirectURI, androidPackage} = getPlaidLinkTokenParameters(); const params: OpenPlaidCompanyCardLoginParams = { @@ -120,7 +120,7 @@ function openPlaidBankAccountSelector(publicToken: string, bankName: string, all function importPlaidAccounts( publicToken: string, - feed: string, + feed: CardFeedWithNumber | CardFeedWithDomainID, feedName: string, country: string, domainName: string, diff --git a/src/libs/actions/Policy/Member.ts b/src/libs/actions/Policy/Member.ts index 3901aa480441..4aecafdc9c54 100644 --- a/src/libs/actions/Policy/Member.ts +++ b/src/libs/actions/Policy/Member.ts @@ -22,7 +22,7 @@ import Parser from '@libs/Parser'; import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils'; import {getPersonalDetailByEmail} from '@libs/PersonalDetailsUtils'; import * as PhoneNumber from '@libs/PhoneNumber'; -import {getDefaultApprover, isUserPolicyAdmin} from '@libs/PolicyUtils'; +import {getDefaultApprover, isPolicyAdmin} from '@libs/PolicyUtils'; import * as ReportActionsUtils from '@libs/ReportActionsUtils'; import * as ReportUtils from '@libs/ReportUtils'; import * as FormActions from '@userActions/FormActions'; @@ -284,7 +284,8 @@ function resetAccountingPreferredExporter(policy: OnyxEntry, loginList: } const owner = policy?.owner ?? ReportUtils.getPersonalDetailsForAccountID(policy?.ownerAccountID).login ?? ''; const policyKey = `${ONYXKEYS.COLLECTION.POLICY}${policy.id}` as const; - const adminLoginList = loginList.filter((login) => isUserPolicyAdmin(policy, login)); + + const adminLoginList = loginList.filter((login) => isPolicyAdmin(policy, login, false)); const connections = [CONST.POLICY.CONNECTIONS.NAME.XERO, CONST.POLICY.CONNECTIONS.NAME.QBO, CONST.POLICY.CONNECTIONS.NAME.SAGE_INTACCT, CONST.POLICY.CONNECTIONS.NAME.QBD]; if (!adminLoginList.length) { diff --git a/src/pages/RoomMemberDetailsPage.tsx b/src/pages/RoomMemberDetailsPage.tsx index a8cdbe6f7942..28ed3221dcb8 100644 --- a/src/pages/RoomMemberDetailsPage.tsx +++ b/src/pages/RoomMemberDetailsPage.tsx @@ -18,7 +18,7 @@ import {removeFromRoom} from '@libs/actions/Report'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; import type {RoomMembersNavigatorParamList} from '@libs/Navigation/types'; import {getDisplayNameOrDefault} from '@libs/PersonalDetailsUtils'; -import {isUserPolicyAdmin} from '@libs/PolicyUtils'; +import {isPolicyAdmin} from '@libs/PolicyUtils'; import {isPolicyExpenseChat} from '@libs/ReportUtils'; import Navigation from '@navigation/Navigation'; import CONST from '@src/CONST'; @@ -52,7 +52,7 @@ function RoomMemberDetailsPage({report, route}: RoomMemberDetailsPagePageProps) const displayName = formatPhoneNumber(getDisplayNameOrDefault(details)); const isSelectedMemberCurrentUser = accountID === currentUserPersonalDetails?.accountID; const isSelectedMemberOwner = accountID === report.ownerAccountID; - const shouldDisableRemoveUser = (isPolicyExpenseChat(report) && isUserPolicyAdmin(policy, details.login)) || isSelectedMemberCurrentUser || isSelectedMemberOwner; + const shouldDisableRemoveUser = (isPolicyExpenseChat(report) && isPolicyAdmin(policy, details.login)) || isSelectedMemberCurrentUser || isSelectedMemberOwner; const removeUser = () => { setIsRemoveMemberConfirmModalVisible(false); removeFromRoom(report, [accountID]); diff --git a/src/pages/RoomMembersPage.tsx b/src/pages/RoomMembersPage.tsx index 2648d7112ce7..6c69c1679975 100644 --- a/src/pages/RoomMembersPage.tsx +++ b/src/pages/RoomMembersPage.tsx @@ -37,7 +37,7 @@ import type {RoomMembersNavigatorParamList} from '@libs/Navigation/types'; import {isPersonalDetailsReady, isSearchStringMatchUserDetails} from '@libs/OptionsListUtils'; import Parser from '@libs/Parser'; import {getDisplayNameOrDefault, getPersonalDetailsByIDs} from '@libs/PersonalDetailsUtils'; -import {isPolicyEmployee as isPolicyEmployeeUtils, isUserPolicyAdmin} from '@libs/PolicyUtils'; +import {isPolicyAdmin, isPolicyEmployee as isPolicyEmployeeUtils} from '@libs/PolicyUtils'; import {getReportAction} from '@libs/ReportActionsUtils'; import { getReportForHeader, @@ -286,7 +286,7 @@ function RoomMembersPage({report, policy}: RoomMembersPageProps) { continue; } const pendingChatMember = reportMetadata?.pendingChatMembers?.findLast((member) => member.accountID === accountID.toString()); - const isAdmin = isUserPolicyAdmin(policy, details.login); + const isAdmin = isPolicyAdmin(policy, details.login); const isDisabled = pendingChatMember?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || details.isOptimisticPersonalDetail; const isDisabledCheckbox = (isPolicyExpenseChat && isAdmin) || diff --git a/src/pages/settings/Wallet/PaymentMethodList.tsx b/src/pages/settings/Wallet/PaymentMethodList.tsx index f88004dafdf6..d30d9d9b7026 100644 --- a/src/pages/settings/Wallet/PaymentMethodList.tsx +++ b/src/pages/settings/Wallet/PaymentMethodList.tsx @@ -24,7 +24,7 @@ import useThemeStyles from '@hooks/useThemeStyles'; import { getAssignedCardSortKey, getCardFeedIcon, - getCompanyCardFeedWithDomainID, + getCardFeedWithDomainID, getPlaidInstitutionIconUrl, isExpensifyCard, isExpensifyCardPendingAction, @@ -39,7 +39,7 @@ import variables from '@styles/variables'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; -import type {BankAccount, BankAccountList, CardList, CompanyCardFeed} from '@src/types/onyx'; +import type {BankAccount, BankAccountList, CardList} from '@src/types/onyx'; import type PaymentMethod from '@src/types/onyx/PaymentMethod'; import {getEmptyObject, isEmptyObject} from '@src/types/utils/EmptyObject'; import type IconAsset from '@src/types/utils/IconAsset'; @@ -211,19 +211,19 @@ function PaymentMethodList({ for (const card of assignedCardsSorted) { const isDisabled = card.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE; const isUserPersonalCard = isPersonalCard(card); - const isCSVCard = card.bank === CONST.COMPANY_CARDS.BANK_NAME.UPLOAD || card.bank.includes(CONST.COMPANY_CARD.FEED_BANK_NAME.CSV); + const isCSVCard = card.bank === CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD || card.bank.includes(CONST.COMPANY_CARD.FEED_BANK_NAME.CSV); const assignedCardsGrouped = isUserPersonalCard ? personalCardsGrouped : companyCardsGrouped; let icon; if (isUserPersonalCard && isCSVCard) { icon = getCardFeedIcon(CONST.COMPANY_CARD.FEED_BANK_NAME.CSV, illustrations, companyCardFeedIcons); } else { - icon = getCardFeedIcon(card.bank as CompanyCardFeed, illustrations, companyCardFeedIcons); + icon = getCardFeedIcon(card.bank, illustrations, companyCardFeedIcons); } let shouldShowRBR = false; if (card.fundID) { - const feedNameWithDomainID = getCompanyCardFeedWithDomainID(card.bank as CompanyCardFeed, card.fundID); + const feedNameWithDomainID = getCardFeedWithDomainID(card.bank, card.fundID); shouldShowRBR = shouldShowRbrForFeedNameWithDomainID[feedNameWithDomainID]; } else if (card.bank !== CONST.PERSONAL_CARD.BANK_NAME.CSV) { // Don't show red dot for CSV imported cards without fundID @@ -244,7 +244,7 @@ function PaymentMethodList({ if (!isExpensifyCard(card)) { const lastFourPAN = lastFourNumbersFromCardName(card.cardName); const plaidUrl = getPlaidInstitutionIconUrl(card.bank); - const isCSVImportCard = card.bank === CONST.COMPANY_CARDS.BANK_NAME.UPLOAD; + const isCSVImportCard = card.bank === CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD; const cardTitle = isCSVImportCard ? (card.nameValuePairs?.cardTitle ?? card.cardName) : maskCardNumber(card.cardName, card.bank); const pressHandler = onPress as CardPressHandler; let cardDescription; diff --git a/src/pages/settings/Wallet/PersonalCardDetailsPage.tsx b/src/pages/settings/Wallet/PersonalCardDetailsPage.tsx index 2fbcac94fe39..96d65aa92b4a 100644 --- a/src/pages/settings/Wallet/PersonalCardDetailsPage.tsx +++ b/src/pages/settings/Wallet/PersonalCardDetailsPage.tsx @@ -52,7 +52,7 @@ function PersonalCardDetailsPage({route}: PersonalCardDetailsPageProps) { const displayName = getDisplayNameOrDefault(cardholder); const isUserPersonalCard = !!(card && isPersonalCard(card)); const reimbursableSetting = card?.reimbursable ?? true; - const isCSVImportedPersonalCard = !!(isUserPersonalCard && card && (card.bank === CONST.COMPANY_CARDS.BANK_NAME.UPLOAD || card.bank.includes(CONST.COMPANY_CARD.FEED_BANK_NAME.CSV))); + const isCSVImportedPersonalCard = !!(isUserPersonalCard && card && (card.bank === CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD || card.bank.includes(CONST.COMPANY_CARD.FEED_BANK_NAME.CSV))); const removeCardFromUser = () => { setIsUnassignModalVisible(false); diff --git a/src/pages/settings/Wallet/WalletPage/index.tsx b/src/pages/settings/Wallet/WalletPage/index.tsx index 98ed6767a850..b1fdc5032bea 100644 --- a/src/pages/settings/Wallet/WalletPage/index.tsx +++ b/src/pages/settings/Wallet/WalletPage/index.tsx @@ -174,7 +174,7 @@ function WalletPage() { const assignedCardPressed = ({event, cardData, icon, cardID}: CardPressHandlerParams) => { paymentMethodButtonRef.current = event?.currentTarget as HTMLDivElement; setSelectedCard(cardData); - const isCSVImportCard = cardData?.bank === CONST.COMPANY_CARDS.BANK_NAME.UPLOAD; + const isCSVImportCard = cardData?.bank === CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD; const cardTitle = isCSVImportCard ? (cardData?.nameValuePairs?.cardTitle ?? cardData?.cardName) : maskCardNumber(cardData?.cardName, cardData?.bank); setPaymentMethod({ isSelectedPaymentMethodDefault: false, @@ -443,7 +443,7 @@ function WalletPage() { ); const cardThreeDotsMenuItems = useMemo(() => { - const shouldShowCSVImportItems = selectedCard?.bank === CONST.COMPANY_CARDS.BANK_NAME.UPLOAD && isBetaEnabled(CONST.BETAS.CSV_CARD_IMPORT); + const shouldShowCSVImportItems = selectedCard?.bank === CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD && isBetaEnabled(CONST.BETAS.CSV_CARD_IMPORT); return [ ...(shouldUseNarrowLayout ? [bottomMountItem] : []), { diff --git a/src/pages/workspace/companyCards/WorkspaceCompanyCardDetailsPage.tsx b/src/pages/workspace/companyCards/WorkspaceCompanyCardDetailsPage.tsx index b3173db647ce..93932b32ea5e 100644 --- a/src/pages/workspace/companyCards/WorkspaceCompanyCardDetailsPage.tsx +++ b/src/pages/workspace/companyCards/WorkspaceCompanyCardDetailsPage.tsx @@ -42,7 +42,7 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import type SCREENS from '@src/SCREENS'; -import type {CompanyCardFeed, CompanyCardFeedWithDomainID} from '@src/types/onyx'; +import type {CompanyCardFeedWithDomainID} from '@src/types/onyx'; import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; import {getExportMenuItem} from './utils'; @@ -82,7 +82,7 @@ function WorkspaceCompanyCardDetailsPage({route}: WorkspaceCompanyCardDetailsPag const isCardBeingUnassigned = globalCard?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE; const card = feedScopedCard ?? (isCardBeingUnassigned ? globalCard : undefined); - const cardBank = card?.bank ?? ''; + const cardBank = card?.bank; const cardholder = personalDetails?.[card?.accountID ?? CONST.DEFAULT_NUMBER_ID]; const displayName = getDisplayNameOrDefault(cardholder); const exportMenuItem = getExportMenuItem(connectedIntegration, policyID, translate, policy, card); @@ -148,7 +148,7 @@ function WorkspaceCompanyCardDetailsPage({route}: WorkspaceCompanyCardDetailsPag ) : ( ; @@ -67,9 +67,9 @@ function WorkspaceCompanyCardFeedSelectorPage({route}: WorkspaceCompanyCardFeedS return { value: feedName, - feed: feedSettings.feed as CompanyCardFeed, + feed: feedSettings.feed as CompanyCardFeedWithNumber, alternateText: domainName ?? policy?.name, - text: getCustomOrFormattedFeedName(translate, feedSettings.feed as CompanyCardFeed, feedSettings.customFeedName), + text: getCustomOrFormattedFeedName(translate, feedSettings.feed, feedSettings.customFeedName), keyForList: feedName, isSelected: feedName === selectedFeedName, isDisabled: feedSettings.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, @@ -83,7 +83,7 @@ function WorkspaceCompanyCardFeedSelectorPage({route}: WorkspaceCompanyCardFeedS /> ) : ( {({hovered}) => ( diff --git a/src/pages/workspace/companyCards/addNew/CardInstructionsStep.tsx b/src/pages/workspace/companyCards/addNew/CardInstructionsStep.tsx index f6c4f2b5cc29..93ebeeff8f7a 100644 --- a/src/pages/workspace/companyCards/addNew/CardInstructionsStep.tsx +++ b/src/pages/workspace/companyCards/addNew/CardInstructionsStep.tsx @@ -13,12 +13,12 @@ import useThemeStyles from '@hooks/useThemeStyles'; import useWorkspaceAccountID from '@hooks/useWorkspaceAccountID'; import {updateSelectedFeed} from '@libs/actions/Card'; import {setAddNewCompanyCardStepAndData} from '@libs/actions/CompanyCards'; -import {getBankName, getCompanyCardFeedWithDomainID} from '@libs/CardUtils'; +import {getBankName, getCardFeedWithDomainID} from '@libs/CardUtils'; import Parser from '@libs/Parser'; import Navigation from '@navigation/Navigation'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {CardFeedProvider} from '@src/types/onyx/CardFeeds'; +import type {CardFeedProvider, CompanyCardFeedWithDomainID} from '@src/types/onyx/CardFeeds'; type CardInstructionsStepProps = { policyID?: string; @@ -54,7 +54,7 @@ function CardInstructionsStep({policyID}: CardInstructionsStepProps) { const submit = () => { if (isStripeFeedProvider && policyID) { - updateSelectedFeed(getCompanyCardFeedWithDomainID(feedProvider, workspaceAccountID), policyID); + updateSelectedFeed(getCardFeedWithDomainID(feedProvider, workspaceAccountID) as CompanyCardFeedWithDomainID, policyID); Navigation.goBack(); return; } diff --git a/src/pages/workspace/companyCards/addNew/PlaidConnectionStep.tsx b/src/pages/workspace/companyCards/addNew/PlaidConnectionStep.tsx index 572e91f11404..1da4cdcb44a8 100644 --- a/src/pages/workspace/companyCards/addNew/PlaidConnectionStep.tsx +++ b/src/pages/workspace/companyCards/addNew/PlaidConnectionStep.tsx @@ -23,6 +23,7 @@ import {importPlaidAccounts, openPlaidCompanyCardLogin} from '@userActions/Plaid import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; 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}) { @@ -116,8 +117,8 @@ function PlaidConnectionStep({feed, policyID, onExit}: {feed?: CompanyCardFeedWi // on success we need to move to bank connection screen with token, bank name = plaid Log.info('[PlaidLink] Success!'); - const plaidConnectedFeed = - (metadata?.institution as PlaidLinkOnSuccessMetadata['institution'])?.institution_id ?? (metadata?.institution as LinkSuccessMetadata['institution'])?.id; + const plaidConnectedFeed = ((metadata?.institution as PlaidLinkOnSuccessMetadata['institution'])?.institution_id ?? + (metadata?.institution as LinkSuccessMetadata['institution'])?.id) as CardFeedWithNumber; const plaidConnectedFeedName = (metadata?.institution as PlaidLinkOnSuccessMetadata['institution'])?.name ?? (metadata?.institution as LinkSuccessMetadata['institution'])?.name; diff --git a/src/pages/workspace/companyCards/assignCard/ConfirmationStep.tsx b/src/pages/workspace/companyCards/assignCard/ConfirmationStep.tsx index 645f22b2db7e..ca168fda502a 100644 --- a/src/pages/workspace/companyCards/assignCard/ConfirmationStep.tsx +++ b/src/pages/workspace/companyCards/assignCard/ConfirmationStep.tsx @@ -107,12 +107,12 @@ function ConfirmationStep({route}: ConfirmationStepProps) { // Check both encryptedCardNumber and cardName since isCardAlreadyAssigned matches on either // This handles cases where workspace card entries only have cardName (masked display name) stored const cardIdentifier = cardToAssign?.encryptedCardNumber ?? cardToAssign?.cardName; - if (cardIdentifier && isCardAlreadyAssigned(cardIdentifier, workspaceCardFeeds)) { + if (cardIdentifier && isCardAlreadyAssigned(cardIdentifier, workspaceCardFeeds, domainOrWorkspaceAccountID)) { setCardError(getMicroSecondOnyxErrorWithTranslationKey('workspace.companyCards.cardAlreadyAssignedError')); return; } - assignWorkspaceCompanyCard(policy, domainOrWorkspaceAccountID, translate, feed, {...cardToAssign, cardholder, bankName}); + assignWorkspaceCompanyCard(policy, domainOrWorkspaceAccountID, translate, {...cardToAssign, cardholder, bankName}); }; const editStep = (step: string) => { diff --git a/src/pages/workspace/members/WorkspaceMemberDetailsPage.tsx b/src/pages/workspace/members/WorkspaceMemberDetailsPage.tsx index 3b8d01d98575..8bf017e21c14 100644 --- a/src/pages/workspace/members/WorkspaceMemberDetailsPage.tsx +++ b/src/pages/workspace/members/WorkspaceMemberDetailsPage.tsx @@ -32,7 +32,7 @@ import {removeApprovalWorkflow as removeApprovalWorkflowAction, updateApprovalWo import { getAllCardsForWorkspace, getCardFeedIcon, - getCompanyCardFeedWithDomainID, + getCardFeedWithDomainID, getCompanyFeeds, getPlaidInstitutionIconUrl, isExpensifyCardFullySetUp, @@ -58,7 +58,7 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import type SCREENS from '@src/SCREENS'; -import type {CompanyCardFeed, Card as MemberCard, PersonalDetails, PersonalDetailsList} from '@src/types/onyx'; +import type {CompanyCardFeed, CompanyCardFeedWithDomainID, Card as MemberCard, PersonalDetails, PersonalDetailsList} from '@src/types/onyx'; type WorkspacePolicyOnyxProps = { /** Personal details of all users */ @@ -253,7 +253,7 @@ function WorkspaceMemberDetailsPage({personalDetails, policy, route}: WorkspaceM Navigation.navigate( ROUTES.WORKSPACE_COMPANY_CARD_DETAILS.getRoute( policyID, - getCompanyCardFeedWithDomainID(card.bank as CompanyCardFeed, card.fundID), + getCardFeedWithDomainID(card.bank, card.fundID) as CompanyCardFeedWithDomainID, card.cardID.toString(), Navigation.getActiveRoute(), ), diff --git a/src/types/onyx/AssignCard.ts b/src/types/onyx/AssignCard.ts index 0145c8325986..91a892733eb3 100644 --- a/src/types/onyx/AssignCard.ts +++ b/src/types/onyx/AssignCard.ts @@ -2,7 +2,7 @@ import type {LinkAccount} from 'react-native-plaid-link-sdk'; import type {PlaidAccount} from 'react-plaid-link'; import type {ValueOf} from 'type-fest'; import type CONST from '@src/CONST'; -import type {CompanyCardFeed} from './CardFeeds'; +import type {CardFeedWithNumber} from './CardFeeds'; import type PersonalDetails from './PersonalDetails'; /** Assign card flow steps */ @@ -32,7 +32,7 @@ type AssignCardData = { encryptedCardNumber: string; /** The name of the feed */ - bankName: CompanyCardFeed; + bankName: CardFeedWithNumber; /** The masked card number displayed to users (e.g., "XXXX1234" or "VISA - 1234"). This is the original card identifier and should not be edited. */ cardName: string; @@ -51,7 +51,7 @@ type AssignCardData = { dateOption: string; /** Bank ID for Plaid */ - institutionId?: string; + institutionId?: CardFeedWithNumber; /** Access token for Plaid bank */ plaidAccessToken?: string; diff --git a/src/types/onyx/Card.ts b/src/types/onyx/Card.ts index cbfe77169606..111537fdee3f 100644 --- a/src/types/onyx/Card.ts +++ b/src/types/onyx/Card.ts @@ -1,5 +1,6 @@ import type {ValueOf} from 'type-fest'; import type CONST from '@src/CONST'; +import type {CardFeedWithNumber} from './CardFeeds'; import type * as OnyxCommon from './OnyxCommon'; import type PersonalDetails from './PersonalDetails'; @@ -21,7 +22,7 @@ type Card = OnyxCommon.OnyxValueWithOfflineFeedback<{ state: ValueOf; /** Bank name */ - bank: string; + bank: CardFeedWithNumber; /** Available amount to spend */ availableSpend?: number; @@ -381,10 +382,10 @@ export type { IssueNewCardStep, IssueNewCardData, WorkspaceCardsList, - CardAssignmentData, CardLimitType, ProvisioningCardData, AssignableCardsList, + CardAssignmentData, UnassignedCard, FrozenCardData, }; diff --git a/src/types/onyx/CardFeeds.ts b/src/types/onyx/CardFeeds.ts index 0b5c580a90d7..c75ff87b95a6 100644 --- a/src/types/onyx/CardFeeds.ts +++ b/src/types/onyx/CardFeeds.ts @@ -4,14 +4,43 @@ import type {ValueOf} from 'type-fest'; import type CONST from '@src/CONST'; import type * as OnyxCommon from './OnyxCommon'; -/** Card feed */ +/** Company card feed name */ type CompanyCardFeed = ValueOf; +/** Company card feed name with a number */ +type CompanyCardFeedWithNumber = CompanyCardFeed | `${CompanyCardFeed}${number}`; -/** Company card feed with domain ID */ -type CompanyCardFeedWithDomainID = `${CompanyCardFeed}${typeof CONST.COMPANY_CARD.FEED_KEY_SEPARATOR}${string}`; +/** Company card feed name with domain ID */ +type CompanyCardFeedWithDomainID = `${CompanyCardFeedWithNumber}${typeof CONST.COMPANY_CARD.FEED_KEY_SEPARATOR}${string}`; -/** Custom card feed with a number */ -type CompanyCardFeedWithNumber = CompanyCardFeed | `${CompanyCardFeed}${number}` | CompanyCardFeedWithDomainID; +/** + * Either a company card feed name or the Expensify card bank name. + */ +type CardFeed = CompanyCardFeed | typeof CONST.EXPENSIFY_CARD.BANK; + +/** + * Either a company card feed name or the Expensify card bank name with a number. + */ +type CardFeedWithNumber = CardFeed | `${CardFeed}${number}`; + +/** + * Card feed name with domain ID + */ +type CardFeedWithDomainID = `${CardFeedWithNumber}${typeof CONST.COMPANY_CARD.FEED_KEY_SEPARATOR}${string}`; + +/** + * Bank name + */ +type BankName = ValueOf; + +/** + * + */ +type CardType = ValueOf; + +/** + * Card type name + */ +type CardTypeName = ValueOf; /** Statement period end */ type StatementPeriodEnd = Exclude, typeof CONST.COMPANY_CARDS.STATEMENT_CLOSE_DATE.CUSTOM_DAY_OF_MONTH>; @@ -131,10 +160,7 @@ type DirectCardFeedData = OnyxCommon.OnyxValueWithOfflineFeedback<{ type CardFeedData = CustomCardFeedData | DirectCardFeedData; /** Both custom and direct company feeds */ -type CompanyFeeds = Partial>; - -/** Custom feed names */ -type CompanyCardNicknames = Partial>; +type CompanyFeeds = Partial>; /** Domain settings model */ type DomainSettings = { @@ -152,6 +178,9 @@ type DomainSettings = { /** Email to primary contact from the domain */ technicalContactEmail?: string; }; + + /** Whether we are loading the data via the API */ + isLoading?: boolean; }; /** Card feeds status */ @@ -171,20 +200,20 @@ type CardFeedsStatusByDomainID = Record; /** * Collection of card feeds status by domain ID */ -type WorkspaceCardFeedsStatus = Record; +type WorkspaceCardFeedsStatus = Record; /** Card feeds model, including domain settings */ type CardFeeds = { /** Feed settings */ settings: { /** User-friendly feed nicknames */ - companyCardNicknames?: CompanyCardNicknames; + companyCardNicknames?: Partial>; /** Company cards feeds */ - companyCards?: Partial>; + companyCards?: Partial>; /** Account details */ - oAuthAccountDetails?: Partial>; + oAuthAccountDetails?: Partial>; /** Collection of card feeds status by domain ID */ cardFeedsStatus?: WorkspaceCardFeedsStatus; @@ -234,7 +263,7 @@ type AddNewCardFeedData = { publicToken?: string; /** Feed from Plaid connection */ - plaidConnectedFeed?: string; + plaidConnectedFeed?: CardFeedWithNumber; /** Feed name from Plaid connection */ plaidConnectedFeedName?: string; @@ -268,21 +297,29 @@ type CombinedCardFeed = CustomCardFeedData & customFeedName?: string; /** Feed name */ - feed: CompanyCardFeedWithNumber; + feed: CardFeedWithNumber; /** Card feed status */ status?: CardFeedsStatus; }; /** Card feeds combined by domain ID into one object */ -type CombinedCardFeeds = Record; +type CombinedCardFeeds = Record; export default CardFeeds; export type { AddNewCardFeedStep, AddNewCompanyCardFeed, AddNewCardFeedData, + CardFeed, + CardFeedWithNumber, + CardFeedWithDomainID, + BankName, + CardType, + CardTypeName, CompanyCardFeed, + CompanyCardFeedWithNumber, + CompanyCardFeedWithDomainID, CardFeedDetails, DirectCardFeedData, CardFeedProvider, @@ -291,10 +328,7 @@ export type { CardFeedsStatusByDomainID, WorkspaceCardFeedsStatus, CompanyFeeds, - CompanyCardFeedWithDomainID, CustomCardFeedData, - CompanyCardNicknames, - CompanyCardFeedWithNumber, FundID, StatementPeriodEnd, StatementPeriodEndDay, diff --git a/src/types/onyx/DerivedValues.ts b/src/types/onyx/DerivedValues.ts index a8bdcd893be5..9f000585d883 100644 --- a/src/types/onyx/DerivedValues.ts +++ b/src/types/onyx/DerivedValues.ts @@ -3,7 +3,7 @@ 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 {CardFeedWithDomainID, CompanyCardFeedWithNumber} from './CardFeeds'; import type {Errors} from './OnyxCommon'; import type Report from './Report'; import type Transaction from './Transaction'; @@ -152,7 +152,7 @@ type AllCardFeedErrorsMap = Map>; /** * The errors of all card feeds. */ -type CardFeedErrorsObject = Record; +type CardFeedErrorsObject = Record; /** * The errors of card feeds. diff --git a/src/types/onyx/index.ts b/src/types/onyx/index.ts index d36862d429e9..92445b936dea 100644 --- a/src/types/onyx/index.ts +++ b/src/types/onyx/index.ts @@ -21,8 +21,10 @@ import type CardContinuousReconciliation from './CardContinuousReconciliation'; import type CardFeeds from './CardFeeds'; import type { AddNewCompanyCardFeed, + CardFeed, CardFeedsStatus, CardFeedsStatusByDomainID, + CardFeedWithDomainID, CombinedCardFeed, CombinedCardFeeds, CompanyCardFeed, @@ -208,6 +210,8 @@ export type { CombinedCardFeeds, CardContinuousReconciliation, CompanyCardFeedWithDomainID, + CardFeed, + CardFeedWithDomainID, LastExportMethod, Locale, LockAccountDetails, diff --git a/tests/unit/CardFeedErrorsDerivedValueTest.ts b/tests/unit/CardFeedErrorsDerivedValueTest.ts index 9e6304906ca8..16b03c17efa0 100644 --- a/tests/unit/CardFeedErrorsDerivedValueTest.ts +++ b/tests/unit/CardFeedErrorsDerivedValueTest.ts @@ -1,10 +1,11 @@ import type {OnyxCollection} from 'react-native-onyx'; import type {DerivedValueContext} from '@libs/actions/OnyxDerived/types'; -import {getCompanyCardFeedWithDomainID} from '@libs/CardUtils'; +import {getCardFeedWithDomainID} from '@libs/CardUtils'; import CONST from '@src/CONST'; import cardFeedErrorsConfig from '@src/libs/actions/OnyxDerived/configs/cardFeedErrors'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Card, CardFeeds, CardList, CompanyCardFeed, CompanyCardFeedWithDomainID, WorkspaceCardsList} from '@src/types/onyx'; +import type {Card, CardFeeds, CardList, WorkspaceCardsList} from '@src/types/onyx'; +import type {CardFeedWithDomainID, CardFeedWithNumber} from '@src/types/onyx/CardFeeds'; const DERIVED_VALUE_CONTEXT: DerivedValueContext = { currentValue: undefined, @@ -16,25 +17,25 @@ const CARD_FEEDS = { [CONST.COMPANY_CARD.FEED_BANK_NAME.CHASE]: { workspaceAccountID: 44444444, feedName: CONST.COMPANY_CARD.FEED_BANK_NAME.CHASE, - feedNameWithDomainID: getCompanyCardFeedWithDomainID(CONST.COMPANY_CARD.FEED_BANK_NAME.CHASE, 44444444), + feedNameWithDomainID: getCardFeedWithDomainID(CONST.COMPANY_CARD.FEED_BANK_NAME.CHASE, 44444444), }, [CONST.COMPANY_CARD.FEED_BANK_NAME.MASTER_CARD]: { workspaceAccountID: 55555555, feedName: CONST.COMPANY_CARD.FEED_BANK_NAME.MASTER_CARD, - feedNameWithDomainID: getCompanyCardFeedWithDomainID(CONST.COMPANY_CARD.FEED_BANK_NAME.MASTER_CARD, 55555555), + feedNameWithDomainID: getCardFeedWithDomainID(CONST.COMPANY_CARD.FEED_BANK_NAME.MASTER_CARD, 55555555), }, [CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX_DIRECT]: { workspaceAccountID: 66666666, feedName: CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX_DIRECT, - feedNameWithDomainID: getCompanyCardFeedWithDomainID(CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX_DIRECT, 66666666), + feedNameWithDomainID: getCardFeedWithDomainID(CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX_DIRECT, 66666666), }, } as const satisfies Partial< Record< - CompanyCardFeed, + CardFeedWithNumber, { workspaceAccountID: number; - feedName: CompanyCardFeed; - feedNameWithDomainID: CompanyCardFeedWithDomainID; + feedName: CardFeedWithNumber; + feedNameWithDomainID: CardFeedWithDomainID; } > >; diff --git a/tests/unit/CardUtilsTest.ts b/tests/unit/CardUtilsTest.ts index 6727ae71574f..9acc2e6f7d70 100644 --- a/tests/unit/CardUtilsTest.ts +++ b/tests/unit/CardUtilsTest.ts @@ -8,8 +8,10 @@ import type {CombinedCardFeeds} from '@src/hooks/useCardFeeds'; import IntlStore from '@src/languages/IntlStore'; import { doesCardFeedExist, + filterAllInactiveCards, + filterCardsByNonExpensify, filterInactiveCards, - flatAllCardsList, + flattenWorkspaceCardsList, formatCardExpiration, getAllCardsForWorkspace, getAssignedCardSortKey, @@ -17,10 +19,10 @@ import { getBankName, getCardDescription, getCardFeedIcon, + getCardFeedWithDomainID, getCardsByCardholderName, getCompanyCardDescription, getCompanyCardFeed, - getCompanyCardFeedWithDomainID, getCompanyFeeds, getCustomFeedNameFromFeeds, getCustomOrFormattedFeedName, @@ -43,10 +45,11 @@ import { lastFourNumbersFromCardName, maskCardNumber, sortCardsByCardholderName, + splitCardFeedWithDomainID, splitMaskedCardNumber, } from '@src/libs/CardUtils'; import type {Card, CardFeeds, CardList, CompanyCardFeed, CompanyCardFeedWithDomainID, ExpensifyCardSettings, PersonalDetailsList, Policy, WorkspaceCardsList} from '@src/types/onyx'; -import type {CompanyCardFeedWithNumber} from '@src/types/onyx/CardFeeds'; +import type {CardFeedWithDomainID, CardFeedWithNumber, CompanyCardFeedWithNumber} from '@src/types/onyx/CardFeeds'; import type IconAsset from '@src/types/utils/IconAsset'; import {localeCompare, translateLocal} from '../utils/TestHelper'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; @@ -323,10 +326,10 @@ const cardFeedsCollection: OnyxCollection = { /* eslint-disable @typescript-eslint/naming-convention */ const allCardsList = { - 'cards_11111111_oauth.capitalone.com': directFeedCardsMultipleList, - cards_11111111_vcf1: customFeedCardsList, - 'cards_22222222_oauth.chase.com': directFeedCardsSingleList, - 'cards_11111111_Expensify Card': { + [`cards_11111111_${CONST.COMPANY_CARD.FEED_BANK_NAME.CAPITAL_ONE}`]: directFeedCardsMultipleList, + [`cards_11111111_${CONST.COMPANY_CARD.FEED_BANK_NAME.VISA}1`]: customFeedCardsList, + [`cards_22222222_${CONST.COMPANY_CARD.FEED_BANK_NAME.CHASE}`]: directFeedCardsSingleList, + [`cards_11111111_${CONST.EXPENSIFY_CARD.BANK}`]: { '21570657': { accountID: 18439984, bank: CONST.EXPENSIFY_CARD.BANK, @@ -340,7 +343,7 @@ const allCardsList = { state: 2, }, }, - 'cards_10101_Expensify Card': { + [`cards_10101_${CONST.EXPENSIFY_CARD.BANK}`]: { '21570657': { accountID: 18439984, bank: CONST.EXPENSIFY_CARD.BANK, @@ -768,12 +771,12 @@ describe('CardUtils', () => { }); it('Should return CSV import card display name without 4-character formatting', () => { - const maskedCardNumber = maskCardNumber('Checking', CONST.COMPANY_CARDS.BANK_NAME.UPLOAD); + const maskedCardNumber = maskCardNumber('Checking', CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD); expect(maskedCardNumber).toBe('Checking'); }); it('Should return CSV import card display name as-is for longer names', () => { - const maskedCardNumber = maskCardNumber('JustChecking', CONST.COMPANY_CARDS.BANK_NAME.UPLOAD); + const maskedCardNumber = maskCardNumber('JustChecking', CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD); expect(maskedCardNumber).toBe('JustChecking'); }); }); @@ -786,13 +789,13 @@ describe('CardUtils', () => { }); it('Should return a valid name if an OldDot feed variation was provided', () => { - const feed = 'oauth.americanexpressfdx.com 2003' as CompanyCardFeed; + const feed = `${CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX_DIRECT} 2003` as CompanyCardFeed; const feedName = getBankName(feed); expect(feedName).toBe('American Express'); }); it('Should return a valid name if a CSV imported feed variation was provided', () => { - const feed = 'cards_2267989_ccupload666' as CompanyCardFeed; + const feed = `cards_10101_${CONST.COMPANY_CARD.FEED_BANK_NAME.CSV}666` as CompanyCardFeed; const feedName = getBankName(feed); expect(feedName).toBe('CSV'); }); @@ -1018,10 +1021,10 @@ describe('CardUtils', () => { }); }); - describe('flatAllCardsList', () => { + describe('flattenCompanyCards', () => { it('should return the flattened list of non-Expensify cards related to the provided workspaceAccountID', () => { const workspaceAccountID = 11111111; - const flattenedCardsList = flatAllCardsList(allCardsList, workspaceAccountID); + const flattenedCardsList = flattenWorkspaceCardsList(allCardsList, workspaceAccountID); const {cardList, ...customCards} = customFeedCardsList; expect(flattenedCardsList).toStrictEqual({ ...directFeedCardsMultipleList, @@ -1031,7 +1034,7 @@ describe('CardUtils', () => { it('should return undefined if not defined cards list was provided', () => { const workspaceAccountID = 11111111; - const flattenedCardsList = flatAllCardsList(undefined, workspaceAccountID); + const flattenedCardsList = flattenWorkspaceCardsList(undefined, workspaceAccountID); expect(flattenedCardsList).toBeUndefined(); }); }); @@ -1072,7 +1075,7 @@ describe('CardUtils', () => { }, '21570655': { accountID: 18439984, - bank: 'oauth.capitalone.com', + bank: CONST.COMPANY_CARD.FEED_BANK_NAME.CAPITAL_ONE, cardID: 21570655, cardName: 'CREDIT CARD...5678', domainName: 'expensify-policy17f617b9fe23d2f1.exfy', @@ -1086,7 +1089,7 @@ describe('CardUtils', () => { }, '21570656': { accountID: 18439984, - bank: 'oauth.capitalone.com', + bank: CONST.COMPANY_CARD.FEED_BANK_NAME.CAPITAL_ONE, cardID: 21570656, cardName: 'CREDIT CARD...4444', domainName: 'expensify-policy17f617b9fe23d2f1.exfy', @@ -1100,7 +1103,7 @@ describe('CardUtils', () => { }, '21570657': { accountID: 18439984, - bank: 'Expensify Card', + bank: CONST.EXPENSIFY_CARD.BANK, cardID: 21570657, cardName: 'CREDIT CARD...5644', domainName: 'expensify-policy17f617b9fe23d2f1.exfy', @@ -1238,7 +1241,7 @@ describe('CardUtils', () => { cardID: 1, accountID: 1, cardName: 'Card 1', - bank: 'expensify', + bank: CONST.EXPENSIFY_CARD.BANK, domainName: 'expensify-policy17f617b9fe23d2f1.exfy', fraud: 'none', lastFourPAN: '', @@ -1249,7 +1252,7 @@ describe('CardUtils', () => { '2': { cardID: 2, accountID: 2, - bank: 'expensify', + bank: CONST.EXPENSIFY_CARD.BANK, cardName: 'Card 2', domainName: 'expensify-policy17f617b9fe23d2f1.exfy', fraud: 'none', @@ -1261,7 +1264,7 @@ describe('CardUtils', () => { '3': { cardID: 3, accountID: 3, - bank: 'expensify', + bank: CONST.EXPENSIFY_CARD.BANK, cardName: 'Card 3', domainName: 'expensify-policy17f617b9fe23d2f1.exfy', fraud: 'none', @@ -1319,7 +1322,7 @@ describe('CardUtils', () => { cardID: 1, accountID: 1, cardName: 'Card 1', - bank: 'expensify', + bank: CONST.EXPENSIFY_CARD.BANK, domainName: 'expensify-policy17f617b9fe23d2f1.exfy', fraud: 'none', lastFourPAN: '', @@ -1330,7 +1333,7 @@ describe('CardUtils', () => { '2': { cardID: 2, cardName: 'Card 2', - bank: 'expensify', + bank: CONST.EXPENSIFY_CARD.BANK, domainName: 'expensify-policy17f617b9fe23d2f1.exfy', fraud: 'none', lastFourPAN: '', @@ -1382,7 +1385,7 @@ describe('CardUtils', () => { state: 2, }; const description = getCardDescription(card, translateLocal); - expect(description).toBe('Expensify Card'); + expect(description).toBe(CONST.EXPENSIFY_CARD.BANK); }); }); @@ -1491,24 +1494,73 @@ describe('CardUtils', () => { }); }); - describe('getCompanyCardFeedWithDomainID', () => { + describe('getCardFeedWithDomainID', () => { it('should combine feed name domain ID', () => { const feedName = CONST.COMPANY_CARD.FEED_BANK_NAME.VISA; const domainID = 11111111; - const combinedKey = getCompanyCardFeedWithDomainID(feedName, domainID); + const combinedKey = getCardFeedWithDomainID(feedName, domainID); expect(combinedKey).toBe(`${feedName}${CONST.COMPANY_CARD.FEED_KEY_SEPARATOR}${domainID}`); }); }); + describe('splitCardFeedWithDomainID', () => { + it('should split the feed name and domain ID', () => { + const feedName = 'vcf#11111111'; + + const splitFeedName = splitCardFeedWithDomainID(feedName); + if (!splitFeedName) { + throw new Error('Failed to split feed name'); + } + + expect(splitFeedName.feedName).toBe('vcf'); + expect(splitFeedName.domainID).toBe(11111111); + }); + + it('should return undefined for a feed name without separator', () => { + const result = splitCardFeedWithDomainID('vcf'); + expect(result).toBeUndefined(); + }); + + it('should return undefined for undefined input', () => { + const result = splitCardFeedWithDomainID(undefined); + expect(result).toBeUndefined(); + }); + + it('should return undefined when domainID is not a number', () => { + const result = splitCardFeedWithDomainID('vcf#abc' as CardFeedWithDomainID); + expect(result).toBeUndefined(); + }); + + it('should return undefined when there are multiple separators', () => { + const result = splitCardFeedWithDomainID('vcf#123#456' as CardFeedWithDomainID); + expect(result).toBeUndefined(); + }); + + it('should handle direct feed with domain ID', () => { + const result = splitCardFeedWithDomainID(`${CONST.COMPANY_CARD.FEED_BANK_NAME.CHASE}#22222222` as CardFeedWithDomainID); + expect(result).toEqual({feedName: CONST.COMPANY_CARD.FEED_BANK_NAME.CHASE, domainID: 22222222}); + }); + + it('should handle custom feed with number and domain ID', () => { + const result = splitCardFeedWithDomainID('vcf1#99999' as CardFeedWithDomainID); + expect(result).toEqual({feedName: 'vcf1', domainID: 99999}); + }); + + it('should handle plaid feed with domain ID', () => { + const result = splitCardFeedWithDomainID('plaid.ins_129663#12345' as CardFeedWithDomainID); + expect(result).toEqual({feedName: 'plaid.ins_129663', domainID: 12345}); + }); + }); + describe('getPlaidInstitutionId', () => { it('should return institution ID from plaid feed name without domain ID', () => { - const feedName = 'plaid.ins_123456'; + const feedName = 'plaid.ins_123456' as CardFeedWithNumber; const institutionId = getPlaidInstitutionId(feedName); expect(institutionId).toBe('ins_123456'); }); it('should return institution ID from plaid feed name with domain ID', () => { - const feedName = 'plaid.ins_129663#12345'; + const feedName = 'plaid.ins_129663#12345' as CardFeedWithDomainID; const institutionId = getPlaidInstitutionId(feedName); expect(institutionId).toBe('ins_129663'); }); @@ -1522,13 +1574,13 @@ describe('CardUtils', () => { describe('getPlaidInstitutionIconUrl', () => { it('should return correct icon URL for plaid feed without domain ID', () => { - const feedName = 'plaid.ins_123456'; + const feedName = 'plaid.ins_123456' as CardFeedWithNumber; const iconUrl = getPlaidInstitutionIconUrl(feedName); expect(iconUrl).toBe(`${CONST.COMPANY_CARD_PLAID}ins_123456.png`); }); it('should return correct icon URL for plaid feed with domain ID', () => { - const feedName = 'plaid.ins_129663#12345'; + const feedName = 'plaid.ins_129663#12345' as CardFeedWithDomainID; const iconUrl = getPlaidInstitutionIconUrl(feedName); expect(iconUrl).toBe(`${CONST.COMPANY_CARD_PLAID}ins_129663.png`); }); @@ -1566,6 +1618,202 @@ describe('CardUtils', () => { }); }); + describe('filterCardsByNonExpensify', () => { + it('should filter out cards with Expensify bank key in their key', () => { + const cards: CardList = { + [`${CONST.EXPENSIFY_CARD.BANK}_card1`]: { + cardID: 1, + bank: CONST.EXPENSIFY_CARD.BANK, + cardName: 'Expensify Card', + domainName: 'test.exfy', + fraud: 'none', + lastFourPAN: '1234', + lastScrape: '', + lastUpdated: '', + state: 3, + }, + visa_card2: { + cardID: 2, + bank: CONST.COMPANY_CARD.FEED_BANK_NAME.VISA, + cardName: 'Visa Card', + domainName: 'test.exfy', + fraud: 'none', + lastFourPAN: '5678', + lastScrape: '', + lastUpdated: '', + state: 3, + }, + chase_card3: { + cardID: 3, + bank: CONST.COMPANY_CARD.FEED_BANK_NAME.CHASE, + cardName: 'Chase Card', + domainName: 'test.exfy', + fraud: 'none', + lastFourPAN: '9012', + lastScrape: '', + lastUpdated: '', + state: 3, + }, + } as unknown as CardList; + + const result = filterCardsByNonExpensify(cards); + const keys = Object.keys(result); + expect(keys).toHaveLength(2); + expect(keys).toContain('visa_card2'); + expect(keys).toContain('chase_card3'); + expect(keys).not.toContain(`${CONST.EXPENSIFY_CARD.BANK}_card1`); + }); + + it('should return empty object when all cards are Expensify cards', () => { + const cards: CardList = { + [`${CONST.EXPENSIFY_CARD.BANK}_1`]: { + cardID: 1, + bank: CONST.EXPENSIFY_CARD.BANK, + cardName: 'Expensify Card 1', + domainName: 'test.exfy', + fraud: 'none', + lastFourPAN: '1111', + lastScrape: '', + lastUpdated: '', + state: 3, + }, + } as unknown as CardList; + + const result = filterCardsByNonExpensify(cards); + expect(Object.keys(result)).toHaveLength(0); + }); + + it('should return empty object when undefined is passed', () => { + const result = filterCardsByNonExpensify(undefined); + expect(result).toEqual({}); + }); + + it('should return all cards when none are Expensify cards', () => { + const cards: CardList = { + visa_1: { + cardID: 1, + bank: CONST.COMPANY_CARD.FEED_BANK_NAME.VISA, + cardName: 'Visa', + domainName: 'test.exfy', + fraud: 'none', + lastFourPAN: '1111', + lastScrape: '', + lastUpdated: '', + state: 3, + }, + chase_2: { + cardID: 2, + bank: CONST.COMPANY_CARD.FEED_BANK_NAME.CHASE, + cardName: 'Chase', + domainName: 'test.exfy', + fraud: 'none', + lastFourPAN: '2222', + lastScrape: '', + lastUpdated: '', + state: 3, + }, + } as unknown as CardList; + + const result = filterCardsByNonExpensify(cards); + expect(Object.keys(result)).toHaveLength(2); + }); + }); + + describe('filterAllInactiveCards', () => { + it('should filter out closed, deactivated and suspended cards', () => { + const cards: CardList = { + '1': {cardID: 1, state: CONST.EXPENSIFY_CARD.STATE.OPEN, bank: 'vcf', cardName: 'a', domainName: '', fraud: 'none', lastFourPAN: '', lastScrape: '', lastUpdated: ''}, + '2': {cardID: 2, state: CONST.EXPENSIFY_CARD.STATE.CLOSED, bank: 'vcf', cardName: 'b', domainName: '', fraud: 'none', lastFourPAN: '', lastScrape: '', lastUpdated: ''}, + '3': { + cardID: 3, + state: CONST.EXPENSIFY_CARD.STATE.STATE_DEACTIVATED, + bank: 'vcf', + cardName: 'c', + domainName: '', + fraud: 'none', + lastFourPAN: '', + lastScrape: '', + lastUpdated: '', + }, + '4': { + cardID: 4, + state: CONST.EXPENSIFY_CARD.STATE.STATE_SUSPENDED, + bank: 'vcf', + cardName: 'd', + domainName: '', + fraud: 'none', + lastFourPAN: '', + lastScrape: '', + lastUpdated: '', + }, + '5': { + cardID: 5, + state: CONST.EXPENSIFY_CARD.STATE.NOT_ACTIVATED, + bank: 'vcf', + cardName: 'e', + domainName: '', + fraud: 'none', + lastFourPAN: '', + lastScrape: '', + lastUpdated: '', + }, + } as unknown as CardList; + + const result = filterAllInactiveCards(cards); + const ids = Object.values(result).map((c) => c.cardID); + expect(ids).toContain(1); + expect(ids).toContain(5); + expect(ids).not.toContain(2); + expect(ids).not.toContain(3); + expect(ids).not.toContain(4); + }); + + it('should return empty object when undefined is passed', () => { + const result = filterAllInactiveCards(undefined); + expect(result).toEqual({}); + }); + + it('should return all cards when none are inactive', () => { + const cards: CardList = { + '1': {cardID: 1, state: CONST.EXPENSIFY_CARD.STATE.OPEN, bank: 'vcf', cardName: 'a', domainName: '', fraud: 'none', lastFourPAN: '', lastScrape: '', lastUpdated: ''}, + '2': { + cardID: 2, + state: CONST.EXPENSIFY_CARD.STATE.NOT_ACTIVATED, + bank: 'vcf', + cardName: 'b', + domainName: '', + fraud: 'none', + lastFourPAN: '', + lastScrape: '', + lastUpdated: '', + }, + } as unknown as CardList; + + const result = filterAllInactiveCards(cards); + expect(Object.keys(result)).toHaveLength(2); + }); + + it('should return empty object when all cards are inactive', () => { + const cards: CardList = { + '1': {cardID: 1, state: CONST.EXPENSIFY_CARD.STATE.CLOSED, bank: 'vcf', cardName: 'a', domainName: '', fraud: 'none', lastFourPAN: '', lastScrape: '', lastUpdated: ''}, + '2': { + cardID: 2, + state: CONST.EXPENSIFY_CARD.STATE.STATE_DEACTIVATED, + bank: 'vcf', + cardName: 'b', + domainName: '', + fraud: 'none', + lastFourPAN: '', + lastScrape: '', + lastUpdated: '', + }, + } as unknown as CardList; + + const result = filterAllInactiveCards(cards); + expect(Object.keys(result)).toHaveLength(0); + }); + }); + describe('UnassignedCard type through getFilteredCardList', () => { describe('Commercial feeds (VCF, MCF, etc.) - cardID is encrypted value', () => { it('should return UnassignedCard with cardID being the encrypted value from cardList', () => { diff --git a/tests/unit/ReportActionsUtilsTest.ts b/tests/unit/ReportActionsUtilsTest.ts index 24a06868b876..cf90d65d8b46 100644 --- a/tests/unit/ReportActionsUtilsTest.ts +++ b/tests/unit/ReportActionsUtilsTest.ts @@ -1437,7 +1437,7 @@ describe('ReportActionsUtils', () => { const activeExpensifyCard: Card = { cardID: 789, state: CONST.EXPENSIFY_CARD.STATE.OPEN, - bank: '', + bank: 'Expensify Card', availableSpend: 0, domainName: '', lastFourPAN: '', diff --git a/tests/unit/Search/buildCardFilterDataTest.ts b/tests/unit/Search/buildCardFilterDataTest.ts index 30d6ebbf19bf..23ebbea6bee2 100644 --- a/tests/unit/Search/buildCardFilterDataTest.ts +++ b/tests/unit/Search/buildCardFilterDataTest.ts @@ -2,6 +2,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ import type {LocaleContextProps} from '@components/LocaleContextProvider'; import {buildCardFeedsData, buildCardsData} from '@libs/CardFeedUtils'; +import type {DomainFeedData} from '@libs/CardFeedUtils'; import type IllustrationsType from '@styles/theme/illustrations/types'; import type {CardList, Policy, WorkspaceCardsList} from '@src/types/onyx'; @@ -295,7 +296,7 @@ const cardListClosed = { const domainFeedDataMock = { 'mockDomain.com': {domainName: 'mockDomain.com', bank: 'Expensify Card', correspondingCardIDs: ['21589168', '21589182']}, -}; +} as const satisfies Record; const translateMock = jest.fn(); diff --git a/tests/unit/useGetExpensifyCardFromReportActionTest.ts b/tests/unit/useGetExpensifyCardFromReportActionTest.ts index 7ebcbe8ddac4..fbc20a640d81 100644 --- a/tests/unit/useGetExpensifyCardFromReportActionTest.ts +++ b/tests/unit/useGetExpensifyCardFromReportActionTest.ts @@ -36,7 +36,7 @@ describe('useGetExpensifyCardFromReportAction', () => { lastUpdated: '2023-01-01T00:00:00.000Z', fraud: CONST.EXPENSIFY_CARD.FRAUD_TYPES.NONE, state: CONST.EXPENSIFY_CARD.STATE.OPEN, - bank: 'Test Bank', + bank: 'Expensify Card', }; const createMockReportAction = (cardID = 123): ReportAction => ({ diff --git a/tests/unit/useIndicatorStatusTest.tsx b/tests/unit/useIndicatorStatusTest.tsx index 954f47aad941..3b12e1ac574d 100644 --- a/tests/unit/useIndicatorStatusTest.tsx +++ b/tests/unit/useIndicatorStatusTest.tsx @@ -261,19 +261,18 @@ const getMockForTestCase = ({name, status}: IndicatorTestCase, isAdmin: boolean) [ONYXKEYS.SUBSCRIPTION_RETRY_BILLING_STATUS_SUCCESSFUL]: status === CONST.INDICATOR_STATUS.HAS_SUBSCRIPTION_INFO, [ONYXKEYS.SUBSCRIPTION_RETRY_BILLING_STATUS_FAILED]: status === CONST.INDICATOR_STATUS.HAS_SUBSCRIPTION_ERRORS, [ONYXKEYS.CARD_LIST]: { - // eslint-disable-next-line @typescript-eslint/naming-convention - '123456': { + card1: { + bank: CONST.COMPANY_CARD.FEED_BANK_NAME.CHASE, + lastScrapeResult: name === cardFeedErrorTestCases.admin.name || name === cardFeedErrorTestCases.employee.name ? 403 : 200, + fundID: String(brokenCardFeed.workspaceAccountID), + }, + card2: { cardID: 123456, bank: CONST.EXPENSIFY_CARD.BANK, accountID: 123, fundID: String(brokenCardFeed.workspaceAccountID), state: status === CONST.INDICATOR_STATUS.HAS_PENDING_CARD_INFO ? CONST.EXPENSIFY_CARD.STATE.STATE_NOT_ISSUED : CONST.EXPENSIFY_CARD.STATE.OPEN, }, - card1: { - bank: 'OTHER_BANK', - lastScrapeResult: name === cardFeedErrorTestCases.admin.name || name === cardFeedErrorTestCases.employee.name ? 403 : 200, - fundID: String(brokenCardFeed.workspaceAccountID), - }, }, [ONYXKEYS.PRIVATE_PERSONAL_DETAILS]: { legalFirstName: 'John', diff --git a/tests/utils/collections/card.ts b/tests/utils/collections/card.ts index 01cc89285ced..c1aeab2d7988 100644 --- a/tests/utils/collections/card.ts +++ b/tests/utils/collections/card.ts @@ -3,11 +3,12 @@ import {format} from 'date-fns'; import type {ValueOf} from 'type-fest'; import CONST from '@src/CONST'; import type {Card} from '@src/types/onyx'; +import type {CardFeedWithNumber} from '@src/types/onyx/CardFeeds'; export default function createRandomCard( index: number, options?: { - bank?: string; + bank?: CardFeedWithNumber; fundID?: string; state?: ValueOf; fraud?: ValueOf; @@ -16,7 +17,15 @@ export default function createRandomCard( }, ): 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 bank = + options?.bank ?? + (rand([ + CONST.EXPENSIFY_CARD.BANK, + CONST.COMPANY_CARD.FEED_BANK_NAME.VISA, + CONST.COMPANY_CARD.FEED_BANK_NAME.STRIPE, + CONST.COMPANY_CARD.FEED_BANK_NAME.CHASE, + CONST.COMPANY_CARD.FEED_BANK_NAME.CAPITAL_ONE, + ]) as CardFeedWithNumber); 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(); @@ -81,12 +90,18 @@ function createRandomExpensifyCard( function createRandomCompanyCard( index: number, options?: { - bank?: string; + bank?: CardFeedWithNumber; accountID?: number; domainName?: string; }, ): Card { - const banks = ['vcf', 'stripe', 'oauth.chase.com', 'oauth.capitalone.com', 'oauth.citibank.com']; + const banks = [ + CONST.COMPANY_CARD.FEED_BANK_NAME.VISA, + CONST.COMPANY_CARD.FEED_BANK_NAME.STRIPE, + CONST.COMPANY_CARD.FEED_BANK_NAME.CHASE, + CONST.COMPANY_CARD.FEED_BANK_NAME.CAPITAL_ONE, + CONST.COMPANY_CARD.FEED_BANK_NAME.CITIBANK, + ]; return createRandomCard(index, { ...options, bank: options?.bank ?? rand(banks),