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
15 changes: 10 additions & 5 deletions src/libs/ReportActionsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2006,16 +2006,20 @@ function getOneTransactionThreadReportAction(
return iouRequestAction;
}

/**
* Resolves the transaction thread reportID from the IOU action the thread is derived from.
* Since we don't always create the transaction thread optimistically, we fall back to CONST.FAKE_REPORT_ID.
*/
function getTransactionThreadReportIDFromAction(reportAction: ReportAction<'IOU'> | undefined): string | undefined {
return reportAction ? (reportAction.childReportID ?? CONST.FAKE_REPORT_ID) : undefined;
Comment thread
lorretheboy marked this conversation as resolved.
Resolved
}

/**
* Gets the reportID for the transaction thread associated with a report by iterating over the reportActions and identifying the IOU report actions.
* Returns a reportID if there is exactly one transaction thread for the report, and undefined otherwise.
*/
function getOneTransactionThreadReportID(...args: Parameters<typeof getOneTransactionThreadReportAction>): string | undefined {
const reportAction = getOneTransactionThreadReportAction(...args);
if (reportAction) {
// Since we don't always create transaction thread optimistically, we return CONST.FAKE_REPORT_ID
return reportAction.childReportID ?? CONST.FAKE_REPORT_ID;
}
return getTransactionThreadReportIDFromAction(getOneTransactionThreadReportAction(...args));
}

