diff --git a/src/hooks/useDeleteTransactions.ts b/src/hooks/useDeleteTransactions.ts index 11c2571a92f1..ed31a47da415 100644 --- a/src/hooks/useDeleteTransactions.ts +++ b/src/hooks/useDeleteTransactions.ts @@ -9,6 +9,7 @@ import {deleteTrackExpense} from '@libs/actions/IOU/TrackExpense'; import initSplitExpense from '@libs/actions/SplitExpenses'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import {calculateAmount as calculateIOUAmount} from '@libs/IOUUtils'; +import Log from '@libs/Log'; import {getOriginalMessage, isActionableTrackExpense, isMoneyRequestAction, isTrackExpenseAction} from '@libs/ReportActionsUtils'; import {isArchivedReport, isExpenseReport, isInvoiceReport, isIOUReport, isSelfDM} from '@libs/ReportUtils'; import type {SearchGroupKey} from '@libs/SearchUIUtils'; @@ -327,11 +328,13 @@ function useDeleteTransactions({report, reportActions, policy}: UseDeleteTransac }); } - for (const {transactionID, action} of nonSplitTransactions) { + for (const {transactionID, action, transaction} of nonSplitTransactions) { + // Some expenses can have no IOU action, but the API can still delete them by transactionID if (!action) { - continue; + Log.info('[useDeleteTransactions] Deleting expense without an IOU action', false, {transactionID, reportID: transaction?.reportID}); } - const iouReportID = isMoneyRequestAction(action) ? action?.reportID : undefined; + + const iouReportID = isMoneyRequestAction(action) ? action?.reportID : transaction?.reportID; const candidateIOUReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`]; // For self-DM tracks and split bills, action.reportID resolves to a chat report, not an IOU/expense report. // Invoice reports also carry the money request action; without them the optimistic delete would run with an @@ -408,7 +411,7 @@ function useDeleteTransactions({report, reportActions, policy}: UseDeleteTransac getCurrencyDecimals, }); deletedTransactionIDs.push(transactionID); - if (action.childReportID) { + if (action?.childReportID) { deletedTransactionThreadReportIDs.add(action.childReportID); } } diff --git a/src/libs/API/parameters/DeleteMoneyRequestParams.ts b/src/libs/API/parameters/DeleteMoneyRequestParams.ts index b44223905e8c..e5524eb9d6a6 100644 --- a/src/libs/API/parameters/DeleteMoneyRequestParams.ts +++ b/src/libs/API/parameters/DeleteMoneyRequestParams.ts @@ -1,6 +1,6 @@ type DeleteMoneyRequestParams = { transactionID: string | undefined; - reportActionID: string; + reportActionID?: string; }; export default DeleteMoneyRequestParams; diff --git a/src/libs/actions/IOU/DeleteMoneyRequest.ts b/src/libs/actions/IOU/DeleteMoneyRequest.ts index 7534053c8f9d..ce99815845de 100644 --- a/src/libs/actions/IOU/DeleteMoneyRequest.ts +++ b/src/libs/actions/IOU/DeleteMoneyRequest.ts @@ -64,7 +64,7 @@ type PrepareToCleanUpMoneyRequestResult = { type DeleteMoneyRequestFunctionParams = { transactionID: string | undefined; - reportAction: OnyxTypes.ReportAction; + reportAction: OnyxTypes.ReportAction | undefined; transactions: OnyxCollection; violations: OnyxCollection; iouReport: OnyxEntry; @@ -89,7 +89,7 @@ type DeleteMoneyRequestFunctionParams = { type PrepareToCleanUpMoneyRequestParams = { transactionID: string; - reportAction: OnyxTypes.ReportAction; + reportAction: OnyxTypes.ReportAction | undefined; transactionThreadReport: OnyxEntry; iouReport: OnyxEntry; chatReport: OnyxEntry; @@ -136,25 +136,29 @@ function prepareToCleanUpMoneyRequest({ const shouldDeleteTransactionThread = !!transactionThreadReport?.reportID; // STEP 3: Update the IOU reportAction and decide if the iouReport should be deleted. We delete the iouReport if there are no visible comments left in the report. - const updatedReportAction = { - [reportAction.reportActionID]: { - pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, - previousMessage: reportAction.message, - message: [ - { - type: 'COMMENT', - html: '', - text: '', - isEdited: true, - isDeletedParentAction: shouldDeleteTransactionThread, - }, - ], - originalMessage: { - IOUTransactionID: shouldRemoveIOUTransactionID ? null : transactionID, - }, - errors: null, - }, - } as Record>; + const updatedReportAction = ( + reportAction + ? { + [reportAction.reportActionID]: { + pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + previousMessage: reportAction.message, + message: [ + { + type: 'COMMENT', + html: '', + text: '', + isEdited: true, + isDeletedParentAction: shouldDeleteTransactionThread, + }, + ], + originalMessage: { + IOUTransactionID: shouldRemoveIOUTransactionID ? null : transactionID, + }, + errors: null, + }, + } + : {} + ) as Record>; let canUserPerformWriteAction = true; if (chatReport) { @@ -167,7 +171,7 @@ function prepareToCleanUpMoneyRequest({ if (shouldDeleteIOUReport) { for (const [reportActionID, reportActionData] of Object.entries(iouReportActions ?? {})) { if ( - reportAction.reportActionID === reportActionID || + reportAction?.reportActionID === reportActionID || reportActionData.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || reportActionData.actionName === 'CREATED' || !reportActionData.message || @@ -178,7 +182,7 @@ function prepareToCleanUpMoneyRequest({ updatedReportAction[reportActionID] = { pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, - previousMessage: reportAction.message, + previousMessage: reportAction?.message, message: [ { type: 'COMMENT', @@ -256,16 +260,9 @@ function prepareToCleanUpMoneyRequest({ } else if (iouReport && !canEditTotal) { updatedIOUReport = {...iouReport}; } else { - updatedIOUReport = updateIOUOwnerAndTotal( - iouReport, - reportAction.actorAccountID ?? CONST.DEFAULT_NUMBER_ID, - amountDiff, - currency, - true, - false, - isTransactionOnHold, - unheldAmountDiff, - ); + // Without an IOU action, treat the report owner as the requester + const actorAccountID = reportAction ? reportAction.actorAccountID : iouReport?.ownerAccountID; + updatedIOUReport = updateIOUOwnerAndTotal(iouReport, actorAccountID ?? CONST.DEFAULT_NUMBER_ID, amountDiff, currency, true, false, isTransactionOnHold, unheldAmountDiff); // Match `updateIOUOwnerAndTotal`'s early-return guard so future refactors of that helper don't silently flip this flag. didUpdateOptimisticTotal = !!iouReport && currency === iouReport.currency; } @@ -344,7 +341,7 @@ function prepareToCleanUpMoneyRequest({ */ function getNavigationUrlOnMoneyRequestDelete( transactionID: string | undefined, - reportAction: OnyxTypes.ReportAction, + reportAction: OnyxTypes.ReportAction | undefined, transactionThreadReport: OnyxEntry, iouReport: OnyxEntry, chatReport: OnyxEntry, @@ -986,11 +983,13 @@ function deleteMoneyRequest({ : { onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`, - value: { - [reportAction.reportActionID]: { - pendingAction: null, - }, - }, + value: reportAction + ? { + [reportAction.reportActionID]: { + pendingAction: null, + }, + } + : {}, }, ]; @@ -1044,7 +1043,7 @@ function deleteMoneyRequest({ const originalReportActionsUpdate = {} as Record>; if (shouldDeleteIOUReport) { for (const action of Object.values(iouReportActions ?? {})) { - if (action.reportActionID === reportAction.reportActionID) { + if (action.reportActionID === reportAction?.reportActionID) { continue; } originalReportActionsUpdate[action.reportActionID] = { @@ -1060,11 +1059,13 @@ function deleteMoneyRequest({ key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport.reportID}`, value: { ...originalReportActionsUpdate, - [reportAction.reportActionID]: { - ...reportAction, - pendingAction: null, - errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericDeleteFailureMessage', errorKey), - }, + ...(reportAction && { + [reportAction.reportActionID]: { + ...reportAction, + pendingAction: null, + errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericDeleteFailureMessage', errorKey), + }, + }), }, }); @@ -1117,7 +1118,7 @@ function deleteMoneyRequest({ const parameters: DeleteMoneyRequestParams = { transactionID, - reportActionID: reportAction.reportActionID, + reportActionID: reportAction?.reportActionID, }; // A group row in a grouped search outlives its child transactions, so flagging the group's own snapshot entry diff --git a/tests/unit/hooks/useDeleteTransactions.test.ts b/tests/unit/hooks/useDeleteTransactions.test.ts index 4544629335ec..d6dbc11fa8dd 100644 --- a/tests/unit/hooks/useDeleteTransactions.test.ts +++ b/tests/unit/hooks/useDeleteTransactions.test.ts @@ -4,6 +4,7 @@ import OnyxListItemProvider from '@components/OnyxListItemProvider'; import useDeleteTransactions from '@hooks/useDeleteTransactions'; +import {WRITE_COMMANDS} from '@libs/API/types'; import {buildOptimisticIOUReportAction} from '@libs/ReportUtils'; import CONST from '@src/CONST'; @@ -15,9 +16,9 @@ import type Transaction from '@src/types/onyx/Transaction'; import Onyx from 'react-native-onyx'; -import {createSelfDM} from '../../utils/collections/reports'; +import {createExpenseReport, createSelfDM} from '../../utils/collections/reports'; import getOnyxValue from '../../utils/getOnyxValue'; -import {getCurrencyDecimalsLocal, getGlobalFetchMock} from '../../utils/TestHelper'; +import {expectAPICommandToHaveBeenCalled, expectAPICommandToHaveBeenCalledWith, getCurrencyDecimalsLocal, getGlobalFetchMock} from '../../utils/TestHelper'; import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; jest.mock('@libs/Navigation/Navigation', () => ({ @@ -107,4 +108,39 @@ describe('useDeleteTransactions', () => { // And the report actions are keyed on the self-DM report, not on a missing IOU report await expect(getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}undefined`)).resolves.toBeFalsy(); }); + + it('deletes an expense that has no IOU action instead of silently skipping it', async () => { + // Given an expense on an expense report whose IOU action was never created + const expenseReport = createExpenseReport(1); + const transactionID = 'transaction'; + const transaction: Transaction = { + transactionID, + amount: -10000, + currency: 'USD', + merchant: 'Test Merchant', + comment: {comment: 'Test comment'}, + created: DateUtils.getDBTime(), + reportID: expenseReport.reportID, + }; + + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`, expenseReport); + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, transaction); + await waitForBatchedUpdates(); + + const {result} = renderHook(() => useDeleteTransactions({report: expenseReport, reportActions: []}), {wrapper: OnyxListItemProvider}); + await waitForBatchedUpdates(); + + // When the expense is bulk-deleted from Search + act(() => { + result.current.deleteTransactions([transactionID], {}, {}); + }); + await waitForBatchedUpdates(); + + // Then DeleteMoneyRequest is sent with the transaction ID, since the API deletes expenses without an IOU action + expectAPICommandToHaveBeenCalled(WRITE_COMMANDS.DELETE_MONEY_REQUEST, 1); + expectAPICommandToHaveBeenCalledWith(WRITE_COMMANDS.DELETE_MONEY_REQUEST, 0, {transactionID}); + + // And the expense is removed from Onyx once the request succeeds + await expect(getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`)).resolves.toBeFalsy(); + }); }); diff --git a/tests/unit/hooks/useSearchBulkActionsDeleteTest.ts b/tests/unit/hooks/useSearchBulkActionsDeleteTest.ts index a5a1cf9863d9..acdce7f4d86e 100644 --- a/tests/unit/hooks/useSearchBulkActionsDeleteTest.ts +++ b/tests/unit/hooks/useSearchBulkActionsDeleteTest.ts @@ -416,17 +416,15 @@ describe('useSearchBulkActions - delete unreported expenses', () => { }); }); - it('does NOT call deleteMoneyRequest when the IOU action is absent from both snapshot and Onyx REPORT_ACTIONS', async () => { + it('calls deleteMoneyRequest without a report action when the IOU action is absent from both snapshot and Onyx REPORT_ACTIONS', async () => { /** * Given: an unreported expense with no IOU action anywhere (neither in the * search snapshot nor in the real Onyx REPORT_ACTIONS collection). * * When: the user confirms bulk delete. * - * Then: deleteMoneyRequest is NOT called — the transaction is silently skipped. - * - * This is a known graceful no-op: without the action there is no IOUReportID - * and nothing to delete server-side. + * Then: deleteMoneyRequest is still called for the transaction, without a report action, + * because the API deletes the expense by transactionID alone. */ // No snapshot data at all. @@ -462,11 +460,14 @@ describe('useSearchBulkActions - delete unreported expenses', () => { }); await waitFor(() => { - expect(mockShowConfirmModal).toHaveBeenCalled(); + expect(deleteMoneyRequest).toHaveBeenCalledTimes(1); + expect(deleteMoneyRequest).toHaveBeenCalledWith( + expect.objectContaining({ + transactionID: TRANSACTION_ID, + reportAction: undefined, + }), + ); }); - - // No deleteMoneyRequest call — no action was found. - expect(deleteMoneyRequest).not.toHaveBeenCalled(); }); it('passes the report and reportActions from the search snapshot to deleteAppReport when the report is not in Onyx', async () => {