diff --git a/src/libs/OptionsListUtils/index.ts b/src/libs/OptionsListUtils/index.ts index 3ba2fee6c162..3752bd5c2630 100644 --- a/src/libs/OptionsListUtils/index.ts +++ b/src/libs/OptionsListUtils/index.ts @@ -2248,12 +2248,17 @@ function getValidOptions( // This prevents the issue of seeing the selected option twice if you have them as a recent chat and select them if (!includeSelectedOptions) { for (const option of selectedOptions) { - if (!option.login) { + if (option.login) { + // Prevent re-inviting already selected users + loginsToExclude[option.login] = true; + loginsToExcludeFromSuggestions[option.login] = true; continue; } - // Prevent re-inviting already selected users - loginsToExclude[option.login] = true; - loginsToExcludeFromSuggestions[option.login] = true; + + if (option.reportID) { + loginsToExclude[option.reportID] = true; + loginsToExcludeFromSuggestions[option.reportID] = true; + } } } const {includeP2P = true, shouldBoldTitleByDefault = true, includeDomainEmail = false, shouldShowGBR = false, ...getValidReportsConfig} = config; @@ -2757,19 +2762,24 @@ function formatSectionsFromSearchTerm( // We show the selected participants at the top of the list when there is no search term or maximum number of participants has already been selected // However, if there is a search term we remove the selected participants from the top of the list unless they are part of the search results // This clears up space on mobile views, where if you create a group with 4+ people you can't see the selected participants and the search results at the same time + const selectedOptionsMapper = (participant: Participant) => { + const isReportPolicyExpenseChat = participant.isPolicyExpenseChat ?? false; + const isIOUInvoiceRoom = participant.accountID === CONST.DEFAULT_NUMBER_ID && !!participant.reportID && 'iouType' in participant && participant.iouType === 'invoice'; + if (participant.isSelfDM || isIOUInvoiceRoom) { + const privateIsArchived = allReportNameValuePairsOnyxConnect?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${participant.reportID}`]?.private_isArchived; + return getReportOption(participant, privateIsArchived, undefined, currentUserAccountID, personalDetails, reportAttributesDerived); + } + return isReportPolicyExpenseChat + ? getPolicyExpenseReportOption(participant, currentUserAccountID, personalDetails, reportAttributesDerived) + : getParticipantsOption(participant, personalDetails); + }; + if (searchTerm === '') { return { section: { title: undefined, sectionIndex: 0, - data: shouldGetOptionDetails - ? selectedOptions.map((participant) => { - const isReportPolicyExpenseChat = participant.isPolicyExpenseChat ?? false; - return isReportPolicyExpenseChat - ? getPolicyExpenseReportOption(participant, currentUserAccountID, personalDetails, reportAttributesDerived) - : getParticipantsOption(participant, personalDetails); - }) - : selectedOptions, + data: shouldGetOptionDetails ? selectedOptions.map(selectedOptionsMapper) : selectedOptions, }, }; } @@ -2779,7 +2789,20 @@ function formatSectionsFromSearchTerm( // This will add them to the list of options, deduping them if they already exist in the other lists const selectedParticipantsWithoutDetails = selectedOptions.filter((participant) => { const accountID = participant.accountID ?? null; - const isPartOfSearchTerm = getPersonalDetailSearchTerms(participant, currentUserAccountID).join(' ').toLowerCase().includes(cleanSearchTerm); + let currentParticipant = participant; + if (currentParticipant.isSelfDM) { + currentParticipant = {...currentParticipant, accountID: currentUserAccountID}; + } + const isPartOfSearchTerm = getPersonalDetailSearchTerms( + { + ...currentParticipant, + login: currentParticipant.login ?? personalDetails[currentParticipant.accountID ?? CONST.DEFAULT_NUMBER_ID]?.login, + }, + currentUserAccountID, + ) + .join(' ') + .toLowerCase() + .includes(cleanSearchTerm); const isReportInRecentReports = filteredRecentReports.some((report) => report.accountID === accountID) || filteredWorkspaceChats.some((report) => report.accountID === accountID); const isReportInPersonalDetails = filteredPersonalDetails.some((personalDetail) => personalDetail.accountID === accountID); @@ -2790,14 +2813,7 @@ function formatSectionsFromSearchTerm( section: { title: undefined, sectionIndex: 0, - data: shouldGetOptionDetails - ? selectedParticipantsWithoutDetails.map((participant) => { - const isReportPolicyExpenseChat = participant.isPolicyExpenseChat ?? false; - return isReportPolicyExpenseChat - ? getPolicyExpenseReportOption(participant, currentUserAccountID, personalDetails, reportAttributesDerived) - : getParticipantsOption(participant, personalDetails); - }) - : selectedParticipantsWithoutDetails, + data: shouldGetOptionDetails ? selectedParticipantsWithoutDetails.map(selectedOptionsMapper) : selectedParticipantsWithoutDetails, }, }; } @@ -2819,7 +2835,7 @@ function getPersonalDetailSearchTerms(item: Partial, currentUs if (item.accountID === currentUserAccountID) { return getCurrentUserSearchTerms(item); } - return [item.participantsList?.[0]?.displayName ?? item.displayName ?? '', item.login ?? '', item.login?.replace(CONST.EMAIL_SEARCH_REGEX, '') ?? '']; + return [item.participantsList?.[0]?.displayName ?? item.displayName ?? '', item.login ?? '', item.login?.replace(CONST.EMAIL_SEARCH_REGEX, '') ?? '', item.text ?? '']; } function getCurrentUserSearchTerms(item: Partial) { diff --git a/src/libs/actions/IOU/index.ts b/src/libs/actions/IOU/index.ts index 61a5db5bd71b..ff59b4a37c4b 100644 --- a/src/libs/actions/IOU/index.ts +++ b/src/libs/actions/IOU/index.ts @@ -11881,7 +11881,16 @@ function getMoneyRequestParticipantsFromReport(report: OnyxEntry { - if (isIOUSplit) { - return; - } - addSingleParticipant(option); - }, - }); + const {searchTerm, debouncedSearchTerm, setSearchTerm, availableOptions, selectedOptions, setSelectedOptions, toggleSelection, areOptionsInitialized, onListEndReached, contactState} = + useSearchSelector({ + selectionMode: isIOUSplit ? CONST.SEARCH_SELECTOR.SELECTION_MODE_MULTI : CONST.SEARCH_SELECTOR.SELECTION_MODE_SINGLE, + searchContext: CONST.SEARCH_SELECTOR.SEARCH_CONTEXT_GENERAL, + includeUserToInvite: !isCategorizeOrShareAction && !isPerDiemRequest, + excludeLogins: CONST.EXPENSIFY_EMAILS_OBJECT, + includeRecentReports: true, + maxRecentReportsToShow: CONST.IOU.MAX_RECENT_REPORTS_TO_SHOW, + getValidOptionsConfig, + shouldInitialize: didScreenTransitionEnd, + enablePhoneContacts: isNative, + contactOptions: contacts, + initialSelected: participants as OptionData[], + onSelectionChange: handleSelectionChange, + onSingleSelect: (option: OptionData) => { + if (isIOUSplit) { + return; + } + addSingleParticipant(option); + }, + }); const cleanSearchTerm = useMemo(() => debouncedSearchTerm.trim().toLowerCase(), [debouncedSearchTerm]); @@ -414,9 +415,15 @@ function MoneyRequestParticipantsSelector({ return; } + // If the selected option is self DM, we need to recall onParticipantsAdded to handle navigation correctly + if (!option && selectedOptions.length === 1 && selectedOptions.at(0)?.isSelfDM) { + onParticipantsAdded(selectedOptions.map((selectedOption) => sanitizedSelectedParticipant(selectedOption, iouType))); + return; + } + onFinish(CONST.IOU.TYPE.SPLIT); }, - [shouldShowSplitBillErrorMessage, onFinish, addSingleParticipant, selectedOptions.length], + [shouldShowSplitBillErrorMessage, onFinish, addSingleParticipant, onParticipantsAdded, selectedOptions, iouType], ); const showLoadingPlaceholder = useMemo(() => !areOptionsInitialized || !didScreenTransitionEnd, [areOptionsInitialized, didScreenTransitionEnd]); @@ -510,9 +517,11 @@ function MoneyRequestParticipantsSelector({ return; } + const reportID = option.reportID ?? CONST.REPORT.UNREPORTED_REPORT_ID; + setSelectedOptions([{...option, isSelected: true, reportID, keyForList: reportID}]); addSingleParticipant(option); }, - [isIOUSplit, addParticipantToSelection, addSingleParticipant], + [isIOUSplit, addParticipantToSelection, addSingleParticipant, setSelectedOptions], ); const importContactsButtonComponent = useMemo(() => { diff --git a/src/pages/iou/request/step/IOURequestStepAmount.tsx b/src/pages/iou/request/step/IOURequestStepAmount.tsx index 1cf5a5dc3ac9..42a10d9c3056 100644 --- a/src/pages/iou/request/step/IOURequestStepAmount.tsx +++ b/src/pages/iou/request/step/IOURequestStepAmount.tsx @@ -34,6 +34,7 @@ import { resetSplitShares, setDraftSplitTransaction, setMoneyRequestAmount, + setMoneyRequestParticipants, setMoneyRequestParticipantsFromReport, setMoneyRequestTaxAmount, setMoneyRequestTaxRate, @@ -316,12 +317,15 @@ function IOURequestStepAmount({ // Starting from global + menu means no participant context exists yet, // so we need to handle participant selection based on available workspace settings + const isReturningFromConfirmationPage = !!transaction?.participants?.length; + const firstParticipant = transaction?.participants?.at(0); + const isP2PChat = isParticipantP2P(firstParticipant, currentUserPersonalDetails.accountID); + const isNegativeAmount = convertToBackendAmount(Number.parseFloat(amount)) < 0; if (shouldUseDefaultExpensePolicy(iouType, defaultExpensePolicy)) { const shouldAutoReport = !!defaultExpensePolicy?.autoReporting || !!personalPolicy?.autoReporting; const targetReport = shouldAutoReport ? getPolicyExpenseChat(currentUserAccountIDParam, defaultExpensePolicy?.id) : selfDMReport; const transactionReportID = isSelfDM(targetReport) ? CONST.REPORT.UNREPORTED_REPORT_ID : targetReport?.reportID; const iouTypeTrackOrSubmit = transactionReportID === CONST.REPORT.UNREPORTED_REPORT_ID ? CONST.IOU.TYPE.TRACK : CONST.IOU.TYPE.SUBMIT; - const isReturningFromConfirmationPage = !!transaction?.participants?.length; const resetToDefaultWorkspace = () => { setTransactionReport(transactionID, {reportID: transactionReportID}, true); @@ -331,10 +335,6 @@ function IOURequestStepAmount({ }; if (isReturningFromConfirmationPage) { - const firstParticipant = transaction?.participants?.at(0); - const isP2PChat = isParticipantP2P(firstParticipant); - const isNegativeAmount = convertToBackendAmount(Number.parseFloat(amount)) < 0; - // P2P chats don't support negative amounts, so reset to default workspace when amount is negative. if (isP2PChat && isNegativeAmount) { resetToDefaultWorkspace(); @@ -353,6 +353,13 @@ function IOURequestStepAmount({ } else { resetToDefaultWorkspace(); } + } + // P2P chats don't support negative amounts, so in cases where there is no default workspace when the amount is negative, we will remove the selected transaction participants. + else if (iouType === CONST.IOU.TYPE.CREATE && isP2PChat && isNegativeAmount && isReturningFromConfirmationPage) { + setTransactionReport(transactionID, {reportID: undefined}, true); + setMoneyRequestParticipants(transactionID, [], true).then(() => { + navigateToParticipantPage(iouType, transactionID, reportID); + }); } else { Navigation.setNavigationActionToMicrotaskQueue(() => { navigateToParticipantPage(iouType, transactionID, reportID); @@ -472,8 +479,8 @@ function IOURequestStepAmount({ /** * Check if the participant is a P2P chat */ -function isParticipantP2P(participant: {accountID?: number; isPolicyExpenseChat?: boolean} | undefined): boolean { - return !!(participant?.accountID && !participant.isPolicyExpenseChat); +function isParticipantP2P(participant: {accountID?: number; isPolicyExpenseChat?: boolean} | undefined, currentUserAccountID?: number): boolean { + return !!(participant?.accountID && !participant.isPolicyExpenseChat && (!currentUserAccountID || participant?.accountID !== currentUserAccountID)); } // eslint-disable-next-line rulesdir/no-negated-variables diff --git a/src/pages/iou/request/step/IOURequestStepParticipants.tsx b/src/pages/iou/request/step/IOURequestStepParticipants.tsx index 85ea9da51388..6b576152d6e0 100644 --- a/src/pages/iou/request/step/IOURequestStepParticipants.tsx +++ b/src/pages/iou/request/step/IOURequestStepParticipants.tsx @@ -41,7 +41,6 @@ import ROUTES from '@src/ROUTES'; import type SCREENS from '@src/SCREENS'; import type {Policy} from '@src/types/onyx'; import type {Participant} from '@src/types/onyx/IOU'; -import getEmptyArray from '@src/types/utils/getEmptyArray'; import KeyboardUtils from '@src/utils/keyboard'; import StepScreenWrapper from './StepScreenWrapper'; import type {WithFullTransactionOrNotFoundProps} from './withFullTransactionOrNotFound'; @@ -72,7 +71,11 @@ function IOURequestStepParticipants({ }, transaction: initialTransaction, }: IOURequestStepParticipantsProps) { - const participants = initialTransaction?.participants; + const isSplitRequest = iouType === CONST.IOU.TYPE.SPLIT; + const participants = useMemo(() => { + const allParticipants = initialTransaction?.participants; + return isSplitRequest ? allParticipants : allParticipants?.filter((participant) => !participant.isSender && participant.selected); + }, [initialTransaction?.participants, isSplitRequest]); const {translate} = useLocalize(); const styles = useThemeStyles(); const isFocused = useIsFocused(); @@ -87,10 +90,11 @@ function IOURequestStepParticipants({ const transactionIDs = useMemo(() => transactions?.map((transaction) => transaction.transactionID), [transactions.length]); // We need to set selectedReportID if user has navigated back from confirmation page and navigates to confirmation page with already selected participant - const selectedReportID = useRef(participants?.length === 1 ? (participants.at(0)?.reportID ?? reportID) : reportID); + // We need to disable the eslint rule here because the reportID from the first participant can be an empty string + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + const selectedReportID = useRef(participants?.length === 1 ? participants.at(0)?.reportID || reportID : reportID); const numberOfParticipants = useRef(participants?.length ?? 0); const iouRequestType = getRequestType(initialTransaction); - const isSplitRequest = iouType === CONST.IOU.TYPE.SPLIT; const isMovingTransactionFromTrackExpense = isMovingTransactionFromTrackExpenseIOUUtils(action); const headerTitle = useMemo(() => { if (action === CONST.IOU.ACTION.CATEGORIZE) { @@ -454,7 +458,7 @@ function IOURequestStepParticipants({ /> )} { expect(results.recentReports).not.toEqual(expect.arrayContaining([expect.objectContaining({login: 'receipts@expensify.com'})])); }); + it('should exclude the person and the report from selected options', () => { + const selectedPerson = PERSONAL_DETAILS['3']; + const selectedReport = REPORTS['3'] as unknown as OptionData; + + const results = getValidOptions( + {reports: OPTIONS.reports, personalDetails: OPTIONS.personalDetails}, + allPolicies, + {}, + nvpDismissedProductTraining, + loginList, + CURRENT_USER_ACCOUNT_ID, + CURRENT_USER_EMAIL, + { + excludeLogins: CONST.EXPENSIFY_EMAILS_OBJECT, + selectedOptions: [selectedPerson, selectedReport], + }, + ); + + // The person must be excluded + expect(results.recentReports.every((option) => option.login !== selectedPerson.login)).toBe(true); + expect(results.personalDetails.every((option) => option.login !== selectedPerson.login)).toBe(true); + + // The report must be excluded + expect(results.recentReports.every((option) => option.reportID !== selectedReport.reportID)).toBe(true); + expect(results.personalDetails.every((option) => option.reportID !== selectedPerson.reportID)).toBe(true); + }); + it('should limit recent reports when maxRecentReportElements is specified', () => { // Given a set of reports and personalDetails with multiple reports // When we call getValidOptions with maxRecentReportElements set to 2