/**
Expand Down Expand Up @@ -4896,6 +4900,7 @@ export {
getNumberOfMoneyRequests,
getOneTransactionThreadReportAction,
getOneTransactionThreadReportID,
getTransactionThreadReportIDFromAction,
getOriginalMessage,
getAddedApprovalRuleMessage,
getDeletedApprovalRuleMessage,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@ import {getMovedReportID} from '@libs/ModifiedExpenseMessage';
import {isTrackOnboardingChoice} from '@libs/OnboardingUtils';
import {
getLinkedTransactionID,
getOneTransactionThreadReportAction,
getOneTransactionThreadReportID,
getOriginalMessage,
getReportAction,
getTransactionThreadReportIDFromAction,
isActionOfType,
isDeletedAction,
isMemberChangeAction,
withDEWRoutedActionsObject,
} from '@libs/ReportActionsUtils';
Expand Down Expand Up @@ -223,30 +224,16 @@ function BaseReportActionContextMenu({
const parentReportAction = getReportAction(childReport?.parentReportID, childReport?.parentReportActionID);
const {reportActions: paginatedReportActions} = usePaginatedReportActions(childReport?.reportID);
const currentUserPersonalDetails = useCurrentUserPersonalDetails();
const transactionThreadReportID = useMemo(
() => getOneTransactionThreadReportID(childReport, childChatReport, paginatedReportActions ?? [], isOffline),
const transactionThreadReportAction = useMemo(
() => getOneTransactionThreadReportAction(childReport, childChatReport, paginatedReportActions ?? [], isOffline),
[paginatedReportActions, isOffline, childReport, childChatReport],
);

const [transactionThreadReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(transactionThreadReportID)}`);
const transactionThreadReportID = getTransactionThreadReportIDFromAction(transactionThreadReportAction);

const isMoneyRequestReport = useMemo(() => ReportUtilsIsMoneyRequestReport(childReport), [childReport]);
const isInvoiceReport = useMemo(() => ReportUtilsIsInvoiceReport(childReport), [childReport]);

const requestParentReportAction = useMemo(() => {
if (isMoneyRequestReport || isInvoiceReport) {
if (transactionThreadReportID === CONST.FAKE_REPORT_ID) {
return Object.values(childReportActions ?? {}).find((action) => action.actionName === CONST.REPORT.ACTIONS.TYPE.IOU && !isDeletedAction(action));
}
if (!paginatedReportActions || !transactionThreadReport?.parentReportActionID) {
return undefined;
}
return paginatedReportActions.find((action) => action.reportActionID === transactionThreadReport.parentReportActionID);
}
return parentReportAction;
}, [parentReportAction, isMoneyRequestReport, isInvoiceReport, paginatedReportActions, transactionThreadReport?.parentReportActionID, transactionThreadReportID, childReportActions]);

const moneyRequestAction = transactionThreadReportID ? requestParentReportAction : parentReportAction;
const moneyRequestAction = transactionThreadReportAction ?? parentReportAction;
const isChildReportArchived = useReportIsArchived(childReport?.reportID);
const isParentReportArchived = useReportIsArchived(childReport?.parentReportID);
const [parentReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${childReport?.parentReportID}`);
Expand Down
178 changes: 176 additions & 2 deletions tests/ui/components/BaseReportActionContextMenuTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import BaseReportActionContextMenu from '@pages/inbox/report/ContextMenu/BaseRep
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {PersonalDetailsList} from '@src/types/onyx';
import type {PersonalDetailsList, ReportAction} from '@src/types/onyx';

import React from 'react';
import Onyx from 'react-native-onyx';
Expand Down Expand Up @@ -85,7 +85,10 @@ jest.mock('@hooks/useLocalize', () => () => ({
getLocalDateFromDatetime: jest.fn(),
}));
jest.mock('@hooks/useNetwork', () => () => ({isOffline: false}));
jest.mock('@hooks/usePaginatedReportActions', () => () => ({reportActions: []}));

// Held in a container so individual tests can control what `usePaginatedReportActions` returns for the child report.
const mockPaginatedReportActions: {reportActions: ReportAction[]} = {reportActions: []};
jest.mock('@hooks/usePaginatedReportActions', () => () => ({reportActions: mockPaginatedReportActions.reportActions}));
jest.mock('@hooks/useReportIsArchived', () => () => false);
jest.mock('@hooks/useResponsiveLayout', () => () => ({shouldUseNarrowLayout: true, isSmallScreenWidth: false}));
jest.mock(
Expand All @@ -106,9 +109,11 @@ jest.mock('@userActions/Session', () => ({
callFunctionIfActionIsAllowed: (fn: () => void) => fn,
}));

const mockShowDeleteModal = jest.fn<void, unknown[]>();
jest.mock('@pages/inbox/report/ContextMenu/ReportActionContextMenu', () => ({
hideContextMenu: jest.fn((_: boolean, onHideCallback?: () => void) => onHideCallback?.()),
showContextMenu: jest.fn(),
showDeleteModal: (...args: unknown[]) => mockShowDeleteModal(...args),
}));

const mockUnholdRequest = jest.fn();
Expand Down Expand Up @@ -272,6 +277,7 @@ describe('BaseReportActionContextMenu edit action', () => {
beforeEach(async () => {
jest.clearAllMocks();
mockContextMenuItemProps.length = 0;
mockPaginatedReportActions.reportActions = [];
});

beforeAll(() => {
Expand Down Expand Up @@ -354,6 +360,7 @@ describe('BaseReportActionContextMenu hold/unhold action', () => {
beforeEach(async () => {
jest.clearAllMocks();
mockContextMenuItemProps.length = 0;
mockPaginatedReportActions.reportActions = [];
});

beforeAll(() => {
Expand Down Expand Up @@ -412,3 +419,170 @@ describe('BaseReportActionContextMenu hold/unhold action', () => {
);
});
});

const dmChatReportID = '600';
const previewActionID = 'previewAction';
const previewIOUReportID = '700';
const iouActionID = 'iouAction700';
const transactionThreadReportID = '800';
const expenseTransactionID = '900';

const iouCreateAction: ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.IOU> = {
reportActionID: iouActionID,
actionName: CONST.REPORT.ACTIONS.TYPE.IOU,
actorAccountID: currentUserAccountID,
reportID: previewIOUReportID,
childReportID: transactionThreadReportID,
created: '2025-03-05 16:34:27',
message: [{type: 'COMMENT', html: 'Expense', text: 'Expense'}],
originalMessage: {
IOUReportID: previewIOUReportID,
IOUTransactionID: expenseTransactionID,
type: CONST.IOU.REPORT_ACTION_TYPE.CREATE,
amount: 1000,
currency: CONST.CURRENCY.USD,
},
};

/**
* Seeds a 1:1 chat containing a report preview action for a one-transaction IOU report, which is the shape the context
* menu sees when long-pressing an expense preview in a chat.
*/
async function seedMoneyRequestPreviewData({
Comment thread
lorretheboy marked this conversation as resolved.
Resolved
transactionThreadReport,
iouAction = iouCreateAction,
}: {
/** When omitted, no transaction thread report exists in Onyx (the state right after clearing the cache). */
transactionThreadReport?: Record<string, unknown>;
iouAction?: ReportAction;
}) {
await Onyx.clear();

await Onyx.merge(ONYXKEYS.SESSION, {accountID: currentUserAccountID, email: currentUserLogin});
await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, testPersonalDetails);
Comment thread
lorretheboy marked this conversation as resolved.
Resolved

