diff --git a/src/hooks/useSearchSelector/base.ts b/src/hooks/useSearchSelector/base.ts index ee12a1222caa..82440cbfce93 100644 --- a/src/hooks/useSearchSelector/base.ts +++ b/src/hooks/useSearchSelector/base.ts @@ -11,6 +11,7 @@ import useSortedActions from '@hooks/useSortedActions'; import type {GetOptionsConfig, Option, OptionList, Options, SearchOption} from '@libs/OptionsListUtils'; import {getEmptyOptions, getSearchOptions, getSearchValueForPhoneOrEmail, getValidOptions} from '@libs/OptionsListUtils'; import {getPersonalDetailSearchTerms} from '@libs/OptionsListUtils/searchMatchUtils'; +import {addSMSDomainIfPhoneNumber} from '@libs/PhoneNumber'; import type {OptionData} from '@libs/ReportUtils'; import {expensifyLoginsSelector} from '@libs/UserUtils'; @@ -228,10 +229,39 @@ function useSearchSelectorBase({ if (!contactOptions?.length || !areOptionsInitialized) { return defaultOptions; } - const personalDetailsWithContacts = defaultOptions.personalDetails.concat(contactOptions); + + // Imported contacts get a generated accountID, so one sharing a login with a real Onyx user would show a duplicate + // row and be treated as a new invite. Track already-represented logins and drop contacts whose login is present. + const existingLogins = new Set(); + + // Seed with real personal details only; optimistic ones are filtered out by getValidOptions and mustn't suppress a contact. + for (const option of defaultOptions.personalDetails) { + if (option.isOptimisticPersonalDetail) { + continue; + } + const login = addSMSDomainIfPhoneNumber(option.login ?? '').toLowerCase(); + if (login) { + existingLogins.add(login); + } + } + + // Keep a contact only if its login is new, deduping against both the seeded accounts and earlier contacts. + const dedupedContactOptions = contactOptions.filter((contact) => { + const login = addSMSDomainIfPhoneNumber(contact.login ?? '').toLowerCase(); + if (!login || existingLogins.has(login)) { + return false; + } + existingLogins.add(login); + return true; + }); + + if (!dedupedContactOptions.length) { + return defaultOptions; + } + return { ...defaultOptions, - personalDetails: personalDetailsWithContacts, + personalDetails: defaultOptions.personalDetails.concat(dedupedContactOptions), }; })(); diff --git a/src/pages/NewChatPage/index.tsx b/src/pages/NewChatPage/index.tsx index 7f27ef9092fe..d7d76b4e4efc 100755 --- a/src/pages/NewChatPage/index.tsx +++ b/src/pages/NewChatPage/index.tsx @@ -8,26 +8,21 @@ import SelectionListWithSections from '@components/SelectionList/SelectionListWi import type {Section} from '@components/SelectionList/SelectionListWithSections/types'; import type {ListItem, SelectionListWithSectionsHandle} from '@components/SelectionList/types'; -import useContactImport from '@hooks/useContactImport'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; -import useDebouncedState from '@hooks/useDebouncedState'; import useDismissedReferralBanners from '@hooks/useDismissedReferralBanners'; -import useFilteredOptions from '@hooks/useFilteredOptions'; -import useIsFocusedRef from '@hooks/useIsFocusedRef'; import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; -import usePaginatedData from '@hooks/usePaginatedData'; import useSafeAreaInsets from '@hooks/useSafeAreaInsets'; +import useSearchSelector from '@hooks/useSearchSelector'; import useSingleExecution from '@hooks/useSingleExecution'; -import useSortedActions from '@hooks/useSortedActions'; import useThemeStyles from '@hooks/useThemeStyles'; import {navigateToAndOpenReport, searchInServer, setGroupDraft} from '@libs/actions/Report'; import {canUseTouchScreen} from '@libs/DeviceCapabilities'; import Log from '@libs/Log'; import Navigation from '@libs/Navigation/Navigation'; -import {filterAndOrderOptions, getHeaderMessage, getValidOptions} from '@libs/OptionsListUtils'; +import {getHeaderMessage} from '@libs/OptionsListUtils'; import {doesPersonalDetailMatchSearchTerm} from '@libs/OptionsListUtils/searchMatchUtils'; import type {OptionWithKey} from '@libs/OptionsListUtils/types'; import type {OptionData} from '@libs/ReportUtils'; @@ -38,7 +33,6 @@ import variables from '@styles/variables'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; -import type {ReportAttributesDerivedValue} from '@src/types/onyx/DerivedValues'; import type {SelectedParticipant} from '@src/types/onyx/NewGroupChatDraft'; import getEmptyArray from '@src/types/utils/getEmptyArray'; import KeyboardUtils from '@src/utils/keyboard'; @@ -47,131 +41,92 @@ import type {Ref} from 'react'; import {useFocusEffect} from '@react-navigation/native'; import {guidedSetupAndTourStatusSelector} from '@selectors/Onboarding'; -import passthroughPolicyTagListSelector from '@selectors/PolicyTagList'; -import reject from 'lodash/reject'; import React, {useEffect, useImperativeHandle, useRef, useState} from 'react'; import {Keyboard} from 'react-native'; -import type SelectedOption from './types'; - -import mergeAndSortPersonalDetailsWithContacts from './mergeAndSortPersonalDetailsWithContacts'; import useGroupChatDraftParticipantSync from './useGroupChatDraftParticipantSync'; const excludedGroupEmails = new Set(CONST.EXPENSIFY_EMAILS.filter((value) => value !== CONST.EMAIL.CONCIERGE)); -const PAGINATION_SIZE = CONST.MAX_SELECTION_LIST_PAGE_LENGTH; -function useOptions(reportAttributesDerived: ReportAttributesDerivedValue['reports'] | undefined) { +type NewChatPageRef = { + focus?: () => void; +}; + +type NewChatPageProps = { + /** Reference to the outer element */ + ref?: Ref; +}; + +function NewChatPage({ref}: NewChatPageProps) { const {translate} = useLocalize(); - const [searchTerm, debouncedSearchTerm, setSearchTerm] = useDebouncedState(''); - const [selectedOptions, setSelectedOptions] = useState([]); - const [betas] = useOnyx(ONYXKEYS.BETAS); - const [countryCode = CONST.DEFAULT_COUNTRY_CODE] = useOnyx(ONYXKEYS.COUNTRY_CODE); - const [loginList] = useOnyx(ONYXKEYS.LOGINS, {selector: expensifyLoginsSelector}); + const {isOffline} = useNetwork(); + const styles = useThemeStyles(); const personalData = useCurrentUserPersonalDetails(); const currentUserAccountID = personalData.accountID; const currentUserEmail = personalData.email ?? ''; - const focusTimeoutRef = useRef(null); - const [didScreenTransitionEnd, setDidScreenTransitionEnd] = useState(false); - const {contacts} = useContactImport(); - const [draftComments] = useOnyx(ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT); + const {top} = useSafeAreaInsets(); + const [countryCode = CONST.DEFAULT_COUNTRY_CODE] = useOnyx(ONYXKEYS.COUNTRY_CODE); + const [isSearchingForReports] = useOnyx(ONYXKEYS.RAM_ONLY_IS_SEARCHING_FOR_REPORTS); + const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); + const [betas] = useOnyx(ONYXKEYS.BETAS); + const [guidedSetupAndTourStatus] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: guidedSetupAndTourStatusSelector}); + const [loginList] = useOnyx(ONYXKEYS.LOGINS, {selector: expensifyLoginsSelector}); + const selectionListRef = useRef(null); const allPersonalDetails = usePersonalDetails(); - const isScreenFocusedRef = useIsFocusedRef(); - const sortedActions = useSortedActions(); - const [allPolicyTags] = useOnyx(ONYXKEYS.COLLECTION.POLICY_TAGS, {selector: passthroughPolicyTagListSelector}); - const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); - - const isSearching = !!debouncedSearchTerm.trim(); - - const { - options: listOptions, - isLoading, - loadMore: loadMoreReports, - hasMore: hasMoreFilteredOptions, - } = useFilteredOptions({ - maxRecentReports: 500, - enabled: didScreenTransitionEnd, - includeP2P: true, - batchSize: 100, - enablePagination: true, - isSearching, - }); - - const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY); - - const reports = listOptions?.reports ?? []; + const {singleExecution} = useSingleExecution(); - const allPersonalDetailOptions = listOptions?.personalDetails ?? []; + const focusTimeoutRef = useRef(null); + const [didScreenTransitionEnd, setDidScreenTransitionEnd] = useState(false); - // Dedupe and sort the union of Onyx personal details and imported contacts so pagination uses an alphabetical prefix. - const sortedPersonalDetailOptionsWithContacts = mergeAndSortPersonalDetailsWithContacts(allPersonalDetailOptions, contacts); + useImperativeHandle(ref, () => ({ + focus: selectionListRef.current?.focusTextInput, + })); - // usePaginatedData resets to page 1 whenever resetKey changes. Encode browse and search as "false" and "true", respectively, - // so that we only reset when the user enters or leaves search, not on every debounced keystroke. - const browsePaginationResetKey = String(isSearching); + // Builds the draft participants (selection plus the current user as creator). Empty when the current user isn't loaded yet. + const buildDraftParticipants = (options: OptionData[]): SelectedParticipant[] => { + if (!personalData?.login || !personalData?.accountID) { + return []; + } + return [ + ...options.map((option) => ({ + login: option.login, + accountID: option.accountID ?? CONST.DEFAULT_NUMBER_ID, + })), + { + login: personalData.login, + accountID: personalData.accountID, + }, + ]; + }; - // Limits raw personal details entering getValidOptions to reduce processing cost on initial load. - // Bypassed during search to avoid repeatedly calling loadMore and prevent FlashList onEndReached infinite loop. - const { - paginatedData: personalDetails, - loadMore: loadMorePersonalDetails, - hasMore: hasMorePersonalDetails, - } = usePaginatedData(sortedPersonalDetailOptionsWithContacts, PAGINATION_SIZE, { - resetKey: browsePaginationResetKey, - skipPagination: isSearching, - }); + // Persist the selection to the group chat draft so an in-progress group survives navigation/reload. + const updateGroupDraft = (newSelectedOptions: OptionData[]) => { + const participants = buildDraftParticipants(newSelectedOptions); + if (!participants.length) { + return; + } + setGroupDraft({participants}); + }; - useGroupChatDraftParticipantSync(allPersonalDetailOptions, !isLoading, allPersonalDetails, loginList, currentUserEmail, currentUserAccountID, selectedOptions, setSelectedOptions); - - const {options: defaultOptions} = getValidOptions( - { - reports, - personalDetails, - }, - allPolicies, - draftComments, - loginList, - currentUserAccountID, - currentUserEmail, - conciergeReportID, - { - betas: betas ?? [], + const {searchTerm, debouncedSearchTerm, setSearchTerm, availableOptions, selectedOptions, setSelectedOptions, toggleSelection, areOptionsInitialized, onListEndReached} = + useSearchSelector({ + selectionMode: CONST.SEARCH_SELECTOR.SELECTION_MODE_MULTI, + searchContext: CONST.SEARCH_SELECTOR.SEARCH_CONTEXT_GENERAL, + includeUserToInvite: true, includeSelfDM: true, - shouldAlwaysIncludeDM: true, - personalDetails: allPersonalDetails, - allPolicyTags, - countryCode, - reportAttributesDerived, - sortedActions, - selectedOptions, - includeSelectedOptions: true, - }, - translate, - ); - - const areOptionsInitialized = !isLoading; - - // Keep selected options in the list (don't filter them out) so they stay in place when toggled, rather than jumping to a separate section at the top. - const options = filterAndOrderOptions(defaultOptions, debouncedSearchTerm, countryCode, loginList, currentUserEmail, currentUserAccountID, allPersonalDetails, { - selectedOptions, - maxRecentReportsToShow: CONST.IOU.MAX_RECENT_REPORTS_TO_SHOW, - }); - - const cleanSearchTerm = debouncedSearchTerm.trim().toLowerCase(); - - // Visual pagination — limits how many filtered personal details are passed to FlashList at once. - const { - paginatedData: paginatedFilteredPersonalDetails, - loadMore: loadMoreFilteredPersonalDetails, - hasMore: hasMoreFilteredPersonalDetails, - } = usePaginatedData(options.personalDetails, PAGINATION_SIZE, {resetKey: cleanSearchTerm, skipPagination: !isSearching}); + maxRecentReportsToShow: CONST.IOU.MAX_RECENT_REPORTS_TO_SHOW, + enablePhoneContacts: true, + // Keep selected options in place (marked with isSelected) so they stay put when toggled instead of jumping to a separate section. + shouldKeepSelectedInAvailableOptions: true, + shouldInitialize: didScreenTransitionEnd, + onSelectionChange: updateGroupDraft, + getValidOptionsConfig: { + includeP2P: true, + shouldAlwaysIncludeDM: true, + }, + }); - const headerMessage = getHeaderMessage( - options.personalDetails.length + options.recentReports.length !== 0, - !!options.userToInvite, - debouncedSearchTerm.trim(), - countryCode, - selectedOptions.some((participant) => doesPersonalDetailMatchSearchTerm(participant, currentUserAccountID, cleanSearchTerm)), - ); + useGroupChatDraftParticipantSync(areOptionsInitialized, allPersonalDetails, loginList, currentUserEmail, currentUserAccountID, translate, selectedOptions, setSelectedOptions); useFocusEffect(() => { focusTimeoutRef.current = setTimeout(() => { @@ -189,88 +144,18 @@ function useOptions(reportAttributesDerived: ReportAttributesDerivedValue['repor searchInServer(debouncedSearchTerm); }, [debouncedSearchTerm]); - const handleEndReached = () => { - const hasNoDataToLoad = !hasMoreFilteredPersonalDetails && !hasMorePersonalDetails && !hasMoreFilteredOptions; - if (hasNoDataToLoad || !areOptionsInitialized || !isScreenFocusedRef.current) { - return; - } - - if (hasMoreFilteredPersonalDetails) { - loadMoreFilteredPersonalDetails(); - } - - if (hasMorePersonalDetails) { - loadMorePersonalDetails(); - } - - if (options.recentReports.length < CONST.IOU.MAX_RECENT_REPORTS_TO_SHOW && hasMoreFilteredOptions) { - loadMoreReports(); - } - }; - - return { - ...options, - personalDetails: paginatedFilteredPersonalDetails, - searchTerm, - debouncedSearchTerm, - setSearchTerm, - areOptionsInitialized, - selectedOptions, - setSelectedOptions, - headerMessage, - handleEndReached, - }; -} - -type NewChatPageRef = { - focus?: () => void; -}; - -type NewChatPageProps = { - /** Reference to the outer element */ - ref?: Ref; -}; -function NewChatPage({ref}: NewChatPageProps) { - const {translate} = useLocalize(); - const {isOffline} = useNetwork(); - // We need to use isSmallScreenWidth instead of shouldUseNarrowLayout to show offline indicator on small screen only - - const styles = useThemeStyles(); - const personalData = useCurrentUserPersonalDetails(); - const currentUserAccountID = personalData.accountID; - const {top} = useSafeAreaInsets(); - const [isSearchingForReports] = useOnyx(ONYXKEYS.RAM_ONLY_IS_SEARCHING_FOR_REPORTS); - const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); - const [betas] = useOnyx(ONYXKEYS.BETAS); - const [guidedSetupAndTourStatus] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: guidedSetupAndTourStatusSelector}); - const selectionListRef = useRef(null); - const allPersonalDetails = usePersonalDetails(); - - const [reportAttributesDerivedFull] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES); + const {userToInvite, personalDetails, recentReports} = availableOptions; - const reportAttributesDerived = reportAttributesDerivedFull?.reports; - - const {singleExecution} = useSingleExecution(); - - useImperativeHandle(ref, () => ({ - focus: selectionListRef.current?.focusTextInput, - })); + const cleanSearchTerm = debouncedSearchTerm.trim().toLowerCase(); + const headerMessage = getHeaderMessage( + personalDetails.length + recentReports.length !== 0, + !!userToInvite, + debouncedSearchTerm.trim(), + countryCode, + selectedOptions.some((participant) => doesPersonalDetailMatchSearchTerm(participant, currentUserAccountID, cleanSearchTerm)), + ); - const { - headerMessage, - searchTerm, - debouncedSearchTerm, - handleEndReached, - setSearchTerm, - selectedOptions, - setSelectedOptions, - recentReports, - personalDetails, - userToInvite, - areOptionsInitialized, - } = useOptions(reportAttributesDerived); - - // Selected rows are marked in place by getValidOptions (isSelected), so the checkmark stays with the row instead of jumping to the top. + // Selected rows are marked in place by the hook (isSelected), so the checkmark stays with the row instead of jumping to the top. // In group selection mode the self DM stays visible (so the list doesn't shift and jump the scroll position) but is made non-selectable. const recentReportsData = selectedOptions.length ? recentReports.map((option) => (option.isSelfDM ? {...option, isDisabled: true} : option)) : recentReports; @@ -280,7 +165,6 @@ function NewChatPage({ref}: NewChatPageProps) { // so they don't need a separate row here. A selected non-existing user (an invited contact created from the search term) // has no row in recents/contacts and disappears once the search input is cleared, so surface only those in a top section // to keep them visible and easy to deselect. The one already shown as the current invite row is excluded to avoid a duplicate. - const cleanSearchTerm = debouncedSearchTerm.trim().toLowerCase(); const selectedSection = selectedOptions.filter( (option) => !!option.isOptimisticAccount && !(userToInvite && option.login === userToInvite.login) && doesPersonalDetailMatchSearchTerm(option, currentUserAccountID, cleanSearchTerm), @@ -318,35 +202,14 @@ function NewChatPage({ref}: NewChatPageProps) { * Removes a selected option from list if already selected. If not already selected add this option to the list. */ const toggleOption = (option: ListItem & Partial) => { - const isOptionInList = !!option.isSelected; - - let newSelectedOptions: SelectedOption[]; - - if (isOptionInList) { - newSelectedOptions = reject(selectedOptions, (selectedOption) => selectedOption.login === option.login); - } else { - newSelectedOptions = [...selectedOptions, {...option, isSelected: true, reportID: option.reportID, keyForList: `${option.keyForList ?? option.reportID}`}]; - } - selectionListRef.current?.clearInputAfterSelect(); if (!canUseTouchScreen()) { selectionListRef.current?.focusTextInput(); } - setSelectedOptions(newSelectedOptions); - - if (personalData?.login && personalData?.accountID) { - const participants: SelectedParticipant[] = [ - ...newSelectedOptions.map((selectedOption) => ({ - login: selectedOption.login, - accountID: selectedOption.accountID ?? CONST.DEFAULT_NUMBER_ID, - })), - { - login: personalData.login, - accountID: personalData.accountID, - }, - ]; - setGroupDraft({participants}); - } + + // The row item is a fully-built option coming from the search selector, so it is safe to treat it as an OptionData. + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + toggleSelection(option as OptionData); }; /** @@ -444,15 +307,11 @@ function NewChatPage({ref}: NewChatPageProps) { }; const createGroup = () => { - if (!personalData?.login || !personalData.accountID) { + const participants = buildDraftParticipants(selectedOptions); + if (!participants.length) { return; } - const selectedParticipants: SelectedParticipant[] = selectedOptions.map((option) => ({ - login: option?.login, - accountID: option.accountID ?? CONST.DEFAULT_NUMBER_ID, - })); - const logins = [...selectedParticipants, {login: personalData.login, accountID: personalData.accountID}]; - setGroupDraft({participants: logins}); + setGroupDraft({participants}); Keyboard.dismiss(); Navigation.navigate(ROUTES.NEW_CHAT_CONFIRM); }; @@ -519,7 +378,7 @@ function NewChatPage({ref}: NewChatPageProps) { shouldShowLoadingPlaceholder={!areOptionsInitialized} shouldPreventDefaultFocusOnSelectRow={!canUseTouchScreen()} isLoadingNewOptions={!!isSearchingForReports} - onEndReached={handleEndReached} + onEndReached={onListEndReached} onEndReachedThreshold={0.75} disableMaintainingScrollPosition addBottomSafeAreaPadding diff --git a/src/pages/NewChatPage/mergeAndSortPersonalDetailsWithContacts.ts b/src/pages/NewChatPage/mergeAndSortPersonalDetailsWithContacts.ts deleted file mode 100644 index d57042e2ac6f..000000000000 --- a/src/pages/NewChatPage/mergeAndSortPersonalDetailsWithContacts.ts +++ /dev/null @@ -1,21 +0,0 @@ -import {orderPersonalDetailsOptions} from '@libs/OptionsListUtils'; -import type {SearchOptionData} from '@libs/OptionsListUtils'; -import {addSMSDomainIfPhoneNumber} from '@libs/PhoneNumber'; - -import lodashUniqBy from 'lodash/uniqBy'; - -/** - * Merges Onyx personal details with imported contacts, removes entries without login, - * de-dupes by normalized login (case-insensitive, with SMS-domain normalization), - * and returns the union sorted alphabetically. - * - * Onyx options are placed first in the merge order, so when logins collide - * the Onyx entry is preserved over the imported contact entry. - */ -function mergeAndSortPersonalDetailsWithContacts(allPersonalDetailOptions: T[], contacts: T[]): T[] { - const merged = [...allPersonalDetailOptions, ...contacts].filter((option) => !!option.login); - const deduped = lodashUniqBy(merged, (option) => addSMSDomainIfPhoneNumber(option.login).toLowerCase()); - return orderPersonalDetailsOptions(deduped); -} - -export default mergeAndSortPersonalDetailsWithContacts; diff --git a/src/pages/NewChatPage/types.ts b/src/pages/NewChatPage/types.ts deleted file mode 100644 index 9ebcdda81a00..000000000000 --- a/src/pages/NewChatPage/types.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type {ListItem} from '@components/SelectionList/types'; - -import type {OptionData} from '@libs/ReportUtils'; - -type SelectedOption = ListItem & - Omit & { - reportID?: string; - }; - -export default SelectedOption; diff --git a/src/pages/NewChatPage/useGroupChatDraftParticipantSync.ts b/src/pages/NewChatPage/useGroupChatDraftParticipantSync.ts index ed5f06dc8c87..80728b3788e6 100644 --- a/src/pages/NewChatPage/useGroupChatDraftParticipantSync.ts +++ b/src/pages/NewChatPage/useGroupChatDraftParticipantSync.ts @@ -1,11 +1,13 @@ +import type {LocalizedTranslate} from '@components/LocaleContextProvider'; + import useIsFocusedRef from '@hooks/useIsFocusedRef'; import useOnyx from '@hooks/useOnyx'; -import {getUserToInviteOption} from '@libs/OptionsListUtils'; -import type {SearchOption} from '@libs/OptionsListUtils'; +import {getParticipantsOption, getUserToInviteOption} from '@libs/OptionsListUtils'; +import type {OptionData} from '@libs/ReportUtils'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Login, PersonalDetails, PersonalDetailsList} from '@src/types/onyx'; +import type {Login, PersonalDetailsList} from '@src/types/onyx'; import type NewGroupChatDraft from '@src/types/onyx/NewGroupChatDraft'; import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; @@ -13,8 +15,6 @@ import type {OnyxEntry} from 'react-native-onyx'; import {useEffect, useEffectEvent, useRef} from 'react'; -import type SelectedOption from './types'; - /** * Keeps the NewChatPage's `selectedOptions` state aligned with the `NEW_GROUP_CHAT_DRAFT` Onyx draft. * @@ -25,14 +25,14 @@ import type SelectedOption from './types'; * consistent when the user returns. */ function useGroupChatDraftParticipantSync( - allPersonalDetailOptions: Array>, - areAllPersonalDetailOptionsLoaded: boolean, + areOptionsInitialized: boolean, allPersonalDetails: OnyxEntry, loginList: OnyxEntry, currentUserEmail: string, currentUserAccountID: number, - selectedOptions: SelectedOption[], - setSelectedOptions: (options: SelectedOption[]) => void, + translate: LocalizedTranslate, + selectedOptions: OptionData[], + setSelectedOptions: (options: OptionData[]) => void, ) { const shouldRestoreSelectedOptionsRef = useRef(true); const isScreenFocusedRef = useIsFocusedRef(); @@ -50,18 +50,23 @@ function useGroupChatDraftParticipantSync( // Flip the ref first so the useOnyx selector disables the subscription shouldRestoreSelectedOptionsRef.current = false; - const restoredOptionsFromDraft = (draftParticipants ?? []).reduce((result, participant) => { + const restoredOptionsFromDraft = (draftParticipants ?? []).reduce((result, participant) => { if (participant.accountID === currentUserAccountID) { return result; } - const option = - allPersonalDetailOptions.find((personalDetail) => personalDetail.accountID === participant.accountID) ?? - getUserToInviteOption({ - searchValue: participant?.login, - personalDetails: allPersonalDetails, - loginList, - currentUserEmail, - }); + + // Existing users resolve to their real account; participants without personal details are invited-by-email/phone + // users restored via getUserToInviteOption so they keep the optimistic flag. + const detail = allPersonalDetails?.[participant.accountID]; + const option = detail + ? // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- participant-shaped option built from real personal details + (getParticipantsOption({accountID: participant.accountID, login: participant.login}, allPersonalDetails, translate) as OptionData) + : getUserToInviteOption({ + searchValue: participant?.login, + personalDetails: allPersonalDetails, + loginList, + currentUserEmail, + }); if (option) { result.push({...option, isSelected: true}); } @@ -94,7 +99,7 @@ function useGroupChatDraftParticipantSync( syncSelectedOptionsWithDraft(); }, [draftParticipants, isScreenFocusedRef]); - const areRestoreInputsReady = areAllPersonalDetailOptionsLoaded && !isLoadingOnyxValue(draftParticipantsMetadata); + const areRestoreInputsReady = areOptionsInitialized && !isLoadingOnyxValue(draftParticipantsMetadata); // Handle reload with existing draft participants useEffect(() => { diff --git a/tests/unit/NewChatPage/mergeAndSortPersonalDetailsWithContactsTest.ts b/tests/unit/NewChatPage/mergeAndSortPersonalDetailsWithContactsTest.ts deleted file mode 100644 index b26e7eac0eaa..000000000000 --- a/tests/unit/NewChatPage/mergeAndSortPersonalDetailsWithContactsTest.ts +++ /dev/null @@ -1,57 +0,0 @@ -import type {SearchOptionData} from '@libs/OptionsListUtils'; - -import mergeAndSortPersonalDetailsWithContacts from '@pages/NewChatPage/mergeAndSortPersonalDetailsWithContacts'; - -describe('mergeAndSortPersonalDetailsWithContacts', () => { - it('sorts the merged set alphabetically by the personalDetailsComparator key', () => { - const onyx: SearchOptionData[] = [ - {login: 'zara@x.com', accountID: 1, text: 'Zara', keyForList: '1', reportID: ''}, - {login: 'bob@x.com', accountID: 2, text: 'Bob', keyForList: '2', reportID: ''}, - ]; - const contacts: SearchOptionData[] = [{login: 'aaron@x.com', accountID: 999, text: 'Aaron', keyForList: '999', reportID: ''}]; - - const result = mergeAndSortPersonalDetailsWithContacts(onyx, contacts); - - expect(result.map((option) => option.text)).toEqual(['Aaron', 'Bob', 'Zara']); - }); - - it('dedupes by login case-insensitively', () => { - const onyx: SearchOptionData[] = [{login: 'john@x.com', accountID: 1, text: 'John Onyx', keyForList: '1', reportID: ''}]; - const contacts: SearchOptionData[] = [{login: 'JOHN@x.com', accountID: 999, text: 'John Contact', keyForList: '999', reportID: ''}]; - - const result = mergeAndSortPersonalDetailsWithContacts(onyx, contacts); - - expect(result).toHaveLength(1); - }); - - it('prefers the Onyx personal-detail copy over the contact copy on a login collision', () => { - const onyx: SearchOptionData[] = [{login: 'john@x.com', accountID: 12345, text: 'John Onyx', keyForList: '12345', reportID: ''}]; - const contacts: SearchOptionData[] = [{login: 'john@x.com', accountID: 99999, text: 'John Contact', keyForList: '99999', reportID: ''}]; - - const result = mergeAndSortPersonalDetailsWithContacts(onyx, contacts); - - expect(result.at(0)?.accountID).toBe(12345); - expect(result.at(0)?.text).toBe('John Onyx'); - }); - - it('dedupes phone-number logins regardless of SMS-domain suffix', () => { - const onyx: SearchOptionData[] = [{login: '+12025550100@expensify.sms', accountID: 1, text: 'Phone Onyx', keyForList: '1', reportID: ''}]; - const contacts: SearchOptionData[] = [{login: '+12025550100', accountID: 999, text: 'Phone Contact', keyForList: '999', reportID: ''}]; - - const result = mergeAndSortPersonalDetailsWithContacts(onyx, contacts); - - expect(result).toHaveLength(1); - expect(result.at(0)?.accountID).toBe(1); - }); - - it('drops entries with empty login', () => { - const onyx: SearchOptionData[] = [ - {login: '', accountID: 1, text: 'Anon', keyForList: '1', reportID: ''}, - {login: 'a@x.com', accountID: 2, text: 'Alice', keyForList: '2', reportID: ''}, - ]; - - const result = mergeAndSortPersonalDetailsWithContacts(onyx, []); - - expect(result.map((option) => option.login)).toEqual(['a@x.com']); - }); -}); diff --git a/tests/unit/useGroupChatDraftParticipantSyncTest.ts b/tests/unit/useGroupChatDraftParticipantSyncTest.ts index 0644802ae25b..6ccfa78b239f 100644 --- a/tests/unit/useGroupChatDraftParticipantSyncTest.ts +++ b/tests/unit/useGroupChatDraftParticipantSyncTest.ts @@ -3,17 +3,15 @@ import {act, renderHook} from '@testing-library/react-native'; import useOnyx from '@hooks/useOnyx'; import * as OptionsListUtilsModule from '@libs/OptionsListUtils'; -import type {SearchOption} from '@libs/OptionsListUtils'; import type {OptionData} from '@libs/ReportUtils'; -import type {PersonalDetails} from '@src/types/onyx'; +import type {PersonalDetails, PersonalDetailsList} from '@src/types/onyx'; import type {SelectedParticipant} from '@src/types/onyx/NewGroupChatDraft'; import type * as ReactNavigation from '@react-navigation/native'; -import type SelectedOption from '../../src/pages/NewChatPage/types'; - import useGroupChatDraftParticipantSync from '../../src/pages/NewChatPage/useGroupChatDraftParticipantSync'; +import {translateLocal as translate} from '../utils/TestHelper'; const mockUseOnyx: jest.Mock = jest.mocked(useOnyx); const mockGetUserToInviteOption = jest.mocked(OptionsListUtilsModule.getUserToInviteOption); @@ -51,15 +49,8 @@ jest.mock('@react-navigation/native', () => { const CURRENT_USER_ACCOUNT_ID = 1; const CURRENT_USER_EMAIL = 'current@test.com'; -function makePersonalDetailOption(accountID: number, login: string): SearchOption { - return { - accountID, - login, - text: login, - keyForList: String(accountID), - reportID: '', - item: {accountID, login, displayName: login}, - }; +function makePersonalDetail(accountID: number, login: string): PersonalDetails { + return {accountID, login, displayName: login}; } function makeSelectedOption(accountID: number, login: string): OptionData { @@ -78,12 +69,12 @@ const PARTICIPANT_B: SelectedParticipant = {accountID: 20, login: 'bob@test.com' const PARTICIPANT_C: SelectedParticipant = {accountID: 30, login: 'carol@test.com'}; const CURRENT_USER_PARTICIPANT: SelectedParticipant = {accountID: CURRENT_USER_ACCOUNT_ID, login: CURRENT_USER_EMAIL}; -const CURRENT_USER_OPTION = makePersonalDetailOption(CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL); -const OPTION_A = makePersonalDetailOption(10, 'alice@test.com'); -const OPTION_B = makePersonalDetailOption(20, 'bob@test.com'); -const OPTION_C = makePersonalDetailOption(30, 'carol@test.com'); - -const ALL_PERSONAL_DETAIL_OPTIONS = [CURRENT_USER_OPTION, OPTION_A, OPTION_B, OPTION_C]; +const ALL_PERSONAL_DETAILS: PersonalDetailsList = { + [CURRENT_USER_ACCOUNT_ID]: makePersonalDetail(CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL), + [PARTICIPANT_A.accountID]: makePersonalDetail(PARTICIPANT_A.accountID, 'alice@test.com'), + [PARTICIPANT_B.accountID]: makePersonalDetail(PARTICIPANT_B.accountID, 'bob@test.com'), + [PARTICIPANT_C.accountID]: makePersonalDetail(PARTICIPANT_C.accountID, 'carol@test.com'), +}; describe('useGroupDraftRestore', () => { beforeEach(() => { @@ -104,34 +95,19 @@ describe('useGroupDraftRestore', () => { } function renderRestoreHook(overrides?: { - allPersonalDetailOptions?: Array>; - areAllPersonalDetailOptionsLoaded?: boolean; + allPersonalDetails?: PersonalDetailsList; + areOptionsInitialized?: boolean; selectedOptions?: OptionData[]; draftParticipants?: SelectedParticipant[] | undefined; draftStatus?: 'loading' | 'loaded'; }) { - const setSelectedOptions = jest.fn(); - const { - allPersonalDetailOptions = ALL_PERSONAL_DETAIL_OPTIONS, - areAllPersonalDetailOptionsLoaded = true, - selectedOptions = [], - draftParticipants, - draftStatus = 'loaded', - } = overrides ?? {}; + const setSelectedOptions = jest.fn(); + const {allPersonalDetails = ALL_PERSONAL_DETAILS, areOptionsInitialized = true, selectedOptions = [], draftParticipants, draftStatus = 'loaded'} = overrides ?? {}; setupUseOnyx(draftParticipants, draftStatus); const {rerender} = renderHook(() => - useGroupChatDraftParticipantSync( - allPersonalDetailOptions, - areAllPersonalDetailOptionsLoaded, - {}, - {}, - CURRENT_USER_EMAIL, - CURRENT_USER_ACCOUNT_ID, - selectedOptions, - setSelectedOptions, - ), + useGroupChatDraftParticipantSync(areOptionsInitialized, allPersonalDetails, {}, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, translate, selectedOptions, setSelectedOptions), ); return {setSelectedOptions, rerender}; @@ -169,7 +145,7 @@ describe('useGroupDraftRestore', () => { const draftParticipants = [PARTICIPANT_A, PARTICIPANT_B]; const {setSelectedOptions} = renderRestoreHook({ draftParticipants, - areAllPersonalDetailOptionsLoaded: false, + areOptionsInitialized: false, }); expect(setSelectedOptions).not.toHaveBeenCalled(); @@ -179,9 +155,9 @@ describe('useGroupDraftRestore', () => { const draftParticipants = [PARTICIPANT_A]; setupUseOnyx(draftParticipants); - const setSelectedOptions = jest.fn(); + const setSelectedOptions = jest.fn(); const {rerender} = renderHook(() => - useGroupChatDraftParticipantSync(ALL_PERSONAL_DETAIL_OPTIONS, true, {}, {}, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, [], setSelectedOptions), + useGroupChatDraftParticipantSync(true, ALL_PERSONAL_DETAILS, {}, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, translate, [], setSelectedOptions), ); expect(setSelectedOptions).toHaveBeenCalledTimes(1); @@ -206,7 +182,7 @@ describe('useGroupDraftRestore', () => { describe('background sync', () => { it('should sync removals when draft changes while screen is in background', () => { const initialDraftParticipants = [CURRENT_USER_PARTICIPANT, PARTICIPANT_A, PARTICIPANT_B, PARTICIPANT_C]; - const setSelectedOptions = jest.fn(); + const setSelectedOptions = jest.fn(); const selectedAfterRestore = [makeSelectedOption(10, 'alice@test.com'), makeSelectedOption(20, 'bob@test.com'), makeSelectedOption(30, 'carol@test.com')]; setupUseOnyx(initialDraftParticipants); @@ -215,7 +191,7 @@ describe('useGroupDraftRestore', () => { const {rerender} = renderHook( ({draftParticipants}) => { setupUseOnyx(draftParticipants); - return useGroupChatDraftParticipantSync(ALL_PERSONAL_DETAIL_OPTIONS, true, {}, {}, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, selectedAfterRestore, setSelectedOptions); + return useGroupChatDraftParticipantSync(true, ALL_PERSONAL_DETAILS, {}, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, translate, selectedAfterRestore, setSelectedOptions); }, {initialProps: {draftParticipants: initialDraftParticipants}}, ); @@ -251,7 +227,7 @@ describe('useGroupDraftRestore', () => { it('should sync to empty when all participants are removed from draft', () => { const initialDraftParticipants = [CURRENT_USER_PARTICIPANT, PARTICIPANT_A, PARTICIPANT_B]; - const setSelectedOptions = jest.fn(); + const setSelectedOptions = jest.fn(); const selectedAfterRestore = [makeSelectedOption(10, 'alice@test.com'), makeSelectedOption(20, 'bob@test.com')]; setupUseOnyx(initialDraftParticipants); @@ -259,7 +235,7 @@ describe('useGroupDraftRestore', () => { const {rerender} = renderHook( ({draftParticipants}) => { setupUseOnyx(draftParticipants); - return useGroupChatDraftParticipantSync(ALL_PERSONAL_DETAIL_OPTIONS, true, {}, {}, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, selectedAfterRestore, setSelectedOptions); + return useGroupChatDraftParticipantSync(true, ALL_PERSONAL_DETAILS, {}, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, translate, selectedAfterRestore, setSelectedOptions); }, {initialProps: {draftParticipants: initialDraftParticipants}}, ); @@ -284,7 +260,7 @@ describe('useGroupDraftRestore', () => { it('should not sync when screen is focused (normal operation after restore)', () => { const draftParticipants = [CURRENT_USER_PARTICIPANT, PARTICIPANT_A, PARTICIPANT_B]; - const setSelectedOptions = jest.fn(); + const setSelectedOptions = jest.fn(); const selectedAfterRestore = [makeSelectedOption(10, 'alice@test.com'), makeSelectedOption(20, 'bob@test.com')]; setupUseOnyx(draftParticipants); @@ -292,7 +268,7 @@ describe('useGroupDraftRestore', () => { const {rerender} = renderHook( ({draft}) => { setupUseOnyx(draft); - return useGroupChatDraftParticipantSync(ALL_PERSONAL_DETAIL_OPTIONS, true, {}, {}, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, selectedAfterRestore, setSelectedOptions); + return useGroupChatDraftParticipantSync(true, ALL_PERSONAL_DETAILS, {}, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, translate, selectedAfterRestore, setSelectedOptions); }, {initialProps: {draft: draftParticipants}}, ); @@ -313,14 +289,14 @@ describe('useGroupDraftRestore', () => { describe('selector inactivity', () => { it('should not react to draft changes after restore (selector returns undefined)', () => { const draftParticipants = [CURRENT_USER_PARTICIPANT, PARTICIPANT_A]; - const setSelectedOptions = jest.fn(); + const setSelectedOptions = jest.fn(); setupUseOnyx(draftParticipants); const {rerender} = renderHook( ({draft}) => { setupUseOnyx(draft); - return useGroupChatDraftParticipantSync(ALL_PERSONAL_DETAIL_OPTIONS, true, {}, {}, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, [], setSelectedOptions); + return useGroupChatDraftParticipantSync(true, ALL_PERSONAL_DETAILS, {}, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, translate, [], setSelectedOptions); }, {initialProps: {draft: draftParticipants}}, ); @@ -363,12 +339,12 @@ describe('useGroupDraftRestore', () => { it('should restore after personal details load (delayed loading)', () => { const draftParticipants = [PARTICIPANT_A, PARTICIPANT_B]; - const setSelectedOptions = jest.fn(); + const setSelectedOptions = jest.fn(); setupUseOnyx(draftParticipants); const {rerender} = renderHook( - ({areLoaded}) => useGroupChatDraftParticipantSync(ALL_PERSONAL_DETAIL_OPTIONS, areLoaded, {}, {}, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, [], setSelectedOptions), + ({areLoaded}) => useGroupChatDraftParticipantSync(areLoaded, ALL_PERSONAL_DETAILS, {}, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, translate, [], setSelectedOptions), {initialProps: {areLoaded: false}}, ); @@ -388,8 +364,8 @@ describe('useGroupDraftRestore', () => { const {setSelectedOptions} = renderRestoreHook({ draftParticipants: [invited], - allPersonalDetailOptions: [], - areAllPersonalDetailOptionsLoaded: true, + allPersonalDetails: {}, + areOptionsInitialized: true, }); expect(setSelectedOptions).toHaveBeenCalledTimes(1); diff --git a/tests/unit/useSearchSelectorTest.tsx b/tests/unit/useSearchSelectorTest.tsx index bd9c5f35d816..f204de5a881c 100644 --- a/tests/unit/useSearchSelectorTest.tsx +++ b/tests/unit/useSearchSelectorTest.tsx @@ -2,12 +2,13 @@ import {act, renderHook} from '@testing-library/react-native'; import useSearchSelectorBase from '@hooks/useSearchSelector/base'; +import type {SearchOption} from '@libs/OptionsListUtils'; import {getSearchOptions, getValidOptions} from '@libs/OptionsListUtils'; import type {OptionData} from '@libs/ReportUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {ReportAction} from '@src/types/onyx'; +import type {PersonalDetails, ReportAction} from '@src/types/onyx'; import type {SortedReportActionsDerivedValue} from '@src/types/onyx/DerivedValues'; import type {OnyxMultiSetInput} from 'react-native-onyx'; @@ -35,10 +36,13 @@ const MOCK_EMAIL = 'test@expensify.com'; const mockGetValidOptions = jest.mocked(getValidOptions); const mockGetSearchOptions = jest.mocked(getSearchOptions); +// Holds the Onyx-sourced personal detail options returned by the mocked useFilteredOptions, so individual tests can control them. +const mockFilteredPersonalDetails: {current: OptionData[]} = {current: []}; + jest.mock('@hooks/useFilteredOptions', () => ({ __esModule: true, default: () => ({ - options: {reports: [], personalDetails: []}, + options: {reports: [], personalDetails: mockFilteredPersonalDetails.current}, isLoading: false, loadMore: jest.fn(), hasMore: false, @@ -539,3 +543,145 @@ describe('useSearchSelector selection and non-existing options', () => { expect(personalDetailLogins).toContain('alice@expensify.com'); }); }); + +// Imported device contacts are always given a generated (optimistic) accountID, even when that person already exists in Onyx. +function makeDeviceContact(login: string, accountID: number, text = login): SearchOption { + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- test fixture only needs a minimal contact option shape + return {login, accountID, text, keyForList: login} as SearchOption; +} + +describe('useSearchSelector phone contact de-duplication', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(async () => { + jest.clearAllMocks(); + mockFilteredPersonalDetails.current = []; + + // getValidOptions is mocked, so the contact de-duplication under test only depends on the inputs passed to the hook. + mockGetValidOptions.mockReturnValue({options: EMPTY_OPTIONS, hasMore: false}); + await act(async () => { + await Onyx.clear(); + }); + await waitForBatchedUpdatesWithAct(); + }); + + afterAll(async () => { + await act(async () => { + await Onyx.clear(); + }); + }); + + /** Returns the personalDetails that were handed to getValidOptions on the most recent call. */ + function getPersonalDetailsPassedToGetValidOptions() { + return mockGetValidOptions.mock.calls.at(-1)?.[0]?.personalDetails ?? []; + } + + it('drops an imported contact whose login already exists in personal details, keeping the real Onyx account', async () => { + // EXISTING_CONTACT is alice@expensify.com with the real Onyx accountID 100. + mockFilteredPersonalDetails.current = [EXISTING_CONTACT]; + + renderHook(() => + useSearchSelectorBase({ + selectionMode: CONST.SEARCH_SELECTOR.SELECTION_MODE_MULTI, + searchContext: CONST.SEARCH_SELECTOR.SEARCH_CONTEXT_GENERAL, + contactOptions: [makeDeviceContact('alice@expensify.com', 987654, 'Alice From Phone'), makeDeviceContact('carol@gmail.com', 987655, 'Carol')], + }), + ); + await waitForBatchedUpdatesWithAct(); + + const personalDetails = getPersonalDetailsPassedToGetValidOptions(); + + // Alice must appear exactly once, and with the real Onyx accountID rather than the generated contact one. + const aliceEntries = personalDetails.filter((option) => option.login === 'alice@expensify.com'); + expect(aliceEntries).toHaveLength(1); + expect(aliceEntries.at(0)?.accountID).toBe(100); + + // The contact that isn't already known must still be added. + expect(personalDetails.map((option) => option.login)).toContain('carol@gmail.com'); + }); + + it('de-dupes imported contacts that share the same login', async () => { + renderHook(() => + useSearchSelectorBase({ + selectionMode: CONST.SEARCH_SELECTOR.SELECTION_MODE_MULTI, + searchContext: CONST.SEARCH_SELECTOR.SEARCH_CONTEXT_GENERAL, + contactOptions: [makeDeviceContact('carol@gmail.com', 987655), makeDeviceContact('carol@gmail.com', 111111)], + }), + ); + await waitForBatchedUpdatesWithAct(); + + const personalDetails = getPersonalDetailsPassedToGetValidOptions(); + expect(personalDetails.filter((option) => option.login === 'carol@gmail.com')).toHaveLength(1); + }); + + it('drops a phone contact that resolves to an SMS login already in personal details', async () => { + // getContactOption already normalizes a device phone number to its SMS-domain login, so both sides carry the same login. + const smsLogin = '+15551234567@expensify.sms'; + mockFilteredPersonalDetails.current = [{...EXISTING_CONTACT, login: smsLogin, accountID: 300}]; + + renderHook(() => + useSearchSelectorBase({ + selectionMode: CONST.SEARCH_SELECTOR.SELECTION_MODE_MULTI, + searchContext: CONST.SEARCH_SELECTOR.SEARCH_CONTEXT_GENERAL, + contactOptions: [makeDeviceContact(smsLogin, 987654, 'Alice From Phone')], + }), + ); + await waitForBatchedUpdatesWithAct(); + + const personalDetails = getPersonalDetailsPassedToGetValidOptions(); + expect(personalDetails).toHaveLength(1); + expect(personalDetails.at(0)?.accountID).toBe(300); + }); + + it('matches logins case-insensitively so a differently-cased contact is not duplicated', async () => { + mockFilteredPersonalDetails.current = [EXISTING_CONTACT]; + + renderHook(() => + useSearchSelectorBase({ + selectionMode: CONST.SEARCH_SELECTOR.SELECTION_MODE_MULTI, + searchContext: CONST.SEARCH_SELECTOR.SEARCH_CONTEXT_GENERAL, + contactOptions: [makeDeviceContact('Alice@Expensify.com', 987654)], + }), + ); + await waitForBatchedUpdatesWithAct(); + + const personalDetails = getPersonalDetailsPassedToGetValidOptions(); + expect(personalDetails).toHaveLength(1); + expect(personalDetails.at(0)?.accountID).toBe(100); + }); + + it('keeps an imported contact when the only matching Onyx entry is optimistic', async () => { + // An optimistic personal detail is filtered out by getValidOptions, so it must not suppress the real device contact. + mockFilteredPersonalDetails.current = [{...EXISTING_CONTACT, isOptimisticPersonalDetail: true}]; + + renderHook(() => + useSearchSelectorBase({ + selectionMode: CONST.SEARCH_SELECTOR.SELECTION_MODE_MULTI, + searchContext: CONST.SEARCH_SELECTOR.SEARCH_CONTEXT_GENERAL, + contactOptions: [makeDeviceContact('alice@expensify.com', 987654, 'Alice From Phone')], + }), + ); + await waitForBatchedUpdatesWithAct(); + + const personalDetails = getPersonalDetailsPassedToGetValidOptions(); + const aliceContact = personalDetails.find((option) => option.login === 'alice@expensify.com' && option.accountID === 987654); + expect(aliceContact).toBeDefined(); + }); + + it('keeps all imported contacts when none of them are already known', async () => { + mockFilteredPersonalDetails.current = [EXISTING_CONTACT]; + + renderHook(() => + useSearchSelectorBase({ + selectionMode: CONST.SEARCH_SELECTOR.SELECTION_MODE_MULTI, + searchContext: CONST.SEARCH_SELECTOR.SEARCH_CONTEXT_GENERAL, + contactOptions: [makeDeviceContact('carol@gmail.com', 987655)], + }), + ); + await waitForBatchedUpdatesWithAct(); + + expect(getPersonalDetailsPassedToGetValidOptions().map((option) => option.login)).toEqual(['alice@expensify.com', 'carol@gmail.com']); + }); +});