From 319a50bc1826c8077450a042c73cc71d1bd2666e Mon Sep 17 00:00:00 2001 From: Shubham Agrawal Date: Mon, 6 Jul 2026 23:25:42 +0530 Subject: [PATCH 1/4] Cleanup functions that are being referenced in test only which escaped knip --- src/hooks/useFrozenPreSelection.ts | 85 ----- src/hooks/useMappedPersonalDetails.ts | 24 -- src/libs/Avatars/InitialAvatars.ts | 50 +-- src/libs/CardFeedUtils.ts | 347 +----------------- src/libs/CardUtils.ts | 75 ---- src/libs/OptionsListUtils/index.ts | 21 -- src/libs/PersonalDetailsUtils.ts | 14 - src/libs/PolicyUtils.ts | 5 - src/libs/ReportTitleUtils.ts | 52 +-- src/libs/ReportUtils.ts | 12 - src/libs/UserAvatarUtils.ts | 13 - src/libs/actions/IOU/ReportWorkflow.ts | 18 - src/pages/inbox/conciergeDraftState.ts | 14 +- src/selectors/Policy.ts | 23 +- tests/actions/IOUTest/ReportWorkflowTest.ts | 33 -- tests/unit/CardFeedUtilsTest.ts | 177 +-------- tests/unit/CardUtilsTest.ts | 224 ----------- tests/unit/OptionsListUtilsTest.tsx | 94 ----- tests/unit/ReportTitleUtilsTest.ts | 67 +--- tests/unit/ReportUtilsTest.ts | 85 ----- tests/unit/Search/buildCardFilterDataTest.ts | 68 +--- .../unit/Search/yourSpendApplicabilityTest.ts | 53 +-- tests/unit/UserAvatarUtilsTest.ts | 2 +- tests/unit/getLetterAvatarSchemeTest.ts | 21 -- .../unit/hooks/useFrozenPreSelection.test.ts | 200 ---------- .../hooks/useMappedPersonalDetails.test.ts | 95 ----- .../unit/libs/Avatars/InitialAvatarsTest.tsx | 28 +- .../__snapshots__/InitialAvatarsTest.tsx.snap | 18 - tests/unit/libs/PersonalDetailsUtilsTest.ts | 47 --- .../pages/inbox/conciergeDraftState.test.ts | 108 +----- tests/unit/selectors/PolicyTest.ts | 67 ---- 31 files changed, 17 insertions(+), 2123 deletions(-) delete mode 100644 src/hooks/useFrozenPreSelection.ts delete mode 100644 src/hooks/useMappedPersonalDetails.ts delete mode 100644 tests/unit/getLetterAvatarSchemeTest.ts delete mode 100644 tests/unit/hooks/useFrozenPreSelection.test.ts delete mode 100644 tests/unit/hooks/useMappedPersonalDetails.test.ts delete mode 100644 tests/unit/libs/Avatars/__snapshots__/InitialAvatarsTest.tsx.snap diff --git a/src/hooks/useFrozenPreSelection.ts b/src/hooks/useFrozenPreSelection.ts deleted file mode 100644 index d2acde8d4b06..000000000000 --- a/src/hooks/useFrozenPreSelection.ts +++ /dev/null @@ -1,85 +0,0 @@ -import type {ListItem} from '@components/SelectionList/ListItem/types'; -import type {Section} from '@components/SelectionList/SelectionListWithSections/types'; - -import CONST from '@src/CONST'; - -import {useState} from 'react'; - -type UseFrozenPreSelectionOptions = { - /** Item identifiers to pin on first capture. Matched against `getKey(item)`, or `item.keyForList` if `getKey` is omitted. */ - initialSelectedValues: string[]; - - /** Set to `true` once the sections are ready to inspect — capture fires on the next render. */ - canCapture: boolean; - - /** Optional filter for pinned rows (e.g. to honor a search term). Needed when pinned rows may not appear in the input `sections`. */ - shouldRenderPinned?: (item: TItem) => boolean; - - /** Optional identity extractor. Defaults to `item.keyForList`. Override when the caller's identifier doesn't match `keyForList`. */ - getKey?: (item: TItem) => string | undefined; -}; - -/** - * Pins pre-selected rows to a top section on first ready render, then locks them in place. - * Toggling a pinned row updates `isSelected` without moving it. - * Returns `sections` unchanged while not ready, or when the list is shorter than `STANDARD_LIST_ITEM_LIMIT`. - */ -function useFrozenPreSelection(sections: Array>, options: UseFrozenPreSelectionOptions): Array> { - const {initialSelectedValues, canCapture, shouldRenderPinned, getKey} = options; - const resolveKey = (item: TItem) => (getKey ? getKey(item) : item.keyForList); - - // null = not captured yet; empty Map = captured but the list was too short to pin. - const [frozenData, setFrozenData] = useState | null>(null); - - if (frozenData === null && canCapture) { - const totalCount = sections.reduce((sum, section) => sum + section.data.length, 0); - if (totalCount < CONST.STANDARD_LIST_ITEM_LIMIT) { - setFrozenData(new Map()); - } else { - const captured = new Map(); - for (const section of sections) { - for (const item of section.data) { - const key = resolveKey(item); - if (key && initialSelectedValues.includes(key)) { - captured.set(key, {...item, isSelected: false}); - } - } - } - setFrozenData(captured); - } - } - - if (!frozenData || frozenData.size === 0) { - return sections; - } - - const frozenSectionData = new Map(shouldRenderPinned ? frozenData : undefined); - const filteredSections = sections.map((section) => { - const data: TItem[] = []; - for (const item of section.data) { - const key = resolveKey(item); - if (key && frozenData.has(key)) { - frozenSectionData.set(key, {...item, isSelected: item.isSelected}); - } else { - data.push(item); - } - } - return {...section, data}; - }); - - if (shouldRenderPinned) { - for (const [key, value] of frozenSectionData) { - if (!shouldRenderPinned(value)) { - frozenSectionData.delete(key); - } - } - } - - if (frozenSectionData.size === 0) { - return filteredSections; - } - - return [{data: [...frozenSectionData.values()], sectionIndex: 0}, ...filteredSections]; -} - -export default useFrozenPreSelection; diff --git a/src/hooks/useMappedPersonalDetails.ts b/src/hooks/useMappedPersonalDetails.ts deleted file mode 100644 index 502127a62ba7..000000000000 --- a/src/hooks/useMappedPersonalDetails.ts +++ /dev/null @@ -1,24 +0,0 @@ -import ONYXKEYS from '@src/ONYXKEYS'; -import type {PersonalDetails} from '@src/types/onyx'; - -import type {OnyxEntry} from 'react-native-onyx'; - -import useOnyx from './useOnyx'; - -/** - * Subscribes to all personal details and transforms each one via the provided mapper. - * Unlike passing a selector directly to useOnyx (which triggers expensive deepEqual - * comparisons on the entire mapped collection), this hook lets Onyx use cheap - * shallowEqual on raw personal detail references, then maps the collection inline. - */ -function useMappedPersonalDetails(mapper: (personalDetail: OnyxEntry) => T) { - const [personalDetails, metadata] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST); - const transformed = Object.entries(personalDetails ?? {}).reduce>((acc, [key, entry]) => { - acc[key] = mapper(entry ?? undefined); - return acc; - }, {}); - - return [transformed, metadata] as const; -} - -export default useMappedPersonalDetails; diff --git a/src/libs/Avatars/InitialAvatars.ts b/src/libs/Avatars/InitialAvatars.ts index e5d3a9b03298..ecddd338ffbc 100644 --- a/src/libs/Avatars/InitialAvatars.ts +++ b/src/libs/Avatars/InitialAvatars.ts @@ -1,8 +1,3 @@ -import * as WorkspaceDefaultAvatars from '@components/Icon/WorkspaceDefaultAvatars'; - -/* eslint-disable @typescript-eslint/naming-convention */ -import type {SvgProps} from 'react-native-svg'; - type LetterInitial = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z'; type NumberInitial = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'; @@ -10,53 +5,10 @@ type Initial = LetterInitial | NumberInitial; const DEFAULT_INITIAL: Initial = 'A'; -const INITIAL_AVATARS: Record> = { - A: WorkspaceDefaultAvatars.WorkspaceA, - B: WorkspaceDefaultAvatars.WorkspaceB, - C: WorkspaceDefaultAvatars.WorkspaceC, - D: WorkspaceDefaultAvatars.WorkspaceD, - E: WorkspaceDefaultAvatars.WorkspaceE, - F: WorkspaceDefaultAvatars.WorkspaceF, - G: WorkspaceDefaultAvatars.WorkspaceG, - H: WorkspaceDefaultAvatars.WorkspaceH, - I: WorkspaceDefaultAvatars.WorkspaceI, - J: WorkspaceDefaultAvatars.WorkspaceJ, - K: WorkspaceDefaultAvatars.WorkspaceK, - L: WorkspaceDefaultAvatars.WorkspaceL, - M: WorkspaceDefaultAvatars.WorkspaceM, - N: WorkspaceDefaultAvatars.WorkspaceN, - O: WorkspaceDefaultAvatars.WorkspaceO, - P: WorkspaceDefaultAvatars.WorkspaceP, - Q: WorkspaceDefaultAvatars.WorkspaceQ, - R: WorkspaceDefaultAvatars.WorkspaceR, - S: WorkspaceDefaultAvatars.WorkspaceS, - T: WorkspaceDefaultAvatars.WorkspaceT, - U: WorkspaceDefaultAvatars.WorkspaceU, - V: WorkspaceDefaultAvatars.WorkspaceV, - W: WorkspaceDefaultAvatars.WorkspaceW, - X: WorkspaceDefaultAvatars.WorkspaceX, - Y: WorkspaceDefaultAvatars.WorkspaceY, - Z: WorkspaceDefaultAvatars.WorkspaceZ, - '0': WorkspaceDefaultAvatars.Workspace0, - '1': WorkspaceDefaultAvatars.Workspace1, - '2': WorkspaceDefaultAvatars.Workspace2, - '3': WorkspaceDefaultAvatars.Workspace3, - '4': WorkspaceDefaultAvatars.Workspace4, - '5': WorkspaceDefaultAvatars.Workspace5, - '6': WorkspaceDefaultAvatars.Workspace6, - '7': WorkspaceDefaultAvatars.Workspace7, - '8': WorkspaceDefaultAvatars.Workspace8, - '9': WorkspaceDefaultAvatars.Workspace9, -}; - function getInitialFromText(text: string | null | undefined): Initial { const match = text?.toUpperCase().match(/[A-Z0-9]/); const initial = match?.[0] as Initial | undefined; return initial ?? DEFAULT_INITIAL; } -function getInitialAvatarSvg(initialOrText: string): React.FC { - return INITIAL_AVATARS[getInitialFromText(initialOrText)]; -} - -export {getInitialAvatarSvg, getInitialFromText, DEFAULT_INITIAL}; +export {getInitialFromText, DEFAULT_INITIAL}; diff --git a/src/libs/CardFeedUtils.ts b/src/libs/CardFeedUtils.ts index 74c23e636211..e8ed01c42050 100644 --- a/src/libs/CardFeedUtils.ts +++ b/src/libs/CardFeedUtils.ts @@ -21,14 +21,12 @@ import type {OptionData} from './ReportUtils'; import { feedHasCards, - getBankName, getCardFeedIcon, getCardFeedWithDomainID, getCustomOrFormattedFeedName, getDomainByFundID, getOriginalCompanyFeeds, getPlaidInstitutionIconUrl, - getPlaidInstitutionId, isCard, isCardClosed, isCardHiddenFromSearch, @@ -37,17 +35,10 @@ import { isDirectFeed, isPersonalCard, } from './CardUtils'; -import {getDescriptionForPolicyDomainCard, isPolicyAdmin} from './PolicyUtils'; +import {isPolicyAdmin} from './PolicyUtils'; type CardFilterItem = Partial & AdditionalCardProps & {isCardFeed?: boolean; correspondingCards?: string[]; cardFeedKey: string; plaidUrl?: string; keyForList: string}; type DomainFeedData = {bank: CardFeedWithNumber; domainName: string; correspondingCardIDs: string[]; fundID?: string; feedCountry?: string}; -type CardFeedNamesWithType = Record; -type CardFeedData = {cardName: string; bank: CardFeedWithNumber; label?: string; type: 'domain' | 'workspace'; feedCountry?: string}; -type GetCardFeedData = { - workspaceCardFeeds: Record | undefined; - translate: LocaleContextProps['translate']; - policies: OnyxCollection; -}; type CardFeedForDisplay = { id: string; feed: CardFeedWithNumber; @@ -58,51 +49,6 @@ type CardFeedForDisplay = { }; type CardFeedsForDisplay = Record; -function getRepeatingBanks(workspaceCardFeedsKeys: string[], domainFeedsData: Record) { - const bankFrequency: Record = {}; - for (const key of workspaceCardFeedsKeys) { - // Example: "cards_18755165_Expensify Card" -> "Expensify Card" - const bankName = key.split('_').at(2); - if (bankName) { - bankFrequency[bankName] = (bankFrequency[bankName] || 0) + 1; - } - } - for (const domainFeed of Object.values(domainFeedsData)) { - bankFrequency[domainFeed.bank] = (bankFrequency[domainFeed.bank] || 0) + 1; - } - return Object.keys(bankFrequency).filter((bank) => bankFrequency[bank] > 1); -} - -/** - * @returns string with the 'cards_' part removed from the beginning - */ -function getCardFeedKey(workspaceCardFeeds: Record | undefined, workspaceFeedKey: string) { - const workspaceFeed = workspaceCardFeeds ? workspaceCardFeeds[workspaceFeedKey] : undefined; - if (!workspaceFeed) { - return; - } - const representativeCard = Object.values(workspaceFeed).find((cardFeedItem) => isCard(cardFeedItem)); - if (!representativeCard) { - return; - } - // Auth emits `cards__` for every feed, and only Travel Invoicing (Expensify Card - // with feedCountry TRAVEL_US) gets the 3-segment `cards__Expensify Card_TRAVEL_US` - // (see Auth/auth/lib/Card.cpp `buildCardsCollectionKey`). Stripping the `cards_` prefix returns - // the exact token that `getWorkspaceCardFeedKey` re-prefixes to look the bucket back up, so the - // round-trip holds for every bank. - return workspaceFeedKey.startsWith(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST) ? workspaceFeedKey.slice(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST.length) : workspaceFeedKey; -} - -/** - * @returns string with added 'cards_' substring at the beginning - */ -function getWorkspaceCardFeedKey(cardFeedKey: string) { - if (!cardFeedKey.startsWith(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST)) { - return `${ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST}${cardFeedKey}`; - } - return cardFeedKey; -} - /** * Resolves the display name of a linked policy when preferredPolicy differs from the current policyID. */ @@ -179,284 +125,6 @@ function buildCardsData( return [...userAssignedCards, ...allWorkspaceCards]; } -/** - * @param cardList - The list of cards to process. Can be undefined. - * @returns a record where keys are domain names and values contain domain feed data. - */ -function generateDomainFeedData(cardList: CardList | undefined): Record { - return Object.values(cardList ?? {}).reduce( - (domainFeedData, currentCard) => { - // Cards in cardList can also be domain cards, we use them to compute domain feed - if (!currentCard?.domainName?.match(CONST.REGEX.EXPENSIFY_POLICY_DOMAIN_NAME) && !isCardHiddenFromSearch(currentCard) && currentCard.fundID) { - const feedCountry = getFeedCountryForDisplay(currentCard); - const key = createCardFeedKey(currentCard.fundID, currentCard.bank, feedCountry); - if (domainFeedData[key]) { - domainFeedData[key].correspondingCardIDs.push(currentCard.cardID.toString()); - } else { - // if the cards belongs to the same domain, every card of it should have the same fundID - // eslint-disable-next-line no-param-reassign - domainFeedData[key] = { - fundID: currentCard.fundID, - domainName: currentCard.domainName, - bank: currentCard?.bank, - correspondingCardIDs: [currentCard.cardID?.toString()], - ...(feedCountry ? {feedCountry} : {}), - }; - } - } - return domainFeedData; - }, - {} as Record, - ); -} - -function getDomainFeedData(workspaceCardFeeds: Record | undefined) { - const flattenedWorkspaceCardFeeds = Object.values(workspaceCardFeeds ?? {}).reduce((result, domainCards) => { - Object.assign(result, domainCards); - return result; - }, {}); - return generateDomainFeedData(flattenedWorkspaceCardFeeds); -} - -function getWorkspaceCardFeedData( - cardFeed: WorkspaceCardsList | undefined, - policies: OnyxCollection, - repeatingBanks: string[], - translate: LocaleContextProps['translate'], -): CardFeedData | undefined { - const cardFeedArray = Object.values(cardFeed ?? {}); - const representativeCard = cardFeedArray.find((cardFeedItem) => isCard(cardFeedItem)); - if (!representativeCard || !cardFeedArray.some((cardFeedItem) => isCard(cardFeedItem) && !isCardHiddenFromSearch(cardFeedItem))) { - return; - } - const {domainName, bank, cardName} = representativeCard; - const isBankRepeating = repeatingBanks.includes(bank); - const policyID = domainName.match(CONST.REGEX.EXPENSIFY_POLICY_DOMAIN_NAME)?.[1] ?? ''; - 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); - - const feedCountry = getFeedCountryForDisplay(representativeCard); - const cardFeedBankName = getCardFeedBankDisplayName(bank, feedCountry, companyCardBank, translate); - const fullCardName = - cardFeedBankName === CONST.COMPANY_CARDS.CARD_TYPE.CSV - ? translate('search.filters.card.cardFeedNameCSV', {cardFeedLabel}) - : translate('search.filters.card.cardFeedName', {cardFeedBankName, cardFeedLabel}); - - return { - cardName: fullCardName, - bank, - label: cardFeedLabel, - type: 'workspace', - ...(feedCountry ? {feedCountry} : {}), - }; -} - -function getDomainCardFeedData(domainFeed: DomainFeedData, policies: OnyxCollection, repeatingBanks: string[], translate: LocaleContextProps['translate']): CardFeedData { - const {domainName, bank, feedCountry} = domainFeed; - const isBankRepeating = repeatingBanks.includes(bank); - const cardFeedBankName = getCardFeedBankDisplayName(bank, feedCountry, getBankName(bank), translate); - const cardFeedLabel = isBankRepeating ? getDescriptionForPolicyDomainCard(domainName, policies) : undefined; - const cardName = - cardFeedBankName === CONST.COMPANY_CARDS.CARD_TYPE.CSV - ? translate('search.filters.card.cardFeedNameCSV', {cardFeedLabel}) - : translate('search.filters.card.cardFeedName', {cardFeedBankName, cardFeedLabel}); - return { - cardName, - bank, - label: cardFeedLabel, - type: 'domain', - ...(feedCountry ? {feedCountry} : {}), - }; -} - -function filterOutDomainCards(workspaceCardFeeds: Record | undefined) { - const domainFeedData = getDomainFeedData(workspaceCardFeeds); - return Object.entries(workspaceCardFeeds ?? {}).filter(([, workspaceFeed]) => { - const firstCard = Object.values(workspaceFeed ?? {}).find(isCard); - if (!firstCard) { - return !isEmptyObject(workspaceFeed); - } - const feedCountry = getFeedCountryForDisplay(firstCard); - const workspaceKey = createCardFeedKey(firstCard.fundID, firstCard.bank, feedCountry); - if (workspaceKey in domainFeedData) { - return false; - } - return !isEmptyObject(workspaceFeed); - }); -} - -function getCardFeedsData({workspaceCardFeeds, policies, translate}: GetCardFeedData) { - const domainFeedData = getDomainFeedData(workspaceCardFeeds); - const repeatingBanks = getRepeatingBanks(Object.keys(workspaceCardFeeds ?? CONST.EMPTY_OBJECT), domainFeedData); - const cardFeedData: Record = {}; - - for (const [cardFeedKey, cardFeed] of filterOutDomainCards(workspaceCardFeeds)) { - const workspaceData = getWorkspaceCardFeedData(cardFeed, policies, repeatingBanks, translate); - if (workspaceData) { - cardFeedData[cardFeedKey] = workspaceData; - } - } - - for (const domainFeed of Object.values(domainFeedData)) { - const cardFeedKey = createCardFeedKey(`cards_${domainFeed.fundID}`, domainFeed.bank, domainFeed.feedCountry); - cardFeedData[cardFeedKey] = getDomainCardFeedData(domainFeed, policies, repeatingBanks, translate); - } - - return cardFeedData; -} - -function getCardFeedNamesWithType(params: GetCardFeedData) { - const cardFeedData = getCardFeedsData(params); - return Object.keys(cardFeedData).reduce((cardFeedNamesWithType, cardFeedKey) => { - /* eslint-disable-next-line no-param-reassign */ - cardFeedNamesWithType[cardFeedKey] = { - name: cardFeedData[cardFeedKey].cardName, - type: cardFeedData[cardFeedKey].type, - }; - return cardFeedNamesWithType; - }, {}); -} - -function createCardFeedKey(fundID: string | undefined, bank: string, feedCountry: string | undefined) { - if (!fundID) { - return bank; - } - if (feedCountry) { - return `${fundID}_${bank}_${feedCountry}`; - } - return `${fundID}_${bank}`; -} - -function createCardFeedItem({ - cardName, - bank, - keyForList, - cardFeedKey, - correspondingCardIDs, - selectedCards, - illustrations, - companyCardIcons, -}: { - cardName: string; - bank: CardFeedWithNumber; - keyForList: string; - cardFeedKey: string; - correspondingCardIDs: string[]; - selectedCards: string[]; - illustrations: IllustrationsType; - companyCardIcons: CompanyCardFeedIcons; -}): CardFilterItem { - const isSelected = correspondingCardIDs.every((card) => selectedCards.includes(card)); - const plaidUrl = getPlaidInstitutionIconUrl(bank); - - const icon = getCardFeedIcon(bank, illustrations, companyCardIcons); - return { - text: cardName, - keyForList, - isSelected, - shouldShowOwnersAvatar: false, - bankIcon: { - icon, - }, - plaidUrl, - cardFeedKey, - isCardFeed: true, - correspondingCards: correspondingCardIDs, - }; -} - -function buildCardFeedsData( - workspaceCardFeeds: Record, - domainFeedsData: Record, - policies: OnyxCollection, - selectedCards: string[], - translate: LocaleContextProps['translate'], - illustrations: IllustrationsType, - companyCardIcons: CompanyCardFeedIcons, -): CardFilterItem[] { - const feeds: CardFilterItem[] = []; - const repeatingBanks = getRepeatingBanks(Object.keys(workspaceCardFeeds), domainFeedsData); - - for (const domainFeed of Object.values(domainFeedsData)) { - const {domainName, bank, correspondingCardIDs, feedCountry} = domainFeed; - - const cardFeedKey = createCardFeedKey(domainFeed.fundID, bank, feedCountry); - const {cardName} = getDomainCardFeedData(domainFeed, policies, repeatingBanks, translate); - - feeds.push( - createCardFeedItem({ - cardName, - bank, - correspondingCardIDs, - keyForList: feedCountry ? `${domainName}-${bank}-${feedCountry}` : `${domainName}-${bank}`, - cardFeedKey, - selectedCards, - illustrations, - companyCardIcons, - }), - ); - } - - for (const [workspaceFeedKey, workspaceFeed] of filterOutDomainCards(workspaceCardFeeds)) { - const correspondingCardIDs = Object.entries(workspaceFeed ?? {}) - .filter(([cardKey, card]) => cardKey !== 'cardList' && isCard(card) && !isCardHiddenFromSearch(card)) - .map(([cardKey]) => cardKey); - - const cardFeedData = getWorkspaceCardFeedData(workspaceFeed, policies, repeatingBanks, translate); - if (!cardFeedData) { - continue; - } - const {cardName, bank} = cardFeedData; - const cardFeedKey = getCardFeedKey(workspaceCardFeeds, workspaceFeedKey); - - feeds.push( - createCardFeedItem({ - cardName, - bank, - correspondingCardIDs, - cardFeedKey: cardFeedKey ?? '', - keyForList: workspaceFeedKey, - selectedCards, - illustrations, - companyCardIcons, - }), - ); - } - - return feeds; -} - -function getSelectedCardsFromFeeds(cards: CardList | undefined, workspaceCardFeeds?: Record, selectedFeeds?: string[]): string[] { - const domainFeedsData = generateDomainFeedData(cards); - const domainFeedCards = Object.fromEntries( - Object.values(domainFeedsData).map((domainFeedData) => [ - createCardFeedKey(domainFeedData.fundID, domainFeedData.bank, domainFeedData.feedCountry), - domainFeedData.correspondingCardIDs, - ]), - ); - - if (!workspaceCardFeeds || !selectedFeeds) { - return []; - } - - const selectedCards = selectedFeeds.flatMap((cardFeedKey) => { - const workspaceCardFeed = workspaceCardFeeds[getWorkspaceCardFeedKey(cardFeedKey)]; - if (!workspaceCardFeed) { - if (!cards || !domainFeedCards[cardFeedKey] || Object.keys(domainFeedCards).length === 0) { - return []; - } - - return domainFeedCards[cardFeedKey].filter((cardNumber) => cards[cardNumber].state !== CONST.EXPENSIFY_CARD.STATE.STATE_NOT_ISSUED); - } - - return Object.keys(workspaceCardFeed).filter((cardNumber) => workspaceCardFeed[cardNumber].state !== CONST.EXPENSIFY_CARD.STATE.STATE_NOT_ISSUED); - }); - - return [...new Set(selectedCards)]; -} - /** * Returns the wire-level country segment used in the Search feed filter token for a card. We only * care about Travel Invoicing feed country segment since it has its own @@ -471,16 +139,6 @@ function getFeedCountryForDisplay(card: Card): string { return card.nameValuePairs?.feedCountry === CONST.TRAVEL.PROGRAM_TRAVEL_US ? CONST.TRAVEL.PROGRAM_TRAVEL_US : ''; } -function getCardFeedBankDisplayName(bank: string, feedCountry: string | undefined, companyCardBankName: string, translate: LocaleContextProps['translate']): string { - if (bank !== CONST.EXPENSIFY_CARD.BANK) { - return companyCardBankName; - } - if (feedCountry === CONST.TRAVEL.PROGRAM_TRAVEL_US) { - return translate('search.filters.card.travelInvoicing'); - } - return translate('search.filters.card.expensify'); -} - function getExpensifyCardFeedsForDisplay(allCards: CardList | undefined, translate: LocaleContextProps['translate'] | undefined): CardFeedsForDisplay { const result = {} as CardFeedsForDisplay; @@ -817,9 +475,6 @@ export type {CardFilterItem, CardFeedForDisplay}; export type {DomainFeedData}; export { buildCardsData, - getCardFeedNamesWithType, - buildCardFeedsData, - getSelectedCardsFromFeeds, getFeedInfo, getLinkedPolicyName, getCardFeedsForDisplay, diff --git a/src/libs/CardUtils.ts b/src/libs/CardUtils.ts index ecef1cac8c93..1a3a1f2023c8 100644 --- a/src/libs/CardUtils.ts +++ b/src/libs/CardUtils.ts @@ -1246,44 +1246,6 @@ function getFeedType(feedKey: CompanyCardFeed, cardFeeds: 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 - * - * @param allCardsList the list where cards split by workspaces and feeds and stored under `card_${workspaceAccountID}_${feedName}` keys - * @param workspaceAccountID the workspace account id we want to get cards for - * @param domainIDs the domain ids we want to get cards for - */ -function flattenWorkspaceCardsList(allCardsList: OnyxCollection, workspaceAccountID: number): CardList | undefined { - if (!allCardsList) { - return; - } - - return Object.entries(allCardsList).reduce((acc, [key, cards]) => { - const isWorkspaceAccountCard = key.includes(workspaceAccountID.toString()); - if (!isWorkspaceAccountCard || key.includes(CONST.EXPENSIFY_CARD.BANK)) { - return acc; - } - const {cardList, ...feedCards} = cards ?? {}; - const filteredCards = filterInactiveCards(feedCards); - Object.assign(acc, filteredCards); - return acc; - }, {}); -} - /** * Check if the card has a broken connection * @@ -1557,20 +1519,6 @@ function getFundIdFromSettingsKey(key: string) { return Number.isNaN(fundID) ? CONST.DEFAULT_NUMBER_ID : fundID; } -/** - * Get card which has a broken connection - * - * @param feedCards the list of the cards, related to one or several feeds - * @param [feedToExclude] the feed to ignore during the check, it's useful for checking broken connection error only in the feeds other than the selected one - */ -function getFeedConnectionBrokenCard(feedCards: CardList | undefined, feedToExclude?: string): Card | undefined { - if (!feedCards || isEmptyObject(feedCards)) { - return undefined; - } - - return Object.values(feedCards).find((card) => !isEmptyObject(card) && card.bank !== feedToExclude && isCardConnectionBroken(card)); -} - /** Extract feed from feed with domainID */ function getCompanyCardFeed(feedWithDomainID: CardFeedWithNumber | CardFeedWithDomainID | undefined): CompanyCardFeedWithNumber { if (!feedWithDomainID) { @@ -1592,11 +1540,6 @@ function isPersonalCard(card?: Card) { return !card?.fundID || card.fundID === '0' || card?.bank === CONST.PERSONAL_CARDS.BANK_NAME.CSV; } -type SplitMaskedCardNumberResult = { - firstDigits?: string; - lastDigits?: string; -}; - /** * Split masked card number into first and last digits * @@ -1612,20 +1555,6 @@ function formatMaskedCardName(cardName: string): string { return padded.match(/.{1,4}/g)?.join('-') ?? padded; } -function splitMaskedCardNumber(cardNumber: string | undefined, maskChar: string = CONST.COMPANY_CARD.CARD_NUMBER_MASK_CHAR): SplitMaskedCardNumberResult { - if (!cardNumber) { - return { - firstDigits: undefined, - lastDigits: undefined, - }; - } - const parts = cardNumber.split(maskChar); - return { - firstDigits: parts.at(0), - lastDigits: parts.at(-1), - }; -} - function isCardAlreadyAssigned(cardNumberToCheck: string, workspaceCardFeeds: OnyxCollection, domainOrWorkspaceAccountID: number, feedName?: string): boolean { if (!cardNumberToCheck || !workspaceCardFeeds) { return false; @@ -2005,12 +1934,10 @@ export { getDomainOrWorkspaceAccountID, mergeCardListWithWorkspaceFeeds, isCard, - filterCardsByNonExpensify, getAllCardsForWorkspace, isCardHiddenFromSearch, getCSVFeedType, getFeedType, - flattenWorkspaceCardsList, isCardConnectionBroken, isSmartLimitEnabled, lastFourNumbersFromCardName, @@ -2043,7 +1970,6 @@ export { getCompanyCardDescription, getPlaidInstitutionIconUrl, getPlaidInstitutionId, - getFeedConnectionBrokenCard, getCorrectStepForPlaidSelectedBank, isDirectFeed, feedHasCards, @@ -2057,7 +1983,6 @@ export { COMPANY_CARD_FEED_ICON_NAMES, COMPANY_CARD_BANK_ICON_NAMES, formatMaskedCardName, - splitMaskedCardNumber, isCardAlreadyAssigned, getCardDescriptionForSearchTable, generateCardID, diff --git a/src/libs/OptionsListUtils/index.ts b/src/libs/OptionsListUtils/index.ts index 95204ae05c6d..d0bedb73f4b3 100644 --- a/src/libs/OptionsListUtils/index.ts +++ b/src/libs/OptionsListUtils/index.ts @@ -579,26 +579,6 @@ function isSearchStringMatchUserDetails(personalDetail: PersonalDetails, searchV return isSearchStringMatch(searchValue.trim(), memberDetails.toLowerCase()); } -/** - * Get IOU report ID of report last action if the action is report action preview - */ -function getIOUReportIDOfLastAction( - report: OnyxEntry, - privateIsArchived: boolean | undefined, - visibleReportActionsData?: VisibleReportActionsDerivedValue, - lastAction?: OnyxEntry, -): string | undefined { - if (!report?.reportID) { - return; - } - const canUserPerformWrite = canUserPerformWriteAction(report, privateIsArchived); - const action = lastAction ?? getLastVisibleAction(report.reportID, canUserPerformWrite, {}, undefined, visibleReportActionsData); - if (!isReportPreviewAction(action)) { - return; - } - return getReportOrDraftReport(getIOUReportIDFromReportActionPreview(action))?.reportID; -} - function hasHiddenDisplayNames(accountIDs: number[]) { return getPersonalDetailsByIDs({accountIDs, currentUserAccountID: 0}).some((personalDetail) => !getDisplayNameOrDefault(personalDetail, undefined, false)); } @@ -3393,7 +3373,6 @@ export { getHeaderMessage, getHeaderMessageForNonUserList, getIOUConfirmationOptionsFromPayeePersonalDetail, - getIOUReportIDOfLastAction, getLastActorDisplayName, getLastActorDisplayNameFromLastVisibleActions, getLastMessageTextForReport, diff --git a/src/libs/PersonalDetailsUtils.ts b/src/libs/PersonalDetailsUtils.ts index f6c22fe1945f..c182685be6cb 100644 --- a/src/libs/PersonalDetailsUtils.ts +++ b/src/libs/PersonalDetailsUtils.ts @@ -567,19 +567,6 @@ const getPhoneNumber = (details: OnyxEntry): string | undefined return login ? Str.removeSMSDomain(login) : ''; }; -/** - * Creates a lookup map from an array of PersonalDetails for O(1) access by accountID. - * This is useful when you need to look up personal details by accountID multiple times - * to avoid O(n) .find() calls in loops. - */ -function createPersonalDetailsLookupByAccountID(details: PersonalDetails[]): Record { - const map: Record = {}; - for (const detail of details) { - map[detail.accountID] = detail; - } - return map; -} - /** * Checks whether any personal details are missing */ @@ -645,6 +632,5 @@ export { arePersonalDetailsMissing, areAddressAndPersonalDetailsMissing, areTravelPersonalDetailsMissing, - createPersonalDetailsLookupByAccountID, temporaryGetDisplayNameOrDefault, }; diff --git a/src/libs/PolicyUtils.ts b/src/libs/PolicyUtils.ts index 2b475d1c0603..5bc8a45e54ee 100644 --- a/src/libs/PolicyUtils.ts +++ b/src/libs/PolicyUtils.ts @@ -1480,10 +1480,6 @@ function arePaymentsEnabled(policy: OnyxEntry): boolean { return policy?.reimbursementChoice !== CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_NO; } -function hasApprovalFlow(policy: OnyxInputOrEntry): boolean { - return isPaidGroupPolicy(policy) && !!policy?.approvalMode && policy.approvalMode !== CONST.POLICY.APPROVAL_MODE.OPTIONAL; -} - function isControlOnAdvancedApprovalMode(policy: OnyxInputOrEntry): boolean { return policy?.type === CONST.POLICY.TYPE.CORPORATE && getApprovalWorkflow(policy) === CONST.POLICY.APPROVAL_MODE.ADVANCED; } @@ -2876,7 +2872,6 @@ export { isPolicyMember, isPolicyPayer, arePaymentsEnabled, - hasApprovalFlow, isSubmitAndClose, isTaxTrackingEnabled, shouldShowPolicy, diff --git a/src/libs/ReportTitleUtils.ts b/src/libs/ReportTitleUtils.ts index b53e1a026e19..99326090b90e 100644 --- a/src/libs/ReportTitleUtils.ts +++ b/src/libs/ReportTitleUtils.ts @@ -1,5 +1,5 @@ import ONYXKEYS from '@src/ONYXKEYS'; -import type {Policy, Report, ReportNameValuePairs} from '@src/types/onyx'; +import type {Policy, ReportNameValuePairs} from '@src/types/onyx'; /** * This file should only be used in context of optimistic report name updates. @@ -9,7 +9,7 @@ import type {OnyxUpdate} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; -import {getTitleReportField, isChatReport} from './ReportUtils'; +import {getTitleReportField} from './ReportUtils'; let allReportNameValuePairs: Record = {}; @@ -67,50 +67,4 @@ function updateTitleFieldToMatchPolicy(reportID: string, policy?: Policy): Array return optimisticData; } -/** - * Remove title field from report's rNVP when report is manually renamed to indicate that the manual name should be preserved, and the custom report name formula should no longer update the name. - */ -function removeTitleFieldFromReport(reportID: string): Array> { - if (!reportID) { - return []; - } - - const optimisticData: Array> = [ - { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${reportID}`, - value: { - // eslint-disable-next-line @typescript-eslint/naming-convention - expensify_text_title: null, - }, - }, - ]; - - return optimisticData; -} - -/** - * Check if a report should have its title field updated based on conditions - */ -function shouldUpdateTitleField(report: Report): boolean { - // todo: this should be more sophisticated function. check for iou etc - if (!report) { - return false; - } - // Skip chat reports - if (isChatReport(report)) { - return false; - } - - // Skip if report has statement card ID (backend check: !getValue(db, reportID, NVP_STATEMENT_CARD_ID).empty()) - // This would need to be implemented based on how statement card IDs are stored in the frontend - - const reportTitleField = getTitleFieldFromRNVP(report.reportID); - if (!reportTitleField) { - return false; - } - - return true; -} - -export {getTitleFieldFromRNVP, removeTitleFieldFromReport, shouldUpdateTitleField, updateTitleFieldToMatchPolicy}; +export {getTitleFieldFromRNVP, updateTitleFieldToMatchPolicy}; diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index d29661d0eec6..c64a7570e2d7 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -151,7 +151,6 @@ import { canSendInvoiceFromWorkspace, getActivePolicies, getConnectedIntegration, - getCorrectedAutoReportingFrequency, getForwardsToAccount, getManagerAccountEmail, getManagerAccountID, @@ -2015,16 +2014,6 @@ function isReportOpenOrUnsubmitted(reportID: string | undefined, reports: OnyxCo return report.stateNum === CONST.REPORT.STATE_NUM.OPEN; } -/** - * Determines if a report requires manual submission based on policy settings and report state - */ -function requiresManualSubmission(report: OnyxEntry, policy: OnyxEntry): boolean { - const isManualSubmitEnabled = getCorrectedAutoReportingFrequency(policy) === CONST.POLICY.AUTO_REPORTING_FREQUENCIES.MANUAL; - - // The report needs manual submission if manual submit is enabled in the policy or the report is open in a Submit & Close policy with no approvers - return isManualSubmitEnabled || (isOpenReport(report) && isInstantSubmitEnabled(policy) && isSubmitAndClose(policy)); -} - function hasReportBeenForwardedSinceLastSubmit(report: OnyxEntry): boolean { if (!report?.reportID) { return false; @@ -13592,7 +13581,6 @@ export { isPolicyExpenseChat, isProcessingReport, isOpenReport, - requiresManualSubmission, isReportIDApproved, isAwaitingFirstLevelApproval, isPublicRoom, diff --git a/src/libs/UserAvatarUtils.ts b/src/libs/UserAvatarUtils.ts index ff7e6ac90b25..6770c890bda5 100644 --- a/src/libs/UserAvatarUtils.ts +++ b/src/libs/UserAvatarUtils.ts @@ -85,18 +85,6 @@ function getAccountIDHashBucket({accountID = CONST.DEFAULT_NUMBER_ID, accountEma return accountIDHashBucket; } -/** - * Returns the colors for a letter-avatar scheme key, falling back to the default scheme when the key is missing or unknown. - * - * @param avatarSchemeKey - A scheme key, e.g. "blue100" - */ -function getLetterAvatarScheme(avatarSchemeKey?: string): LetterAvatarColorStyle { - if (avatarSchemeKey && isLetterAvatarSchemeKey(avatarSchemeKey)) { - return LETTER_AVATAR_SCHEMES[avatarSchemeKey]; - } - return DEFAULT_LETTER_AVATAR_SCHEME; -} - /** * Returns the default avatar asset associated with the given accountID. * Special accounts (Concierge, Notifications) have dedicated avatars. @@ -444,7 +432,6 @@ export { getDefaultAvatar, getDefaultAvatarName, getDefaultAvatarURL, - getLetterAvatarScheme, getCatalogAvatarNameFromURL, getFullSizeAvatar, getSmallSizeAvatar, diff --git a/src/libs/actions/IOU/ReportWorkflow.ts b/src/libs/actions/IOU/ReportWorkflow.ts index b36f5c393e9b..7c38cf91e4bc 100644 --- a/src/libs/actions/IOU/ReportWorkflow.ts +++ b/src/libs/actions/IOU/ReportWorkflow.ts @@ -20,7 +20,6 @@ import { getSubmitReportManagerAccountID, hasDynamicExternalWorkflow, isPaidGroupPolicy, - isPolicyAdmin, isSubmitAndClose, isSubmitPolicy, isSubmitterApproveBlockedOnSubmitWorkspace, @@ -57,7 +56,6 @@ import { isPayer as isPayerReportUtils, isProcessingReport, isReportApproved, - isReportManager, isReportPendingDelete, isSettled, } from '@libs/ReportUtils'; @@ -181,16 +179,6 @@ function canApproveIOU( ); } -function canUnapproveIOU(iouReport: OnyxEntry, policy: OnyxEntry) { - return ( - isExpenseReport(iouReport) && - (isReportManager(iouReport) || isPolicyAdmin(policy)) && - isReportApproved({report: iouReport}) && - !isSubmitAndClose(policy) && - !iouReport?.isWaitingOnBankAccount - ); -} - function canIOUBePaid( iouReport: OnyxTypes.OnyxInputOrEntry, chatReport: OnyxTypes.OnyxInputOrEntry, @@ -267,10 +255,6 @@ function canIOUBePaid( ); } -function canCancelPayment(iouReport: OnyxEntry, session: OnyxEntry, bankAccountList: OnyxEntry) { - return isPayerReportUtils(session?.accountID, session?.email, iouReport, bankAccountList) && (isSettled(iouReport) || iouReport?.isWaitingOnBankAccount) && isExpenseReport(iouReport); -} - function canSubmitReport( report: OnyxEntry, policy: OnyxEntry, @@ -1896,10 +1880,8 @@ export { approveMoneyRequest, assignReportToMe, canApproveIOU, - canCancelPayment, canIOUBePaid, canSubmitReport, - canUnapproveIOU, clearPendingExpenseAction, getBadgeFromIOUReport, getIOUReportActionWithBadge, diff --git a/src/pages/inbox/conciergeDraftState.ts b/src/pages/inbox/conciergeDraftState.ts index 82c6b2c367bb..6585ab80d8ce 100644 --- a/src/pages/inbox/conciergeDraftState.ts +++ b/src/pages/inbox/conciergeDraftState.ts @@ -661,10 +661,6 @@ function getNextVisibleConciergeDraftMarkdown( }; } -function getNextVisibleConciergeDraftBodyMarkdown(currentBodyMarkdown: string, targetBodyMarkdown: string): string { - return getNextVisibleConciergeDraftMarkdown(currentBodyMarkdown, targetBodyMarkdown).bodyMarkdown; -} - // Module-level cache so a chat re-mount (ReportScreen unmount/remount on chat // switch) preserves the in-progress draft. Without this the gate's local state // resets to null on every revisit and the synthetic bubble disappears for the @@ -729,13 +725,5 @@ function applyConciergeDraftEvent(currentDraft: ConciergeDraft | null, event: Co }; } -export { - applyConciergeDraftEvent, - CONCIERGE_DRAFT_STATUS, - getCachedDraft, - getNextVisibleConciergeDraftBodyMarkdown, - getNextVisibleConciergeDraftMarkdown, - setCachedDraft, - stripIncompleteMarkdown, -}; +export {applyConciergeDraftEvent, CONCIERGE_DRAFT_STATUS, getCachedDraft, getNextVisibleConciergeDraftMarkdown, setCachedDraft, stripIncompleteMarkdown}; export type {ConciergeDraft}; diff --git a/src/selectors/Policy.ts b/src/selectors/Policy.ts index ed84c7aad07e..96b850a81b13 100644 --- a/src/selectors/Policy.ts +++ b/src/selectors/Policy.ts @@ -1,6 +1,6 @@ import {hasSynchronizationErrorMessage, isConnectionUnverified} from '@libs/actions/connections'; import {getDisplayNameForWorkspace} from '@libs/actions/Policy/Policy'; -import {getActiveAdminWorkspaces, getOwnedPaidPolicies, isPaidGroupPolicy, isPendingDeletePolicy, isPolicyAdmin, shouldShowPolicy} from '@libs/PolicyUtils'; +import {getActiveAdminWorkspaces, getOwnedPaidPolicies, isPendingDeletePolicy, isPolicyAdmin, shouldShowPolicy} from '@libs/PolicyUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -184,23 +184,6 @@ const policyTimeTrackingSelector = (policy: OnyxEntry) => units: policy.units, }; -const hasMultipleOutputCurrenciesSelector = (policies: OnyxCollection) => { - const currencies = new Set(); - - for (const policy of Object.values(policies ?? {})) { - if (!policy || !isPaidGroupPolicy(policy)) { - continue; - } - - currencies.add(policy.outputCurrency); - if (currencies.size > 1) { - return true; - } - } - - return false; -}; - type PolicySelector = Pick; const policyMapper = (policy: OnyxEntry): PolicySelector => @@ -324,8 +307,6 @@ function getReusablePoliciesConnectedTo(policies: OnyxCollection, connec const reusablePoliciesConnectedToSelector = (policies: OnyxCollection, connectionName: ReusablePolicyConnectionName, currentPolicyID?: string) => getReusablePoliciesConnectedTo(policies, connectionName, currentPolicyID); -const hasPoliciesConnectedToQBDSelector = (policies: OnyxCollection) => !!adminPoliciesConnectedToQBDSelector(policies).length; - const hasReusablePoliciesConnectedToSelector = (policies: OnyxCollection, connectionName: ReusablePolicyConnectionName, currentPolicyID?: string) => Object.values(policies ?? {}).some((policy) => isAdminPolicyConnectedTo(policy, connectionName) && isReusablePolicyConnection(policy, connectionName, currentPolicyID)); @@ -402,12 +383,10 @@ export { hasActiveAdminPoliciesSelector, createPoliciesForDomainCardsSelector, policyTimeTrackingSelector, - hasMultipleOutputCurrenciesSelector, iouRequestPolicyCollectionSelector, policyMapper, adminPoliciesConnectedToQBDSelector, reusablePoliciesConnectedToSelector, - hasPoliciesConnectedToQBDSelector, hasReusablePoliciesConnectedToSelector, lastWorkspaceNumberSelector, hasOnlyPersonalPoliciesSelector, diff --git a/tests/actions/IOUTest/ReportWorkflowTest.ts b/tests/actions/IOUTest/ReportWorkflowTest.ts index 6a2d484ecd63..dd6544fb35e2 100644 --- a/tests/actions/IOUTest/ReportWorkflowTest.ts +++ b/tests/actions/IOUTest/ReportWorkflowTest.ts @@ -8,10 +8,8 @@ import useReportWithTransactionsAndViolations from '@hooks/useReportWithTransact import { approveMoneyRequest, canApproveIOU, - canCancelPayment, canIOUBePaid, canSubmitReport, - canUnapproveIOU, getBadgeFromIOUReport, getIOUReportActionWithBadge, getReportOriginalCreationTimestamp, @@ -2639,37 +2637,6 @@ describe('actions/IOU/ReportWorkflow', () => { }); }); - describe('canUnapproveIOU', () => { - it('should return false if the report is waiting for a bank account', () => { - const fakeReport: Report = { - ...createRandomReport(1, undefined), - type: CONST.REPORT.TYPE.EXPENSE, - policyID: 'A', - stateNum: CONST.REPORT.STATE_NUM.APPROVED, - statusNum: CONST.REPORT.STATUS_NUM.APPROVED, - isWaitingOnBankAccount: true, - managerID: RORY_ACCOUNT_ID, - }; - expect(canUnapproveIOU(fakeReport, undefined)).toBeFalsy(); - }); - }); - - describe('canCancelPayment', () => { - it('should return true if the report is waiting for a bank account', () => { - // Using ID_FAKE to test the isWaitingOnBankAccount logic without workspace membership concerns - const fakeReport: Report = { - ...createRandomReport(1, undefined), - type: CONST.REPORT.TYPE.EXPENSE, - policyID: CONST.POLICY.ID_FAKE, - stateNum: CONST.REPORT.STATE_NUM.APPROVED, - statusNum: CONST.REPORT.STATUS_NUM.APPROVED, - isWaitingOnBankAccount: true, - managerID: RORY_ACCOUNT_ID, - }; - expect(canCancelPayment(fakeReport, {accountID: RORY_ACCOUNT_ID}, undefined)).toBeTruthy(); - }); - }); - describe('canIOUBePaid', () => { it('should return false if the report has negative total and onlyShowPayElsewhere is false', async () => { const policyChat = createRandomReport(1, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT); diff --git a/tests/unit/CardFeedUtilsTest.ts b/tests/unit/CardFeedUtilsTest.ts index 147171939ecf..5d32b6be900b 100644 --- a/tests/unit/CardFeedUtilsTest.ts +++ b/tests/unit/CardFeedUtilsTest.ts @@ -1,16 +1,8 @@ -import { - getCardFeedNamesWithType, - getCardFeedsForDisplay, - getCardFeedsForDisplayPerPolicy, - getExpensifyCardFeedsForDisplay, - getFeedInfo, - getSelectedCardsFromFeeds, - getVisibleCompanyCardFeedsForSelector, -} from '@libs/CardFeedUtils'; +import {getCardFeedsForDisplay, getCardFeedsForDisplayPerPolicy, getExpensifyCardFeedsForDisplay, getFeedInfo, getVisibleCompanyCardFeedsForSelector} from '@libs/CardFeedUtils'; import CONST from '@src/CONST'; import IntlStore from '@src/languages/IntlStore'; -import type {Card, CardFeeds, CardList, CompanyCardFeed, Domain, Policy, WorkspaceCardsList} from '@src/types/onyx'; +import type {Card, CardFeeds, CardList, CompanyCardFeed, Domain, Policy} from '@src/types/onyx'; import type {CardFeedWithNumber} from '@src/types/onyx/CardFeeds'; /* eslint-disable @typescript-eslint/naming-convention */ @@ -46,79 +38,11 @@ function createTestPolicy(overrides: Partial & Pick): Poli }; } -function createExpensifyCardBase(cardID: number, fundID: string, feedCountry?: string): Card { - return createTestCard({ - accountID: cardID, - lastUpdated: '2024-11-29', - bank: CONST.EXPENSIFY_CARD.BANK, - cardID, - cardName: `${cardID}XXXXXX`, - domainName: 'user.com', - fundID, - lastFourPAN: '1234', - lastScrapeResult: 200, - scrapeMinDate: '', - ...(feedCountry ? {nameValuePairs: createCardNameValuePairs({feedCountry})} : {}), - }); -} - const cardFeedAmericaExpressMock: CardFeedWithNumber = `${CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX_DIRECT} 1001`; const cardFeedVisaMock: CompanyCardFeed = CONST.COMPANY_CARD.FEED_BANK_NAME.VISA; const cardFeedCitiBankMock: CompanyCardFeed = CONST.COMPANY_CARD.FEED_BANK_NAME.CITIBANK; const cardFeedStripeMock: CompanyCardFeed = CONST.COMPANY_CARD.FEED_BANK_NAME.STRIPE; -const fakeWorkspace: Record = { - 'cards_11111111_Expensify Card': { - '11111111': { - accountID: 11111111, - lastUpdated: '2024-11-29', - bank: 'Expensify Card', - cardID: 11111111, - cardName: '111111XXXXXX1111', - domainName: 'expensify-policy1234567891011121.exfy', - fraud: 'none', - fundID: '11111111', - lastFourPAN: '1234', - lastScrape: '', - lastScrapeResult: 200, - scrapeMinDate: '', - state: 3, - }, - '22222222': { - accountID: 22222222, - lastUpdated: '2024-11-29', - bank: 'Expensify Card', - cardID: 22222222, - cardName: '222222XXXXXX2222', - domainName: 'expensify-policy1234567891011121.exfy', - fraud: 'none', - fundID: '11111111', - lastFourPAN: '5678', - lastScrape: '', - lastScrapeResult: 200, - scrapeMinDate: '', - state: 3, - }, - }, - 'cards_22222222_Expensify Card': { - '33333333': { - accountID: 33333333, - lastUpdated: '2024-11-29', - bank: 'Expensify Card', - cardID: 33333333, - cardName: '333333XXXXXX3333', - domainName: 'expensify-policy1234567891011121.exfy', - fraud: 'none', - fundID: '22222222', - lastFourPAN: '9101', - lastScrape: '', - lastScrapeResult: 200, - scrapeMinDate: '', - state: 3, - }, - }, -}; - const cardListMock: CardList = { '11223344': createTestCard({cardID: 11223344, bank: CONST.COMPANY_CARD.FEED_BANK_NAME.VISA, fundID: '5555', state: CONST.EXPENSIFY_CARD.STATE.OPEN}), '10203040': createTestCard({cardID: 10203040, bank: CONST.EXPENSIFY_CARD.BANK, fundID: '5555', state: CONST.EXPENSIFY_CARD.STATE.OPEN}), @@ -149,29 +73,6 @@ describe('Card Feed Utils', () => { IntlStore.load(CONST.LOCALES.EN); return waitForBatchedUpdates(); }); - it('returns display name of workspace & domain cards', () => { - const cardFeedNamesWithType = getCardFeedNamesWithType({workspaceCardFeeds: fakeWorkspace, policies: undefined, translate: translateLocal}); - expect(Object.keys(cardFeedNamesWithType).length).toBe(2); - expect(Object.values(cardFeedNamesWithType).every((cardFeedName) => cardFeedName.name === 'All Expensify')).toBe(true); - }); - - it('returns feeds to selected cards', () => { - const feeds = ['22222222_Expensify Card']; - const selected = getSelectedCardsFromFeeds({}, fakeWorkspace, feeds); - expect(selected.length).toBe(1); - expect(selected.at(0)).toEqual('33333333'); - }); - - it('returns empty object when workspaceCardFeeds is empty', () => { - const names = getCardFeedNamesWithType({workspaceCardFeeds: {key: {}}, policies: undefined, translate: translateLocal}); - expect(names).toEqual({}); - }); - - it('returns empty array when selectedFeeds contains a non-existent feed', () => { - const feeds = ['99999999_Expensify Card']; - const selected = getSelectedCardsFromFeeds({}, fakeWorkspace, feeds); - expect(selected).toEqual([]); - }); it('returns card feeds for display with custom names', () => { const cardFeedsForDisplay = getCardFeedsForDisplay(cardFeedsMock, cardListMock, translateLocal); @@ -465,80 +366,6 @@ describe('getExpensifyCardFeedsForDisplay', () => { }); }); -describe('country-aware domain feed picker', () => { - beforeAll(() => { - IntlStore.load(CONST.LOCALES.EN); - return waitForBatchedUpdates(); - }); - - it('feed names are different for Expensify Cards and Travel invoicing', () => { - const workspaceCardFeeds: Record = { - 'cards_5555_Expensify Card': { - '1': createExpensifyCardBase(1, '5555', CONST.COUNTRY.US), - '2': createExpensifyCardBase(2, '5555', CONST.COUNTRY.GB), - }, - 'cards_5555_Expensify Card_TRAVEL_US': { - '3': createExpensifyCardBase(3, '5555', CONST.TRAVEL.PROGRAM_TRAVEL_US), - }, - }; - - const names = getCardFeedNamesWithType({workspaceCardFeeds, policies: undefined, translate: translateLocal}); - expect(Object.keys(names).sort()).toEqual(['cards_5555_Expensify Card', 'cards_5555_Expensify Card_TRAVEL_US']); - expect(names['cards_5555_Expensify Card'].name).toBe('All Expensify - user.com'); - expect(names['cards_5555_Expensify Card_TRAVEL_US'].name).toBe('All Consolidated Travel Billing - user.com'); - }); - - it('resolves a travel selection to only travel cards', () => { - const cardList: CardList = { - '1': createExpensifyCardBase(1, '5555', CONST.COUNTRY.US), - '2': createExpensifyCardBase(2, '5555', CONST.TRAVEL.PROGRAM_TRAVEL_US), - '3': createExpensifyCardBase(3, '5555', CONST.TRAVEL.PROGRAM_TRAVEL_US), - }; - - const selected = getSelectedCardsFromFeeds(cardList, {}, ['5555_Expensify Card_TRAVEL_US']); - expect(selected.sort()).toEqual(['2', '3']); - }); - - it('resolves a 2-segment Expensify selection to every non-travel card for the fundID', () => { - const cardList: CardList = { - '1': createExpensifyCardBase(1, '5555', CONST.COUNTRY.US), - '2': createExpensifyCardBase(2, '5555', CONST.COUNTRY.GB), - '3': createExpensifyCardBase(3, '5555', CONST.TRAVEL.PROGRAM_TRAVEL_US), - }; - - const selected = getSelectedCardsFromFeeds(cardList, {}, ['5555_Expensify Card']); - expect(selected.sort()).toEqual(['1', '2']); - }); - - it('still resolves a 2-segment selection when cards carry no feedCountry', () => { - const cardList: CardList = { - '1': createExpensifyCardBase(1, '5555'), - '2': createExpensifyCardBase(2, '5555'), - }; - - const selected = getSelectedCardsFromFeeds(cardList, {}, ['5555_Expensify Card']); - expect(selected.sort()).toEqual(['1', '2']); - }); - - it('keeps the travel workspace feed visible when the only domain entry is a regular Expensify Card', () => { - const workspaceCardFeeds: Record = { - 'cards_5555_Expensify Card': { - '1': {...createExpensifyCardBase(1, '5555', CONST.COUNTRY.US), domainName: 'user.com'}, - '2': {...createExpensifyCardBase(2, '5555', CONST.COUNTRY.US), domainName: 'expensify-policy1234567891011121.exfy'}, - }, - 'cards_5555_Expensify Card_TRAVEL_US': { - '3': {...createExpensifyCardBase(3, '5555', CONST.TRAVEL.PROGRAM_TRAVEL_US), domainName: 'expensify-policy1234567891011121.exfy'}, - }, - }; - - const names = getCardFeedNamesWithType({workspaceCardFeeds, policies: undefined, translate: translateLocal}); - expect(Object.keys(names)).toContain('cards_5555_Expensify Card_TRAVEL_US'); - expect(names['cards_5555_Expensify Card_TRAVEL_US'].type).toBe('workspace'); - expect(Object.keys(names)).toContain('cards_5555_Expensify Card'); - expect(names['cards_5555_Expensify Card'].type).toBe('domain'); - }); -}); - describe('getVisibleCompanyCardFeedsForSelector', () => { const fundID = 1234; const currentUserAccountID = 777; diff --git a/tests/unit/CardUtilsTest.ts b/tests/unit/CardUtilsTest.ts index 35de624109c7..337731b8865b 100644 --- a/tests/unit/CardUtilsTest.ts +++ b/tests/unit/CardUtilsTest.ts @@ -12,10 +12,8 @@ import { doesCardFeedExist, feedHasCards, filterAllInactiveCards, - filterCardsByNonExpensify, filterInactiveCards, filterInactiveCardsForWorkspace, - flattenWorkspaceCardsList, formatCardExpiration, formatMaskedCardName, getAllCardsForWorkspace, @@ -43,7 +41,6 @@ import { getDisplayableThirdPartyCards, getEligibleBankAccountsForCard, getEligibleBankAccountsForUkEuCard, - getFeedConnectionBrokenCard, getFeedNameForDisplay, getFeedType, getFilteredCardList, @@ -71,7 +68,6 @@ import { maskCardNumber, sortCardsByCardholderName, splitCardFeedWithDomainID, - splitMaskedCardNumber, } from '@src/libs/CardUtils'; import type {CardProgramKey} from '@src/libs/CardUtils'; import DateUtils from '@src/libs/DateUtils'; @@ -1977,24 +1973,6 @@ describe('CardUtils', () => { }); }); - describe('flattenCompanyCards', () => { - it('should return the flattened list of non-Expensify cards related to the provided workspaceAccountID', () => { - const workspaceAccountID = 11111111; - const flattenedCardsList = flattenWorkspaceCardsList(allCardsList, workspaceAccountID); - const {cardList, ...customCards} = customFeedCardsList; - expect(flattenedCardsList).toStrictEqual({ - ...directFeedCardsMultipleList, - ...customCards, - }); - }); - - it('should return undefined if not defined cards list was provided', () => { - const workspaceAccountID = 11111111; - const flattenedCardsList = flattenWorkspaceCardsList(undefined, workspaceAccountID); - expect(flattenedCardsList).toBeUndefined(); - }); - }); - describe('hasIssuedExpensifyCard', () => { it('should return true when Expensify Card was issued for given workspace', () => { const workspaceAccountID = 11111111; @@ -3405,139 +3383,6 @@ describe('CardUtils', () => { }); }); - describe('splitMaskedCardNumber', () => { - it('should split a masked card number correctly', () => { - const result = splitMaskedCardNumber('1234XXXX5678'); - expect(result.firstDigits).toBe('1234'); - expect(result.lastDigits).toBe('5678'); - }); - - it('should handle card numbers with custom mask character', () => { - const result = splitMaskedCardNumber('1234****5678', '*'); - expect(result.firstDigits).toBe('1234'); - expect(result.lastDigits).toBe('5678'); - }); - - it('should handle undefined card number', () => { - const result = splitMaskedCardNumber(undefined); - expect(result.firstDigits).toBeUndefined(); - expect(result.lastDigits).toBeUndefined(); - }); - - it('should handle card number with only first digits', () => { - const result = splitMaskedCardNumber('1234XXXX'); - expect(result.firstDigits).toBe('1234'); - expect(result.lastDigits).toBe(''); - }); - - it('should handle card number with only last digits', () => { - const result = splitMaskedCardNumber('XXXX5678'); - expect(result.firstDigits).toBe(''); - expect(result.lastDigits).toBe('5678'); - }); - }); - - describe('filterCardsByNonExpensify', () => { - it('should filter out cards with Expensify bank key in their key', () => { - const cards: CardList = createMock({ - [`${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, - }, - }); - - 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 = createMock({ - [`${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, - }, - }); - - 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 = createMock({ - 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, - }, - }); - - const result = filterCardsByNonExpensify(cards); - expect(Object.keys(result)).toHaveLength(2); - }); - }); - describe('filterAllInactiveCards', () => { it('should filter out closed, deactivated and suspended cards', () => { const cards: CardList = createMock({ @@ -4252,75 +4097,6 @@ describe('CardUtils', () => { }); }); - describe('getFeedConnectionBrokenCard', () => { - it('Should return undefined when feedCards is undefined', () => { - expect(getFeedConnectionBrokenCard(undefined)).toBeUndefined(); - }); - - it('Should return undefined when feedCards is empty', () => { - expect(getFeedConnectionBrokenCard({})).toBeUndefined(); - }); - - it('Should return the card with a broken connection status', () => { - const feedCards: CardList = { - card1: createMock({bank: 'oauth.chase.com', lastScrapeResult: 403, cardID: 1, state: CONST.EXPENSIFY_CARD.STATE.OPEN}), - }; - const result = getFeedConnectionBrokenCard(feedCards); - expect(result).toBeDefined(); - expect(result?.cardID).toBe(1); - }); - - it('Should return undefined when all cards have ignored statuses (200, 434, etc.)', () => { - const feedCards: CardList = { - card1: createMock({bank: 'oauth.chase.com', lastScrapeResult: 200, cardID: 1, state: CONST.EXPENSIFY_CARD.STATE.OPEN}), - card2: createMock({bank: 'oauth.chase.com', lastScrapeResult: 434, cardID: 2, state: CONST.EXPENSIFY_CARD.STATE.OPEN}), - }; - expect(getFeedConnectionBrokenCard(feedCards)).toBeUndefined(); - }); - - it('Should return undefined when cards have no lastScrapeResult', () => { - const feedCards: CardList = { - card1: createMock({bank: 'oauth.chase.com', cardID: 1, state: CONST.EXPENSIFY_CARD.STATE.OPEN}), - }; - expect(getFeedConnectionBrokenCard(feedCards)).toBeUndefined(); - }); - - it('Should exclude cards matching feedToExclude', () => { - const feedCards: CardList = { - card1: createMock({bank: 'oauth.chase.com', lastScrapeResult: 403, cardID: 1, state: CONST.EXPENSIFY_CARD.STATE.OPEN}), - }; - expect(getFeedConnectionBrokenCard(feedCards, 'oauth.chase.com')).toBeUndefined(); - }); - - it('Should return a broken card from a different feed when feedToExclude is set', () => { - const feedCards: CardList = { - card1: createMock({bank: 'oauth.chase.com', lastScrapeResult: 403, cardID: 1, state: CONST.EXPENSIFY_CARD.STATE.OPEN}), - card2: createMock({bank: CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX_DIRECT, lastScrapeResult: 403, cardID: 2, state: CONST.EXPENSIFY_CARD.STATE.OPEN}), - }; - const result = getFeedConnectionBrokenCard(feedCards, 'oauth.chase.com'); - expect(result).toBeDefined(); - expect(result?.cardID).toBe(2); - }); - - it('Should skip empty card objects', () => { - const feedCards: CardList = { - card1: createMock({}), - card2: createMock({bank: 'oauth.chase.com', lastScrapeResult: 403, cardID: 2, state: CONST.EXPENSIFY_CARD.STATE.OPEN}), - }; - const result = getFeedConnectionBrokenCard(feedCards); - expect(result).toBeDefined(); - expect(result?.cardID).toBe(2); - }); - - it('Should return undefined when all non-ignored statuses belong to excluded feed', () => { - const feedCards: CardList = { - card1: createMock({bank: 'oauth.chase.com', lastScrapeResult: 403, cardID: 1, state: CONST.EXPENSIFY_CARD.STATE.OPEN}), - card2: createMock({bank: CONST.COMPANY_CARD.FEED_BANK_NAME.AMEX_DIRECT, lastScrapeResult: 200, cardID: 2, state: CONST.EXPENSIFY_CARD.STATE.OPEN}), - }; - expect(getFeedConnectionBrokenCard(feedCards, 'oauth.chase.com')).toBeUndefined(); - }); - }); - describe('getCardHintText', () => { afterEach(() => { jest.restoreAllMocks(); diff --git a/tests/unit/OptionsListUtilsTest.tsx b/tests/unit/OptionsListUtilsTest.tsx index aa3d7424746c..78bf6df78fc4 100644 --- a/tests/unit/OptionsListUtilsTest.tsx +++ b/tests/unit/OptionsListUtilsTest.tsx @@ -24,7 +24,6 @@ import { formatMemberForList, formatSectionsFromSearchTerm, getFilteredRecentAttendees, - getIOUReportIDOfLastAction, getLastActorDisplayName, getLastActorDisplayNameFromLastVisibleActions, getLastMessageTextForReport, @@ -8531,99 +8530,6 @@ describe('OptionsListUtils', () => { }); }); - describe('getIOUReportIDOfLastAction', () => { - it('should return undefined when report is undefined', () => { - const result = getIOUReportIDOfLastAction(undefined, undefined); - expect(result).toBeUndefined(); - }); - - it('should return undefined when report has no reportID', () => { - const report = {} as Report; - const result = getIOUReportIDOfLastAction(report, undefined); - expect(result).toBeUndefined(); - }); - - it('should return undefined when lastAction is not a REPORT_PREVIEW action', () => { - const report: Report = { - ...createRandomReport(0, undefined), - reportID: 'iou-test-1', - }; - const lastAction: ReportAction = { - ...createRandomReportAction(1), - actionName: CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT, - }; - - const result = getIOUReportIDOfLastAction(report, undefined, undefined, lastAction); - expect(result).toBeUndefined(); - }); - - it('should return IOU report ID when lastAction is a REPORT_PREVIEW action with a valid IOU report', async () => { - const iouReportID = 'iou-report-1'; - const reportID = 'iou-test-2'; - const report: Report = { - ...createRandomReport(0, undefined), - reportID, - }; - - // Create the IOU report in Onyx so getReportOrDraftReport can find it - const iouReport: Report = { - ...createRandomReport(0, undefined), - reportID: iouReportID, - }; - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`, iouReport); - await waitForBatchedUpdates(); - - const lastAction: ReportAction = { - ...createRandomReportAction(1), - actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, - originalMessage: { - linkedReportID: iouReportID, - }, - } as ReportAction; - - const result = getIOUReportIDOfLastAction(report, undefined, undefined, lastAction); - expect(result).toBe(iouReportID); - }); - - it('should return undefined when report is archived and canUserPerformWrite returns false', async () => { - const reportID = 'iou-test-archived'; - const report: Report = { - ...createRandomReport(0, undefined), - reportID, - statusNum: CONST.REPORT.STATUS_NUM.CLOSED, - stateNum: CONST.REPORT.STATE_NUM.APPROVED, - type: CONST.REPORT.TYPE.CHAT, - }; - - // Set up the report in Onyx - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, report); - await waitForBatchedUpdates(); - - // When we pass true for privateIsArchived, the report is considered archived - const privateIsArchived = true; - - // With no lastAction provided and no visible actions in Onyx, it falls through to the lastVisibleAction lookup - // which returns undefined, so isReportPreviewAction returns false - const result = getIOUReportIDOfLastAction(report, privateIsArchived); - expect(result).toBeUndefined(); - }); - - it('should handle privateIsArchived as undefined (non-archived report)', () => { - const report: Report = { - ...createRandomReport(0, undefined), - reportID: 'iou-test-not-archived', - }; - const lastAction: ReportAction = { - ...createRandomReportAction(1), - actionName: CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT, - }; - - // privateIsArchived is undefined means the report is not archived - const result = getIOUReportIDOfLastAction(report, undefined, undefined, lastAction); - expect(result).toBeUndefined(); - }); - }); - describe('prepareReportOptionsForDisplay with sortedActions', () => { it('should use sortedActions to compute lastIOUCreationDate for expense report sorting', async () => { const reportID = 'sorted-test-1'; diff --git a/tests/unit/ReportTitleUtilsTest.ts b/tests/unit/ReportTitleUtilsTest.ts index 2d3a6ad259e8..e862cea691ce 100644 --- a/tests/unit/ReportTitleUtilsTest.ts +++ b/tests/unit/ReportTitleUtilsTest.ts @@ -1,9 +1,8 @@ -import {getTitleFieldFromRNVP, removeTitleFieldFromReport, shouldUpdateTitleField, updateTitleFieldToMatchPolicy} from '@libs/ReportTitleUtils'; +import {getTitleFieldFromRNVP, updateTitleFieldToMatchPolicy} from '@libs/ReportTitleUtils'; import * as ReportUtils from '@libs/ReportUtils'; -import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Policy, PolicyReportField, Report} from '@src/types/onyx'; +import type {Policy, PolicyReportField} from '@src/types/onyx'; import Onyx from 'react-native-onyx'; @@ -94,66 +93,4 @@ describe('ReportTitleUtils', () => { expect(mockedReportUtils.getTitleReportField).not.toHaveBeenCalled(); }); }); - - describe('removeTitleFieldFromReport', () => { - const mockReportID = '12345'; - - it('should return optimistic update with null value for valid reportID', () => { - const result = removeTitleFieldFromReport(mockReportID); - - expect(result).toHaveLength(1); - expect(result.at(0)).toEqual({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${mockReportID}`, - value: { - // eslint-disable-next-line @typescript-eslint/naming-convention - expensify_text_title: null, - }, - }); - }); - }); - - describe('shouldUpdateTitleField', () => { - const mockReportID = '12345'; - - it('should return false when report is chat report', () => { - const mockReport: Report = { - reportID: mockReportID, - type: CONST.REPORT.TYPE.CHAT, - } as Report; - - mockedReportUtils.isChatReport.mockReturnValue(true); - - const result = shouldUpdateTitleField(mockReport); - - expect(mockedReportUtils.isChatReport).toHaveBeenCalledWith(mockReport); - expect(result).toBe(false); - }); - - it('should return false when report has no title field in RNVP', () => { - const mockReport: Report = { - reportID: '5555', - type: CONST.REPORT.TYPE.EXPENSE, - } as Report; - - mockedReportUtils.isChatReport.mockReturnValue(false); - - const result = shouldUpdateTitleField(mockReport); - - expect(result).toBe(false); - }); - - it('should return true when non-chat report has title field', () => { - const mockReport: Report = { - reportID: mockReportID, - type: CONST.REPORT.TYPE.EXPENSE, - } as Report; - - mockedReportUtils.isChatReport.mockReturnValue(false); - - const result = shouldUpdateTitleField(mockReport); - - expect(result).toBe(true); - }); - }); }); diff --git a/tests/unit/ReportUtilsTest.ts b/tests/unit/ReportUtilsTest.ts index 7f94bb8478f9..b2d1f7586a7a 100644 --- a/tests/unit/ReportUtilsTest.ts +++ b/tests/unit/ReportUtilsTest.ts @@ -162,7 +162,6 @@ import { pushTransactionViolationsOnyxData, reasonForReportToBeInOptionList, requiresAttentionFromCurrentUser, - requiresManualSubmission, shouldBlockSubmitDueToPreventSelfApproval, shouldBlockSubmitDueToStrictPolicyRules, shouldDisableRename, @@ -11884,90 +11883,6 @@ describe('ReportUtils', () => { }); }); - describe('requiresManualSubmission', () => { - it('should return true when manual submit is enabled', () => { - const report: Report = { - ...createRandomReport(1, undefined), - stateNum: CONST.REPORT.STATE_NUM.OPEN, - statusNum: CONST.REPORT.STATUS_NUM.OPEN, - }; - const policy1 = createRandomPolicy(1); - policy1.harvesting = {enabled: false}; - policy1.autoReportingFrequency = CONST.POLICY.AUTO_REPORTING_FREQUENCIES.IMMEDIATE; - const result = requiresManualSubmission(report, policy1); - expect(result).toBe(true); - }); - - it('should return false when instant submit is enabled and report is not open', () => { - const report: Report = { - ...createRandomReport(2, undefined), - stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, - statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED, - }; - const policy2 = createRandomPolicy(2); - policy2.autoReporting = true; - policy2.autoReportingFrequency = CONST.POLICY.AUTO_REPORTING_FREQUENCIES.INSTANT; - policy2.approvalMode = CONST.POLICY.APPROVAL_MODE.BASIC; - const result = requiresManualSubmission(report, policy2); - expect(result).toBe(false); - }); - - it('should return false when instant submit is enabled with approvers', () => { - const report: Report = { - ...createRandomReport(3, undefined), - stateNum: CONST.REPORT.STATE_NUM.OPEN, - statusNum: CONST.REPORT.STATUS_NUM.OPEN, - }; - const policy3 = createRandomPolicy(3); - policy3.autoReporting = true; - policy3.autoReportingFrequency = CONST.POLICY.AUTO_REPORTING_FREQUENCIES.INSTANT; - policy3.approvalMode = CONST.POLICY.APPROVAL_MODE.BASIC; - const result = requiresManualSubmission(report, policy3); - expect(result).toBe(false); - }); - - it('should return true for open report in Submit & Close policy with instant submit', () => { - const report: Report = { - ...createRandomReport(4, undefined), - stateNum: CONST.REPORT.STATE_NUM.OPEN, - statusNum: CONST.REPORT.STATUS_NUM.OPEN, - }; - const policy4 = createRandomPolicy(4); - policy4.autoReporting = true; - policy4.autoReportingFrequency = CONST.POLICY.AUTO_REPORTING_FREQUENCIES.INSTANT; - policy4.approvalMode = CONST.POLICY.APPROVAL_MODE.OPTIONAL; // Submit & Close (no approvers) - const result = requiresManualSubmission(report, policy4); - expect(result).toBe(true); - }); - - it('should return false for closed report in Submit & Close policy with instant submit', () => { - const report: Report = { - ...createRandomReport(5, undefined), - stateNum: CONST.REPORT.STATE_NUM.APPROVED, - statusNum: CONST.REPORT.STATUS_NUM.CLOSED, - }; - const policy5 = createRandomPolicy(5); - policy5.autoReporting = true; - policy5.autoReportingFrequency = CONST.POLICY.AUTO_REPORTING_FREQUENCIES.INSTANT; - policy5.approvalMode = CONST.POLICY.APPROVAL_MODE.OPTIONAL; // Submit & Close (no approvers) - const result = requiresManualSubmission(report, policy5); - expect(result).toBe(false); - }); - - it('should return false when policy has auto reporting with monthly frequency (delayed submission)', () => { - const report: Report = { - ...createRandomReport(8, undefined), - stateNum: CONST.REPORT.STATE_NUM.OPEN, - statusNum: CONST.REPORT.STATUS_NUM.OPEN, - }; - const policy6 = createRandomPolicy(8); - policy6.autoReporting = true; - policy6.autoReportingFrequency = CONST.POLICY.AUTO_REPORTING_FREQUENCIES.MONTHLY; - const result = requiresManualSubmission(report, policy6); - expect(result).toBe(false); - }); - }); - describe('isWorkspaceMemberLeavingWorkspaceRoom', () => { test('should return false when not a policy employee', () => { const report = { diff --git a/tests/unit/Search/buildCardFilterDataTest.ts b/tests/unit/Search/buildCardFilterDataTest.ts index 55ac42e9126f..86d70988592c 100644 --- a/tests/unit/Search/buildCardFilterDataTest.ts +++ b/tests/unit/Search/buildCardFilterDataTest.ts @@ -1,22 +1,13 @@ // The cards_ object keys don't follow normal naming convention, so to test this reliably we have to disable liner /* 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 {buildCardsData} from '@libs/CardFeedUtils'; import type IllustrationsType from '@styles/theme/illustrations/types'; -import type {CardList, Policy, WorkspaceCardsList} from '@src/types/onyx'; +import type {CardList, WorkspaceCardsList} from '@src/types/onyx'; jest.mock('@src/components/ConfirmedRoute.tsx'); -const mockPolicies = { - policy_1: {id: '1', name: ''} as Policy, - policy_2: {id: '2', name: 'test1'} as Policy, - policy_3: {id: '3', name: 'test2'} as Policy, -}; - const workspaceCardFeeds = { cards_18680694_vcf: { '21593492': { @@ -297,12 +288,6 @@ const cardListClosed = { }, }; -const domainFeedDataMock = { - 'mockDomain.com': {domainName: 'mockDomain.com', bank: 'Expensify Card', correspondingCardIDs: ['21589168', '21589182']}, -} as const satisfies Record; - -const translateMock = jest.fn(); - const illustrationsMock = { EmptyStateBackgroundImage: jest.fn(), ExampleCheckES: jest.fn(), @@ -406,48 +391,6 @@ describe('buildCardsData with empty argument objects', () => { }); }); -describe('buildCardFeedsData', () => { - const result = buildCardFeedsData( - workspaceCardFeeds as unknown as Record, - domainFeedDataMock, - mockPolicies, - [], - translateMock as LocaleContextProps['translate'], - illustrationsMock as IllustrationsType, - companyCardIconsMock, - ); - - it('Build domain card feed properly', () => { - // Check if external domain feed was built properly - expect(result.at(0)).toMatchObject({ - isCardFeed: true, - correspondingCards: ['21589168', '21589182'], - }); - expect(translateMock).toHaveBeenCalledWith('search.filters.card.cardFeedName', {cardFeedBankName: undefined, cardFeedLabel: 'mockDomain.com'}); - - // Check if domain card feed was built properly - expect(result.at(1)).toMatchObject({ - isCardFeed: true, - correspondingCards: ['21593492', '21604933', '21638320', '21638598'], - }); - expect(translateMock).toHaveBeenCalledWith('search.filters.card.cardFeedName', {cardFeedBankName: 'Visa', cardFeedLabel: undefined}); - // Check if workspace card feed that comes from company cards was built properly. - expect(result.at(2)).toMatchObject({ - isCardFeed: true, - correspondingCards: ['21588678', '21588684'], - }); - expect(translateMock).toHaveBeenCalledWith('search.filters.card.cardFeedName', {cardFeedBankName: undefined, cardFeedLabel: 'test1'}); - // Check if workspace card feed that comes from expensify cards was built properly - expect(result.at(3)).toMatchObject({ - isCardFeed: true, - correspondingCards: ['21589168', '21589182', '21589202', '21638322'], - }); - expect(translateMock).toHaveBeenCalledWith('search.filters.card.cardFeedName', {cardFeedBankName: undefined, cardFeedLabel: 'test2'}); - // Check if domain card feed was built properly - expect(result.length).toEqual(4); - }); -}); - describe('buildCardsData isPersonal with customCardNames', () => { it('Uses customCardNames for personal cards when provided', () => { // Card 11111111 has no fundID, so it is treated as personal (isPersonalCard returns true) @@ -485,10 +428,3 @@ describe('buildCardsData isPersonal with customCardNames', () => { expect(personalCard?.cardName).toBe('455594XXXXXX1138'); }); }); - -describe('buildIndividualCardsData with empty argument objects', () => { - it('Return empty array when domainCardFeeds and workspaceCardFeeds are empty', () => { - const result = buildCardFeedsData({}, {}, mockPolicies, [], translateMock as LocaleContextProps['translate'], illustrationsMock as IllustrationsType, companyCardIconsMock); - expect(result).toEqual([]); - }); -}); diff --git a/tests/unit/Search/yourSpendApplicabilityTest.ts b/tests/unit/Search/yourSpendApplicabilityTest.ts index 3c37084ac137..1b1ed766de5e 100644 --- a/tests/unit/Search/yourSpendApplicabilityTest.ts +++ b/tests/unit/Search/yourSpendApplicabilityTest.ts @@ -1,11 +1,7 @@ /** * Tests for Your Spend slot applicability helpers. - * - * `hasApprovalFlow` must gate on `isPaidGroupPolicy` first. Approval mode is - * present on personal/free policies but is functionally inert there. A personal - * policy with `approvalMode = BASIC` must NOT be treated as having an approval flow. */ -import {arePaymentsEnabled, hasApprovalFlow} from '@libs/PolicyUtils'; +import {arePaymentsEnabled} from '@libs/PolicyUtils'; import {getOutstandingReportsSignature, getYourSpendApplicability} from '@pages/home/YourSpendSection/useYourSpendData'; @@ -46,53 +42,6 @@ function reportsCollection(reports: Report[]): Record { return Object.fromEntries(reports.map((r) => [`${ONYXKEYS.COLLECTION.REPORT}${r.reportID}`, r])); } -describe('hasApprovalFlow', () => { - // Personal-policy fixture that locks in the isPaidGroupPolicy gate - it('returns false for a personal policy even when approvalMode is BASIC', () => { - const personalPolicy = makePolicy({ - type: CONST.POLICY.TYPE.PERSONAL, - approvalMode: CONST.POLICY.APPROVAL_MODE.BASIC, - }); - expect(hasApprovalFlow(personalPolicy)).toBe(false); - }); - - it('returns false for a TEAM policy with approvalMode OPTIONAL (Submit & Close)', () => { - const policy = makePolicy({ - type: CONST.POLICY.TYPE.TEAM, - approvalMode: CONST.POLICY.APPROVAL_MODE.OPTIONAL, - }); - expect(hasApprovalFlow(policy)).toBe(false); - }); - - it('returns false for a CORPORATE policy with no approvalMode set', () => { - const policy = makePolicy({ - type: CONST.POLICY.TYPE.CORPORATE, - approvalMode: undefined, - }); - expect(hasApprovalFlow(policy)).toBe(false); - }); - - it('returns false for an undefined policy', () => { - expect(hasApprovalFlow(undefined)).toBe(false); - }); - - it('returns true for a TEAM (paid group) policy with approvalMode BASIC', () => { - const policy = makePolicy({ - type: CONST.POLICY.TYPE.TEAM, - approvalMode: CONST.POLICY.APPROVAL_MODE.BASIC, - }); - expect(hasApprovalFlow(policy)).toBe(true); - }); - - it('returns true for a CORPORATE (paid group) policy with approvalMode ADVANCED', () => { - const policy = makePolicy({ - type: CONST.POLICY.TYPE.CORPORATE, - approvalMode: CONST.POLICY.APPROVAL_MODE.ADVANCED, - }); - expect(hasApprovalFlow(policy)).toBe(true); - }); -}); - describe('arePaymentsEnabled (payment row applicability)', () => { it('returns false when reimbursementChoice is REIMBURSEMENT_NO', () => { const policy = makePolicy({ diff --git a/tests/unit/UserAvatarUtilsTest.ts b/tests/unit/UserAvatarUtilsTest.ts index bef90c91ebb4..b278ef969aa1 100644 --- a/tests/unit/UserAvatarUtilsTest.ts +++ b/tests/unit/UserAvatarUtilsTest.ts @@ -386,7 +386,7 @@ describe('UserAvatarUtils', () => { const url = UserAvatarUtils.getLetterAvatarURL(42, 'Dave', 'Lee', 'dave@example.com'); const parsed = UserAvatarUtils.parseLetterAvatarURL(url); expect(parsed?.initials).toBe('DL'); - expect(parsed?.colors).toEqual(UserAvatarUtils.getLetterAvatarScheme('blue100')); + expect(parsed?.colors).toEqual({backgroundColor: '#B0D9FF', fillColor: '#0164BF'}); }); }); }); diff --git a/tests/unit/getLetterAvatarSchemeTest.ts b/tests/unit/getLetterAvatarSchemeTest.ts deleted file mode 100644 index 4f77433ac0f8..000000000000 --- a/tests/unit/getLetterAvatarSchemeTest.ts +++ /dev/null @@ -1,21 +0,0 @@ -import {DEFAULT_LETTER_AVATAR_SCHEME, LETTER_AVATAR_SCHEMES} from '@libs/Avatars/letterAvatarPalette'; -import {getLetterAvatarScheme} from '@libs/UserAvatarUtils'; - -describe('getLetterAvatarScheme', () => { - it('returns the scheme for a valid key', () => { - expect(getLetterAvatarScheme('pink400')).toEqual(LETTER_AVATAR_SCHEMES.pink400); - }); - - it('falls back to the default scheme for an unknown key', () => { - expect(getLetterAvatarScheme('not-a-real-key')).toEqual(DEFAULT_LETTER_AVATAR_SCHEME); - }); - - it('falls back to the default scheme for inherited Object keys', () => { - expect(getLetterAvatarScheme('toString')).toEqual(DEFAULT_LETTER_AVATAR_SCHEME); - expect(getLetterAvatarScheme('constructor')).toEqual(DEFAULT_LETTER_AVATAR_SCHEME); - }); - - it('falls back to the default scheme when no key is given', () => { - expect(getLetterAvatarScheme()).toEqual(DEFAULT_LETTER_AVATAR_SCHEME); - }); -}); diff --git a/tests/unit/hooks/useFrozenPreSelection.test.ts b/tests/unit/hooks/useFrozenPreSelection.test.ts deleted file mode 100644 index 92f3dbff77d1..000000000000 --- a/tests/unit/hooks/useFrozenPreSelection.test.ts +++ /dev/null @@ -1,200 +0,0 @@ -import {renderHook} from '@testing-library/react-native'; - -import useFrozenPreSelection from '@hooks/useFrozenPreSelection'; - -import CONST from '@src/CONST'; - -type Item = { - keyForList: string; - text?: string; - isSelected?: boolean; -}; - -type Section = {data: Item[]; sectionIndex: number}; - -const padTo = (target: number, existing: Item[]): Section[] => { - const filler: Item[] = []; - for (let i = existing.length; i < target; i++) { - filler.push({keyForList: `filler-${i}`}); - } - return [{data: [...existing, ...filler], sectionIndex: 1}]; -}; - -const longList = CONST.STANDARD_LIST_ITEM_LIMIT; - -describe('useFrozenPreSelection', () => { - it('returns input unchanged while canCapture is false', () => { - const item: Item = {keyForList: '1'}; - const sections = padTo(longList, [item]); - const {result} = renderHook(() => useFrozenPreSelection(sections, {initialSelectedValues: ['1'], canCapture: false})); - - expect(result.current).toBe(sections); - }); - - it('pins pre-selected rows in a new top section and removes them from the input sections', () => { - const pinned: Item = {keyForList: '1', isSelected: true}; - const other: Item = {keyForList: '2'}; - const sections = padTo(longList, [pinned, other]); - const {result} = renderHook(() => useFrozenPreSelection(sections, {initialSelectedValues: ['1'], canCapture: true})); - - expect(result.current.at(0)).toEqual({data: [pinned], sectionIndex: 0}); - expect(result.current.at(1)?.data.some((item) => item.keyForList === '1')).toBe(false); - expect(result.current.at(1)?.data.some((item) => item.keyForList === '2')).toBe(true); - }); - - it('returns input unchanged when the combined item count is below the threshold', () => { - const item: Item = {keyForList: '1'}; - const sections: Section[] = [{data: [item], sectionIndex: 1}]; - const {result} = renderHook(() => useFrozenPreSelection(sections, {initialSelectedValues: ['1'], canCapture: true})); - - expect(result.current).toBe(sections); - }); - - it('locks the snapshot once captured, even when initialSelectedValues changes later', () => { - const captured: Item = {keyForList: '1'}; - const newcomer: Item = {keyForList: '99'}; - const initialSections = padTo(longList, [captured, newcomer]); - const {result, rerender} = renderHook( - ({sections, initialSelectedValues}: {sections: Section[]; initialSelectedValues: string[]}) => useFrozenPreSelection(sections, {initialSelectedValues, canCapture: true}), - {initialProps: {sections: initialSections, initialSelectedValues: ['1']}}, - ); - - expect(result.current.at(0)?.data).toEqual([captured]); - - rerender({sections: initialSections, initialSelectedValues: ['99']}); - - expect(result.current.at(0)?.data).toEqual([captured]); - }); - - it('preserves capture order across renders, using the live row from input sections', () => { - const a: Item = {keyForList: 'a'}; - const b: Item = {keyForList: 'b'}; - const initialSections = padTo(longList, [b, a]); - const {result, rerender} = renderHook(({sections}: {sections: Section[]}) => useFrozenPreSelection(sections, {initialSelectedValues: ['a', 'b'], canCapture: true}), { - initialProps: {sections: initialSections}, - }); - - // Capture order follows traversal of sections — b appears before a. - expect(result.current.at(0)?.data.map((item) => item.keyForList)).toEqual(['b', 'a']); - - // Live row replaces the captured row so toggles refresh in place. - const aLive: Item = {keyForList: 'a', isSelected: false}; - const bLive: Item = {keyForList: 'b', isSelected: true}; - rerender({sections: padTo(longList, [bLive, aLive])}); - - expect(result.current.at(0)?.data).toEqual([bLive, aLive]); - }); - - it('drops frozen items that are not present in any input section', () => { - const visible: Item = {keyForList: 'visible'}; - const sections = padTo(longList, [visible]); - const {result} = renderHook(() => useFrozenPreSelection(sections, {initialSelectedValues: ['missing', 'visible'], canCapture: true})); - - expect(result.current.at(0)?.data).toEqual([visible]); - }); - - it('returns input unchanged when no initialSelectedValues match anything in sections', () => { - const sections = padTo(longList, [{keyForList: 'visible'}]); - const {result} = renderHook(() => useFrozenPreSelection(sections, {initialSelectedValues: ['nothing-matches'], canCapture: true})); - - expect(result.current).toBe(sections); - }); - - it('returns input unchanged when initialSelectedValues is empty', () => { - const sections = padTo(longList, [{keyForList: 'visible'}]); - const {result} = renderHook(() => useFrozenPreSelection(sections, {initialSelectedValues: [], canCapture: true})); - - expect(result.current).toBe(sections); - }); - - it('with shouldRenderPinned, retains pinned rows even when they are absent from input sections', () => { - const pinned: Item = {keyForList: 'pinned'}; - const initialSections = padTo(longList, [pinned]); - const {result, rerender} = renderHook( - ({sections}: {sections: Section[]}) => useFrozenPreSelection(sections, {initialSelectedValues: ['pinned'], canCapture: true, shouldRenderPinned: () => true}), - { - initialProps: {sections: initialSections}, - }, - ); - - // While the row is in the input sections, the live copy surfaces (no isSelected on the live row). - expect(result.current.at(0)?.data).toEqual([pinned]); - - // Simulate a search filtering "pinned" out of the input sections — the captured copy (initialized - // with isSelected: false at capture time) should still surface. - rerender({sections: padTo(longList, [{keyForList: 'other'}])}); - - expect(result.current.at(0)?.data).toEqual([{keyForList: 'pinned', isSelected: false}]); - }); - - it('with shouldRenderPinned, drops pinned rows for which the predicate returns false', () => { - const matching: Item = {keyForList: 'match'}; - const filtered: Item = {keyForList: 'filtered'}; - const sections = padTo(longList, [matching, filtered]); - const {result} = renderHook(() => - useFrozenPreSelection(sections, { - initialSelectedValues: ['match', 'filtered'], - canCapture: true, - shouldRenderPinned: (item) => item.keyForList === 'match', - }), - ); - - expect(result.current.at(0)?.data).toEqual([matching]); - }); - - it('with shouldRenderPinned, omits the top section entirely when the predicate filters everything out', () => { - const filtered: Item = {keyForList: 'filtered'}; - const other: Item = {keyForList: 'other'}; - const sections = padTo(longList, [filtered, other]); - const {result} = renderHook(() => - useFrozenPreSelection(sections, { - initialSelectedValues: ['filtered'], - canCapture: true, - shouldRenderPinned: () => false, - }), - ); - - // No frozen section at the top, but "filtered" is still removed from the input section because it was captured. - expect(result.current.at(0)?.data.some((item) => item.keyForList === 'filtered')).toBe(false); - expect(result.current.at(0)?.data.some((item) => item.keyForList === 'other')).toBe(true); - }); - - it('with getKey, matches items against initialSelectedValues using the extractor instead of keyForList', () => { - type ItemWithAccountID = Item & {accountID: number}; - const pinned: ItemWithAccountID = {keyForList: 'report-1', accountID: 1}; - const other: ItemWithAccountID = {keyForList: 'report-2', accountID: 2}; - const filler: ItemWithAccountID[] = []; - for (let i = 0; i < longList - 2; i++) { - filler.push({keyForList: `report-${i + 3}`, accountID: i + 3}); - } - const sections: Array<{data: ItemWithAccountID[]; sectionIndex: number}> = [{data: [pinned, other, ...filler], sectionIndex: 1}]; - - const {result} = renderHook(() => - useFrozenPreSelection(sections, { - initialSelectedValues: ['1'], - canCapture: true, - getKey: (item) => item.accountID.toString(), - }), - ); - - expect(result.current.at(0)?.data).toEqual([pinned]); - expect(result.current.at(1)?.data.some((item) => item.keyForList === 'report-1')).toBe(false); - }); - - it('does not re-capture on later renders after capturing an empty snapshot below the threshold', () => { - const item: Item = {keyForList: '1'}; - const initialSections: Section[] = [{data: [item], sectionIndex: 1}]; - const {result, rerender} = renderHook(({sections}: {sections: Section[]}) => useFrozenPreSelection(sections, {initialSelectedValues: ['1'], canCapture: true}), { - initialProps: {sections: initialSections}, - }); - - // Below threshold on first render → empty snapshot captured. - expect(result.current).toBe(initialSections); - - // List grows past the threshold on a later render; snapshot stays empty, no pinning. - const grownSections = padTo(longList, [item]); - rerender({sections: grownSections}); - - expect(result.current).toBe(grownSections); - }); -}); diff --git a/tests/unit/hooks/useMappedPersonalDetails.test.ts b/tests/unit/hooks/useMappedPersonalDetails.test.ts deleted file mode 100644 index 84a7864dca50..000000000000 --- a/tests/unit/hooks/useMappedPersonalDetails.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import {renderHook, waitFor} from '@testing-library/react-native'; - -import useMappedPersonalDetails from '@hooks/useMappedPersonalDetails'; - -import ONYXKEYS from '@src/ONYXKEYS'; -import type {PersonalDetails} from '@src/types/onyx'; - -import type {OnyxEntry} from 'react-native-onyx'; - -import Onyx from 'react-native-onyx'; - -const ACCOUNT_ID_ALICE = 1; -const ACCOUNT_ID_BOB = 2; - -describe('useMappedPersonalDetails', () => { - beforeAll(() => { - Onyx.init({keys: ONYXKEYS}); - }); - - beforeEach(async () => { - await Onyx.clear(); - }); - - it('should return mapped personal details using the provided mapper', async () => { - const personalDetailsList = { - [ACCOUNT_ID_ALICE]: {accountID: ACCOUNT_ID_ALICE, displayName: 'Alice', login: 'alice@test.com'}, - [ACCOUNT_ID_BOB]: {accountID: ACCOUNT_ID_BOB, displayName: 'Bob', login: 'bob@test.com'}, - }; - - await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, personalDetailsList); - - const mapper = (pd: OnyxEntry) => pd && {displayName: pd.displayName}; - - const {result} = renderHook(() => useMappedPersonalDetails(mapper)); - - await waitFor(() => { - expect(result.current[0]).toEqual({ - [ACCOUNT_ID_ALICE]: {displayName: 'Alice'}, - [ACCOUNT_ID_BOB]: {displayName: 'Bob'}, - }); - }); - }); - - it('should return empty object when personal details list is empty', async () => { - const mapper = (pd: OnyxEntry) => pd?.displayName; - - const {result} = renderHook(() => useMappedPersonalDetails(mapper)); - - await waitFor(() => { - expect(result.current[0]).toEqual({}); - }); - }); - - it('should apply mapper that extracts a single field', async () => { - const personalDetailsList = { - [ACCOUNT_ID_ALICE]: {accountID: ACCOUNT_ID_ALICE, displayName: 'Alice', login: 'alice@test.com'}, - [ACCOUNT_ID_BOB]: {accountID: ACCOUNT_ID_BOB, displayName: 'Bob', login: 'bob@test.com'}, - }; - - await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, personalDetailsList); - - const mapper = (pd: OnyxEntry) => pd?.displayName ?? 'unknown'; - - const {result} = renderHook(() => useMappedPersonalDetails(mapper)); - - await waitFor(() => { - expect(result.current[0]).toEqual({ - [ACCOUNT_ID_ALICE]: 'Alice', - [ACCOUNT_ID_BOB]: 'Bob', - }); - }); - }); - - it('should update mapped details when Onyx data changes', async () => { - await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, { - [ACCOUNT_ID_ALICE]: {accountID: ACCOUNT_ID_ALICE, displayName: 'Alice', login: 'alice@test.com'}, - }); - - const mapper = (pd: OnyxEntry) => pd && {displayName: pd.displayName}; - const {result} = renderHook(() => useMappedPersonalDetails(mapper)); - - await waitFor(() => { - expect(Object.keys(result.current[0])).toHaveLength(1); - }); - - await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, { - [ACCOUNT_ID_BOB]: {accountID: ACCOUNT_ID_BOB, displayName: 'Bob', login: 'bob@test.com'}, - }); - - await waitFor(() => { - expect(Object.keys(result.current[0])).toHaveLength(2); - expect(result.current[0][ACCOUNT_ID_BOB]).toEqual({displayName: 'Bob'}); - }); - }); -}); diff --git a/tests/unit/libs/Avatars/InitialAvatarsTest.tsx b/tests/unit/libs/Avatars/InitialAvatarsTest.tsx index d5ba6cd03a09..c03c9c61a92a 100644 --- a/tests/unit/libs/Avatars/InitialAvatarsTest.tsx +++ b/tests/unit/libs/Avatars/InitialAvatarsTest.tsx @@ -1,10 +1,4 @@ -import {render} from '@testing-library/react-native'; - -import Icon from '@components/Icon'; - -import {DEFAULT_INITIAL, getInitialAvatarSvg, getInitialFromText} from '@libs/Avatars/InitialAvatars'; - -import React from 'react'; +import {DEFAULT_INITIAL, getInitialFromText} from '@libs/Avatars/InitialAvatars'; describe('getInitialFromText', () => { it('returns the first valid letter or number', () => { @@ -26,23 +20,3 @@ describe('getInitialFromText', () => { expect(getInitialFromText('你好')).toBe(DEFAULT_INITIAL); }); }); - -describe('getInitialAvatarSvg', () => { - it('resolves a component for a valid initial', () => { - const AvatarComponent = getInitialAvatarSvg('J'); - expect(AvatarComponent).toBeDefined(); - expect(typeof AvatarComponent).toBe('function'); - }); - - it('renders a letter avatar component', () => { - const AvatarComponent = getInitialAvatarSvg('J'); - const {toJSON} = render(); - expect(toJSON()).toBeTruthy(); - }); - - it('matches snapshot for a letter avatar', () => { - const AvatarComponent = getInitialAvatarSvg('J'); - const {toJSON} = render(); - expect(toJSON()).toMatchSnapshot(); - }); -}); diff --git a/tests/unit/libs/Avatars/__snapshots__/InitialAvatarsTest.tsx.snap b/tests/unit/libs/Avatars/__snapshots__/InitialAvatarsTest.tsx.snap deleted file mode 100644 index 4ae1532b24d0..000000000000 --- a/tests/unit/libs/Avatars/__snapshots__/InitialAvatarsTest.tsx.snap +++ /dev/null @@ -1,18 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`getInitialAvatarSvg matches snapshot for a letter avatar 1`] = ` - - - -`; diff --git a/tests/unit/libs/PersonalDetailsUtilsTest.ts b/tests/unit/libs/PersonalDetailsUtilsTest.ts index b192ebd59395..702550c5050a 100644 --- a/tests/unit/libs/PersonalDetailsUtilsTest.ts +++ b/tests/unit/libs/PersonalDetailsUtilsTest.ts @@ -2,7 +2,6 @@ import { arePersonalDetailsMissing, areTravelPersonalDetailsMissing, createDisplayName, - createPersonalDetailsLookupByAccountID, getAccountIDsByLogins, getDisplayNameOrYou, getEffectiveDisplayName, @@ -685,52 +684,6 @@ describe('PersonalDetailsUtils', () => { }); }); - describe('createPersonalDetailsLookupByAccountID', () => { - it('should create a lookup map from an array of personal details', () => { - const details: PersonalDetails[] = [ - {accountID: 1, login: 'user1@example.com', displayName: 'User One'}, - {accountID: 2, login: 'user2@example.com', displayName: 'User Two'}, - {accountID: 3, login: 'user3@example.com', displayName: 'User Three'}, - ]; - - const result = createPersonalDetailsLookupByAccountID(details); - - expect(result[1]).toEqual({accountID: 1, login: 'user1@example.com', displayName: 'User One'}); - expect(result[2]).toEqual({accountID: 2, login: 'user2@example.com', displayName: 'User Two'}); - expect(result[3]).toEqual({accountID: 3, login: 'user3@example.com', displayName: 'User Three'}); - }); - - it('should return an empty object for an empty array', () => { - const result = createPersonalDetailsLookupByAccountID([]); - expect(result).toEqual({}); - }); - - it('should allow O(1) lookup by accountID', () => { - const details: PersonalDetails[] = [{accountID: 100, login: 'test@example.com', displayName: 'Test User'}]; - - const map = createPersonalDetailsLookupByAccountID(details); - - // Direct access should work - expect(map[100]).toBeDefined(); - expect(map[100].displayName).toBe('Test User'); - - // Non-existent key should be undefined - expect(map[999]).toBeUndefined(); - }); - - it('should handle duplicate accountIDs by keeping the last occurrence', () => { - const details: PersonalDetails[] = [ - {accountID: 1, login: 'first@example.com', displayName: 'First'}, - {accountID: 1, login: 'second@example.com', displayName: 'Second'}, - ]; - - const result = createPersonalDetailsLookupByAccountID(details); - - // The second entry should overwrite the first - expect(result[1]).toEqual({accountID: 1, login: 'second@example.com', displayName: 'Second'}); - }); - }); - describe('temporaryGetDisplayNameOrDefault', () => { const translate = translateLocal; diff --git a/tests/unit/pages/inbox/conciergeDraftState.test.ts b/tests/unit/pages/inbox/conciergeDraftState.test.ts index 8c9f383cb1da..dd0856215ec7 100644 --- a/tests/unit/pages/inbox/conciergeDraftState.test.ts +++ b/tests/unit/pages/inbox/conciergeDraftState.test.ts @@ -1,11 +1,4 @@ -import { - applyConciergeDraftEvent, - getCachedDraft, - getNextVisibleConciergeDraftBodyMarkdown, - getNextVisibleConciergeDraftMarkdown, - setCachedDraft, - stripIncompleteMarkdown, -} from '@pages/inbox/conciergeDraftState'; +import {applyConciergeDraftEvent, getCachedDraft, setCachedDraft, stripIncompleteMarkdown} from '@pages/inbox/conciergeDraftState'; import CONST from '@src/CONST'; @@ -154,105 +147,6 @@ describe('conciergeDraftState', () => { expect(otherReportDraft).toBe(initialDraft); }); - describe('getNextVisibleConciergeDraftBodyMarkdown', () => { - it('handles normal reveal, code points, and corrections', () => { - // Given representative pacing inputs - const longTarget = 'a'.repeat(200); - - // When calculating the next visible body - const firstSlice = getNextVisibleConciergeDraftBodyMarkdown('', 'Hello'); - const secondSlice = getNextVisibleConciergeDraftBodyMarkdown('H', 'Hello'); - const emojiSlice = getNextVisibleConciergeDraftBodyMarkdown('Hi ', 'Hi 😃 there'); - const longBacklogSlice = getNextVisibleConciergeDraftBodyMarkdown('', longTarget); - const correctedSlice = getNextVisibleConciergeDraftBodyMarkdown('Old draft', 'New draft'); - - // Then each pacing path preserves its expected reveal behavior - expect(firstSlice).toBe('H'); - expect(secondSlice).toBe('He'); - expect(emojiSlice).toBe('Hi 😃'); - expect(longBacklogSlice).toBe('a'); - expect(correctedSlice).toBe('New draft'); - }); - }); - - describe('getNextVisibleConciergeDraftMarkdown', () => { - it('streams complete bold markup by visible characters while keeping the style active', () => { - const firstBoldSlice = getNextVisibleConciergeDraftMarkdown('Hello ', 'Hello **world**!', 'Hello '.length, 'Hello '); - const secondBoldSlice = getNextVisibleConciergeDraftMarkdown(firstBoldSlice.bodyMarkdown, 'Hello **world**!', firstBoldSlice.sourceOffset, firstBoldSlice.sourceMarkdown); - - expect(firstBoldSlice.bodyMarkdown).toBe('Hello **w**'); - expect(firstBoldSlice.sourceMarkdown).toBe('Hello **w'); - expect(secondBoldSlice.bodyMarkdown).toBe('Hello **wo**'); - expect(secondBoldSlice.sourceMarkdown).toBe('Hello **wo'); - }); - - it('keeps temporary bold markup valid when the visible content ends in whitespace', () => { - const spaceSlice = getNextVisibleConciergeDraftMarkdown('Hello **QuickBooks**', 'Hello **QuickBooks Online**', 'Hello **QuickBooks'.length, 'Hello **QuickBooks'); - const draft = applyConciergeDraftEvent(null, createDraftEvent({bodyMarkdown: spaceSlice.bodyMarkdown}), REPORT_ID, false); - - expect(spaceSlice.bodyMarkdown).toBe('Hello **QuickBooks** '); - expect(spaceSlice.sourceMarkdown).toBe('Hello **QuickBooks '); - expect(stripIncompleteMarkdown(spaceSlice.bodyMarkdown)).toBe('Hello *QuickBooks* '); - expect(getFirstMessageHTML(draft)).toContain('QuickBooks'); - expect(getFirstMessageHTML(draft)).not.toContain('*QuickBooks'); - }); - - it('streams complete strikethrough and inline code markup by visible characters', () => { - const strikeSlice = getNextVisibleConciergeDraftMarkdown('Remove ', 'Remove ~~this~~', 'Remove '.length, 'Remove '); - const codeSlice = getNextVisibleConciergeDraftMarkdown('Run ', 'Run `npm test`', 'Run '.length, 'Run '); - - expect(strikeSlice.bodyMarkdown).toBe('Remove ~~t~~'); - expect(codeSlice.bodyMarkdown).toBe('Run `n`'); - }); - - it('streams complete italic markup by visible characters while keeping the style active', () => { - const italicSlice = getNextVisibleConciergeDraftMarkdown('Hello ', 'Hello *world*!', 'Hello '.length, 'Hello '); - - expect(italicSlice.bodyMarkdown).toBe('Hello *w*'); - expect(italicSlice.sourceMarkdown).toBe('Hello *w'); - expect(stripIncompleteMarkdown(italicSlice.bodyMarkdown)).toBe('Hello _w_'); - }); - - it('keeps temporary italic markup valid when the visible content ends in whitespace', () => { - const spaceSlice = getNextVisibleConciergeDraftMarkdown('Hello *QuickBooks*', 'Hello *QuickBooks Online*', 'Hello *QuickBooks'.length, 'Hello *QuickBooks'); - - expect(spaceSlice.bodyMarkdown).toBe('Hello *QuickBooks* '); - expect(spaceSlice.sourceMarkdown).toBe('Hello *QuickBooks '); - expect(stripIncompleteMarkdown(spaceSlice.bodyMarkdown)).toBe('Hello _QuickBooks_ '); - }); - - it('streams complete links by linked text without exposing the destination URL as plain text', () => { - const linkSlice = getNextVisibleConciergeDraftMarkdown('See ', 'See [docs](https://example.com)', 'See '.length, 'See '); - - expect(linkSlice.bodyMarkdown).toBe('See [d](https://example.com)'); - expect(linkSlice.sourceMarkdown).toBe('See [d'); - }); - - it('does not consume hidden source text while markdown is still incomplete', () => { - const boldSlice = getNextVisibleConciergeDraftMarkdown('Hello ', 'Hello **world', 'Hello '.length, 'Hello '); - const italicSlice = getNextVisibleConciergeDraftMarkdown('Hello ', 'Hello *world', 'Hello '.length, 'Hello '); - const linkSlice = getNextVisibleConciergeDraftMarkdown('See ', 'See [docs](https://example', 'See '.length, 'See '); - - expect(boldSlice.bodyMarkdown).toBe('Hello '); - expect(boldSlice.sourceMarkdown).toBe('Hello '); - expect(boldSlice.sourceOffset).toBe('Hello '.length); - expect(italicSlice.bodyMarkdown).toBe('Hello '); - expect(italicSlice.sourceMarkdown).toBe('Hello '); - expect(italicSlice.sourceOffset).toBe('Hello '.length); - expect(linkSlice.bodyMarkdown).toBe('See '); - expect(linkSlice.sourceMarkdown).toBe('See '); - expect(linkSlice.sourceOffset).toBe('See '.length); - }); - - it('uses source markdown to keep moving smoothly when a previously incomplete span becomes complete', () => { - const targetWithCompletedBold = 'Hello **world**'; - const nextSlice = getNextVisibleConciergeDraftMarkdown('Hello ', targetWithCompletedBold, 'Hello '.length, 'Hello '); - - expect(nextSlice.bodyMarkdown).toBe('Hello **w**'); - expect(nextSlice.sourceMarkdown).toBe('Hello **w'); - }); - }); - describe('stripIncompleteMarkdown', () => { it('returns empty/falsy values unchanged', () => { expect(stripIncompleteMarkdown('')).toBe(''); diff --git a/tests/unit/selectors/PolicyTest.ts b/tests/unit/selectors/PolicyTest.ts index 0d8029563367..d2dccb2a2e8b 100644 --- a/tests/unit/selectors/PolicyTest.ts +++ b/tests/unit/selectors/PolicyTest.ts @@ -7,9 +7,7 @@ import { activeAdminPoliciesSelector, adminPoliciesConnectedToQBDSelector, createOwnedPaidPoliciesCountsSelector, - hasMultipleOutputCurrenciesSelector, hasOnlyPersonalPoliciesSelector, - hasPoliciesConnectedToQBDSelector, hasReusablePoliciesConnectedToSelector, reusablePoliciesConnectedToSelector, } from '@selectors/Policy'; @@ -67,49 +65,6 @@ describe('createOwnedPaidPoliciesCountsSelector', () => { }); }); -describe('hasMultipleOutputCurrenciesSelector', () => { - it('returns false when paid group policies have the same output currency', () => { - const policies: OnyxCollection = { - policy1: {...createRandomPolicy(1, CONST.POLICY.TYPE.TEAM), outputCurrency: 'USD'}, - policy2: {...createRandomPolicy(2, CONST.POLICY.TYPE.CORPORATE), outputCurrency: 'USD'}, - }; - - expect(hasMultipleOutputCurrenciesSelector(policies)).toBe(false); - }); - - it('returns true when paid group policies have different output currencies', () => { - const policies: OnyxCollection = { - policy1: {...createRandomPolicy(1, CONST.POLICY.TYPE.TEAM), outputCurrency: 'USD'}, - policy2: {...createRandomPolicy(2, CONST.POLICY.TYPE.CORPORATE), outputCurrency: 'EUR'}, - }; - - expect(hasMultipleOutputCurrenciesSelector(policies)).toBe(true); - }); - - it('returns false when policies object is empty', () => { - const policies: OnyxCollection = {}; - - expect(hasMultipleOutputCurrenciesSelector(policies)).toBe(false); - }); - - it('returns false when there are only personal policies', () => { - const policies: OnyxCollection = { - policy1: {...createRandomPolicy(1, CONST.POLICY.TYPE.PERSONAL), outputCurrency: 'USD'}, - policy2: {...createRandomPolicy(2, CONST.POLICY.TYPE.PERSONAL), outputCurrency: 'EUR'}, - }; - - expect(hasMultipleOutputCurrenciesSelector(policies)).toBe(false); - }); - - it('returns false when there is only a single paid group policy', () => { - const policies: OnyxCollection = { - policy1: {...createRandomPolicy(1, CONST.POLICY.TYPE.TEAM), outputCurrency: 'USD'}, - }; - - expect(hasMultipleOutputCurrenciesSelector(policies)).toBe(false); - }); -}); - const TEST_LOGIN = 'admin@expensify.com'; function buildSelectorPolicy(id: number, overrides: Partial): Policy { @@ -227,28 +182,6 @@ describe('adminPoliciesConnectedToQBDSelector', () => { }); }); -describe('hasPoliciesConnectedToQBDSelector', () => { - it('returns true when admin policies with QBD connections exist', () => { - const policies: OnyxCollection = { - policy1: buildSelectorPolicy(1, {role: CONST.POLICY.ROLE.ADMIN, connections: {quickbooksDesktop: {}} as Policy['connections']}), - }; - - expect(hasPoliciesConnectedToQBDSelector(policies)).toBe(true); - }); - - it('returns false when no QBD connections exist', () => { - const policies: OnyxCollection = { - policy1: buildSelectorPolicy(1, {role: CONST.POLICY.ROLE.ADMIN}), - }; - - expect(hasPoliciesConnectedToQBDSelector(policies)).toBe(false); - }); - - it('returns false for empty collection', () => { - expect(hasPoliciesConnectedToQBDSelector({})).toBe(false); - }); -}); - describe('reusablePoliciesConnectedToSelector for QBD', () => { it('includes healthy QBD admin workspaces from other policies', () => { const currentPolicyID = '1'; From 5b98be35ea44d1aaec25daf23df4040efef72c60 Mon Sep 17 00:00:00 2001 From: Shubham Agrawal Date: Mon, 6 Jul 2026 23:52:10 +0530 Subject: [PATCH 2/4] Knip fix --- src/libs/CardFeedUtils.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/libs/CardFeedUtils.ts b/src/libs/CardFeedUtils.ts index e8ed01c42050..2dad89cdce8f 100644 --- a/src/libs/CardFeedUtils.ts +++ b/src/libs/CardFeedUtils.ts @@ -38,7 +38,6 @@ import { import {isPolicyAdmin} from './PolicyUtils'; type CardFilterItem = Partial & AdditionalCardProps & {isCardFeed?: boolean; correspondingCards?: string[]; cardFeedKey: string; plaidUrl?: string; keyForList: string}; -type DomainFeedData = {bank: CardFeedWithNumber; domainName: string; correspondingCardIDs: string[]; fundID?: string; feedCountry?: string}; type CardFeedForDisplay = { id: string; feed: CardFeedWithNumber; @@ -472,7 +471,6 @@ function getCombinedCardFeedsFromAllFeeds( } export type {CardFilterItem, CardFeedForDisplay}; -export type {DomainFeedData}; export { buildCardsData, getFeedInfo, From d5ca89092ba52c5d33e7599037ea7cb3b15191e5 Mon Sep 17 00:00:00 2001 From: Shubham Agrawal Date: Tue, 7 Jul 2026 19:41:24 +0530 Subject: [PATCH 3/4] Re-add tests for getNextVisibleConciergeDraftMarkdown --- .../pages/inbox/conciergeDraftState.test.ts | 80 ++++++++++++++++++- 1 file changed, 79 insertions(+), 1 deletion(-) diff --git a/tests/unit/pages/inbox/conciergeDraftState.test.ts b/tests/unit/pages/inbox/conciergeDraftState.test.ts index dd0856215ec7..c53db50f80e5 100644 --- a/tests/unit/pages/inbox/conciergeDraftState.test.ts +++ b/tests/unit/pages/inbox/conciergeDraftState.test.ts @@ -1,4 +1,4 @@ -import {applyConciergeDraftEvent, getCachedDraft, setCachedDraft, stripIncompleteMarkdown} from '@pages/inbox/conciergeDraftState'; +import {applyConciergeDraftEvent, getCachedDraft, getNextVisibleConciergeDraftMarkdown, setCachedDraft, stripIncompleteMarkdown} from '@pages/inbox/conciergeDraftState'; import CONST from '@src/CONST'; @@ -147,6 +147,84 @@ describe('conciergeDraftState', () => { expect(otherReportDraft).toBe(initialDraft); }); + describe('getNextVisibleConciergeDraftMarkdown', () => { + it('streams complete bold markup by visible characters while keeping the style active', () => { + const firstBoldSlice = getNextVisibleConciergeDraftMarkdown('Hello ', 'Hello **world**!', 'Hello '.length, 'Hello '); + const secondBoldSlice = getNextVisibleConciergeDraftMarkdown(firstBoldSlice.bodyMarkdown, 'Hello **world**!', firstBoldSlice.sourceOffset, firstBoldSlice.sourceMarkdown); + + expect(firstBoldSlice.bodyMarkdown).toBe('Hello **w**'); + expect(firstBoldSlice.sourceMarkdown).toBe('Hello **w'); + expect(secondBoldSlice.bodyMarkdown).toBe('Hello **wo**'); + expect(secondBoldSlice.sourceMarkdown).toBe('Hello **wo'); + }); + + it('keeps temporary bold markup valid when the visible content ends in whitespace', () => { + const spaceSlice = getNextVisibleConciergeDraftMarkdown('Hello **QuickBooks**', 'Hello **QuickBooks Online**', 'Hello **QuickBooks'.length, 'Hello **QuickBooks'); + const draft = applyConciergeDraftEvent(null, createDraftEvent({bodyMarkdown: spaceSlice.bodyMarkdown}), REPORT_ID, false); + + expect(spaceSlice.bodyMarkdown).toBe('Hello **QuickBooks** '); + expect(spaceSlice.sourceMarkdown).toBe('Hello **QuickBooks '); + expect(stripIncompleteMarkdown(spaceSlice.bodyMarkdown)).toBe('Hello *QuickBooks* '); + expect(getFirstMessageHTML(draft)).toContain('QuickBooks'); + expect(getFirstMessageHTML(draft)).not.toContain('*QuickBooks'); + }); + + it('streams complete strikethrough and inline code markup by visible characters', () => { + const strikeSlice = getNextVisibleConciergeDraftMarkdown('Remove ', 'Remove ~~this~~', 'Remove '.length, 'Remove '); + const codeSlice = getNextVisibleConciergeDraftMarkdown('Run ', 'Run `npm test`', 'Run '.length, 'Run '); + + expect(strikeSlice.bodyMarkdown).toBe('Remove ~~t~~'); + expect(codeSlice.bodyMarkdown).toBe('Run `n`'); + }); + + it('streams complete italic markup by visible characters while keeping the style active', () => { + const italicSlice = getNextVisibleConciergeDraftMarkdown('Hello ', 'Hello *world*!', 'Hello '.length, 'Hello '); + + expect(italicSlice.bodyMarkdown).toBe('Hello *w*'); + expect(italicSlice.sourceMarkdown).toBe('Hello *w'); + expect(stripIncompleteMarkdown(italicSlice.bodyMarkdown)).toBe('Hello _w_'); + }); + + it('keeps temporary italic markup valid when the visible content ends in whitespace', () => { + const spaceSlice = getNextVisibleConciergeDraftMarkdown('Hello *QuickBooks*', 'Hello *QuickBooks Online*', 'Hello *QuickBooks'.length, 'Hello *QuickBooks'); + + expect(spaceSlice.bodyMarkdown).toBe('Hello *QuickBooks* '); + expect(spaceSlice.sourceMarkdown).toBe('Hello *QuickBooks '); + expect(stripIncompleteMarkdown(spaceSlice.bodyMarkdown)).toBe('Hello _QuickBooks_ '); + }); + + it('streams complete links by linked text without exposing the destination URL as plain text', () => { + const linkSlice = getNextVisibleConciergeDraftMarkdown('See ', 'See [docs](https://example.com)', 'See '.length, 'See '); + + expect(linkSlice.bodyMarkdown).toBe('See [d](https://example.com)'); + expect(linkSlice.sourceMarkdown).toBe('See [d'); + }); + + it('does not consume hidden source text while markdown is still incomplete', () => { + const boldSlice = getNextVisibleConciergeDraftMarkdown('Hello ', 'Hello **world', 'Hello '.length, 'Hello '); + const italicSlice = getNextVisibleConciergeDraftMarkdown('Hello ', 'Hello *world', 'Hello '.length, 'Hello '); + const linkSlice = getNextVisibleConciergeDraftMarkdown('See ', 'See [docs](https://example', 'See '.length, 'See '); + + expect(boldSlice.bodyMarkdown).toBe('Hello '); + expect(boldSlice.sourceMarkdown).toBe('Hello '); + expect(boldSlice.sourceOffset).toBe('Hello '.length); + expect(italicSlice.bodyMarkdown).toBe('Hello '); + expect(italicSlice.sourceMarkdown).toBe('Hello '); + expect(italicSlice.sourceOffset).toBe('Hello '.length); + expect(linkSlice.bodyMarkdown).toBe('See '); + expect(linkSlice.sourceMarkdown).toBe('See '); + expect(linkSlice.sourceOffset).toBe('See '.length); + }); + + it('uses source markdown to keep moving smoothly when a previously incomplete span becomes complete', () => { + const targetWithCompletedBold = 'Hello **world**'; + const nextSlice = getNextVisibleConciergeDraftMarkdown('Hello ', targetWithCompletedBold, 'Hello '.length, 'Hello '); + + expect(nextSlice.bodyMarkdown).toBe('Hello **w**'); + expect(nextSlice.sourceMarkdown).toBe('Hello **w'); + }); + }); + describe('stripIncompleteMarkdown', () => { it('returns empty/falsy values unchanged', () => { expect(stripIncompleteMarkdown('')).toBe(''); From e6ed3a3ea27f976de93dfd367b549404191c2597 Mon Sep 17 00:00:00 2001 From: Shubham Agrawal Date: Tue, 7 Jul 2026 20:54:41 +0530 Subject: [PATCH 4/4] Fix ts --- src/libs/actions/IOU/ReportWorkflow.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/libs/actions/IOU/ReportWorkflow.ts b/src/libs/actions/IOU/ReportWorkflow.ts index 6dcd235a597b..ad4e7be50759 100644 --- a/src/libs/actions/IOU/ReportWorkflow.ts +++ b/src/libs/actions/IOU/ReportWorkflow.ts @@ -20,6 +20,7 @@ import { getSubmitReportManagerAccountID, hasDynamicExternalWorkflow, isPaidGroupPolicy, + isPolicyAdmin, isSubmitAndClose, isSubmitPolicy, isSubmitterApproveBlockedOnSubmitWorkspace,