// The 1:1 chat holding the report preview action that gets long-pressed
await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${dmChatReportID}`, {
reportID: dmChatReportID,
type: CONST.REPORT.TYPE.CHAT,
});
await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${dmChatReportID}`, {
[previewActionID]: {
reportActionID: previewActionID,
actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW,
actorAccountID: currentUserAccountID,
reportID: dmChatReportID,
childReportID: previewIOUReportID,
created: '2025-03-05 16:34:27',
message: [{type: 'COMMENT', html: 'Expense preview', text: 'Expense preview'}],
originalMessage: {linkedReportID: previewIOUReportID},
},
});

// The IOU report the preview points at, holding exactly one IOU action
await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${previewIOUReportID}`, {
reportID: previewIOUReportID,
type: CONST.REPORT.TYPE.IOU,
chatReportID: dmChatReportID,
parentReportID: dmChatReportID,
parentReportActionID: previewActionID,
ownerAccountID: currentUserAccountID,
managerID: currentUserAccountID,
stateNum: CONST.REPORT.STATE_NUM.OPEN,
statusNum: CONST.REPORT.STATUS_NUM.OPEN,
});
await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${previewIOUReportID}`, {[iouActionID]: iouAction});

if (transactionThreadReport) {
await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReportID}`, {
reportID: transactionThreadReportID,
type: CONST.REPORT.TYPE.CHAT,
parentReportID: previewIOUReportID,
...transactionThreadReport,
});
}

await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${expenseTransactionID}`, {
transactionID: expenseTransactionID,
reportID: previewIOUReportID,
amount: 1000,
currency: CONST.CURRENCY.USD,
});

mockPaginatedReportActions.reportActions = [iouAction];
await waitForBatchedUpdates();
}

async function renderMenuAndPressDelete() {
Comment thread
lorretheboy marked this conversation as resolved.
Resolved
render(
<BaseReportActionContextMenu
reportID={dmChatReportID}
originalReportID={dmChatReportID}
reportActionID={previewActionID}
isVisible
/>,
);

const onPress = await getContextMenuItemOnPress(CONST.SENTRY_LABEL.CONTEXT_MENU.DELETE);
await act(async () => {
onPress({});
});
}

function expectDeleteTargetedTheIOUAction() {
Comment thread
lorretheboy marked this conversation as resolved.
Resolved
expect(mockShowDeleteModal).toHaveBeenCalledTimes(1);
expect(mockShowDeleteModal).toHaveBeenCalledWith(previewIOUReportID, expect.objectContaining({reportActionID: iouActionID, actionName: CONST.REPORT.ACTIONS.TYPE.IOU}));

// Regression guard: deleting the REPORT_PREVIEW action instead of the IOU action is what orphaned the expense.
expect(mockShowDeleteModal).not.toHaveBeenCalledWith(expect.anything(), expect.objectContaining({reportActionID: previewActionID}));
}

