Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,12 @@ import useOnyx from '@hooks/useOnyx';
import useTransactionsAndViolationsForReport from '@hooks/useTransactionsAndViolationsForReport';

import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID';
import {getThreadReportIDsForTransactions} from '@libs/MoneyRequestReportUtils';
import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute';
import Navigation from '@libs/Navigation/Navigation';
import {getIOUActionForReportID} from '@libs/ReportActionsUtils';
import {getOrCreateTransactionThreadReportID} from '@libs/TransactionThreadNavigationUtils';
import {isDuplicate} from '@libs/TransactionUtils';

import {createTransactionThreadReport} from '@userActions/Report';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import {DYNAMIC_ROUTES} from '@src/ROUTES';
Expand All @@ -31,7 +29,7 @@ function ReviewDuplicatesPrimaryAction({reportID, chatReportID}: SimpleActionPro
const {accountID, email} = useCurrentUserPersonalDetails();
const personalDetails = usePersonalDetails();

const {moneyRequestReport, reportActions, transactionThreadReportID} = useTransactionThreadData(reportID, chatReportID);
const {moneyRequestReport, transactionThreadReportID} = useTransactionThreadData(reportID, chatReportID);
const [policy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${getNonEmptyStringOnyxID(moneyRequestReport?.policyID)}`);
const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED);
const [betas] = useOnyx(ONYXKEYS.BETAS);
Expand All @@ -41,45 +39,42 @@ function ReviewDuplicatesPrimaryAction({reportID, chatReportID}: SimpleActionPro
const {transactions: reportTransactionsMap} = useTransactionsAndViolationsForReport(moneyRequestReport?.reportID);
const transactions = Object.values(reportTransactionsMap);

const duplicateTransaction = transactions.find((reportTransaction) =>
isDuplicate(
reportTransaction,
email ?? '',
accountID,
moneyRequestReport,
ownerLogin,
policy,
allTransactionViolations?.[ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + reportTransaction.transactionID],
),
);
const duplicateIOUAction = getIOUActionForReportID(moneyRequestReport?.reportID, duplicateTransaction?.transactionID);
const duplicateThreadReportID = duplicateIOUAction?.childReportID;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we use getIOUActionForReportID().childReportID instead of the previous getThreadReportIDsForTransactions?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getThreadReportIDsForTransactions looks up the childReportID from the reportActions we pass it, which is the paginated slice from usePaginatedReportActions. getIOUActionForReportID instead reads the full cached report actions (via getAllReportActions), so it still resolves the thread even when the IOU action is outside the currently loaded page — e.g. an older duplicate in a long report. Codex flagged the same thing on the paginated version, so I switched to the full-collection lookup to be safe.

Happy to go back to getThreadReportIDsForTransactions if you'd rather keep it paginated — just let me know.

const [duplicateThreadReportExists] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(duplicateThreadReportID)}`, {selector: (report) => !!report?.reportID});

return (
<Button
variant={CONST.BUTTON_VARIANT.SUCCESS}
onPress={() => {
let threadID: string | undefined | null = transactionThreadReportID;
if (!threadID) {
const duplicateTransaction = transactions.find((reportTransaction) =>
isDuplicate(
reportTransaction,
email ?? '',
accountID,
moneyRequestReport,
ownerLogin,
policy,
allTransactionViolations?.[ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + reportTransaction.transactionID],
),
);
if (duplicateTransaction) {
const existingThreadID = getThreadReportIDsForTransactions(reportActions, [duplicateTransaction]).at(0);
if (existingThreadID) {
threadID = existingThreadID;
} else {
const transactionID = duplicateTransaction.transactionID;
const iouAction = getIOUActionForReportID(moneyRequestReport?.reportID, transactionID);
const createdTransactionThreadReport = createTransactionThreadReport({
introSelected,
currentUserLogin: email ?? '',
currentUserAccountID: accountID,
betas,
iouReport: moneyRequestReport,
iouReportAction: iouAction,
personalDetails,
});
threadID = createdTransactionThreadReport?.reportID;
}
}
}
const threadID =
transactionThreadReportID ??
(duplicateTransaction
? getOrCreateTransactionThreadReportID(
{
threadReportID: duplicateThreadReportID,
threadReportExists: !!duplicateThreadReportExists,
iouReport: moneyRequestReport,
iouReportAction: duplicateIOUAction,
transaction: duplicateTransaction,
},
{introSelected, betas, currentUserEmail: email, currentUserAccountID: accountID, personalDetails},
)
: undefined);
if (threadID) {
Navigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.TRANSACTION_DUPLICATE_REVIEW.getRoute(threadID)));
// Navigate on the microtask queue so the optimistic transaction thread is committed to Onyx before we navigate.
Navigation.setNavigationActionToMicrotaskQueue(() => Navigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.TRANSACTION_DUPLICATE_REVIEW.getRoute(threadID))));
}
}}
>
Expand Down
56 changes: 54 additions & 2 deletions src/libs/TransactionThreadNavigationUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type {Beta, IntroSelected, PersonalDetailsList, Report, ReportAction, Tra

import type {OnyxEntry} from 'react-native-onyx';

import {createTransactionThreadReport} from './actions/Report';
import {createTransactionThreadReport, setOptimisticTransactionThread} from './actions/Report';
import {getIOUActionForReportID} from './ReportActionsUtils';
import {findSelfDMReportID, getReportOrDraftReport} from './ReportUtils';
import {isExpenseUnreported} from './TransactionUtils';
Expand Down Expand Up @@ -82,5 +82,57 @@ function getReportIDToOpenForExpense(expense: TransactionThreadNavigationDescrip
return transactionThreadReport?.reportID ?? reportID;
}

export {getReportIDToOpenForExpense};
/**
* Resolves the transaction thread report to navigate to for a given expense's IOU action: returns the existing
* thread — optimistically materializing it in Onyx when the action references a thread that hasn't been fetched
* yet — or creates a new thread when none exists. Shared by the duplicate-review action and the prev/next carousel.
*/
function getOrCreateTransactionThreadReportID(
{
threadReportID,
threadReportExists,
iouReport,
iouReportAction,
transaction,
}: {
/** The transaction thread report ID from the IOU action's childReportID, if any */
threadReportID: string | undefined;

/** Whether the thread report already exists in Onyx */
threadReportExists: boolean;

/** The expense's parent IOU report */
iouReport: OnyxEntry<Report>;

/** The expense's parent IOU report action */
iouReportAction: OnyxEntry<ReportAction>;

/** The expense transaction */
transaction: OnyxEntry<Transaction>;
},
context: ResolveReportContext,
): string | undefined {
// The thread already exists; it just may not have been fetched into Onyx yet, so set it optimistically.
if (threadReportID) {
if (!threadReportExists) {
setOptimisticTransactionThread(threadReportID, iouReport?.reportID, iouReportAction?.reportActionID, iouReport?.policyID);
}
return threadReportID;
}

// No thread yet, so create it.
const transactionThreadReport = createTransactionThreadReport({
introSelected: context.introSelected,
currentUserLogin: context.currentUserEmail ?? '',
currentUserAccountID: context.currentUserAccountID,
betas: context.betas,
iouReport,
iouReportAction,
transaction,
personalDetails: context.personalDetails,
});
return transactionThreadReport?.reportID;
}

export {getReportIDToOpenForExpense, getOrCreateTransactionThreadReportID};
export type {TransactionThreadNavigationDescriptor};
74 changes: 72 additions & 2 deletions tests/unit/libs/TransactionThreadNavigationUtilsTest.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {createTransactionThreadReport} from '@libs/actions/Report';
import {createTransactionThreadReport, setOptimisticTransactionThread} from '@libs/actions/Report';
import type {TransactionThreadNavigationDescriptor} from '@libs/TransactionThreadNavigationUtils';
import {getReportIDToOpenForExpense} from '@libs/TransactionThreadNavigationUtils';
import {getOrCreateTransactionThreadReportID, getReportIDToOpenForExpense} from '@libs/TransactionThreadNavigationUtils';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
Expand All @@ -18,10 +18,12 @@ jest.mock('@libs/actions/Report', () => {
return {
...actual,
createTransactionThreadReport: jest.fn(() => ({reportID: 'created_thread'})),
setOptimisticTransactionThread: jest.fn(),
};
});

const mockCreateTransactionThreadReport = jest.mocked(createTransactionThreadReport);
const mockSetOptimisticTransactionThread = jest.mocked(setOptimisticTransactionThread);

const CONTEXT = {introSelected: undefined, betas: undefined, currentUserEmail: 'me@test.com', currentUserAccountID: 1, personalDetails: undefined};

Expand Down Expand Up @@ -102,3 +104,71 @@ describe('getReportIDToOpenForExpense', () => {
expect(mockCreateTransactionThreadReport).not.toHaveBeenCalled();
});
});

