Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions src/hooks/useDeleteTransactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -408,7 +411,7 @@ function useDeleteTransactions({report, reportActions, policy}: UseDeleteTransac
getCurrencyDecimals,
});
deletedTransactionIDs.push(transactionID);
if (action.childReportID) {
if (action?.childReportID) {
deletedTransactionThreadReportIDs.add(action.childReportID);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/libs/API/parameters/DeleteMoneyRequestParams.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
type DeleteMoneyRequestParams = {
transactionID: string | undefined;
reportActionID: string;
reportActionID?: string;
};

export default DeleteMoneyRequestParams;
93 changes: 47 additions & 46 deletions src/libs/actions/IOU/DeleteMoneyRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ type PrepareToCleanUpMoneyRequestResult = {

type DeleteMoneyRequestFunctionParams = {
transactionID: string | undefined;
reportAction: OnyxTypes.ReportAction;
reportAction: OnyxTypes.ReportAction | undefined;
transactions: OnyxCollection<OnyxTypes.Transaction>;
violations: OnyxCollection<OnyxTypes.TransactionViolations>;
iouReport: OnyxEntry<OnyxTypes.Report>;
Expand All @@ -89,7 +89,7 @@ type DeleteMoneyRequestFunctionParams = {

type PrepareToCleanUpMoneyRequestParams = {
transactionID: string;
reportAction: OnyxTypes.ReportAction;
reportAction: OnyxTypes.ReportAction | undefined;
transactionThreadReport: OnyxEntry<OnyxTypes.Report>;
iouReport: OnyxEntry<OnyxTypes.Report>;
chatReport: OnyxEntry<OnyxTypes.Report>;
Expand Down Expand Up @@ -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<string, NullishDeep<OnyxTypes.ReportAction>>;
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<string, NullishDeep<OnyxTypes.ReportAction>>;

let canUserPerformWriteAction = true;
if (chatReport) {
Expand All @@ -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 ||
Expand All @@ -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',
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -344,7 +341,7 @@ function prepareToCleanUpMoneyRequest({
*/
function getNavigationUrlOnMoneyRequestDelete(
transactionID: string | undefined,
reportAction: OnyxTypes.ReportAction,
reportAction: OnyxTypes.ReportAction | undefined,
transactionThreadReport: OnyxEntry<OnyxTypes.Report>,
iouReport: OnyxEntry<OnyxTypes.Report>,
chatReport: OnyxEntry<OnyxTypes.Report>,
Expand Down Expand Up @@ -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,
},
}
: {},
},
];

Expand Down Expand Up @@ -1044,7 +1043,7 @@ function deleteMoneyRequest({
const originalReportActionsUpdate = {} as Record<string, Partial<OnyxTypes.ReportAction>>;
if (shouldDeleteIOUReport) {
for (const action of Object.values(iouReportActions ?? {})) {
if (action.reportActionID === reportAction.reportActionID) {
if (action.reportActionID === reportAction?.reportActionID) {
continue;
}
originalReportActionsUpdate[action.reportActionID] = {
Expand All @@ -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),
},
}),
},
});

Expand Down Expand Up @@ -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
Expand Down
40 changes: 38 additions & 2 deletions tests/unit/hooks/useDeleteTransactions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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', () => ({
Expand Down Expand Up @@ -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();
});
});
19 changes: 10 additions & 9 deletions tests/unit/hooks/useSearchBulkActionsDeleteTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 () => {
Expand Down
Loading