describe('BaseReportActionContextMenu money request action resolution', () => {
beforeEach(async () => {
jest.clearAllMocks();
mockContextMenuItemProps.length = 0;
mockPaginatedReportActions.reportActions = [];
});

beforeAll(() => {
Onyx.init({keys: ONYXKEYS, evictableKeys: [ONYXKEYS.COLLECTION.REPORT_ACTIONS]});
});

it('resolves the IOU action when the transaction thread report is missing from Onyx', async () => {
// Right after clearing the cache the transaction thread report has not been re-fetched yet, so its
// parentReportActionID cannot be looked up. The IOU action the thread was derived from must still be used.
await seedMoneyRequestPreviewData({});

await renderMenuAndPressDelete();

expectDeleteTargetedTheIOUAction();
});

it('resolves the IOU action when the transaction thread report holds a stale parentReportActionID', async () => {
// During the optimistic -> server reconciliation of a newly created expense, the thread report can still point at
// the optimistic action ID after that action has been replaced in the report actions.
await seedMoneyRequestPreviewData({transactionThreadReport: {parentReportActionID: 'staleOptimisticActionID'}});

await renderMenuAndPressDelete();

expectDeleteTargetedTheIOUAction();
});

it('resolves the IOU action when the transaction thread report is fully loaded', async () => {
await seedMoneyRequestPreviewData({transactionThreadReport: {parentReportActionID: iouActionID}});

await renderMenuAndPressDelete();

expectDeleteTargetedTheIOUAction();
});

it('resolves the IOU action when the transaction thread was never created optimistically', async () => {
// No childReportID on the IOU action means the transaction thread reportID falls back to CONST.FAKE_REPORT_ID.
const iouActionWithoutThread = {...iouCreateAction, childReportID: undefined};
await seedMoneyRequestPreviewData({iouAction: iouActionWithoutThread});

await renderMenuAndPressDelete();

expectDeleteTargetedTheIOUAction();
});
});
29 changes: 29 additions & 0 deletions tests/unit/ReportActionsUtilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import {
getReportActionActorAccountID,
getRequireCompanyCardsEnabledMessage,
getSendMoneyFlowAction,
getTransactionThreadReportIDFromAction,
getUnassignedCompanyCardMessage,
getUpdateACHAccountMessage,
getUpdatedAutoHarvestingMessage,
Expand Down Expand Up @@ -591,6 +592,34 @@ describe('ReportActionsUtils', () => {
);
expect(result).toEqual(linkedActionWithChildReportID);
});

describe('getTransactionThreadReportIDFromAction', () => {
it('should return the childReportID of the action', () => {
expect(getTransactionThreadReportIDFromAction(linkedActionWithChildReportID)).toEqual('existingChildReportID');
});

it('should return CONST.FAKE_REPORT_ID when the action has no childReportID, because the transaction thread is not always created optimistically', () => {
expect(getTransactionThreadReportIDFromAction(linkedActionWithoutChildReportID)).toEqual(CONST.FAKE_REPORT_ID);
});

it('should return undefined when there is no action', () => {
expect(getTransactionThreadReportIDFromAction(undefined)).toBeUndefined();
});

it('should produce the same reportID as getOneTransactionThreadReportID for the same inputs', () => {
// getOneTransactionThreadReportID is defined in terms of this helper, so callers that already hold the
// action can derive the ID from it instead of re-running the O(n) scan over the report actions.
const args: Parameters<typeof getOneTransactionThreadReportID> = [
mockedReports[IOUReportID],
mockedReports[mockChatReportID],
[linkedActionWithChildReportID],
false,
[IOUTransactionID],
];

expect(getTransactionThreadReportIDFromAction(ReportActionsUtils.getOneTransactionThreadReportAction(...args))).toEqual(getOneTransactionThreadReportID(...args));
});
});
});

describe('getOneTransactionThreadReportID', () => {
Expand Down
Loading