describe('getOrCreateTransactionThreadReportID', () => {
const iouReport = {reportID: 'parent', policyID: 'policy1'} as Report;

beforeEach(() => {
mockCreateTransactionThreadReport.mockClear();
mockSetOptimisticTransactionThread.mockClear();
});

it('returns the existing thread without side effects when it is already in Onyx', () => {
const reportID = getOrCreateTransactionThreadReportID(
{
threadReportID: 'existing_thread',
threadReportExists: true,
iouReport,
iouReportAction: buildIOUAction('a1', 'existing_thread'),
transaction: buildTransaction('t1', 'parent'),
},
CONTEXT,
);

expect(reportID).toBe('existing_thread');
expect(mockSetOptimisticTransactionThread).not.toHaveBeenCalled();
expect(mockCreateTransactionThreadReport).not.toHaveBeenCalled();
});

it('optimistically materializes the existing thread when it has not been fetched to Onyx yet', () => {
const reportID = getOrCreateTransactionThreadReportID(
{
threadReportID: 'existing_thread',
threadReportExists: false,
iouReport,
iouReportAction: buildIOUAction('a1', 'existing_thread'),
transaction: buildTransaction('t1', 'parent'),
},
CONTEXT,
);

expect(reportID).toBe('existing_thread');
expect(mockSetOptimisticTransactionThread).toHaveBeenCalledTimes(1);
expect(mockSetOptimisticTransactionThread).toHaveBeenCalledWith('existing_thread', 'parent', 'a1', 'policy1');
expect(mockCreateTransactionThreadReport).not.toHaveBeenCalled();
});

it('creates a new thread when none exists yet', () => {
const reportID = getOrCreateTransactionThreadReportID(
{
threadReportID: undefined,
threadReportExists: false,
iouReport,
iouReportAction: buildIOUAction('a1'),
transaction: buildTransaction('t1', 'parent'),
},
CONTEXT,
);

expect(reportID).toBe('created_thread');
expect(mockSetOptimisticTransactionThread).not.toHaveBeenCalled();
expect(mockCreateTransactionThreadReport).toHaveBeenCalledTimes(1);
expect(mockCreateTransactionThreadReport).toHaveBeenCalledWith(
expect.objectContaining({
iouReport: expect.objectContaining({reportID: 'parent'}),
iouReportAction: expect.objectContaining({reportActionID: 'a1'}),
transaction: expect.objectContaining({transactionID: 't1'}),
}),
);
});
});
Loading