diff --git a/src/components/Search/SearchList/index.tsx b/src/components/Search/SearchList/index.tsx index a97d96b2b8ea..e106c04bcb0d 100644 --- a/src/components/Search/SearchList/index.tsx +++ b/src/components/Search/SearchList/index.tsx @@ -183,15 +183,37 @@ function SearchList({ } return data; }, [data, groupBy, type]); - const flattenedItemsWithoutPendingDelete = useMemo(() => flattenedItems.filter((t) => t?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE), [flattenedItems]); - - const selectedItemsLength = useMemo( - () => - flattenedItems.reduce((acc, item) => { - return item?.isSelected ? acc + 1 : acc; - }, 0), - [flattenedItems], - ); + + const emptyReports = useMemo(() => { + if (type === CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT && isTransactionGroupListItemArray(data)) { + return data.filter((item) => item.transactions.length === 0); + } + return []; + }, [data, type]); + + const selectedItemsLength = useMemo(() => { + const selectedTransactions = flattenedItems.reduce((acc, item) => { + return acc + (item?.isSelected ? 1 : 0); + }, 0); + + if (type === CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT && isTransactionGroupListItemArray(data)) { + const selectedEmptyReports = emptyReports.reduce((acc, item) => { + return acc + (item.isSelected ? 1 : 0); + }, 0); + + return selectedEmptyReports + selectedTransactions; + } + + return selectedTransactions; + }, [flattenedItems, type, data, emptyReports]); + + const totalItems = useMemo(() => { + if (type === CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT && isTransactionGroupListItemArray(data)) { + return emptyReports.length + flattenedItems.length; + } + + return flattenedItems.length; + }, [data, type, flattenedItems, emptyReports]); const {translate} = useLocalize(); const {isOffline} = useNetwork(); @@ -237,10 +259,6 @@ function SearchList({ if (shouldPreventLongPressRow || !isSmallScreenWidth || item?.isDisabled || item?.isDisabledCheckbox) { return; } - // disable long press for empty expense reports - if ('transactions' in item && item.transactions.length === 0 && !groupBy) { - return; - } if (isMobileSelectionModeEnabled) { onCheckboxPress(item, itemTransactions); return; @@ -249,7 +267,7 @@ function SearchList({ setLongPressedItemTransactions(itemTransactions); setIsModalVisible(true); }, - [groupBy, route.key, shouldPreventLongPressRow, isSmallScreenWidth, isMobileSelectionModeEnabled, onCheckboxPress], + [route.key, shouldPreventLongPressRow, isSmallScreenWidth, isMobileSelectionModeEnabled, onCheckboxPress], ); const turnOnSelectionMode = useCallback(() => { @@ -373,7 +391,7 @@ function SearchList({ const tableHeaderVisible = (canSelectMultiple || !!SearchTableHeader) && (!groupBy || type === CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT); const selectAllButtonVisible = canSelectMultiple && !SearchTableHeader; - const isSelectAllChecked = selectedItemsLength > 0 && selectedItemsLength === flattenedItemsWithoutPendingDelete.length; + const isSelectAllChecked = selectedItemsLength > 0 && selectedItemsLength === totalItems; return ( @@ -383,7 +401,7 @@ function SearchList({ 0 && selectedItemsLength !== flattenedItemsWithoutPendingDelete.length} + isIndeterminate={selectedItemsLength > 0 && selectedItemsLength !== totalItems} onPress={() => { onAllCheckboxPress(); }} diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx index 9ae0110fd7bd..8fbdab23684a 100644 --- a/src/components/Search/index.tsx +++ b/src/components/Search/index.tsx @@ -9,7 +9,14 @@ import FullPageErrorView from '@components/BlockingViews/FullPageErrorView'; import FullPageOfflineBlockingView from '@components/BlockingViews/FullPageOfflineBlockingView'; import ConfirmModal from '@components/ConfirmModal'; import SearchTableHeader, {getExpenseHeaders} from '@components/SelectionListWithSections/SearchTableHeader'; -import type {ReportActionListItemType, SearchListItem, SelectionListHandle, TransactionGroupListItemType, TransactionListItemType} from '@components/SelectionListWithSections/types'; +import type { + ReportActionListItemType, + SearchListItem, + SelectionListHandle, + TransactionGroupListItemType, + TransactionListItemType, + TransactionReportGroupListItemType, +} from '@components/SelectionListWithSections/types'; import SearchRowSkeleton from '@components/Skeletons/SearchRowSkeleton'; import {WideRHPContext} from '@components/WideRHPContextProvider'; import useArchivedReportsIdSet from '@hooks/useArchivedReportsIdSet'; @@ -51,6 +58,7 @@ import { isTransactionGroupListItemType, isTransactionListItemType, isTransactionMemberGroupListItemType, + isTransactionReportGroupListItemType, isTransactionWithdrawalIDGroupListItemType, shouldShowEmptyState, shouldShowYear as shouldShowYearUtil, @@ -91,7 +99,11 @@ type SearchProps = { const expenseHeaders = getExpenseHeaders(); -function mapTransactionItemToSelectedEntry(item: TransactionListItemType, outstandingReportsByPolicyID?: OutstandingReportsByPolicyIDDerivedValue): [string, SelectedTransactionInfo] { +function mapTransactionItemToSelectedEntry( + item: TransactionListItemType, + outstandingReportsByPolicyID?: OutstandingReportsByPolicyIDDerivedValue, + allowNegativeAmount = true, +): [string, SelectedTransactionInfo] { return [ item.keyForList, { @@ -114,7 +126,7 @@ function mapTransactionItemToSelectedEntry(item: TransactionListItemType, outsta convertedCurrency: item.convertedCurrency, reportID: item.reportID, policyID: item.report?.policyID, - amount: item.modifiedAmount ?? item.amount, + amount: allowNegativeAmount ? (item.modifiedAmount ?? item.amount) : Math.abs(item.modifiedAmount ?? item.amount), convertedAmount: item.convertedAmount, currency: item.currency, isFromOneTransactionReport: item.isFromOneTransactionReport, @@ -123,6 +135,27 @@ function mapTransactionItemToSelectedEntry(item: TransactionListItemType, outsta ]; } +function mapEmptyReportToSelectedEntry(item: TransactionReportGroupListItemType): [string, SelectedTransactionInfo] { + return [ + item.keyForList ?? '', + { + isSelected: true, + canDelete: true, + canHold: false, + isHeld: false, + canUnhold: false, + canChangeReport: false, + action: item.action ?? CONST.SEARCH.ACTION_TYPES.VIEW, + reportID: item.reportID, + policyID: item.policyID ?? CONST.POLICY.ID_FAKE, + amount: 0, + convertedAmount: 0, + convertedCurrency: '', + currency: '', + }, + ]; +} + function mapToTransactionItemWithAdditionalInfo( item: TransactionListItemType, selectedTransactions: SelectedTransactions, @@ -159,47 +192,24 @@ function mapToItemWithAdditionalInfo(item: SearchListItem, selectedTransactions: mapToTransactionItemWithAdditionalInfo(transaction, selectedTransactions, canSelectMultiple, shouldAnimateInHighlight, hash), ), isSelected: - item?.transactions?.length > 0 && - item.transactions?.filter((t) => !isTransactionPendingDelete(t)).every((transaction) => selectedTransactions[transaction.keyForList]?.isSelected && canSelectMultiple), + item?.transactions?.length > 0 + ? item.transactions?.filter((t) => !isTransactionPendingDelete(t)).every((transaction) => selectedTransactions[transaction.keyForList]?.isSelected && canSelectMultiple) + : !!(item.keyForList && selectedTransactions[item.keyForList]?.isSelected && canSelectMultiple), hash, }; } -function prepareTransactionsList(item: TransactionListItemType, selectedTransactions: SelectedTransactions, outstandingReportsByPolicyID?: OutstandingReportsByPolicyIDDerivedValue) { +function toggleTransactionInList(item: TransactionListItemType, selectedTransactions: SelectedTransactions, outstandingReportsByPolicyID?: OutstandingReportsByPolicyIDDerivedValue) { if (selectedTransactions[item.keyForList]?.isSelected) { const {[item.keyForList]: omittedTransaction, ...transactions} = selectedTransactions; return transactions; } + const [key, selectedInfo] = mapTransactionItemToSelectedEntry(item, outstandingReportsByPolicyID, false); return { ...selectedTransactions, - [item.keyForList]: { - isSelected: true, - canDelete: item.canDelete, - canHold: item.canHold, - isHeld: isOnHold(item), - canUnhold: item.canUnhold, - canChangeReport: canEditFieldOfMoneyRequest( - item.reportAction, - CONST.EDIT_REQUEST_FIELD.REPORT, - undefined, - undefined, - outstandingReportsByPolicyID, - item, - item.report, - item.policy, - ), - action: item.action, - reportID: item.reportID, - policyID: item.policyID, - amount: Math.abs(item.modifiedAmount || item.amount), - convertedAmount: item.convertedAmount, - convertedCurrency: item.convertedCurrency, - currency: item.currency, - isFromOneTransactionReport: item.isFromOneTransactionReport, - ownerAccountID: item.report?.ownerAccountID ?? item.accountID, - }, + [key]: selectedInfo, }; } @@ -447,6 +457,22 @@ function Search({ if (!Object.hasOwn(transactionGroup, 'transactions') || !('transactions' in transactionGroup)) { return; } + + if (transactionGroup.transactions.length === 0 && isTransactionReportGroupListItemType(transactionGroup)) { + const reportKey = transactionGroup.keyForList; + if (transactionGroup.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) { + return; + } + if (reportKey && (reportKey in selectedTransactions || areAllMatchingItemsSelected)) { + const [, emptyReportSelection] = mapEmptyReportToSelectedEntry(transactionGroup); + newTransactionList[reportKey] = { + ...emptyReportSelection, + isSelected: areAllMatchingItemsSelected || selectedTransactions[reportKey]?.isSelected, + }; + } + return; + } + transactionGroup.transactions.forEach((transactionItem) => { if (!(transactionItem.transactionID in selectedTransactions) && !areAllMatchingItemsSelected) { return; @@ -550,25 +576,36 @@ function Search({ isRefreshingSelection.current = false; }, [selectedTransactions]); - useEffect(() => { - if (!isFocused) { - return; - } - - if (!data.length || isRefreshingSelection.current) { - return; - } - const areItemsGrouped = !!validGroupBy || type === CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT; - const flattenedItems = areItemsGrouped ? (data as TransactionGroupListItemType[]).flatMap((item) => item.transactions) : data; - const areAllItemsSelected = flattenedItems.length === Object.keys(selectedTransactions).length; - - // If the user has selected all the expenses in their view but there are more expenses matched by the search - // give them the option to select all matching expenses - shouldShowSelectAllMatchingItems(!!(areAllItemsSelected && searchResults?.search?.hasMoreResults)); - if (!areAllItemsSelected) { - selectAllMatchingItems(false); - } - }, [isFocused, data, searchResults?.search?.hasMoreResults, selectedTransactions, selectAllMatchingItems, shouldShowSelectAllMatchingItems, validGroupBy, type]); + const updateSelectAllMatchingItemsState = useCallback( + (updatedSelectedTransactions: SelectedTransactions) => { + if (!data.length || isRefreshingSelection.current) { + return; + } + const areItemsGrouped = !!validGroupBy || type === CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT; + const totalSelectableItemsCount = areItemsGrouped + ? (data as TransactionGroupListItemType[]).reduce((count, item) => { + // For empty reports, count the report itself as a selectable item + if (item.transactions.length === 0 && isTransactionReportGroupListItemType(item)) { + if (item.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) { + return count; + } + return count + 1; + } + // For regular reports, count all transactions + return count + item.transactions.length; + }, 0) + : data.length; + const areAllItemsSelected = totalSelectableItemsCount === Object.keys(updatedSelectedTransactions).length; + + // If the user has selected all the expenses in their view but there are more expenses matched by the search + // give them the option to select all matching expenses + shouldShowSelectAllMatchingItems(!!(areAllItemsSelected && searchResults?.search?.hasMoreResults)); + if (!areAllItemsSelected) { + selectAllMatchingItems(false); + } + }, + [data, validGroupBy, type, searchResults?.search?.hasMoreResults, shouldShowSelectAllMatchingItems, selectAllMatchingItems], + ); const toggleTransaction = useCallback( (item: SearchListItem, itemTransactions?: TransactionListItemType[]) => { @@ -585,11 +622,44 @@ function Search({ if (isTransactionPendingDelete(item)) { return; } - setSelectedTransactions(prepareTransactionsList(item, selectedTransactions, outstandingReportsByPolicyID), data); + const updatedTransactions = toggleTransactionInList(item, selectedTransactions, outstandingReportsByPolicyID); + setSelectedTransactions(updatedTransactions, data); + updateSelectAllMatchingItemsState(updatedTransactions); return; } const currentTransactions = itemTransactions ?? item.transactions; + + // Handle empty reports - treat the report itself as selectable + if (currentTransactions.length === 0 && isTransactionReportGroupListItemType(item)) { + const reportKey = item.keyForList; + if (!reportKey) { + return; + } + + if (item.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) { + return; + } + + if (selectedTransactions[reportKey]?.isSelected) { + // Deselect the empty report + const reducedSelectedTransactions: SelectedTransactions = {...selectedTransactions}; + delete reducedSelectedTransactions[reportKey]; + setSelectedTransactions(reducedSelectedTransactions, data); + updateSelectAllMatchingItemsState(reducedSelectedTransactions); + return; + } + + const [, emptyReportSelection] = mapEmptyReportToSelectedEntry(item); + const updatedTransactions = { + ...selectedTransactions, + [reportKey]: emptyReportSelection, + }; + setSelectedTransactions(updatedTransactions, data); + updateSelectAllMatchingItemsState(updatedTransactions); + return; + } + if (currentTransactions.some((transaction) => selectedTransactions[transaction.keyForList]?.isSelected)) { const reducedSelectedTransactions: SelectedTransactions = {...selectedTransactions}; @@ -598,22 +668,22 @@ function Search({ }); setSelectedTransactions(reducedSelectedTransactions, data); + updateSelectAllMatchingItemsState(reducedSelectedTransactions); return; } - setSelectedTransactions( - { - ...selectedTransactions, - ...Object.fromEntries( - currentTransactions - .filter((t) => !isTransactionPendingDelete(t)) - .map((transactionItem) => mapTransactionItemToSelectedEntry(transactionItem, outstandingReportsByPolicyID)), - ), - }, - data, - ); + const updatedTransactions = { + ...selectedTransactions, + ...Object.fromEntries( + currentTransactions + .filter((t) => !isTransactionPendingDelete(t)) + .map((transactionItem) => mapTransactionItemToSelectedEntry(transactionItem, outstandingReportsByPolicyID)), + ), + }; + setSelectedTransactions(updatedTransactions, data); + updateSelectAllMatchingItemsState(updatedTransactions); }, - [data, selectedTransactions, outstandingReportsByPolicyID, setSelectedTransactions], + [data, selectedTransactions, outstandingReportsByPolicyID, setSelectedTransactions, updateSelectAllMatchingItemsState], ); const onSelectRow = useCallback( @@ -808,33 +878,38 @@ function Search({ if (totalSelected > 0) { clearSelectedTransactions(); + updateSelectAllMatchingItemsState({}); return; } + let updatedTransactions: SelectedTransactions; if (areItemsGrouped) { - setSelectedTransactions( - Object.fromEntries( - (data as TransactionGroupListItemType[]).flatMap((item) => - item.transactions - .filter((t) => !isTransactionPendingDelete(t)) - .map((transactionItem) => mapTransactionItemToSelectedEntry(transactionItem, outstandingReportsByPolicyID)), - ), + const allSelections: Array<[string, SelectedTransactionInfo]> = (data as TransactionGroupListItemType[]).flatMap((item) => { + if (item.transactions.length === 0 && isTransactionReportGroupListItemType(item) && item.keyForList) { + if (item.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) { + return []; + } + return [mapEmptyReportToSelectedEntry(item)]; + } + + return item.transactions + .filter((t) => !isTransactionPendingDelete(t)) + .map((transactionItem) => mapTransactionItemToSelectedEntry(transactionItem, outstandingReportsByPolicyID)); + }); + updatedTransactions = Object.fromEntries(allSelections); + } else { + updatedTransactions = Object.fromEntries( + (data as TransactionGroupListItemType[]).flatMap((item) => + item.transactions + .filter((t) => !isTransactionPendingDelete(t)) + .map((transactionItem) => mapTransactionItemToSelectedEntry(transactionItem, outstandingReportsByPolicyID)), ), - data, ); - - return; } - setSelectedTransactions( - Object.fromEntries( - (data as TransactionListItemType[]) - .filter((t) => !isTransactionPendingDelete(t)) - .map((transactionItem) => mapTransactionItemToSelectedEntry(transactionItem, outstandingReportsByPolicyID)), - ), - data, - ); - }, [clearSelectedTransactions, data, validGroupBy, selectedTransactions, setSelectedTransactions, outstandingReportsByPolicyID, isExpenseReportType]); + setSelectedTransactions(updatedTransactions, data); + updateSelectAllMatchingItemsState(updatedTransactions); + }, [clearSelectedTransactions, data, validGroupBy, selectedTransactions, setSelectedTransactions, outstandingReportsByPolicyID, isExpenseReportType, updateSelectAllMatchingItemsState]); const onLayout = useCallback(() => handleSelectionListScroll(sortedSelectedData, searchListRef.current), [handleSelectionListScroll, sortedSelectedData]); diff --git a/src/components/SelectionListWithSections/Search/TransactionGroupListItem.tsx b/src/components/SelectionListWithSections/Search/TransactionGroupListItem.tsx index 00e526591197..975c075ceb14 100644 --- a/src/components/SelectionListWithSections/Search/TransactionGroupListItem.tsx +++ b/src/components/SelectionListWithSections/Search/TransactionGroupListItem.tsx @@ -129,10 +129,13 @@ function TransactionGroupListItem({ return transactions.filter((transaction) => transaction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE); }, [transactions]); - const isSelectAllChecked = selectedItemsLength === transactions.length && transactions.length > 0; + const isEmpty = transactions.length === 0; + + const isEmptyReportSelected = isEmpty && item?.keyForList && selectedTransactions[item.keyForList]?.isSelected; + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + const isSelectAllChecked = isEmptyReportSelected || (selectedItemsLength === transactionsWithoutPendingDelete.length && transactionsWithoutPendingDelete.length > 0); const isIndeterminate = selectedItemsLength > 0 && selectedItemsLength !== transactionsWithoutPendingDelete.length; - const isEmpty = transactions.length === 0; // Currently only the transaction report groups have transactions where the empty view makes sense const shouldDisplayEmptyView = isEmpty && isExpenseReportType; const isDisabledOrEmpty = isEmpty || isDisabled; @@ -191,11 +194,8 @@ function TransactionGroupListItem({ }, [isExpenseReportType, transactions.length, onSelectRow, transactionPreviewData, item, handleToggle]); const onLongPress = useCallback(() => { - if (isEmpty) { - return; - } onLongPressRow?.(item, isExpenseReportType ? undefined : transactions); - }, [isEmpty, isExpenseReportType, item, onLongPressRow, transactions]); + }, [isExpenseReportType, item, onLongPressRow, transactions]); const onCheckboxPress = useCallback( (val: TItem) => { @@ -261,7 +261,7 @@ function TransactionGroupListItem({ report={groupItem as TransactionReportGroupListItemType} onSelectRow={(listItem) => onSelectRow(listItem, transactionPreviewData)} onCheckboxPress={onCheckboxPress} - isDisabled={isDisabledOrEmpty} + isDisabled={isDisabled} isFocused={isFocused} canSelectMultiple={canSelectMultiple} isSelectAllChecked={isSelectAllChecked} @@ -282,19 +282,20 @@ function TransactionGroupListItem({ }, [ groupItem, - onSelectRow, - transactionPreviewData, onCheckboxPress, isDisabledOrEmpty, - isFocused, canSelectMultiple, isSelectAllChecked, isIndeterminate, - onDEWModalOpen, - groupBy, - isExpanded, onExpandIconPress, + isExpanded, + isFocused, searchType, + groupBy, + isDisabled, + onDEWModalOpen, + onSelectRow, + transactionPreviewData, ], ); diff --git a/src/libs/actions/Search.ts b/src/libs/actions/Search.ts index 4b31569268af..819c8ba20721 100644 --- a/src/libs/actions/Search.ts +++ b/src/libs/actions/Search.ts @@ -6,7 +6,7 @@ import type {FormOnyxValues} from '@components/Form/types'; import type {ContinueActionParams, PaymentMethod, PaymentMethodType} from '@components/KYCWall/types'; import type {LocalizedTranslate} from '@components/LocaleContextProvider'; import type {PopoverMenuItem} from '@components/PopoverMenu'; -import type {BankAccountMenuItem, PaymentData, SearchQueryJSON, SelectedReports, SelectedTransactions} from '@components/Search/types'; +import type {BankAccountMenuItem, PaymentData, SearchQueryJSON, SelectedReports, SelectedTransactionInfo, SelectedTransactions} from '@components/Search/types'; import type {TransactionListItemType, TransactionReportGroupListItemType} from '@components/SelectionListWithSections/types'; import * as API from '@libs/API'; import {waitForWrites} from '@libs/API'; @@ -47,7 +47,7 @@ import type {SearchReport, SearchTransaction} from '@src/types/onyx/SearchResult import type Nullable from '@src/types/utils/Nullable'; import SafeString from '@src/utils/SafeString'; import {setPersonalBankAccountContinueKYCOnSuccess} from './BankAccounts'; -import {setOptimisticTransactionThread} from './Report'; +import {deleteAppReport, setOptimisticTransactionThread} from './Report'; import {saveLastSearchParams} from './ReportNavigation'; type OnyxSearchResponse = { @@ -619,6 +619,30 @@ function deleteMoneyRequestOnSearch(hash: number, transactionIDList: string[]) { API.write(WRITE_COMMANDS.DELETE_MONEY_REQUEST_ON_SEARCH, {hash, transactionIDList}, {optimisticData, failureData, finallyData}); } +function bulkDeleteReports(hash: number, selectedTransactions: Record) { + const transactionIDList: string[] = []; + const reportIDList: string[] = []; + + Object.keys(selectedTransactions).forEach((key) => { + const selectedItem = selectedTransactions[key]; + if (selectedItem.action === CONST.SEARCH.ACTION_TYPES.VIEW && key === selectedItem.reportID) { + reportIDList.push(selectedItem.reportID); + } else { + transactionIDList.push(key); + } + }); + + if (transactionIDList.length > 0) { + deleteMoneyRequestOnSearch(hash, transactionIDList); + } + + if (reportIDList.length > 0) { + reportIDList.forEach((reportID) => { + deleteAppReport(reportID); + }); + } +} + type Params = Record; function exportSearchItemsToCSV({query, jsonQuery, reportIDList, transactionIDList}: ExportSearchItemsToCSVParams, onDownloadFailed: () => void) { @@ -956,6 +980,7 @@ export { search, updateSearchResultsWithTransactionThreadReportID, deleteMoneyRequestOnSearch, + bulkDeleteReports, holdMoneyRequestOnSearch, unholdMoneyRequestOnSearch, exportSearchItemsToCSV, diff --git a/src/pages/Search/SearchPage.tsx b/src/pages/Search/SearchPage.tsx index ae86767186c2..26b322fd063e 100644 --- a/src/pages/Search/SearchPage.tsx +++ b/src/pages/Search/SearchPage.tsx @@ -38,7 +38,7 @@ import {confirmReadyToOpenApp} from '@libs/actions/App'; import {moveIOUReportToPolicy, moveIOUReportToPolicyAndInviteSubmitter, searchInServer} from '@libs/actions/Report'; import { approveMoneyRequestOnSearch, - deleteMoneyRequestOnSearch, + bulkDeleteReports, exportSearchItemsToCSV, getExportTemplates, getLastPolicyPaymentMethod, @@ -553,16 +553,16 @@ function SearchPage({route}: SearchPageProps) { isOffline, selectedReports, queryJSON, + integrationsExportTemplates, + csvExportLayouts, clearSelectedTransactions, + beginExportWithTemplate, + policies, lastPaymentMethods, theme.icon, styles.colorMuted, styles.fontWeightNormal, styles.textWrap, - beginExportWithTemplate, - integrationsExportTemplates, - csvExportLayouts, - policies, bulkPayButtonOptions, onBulkPaySelected, selectedPolicyIDs, @@ -582,7 +582,7 @@ function SearchPage({route}: SearchPageProps) { // We need to wait for modal to fully disappear before clearing them to avoid translation flicker between singular vs plural // eslint-disable-next-line @typescript-eslint/no-deprecated InteractionManager.runAfterInteractions(() => { - deleteMoneyRequestOnSearch(hash, selectedTransactionsKeys); + bulkDeleteReports(hash, selectedTransactions); clearSelectedTransactions(); }); }; diff --git a/tests/unit/Search/deleteSelectedItemsOnSearchTest.ts b/tests/unit/Search/deleteSelectedItemsOnSearchTest.ts new file mode 100644 index 000000000000..5e1bda64759b --- /dev/null +++ b/tests/unit/Search/deleteSelectedItemsOnSearchTest.ts @@ -0,0 +1,264 @@ +/* eslint-disable @typescript-eslint/naming-convention */ +import Onyx from 'react-native-onyx'; +import type {SelectedTransactionInfo} from '@components/Search/types'; +import {bulkDeleteReports} from '@libs/actions/Search'; +import {deleteAppReport} from '@userActions/Report'; +import CONST from '@src/CONST'; + +jest.mock('@userActions/Report', () => ({ + deleteAppReport: jest.fn(), +})); + +jest.mock('@libs/API', () => ({ + write: jest.fn(), +})); + +describe('bulkDeleteReports', () => { + beforeEach(() => { + jest.clearAllMocks(); + return Onyx.clear(); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + describe('Empty Report Deletion', () => { + it('should delete empty reports when selected', () => { + const hash = 12345; + const selectedTransactions: Record = { + report_123: { + reportID: 'report_123', + action: CONST.SEARCH.ACTION_TYPES.VIEW, + isSelected: true, + canDelete: true, + canHold: false, + canChangeReport: false, + isHeld: false, + canUnhold: false, + policyID: 'policy123', + amount: 0, + convertedAmount: 0, + convertedCurrency: 'USD', + currency: 'USD', + }, + report_456: { + reportID: 'report_456', + action: CONST.SEARCH.ACTION_TYPES.VIEW, + isSelected: true, + canDelete: true, + canHold: false, + canChangeReport: false, + isHeld: false, + canUnhold: false, + policyID: 'policy456', + amount: 0, + convertedAmount: 0, + convertedCurrency: 'USD', + currency: 'USD', + }, + }; + + bulkDeleteReports(hash, selectedTransactions); + + // Should call deleteAppReport for each empty report + expect(deleteAppReport).toHaveBeenCalledTimes(2); + expect(deleteAppReport).toHaveBeenCalledWith('report_123'); + expect(deleteAppReport).toHaveBeenCalledWith('report_456'); + }); + + it('should handle mixed selection of empty reports and transactions', () => { + const hash = 12345; + const selectedTransactions: Record = { + report_123: { + reportID: 'report_123', + action: CONST.SEARCH.ACTION_TYPES.VIEW, + isSelected: true, + canDelete: true, + canHold: false, + canChangeReport: false, + isHeld: false, + canUnhold: false, + policyID: 'policy123', + amount: 0, + convertedAmount: 0, + convertedCurrency: 'USD', + currency: 'USD', + }, + transaction_789: { + reportID: 'report_456', + action: CONST.SEARCH.ACTION_TYPES.VIEW, + isSelected: true, + canDelete: true, + canHold: true, + canChangeReport: true, + isHeld: false, + canUnhold: false, + policyID: 'policy456', + amount: 1000, + convertedAmount: 1000, + convertedCurrency: 'USD', + currency: 'USD', + }, + transaction_101: { + reportID: 'report_456', + action: CONST.SEARCH.ACTION_TYPES.VIEW, + isSelected: true, + canDelete: true, + canHold: true, + canChangeReport: true, + isHeld: false, + canUnhold: false, + policyID: 'policy456', + amount: 500, + convertedAmount: 500, + convertedCurrency: 'USD', + currency: 'USD', + }, + }; + + bulkDeleteReports(hash, selectedTransactions); + + // Should call deleteAppReport for empty report + expect(deleteAppReport).toHaveBeenCalledTimes(1); + expect(deleteAppReport).toHaveBeenCalledWith('report_123'); + }); + + it('should not delete reports when no empty reports are selected', () => { + const hash = 12345; + const selectedTransactions: Record = { + transaction_789: { + reportID: 'report_456', + action: CONST.SEARCH.ACTION_TYPES.VIEW, + isSelected: true, + canDelete: true, + canHold: true, + canChangeReport: true, + isHeld: false, + canUnhold: false, + policyID: 'policy456', + amount: 1000, + convertedAmount: 1000, + convertedCurrency: 'USD', + currency: 'USD', + }, + transaction_101: { + reportID: 'report_456', + action: CONST.SEARCH.ACTION_TYPES.VIEW, + isSelected: true, + canDelete: true, + canHold: true, + canChangeReport: true, + isHeld: false, + canUnhold: false, + policyID: 'policy456', + amount: 500, + convertedAmount: 500, + convertedCurrency: 'USD', + currency: 'USD', + }, + }; + + bulkDeleteReports(hash, selectedTransactions); + + // Should not call deleteAppReport + expect(deleteAppReport).not.toHaveBeenCalled(); + }); + + it('should handle empty selection gracefully', () => { + const hash = 12345; + const selectedTransactions: Record = {}; + + bulkDeleteReports(hash, selectedTransactions); + + // Should not call any deletion functions + expect(deleteAppReport).not.toHaveBeenCalled(); + }); + + it('should only delete reports where key matches reportID for VIEW action', () => { + const hash = 12345; + const selectedTransactions: Record = { + report_123: { + reportID: 'report_123', + action: CONST.SEARCH.ACTION_TYPES.VIEW, + isSelected: true, + canDelete: true, + canHold: false, + canChangeReport: false, + isHeld: false, + canUnhold: false, + policyID: 'policy123', + amount: 0, + convertedAmount: 0, + convertedCurrency: 'USD', + currency: 'USD', + }, + different_key: { + reportID: 'report_456', + action: CONST.SEARCH.ACTION_TYPES.VIEW, + isSelected: true, + canDelete: true, + canHold: false, + canChangeReport: false, + isHeld: false, + canUnhold: false, + policyID: 'policy456', + amount: 0, + convertedAmount: 0, + convertedCurrency: 'USD', + currency: 'USD', + }, + }; + + bulkDeleteReports(hash, selectedTransactions); + + // Should only call deleteAppReport for the first report where key === reportID + expect(deleteAppReport).toHaveBeenCalledTimes(1); + expect(deleteAppReport).toHaveBeenCalledWith('report_123'); + expect(deleteAppReport).not.toHaveBeenCalledWith('report_456'); + }); + }); + + describe('Transaction Deletion', () => { + it('should handle transaction deletion when transactions are selected', () => { + const hash = 12345; + const selectedTransactions: Record = { + transaction_789: { + reportID: 'report_456', + action: CONST.SEARCH.ACTION_TYPES.VIEW, + isSelected: true, + canDelete: true, + canHold: true, + canChangeReport: true, + isHeld: false, + canUnhold: false, + policyID: 'policy456', + amount: 1000, + convertedAmount: 1000, + convertedCurrency: 'USD', + currency: 'USD', + }, + transaction_101: { + reportID: 'report_456', + action: CONST.SEARCH.ACTION_TYPES.VIEW, + isSelected: true, + canDelete: true, + canHold: true, + canChangeReport: true, + isHeld: false, + canUnhold: false, + policyID: 'policy456', + amount: 500, + convertedAmount: 500, + convertedCurrency: 'USD', + currency: 'USD', + }, + }; + + bulkDeleteReports(hash, selectedTransactions); + + // Should not call deleteAppReport for transactions + expect(deleteAppReport).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/tests/unit/TransactionGroupListItemTest.tsx b/tests/unit/TransactionGroupListItemTest.tsx index aa943ca8895d..9628448b8d4a 100644 --- a/tests/unit/TransactionGroupListItemTest.tsx +++ b/tests/unit/TransactionGroupListItemTest.tsx @@ -23,6 +23,47 @@ jest.mock('@libs/SearchUIUtils', () => ({ isCorrectSearchUserName: jest.fn(() => true), })); +const mockEmptyReport: TransactionReportGroupListItemType = { + accountID: 1, + chatReportID: '4735435600700077', + chatType: undefined, + created: '2025-09-19 20:00:47', + currency: 'USD', + isOneTransactionReport: false, + isOwnPolicyExpenseChat: false, + isPolicyExpenseChat: false, + isWaitingOnBankAccount: false, + managerID: 1, + nonReimbursableTotal: 0, + oldPolicyName: '', + ownerAccountID: 1, + parentReportActionID: '2454187434077044186', + parentReportID: '4735435600700077', + policyID: '06F34677820A4D07', + private_isArchived: '', + reportID: '515146912679679', + reportName: 'Expense Report #515146912679679', + stateNum: 1, + statusNum: 1, + total: 0, + type: 'expense', + unheldTotal: 0, + from: { + accountID: 1, + avatar: 'https://d2k5nsl2zxldvw.cloudfront.net/images/avatars/default-avatar_15.png', + displayName: 'Main Applause QA', + }, + to: { + accountID: 1, + avatar: 'https://d2k5nsl2zxldvw.cloudfront.net/images/avatars/default-avatar_15.png', + displayName: 'Main Applause QA', + }, + transactions: [], + groupedBy: 'expense-report', + keyForList: '515146912679679', + action: CONST.SEARCH.ACTION_TYPES.VIEW, +}; + const mockTransaction: TransactionListItemType = { accountID: 1, amount: 0, @@ -89,6 +130,54 @@ const mockTransaction: TransactionListItemType = { }, }; +const mockNonEmptyReport: TransactionReportGroupListItemType = { + accountID: 2, + chatReportID: '4735435600700078', + chatType: undefined, + created: '2025-09-20 10:00:00', + currency: 'USD', + isOneTransactionReport: false, + isOwnPolicyExpenseChat: false, + isPolicyExpenseChat: false, + isWaitingOnBankAccount: false, + managerID: 2, + nonReimbursableTotal: 0, + oldPolicyName: '', + ownerAccountID: 2, + parentReportActionID: '2454187434077044187', + parentReportID: '4735435600700078', + policyID: '06F34677820A4D07', + private_isArchived: '', + reportID: '515146912679680', + reportName: 'Expense Report #515146912679680', + stateNum: 1, + statusNum: 1, + total: -1284, + type: 'expense', + unheldTotal: -1284, + from: { + accountID: 2, + avatar: 'https://d2k5nsl2zxldvw.cloudfront.net/images/avatars/default-avatar_16.png', + displayName: 'Test User', + }, + to: { + accountID: 2, + avatar: 'https://d2k5nsl2zxldvw.cloudfront.net/images/avatars/default-avatar_16.png', + displayName: 'Test User', + }, + transactions: [ + { + ...mockTransaction, + transactionID: '2', + reportID: '515146912679680', + keyForList: '2', + }, + ], + groupedBy: 'expense-report', + keyForList: '515146912679680', + action: CONST.SEARCH.ACTION_TYPES.VIEW, +}; + const mockReport: TransactionReportGroupListItemType = { accountID: 1, chatReportID: '4735435600700077', @@ -324,3 +413,232 @@ describe('TransactionGroupListItem', () => { expect(screen.getByTestId('ReportSearchHeader')).toBeTruthy(); }); }); + +describe('Empty Report Selection', () => { + const mockOnSelectRow = jest.fn(); + const mockOnCheckboxPress = jest.fn(); + + beforeAll(() => { + Onyx.init({ + keys: ONYXKEYS, + evictableKeys: [ONYXKEYS.COLLECTION.REPORT_ACTIONS], + }); + jest.spyOn(NativeNavigation, 'useRoute').mockReturnValue({key: '', name: ''}); + }); + + beforeEach(() => { + jest.clearAllMocks(); + mockOnSelectRow.mockClear(); + mockOnCheckboxPress.mockClear(); + return act(async () => { + await Onyx.clear(); + await waitForBatchedUpdatesWithAct(); + }); + }); + + const defaultProps: TransactionGroupListItemProps = { + item: mockEmptyReport, + showTooltip: false, + onSelectRow: mockOnSelectRow, + onCheckboxPress: mockOnCheckboxPress, + searchType: CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT, + canSelectMultiple: true, + }; + + function TestWrapper({children}: {children: React.ReactNode}) { + return ( + + + {children} + + + ); + } + + const renderTransactionGroupListItem = () => { + return render( + , + {wrapper: TestWrapper}, + ); + }; + + it('should render an empty report with checkbox', async () => { + renderTransactionGroupListItem(); + await waitForBatchedUpdatesWithAct(); + + // Then the empty report should be rendered with a checkbox + expect(screen.getByRole(CONST.ROLE.CHECKBOX)).toBeTruthy(); + expect(screen.getByRole(CONST.ROLE.CHECKBOX)).not.toBeChecked(); + expect(screen.getByTestId('ReportSearchHeader')).toBeTruthy(); + expect(screen.getByTestId('TotalCell')).toBeTruthy(); + expect(screen.getByTestId('ActionCell')).toBeTruthy(); + }); + + it('should call onCheckboxPress when checkbox is clicked on an empty report', async () => { + renderTransactionGroupListItem(); + await waitForBatchedUpdatesWithAct(); + + // When clicking on the empty report checkbox + const checkbox = screen.getByRole(CONST.ROLE.CHECKBOX); + expect(checkbox).not.toBeChecked(); + + fireEvent.press(checkbox); + await waitForBatchedUpdatesWithAct(); + + // Then onCheckboxPress should be called with the empty report and undefined (for groupBy reports) + expect(mockOnCheckboxPress).toHaveBeenCalledTimes(1); + expect(mockOnCheckboxPress).toHaveBeenCalledWith(mockEmptyReport, undefined); + }); + + it('should call onCheckboxPress multiple times when checkbox is clicked multiple times', async () => { + renderTransactionGroupListItem(); + await waitForBatchedUpdatesWithAct(); + + const checkbox = screen.getByRole(CONST.ROLE.CHECKBOX); + + // First click + fireEvent.press(checkbox); + await waitForBatchedUpdatesWithAct(); + expect(mockOnCheckboxPress).toHaveBeenCalledTimes(1); + + // Second click + fireEvent.press(checkbox); + await waitForBatchedUpdatesWithAct(); + + // Then onCheckboxPress should be called twice + expect(mockOnCheckboxPress).toHaveBeenCalledTimes(2); + }); + + it('should not show expandable content for an empty report', async () => { + renderTransactionGroupListItem(); + await waitForBatchedUpdatesWithAct(); + + // Empty reports should not have expandable transaction content + // The AnimatedCollapsible content should not be visible + const collapsibleContent = screen.queryByTestId(CONST.ANIMATED_COLLAPSIBLE_CONTENT_TEST_ID); + + // The collapsible content should not be rendered for empty reports + expect(collapsibleContent).toBeNull(); + }); + + it('should handle selecting both empty and non-empty reports', async () => { + // First render and select an empty report + const {unmount: unmountEmpty} = renderTransactionGroupListItem(); + await waitForBatchedUpdatesWithAct(); + + const emptyCheckbox = screen.getByRole(CONST.ROLE.CHECKBOX); + expect(emptyCheckbox).not.toBeChecked(); + + fireEvent.press(emptyCheckbox); + await waitForBatchedUpdatesWithAct(); + + expect(mockOnCheckboxPress).toHaveBeenCalledTimes(1); + expect(mockOnCheckboxPress).toHaveBeenCalledWith(mockEmptyReport, undefined); + + unmountEmpty(); + mockOnCheckboxPress.mockClear(); + + // Render and select a non-empty report + const nonEmptyProps: TransactionGroupListItemProps = { + ...defaultProps, + item: mockNonEmptyReport, + }; + + const {unmount: unmountNonEmpty} = render( + , + {wrapper: TestWrapper}, + ); + await waitForBatchedUpdatesWithAct(); + + const nonEmptyCheckbox = screen.getByRole(CONST.ROLE.CHECKBOX); + expect(nonEmptyCheckbox).not.toBeChecked(); + + fireEvent.press(nonEmptyCheckbox); + await waitForBatchedUpdatesWithAct(); + + expect(mockOnCheckboxPress).toHaveBeenCalledTimes(1); + expect(mockOnCheckboxPress).toHaveBeenCalledWith(mockNonEmptyReport, undefined); + + unmountNonEmpty(); + }); + + it('should track the number of checkbox presses for multiple selections', async () => { + renderTransactionGroupListItem(); + await waitForBatchedUpdatesWithAct(); + + const checkbox = screen.getByRole(CONST.ROLE.CHECKBOX); + + for (let i = 1; i <= 3; i++) { + fireEvent.press(checkbox); + await waitForBatchedUpdatesWithAct(); + expect(mockOnCheckboxPress).toHaveBeenCalledTimes(i); + } + + expect(mockOnCheckboxPress).toHaveBeenNthCalledWith(1, mockEmptyReport, undefined); + expect(mockOnCheckboxPress).toHaveBeenNthCalledWith(2, mockEmptyReport, undefined); + expect(mockOnCheckboxPress).toHaveBeenNthCalledWith(3, mockEmptyReport, undefined); + }); + + it('should show expandable content for non-empty reports', async () => { + const nonEmptyProps: TransactionGroupListItemProps = { + ...defaultProps, + item: mockNonEmptyReport, + }; + + render( + , + {wrapper: TestWrapper}, + ); + await waitForBatchedUpdatesWithAct(); + + // Non-empty reports should have an expand button + const expandButton = screen.getByLabelText('Expand'); + expect(expandButton).toBeTruthy(); + + // Initially, the collapsible content should not be visible + let collapsibleContent = screen.queryByTestId(CONST.ANIMATED_COLLAPSIBLE_CONTENT_TEST_ID); + expect(collapsibleContent).toBeNull(); + + // Click the expand button + fireEvent.press(expandButton); + await waitForBatchedUpdatesWithAct(); + + // After expanding, the collapsible content should be visible + collapsibleContent = screen.queryByTestId(CONST.ANIMATED_COLLAPSIBLE_CONTENT_TEST_ID); + expect(collapsibleContent).toBeTruthy(); + + // The button label should change to 'Collapse' + const collapseButton = screen.getByLabelText('Collapse'); + expect(collapseButton).toBeTruthy(); + + // Click the collapse button + fireEvent.press(collapseButton); + await waitForBatchedUpdatesWithAct(); + + // The button label should change back to 'Expand' + const expandButtonAgain = screen.getByLabelText('Expand'); + expect(expandButtonAgain).toBeTruthy(); + }); + + it('should not show expand button for empty reports', async () => { + renderTransactionGroupListItem(); + await waitForBatchedUpdatesWithAct(); + + // Empty reports should have an expand button but it should be disabled + const expandButton = screen.queryByLabelText('Expand'); + expect(expandButton).toBeTruthy(); + + // The collapsible content should not be rendered for empty reports + const collapsibleContent = screen.queryByTestId(CONST.ANIMATED_COLLAPSIBLE_CONTENT_TEST_ID); + expect(collapsibleContent).toBeNull(); + }); +});