From 2157fe9aaaee18c17bbe85ee3a076ef5927b57b5 Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Sat, 1 Nov 2025 10:10:34 +0700 Subject: [PATCH 01/20] Fix - The "Reply" hyperlink below the expense preview is shown --- src/libs/actions/IOU.ts | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/libs/actions/IOU.ts b/src/libs/actions/IOU.ts index 0f7c97689617..aeaaaa14de95 100644 --- a/src/libs/actions/IOU.ts +++ b/src/libs/actions/IOU.ts @@ -201,6 +201,7 @@ import { prepareOnboardingOnyxData, shouldCreateNewMoneyRequestReport as shouldCreateNewMoneyRequestReportReportUtils, shouldEnableNegative, + updateOptimisticParentReportAction, updateReportPreview, } from '@libs/ReportUtils'; import {getCurrentSearchQueryJSON} from '@libs/SearchQueryUtils'; @@ -8300,7 +8301,7 @@ function prepareToCleanUpMoneyRequest( // STEP 4: Update the iouReport and reportPreview with new totals and messages if it wasn't deleted let updatedIOUReport; const currency = getCurrency(transaction); - const updatedReportPreviewAction: Partial> = cloneDeep(reportPreviewAction ?? {}); + let updatedReportPreviewAction: Partial> = cloneDeep(reportPreviewAction ?? {}); updatedReportPreviewAction.pendingAction = shouldDeleteIOUReport ? CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE : CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE; const transactionPendingDelete = transactionIDsPendingDeletion?.map((id) => allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${id}`]); @@ -8344,8 +8345,8 @@ function prepareToCleanUpMoneyRequest( : updateIOUOwnerAndTotal(iouReport, reportAction.actorAccountID ?? CONST.DEFAULT_NUMBER_ID, amountDiff, currency, true, false, isTransactionOnHold, unheldAmountDiff); } + const lastVisibleAction = getLastVisibleAction(iouReport?.reportID, canUserPerformWriteAction, updatedReportAction); if (updatedIOUReport) { - const lastVisibleAction = getLastVisibleAction(iouReport?.reportID, canUserPerformWriteAction, updatedReportAction); const iouReportLastMessageText = getLastVisibleMessage(iouReport?.reportID, canUserPerformWriteAction, updatedReportAction).lastMessageText; updatedIOUReport.lastMessageText = iouReportLastMessageText; updatedIOUReport.lastVisibleActionCreated = lastVisibleAction?.created; @@ -8376,6 +8377,23 @@ function prepareToCleanUpMoneyRequest( updatedReportPreviewAction.childMoneyRequestCount = reportPreviewAction.childMoneyRequestCount - 1; } + if ( + updatedReportPreviewAction && + reportPreviewAction?.childVisibleActionCount && + reportPreviewAction?.childVisibleActionCount > 0 && + reportAction.childVisibleActionCount && + reportAction.childVisibleActionCount > 0 + ) { + const optimisticReportPreviewActionForChildVisibleActionCount = updateOptimisticParentReportAction( + reportPreviewAction as ReportAction, + lastVisibleAction?.childLastVisibleActionCreated ?? lastVisibleAction?.created ?? '', + CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + reportAction.childVisibleActionCount, + ); + + updatedReportPreviewAction = {...updatedReportPreviewAction, ...optimisticReportPreviewActionForChildVisibleActionCount}; + } + return { shouldDeleteTransactionThread, shouldDeleteIOUReport, From 62babf50a6d974a862f53e1535778aa3319cbcb2 Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Tue, 4 Nov 2025 19:11:24 +0700 Subject: [PATCH 02/20] Fix - The "Reply" hyperlink below the expense preview is shown --- tests/actions/IOUTest.ts | 136 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 136 insertions(+) diff --git a/tests/actions/IOUTest.ts b/tests/actions/IOUTest.ts index 4cadfe27de41..2630f9f5a8f3 100644 --- a/tests/actions/IOUTest.ts +++ b/tests/actions/IOUTest.ts @@ -4766,6 +4766,142 @@ describe('actions/IOU', () => { expect(navigateToAfterDelete).toEqual(ROUTES.REPORT_WITH_ID.getRoute(chatReport?.reportID)); } }); + + it('update reportPreview with childVisibleActionCount if the IOU report is not deleted', async () => { + await waitForBatchedUpdates(); + Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID}`, + callback: (val) => (iouReport = val), + }); + await waitForBatchedUpdates(); + + // Given a second expense in addition to the first one + + jest.advanceTimersByTime(10); + const amount2 = 20000; + const comment2 = 'Send me money please 2'; + if (chatReport) { + requestMoney({ + report: chatReport, + participantParams: { + payeeEmail: TEST_USER_LOGIN, + payeeAccountID: TEST_USER_ACCOUNT_ID, + participant: {login: RORY_EMAIL, accountID: RORY_ACCOUNT_ID}, + }, + transactionParams: { + amount: amount2, + attendees: [], + currency: CONST.CURRENCY.USD, + created: '', + merchant: '', + comment: comment2, + }, + shouldGenerateTransactionThreadReport: true, + }); + } + + await waitForBatchedUpdates(); + + // Then we expect the IOU report and reportPreview to update with new totals + + expect(iouReport).toBeTruthy(); + expect(iouReport).toHaveProperty('reportID'); + expect(iouReport).toHaveProperty('chatReportID'); + expect(iouReport?.total).toBe(30000); + + await waitForBatchedUpdates(); + + // Given a transaction thread + thread = buildTransactionThread(createIOUAction, iouReport); + + expect(thread.participants).toEqual({[CARLOS_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}}); + + const participantAccountIDs = Object.keys(thread.participants ?? {}).map(Number); + const userLogins = getLoginsByAccountIDs(participantAccountIDs); + jest.advanceTimersByTime(10); + openReport(thread.reportID, '', userLogins, thread, createIOUAction?.reportActionID); + await waitForBatchedUpdates(); + + Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${thread.reportID}`, + callback: (val) => (reportActions = val), + }); + await waitForBatchedUpdates(); + + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeTruthy(); + resolve(); + }, + }); + }); + + jest.advanceTimersByTime(10); + + // When a comment is added + addComment(thread.reportID, thread.reportID, 'Testing a comment', CONST.DEFAULT_TIME_ZONE); + await waitForBatchedUpdates(); + + // Then comment details should match the expected report action + const resultAction = Object.values(reportActions ?? {}).find((reportAction) => reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT); + reportActionID = resultAction?.reportActionID; + expect(resultAction?.message).toEqual(REPORT_ACTION.message); + expect(resultAction?.person).toEqual(REPORT_ACTION.person); + + await waitForBatchedUpdates(); + + // Then the childVisibleActionCount of createIOUAction and iouPreview should be increased by 1 + const allReportActions = await new Promise>((resolve) => { + const connection = Onyx.connect({ + key: ONYXKEYS.COLLECTION.REPORT_ACTIONS, + waitForCollectionCallback: true, + callback: (actions) => { + Onyx.disconnect(connection); + resolve(actions); + }, + }); + }); + + const reportActionsForIOUReport = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.iouReportID}`]; + createIOUAction = Object.values(reportActionsForIOUReport ?? {}).find((reportAction): reportAction is ReportAction => + isMoneyRequestAction(reportAction), + ); + expect(createIOUAction).toBeTruthy(); + expect(createIOUAction?.childVisibleActionCount).toEqual(1); + expect(createIOUAction?.childCommenterCount).toEqual(1); + + let iouPreview = chatReport?.reportID && iouReport?.reportID ? getReportPreviewAction(chatReport.reportID, iouReport.reportID) : undefined; + expect(iouPreview).toBeTruthy(); + expect(iouPreview?.childVisibleActionCount).toEqual(1); + expect(iouPreview?.childCommenterCount).toEqual(1); + + // When we delete the first expense + mockFetch?.pause?.(); + jest.advanceTimersByTime(10); + if (transaction && createIOUAction) { + deleteMoneyRequest(transaction.transactionID, createIOUAction, {}, {}, iouReport, chatReport, undefined); + } + await waitForBatchedUpdates(); + + // Then we expect the reportPreview to update with new childVisibleActionCount + + iouPreview = chatReport?.reportID && iouReport?.reportID ? getReportPreviewAction(chatReport.reportID, iouReport.reportID) : undefined; + expect(iouPreview).toBeTruthy(); + expect(iouPreview?.childVisibleActionCount).toEqual(0); + expect(iouPreview?.childCommenterCount).toEqual(0); + + // When we resume + mockFetch?.resume?.(); + + // Then we expect the reportPreview to update with new childVisibleActionCount + iouPreview = chatReport?.reportID && iouReport?.reportID ? getReportPreviewAction(chatReport.reportID, iouReport.reportID) : undefined; + expect(iouPreview).toBeTruthy(); + expect(iouPreview?.childVisibleActionCount).toEqual(0); + expect(iouPreview?.childCommenterCount).toEqual(0); + }); }); describe('bulk deleteMoneyRequest', () => { From 6695e9a0ba121552480eff8bd4619de05abbe512 Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Thu, 8 Jan 2026 11:34:44 +0700 Subject: [PATCH 03/20] Fix - The "Reply" hyperlink below the expense preview is shown --- src/libs/actions/IOU/index.ts | 290 ++++++++++++++++----------- src/libs/actions/MergeTransaction.ts | 14 +- tests/actions/IOUTest.ts | 136 ------------- 3 files changed, 191 insertions(+), 249 deletions(-) diff --git a/src/libs/actions/IOU/index.ts b/src/libs/actions/IOU/index.ts index 2f9b6f3c018b..27f2d70c2a76 100644 --- a/src/libs/actions/IOU/index.ts +++ b/src/libs/actions/IOU/index.ts @@ -2688,9 +2688,9 @@ function getDeleteTrackExpenseInformation( } // STEP 2: Decide if we need to: - // 1. Delete the transactionThread - delete if there are no visible comments in the thread and we're not moving the transaction + // 1. Delete the transactionThread - delete if we're not moving the transaction // 2. Update the moneyRequestPreview to show [Deleted expense] - update if the transactionThread exists AND it isn't being deleted and we're not moving the transaction - const shouldDeleteTransactionThread = !isMovingTransactionFromTrackExpense && (transactionThreadID ? (reportAction?.childVisibleActionCount ?? 0) === 0 : false); + const shouldDeleteTransactionThread = !isMovingTransactionFromTrackExpense && !!transactionThreadID; const shouldShowDeletedRequestMessage = !isMovingTransactionFromTrackExpense && !!transactionThreadID && !shouldDeleteTransactionThread; @@ -2750,31 +2750,11 @@ function getDeleteTrackExpenseInformation( value: null, }); - if (shouldDeleteTransactionThread) { - optimisticData.push( - // Use merge instead of set to avoid deleting the report too quickly, which could cause a brief "not found" page to appear. - // The remaining parts of the report object will be removed after the API call is successful. - { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadID}`, - value: { - reportID: null, - stateNum: CONST.REPORT.STATE_NUM.APPROVED, - statusNum: CONST.REPORT.STATUS_NUM.CLOSED, - participants: { - [userAccountID]: { - notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, - }, - }, - }, - }, - { - onyxMethod: Onyx.METHOD.SET, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadID}`, - value: null, - }, - ); - } + const cleanUpTransactionThreadReportOnyxData = getCleanUpTransactionThreadReportOnyxData({ + transactionThreadID, + shouldDeleteTransactionThread, + }); + optimisticData.push(...cleanUpTransactionThreadReportOnyxData.optimisticData); optimisticData.push( { @@ -2808,13 +2788,7 @@ function getDeleteTrackExpenseInformation( // Ensure that any remaining data is removed upon successful completion, even if the server sends a report removal response. // This is done to prevent the removal update from lingering in the applyHTTPSOnyxUpdates function. - if (shouldDeleteTransactionThread && transactionThread) { - successData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadID}`, - value: null, - }); - } + successData.push(...cleanUpTransactionThreadReportOnyxData.successData); const failureData: Array< OnyxUpdate @@ -2843,13 +2817,7 @@ function getDeleteTrackExpenseInformation( value: transactionViolations ?? null, }); - if (shouldDeleteTransactionThread) { - failureData.push({ - onyxMethod: Onyx.METHOD.SET, - key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadID}`, - value: transactionThread, - }); - } + failureData.push(...cleanUpTransactionThreadReportOnyxData.failureData); if (actionableWhisperReportActionID) { const actionableWhisperReportAction = getReportAction(chatReportID, actionableWhisperReportActionID); @@ -8360,7 +8328,7 @@ function prepareToCleanUpMoneyRequest( // STEP 4: Update the iouReport and reportPreview with new totals and messages if it wasn't deleted let updatedIOUReport; const currency = getCurrency(transaction); - let updatedReportPreviewAction: Partial> = cloneDeep(reportPreviewAction ?? {}); + const updatedReportPreviewAction: Partial> = cloneDeep(reportPreviewAction ?? {}); updatedReportPreviewAction.pendingAction = shouldDeleteIOUReport ? CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE : CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE; const transactionPendingDelete = transactionIDsPendingDeletion?.map((id) => allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${id}`]); @@ -8404,8 +8372,8 @@ function prepareToCleanUpMoneyRequest( : updateIOUOwnerAndTotal(iouReport, reportAction.actorAccountID ?? CONST.DEFAULT_NUMBER_ID, amountDiff, currency, true, false, isTransactionOnHold, unheldAmountDiff); } - const lastVisibleAction = getLastVisibleAction(iouReport?.reportID, canUserPerformWriteAction, updatedReportAction); if (updatedIOUReport) { + const lastVisibleAction = getLastVisibleAction(iouReport?.reportID, canUserPerformWriteAction, updatedReportAction); const iouReportLastMessageText = getLastVisibleMessage(iouReport?.reportID, canUserPerformWriteAction, updatedReportAction).lastMessageText; updatedIOUReport.lastMessageText = iouReportLastMessageText; updatedIOUReport.lastVisibleActionCreated = lastVisibleAction?.created; @@ -8437,23 +8405,6 @@ function prepareToCleanUpMoneyRequest( updatedReportPreviewAction.childMoneyRequestCount = reportPreviewAction.childMoneyRequestCount - 1; } - if ( - updatedReportPreviewAction && - reportPreviewAction?.childVisibleActionCount && - reportPreviewAction?.childVisibleActionCount > 0 && - reportAction.childVisibleActionCount && - reportAction.childVisibleActionCount > 0 - ) { - const optimisticReportPreviewActionForChildVisibleActionCount = updateOptimisticParentReportAction( - reportPreviewAction as ReportAction, - lastVisibleAction?.childLastVisibleActionCreated ?? lastVisibleAction?.created ?? '', - CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, - reportAction.childVisibleActionCount, - ); - - updatedReportPreviewAction = {...updatedReportPreviewAction, ...optimisticReportPreviewActionForChildVisibleActionCount}; - } - return { shouldDeleteTransactionThread, shouldDeleteIOUReport, @@ -8726,6 +8677,141 @@ function cleanUpMoneyRequest( }); } +/** + * @param transactionThreadID - The transaction thread reportID of the transaction + * @param shouldDeleteTransactionThread - Flag indicating whether the transactionThread should be optimistically deleted + * @param reportAction - The IOU action of the transaction + * @return Returns Onyx data including information about deleting the transactionThread and updating the child comment count for the preview report action + */ +function getCleanUpTransactionThreadReportOnyxData({ + transactionThreadID, + shouldDeleteTransactionThread, + reportAction, + isChatIOUReportArchived, +}: { + transactionThreadID?: string; + shouldDeleteTransactionThread: boolean; + reportAction?: ReportAction; + isChatIOUReportArchived?: boolean; +}) { + const optimisticData: OnyxUpdate[] = []; + const successData: OnyxUpdate[] = []; + const failureData: OnyxUpdate[] = []; + + if (shouldDeleteTransactionThread) { + let transactionThread = null; + let transactionThreadReportActions = null; + if (transactionThreadID) { + transactionThread = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${transactionThreadID}`] ?? null; + transactionThreadReportActions = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadID}`] ?? null; + } + + optimisticData.push( + // Use merge instead of set to avoid deleting the report too quickly, which could cause a brief "not found" page to appear. + // The remaining parts of the report object will be removed after the API call is successful. + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadID}`, + value: { + reportID: null, + stateNum: CONST.REPORT.STATE_NUM.APPROVED, + statusNum: CONST.REPORT.STATUS_NUM.CLOSED, + participants: { + [userAccountID]: { + notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, + }, + }, + }, + }, + { + onyxMethod: Onyx.METHOD.SET, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadID}`, + value: null, + }, + ); + if (transactionThread) { + successData.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadID}`, + value: null, + }); + } + failureData.push( + { + onyxMethod: Onyx.METHOD.SET, + key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadID}`, + value: transactionThread, + }, + { + onyxMethod: Onyx.METHOD.SET, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadID}`, + value: transactionThreadReportActions, + }, + ); + } + + // Update the child comment visible count for reportPreviewAction. + const iouReportID = isMoneyRequestAction(reportAction) ? getOriginalMessage(reportAction)?.IOUReportID : undefined; + const iouReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`]; + const chatReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${iouReport?.chatReportID}`]; + const reportPreviewAction = getReportPreviewAction(chatReport?.reportID, iouReport?.reportID); + if ( + reportPreviewAction?.reportActionID && + reportPreviewAction?.childVisibleActionCount && + reportPreviewAction?.childVisibleActionCount > 0 && + reportAction?.childVisibleActionCount && + reportAction?.childVisibleActionCount > 0 + ) { + let canUserPerformWriteAction = true; + if (chatReport) { + const reportNameValuePairs = allReportNameValuePairs?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${iouReport?.reportID}`]; + const isArchivedExpenseReport = isArchivedReport(reportNameValuePairs); + + canUserPerformWriteAction = !!canUserPerformWriteActionReportUtils(chatReport, isChatIOUReportArchived ?? isArchivedExpenseReport); + } + const lastVisibleAction = getLastVisibleAction(iouReportID, canUserPerformWriteAction); + + const {childVisibleActionCount, childCommenterCount, childLastVisibleActionCreated, childOldestFourAccountIDs} = updateOptimisticParentReportAction( + reportPreviewAction as ReportAction, + lastVisibleAction?.childLastVisibleActionCreated ?? lastVisibleAction?.created ?? '', + CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + reportAction.childVisibleActionCount, + ); + + optimisticData.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.reportID}`, + value: { + [reportPreviewAction.reportActionID]: { + childVisibleActionCount, + childCommenterCount, + childLastVisibleActionCreated, + childOldestFourAccountIDs, + }, + }, + }); + + failureData.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.reportID}`, + value: { + [reportPreviewAction.reportActionID]: { + childVisibleActionCount: reportPreviewAction.childVisibleActionCount, + childCommenterCount: reportPreviewAction.childCommenterCount, + childLastVisibleActionCreated: reportPreviewAction.childLastVisibleActionCreated, + childOldestFourAccountIDs: reportPreviewAction.childOldestFourAccountIDs, + }, + }, + }); + } + + return { + optimisticData, + successData, + failureData, + }; +} + /** * * @param transactionID - The transactionID of IOU @@ -8758,7 +8844,6 @@ function deleteMoneyRequest({ updatedIOUReport, updatedReportPreviewAction, transactionThreadID, - transactionThread, transaction, transactionViolations, reportPreviewAction, @@ -8801,32 +8886,6 @@ function deleteMoneyRequest({ removeTransactionFromDuplicateTransactionViolation({optimisticData, failureData}, transactionID, transactions, violations); - if (shouldDeleteTransactionThread) { - optimisticData.push( - // Use merge instead of set to avoid deleting the report too quickly, which could cause a brief "not found" page to appear. - // The remaining parts of the report object will be removed after the API call is successful. - { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadID}`, - value: { - reportID: null, - stateNum: CONST.REPORT.STATE_NUM.APPROVED, - statusNum: CONST.REPORT.STATUS_NUM.CLOSED, - participants: { - [userAccountID]: { - notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, - }, - }, - }, - }, - { - onyxMethod: Onyx.METHOD.SET, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadID}`, - value: null, - }, - ); - } - optimisticData.push( { onyxMethod: Onyx.METHOD.MERGE, @@ -8896,6 +8955,9 @@ function deleteMoneyRequest({ }); } + const cleanUpTransactionThreadReportOnyxData = getCleanUpTransactionThreadReportOnyxData({shouldDeleteTransactionThread, transactionThreadID, reportAction, isChatIOUReportArchived}); + optimisticData.push(...cleanUpTransactionThreadReportOnyxData.optimisticData); + const successData: OnyxUpdate[] = [ shouldDeleteIOUReport ? { @@ -8929,13 +8991,7 @@ function deleteMoneyRequest({ // Ensure that any remaining data is removed upon successful completion, even if the server sends a report removal response. // This is done to prevent the removal update from lingering in the applyHTTPSOnyxUpdates function. - if (shouldDeleteTransactionThread && transactionThread) { - successData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadID}`, - value: null, - }); - } + successData.push(...cleanUpTransactionThreadReportOnyxData.successData); if (shouldDeleteIOUReport) { successData.push({ @@ -8957,13 +9013,7 @@ function deleteMoneyRequest({ value: transactionViolations ?? null, }); - if (shouldDeleteTransactionThread) { - failureData.push({ - onyxMethod: Onyx.METHOD.SET, - key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadID}`, - value: transactionThread, - }); - } + failureData.push(...cleanUpTransactionThreadReportOnyxData.failureData); const errorKey = DateUtils.getMicroseconds(); @@ -12249,6 +12299,21 @@ function mergeDuplicates({transactionThreadReportID: optimisticTransactionThread }, {}), }; + const cleanUpTransactionThreadReportsOptimisticData = []; + const cleanUpTransactionThreadReportsSuccessData = []; + const cleanUpTransactionThreadReportsFailureData = []; + for (const iouAction of iouActionsToDelete) { + const transactionThreadID = iouAction.childReportID; + const shouldDeleteTransactionThread = !!transactionThreadID; + const cleanUpTransactionThreadReportOnyxDataForIouAction = getCleanUpTransactionThreadReportOnyxData({ + transactionThreadID, + shouldDeleteTransactionThread, + reportAction: iouAction, + }); + cleanUpTransactionThreadReportsOptimisticData.push(...cleanUpTransactionThreadReportOnyxDataForIouAction.optimisticData); + cleanUpTransactionThreadReportsSuccessData.push(...cleanUpTransactionThreadReportOnyxDataForIouAction.successData); + cleanUpTransactionThreadReportsFailureData.push(...cleanUpTransactionThreadReportOnyxDataForIouAction.failureData); + } const optimisticReportAction = buildOptimisticResolvedDuplicatesReportAction(); const transactionThreadReportID = @@ -12271,7 +12336,7 @@ function mergeDuplicates({transactionThreadReportID: optimisticTransactionThread const optimisticData: OnyxUpdate[] = []; const failureData: OnyxUpdate[] = []; - const successData: Array> = []; + const successData: Array> = []; optimisticData.push( optimisticTransactionData, @@ -12280,7 +12345,9 @@ function mergeDuplicates({transactionThreadReportID: optimisticTransactionThread expenseReportOptimisticData, expenseReportActionsOptimisticData, optimisticReportActionData, + ...cleanUpTransactionThreadReportsOptimisticData, ); + successData.push(...cleanUpTransactionThreadReportsSuccessData); failureData.push( failureTransactionData, ...failureTransactionDuplicatesData, @@ -12288,6 +12355,7 @@ function mergeDuplicates({transactionThreadReportID: optimisticTransactionThread expenseReportFailureData, expenseReportActionsFailureData, failureReportActionData, + ...cleanUpTransactionThreadReportsFailureData, ); if (optimisticTransactionThreadReportID) { @@ -14188,17 +14256,18 @@ function updateSplitTransactions({ errors: null, }, }; - const transactionThread = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${firstIOU.childReportID}`] ?? null; - optimisticData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${firstIOU?.childReportID}`, - value: null, + const cleanUpTransactionThreadReportOnyxData = getCleanUpTransactionThreadReportOnyxData({ + transactionThreadID: firstIOU.childReportID, + shouldDeleteTransactionThread: !!firstIOU.childReportID, + reportAction: firstIOU, }); optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`, value: updatedReportAction, }); + optimisticData.push(...cleanUpTransactionThreadReportOnyxData.optimisticData); + successData.push(...cleanUpTransactionThreadReportOnyxData.successData); failureData.push({ onyxMethod: Onyx.METHOD.MERGE, @@ -14210,11 +14279,7 @@ function updateSplitTransactions({ }, }, }); - failureData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${firstIOU?.childReportID}`, - value: transactionThread, - }); + failureData.push(...cleanUpTransactionThreadReportOnyxData.failureData); } optimisticData.push({ @@ -14775,6 +14840,7 @@ export { getAllPersonalDetails, getReceiptError, getSearchOnyxUpdate, + getCleanUpTransactionThreadReportOnyxData, }; export type { GPSPoint as GpsPoint, diff --git a/src/libs/actions/MergeTransaction.ts b/src/libs/actions/MergeTransaction.ts index a8379b16e6e6..85166f3830a6 100644 --- a/src/libs/actions/MergeTransaction.ts +++ b/src/libs/actions/MergeTransaction.ts @@ -24,7 +24,7 @@ import {getTransactionViolationsOfTransaction, isDistanceRequest, isTransactionP import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import type {CardList, MergeTransaction, Policy, PolicyCategories, PolicyTagLists, Report, Transaction} from '@src/types/onyx'; -import {getUpdateMoneyRequestParams, getUpdateTrackExpenseParams} from './IOU'; +import {getCleanUpTransactionThreadReportOnyxData, getUpdateMoneyRequestParams, getUpdateTrackExpenseParams} from './IOU'; import type {UpdateMoneyRequestData} from './IOU'; /** @@ -402,6 +402,18 @@ function mergeTransactionRequest({ ] : []; + const sourceIouAction = getIOUActionForReportID(sourceTransaction.reportID, sourceTransaction.transactionID); + const sourceTransactionThreadReportID = sourceIouAction?.childReportID; + const shouldDeleteTransactionThread = !!sourceTransactionThreadReportID; + const cleanUpSourceTransactionThreadReportOnyxData = getCleanUpTransactionThreadReportOnyxData({ + transactionThreadID: sourceTransactionThreadReportID, + shouldDeleteTransactionThread, + reportAction: sourceIouAction, + }); + optimisticSourceReportActionData.push(...cleanUpSourceTransactionThreadReportOnyxData.optimisticData); + successSourceReportActionData.push(...cleanUpSourceTransactionThreadReportOnyxData.successData); + failureSourceReportActionData.push(...cleanUpSourceTransactionThreadReportOnyxData.failureData); + // Optimistic delete the merge transaction const optimisticMergeTransactionData: OnyxUpdate = { onyxMethod: Onyx.METHOD.SET, diff --git a/tests/actions/IOUTest.ts b/tests/actions/IOUTest.ts index daaa5abed89a..307ba204dea4 100644 --- a/tests/actions/IOUTest.ts +++ b/tests/actions/IOUTest.ts @@ -5651,142 +5651,6 @@ describe('actions/IOU', () => { expect(navigateToAfterDelete).toEqual(ROUTES.REPORT_WITH_ID.getRoute(chatReport?.reportID)); } }); - - it('update reportPreview with childVisibleActionCount if the IOU report is not deleted', async () => { - await waitForBatchedUpdates(); - Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID}`, - callback: (val) => (iouReport = val), - }); - await waitForBatchedUpdates(); - - // Given a second expense in addition to the first one - - jest.advanceTimersByTime(10); - const amount2 = 20000; - const comment2 = 'Send me money please 2'; - if (chatReport) { - requestMoney({ - report: chatReport, - participantParams: { - payeeEmail: TEST_USER_LOGIN, - payeeAccountID: TEST_USER_ACCOUNT_ID, - participant: {login: RORY_EMAIL, accountID: RORY_ACCOUNT_ID}, - }, - transactionParams: { - amount: amount2, - attendees: [], - currency: CONST.CURRENCY.USD, - created: '', - merchant: '', - comment: comment2, - }, - shouldGenerateTransactionThreadReport: true, - }); - } - - await waitForBatchedUpdates(); - - // Then we expect the IOU report and reportPreview to update with new totals - - expect(iouReport).toBeTruthy(); - expect(iouReport).toHaveProperty('reportID'); - expect(iouReport).toHaveProperty('chatReportID'); - expect(iouReport?.total).toBe(30000); - - await waitForBatchedUpdates(); - - // Given a transaction thread - thread = buildTransactionThread(createIOUAction, iouReport); - - expect(thread.participants).toEqual({[CARLOS_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}}); - - const participantAccountIDs = Object.keys(thread.participants ?? {}).map(Number); - const userLogins = getLoginsByAccountIDs(participantAccountIDs); - jest.advanceTimersByTime(10); - openReport(thread.reportID, '', userLogins, thread, createIOUAction?.reportActionID); - await waitForBatchedUpdates(); - - Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${thread.reportID}`, - callback: (val) => (reportActions = val), - }); - await waitForBatchedUpdates(); - - await new Promise((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, - callback: (report) => { - Onyx.disconnect(connection); - expect(report).toBeTruthy(); - resolve(); - }, - }); - }); - - jest.advanceTimersByTime(10); - - // When a comment is added - addComment(thread.reportID, thread.reportID, 'Testing a comment', CONST.DEFAULT_TIME_ZONE); - await waitForBatchedUpdates(); - - // Then comment details should match the expected report action - const resultAction = Object.values(reportActions ?? {}).find((reportAction) => reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT); - reportActionID = resultAction?.reportActionID; - expect(resultAction?.message).toEqual(REPORT_ACTION.message); - expect(resultAction?.person).toEqual(REPORT_ACTION.person); - - await waitForBatchedUpdates(); - - // Then the childVisibleActionCount of createIOUAction and iouPreview should be increased by 1 - const allReportActions = await new Promise>((resolve) => { - const connection = Onyx.connect({ - key: ONYXKEYS.COLLECTION.REPORT_ACTIONS, - waitForCollectionCallback: true, - callback: (actions) => { - Onyx.disconnect(connection); - resolve(actions); - }, - }); - }); - - const reportActionsForIOUReport = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.iouReportID}`]; - createIOUAction = Object.values(reportActionsForIOUReport ?? {}).find((reportAction): reportAction is ReportAction => - isMoneyRequestAction(reportAction), - ); - expect(createIOUAction).toBeTruthy(); - expect(createIOUAction?.childVisibleActionCount).toEqual(1); - expect(createIOUAction?.childCommenterCount).toEqual(1); - - let iouPreview = chatReport?.reportID && iouReport?.reportID ? getReportPreviewAction(chatReport.reportID, iouReport.reportID) : undefined; - expect(iouPreview).toBeTruthy(); - expect(iouPreview?.childVisibleActionCount).toEqual(1); - expect(iouPreview?.childCommenterCount).toEqual(1); - - // When we delete the first expense - mockFetch?.pause?.(); - jest.advanceTimersByTime(10); - if (transaction && createIOUAction) { - deleteMoneyRequest(transaction.transactionID, createIOUAction, {}, {}, iouReport, chatReport, undefined); - } - await waitForBatchedUpdates(); - - // Then we expect the reportPreview to update with new childVisibleActionCount - - iouPreview = chatReport?.reportID && iouReport?.reportID ? getReportPreviewAction(chatReport.reportID, iouReport.reportID) : undefined; - expect(iouPreview).toBeTruthy(); - expect(iouPreview?.childVisibleActionCount).toEqual(0); - expect(iouPreview?.childCommenterCount).toEqual(0); - - // When we resume - mockFetch?.resume?.(); - - // Then we expect the reportPreview to update with new childVisibleActionCount - iouPreview = chatReport?.reportID && iouReport?.reportID ? getReportPreviewAction(chatReport.reportID, iouReport.reportID) : undefined; - expect(iouPreview).toBeTruthy(); - expect(iouPreview?.childVisibleActionCount).toEqual(0); - expect(iouPreview?.childCommenterCount).toEqual(0); - }); }); describe('bulk deleteMoneyRequest', () => { From 492aa9bdedbdb485e5371a779245219540dec7d4 Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Thu, 8 Jan 2026 11:38:04 +0700 Subject: [PATCH 04/20] Fix - The "Reply" hyperlink below the expense preview is shown --- src/libs/actions/IOU/index.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libs/actions/IOU/index.ts b/src/libs/actions/IOU/index.ts index 35173bcc3738..6fae163e8517 100644 --- a/src/libs/actions/IOU/index.ts +++ b/src/libs/actions/IOU/index.ts @@ -8715,12 +8715,12 @@ function getCleanUpTransactionThreadReportOnyxData({ { onyxMethod: Onyx.METHOD.SET, key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadID}`, - value: transactionThread, + value: transactionThread ?? null, }, { onyxMethod: Onyx.METHOD.SET, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadID}`, - value: transactionThreadReportActions, + value: transactionThreadReportActions ?? null, }, ); } From efda2e6ba8708658070c5449f244763122f02e41 Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Thu, 8 Jan 2026 11:51:19 +0700 Subject: [PATCH 05/20] fix lint --- src/libs/actions/IOU/index.ts | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/libs/actions/IOU/index.ts b/src/libs/actions/IOU/index.ts index 6fae163e8517..5f41ebda4df6 100644 --- a/src/libs/actions/IOU/index.ts +++ b/src/libs/actions/IOU/index.ts @@ -2684,10 +2684,6 @@ function getDeleteTrackExpenseInformation( const transaction = allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; const transactionViolations = allTransactionViolations[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`]; const transactionThreadID = reportAction.childReportID; - let transactionThread = null; - if (transactionThreadID) { - transactionThread = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${transactionThreadID}`] ?? null; - } // STEP 2: Decide if we need to: // 1. Delete the transactionThread - delete if we're not moving the transaction @@ -8669,9 +8665,9 @@ function getCleanUpTransactionThreadReportOnyxData({ reportAction?: ReportAction; isChatIOUReportArchived?: boolean; }) { - const optimisticData: OnyxUpdate[] = []; - const successData: OnyxUpdate[] = []; - const failureData: OnyxUpdate[] = []; + const optimisticData: Array> = []; + const successData: Array> = []; + const failureData: Array> = []; if (shouldDeleteTransactionThread) { let transactionThread = null; From 88e019d13a37aeaf998818bbf2a09f465cd76d1c Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Thu, 8 Jan 2026 17:12:09 +0700 Subject: [PATCH 06/20] Fix - The "Reply" hyperlink below the expense preview is shown --- src/libs/actions/IOU/index.ts | 1 + src/libs/actions/MergeTransaction.ts | 215 ++++++++++++++++----------- 2 files changed, 128 insertions(+), 88 deletions(-) diff --git a/src/libs/actions/IOU/index.ts b/src/libs/actions/IOU/index.ts index 5f41ebda4df6..62f06d05de38 100644 --- a/src/libs/actions/IOU/index.ts +++ b/src/libs/actions/IOU/index.ts @@ -14730,6 +14730,7 @@ export { getReceiptError, getSearchOnyxUpdate, getCleanUpTransactionThreadReportOnyxData, + getDeleteTrackExpenseInformation, }; export type { GPSPoint as GpsPoint, diff --git a/src/libs/actions/MergeTransaction.ts b/src/libs/actions/MergeTransaction.ts index 85166f3830a6..a936dac79759 100644 --- a/src/libs/actions/MergeTransaction.ts +++ b/src/libs/actions/MergeTransaction.ts @@ -5,6 +5,7 @@ import type {LocaleContextProps} from '@components/LocaleContextProvider'; import * as API from '@libs/API'; import type {GetTransactionsForMergingParams} from '@libs/API/parameters'; import {READ_COMMANDS, WRITE_COMMANDS} from '@libs/API/types'; +import Log from '@libs/Log'; import { areTransactionsEligibleForMerge, getMergeableDataAndConflictFields, @@ -17,14 +18,22 @@ import { import type {MergeFieldKey, MergeTransactionUpdateValues} from '@libs/MergeTransactionUtils'; import Navigation from '@libs/Navigation/Navigation'; import {isPaidGroupPolicy, isPolicyAdmin} from '@libs/PolicyUtils'; -import {getIOUActionForReportID} from '@libs/ReportActionsUtils'; -import {getReportOrDraftReport, getReportTransactions, getTransactionDetails, isCurrentUserSubmitter, isMoneyRequestReportEligibleForMerge, isReportManager} from '@libs/ReportUtils'; +import {getIOUActionForReportID, getTrackExpenseActionableWhisper} from '@libs/ReportActionsUtils'; +import { + findSelfDMReportID, + getReportOrDraftReport, + getReportTransactions, + getTransactionDetails, + isCurrentUserSubmitter, + isMoneyRequestReportEligibleForMerge, + isReportManager, +} from '@libs/ReportUtils'; import CONST from '@src/CONST'; import {getTransactionViolationsOfTransaction, isDistanceRequest, isTransactionPendingDelete} from '@src/libs/TransactionUtils'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import type {CardList, MergeTransaction, Policy, PolicyCategories, PolicyTagLists, Report, Transaction} from '@src/types/onyx'; -import {getCleanUpTransactionThreadReportOnyxData, getUpdateMoneyRequestParams, getUpdateTrackExpenseParams} from './IOU'; +import {getCleanUpTransactionThreadReportOnyxData, getDeleteTrackExpenseInformation, getUpdateMoneyRequestParams, getUpdateTrackExpenseParams} from './IOU'; import type {UpdateMoneyRequestData} from './IOU'; /** @@ -327,93 +336,131 @@ function mergeTransactionRequest({ ); // Optimistic delete the source transaction and also delete its report if it was a single expense report - const optimisticSourceTransactionData: OnyxUpdate = { - onyxMethod: Onyx.METHOD.SET, - key: `${ONYXKEYS.COLLECTION.TRANSACTION}${sourceTransaction.transactionID}`, - value: null, - }; - const failureSourceTransactionData: OnyxUpdate = { - onyxMethod: Onyx.METHOD.SET, - key: `${ONYXKEYS.COLLECTION.TRANSACTION}${sourceTransaction.transactionID}`, - value: sourceTransaction, - }; - const transactionsOfSourceReport = getReportTransactions(sourceTransaction.reportID); - const optimisticSourceReportData: OnyxUpdate[] = - transactionsOfSourceReport.length === 1 + const isUnreportedSourceTransaction = sourceTransaction.reportID === CONST.REPORT.UNREPORTED_REPORT_ID; + const selfDMReportID = findSelfDMReportID(); + + const sourceTransactionOptimisticData: OnyxUpdate[] = []; + const sourceTransactionSuccessData: OnyxUpdate[] = []; + const sourceTransactionFailureData: OnyxUpdate[] = []; + if (!isUnreportedSourceTransaction || !selfDMReportID) { + const optimisticSourceTransactionData: OnyxUpdate = { + onyxMethod: Onyx.METHOD.SET, + key: `${ONYXKEYS.COLLECTION.TRANSACTION}${sourceTransaction.transactionID}`, + value: null, + }; + const failureSourceTransactionData: OnyxUpdate = { + onyxMethod: Onyx.METHOD.SET, + key: `${ONYXKEYS.COLLECTION.TRANSACTION}${sourceTransaction.transactionID}`, + value: sourceTransaction, + }; + const transactionsOfSourceReport = getReportTransactions(sourceTransaction.reportID); + const optimisticSourceReportData: OnyxUpdate[] = + transactionsOfSourceReport.length === 1 + ? [ + { + onyxMethod: Onyx.METHOD.SET, + key: `${ONYXKEYS.COLLECTION.REPORT}${sourceTransaction.reportID}`, + value: null, + }, + ] + : []; + + // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 + const failureSourceReportData: OnyxUpdate[] = + transactionsOfSourceReport.length === 1 + ? [ + { + onyxMethod: Onyx.METHOD.SET, + key: `${ONYXKEYS.COLLECTION.REPORT}${sourceTransaction.reportID}`, + value: getReportOrDraftReport(sourceTransaction.reportID), + }, + ] + : []; + const iouActionOfSourceTransaction = getIOUActionForReportID(sourceTransaction.reportID, sourceTransaction.transactionID); + const optimisticSourceReportActionData: OnyxUpdate[] = iouActionOfSourceTransaction ? [ { - onyxMethod: Onyx.METHOD.SET, - key: `${ONYXKEYS.COLLECTION.REPORT}${sourceTransaction.reportID}`, - value: null, + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${sourceTransaction.reportID}`, + value: { + [iouActionOfSourceTransaction.reportActionID]: { + pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + }, + }, }, ] : []; - - // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 - const failureSourceReportData: OnyxUpdate[] = - transactionsOfSourceReport.length === 1 + const successSourceReportActionData: OnyxUpdate[] = iouActionOfSourceTransaction ? [ { - onyxMethod: Onyx.METHOD.SET, - key: `${ONYXKEYS.COLLECTION.REPORT}${sourceTransaction.reportID}`, - value: getReportOrDraftReport(sourceTransaction.reportID), + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${sourceTransaction.reportID}`, + value: { + [iouActionOfSourceTransaction.reportActionID]: { + pendingAction: null, + }, + }, }, ] : []; - const iouActionOfSourceTransaction = getIOUActionForReportID(sourceTransaction.reportID, sourceTransaction.transactionID); - const optimisticSourceReportActionData: OnyxUpdate[] = iouActionOfSourceTransaction - ? [ - { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${sourceTransaction.reportID}`, - value: { - [iouActionOfSourceTransaction.reportActionID]: { - pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, - }, - }, - }, - ] - : []; - const successSourceReportActionData: OnyxUpdate[] = iouActionOfSourceTransaction - ? [ - { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${sourceTransaction.reportID}`, - value: { - [iouActionOfSourceTransaction.reportActionID]: { - pendingAction: null, - }, - }, - }, - ] - : []; - - const failureSourceReportActionData: OnyxUpdate[] = iouActionOfSourceTransaction - ? [ - { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${sourceTransaction.reportID}`, - value: { - [iouActionOfSourceTransaction.reportActionID]: { - pendingAction: null, + + const failureSourceReportActionData: OnyxUpdate[] = iouActionOfSourceTransaction + ? [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${sourceTransaction.reportID}`, + value: { + [iouActionOfSourceTransaction.reportActionID]: { + pendingAction: null, + }, }, }, - }, - ] - : []; - - const sourceIouAction = getIOUActionForReportID(sourceTransaction.reportID, sourceTransaction.transactionID); - const sourceTransactionThreadReportID = sourceIouAction?.childReportID; - const shouldDeleteTransactionThread = !!sourceTransactionThreadReportID; - const cleanUpSourceTransactionThreadReportOnyxData = getCleanUpTransactionThreadReportOnyxData({ - transactionThreadID: sourceTransactionThreadReportID, - shouldDeleteTransactionThread, - reportAction: sourceIouAction, - }); - optimisticSourceReportActionData.push(...cleanUpSourceTransactionThreadReportOnyxData.optimisticData); - successSourceReportActionData.push(...cleanUpSourceTransactionThreadReportOnyxData.successData); - failureSourceReportActionData.push(...cleanUpSourceTransactionThreadReportOnyxData.failureData); + ] + : []; + const sourceIouAction = getIOUActionForReportID(sourceTransaction.reportID, sourceTransaction.transactionID); + const sourceTransactionThreadReportID = sourceIouAction?.childReportID; + const shouldDeleteTransactionThread = !!sourceTransactionThreadReportID; + const cleanUpSourceTransactionThreadReportOnyxData = getCleanUpTransactionThreadReportOnyxData({ + transactionThreadID: sourceTransactionThreadReportID, + shouldDeleteTransactionThread, + reportAction: sourceIouAction, + }); + optimisticSourceReportActionData.push(...cleanUpSourceTransactionThreadReportOnyxData.optimisticData); + successSourceReportActionData.push(...cleanUpSourceTransactionThreadReportOnyxData.successData); + failureSourceReportActionData.push(...cleanUpSourceTransactionThreadReportOnyxData.failureData); + + // Optimistic data + sourceTransactionOptimisticData.push(optimisticSourceTransactionData, ...optimisticSourceReportData, ...optimisticSourceReportActionData); + // Failure data + sourceTransactionFailureData.push(failureSourceTransactionData, ...failureSourceReportData, ...failureSourceReportActionData); + // Success data + sourceTransactionSuccessData.push(...successSourceReportActionData); + } else { + const whisperAction = getTrackExpenseActionableWhisper(sourceTransaction.transactionID, selfDMReportID); + const sourceIouAction = getIOUActionForReportID(selfDMReportID, sourceTransaction.transactionID); + const actionableWhisperReportActionID = whisperAction?.reportActionID; + + if (!sourceIouAction) { + Log.warn("Can't find the iouAction for the transaction in the selfDM report."); + } else { + const {optimisticData, successData, failureData} = getDeleteTrackExpenseInformation( + selfDMReportID, + sourceTransaction.transactionID, + sourceIouAction, + false, + undefined, + undefined, + actionableWhisperReportActionID, + CONST.REPORT.ACTIONABLE_TRACK_EXPENSE_WHISPER_RESOLUTION.NOTHING, + false, + ); + + sourceTransactionOptimisticData.push(...optimisticData); + sourceTransactionSuccessData.push(...successData); + sourceTransactionFailureData.push(...failureData); + } + } // Optimistic delete the merge transaction const optimisticMergeTransactionData: OnyxUpdate = { onyxMethod: Onyx.METHOD.SET, @@ -446,25 +493,17 @@ function mergeTransactionRequest({ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const optimisticData: OnyxUpdate[] = [ ...(onyxTargetTransactionData.optimisticData ?? []), - optimisticSourceTransactionData, - ...optimisticSourceReportData, optimisticMergeTransactionData, ...optimisticTransactionViolations, - ...optimisticSourceReportActionData, + ...sourceTransactionOptimisticData, ]; // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const failureData: OnyxUpdate[] = [ - ...(onyxTargetTransactionData.failureData ?? []), - failureSourceTransactionData, - ...failureSourceReportData, - ...failureTransactionViolations, - ...failureSourceReportActionData, - ]; + const failureData: OnyxUpdate[] = [...(onyxTargetTransactionData.failureData ?? []), ...failureTransactionViolations, ...sourceTransactionFailureData]; const successData: OnyxUpdate[] = []; - successData.push(...successSourceReportActionData); + successData.push(...sourceTransactionSuccessData); successData.push(...(onyxTargetTransactionData.successData ?? [])); API.write(WRITE_COMMANDS.MERGE_TRANSACTION, params, {optimisticData, failureData, successData}); From 5cc84411e5f701229d6a1058fa5f3a24d0adbc3c Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Sat, 10 Jan 2026 22:02:36 +0700 Subject: [PATCH 07/20] Add unit tests - The "Reply" hyperlink below the expense preview is shown --- src/libs/actions/IOU/index.ts | 65 +- tests/actions/IOUTest.ts | 1050 ++++++++++++++++++++++--- tests/actions/MergeTransactionTest.ts | 336 +++++++- 3 files changed, 1327 insertions(+), 124 deletions(-) diff --git a/src/libs/actions/IOU/index.ts b/src/libs/actions/IOU/index.ts index 7ac49c6bd237..a69843cd92f6 100644 --- a/src/libs/actions/IOU/index.ts +++ b/src/libs/actions/IOU/index.ts @@ -8753,11 +8753,15 @@ function getCleanUpTransactionThreadReportOnyxData({ shouldDeleteTransactionThread, reportAction, isChatIOUReportArchived, + updatedReportPreviewAction, + shouldAddUpdatedReportPreviewActionToOnyxData = true, }: { transactionThreadID?: string; shouldDeleteTransactionThread: boolean; reportAction?: ReportAction; isChatIOUReportArchived?: boolean; + updatedReportPreviewAction?: ReportAction; + shouldAddUpdatedReportPreviewActionToOnyxData?: boolean; }) { const optimisticData: Array> = []; const successData: Array> = []; @@ -8796,7 +8800,7 @@ function getCleanUpTransactionThreadReportOnyxData({ ); if (transactionThread) { successData.push({ - onyxMethod: Onyx.METHOD.MERGE, + onyxMethod: Onyx.METHOD.SET, key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadID}`, value: null, }); @@ -8819,7 +8823,7 @@ function getCleanUpTransactionThreadReportOnyxData({ const iouReportID = isMoneyRequestAction(reportAction) ? getOriginalMessage(reportAction)?.IOUReportID : undefined; const iouReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`]; const chatReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${iouReport?.chatReportID}`]; - const reportPreviewAction = getReportPreviewAction(chatReport?.reportID, iouReport?.reportID); + let reportPreviewAction = updatedReportPreviewAction ?? getReportPreviewAction(chatReport?.reportID, iouReport?.reportID) ?? undefined; if ( reportPreviewAction?.reportActionID && reportPreviewAction?.childVisibleActionCount && @@ -8837,43 +8841,48 @@ function getCleanUpTransactionThreadReportOnyxData({ const lastVisibleAction = getLastVisibleAction(iouReportID, canUserPerformWriteAction); const {childVisibleActionCount, childCommenterCount, childLastVisibleActionCreated, childOldestFourAccountIDs} = updateOptimisticParentReportAction( - reportPreviewAction as ReportAction, + reportPreviewAction, lastVisibleAction?.childLastVisibleActionCreated ?? lastVisibleAction?.created ?? '', CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, reportAction.childVisibleActionCount, ); - optimisticData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.reportID}`, - value: { - [reportPreviewAction.reportActionID]: { - childVisibleActionCount, - childCommenterCount, - childLastVisibleActionCreated, - childOldestFourAccountIDs, + if (shouldAddUpdatedReportPreviewActionToOnyxData) { + optimisticData.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.reportID}`, + value: { + [reportPreviewAction.reportActionID]: { + childVisibleActionCount, + childCommenterCount, + childLastVisibleActionCreated, + childOldestFourAccountIDs, + }, }, - }, - }); + }); - failureData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.reportID}`, - value: { - [reportPreviewAction.reportActionID]: { - childVisibleActionCount: reportPreviewAction.childVisibleActionCount, - childCommenterCount: reportPreviewAction.childCommenterCount, - childLastVisibleActionCreated: reportPreviewAction.childLastVisibleActionCreated, - childOldestFourAccountIDs: reportPreviewAction.childOldestFourAccountIDs, + failureData.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.reportID}`, + value: { + [reportPreviewAction.reportActionID]: { + childVisibleActionCount: reportPreviewAction.childVisibleActionCount, + childCommenterCount: reportPreviewAction.childCommenterCount, + childLastVisibleActionCreated: reportPreviewAction.childLastVisibleActionCreated, + childOldestFourAccountIDs: reportPreviewAction.childOldestFourAccountIDs, + }, }, - }, - }); + }); + } + + reportPreviewAction = {...reportPreviewAction, childVisibleActionCount, childCommenterCount, childLastVisibleActionCreated, childOldestFourAccountIDs}; } return { optimisticData, successData, failureData, + updatedReportPreviewAction: reportPreviewAction, }; } @@ -12372,17 +12381,21 @@ function mergeDuplicates({transactionThreadReportID: optimisticTransactionThread const cleanUpTransactionThreadReportsOptimisticData = []; const cleanUpTransactionThreadReportsSuccessData = []; const cleanUpTransactionThreadReportsFailureData = []; - for (const iouAction of iouActionsToDelete) { + let updatedReportPreviewAction; + for (const [index, iouAction] of Object.entries(iouActionsToDelete)) { const transactionThreadID = iouAction.childReportID; const shouldDeleteTransactionThread = !!transactionThreadID; const cleanUpTransactionThreadReportOnyxDataForIouAction = getCleanUpTransactionThreadReportOnyxData({ transactionThreadID, shouldDeleteTransactionThread, reportAction: iouAction, + updatedReportPreviewAction, + shouldAddUpdatedReportPreviewActionToOnyxData: Number(index) === iouActionsToDelete.length - 1, }); cleanUpTransactionThreadReportsOptimisticData.push(...cleanUpTransactionThreadReportOnyxDataForIouAction.optimisticData); cleanUpTransactionThreadReportsSuccessData.push(...cleanUpTransactionThreadReportOnyxDataForIouAction.successData); cleanUpTransactionThreadReportsFailureData.push(...cleanUpTransactionThreadReportOnyxDataForIouAction.failureData); + updatedReportPreviewAction = cleanUpTransactionThreadReportOnyxDataForIouAction.updatedReportPreviewAction; } const optimisticReportAction = buildOptimisticResolvedDuplicatesReportAction(); diff --git a/tests/actions/IOUTest.ts b/tests/actions/IOUTest.ts index 6d44fe44f2ce..cc9c2901e45a 100644 --- a/tests/actions/IOUTest.ts +++ b/tests/actions/IOUTest.ts @@ -24,6 +24,7 @@ import { deleteMoneyRequest, duplicateExpenseTransaction, evenlyDistributeSplitExpenseAmounts, + getDeleteTrackExpenseInformation, getIOUReportActionToApproveOrPay, getPerDiemExpenseInformation, getReportOriginalCreationTimestamp, @@ -71,6 +72,7 @@ import {getLoginsByAccountIDs} from '@libs/PersonalDetailsUtils'; import type * as PolicyUtils from '@libs/PolicyUtils'; import { getOriginalMessage, + getReportAction, getReportActionHtml, getReportActionMessage, getReportActionText, @@ -80,7 +82,14 @@ import { isMoneyRequestAction, } from '@libs/ReportActionsUtils'; import type {OptimisticChatReport} from '@libs/ReportUtils'; -import {buildOptimisticIOUReport, buildOptimisticIOUReportAction, buildTransactionThread, createDraftTransactionAndNavigateToParticipantSelector, isIOUReport} from '@libs/ReportUtils'; +import { + buildOptimisticIOUReport, + buildOptimisticIOUReportAction, + buildTransactionThread, + createDraftTransactionAndNavigateToParticipantSelector, + getReportOrDraftReport, + isIOUReport, +} from '@libs/ReportUtils'; import {buildOptimisticTransaction, getValidWaypoints, isDistanceRequest as isDistanceRequestUtil} from '@libs/TransactionUtils'; import type {IOUAction} from '@src/CONST'; import CONST from '@src/CONST'; @@ -3597,6 +3606,204 @@ describe('actions/IOU', () => { expect(originalTransactionThread).toBe(undefined); }); + it('should delete the original transaction thread report regardless of whether there are visible comments, and update the comment count of the preview report', async () => { + const chatReportID = 'report123'; + const reportID = 'report456'; + const transactionID = 'transaction123'; + const previewActionID = 'action123'; + const iouActionID = 'action123'; + + const chatReport: Report = { + ...createRandomReport(0, undefined), + policyID: CONST.POLICY.ID_FAKE, + parentReportID: undefined, + parentReportActionID: undefined, + reportID: chatReportID, + type: 'chat', + }; + let previewAction: OnyxEntry = { + ...createRandomReportAction(0), + actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, + reportActionID: previewActionID, + childMoneyRequestCount: 1, + childVisibleActionCount: 0, + originalMessage: {linkedReportID: reportID}, + }; + const iouReport: Report = { + ...createRandomReport(1, undefined), + type: CONST.REPORT.TYPE.IOU, + chatReportID: chatReport.reportID, + parentReportID: chatReport.reportID, + parentReportActionID: previewAction.reportActionID, + reportID, + }; + const transaction: Transaction = { + amount: 100, + currency: 'USD', + transactionID, + reportID: iouReport.reportID, + created: DateUtils.getDBTime(), + merchant: 'test', + }; + + let iouAction: OnyxEntry = { + ...buildOptimisticIOUReportAction({ + type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, + amount: transaction.amount, + currency: transaction.currency, + comment: '', + participants: [], + transactionID: transaction.transactionID, + iouReportID: iouReport.reportID, + }), + reportActionID: iouActionID, + }; + + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, transaction); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, iouReport); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`, chatReport); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`, []); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReportID}`, { + [previewActionID]: previewAction, + }); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, { + [iouActionID]: iouAction, + }); + await waitForBatchedUpdates(); + + const thread = buildTransactionThread(iouAction, iouReport); + + expect(thread.participants).toEqual({ + [RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}, + }); + + const participantAccountIDs = Object.keys(thread.participants ?? {}).map(Number); + const userLogins = getLoginsByAccountIDs(participantAccountIDs); + jest.advanceTimersByTime(10); + openReport(thread.reportID, '', userLogins, thread, iouAction?.reportActionID); + await waitForBatchedUpdates(); + + let transactionThreadReportActions: OnyxEntry; + Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${thread.reportID}`, + callback: (val) => (transactionThreadReportActions = val), + }); + await waitForBatchedUpdates(); + + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeTruthy(); + resolve(); + }, + }); + }); + + jest.advanceTimersByTime(10); + + // When a comment is added + addComment( + thread, + thread.reportID, + [ + {report: iouReport, reportAction: iouAction, shouldDisplayNewMarker: false}, + {report: chatReport, reportAction: previewAction, shouldDisplayNewMarker: false}, + ], + 'test comment', + CONST.DEFAULT_TIME_ZONE, + ); + await waitForBatchedUpdates(); + + // Then the report should have 2 actions + expect(Object.values(transactionThreadReportActions ?? {}).length).toBe(2); + + iouAction = getReportAction(iouReport.reportID, iouActionID); + previewAction = getReportAction(chatReport.reportID, previewActionID); + expect(iouAction?.childVisibleActionCount).toBe(1); + expect(previewAction?.childVisibleActionCount).toBe(1); + + await waitForBatchedUpdates(); + + const draftTransaction: OnyxEntry = { + ...transaction, + comment: { + originalTransactionID: transaction.transactionID, + }, + }; + + let allTransactions: OnyxCollection; + let allReports: OnyxCollection; + let allReportNameValuePairs: OnyxCollection; + await getOnyxData({ + key: ONYXKEYS.COLLECTION.TRANSACTION, + waitForCollectionCallback: true, + callback: (value) => { + allTransactions = value; + }, + }); + await getOnyxData({ + key: ONYXKEYS.COLLECTION.REPORT, + waitForCollectionCallback: true, + callback: (value) => { + allReports = value; + }, + }); + await getOnyxData({ + key: ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, + waitForCollectionCallback: true, + callback: (value) => { + allReportNameValuePairs = value; + }, + }); + + updateSplitTransactionsFromSplitExpensesFlow({ + allTransactionsList: allTransactions, + allReportsList: allReports, + allReportNameValuePairsList: allReportNameValuePairs, + transactionData: { + reportID: draftTransaction?.reportID ?? String(CONST.DEFAULT_NUMBER_ID), + originalTransactionID: draftTransaction?.comment?.originalTransactionID ?? String(CONST.DEFAULT_NUMBER_ID), + splitExpenses: draftTransaction?.comment?.splitExpenses ?? [], + splitExpensesTotal: draftTransaction?.comment?.splitExpensesTotal, + }, + searchContext: { + currentSearchHash: -2, + }, + policyCategories: undefined, + policy: undefined, + policyRecentlyUsedCategories: [], + iouReport, + firstIOU: iouAction, + isASAPSubmitBetaEnabled: false, + currentUserPersonalDetails, + transactionViolations: {}, + policyRecentlyUsedCurrencies: [], + }); + + await waitForBatchedUpdates(); + + // Then we expect the reportPreview to update with new childVisibleActionCount + previewAction = getReportPreviewAction(chatReport?.reportID, iouReport?.reportID) ?? undefined; + expect(previewAction).toBeTruthy(); + expect(previewAction?.childVisibleActionCount).toEqual(0); + expect(previewAction?.childCommenterCount).toEqual(0); + + // Then the transaction thread report should be deleted + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + waitForCollectionCallback: false, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeFalsy(); + resolve(); + }, + }); + }); + }); + it('should remove the original transaction from the search snapshot data', async () => { // Given a single expense const expenseReport: Report = { @@ -5180,7 +5387,7 @@ describe('actions/IOU', () => { expect(report?.reportID).toBeFalsy(); }); - it('does not delete the transaction thread if there are visible comments in the thread', async () => { + it('should delete the transaction thread regardless of whether there are visible comments in the thread.', async () => { // Given initial environment is set up await waitForBatchedUpdates(); @@ -5233,6 +5440,22 @@ describe('actions/IOU', () => { mockFetch?.pause?.(); + const allReportActions = await new Promise>((resolve) => { + const connection = Onyx.connect({ + key: ONYXKEYS.COLLECTION.REPORT_ACTIONS, + waitForCollectionCallback: true, + callback: (actions) => { + Onyx.disconnect(connection); + resolve(actions); + }, + }); + }); + + const reportActionsForIOUReport = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.iouReportID}`]; + createIOUAction = Object.values(reportActionsForIOUReport ?? {}).find( + (reportAction): reportAction is ReportAction => reportAction.reportActionID === createIOUAction?.reportActionID, + ); + if (transaction && createIOUAction) { // When deleting expense deleteMoneyRequest({ @@ -5246,28 +5469,32 @@ describe('actions/IOU', () => { } await waitForBatchedUpdates(); - // Then the transaction thread report should still exist + // Then the transaction thread report should be ready to be deleted await new Promise((resolve) => { const connection = Onyx.connect({ key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, waitForCollectionCallback: false, callback: (report) => { Onyx.disconnect(connection); - expect(report).toBeTruthy(); + expect(report?.reportID).toBeFalsy(); resolve(); }, }); }); // When fetch resumes - // Then the transaction thread report should still exist + // Then the transaction thread report should be deleted mockFetch?.resume?.(); + await waitForBatchedUpdates(); + + // Then the transaction thread report should be deleted await new Promise((resolve) => { const connection = Onyx.connect({ key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + waitForCollectionCallback: false, callback: (report) => { Onyx.disconnect(connection); - expect(report).toBeTruthy(); + expect(report).toBeFalsy(); resolve(); }, }); @@ -5659,99 +5886,525 @@ describe('actions/IOU', () => { expect(navigateToAfterDelete).toEqual(ROUTES.REPORT_WITH_ID.getRoute(chatReport?.reportID)); } }); - }); - - describe('bulk deleteMoneyRequest', () => { - it('update IOU report total properly for bulk deletion of expenses', async () => { - const expenseReport: Report = { - ...createRandomReport(11, undefined), - type: CONST.REPORT.TYPE.EXPENSE, - total: 30, - currency: CONST.CURRENCY.USD, - unheldTotal: 20, - unheldNonReimbursableTotal: 20, - }; - const transaction1: Transaction = { - ...createRandomTransaction(1), - amount: 10, - comment: {hold: '123'}, - currency: CONST.CURRENCY.USD, - reportID: expenseReport.reportID, - reimbursable: true, - }; - const moneyRequestAction1: ReportAction = { - ...createRandomReportAction(1), - actionName: CONST.REPORT.ACTIONS.TYPE.IOU, - childReportID: '1', - originalMessage: { - IOUReportID: expenseReport.reportID, - amount: transaction1.amount, - currency: transaction1.currency, - type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, - }, - message: undefined, - previousMessage: undefined, - }; - const transaction2: Transaction = {...createRandomTransaction(2), amount: 10, currency: CONST.CURRENCY.USD, reportID: expenseReport.reportID, reimbursable: false}; - const moneyRequestAction2: ReportAction = { - ...createRandomReportAction(2), - actionName: CONST.REPORT.ACTIONS.TYPE.IOU, - childReportID: '2', - originalMessage: { - IOUReportID: expenseReport.reportID, - amount: transaction2.amount, - currency: transaction2.currency, - type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, - }, - message: undefined, - previousMessage: undefined, - }; - const transaction3: Transaction = {...createRandomTransaction(3), amount: 10, currency: CONST.CURRENCY.USD, reportID: expenseReport.reportID, reimbursable: false}; - - await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction1.transactionID}`, transaction1); - await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction2.transactionID}`, transaction2); - await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction3.transactionID}`, transaction3); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`, expenseReport); - const selectedTransactionIDs = [transaction1.transactionID, transaction2.transactionID]; - deleteMoneyRequest({ - transactionID: transaction1.transactionID, - reportAction: moneyRequestAction1, - transactions: {}, - violations: {}, - iouReport: expenseReport, - chatReport: expenseReport, - transactionIDsPendingDeletion: [], - selectedTransactionIDs, - }); - deleteMoneyRequest({ - transactionID: transaction2.transactionID, - reportAction: moneyRequestAction2, - transactions: {}, - violations: {}, - iouReport: expenseReport, - chatReport: expenseReport, - transactionIDsPendingDeletion: [transaction1.transactionID], - selectedTransactionIDs, + it('update reportPreview with childVisibleActionCount if the IOU report is not deleted', async () => { + await waitForBatchedUpdates(); + Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID}`, + callback: (val) => (iouReport = val), }); - await waitForBatchedUpdates(); - const report = await new Promise>((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`, - callback: (val) => { - Onyx.disconnect(connection); - resolve(val); - }, - }); - }); + // Given a second expense in addition to the first one - expect(report?.total).toBe(10); - expect(report?.unheldTotal).toBe(10); - expect(report?.unheldNonReimbursableTotal).toBe(10); - }); - }); + jest.advanceTimersByTime(10); + const amount2 = 20000; + const comment2 = 'Send me money please 2'; + if (chatReport) { + requestMoney({ + report: chatReport, + participantParams: { + payeeEmail: TEST_USER_LOGIN, + payeeAccountID: TEST_USER_ACCOUNT_ID, + participant: {login: RORY_EMAIL, accountID: RORY_ACCOUNT_ID}, + }, + transactionParams: { + amount: amount2, + attendees: [], + currency: CONST.CURRENCY.USD, + created: '', + merchant: '', + comment: comment2, + }, + shouldGenerateTransactionThreadReport: true, + isASAPSubmitBetaEnabled: false, + transactionViolations: {}, + currentUserAccountIDParam: 123, + currentUserEmailParam: 'existing@example.com', + policyRecentlyUsedCurrencies: [], + }); + } + + await waitForBatchedUpdates(); + + // Then we expect the IOU report and reportPreview to update with new totals + + expect(iouReport).toBeTruthy(); + expect(iouReport).toHaveProperty('reportID'); + expect(iouReport).toHaveProperty('chatReportID'); + expect(iouReport?.total).toBe(30000); + + await waitForBatchedUpdates(); + + // Given a transaction thread + thread = buildTransactionThread(createIOUAction, iouReport); + + expect(thread.participants).toEqual({[CARLOS_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}}); + + const participantAccountIDs = Object.keys(thread.participants ?? {}).map(Number); + const userLogins = getLoginsByAccountIDs(participantAccountIDs); + jest.advanceTimersByTime(10); + openReport(thread.reportID, '', userLogins, thread, createIOUAction?.reportActionID); + await waitForBatchedUpdates(); + + Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${thread.reportID}`, + callback: (val) => (reportActions = val), + }); + await waitForBatchedUpdates(); + + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeTruthy(); + resolve(); + }, + }); + }); + + jest.advanceTimersByTime(10); + + // When a comment is added + let iouPreview = getReportPreviewAction(chatReport?.reportID, iouReport?.reportID); + const ascentors = []; + ascentors.push(...(iouReport && createIOUAction ? [{report: iouReport, reportAction: createIOUAction, shouldDisplayNewMarker: false}] : [])); + ascentors.push(...(chatReport && iouPreview ? [{report: chatReport, reportAction: iouPreview, shouldDisplayNewMarker: false}] : [])); + addComment(thread, thread.reportID, ascentors, 'Testing a comment', CONST.DEFAULT_TIME_ZONE); + await waitForBatchedUpdates(); + + // Then comment details should match the expected report action + const resultAction = Object.values(reportActions ?? {}).find((reportAction) => reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT); + reportActionID = resultAction?.reportActionID; + expect(resultAction?.message).toEqual(REPORT_ACTION.message); + expect(resultAction?.person).toEqual(REPORT_ACTION.person); + + await waitForBatchedUpdates(); + + // Then the childVisibleActionCount of createIOUAction and iouPreview should be increased by 1 + const allReportActions = await new Promise>((resolve) => { + const connection = Onyx.connect({ + key: ONYXKEYS.COLLECTION.REPORT_ACTIONS, + waitForCollectionCallback: true, + callback: (actions) => { + Onyx.disconnect(connection); + resolve(actions); + }, + }); + }); + + const reportActionsForIOUReport = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.iouReportID}`]; + createIOUAction = Object.values(reportActionsForIOUReport ?? {}).find( + (reportAction): reportAction is ReportAction => + isMoneyRequestAction(reportAction) && reportAction.reportActionID === createIOUAction?.reportActionID, + ); + expect(createIOUAction).toBeTruthy(); + expect(createIOUAction?.childVisibleActionCount).toEqual(1); + expect(createIOUAction?.childCommenterCount).toEqual(1); + + iouPreview = getReportPreviewAction(chatReport?.reportID, iouReport?.reportID); + expect(iouPreview).toBeTruthy(); + expect(iouPreview?.childVisibleActionCount).toEqual(1); + expect(iouPreview?.childCommenterCount).toEqual(1); + + // When we delete the first expense + mockFetch?.pause?.(); + jest.advanceTimersByTime(10); + if (transaction && createIOUAction) { + deleteMoneyRequest({transactionID: transaction.transactionID, reportAction: createIOUAction, transactions: {}, violations: {}, iouReport, chatReport}); + } + + await waitForBatchedUpdates(); + + // Then we expect the reportPreview to update with new childVisibleActionCount + + iouPreview = getReportPreviewAction(chatReport?.reportID, iouReport?.reportID); + expect(iouPreview).toBeTruthy(); + expect(iouPreview?.childVisibleActionCount).toEqual(0); + expect(iouPreview?.childCommenterCount).toEqual(0); + + // When we resume + mockFetch?.resume?.(); + await waitForBatchedUpdates(); + + // Then we expect the reportPreview to update with new childVisibleActionCount + iouPreview = getReportPreviewAction(chatReport?.reportID, iouReport?.reportID); + expect(iouPreview).toBeTruthy(); + expect(iouPreview?.childVisibleActionCount).toEqual(0); + expect(iouPreview?.childCommenterCount).toEqual(0); + }); + }); + + describe('getDeleteTrackExpenseInformation', () => { + const amount = 10000; + const comment = 'Send me money please'; + let selfDMReport: Report; + let createIOUAction: OnyxEntry>; + let transaction: OnyxEntry; + let thread: OptimisticChatReport; + const TEST_USER_ACCOUNT_ID = 1; + const TEST_USER_LOGIN = 'test@test.com'; + let reportActionID; + const REPORT_ACTION: OnyxEntry = { + actionName: CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT, + actorAccountID: TEST_USER_ACCOUNT_ID, + automatic: false, + avatar: 'https://d2k5nsl2zxldvw.cloudfront.net/images/avatars/avatar_3.png', + message: [{type: 'COMMENT', html: 'Testing a comment', text: 'Testing a comment', translationKey: ''}], + person: [{type: 'TEXT', style: 'strong', text: 'Test User'}], + shouldShow: true, + created: DateUtils.getDBTime(), + reportActionID: '1', + originalMessage: { + html: '', + whisperedTo: [], + }, + }; + + let reportActions: OnyxCollection; + + beforeEach(async () => { + // Given mocks are cleared and helpers are set up + jest.clearAllMocks(); + PusherHelper.setup(); + + // Given a test user is signed in with Onyx setup and some initial data + await signInWithTestUser(TEST_USER_ACCOUNT_ID, TEST_USER_LOGIN); + subscribeToUserEvents(); + await waitForBatchedUpdates(); + await setPersonalDetails(TEST_USER_LOGIN, TEST_USER_ACCOUNT_ID); + + selfDMReport = { + ...createRandomReport(1, CONST.REPORT.CHAT_TYPE.SELF_DM), + reportID: '10', + }; + + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${selfDMReport.reportID}`, selfDMReport); + + // Create a tracked expense + trackExpense({ + report: selfDMReport, + isDraftPolicy: true, + action: CONST.IOU.ACTION.CREATE, + participantParams: { + payeeEmail: TEST_USER_LOGIN, + payeeAccountID: TEST_USER_ACCOUNT_ID, + participant: {login: RORY_EMAIL, accountID: RORY_ACCOUNT_ID}, + }, + transactionParams: { + amount, + currency: 'USD', + created: format(new Date(), CONST.DATE.FNS_FORMAT_STRING), + merchant: comment, + billable: false, + }, + isASAPSubmitBetaEnabled: false, + currentUserAccountIDParam: RORY_ACCOUNT_ID, + currentUserEmailParam: RORY_EMAIL, + introSelected: undefined, + activePolicyID: undefined, + quickAction: undefined, + }); + await waitForBatchedUpdates(); + + // When fetching all reports from Onyx + const allReports = await new Promise>((resolve) => { + const connection = Onyx.connect({ + key: ONYXKEYS.COLLECTION.REPORT, + waitForCollectionCallback: true, + callback: (reports) => { + Onyx.disconnect(connection); + resolve(reports); + }, + }); + }); + + // Then we should have exactly 2 reports + expect(Object.values(allReports ?? {}).length).toBe(2); + + // Then one of them should be a chat report with relevant properties + const transactionThreadReport = Object.values(allReports ?? {}).find((report) => report?.type === CONST.REPORT.TYPE.CHAT); + if (transactionThreadReport) { + thread = transactionThreadReport; + } + expect(thread).toBeTruthy(); + expect(thread).toHaveProperty('reportID'); + expect(thread?.parentReportID).toBe(selfDMReport.reportID); + expect(thread).toHaveProperty('parentReportActionID'); + + await waitForBatchedUpdates(); + + // When fetching all report actions from Onyx + const allReportActions = await new Promise>((resolve) => { + const connection = Onyx.connect({ + key: ONYXKEYS.COLLECTION.REPORT_ACTIONS, + waitForCollectionCallback: true, + callback: (actions) => { + Onyx.disconnect(connection); + resolve(actions); + }, + }); + }); + + // Then we should find an IOU action with specific properties + const reportActionsForIOUReport = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${selfDMReport.reportID}`]; + createIOUAction = Object.values(reportActionsForIOUReport ?? {}).find( + (reportAction): reportAction is ReportAction => reportAction.reportActionID === thread?.parentReportActionID, + ); + expect(createIOUAction).toBeTruthy(); + expect(createIOUAction?.childReportID).toBe(thread?.reportID); + + // When fetching all transactions from Onyx + const allTransactions = await new Promise>((resolve) => { + const connection = Onyx.connect({ + key: ONYXKEYS.COLLECTION.TRANSACTION, + waitForCollectionCallback: true, + callback: (transactions) => { + Onyx.disconnect(connection); + resolve(transactions); + }, + }); + }); + + // Then we should find a specific transaction with relevant properties + transaction = Object.values(allTransactions ?? {}).find((t) => t); + expect(transaction).toBeTruthy(); + expect(transaction?.amount).toBe(-amount); + expect(transaction?.reportID).toBe(CONST.REPORT.UNREPORTED_REPORT_ID); + expect(createIOUAction && getOriginalMessage(createIOUAction)?.IOUTransactionID).toBe(transaction?.transactionID); + }); + + afterEach(PusherHelper.teardown); + + it('should delete the transaction thread regardless of whether there are visible comments in the thread, if isMovingTransactionFromTrackExpense equals false.', async () => { + // Given initial environment is set up + await waitForBatchedUpdates(); + + expect(thread.participants).toEqual({[CARLOS_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}}); + + const participantAccountIDs = Object.keys(thread.participants ?? {}).map(Number); + const userLogins = getLoginsByAccountIDs(participantAccountIDs); + jest.advanceTimersByTime(10); + openReport(thread.reportID, '', userLogins, thread, createIOUAction?.reportActionID); + await waitForBatchedUpdates(); + + Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${thread?.reportID}`, + callback: (val) => (reportActions = val), + }); + await waitForBatchedUpdates(); + + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeTruthy(); + resolve(); + }, + }); + }); + + jest.advanceTimersByTime(10); + + // When a comment is added + addComment(thread, thread.reportID, [], 'Testing a comment', CONST.DEFAULT_TIME_ZONE); + await waitForBatchedUpdates(); + + // Then comment details should match the expected report action + const resultAction = Object.values(reportActions ?? {}).find((reportAction) => reportAction?.actionName === CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT); + reportActionID = resultAction?.reportActionID; + expect(resultAction?.message).toEqual(REPORT_ACTION.message); + expect(resultAction?.person).toEqual(REPORT_ACTION.person); + + await waitForBatchedUpdates(); + + // Then the report should have 2 actions + expect(Object.values(reportActions ?? {}).length).toBe(2); + const resultActionAfter = reportActionID ? reportActions?.[reportActionID] : undefined; + expect(resultActionAfter?.pendingAction).toBeUndefined(); + + const allReportActions = await new Promise>((resolve) => { + const connection = Onyx.connect({ + key: ONYXKEYS.COLLECTION.REPORT_ACTIONS, + waitForCollectionCallback: true, + callback: (actions) => { + Onyx.disconnect(connection); + resolve(actions); + }, + }); + }); + + const reportActionsForIOUReport = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${selfDMReport.reportID}`]; + createIOUAction = Object.values(reportActionsForIOUReport ?? {}).find( + (reportAction): reportAction is ReportAction => reportAction.reportActionID === createIOUAction?.reportActionID, + ); + expect(createIOUAction).toBeTruthy(); + + // When deleting expense + const {optimisticData, successData, shouldDeleteTransactionThread} = getDeleteTrackExpenseInformation( + selfDMReport.reportID, + transaction?.transactionID, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + createIOUAction!, + false, + undefined, + undefined, + ); + await waitForBatchedUpdates(); + + // Then the transaction thread report should be ready to be deleted + expect(shouldDeleteTransactionThread).toBe(true); + expect(optimisticData).toEqual( + expect.arrayContaining([expect.objectContaining({key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, value: expect.objectContaining({reportID: null})})]), + ); + expect(optimisticData).toEqual(expect.arrayContaining([expect.objectContaining({key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${thread.reportID}`, value: null})])); + expect(successData).toEqual(expect.arrayContaining([expect.objectContaining({key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, value: null})])); + }); + + it('should NOT delete the transaction thread regardless of whether there are no visible comments in the thread, if isMovingTransactionFromTrackExpense equals true.', async () => { + // Given initial environment is set up + await waitForBatchedUpdates(); + + expect(thread.participants).toEqual({[CARLOS_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}}); + + const participantAccountIDs = Object.keys(thread.participants ?? {}).map(Number); + const userLogins = getLoginsByAccountIDs(participantAccountIDs); + jest.advanceTimersByTime(10); + openReport(thread.reportID, '', userLogins, thread, createIOUAction?.reportActionID); + await waitForBatchedUpdates(); + + Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${thread?.reportID}`, + callback: (val) => (reportActions = val), + }); + await waitForBatchedUpdates(); + + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeTruthy(); + resolve(); + }, + }); + }); + + // When deleting expense + const {optimisticData, successData, shouldDeleteTransactionThread} = getDeleteTrackExpenseInformation( + selfDMReport.reportID, + transaction?.transactionID, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + createIOUAction!, + false, + undefined, + true, + ); + await waitForBatchedUpdates(); + + // Then the transaction thread report should be ready to be deleted + expect(shouldDeleteTransactionThread).toBe(false); + expect(optimisticData).not.toEqual( + expect.arrayContaining([expect.objectContaining({key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, value: expect.objectContaining({reportID: null})})]), + ); + expect(optimisticData).not.toEqual(expect.arrayContaining([expect.objectContaining({key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${thread.reportID}`, value: null})])); + expect(successData).not.toEqual(expect.arrayContaining([expect.objectContaining({key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, value: null})])); + }); + }); + + describe('bulk deleteMoneyRequest', () => { + it('update IOU report total properly for bulk deletion of expenses', async () => { + const expenseReport: Report = { + ...createRandomReport(11, undefined), + type: CONST.REPORT.TYPE.EXPENSE, + total: 30, + currency: CONST.CURRENCY.USD, + unheldTotal: 20, + unheldNonReimbursableTotal: 20, + }; + const transaction1: Transaction = { + ...createRandomTransaction(1), + amount: 10, + comment: {hold: '123'}, + currency: CONST.CURRENCY.USD, + reportID: expenseReport.reportID, + reimbursable: true, + }; + const moneyRequestAction1: ReportAction = { + ...createRandomReportAction(1), + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + childReportID: '1', + originalMessage: { + IOUReportID: expenseReport.reportID, + amount: transaction1.amount, + currency: transaction1.currency, + type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, + }, + message: undefined, + previousMessage: undefined, + }; + const transaction2: Transaction = {...createRandomTransaction(2), amount: 10, currency: CONST.CURRENCY.USD, reportID: expenseReport.reportID, reimbursable: false}; + const moneyRequestAction2: ReportAction = { + ...createRandomReportAction(2), + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + childReportID: '2', + originalMessage: { + IOUReportID: expenseReport.reportID, + amount: transaction2.amount, + currency: transaction2.currency, + type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, + }, + message: undefined, + previousMessage: undefined, + }; + const transaction3: Transaction = {...createRandomTransaction(3), amount: 10, currency: CONST.CURRENCY.USD, reportID: expenseReport.reportID, reimbursable: false}; + + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction1.transactionID}`, transaction1); + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction2.transactionID}`, transaction2); + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction3.transactionID}`, transaction3); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`, expenseReport); + + const selectedTransactionIDs = [transaction1.transactionID, transaction2.transactionID]; + deleteMoneyRequest({ + transactionID: transaction1.transactionID, + reportAction: moneyRequestAction1, + transactions: {}, + violations: {}, + iouReport: expenseReport, + chatReport: expenseReport, + transactionIDsPendingDeletion: [], + selectedTransactionIDs, + }); + deleteMoneyRequest({ + transactionID: transaction2.transactionID, + reportAction: moneyRequestAction2, + transactions: {}, + violations: {}, + iouReport: expenseReport, + chatReport: expenseReport, + transactionIDsPendingDeletion: [transaction1.transactionID], + selectedTransactionIDs, + }); + + await waitForBatchedUpdates(); + + const report = await new Promise>((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`, + callback: (val) => { + Onyx.disconnect(connection); + resolve(val); + }, + }); + }); + + expect(report?.total).toBe(10); + expect(report?.unheldTotal).toBe(10); + expect(report?.unheldNonReimbursableTotal).toBe(10); + }); + }); describe('submitReport', () => { it('correctly submits a report', () => { @@ -9728,13 +10381,14 @@ describe('actions/IOU', () => { {name: CONST.VIOLATIONS.MISSING_CATEGORY, type: CONST.VIOLATION_TYPES.VIOLATION}, ]; - const createMockIouAction = (transactionID: string, reportActionID: string, childReportID: string): ReportAction => ({ + const createMockIouAction = (transactionID: string, reportActionID: string, childReportID: string, IOUReportID?: string): ReportAction => ({ reportActionID, actionName: CONST.REPORT.ACTIONS.TYPE.IOU, created: '2024-01-01 12:00:00', originalMessage: { IOUTransactionID: transactionID, type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, + IOUReportID, } as OriginalMessageIOU, message: [{type: 'TEXT', text: 'Test IOU message'}], childReportID, @@ -9937,6 +10591,212 @@ describe('actions/IOU', () => { // Then: Verify API was still called expect(writeSpy).toHaveBeenCalledWith(WRITE_COMMANDS.MERGE_DUPLICATES, expect.objectContaining({}), expect.objectContaining({})); }); + + it('should delete the thread reports of the duplicated transactions and update the comment count of the preview report', async () => { + // Given: Set up test data with main transaction and duplicates + const chatReportID = 'report123'; + const reportID = 'report456'; + const mainTransactionID = 'main123'; + const duplicate1ID = 'dup456'; + const duplicate2ID = 'dup789'; + const duplicateTransactionIDs = [duplicate1ID, duplicate2ID]; + const previewActionID = 'action123'; + const iouAction1ID = 'action456'; + const iouAction2ID = 'action789'; + + const chatReport: Report = { + ...createRandomReport(0, undefined), + policyID: CONST.POLICY.ID_FAKE, + parentReportID: undefined, + parentReportActionID: undefined, + reportID: chatReportID, + type: 'chat', + }; + let previewAction: OnyxEntry = { + ...createRandomReportAction(0), + actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, + reportActionID: previewActionID, + childMoneyRequestCount: 3, + childVisibleActionCount: 0, + originalMessage: {linkedReportID: reportID}, + }; + const expenseReport: Report = { + ...createMockReport(reportID, 300), + chatReportID: chatReport.reportID, + parentReportID: chatReport.reportID, + parentReportActionID: previewAction.reportActionID, + }; + const mainTransaction = createMockTransaction(mainTransactionID, reportID, 100); + const duplicateTransaction1 = createMockTransaction(duplicate1ID, reportID, 100); + const duplicateTransaction2 = createMockTransaction(duplicate2ID, reportID, 100); + + const mainViolations = createMockViolations(); + const duplicate1Violations = createMockViolations(); + const duplicate2Violations = createMockViolations(); + + let iouAction1 = createMockIouAction(duplicate1ID, iouAction1ID, '', reportID) as OnyxEntry; + let iouAction2 = createMockIouAction(duplicate2ID, iouAction2ID, '', reportID) as OnyxEntry; + + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`, mainTransaction); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate1ID}`, duplicateTransaction1); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate2ID}`, duplicateTransaction2); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, expenseReport); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`, chatReport); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${mainTransactionID}`, mainViolations); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate1ID}`, duplicate1Violations); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate2ID}`, duplicate2Violations); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReportID}`, { + [previewActionID]: previewAction, + }); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, { + [iouAction1ID]: iouAction1, + [iouAction2ID]: iouAction2, + }); + await waitForBatchedUpdates(); + + const transactionThreadReport1 = buildTransactionThread(iouAction1, expenseReport); + const transactionThreadReport2 = buildTransactionThread(iouAction2, expenseReport); + + expect(transactionThreadReport1.participants).toEqual({ + [RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}, + }); + expect(transactionThreadReport2.participants).toEqual({ + [RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}, + }); + + const participantAccountIDs = Object.keys(transactionThreadReport1.participants ?? {}).map(Number); + const userLogins = getLoginsByAccountIDs(participantAccountIDs); + jest.advanceTimersByTime(10); + openReport(transactionThreadReport1.reportID, '', userLogins, transactionThreadReport1, iouAction1?.reportActionID); + openReport(transactionThreadReport2.reportID, '', userLogins, transactionThreadReport1, iouAction2?.reportActionID); + await waitForBatchedUpdates(); + + let transactionThreadReportActions1: OnyxEntry; + let transactionThreadReportActions2: OnyxEntry; + Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReport1.reportID}`, + callback: (val) => (transactionThreadReportActions1 = val), + }); + Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReport2.reportID}`, + callback: (val) => (transactionThreadReportActions2 = val), + }); + await waitForBatchedUpdates(); + + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport1.reportID}`, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeTruthy(); + resolve(); + }, + }); + }); + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport2.reportID}`, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeTruthy(); + resolve(); + }, + }); + }); + + jest.advanceTimersByTime(10); + + // When a comment is added + const addCommentToThread = async (thread: Report, iouActionID: string, message: string) => { + const updatedIouAction = getReportAction(expenseReport.reportID, iouActionID); + const updatedPreviewAction = getReportAction(chatReport.reportID, previewActionID); + const ascentors = []; + ascentors.push(...(updatedIouAction ? [{report: expenseReport, reportAction: updatedIouAction, shouldDisplayNewMarker: false}] : [])); + ascentors.push(...(updatedPreviewAction ? [{report: chatReport, reportAction: updatedPreviewAction, shouldDisplayNewMarker: false}] : [])); + addComment(thread, thread.reportID, ascentors, message, CONST.DEFAULT_TIME_ZONE); + await waitForBatchedUpdates(); + }; + await addCommentToThread(transactionThreadReport1, iouAction1ID, 'Testing a comment'); + await addCommentToThread(transactionThreadReport1, iouAction1ID, 'Testing a comment1'); + await addCommentToThread(transactionThreadReport2, iouAction2ID, 'Testing a comment2'); + + // Then the report should have 3 actions + expect(Object.values(transactionThreadReportActions1 ?? {}).length).toBe(3); + // And the report should have 2 actions + expect(Object.values(transactionThreadReportActions2 ?? {}).length).toBe(2); + + iouAction1 = getReportAction(expenseReport.reportID, iouAction1ID); + iouAction2 = getReportAction(expenseReport.reportID, iouAction2ID); + previewAction = getReportAction(chatReport.reportID, previewActionID); + expect(iouAction1?.childVisibleActionCount).toBe(2); + expect(iouAction2?.childVisibleActionCount).toBe(1); + expect(previewAction?.childVisibleActionCount).toBe(3); + + await waitForBatchedUpdates(); + + const mergeParams = { + transactionID: mainTransactionID, + transactionIDList: duplicateTransactionIDs, + created: '2024-01-01 12:00:00', + merchant: 'Updated Merchant', + amount: 100, + currency: CONST.CURRENCY.EUR, + category: 'Travel', + comment: 'Updated comment', + billable: true, + reimbursable: false, + tag: 'UpdatedProject', + receiptID: 123, + reportID, + }; + + // When: Call mergeDuplicates + mergeDuplicates(mergeParams); + await waitForBatchedUpdates(); + + // Then we expect the reportPreview to update with new childVisibleActionCount + previewAction = getReportPreviewAction(chatReport?.reportID, expenseReport?.reportID) ?? undefined; + expect(previewAction).toBeTruthy(); + expect(previewAction?.childVisibleActionCount).toEqual(0); + expect(previewAction?.childCommenterCount).toEqual(0); + + // Then the transaction thread report should be ready to be deleted + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport1.reportID}`, + waitForCollectionCallback: false, + callback: (report) => { + Onyx.disconnect(connection); + expect(report?.reportID).toBeFalsy(); + resolve(); + }, + }); + }); + + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport2.reportID}`, + waitForCollectionCallback: false, + callback: (report) => { + Onyx.disconnect(connection); + expect(report?.reportID).toBeFalsy(); + resolve(); + }, + }); + }); + + // Then the transaction thread report should be deleted in the success onyx data + expect(writeSpy).toHaveBeenCalledWith( + WRITE_COMMANDS.MERGE_DUPLICATES, + expect.objectContaining(mergeParams), + expect.objectContaining({ + successData: expect.arrayContaining([ + expect.objectContaining({key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport1.reportID}`, value: null}), + expect.objectContaining({key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport2.reportID}`, value: null}), + ]), + }), + ); + }); }); describe('resolveDuplicates', () => { diff --git a/tests/actions/MergeTransactionTest.ts b/tests/actions/MergeTransactionTest.ts index ff44e747b421..987f891b9774 100644 --- a/tests/actions/MergeTransactionTest.ts +++ b/tests/actions/MergeTransactionTest.ts @@ -1,11 +1,26 @@ import Onyx from 'react-native-onyx'; -import type {OnyxCollection} from 'react-native-onyx'; +import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; +import {getReportPreviewAction} from '@libs/actions/IOU'; import {areTransactionsEligibleForMerge, mergeTransactionRequest, setMergeTransactionKey, setupMergeTransactionData} from '@libs/actions/MergeTransaction'; +import {addComment, openReport} from '@libs/actions/Report'; +import {getLoginsByAccountIDs} from '@libs/PersonalDetailsUtils'; +import {getReportAction} from '@libs/ReportActionsUtils'; +import {buildTransactionThread, getReportOrDraftReport} from '@libs/ReportUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {MergeTransaction as MergeTransactionType, Report, Transaction, TransactionViolation, TransactionViolations} from '@src/types/onyx'; +import type { + MergeTransaction as MergeTransactionType, + OriginalMessageIOU, + Report, + ReportAction, + ReportActions, + Transaction, + TransactionViolation, + TransactionViolations, +} from '@src/types/onyx'; import createRandomMergeTransaction from '../utils/collections/mergeTransaction'; -import {createExpenseReport} from '../utils/collections/reports'; +import createRandomReportAction from '../utils/collections/reportActions'; +import {createExpenseReport, createRandomReport} from '../utils/collections/reports'; import createRandomTransaction, {createRandomDistanceRequestTransaction} from '../utils/collections/transaction'; import * as TestHelper from '../utils/TestHelper'; import type {MockFetch} from '../utils/TestHelper'; @@ -44,12 +59,19 @@ function createAllTransactionViolations( return allViolations; } +const TEST_EMAIL = 'test@expensifail.com'; +const TEST_ACCOUNT_ID = 1; + describe('mergeTransactionRequest', () => { let mockFetch: MockFetch; beforeAll(() => { Onyx.init({ keys: ONYXKEYS, + initialKeyStates: { + [ONYXKEYS.SESSION]: {accountID: TEST_ACCOUNT_ID, email: TEST_EMAIL}, + [ONYXKEYS.PERSONAL_DETAILS_LIST]: {[TEST_ACCOUNT_ID]: {accountID: TEST_ACCOUNT_ID, login: TEST_EMAIL}}, + }, }); }); @@ -488,6 +510,314 @@ describe('mergeTransactionRequest', () => { expect(updatedSourceReport).toEqual(sourceReport); expect(updatedSourceReport?.reportID).toBe(sourceReport.reportID); }); + + it('should delete the source transaction thread regardless of whether there are visible comments in the thread', async () => { + // Given: A source transaction that is one of multiple transactions in its report + const chatReportID = 'chat-report-123'; + const sourceReportID = 'source-report-123'; + const previewActionID = 'preview-action-123'; + const chatReport: Report = { + ...createRandomReport(0, undefined), + policyID: CONST.POLICY.ID_FAKE, + parentReportID: undefined, + parentReportActionID: undefined, + reportID: chatReportID, + type: 'chat', + }; + let previewAction: OnyxEntry = { + ...createRandomReportAction(0), + actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, + reportActionID: previewActionID, + childMoneyRequestCount: 2, + childVisibleActionCount: 0, + originalMessage: {linkedReportID: sourceReportID}, + }; + const sourceReport = { + ...createExpenseReport(1), + reportID: 'source-report-123', + chatReportID: chatReport.reportID, + }; + const targetTransaction = { + ...createRandomTransaction(1), + transactionID: 'target123', + reportID: 'target-report-456', + }; + const sourceTransaction = { + ...createRandomTransaction(2), + transactionID: 'source456', + reportID: sourceReport.reportID, + }; + const otherTransaction = { + ...createRandomTransaction(3), + transactionID: 'other789', + reportID: sourceReport.reportID, + }; + const mergeTransaction = { + ...createRandomMergeTransaction(1), + targetTransactionID: 'target123', + sourceTransactionID: 'source456', + }; + const mergeTransactionID = 'merge789'; + + let sourceIOUAction: OnyxEntry = { + reportActionID: 'source-action-123', + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + created: '2024-01-01 12:00:00', + originalMessage: { + IOUTransactionID: sourceTransaction.transactionID, + type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, + IOUReportID: sourceReportID, + } as OriginalMessageIOU, + message: [{type: 'TEXT', text: 'Test IOU message'}], + }; + const targetViolations: TransactionViolation[] = []; + const sourceViolations: TransactionViolation[] = []; + + // Set up initial state + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${targetTransaction.transactionID}`, targetTransaction); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${sourceTransaction.transactionID}`, sourceTransaction); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${otherTransaction.transactionID}`, otherTransaction); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${sourceReport.reportID}`, sourceReport); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`, chatReport); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${sourceReport.reportID}`, {[sourceIOUAction.reportActionID]: sourceIOUAction}); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport.reportID}`, {[previewAction.reportActionID]: previewAction}); + await Onyx.set(`${ONYXKEYS.COLLECTION.MERGE_TRANSACTION}${mergeTransactionID}`, mergeTransaction); + + const thread = buildTransactionThread(sourceIOUAction, sourceReport); + + expect(thread.participants).toEqual({ + [TEST_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}, + }); + + const participantAccountIDs = Object.keys(thread.participants ?? {}).map(Number); + const userLogins = getLoginsByAccountIDs(participantAccountIDs); + jest.advanceTimersByTime(10); + openReport(thread.reportID, '', userLogins, thread, sourceIOUAction.reportActionID); + await waitForBatchedUpdates(); + + let transactionThreadReportActions: OnyxEntry; + Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${thread.reportID}`, + callback: (val) => (transactionThreadReportActions = val), + }); + + await waitForBatchedUpdates(); + + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeTruthy(); + resolve(); + }, + }); + }); + + jest.advanceTimersByTime(10); + + // When a comment is added + addComment( + thread, + thread.reportID, + [ + {report: sourceReport, reportAction: sourceIOUAction, shouldDisplayNewMarker: false}, + {report: chatReport, reportAction: previewAction, shouldDisplayNewMarker: false}, + ], + 'test comment', + CONST.DEFAULT_TIME_ZONE, + ); + await waitForBatchedUpdates(); + + // Then the report should have 2 actions + expect(Object.values(transactionThreadReportActions ?? {}).length).toBe(2); + + sourceIOUAction = getReportAction(sourceReport.reportID, sourceIOUAction.reportActionID); + previewAction = getReportAction(chatReport.reportID, previewActionID); + expect(sourceIOUAction?.childVisibleActionCount).toBe(1); + expect(previewAction?.childVisibleActionCount).toBe(1); + + await waitForBatchedUpdates(); + + mockFetch?.pause?.(); + + // When: The merge request is executed + mergeTransactionRequest({ + mergeTransactionID, + mergeTransaction, + targetTransaction, + sourceTransaction, + allTransactionViolations: createAllTransactionViolations(targetTransaction.transactionID, sourceTransaction.transactionID, targetViolations, sourceViolations), + policy: undefined, + policyTags: undefined, + policyCategories: undefined, + currentUserAccountIDParam: 123, + currentUserEmailParam: 'existing@example.com', + isASAPSubmitBetaEnabled: false, + }); + + await waitForBatchedUpdates(); + + // Then we expect the reportPreview to update with new childVisibleActionCount + previewAction = getReportPreviewAction(chatReport.reportID, sourceReport.reportID) as OnyxEntry; + expect(previewAction).toBeTruthy(); + expect(previewAction?.childVisibleActionCount).toEqual(0); + expect(previewAction?.childCommenterCount).toEqual(0); + + // Then the transaction thread report should be ready to be deleted + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + waitForCollectionCallback: false, + callback: (report) => { + Onyx.disconnect(connection); + expect(report?.reportID).toBeFalsy(); + resolve(); + }, + }); + }); + + // When we resume + mockFetch?.resume?.(); + await waitForBatchedUpdates(); + + // Then we expect the reportPreview to update with new childVisibleActionCount + previewAction = getReportPreviewAction(chatReport.reportID, sourceReport.reportID) as OnyxEntry; + expect(previewAction).toBeTruthy(); + expect(previewAction?.childVisibleActionCount).toEqual(0); + expect(previewAction?.childCommenterCount).toEqual(0); + + // Then the transaction thread report should be deleted + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + waitForCollectionCallback: false, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeFalsy(); + resolve(); + }, + }); + }); + }); + + it('should delete the transaction thread of the source unreported transaction', async () => { + // Given: A source transaction that is one of multiple transactions in its report + const selfDMReportID = 'selfDM-report-123'; + const selfDMReport = { + ...createRandomReport(1, CONST.REPORT.CHAT_TYPE.SELF_DM), + reportID: selfDMReportID, + }; + const targetTransaction = { + ...createRandomTransaction(1), + transactionID: 'target123', + reportID: 'target-report-456', + }; + const sourceTransaction = { + ...createRandomTransaction(2), + transactionID: 'source456', + reportID: CONST.REPORT.UNREPORTED_REPORT_ID, + }; + const mergeTransaction = { + ...createRandomMergeTransaction(1), + targetTransactionID: 'target123', + sourceTransactionID: 'source456', + }; + const mergeTransactionID = 'merge789'; + + const sourceIOUAction: ReportAction = { + reportActionID: 'source-action-123', + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + created: '2024-01-01 12:00:00', + originalMessage: { + IOUTransactionID: sourceTransaction.transactionID, + type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, + IOUReportID: selfDMReportID, + } as OriginalMessageIOU, + message: [{type: 'TEXT', text: 'Test IOU message'}], + }; + const targetViolations: TransactionViolation[] = []; + const sourceViolations: TransactionViolation[] = []; + + // Set up initial state + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${targetTransaction.transactionID}`, targetTransaction); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${sourceTransaction.transactionID}`, sourceTransaction); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${selfDMReport.reportID}`, selfDMReport); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${selfDMReport.reportID}`, {[sourceIOUAction.reportActionID]: sourceIOUAction}); + await Onyx.set(`${ONYXKEYS.COLLECTION.MERGE_TRANSACTION}${mergeTransactionID}`, mergeTransaction); + + const thread = buildTransactionThread(sourceIOUAction, selfDMReport); + + expect(thread.participants).toEqual({ + [TEST_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}, + }); + + const participantAccountIDs = Object.keys(thread.participants ?? {}).map(Number); + const userLogins = getLoginsByAccountIDs(participantAccountIDs); + jest.advanceTimersByTime(10); + openReport(thread.reportID, '', userLogins, thread, sourceIOUAction.reportActionID); + await waitForBatchedUpdates(); + + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeTruthy(); + resolve(); + }, + }); + }); + + mockFetch?.pause?.(); + + // When: The merge request is executed + mergeTransactionRequest({ + mergeTransactionID, + mergeTransaction, + targetTransaction, + sourceTransaction, + allTransactionViolations: createAllTransactionViolations(targetTransaction.transactionID, sourceTransaction.transactionID, targetViolations, sourceViolations), + policy: undefined, + policyTags: undefined, + policyCategories: undefined, + currentUserAccountIDParam: 123, + currentUserEmailParam: 'existing@example.com', + isASAPSubmitBetaEnabled: false, + }); + + await waitForBatchedUpdates(); + + // Then the transaction thread report should be ready to be deleted + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + waitForCollectionCallback: false, + callback: (report) => { + Onyx.disconnect(connection); + expect(report?.reportID).toBeFalsy(); + resolve(); + }, + }); + }); + + // When we resume + mockFetch?.resume?.(); + await waitForBatchedUpdates(); + + // Then the transaction thread report should be deleted + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + waitForCollectionCallback: false, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeFalsy(); + resolve(); + }, + }); + }); + }); }); }); From 7f267c36a1902209826a9973b24166bbe7bfe06d Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Sat, 10 Jan 2026 22:22:48 +0700 Subject: [PATCH 08/20] fix lint --- tests/actions/IOUTest.ts | 25 +++++++++---------------- tests/actions/MergeTransactionTest.ts | 2 +- 2 files changed, 10 insertions(+), 17 deletions(-) diff --git a/tests/actions/IOUTest.ts b/tests/actions/IOUTest.ts index cc9c2901e45a..1f90e423bf0e 100644 --- a/tests/actions/IOUTest.ts +++ b/tests/actions/IOUTest.ts @@ -82,14 +82,7 @@ import { isMoneyRequestAction, } from '@libs/ReportActionsUtils'; import type {OptimisticChatReport} from '@libs/ReportUtils'; -import { - buildOptimisticIOUReport, - buildOptimisticIOUReportAction, - buildTransactionThread, - createDraftTransactionAndNavigateToParticipantSelector, - getReportOrDraftReport, - isIOUReport, -} from '@libs/ReportUtils'; +import {buildOptimisticIOUReport, buildOptimisticIOUReportAction, buildTransactionThread, createDraftTransactionAndNavigateToParticipantSelector, isIOUReport} from '@libs/ReportUtils'; import {buildOptimisticTransaction, getValidWaypoints, isDistanceRequest as isDistanceRequestUtil} from '@libs/TransactionUtils'; import type {IOUAction} from '@src/CONST'; import CONST from '@src/CONST'; @@ -5968,10 +5961,10 @@ describe('actions/IOU', () => { // When a comment is added let iouPreview = getReportPreviewAction(chatReport?.reportID, iouReport?.reportID); - const ascentors = []; - ascentors.push(...(iouReport && createIOUAction ? [{report: iouReport, reportAction: createIOUAction, shouldDisplayNewMarker: false}] : [])); - ascentors.push(...(chatReport && iouPreview ? [{report: chatReport, reportAction: iouPreview, shouldDisplayNewMarker: false}] : [])); - addComment(thread, thread.reportID, ascentors, 'Testing a comment', CONST.DEFAULT_TIME_ZONE); + const ancestors = []; + ancestors.push(...(iouReport && createIOUAction ? [{report: iouReport, reportAction: createIOUAction, shouldDisplayNewMarker: false}] : [])); + ancestors.push(...(chatReport && iouPreview ? [{report: chatReport, reportAction: iouPreview, shouldDisplayNewMarker: false}] : [])); + addComment(thread, thread.reportID, ancestors, 'Testing a comment', CONST.DEFAULT_TIME_ZONE); await waitForBatchedUpdates(); // Then comment details should match the expected report action @@ -10710,10 +10703,10 @@ describe('actions/IOU', () => { const addCommentToThread = async (thread: Report, iouActionID: string, message: string) => { const updatedIouAction = getReportAction(expenseReport.reportID, iouActionID); const updatedPreviewAction = getReportAction(chatReport.reportID, previewActionID); - const ascentors = []; - ascentors.push(...(updatedIouAction ? [{report: expenseReport, reportAction: updatedIouAction, shouldDisplayNewMarker: false}] : [])); - ascentors.push(...(updatedPreviewAction ? [{report: chatReport, reportAction: updatedPreviewAction, shouldDisplayNewMarker: false}] : [])); - addComment(thread, thread.reportID, ascentors, message, CONST.DEFAULT_TIME_ZONE); + const ancestors = []; + ancestors.push(...(updatedIouAction ? [{report: expenseReport, reportAction: updatedIouAction, shouldDisplayNewMarker: false}] : [])); + ancestors.push(...(updatedPreviewAction ? [{report: chatReport, reportAction: updatedPreviewAction, shouldDisplayNewMarker: false}] : [])); + addComment(thread, thread.reportID, ancestors, message, CONST.DEFAULT_TIME_ZONE); await waitForBatchedUpdates(); }; await addCommentToThread(transactionThreadReport1, iouAction1ID, 'Testing a comment'); diff --git a/tests/actions/MergeTransactionTest.ts b/tests/actions/MergeTransactionTest.ts index 987f891b9774..f783d25efb12 100644 --- a/tests/actions/MergeTransactionTest.ts +++ b/tests/actions/MergeTransactionTest.ts @@ -5,7 +5,7 @@ import {areTransactionsEligibleForMerge, mergeTransactionRequest, setMergeTransa import {addComment, openReport} from '@libs/actions/Report'; import {getLoginsByAccountIDs} from '@libs/PersonalDetailsUtils'; import {getReportAction} from '@libs/ReportActionsUtils'; -import {buildTransactionThread, getReportOrDraftReport} from '@libs/ReportUtils'; +import {buildTransactionThread} from '@libs/ReportUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type { From 9baa18507210955ed9d043fc812faa955fd0829b Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Tue, 13 Jan 2026 11:30:14 +0700 Subject: [PATCH 09/20] Fix - The "Reply" hyperlink below the expense preview is shown --- src/libs/actions/IOU/DuplicateAction.ts | 25 +- src/libs/actions/IOU/index.ts | 279 ------- tests/actions/IOUTest.ts | 802 +------------------ tests/actions/IOUTest/DuplicateActionTest.ts | 217 ++++- 4 files changed, 240 insertions(+), 1083 deletions(-) diff --git a/src/libs/actions/IOU/DuplicateAction.ts b/src/libs/actions/IOU/DuplicateAction.ts index 0d52f42439a1..b1409506e586 100644 --- a/src/libs/actions/IOU/DuplicateAction.ts +++ b/src/libs/actions/IOU/DuplicateAction.ts @@ -25,6 +25,7 @@ import type * as OnyxTypes from '@src/types/onyx'; import type {Attendee} from '@src/types/onyx/IOU'; import type {WaypointCollection} from '@src/types/onyx/Transaction'; import type {CreateTrackExpenseParams, RequestMoneyInformation} from '.'; +import {getCleanUpTransactionThreadReportOnyxData} from '.'; import { getAllReportActionsFromIOU, getAllReports, @@ -190,6 +191,25 @@ function mergeDuplicates({transactionThreadReportID: optimisticTransactionThread }, {}), }; + const cleanUpTransactionThreadReportsOptimisticData = []; + const cleanUpTransactionThreadReportsSuccessData = []; + const cleanUpTransactionThreadReportsFailureData = []; + let updatedReportPreviewAction; + for (const [index, iouAction] of Object.entries(iouActionsToDelete)) { + const transactionThreadID = iouAction.childReportID; + const shouldDeleteTransactionThread = !!transactionThreadID; + const cleanUpTransactionThreadReportOnyxDataForIouAction = getCleanUpTransactionThreadReportOnyxData({ + transactionThreadID, + shouldDeleteTransactionThread, + reportAction: iouAction, + updatedReportPreviewAction, + shouldAddUpdatedReportPreviewActionToOnyxData: Number(index) === iouActionsToDelete.length - 1, + }); + cleanUpTransactionThreadReportsOptimisticData.push(...cleanUpTransactionThreadReportOnyxDataForIouAction.optimisticData); + cleanUpTransactionThreadReportsSuccessData.push(...cleanUpTransactionThreadReportOnyxDataForIouAction.successData); + cleanUpTransactionThreadReportsFailureData.push(...cleanUpTransactionThreadReportOnyxDataForIouAction.failureData); + updatedReportPreviewAction = cleanUpTransactionThreadReportOnyxDataForIouAction.updatedReportPreviewAction; + } const optimisticReportAction = buildOptimisticResolvedDuplicatesReportAction(); const transactionThreadReportID = @@ -212,7 +232,7 @@ function mergeDuplicates({transactionThreadReportID: optimisticTransactionThread const optimisticData: OnyxUpdate[] = []; const failureData: OnyxUpdate[] = []; - const successData: Array> = []; + const successData: Array> = []; optimisticData.push( optimisticTransactionData, @@ -221,7 +241,9 @@ function mergeDuplicates({transactionThreadReportID: optimisticTransactionThread expenseReportOptimisticData, expenseReportActionsOptimisticData, optimisticReportActionData, + ...cleanUpTransactionThreadReportsOptimisticData, ); + successData.push(...cleanUpTransactionThreadReportsSuccessData); failureData.push( failureTransactionData, ...failureTransactionDuplicatesData, @@ -229,6 +251,7 @@ function mergeDuplicates({transactionThreadReportID: optimisticTransactionThread expenseReportFailureData, expenseReportActionsFailureData, failureReportActionData, + ...cleanUpTransactionThreadReportsFailureData, ); if (optimisticTransactionThreadReportID) { diff --git a/src/libs/actions/IOU/index.ts b/src/libs/actions/IOU/index.ts index f006bdfe9054..00851b6d9275 100644 --- a/src/libs/actions/IOU/index.ts +++ b/src/libs/actions/IOU/index.ts @@ -12517,285 +12517,6 @@ function getIOURequestPolicyID(transaction: OnyxEntry, re return workspaceSender?.policyID ?? report?.policyID; } -function getIOUActionForTransactions(transactionIDList: Array, iouReportID: string | undefined): Array> { - return Object.values(allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReportID}`] ?? {})?.filter( - (reportAction): reportAction is ReportAction => { - if (!isMoneyRequestAction(reportAction)) { - return false; - } - const message = getOriginalMessage(reportAction); - if (!message?.IOUTransactionID) { - return false; - } - return transactionIDList.includes(message.IOUTransactionID); - }, - ); -} - -/** Merge several transactions into one by updating the fields of the one we want to keep and deleting the rest */ -function mergeDuplicates({transactionThreadReportID: optimisticTransactionThreadReportID, ...params}: MergeDuplicatesParams) { - const allParams: MergeDuplicatesParams = {...params}; - - const originalSelectedTransaction = allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${params.transactionID}`]; - - const optimisticTransactionData: OnyxUpdate = { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.TRANSACTION}${params.transactionID}`, - value: { - ...originalSelectedTransaction, - billable: params.billable, - comment: { - comment: params.comment, - }, - category: params.category, - created: params.created, - currency: params.currency, - modifiedMerchant: params.merchant, - reimbursable: params.reimbursable, - tag: params.tag, - }, - }; - - const failureTransactionData: OnyxUpdate = { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.TRANSACTION}${params.transactionID}`, - // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style - value: originalSelectedTransaction as OnyxTypes.Transaction, - }; - - const optimisticTransactionDuplicatesData: OnyxUpdate[] = params.transactionIDList.map((id) => ({ - onyxMethod: Onyx.METHOD.SET, - key: `${ONYXKEYS.COLLECTION.TRANSACTION}${id}`, - value: null, - })); - - const failureTransactionDuplicatesData: OnyxUpdate[] = params.transactionIDList.map((id) => ({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.TRANSACTION}${id}`, - // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style - value: allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${id}`] as OnyxTypes.Transaction, - })); - - const optimisticTransactionViolations: OnyxUpdate[] = [...params.transactionIDList, params.transactionID].map((id) => { - const violations = allTransactionViolations[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${id}`] ?? []; - return { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${id}`, - // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 - value: violations.filter((violation) => violation.name !== CONST.VIOLATIONS.DUPLICATED_TRANSACTION), - }; - }); - - const failureTransactionViolations: OnyxUpdate[] = [...params.transactionIDList, params.transactionID].map((id) => { - const violations = allTransactionViolations[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${id}`] ?? []; - return { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${id}`, - value: violations, - }; - }); - - const duplicateTransactionTotals = params.transactionIDList.reduce((total, id) => { - const duplicateTransaction = allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${id}`]; - if (!duplicateTransaction) { - return total; - } - return total + duplicateTransaction.amount; - }, 0); - - const expenseReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${params.reportID}`]; - const expenseReportOptimisticData: OnyxUpdate = { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${params.reportID}`, - value: { - total: (expenseReport?.total ?? 0) - duplicateTransactionTotals, - }, - }; - const expenseReportFailureData: OnyxUpdate = { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${params.reportID}`, - value: { - total: expenseReport?.total, - }, - }; - - const iouActionsToDelete = params.reportID ? getIOUActionForTransactions(params.transactionIDList, params.reportID) : []; - - const deletedTime = DateUtils.getDBTime(); - const expenseReportActionsOptimisticData: OnyxUpdate = { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${params.reportID}`, - value: iouActionsToDelete.reduce>>>((val, reportAction) => { - const firstMessage = Array.isArray(reportAction.message) ? reportAction.message.at(0) : null; - // eslint-disable-next-line no-param-reassign - val[reportAction.reportActionID] = { - originalMessage: { - deleted: deletedTime, - }, - ...(firstMessage && { - message: [ - { - ...firstMessage, - deleted: deletedTime, - }, - ...(Array.isArray(reportAction.message) ? reportAction.message.slice(1) : []), - ], - }), - ...(!Array.isArray(reportAction.message) && { - message: { - deleted: deletedTime, - }, - }), - }; - return val; - }, {}), - }; - const expenseReportActionsFailureData: OnyxUpdate = { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${params.reportID}`, - value: iouActionsToDelete.reduce>>>>((val, reportAction) => { - // eslint-disable-next-line no-param-reassign - val[reportAction.reportActionID] = { - originalMessage: { - deleted: null, - }, - message: reportAction.message, - }; - return val; - }, {}), - }; - - const cleanUpTransactionThreadReportsOptimisticData = []; - const cleanUpTransactionThreadReportsSuccessData = []; - const cleanUpTransactionThreadReportsFailureData = []; - let updatedReportPreviewAction; - for (const [index, iouAction] of Object.entries(iouActionsToDelete)) { - const transactionThreadID = iouAction.childReportID; - const shouldDeleteTransactionThread = !!transactionThreadID; - const cleanUpTransactionThreadReportOnyxDataForIouAction = getCleanUpTransactionThreadReportOnyxData({ - transactionThreadID, - shouldDeleteTransactionThread, - reportAction: iouAction, - updatedReportPreviewAction, - shouldAddUpdatedReportPreviewActionToOnyxData: Number(index) === iouActionsToDelete.length - 1, - }); - cleanUpTransactionThreadReportsOptimisticData.push(...cleanUpTransactionThreadReportOnyxDataForIouAction.optimisticData); - cleanUpTransactionThreadReportsSuccessData.push(...cleanUpTransactionThreadReportOnyxDataForIouAction.successData); - cleanUpTransactionThreadReportsFailureData.push(...cleanUpTransactionThreadReportOnyxDataForIouAction.failureData); - updatedReportPreviewAction = cleanUpTransactionThreadReportOnyxDataForIouAction.updatedReportPreviewAction; - } - const optimisticReportAction = buildOptimisticResolvedDuplicatesReportAction(); - - const transactionThreadReportID = - optimisticTransactionThreadReportID ?? (params.reportID ? getIOUActionForTransactions([params.transactionID], params.reportID).at(0)?.childReportID : undefined); - const optimisticReportActionData: OnyxUpdate = { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReportID}`, - value: { - [optimisticReportAction.reportActionID]: optimisticReportAction, - }, - }; - - const failureReportActionData: OnyxUpdate = { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReportID}`, - value: { - [optimisticReportAction.reportActionID]: null, - }, - }; - - const optimisticData: OnyxUpdate[] = []; - const failureData: OnyxUpdate[] = []; - const successData: Array> = []; - - optimisticData.push( - optimisticTransactionData, - ...optimisticTransactionDuplicatesData, - ...optimisticTransactionViolations, - expenseReportOptimisticData, - expenseReportActionsOptimisticData, - optimisticReportActionData, - ...cleanUpTransactionThreadReportsOptimisticData, - ); - successData.push(...cleanUpTransactionThreadReportsSuccessData); - failureData.push( - failureTransactionData, - ...failureTransactionDuplicatesData, - ...failureTransactionViolations, - expenseReportFailureData, - expenseReportActionsFailureData, - failureReportActionData, - ...cleanUpTransactionThreadReportsFailureData, - ); - - if (optimisticTransactionThreadReportID) { - const iouAction = getIOUActionForReportID(params.reportID, params.transactionID); - const optimisticCreatedAction = buildOptimisticCreatedReportAction(currentUserEmail); - const optimisticTransactionThreadReport = buildTransactionThread(iouAction, expenseReport, undefined, optimisticTransactionThreadReportID); - - allParams.transactionThreadReportID = optimisticTransactionThreadReportID; - allParams.createdReportActionIDForThread = optimisticCreatedAction?.reportActionID; - optimisticTransactionThreadReport.pendingFields = { - createChat: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD, - }; - - optimisticData.push( - { - onyxMethod: Onyx.METHOD.SET, - key: `${ONYXKEYS.COLLECTION.REPORT}${optimisticTransactionThreadReportID}`, - value: optimisticTransactionThreadReport, - }, - { - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticTransactionThreadReportID}`, - value: {[optimisticCreatedAction.reportActionID]: optimisticCreatedAction}, - }, - ); - - failureData.push( - { - onyxMethod: Onyx.METHOD.SET, - key: `${ONYXKEYS.COLLECTION.REPORT}${optimisticTransactionThreadReportID}`, - value: null, - }, - { - onyxMethod: Onyx.METHOD.SET, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticTransactionThreadReportID}`, - value: null, - }, - ); - - if (iouAction?.reportActionID) { - // Context: Right now updates provided in one Onyx.update can reach component in different renders. - // This is because `Onyx.merge` is batched and `Onyx.set` is not, so it may not be necessary after https://github.com/Expensify/App/issues/71207 is resolved. - // Setting up the transactions null values (removing of the transactions) happens faster than setting of optimistic childReportID, - // though both updates come from one optimistic data. - // To escape unexpected effects we setting the childReportID using Onyx.merge, making sure it will be in place when transactions are cleared out. - Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticTransactionThreadReport?.parentReportID}`, { - [iouAction?.reportActionID]: {childReportID: optimisticTransactionThreadReportID, childType: CONST.REPORT.TYPE.CHAT}, - }); - optimisticData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticTransactionThreadReport?.parentReportID}`, - value: {[iouAction?.reportActionID]: {childReportID: optimisticTransactionThreadReportID, childType: CONST.REPORT.TYPE.CHAT}}, - }); - failureData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticTransactionThreadReport?.parentReportID}`, - value: {[iouAction?.reportActionID]: {childReportID: null, childType: null}}, - }); - } - - successData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticTransactionThreadReportID}`, - value: {[optimisticCreatedAction.reportActionID]: {pendingAction: null}}, - }); - } - - API.write(WRITE_COMMANDS.MERGE_DUPLICATES, {...allParams, reportActionID: optimisticReportAction.reportActionID}, {optimisticData, failureData, successData}); -} - function updateLastLocationPermissionPrompt() { Onyx.set(ONYXKEYS.NVP_LAST_LOCATION_PERMISSION_PROMPT, new Date().toISOString()); } diff --git a/tests/actions/IOUTest.ts b/tests/actions/IOUTest.ts index 55058a0af1f3..2ac1a45febb1 100644 --- a/tests/actions/IOUTest.ts +++ b/tests/actions/IOUTest.ts @@ -3780,6 +3780,7 @@ describe('actions/IOU', () => { currentUserPersonalDetails, transactionViolations: {}, policyRecentlyUsedCurrencies: [], + quickAction: undefined, }); await waitForBatchedUpdates(); @@ -5933,6 +5934,7 @@ describe('actions/IOU', () => { currentUserAccountIDParam: 123, currentUserEmailParam: 'existing@example.com', policyRecentlyUsedCurrencies: [], + quickAction: undefined, }); } @@ -10301,806 +10303,6 @@ describe('actions/IOU', () => { }); }); - describe('mergeDuplicates', () => { - let writeSpy: jest.SpyInstance; - - beforeEach(() => { - jest.clearAllMocks(); - global.fetch = getGlobalFetchMock(); - // eslint-disable-next-line rulesdir/no-multiple-api-calls - writeSpy = jest.spyOn(API, 'write').mockImplementation((command, params, options) => { - // Apply optimistic data for testing - if (options?.optimisticData) { - for (const update of options.optimisticData) { - if (update.onyxMethod === Onyx.METHOD.MERGE) { - Onyx.merge(update.key, update.value); - } else if (update.onyxMethod === Onyx.METHOD.SET) { - Onyx.set(update.key, update.value); - } - } - } - return Promise.resolve(); - }); - return Onyx.clear(); - }); - - afterEach(() => { - writeSpy.mockRestore(); - }); - - const createMockTransaction = (id: string, reportID: string, amount = 100): Transaction => ({ - ...createRandomTransaction(Number(id)), - transactionID: id, - reportID, - amount, - created: '2024-01-01 12:00:00', - currency: 'EUR', - merchant: 'Test Merchant', - modifiedMerchant: 'Updated Merchant', - comment: {comment: 'Updated comment'}, - category: 'Travel', - tag: 'UpdatedProject', - billable: true, - reimbursable: false, - }); - - const createMockReport = (reportID: string, total = 300): Report => ({ - ...createRandomReport(Number(reportID), undefined), - reportID, - type: CONST.REPORT.TYPE.EXPENSE, - total, - }); - - const createMockViolations = () => [ - {name: CONST.VIOLATIONS.DUPLICATED_TRANSACTION, type: CONST.VIOLATION_TYPES.VIOLATION}, - {name: CONST.VIOLATIONS.MISSING_CATEGORY, type: CONST.VIOLATION_TYPES.VIOLATION}, - ]; - - const createMockIouAction = (transactionID: string, reportActionID: string, childReportID: string, IOUReportID?: string): ReportAction => ({ - reportActionID, - actionName: CONST.REPORT.ACTIONS.TYPE.IOU, - created: '2024-01-01 12:00:00', - originalMessage: { - IOUTransactionID: transactionID, - type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, - IOUReportID, - } as OriginalMessageIOU, - message: [{type: 'TEXT', text: 'Test IOU message'}], - childReportID, - }); - - it('should merge duplicate transactions successfully', async () => { - // Given: Set up test data with main transaction and duplicates - const reportID = 'report123'; - const mainTransactionID = 'main123'; - const duplicate1ID = 'dup456'; - const duplicate2ID = 'dup789'; - const duplicateTransactionIDs = [duplicate1ID, duplicate2ID]; - const childReportID = 'child123'; - - const mainTransaction = createMockTransaction(mainTransactionID, reportID, 150); - const duplicateTransaction1 = createMockTransaction(duplicate1ID, reportID, 100); - const duplicateTransaction2 = createMockTransaction(duplicate2ID, reportID, 50); - const expenseReport = createMockReport(reportID, 300); - - const mainViolations = createMockViolations(); - const duplicate1Violations = createMockViolations(); - const duplicate2Violations = createMockViolations(); - - const iouAction1 = createMockIouAction(duplicate1ID, 'action456', childReportID); - const iouAction2 = createMockIouAction(duplicate2ID, 'action789', childReportID); - - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`, mainTransaction); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate1ID}`, duplicateTransaction1); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate2ID}`, duplicateTransaction2); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, expenseReport); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${mainTransactionID}`, mainViolations); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate1ID}`, duplicate1Violations); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate2ID}`, duplicate2Violations); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, { - action456: iouAction1, - action789: iouAction2, - }); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${childReportID}`, {}); - await waitForBatchedUpdates(); - - const mergeParams = { - transactionID: mainTransactionID, - transactionIDList: duplicateTransactionIDs, - created: '2024-01-01 12:00:00', - merchant: 'Updated Merchant', - amount: 200, - currency: CONST.CURRENCY.EUR, - category: 'Travel', - comment: 'Updated comment', - billable: true, - reimbursable: false, - tag: 'UpdatedProject', - receiptID: 123, - reportID, - }; - - // When: Call mergeDuplicates - mergeDuplicates(mergeParams); - await waitForBatchedUpdates(); - - // Then: Verify main transaction was updated - const updatedMainTransaction = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`); - expect(updatedMainTransaction).toMatchObject({ - billable: true, - comment: {comment: 'Updated comment'}, - category: 'Travel', - created: '2024-01-01 12:00:00', - currency: CONST.CURRENCY.EUR, - modifiedMerchant: 'Updated Merchant', - reimbursable: false, - tag: 'UpdatedProject', - }); - - // Then: Verify duplicate transactions were removed - const removedDuplicate1 = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate1ID}`); - const removedDuplicate2 = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate2ID}`); - expect(removedDuplicate1).toBeFalsy(); - expect(removedDuplicate2).toBeFalsy(); - - // Then: Verify violations were filtered to remove DUPLICATED_TRANSACTION - const updatedMainViolations = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${mainTransactionID}`); - const updatedDup1Violations = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate1ID}`); - const updatedDup2Violations = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate2ID}`); - - expect(updatedMainViolations).toEqual([{name: CONST.VIOLATIONS.MISSING_CATEGORY, type: CONST.VIOLATION_TYPES.VIOLATION}]); - expect(updatedDup1Violations).toEqual([{name: CONST.VIOLATIONS.MISSING_CATEGORY, type: CONST.VIOLATION_TYPES.VIOLATION}]); - expect(updatedDup2Violations).toEqual([{name: CONST.VIOLATIONS.MISSING_CATEGORY, type: CONST.VIOLATION_TYPES.VIOLATION}]); - - // Then: Verify expense report total was updated - const updatedReport = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`); - expect(updatedReport?.total).toBe(150); // 300 - 100 - 50 = 150 - - // Then: Verify IOU actions were marked as deleted - const updatedReportActions = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`); - expect(getOriginalMessage(updatedReportActions?.action456)).toHaveProperty('deleted'); - expect(getOriginalMessage(updatedReportActions?.action789)).toHaveProperty('deleted'); - - // Then: Verify API was called with correct parameters - expect(writeSpy).toHaveBeenCalledWith( - WRITE_COMMANDS.MERGE_DUPLICATES, - expect.objectContaining(mergeParams), - expect.objectContaining({ - optimisticData: expect.arrayContaining([]), - failureData: expect.arrayContaining([]), - }), - ); - }); - - it('should handle empty duplicate transaction list', async () => { - // Given: Set up test data with only main transaction - const reportID = 'report123'; - const mainTransactionID = 'main123'; - const mainTransaction = createMockTransaction(mainTransactionID, reportID); - const expenseReport = createMockReport(reportID, 150); - - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`, mainTransaction); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, expenseReport); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${mainTransactionID}`, []); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, {}); - await waitForBatchedUpdates(); - - const mergeParams = { - transactionID: mainTransactionID, - transactionIDList: [], - created: '2024-01-01 12:00:00', - merchant: 'Updated Merchant', - amount: 200, - currency: CONST.CURRENCY.EUR, - category: 'Travel', - comment: 'Updated comment', - billable: true, - reimbursable: false, - tag: 'UpdatedProject', - receiptID: 123, - reportID, - }; - - // When: Call mergeDuplicates with empty duplicate list - mergeDuplicates(mergeParams); - await waitForBatchedUpdates(); - - // Then: Verify main transaction was still updated - const updatedMainTransaction = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`); - expect(updatedMainTransaction).toMatchObject({ - billable: true, - comment: {comment: 'Updated comment'}, - category: 'Travel', - modifiedMerchant: 'Updated Merchant', - }); - - // Then: Verify expense report total remained unchanged (no duplicates to subtract) - const updatedReport = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`); - expect(updatedReport?.total).toBe(150); - }); - - it('should handle missing expense report gracefully', async () => { - // Given: Set up test data without expense report - const reportID = 'report123'; - const mainTransactionID = 'main123'; - const duplicate1ID = 'dup456'; - const duplicateTransactionIDs = [duplicate1ID]; - - const mainTransaction = createMockTransaction(mainTransactionID, reportID); - const duplicateTransaction = createMockTransaction(duplicate1ID, reportID, 50); - - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`, mainTransaction); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate1ID}`, duplicateTransaction); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${mainTransactionID}`, []); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate1ID}`, []); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, {}); - await waitForBatchedUpdates(); - - const mergeParams = { - transactionID: mainTransactionID, - transactionIDList: duplicateTransactionIDs, - created: '2024-01-01 12:00:00', - merchant: 'Updated Merchant', - amount: 200, - currency: CONST.CURRENCY.EUR, - category: 'Travel', - comment: 'Updated comment', - billable: true, - reimbursable: false, - tag: 'UpdatedProject', - receiptID: 123, - reportID, - }; - - // When: Call mergeDuplicates without expense report - mergeDuplicates(mergeParams); - await waitForBatchedUpdates(); - - // Then: Verify function completed without errors - const updatedMainTransaction = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`); - expect(updatedMainTransaction).toMatchObject({ - category: 'Travel', - modifiedMerchant: 'Updated Merchant', - }); - - // Then: Verify API was still called - expect(writeSpy).toHaveBeenCalledWith(WRITE_COMMANDS.MERGE_DUPLICATES, expect.objectContaining({}), expect.objectContaining({})); - }); - - it('should delete the thread reports of the duplicated transactions and update the comment count of the preview report', async () => { - // Given: Set up test data with main transaction and duplicates - const chatReportID = 'report123'; - const reportID = 'report456'; - const mainTransactionID = 'main123'; - const duplicate1ID = 'dup456'; - const duplicate2ID = 'dup789'; - const duplicateTransactionIDs = [duplicate1ID, duplicate2ID]; - const previewActionID = 'action123'; - const iouAction1ID = 'action456'; - const iouAction2ID = 'action789'; - - const chatReport: Report = { - ...createRandomReport(0, undefined), - policyID: CONST.POLICY.ID_FAKE, - parentReportID: undefined, - parentReportActionID: undefined, - reportID: chatReportID, - type: 'chat', - }; - let previewAction: OnyxEntry = { - ...createRandomReportAction(0), - actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, - reportActionID: previewActionID, - childMoneyRequestCount: 3, - childVisibleActionCount: 0, - originalMessage: {linkedReportID: reportID}, - }; - const expenseReport: Report = { - ...createMockReport(reportID, 300), - chatReportID: chatReport.reportID, - parentReportID: chatReport.reportID, - parentReportActionID: previewAction.reportActionID, - }; - const mainTransaction = createMockTransaction(mainTransactionID, reportID, 100); - const duplicateTransaction1 = createMockTransaction(duplicate1ID, reportID, 100); - const duplicateTransaction2 = createMockTransaction(duplicate2ID, reportID, 100); - - const mainViolations = createMockViolations(); - const duplicate1Violations = createMockViolations(); - const duplicate2Violations = createMockViolations(); - - let iouAction1 = createMockIouAction(duplicate1ID, iouAction1ID, '', reportID) as OnyxEntry; - let iouAction2 = createMockIouAction(duplicate2ID, iouAction2ID, '', reportID) as OnyxEntry; - - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`, mainTransaction); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate1ID}`, duplicateTransaction1); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate2ID}`, duplicateTransaction2); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, expenseReport); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`, chatReport); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${mainTransactionID}`, mainViolations); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate1ID}`, duplicate1Violations); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate2ID}`, duplicate2Violations); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReportID}`, { - [previewActionID]: previewAction, - }); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, { - [iouAction1ID]: iouAction1, - [iouAction2ID]: iouAction2, - }); - await waitForBatchedUpdates(); - - const transactionThreadReport1 = buildTransactionThread(iouAction1, expenseReport); - const transactionThreadReport2 = buildTransactionThread(iouAction2, expenseReport); - - expect(transactionThreadReport1.participants).toEqual({ - [RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}, - }); - expect(transactionThreadReport2.participants).toEqual({ - [RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}, - }); - - const participantAccountIDs = Object.keys(transactionThreadReport1.participants ?? {}).map(Number); - const userLogins = getLoginsByAccountIDs(participantAccountIDs); - jest.advanceTimersByTime(10); - openReport(transactionThreadReport1.reportID, '', userLogins, transactionThreadReport1, iouAction1?.reportActionID); - openReport(transactionThreadReport2.reportID, '', userLogins, transactionThreadReport1, iouAction2?.reportActionID); - await waitForBatchedUpdates(); - - let transactionThreadReportActions1: OnyxEntry; - let transactionThreadReportActions2: OnyxEntry; - Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReport1.reportID}`, - callback: (val) => (transactionThreadReportActions1 = val), - }); - Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReport2.reportID}`, - callback: (val) => (transactionThreadReportActions2 = val), - }); - await waitForBatchedUpdates(); - - await new Promise((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport1.reportID}`, - callback: (report) => { - Onyx.disconnect(connection); - expect(report).toBeTruthy(); - resolve(); - }, - }); - }); - await new Promise((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport2.reportID}`, - callback: (report) => { - Onyx.disconnect(connection); - expect(report).toBeTruthy(); - resolve(); - }, - }); - }); - - jest.advanceTimersByTime(10); - - // When a comment is added - const addCommentToThread = async (thread: Report, iouActionID: string, message: string) => { - const updatedIouAction = getReportAction(expenseReport.reportID, iouActionID); - const updatedPreviewAction = getReportAction(chatReport.reportID, previewActionID); - const ancestors = []; - ancestors.push(...(updatedIouAction ? [{report: expenseReport, reportAction: updatedIouAction, shouldDisplayNewMarker: false}] : [])); - ancestors.push(...(updatedPreviewAction ? [{report: chatReport, reportAction: updatedPreviewAction, shouldDisplayNewMarker: false}] : [])); - addComment(thread, thread.reportID, ancestors, message, CONST.DEFAULT_TIME_ZONE); - await waitForBatchedUpdates(); - }; - await addCommentToThread(transactionThreadReport1, iouAction1ID, 'Testing a comment'); - await addCommentToThread(transactionThreadReport1, iouAction1ID, 'Testing a comment1'); - await addCommentToThread(transactionThreadReport2, iouAction2ID, 'Testing a comment2'); - - // Then the report should have 3 actions - expect(Object.values(transactionThreadReportActions1 ?? {}).length).toBe(3); - // And the report should have 2 actions - expect(Object.values(transactionThreadReportActions2 ?? {}).length).toBe(2); - - iouAction1 = getReportAction(expenseReport.reportID, iouAction1ID); - iouAction2 = getReportAction(expenseReport.reportID, iouAction2ID); - previewAction = getReportAction(chatReport.reportID, previewActionID); - expect(iouAction1?.childVisibleActionCount).toBe(2); - expect(iouAction2?.childVisibleActionCount).toBe(1); - expect(previewAction?.childVisibleActionCount).toBe(3); - - await waitForBatchedUpdates(); - - const mergeParams = { - transactionID: mainTransactionID, - transactionIDList: duplicateTransactionIDs, - created: '2024-01-01 12:00:00', - merchant: 'Updated Merchant', - amount: 100, - currency: CONST.CURRENCY.EUR, - category: 'Travel', - comment: 'Updated comment', - billable: true, - reimbursable: false, - tag: 'UpdatedProject', - receiptID: 123, - reportID, - }; - - // When: Call mergeDuplicates - mergeDuplicates(mergeParams); - await waitForBatchedUpdates(); - - // Then we expect the reportPreview to update with new childVisibleActionCount - previewAction = getReportPreviewAction(chatReport?.reportID, expenseReport?.reportID) ?? undefined; - expect(previewAction).toBeTruthy(); - expect(previewAction?.childVisibleActionCount).toEqual(0); - expect(previewAction?.childCommenterCount).toEqual(0); - - // Then the transaction thread report should be ready to be deleted - await new Promise((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport1.reportID}`, - waitForCollectionCallback: false, - callback: (report) => { - Onyx.disconnect(connection); - expect(report?.reportID).toBeFalsy(); - resolve(); - }, - }); - }); - - await new Promise((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport2.reportID}`, - waitForCollectionCallback: false, - callback: (report) => { - Onyx.disconnect(connection); - expect(report?.reportID).toBeFalsy(); - resolve(); - }, - }); - }); - - // Then the transaction thread report should be deleted in the success onyx data - expect(writeSpy).toHaveBeenCalledWith( - WRITE_COMMANDS.MERGE_DUPLICATES, - expect.objectContaining(mergeParams), - expect.objectContaining({ - successData: expect.arrayContaining([ - expect.objectContaining({key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport1.reportID}`, value: null}), - expect.objectContaining({key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport2.reportID}`, value: null}), - ]), - }), - ); - }); - }); - - describe('resolveDuplicates', () => { - let writeSpy: jest.SpyInstance; - - beforeEach(() => { - jest.clearAllMocks(); - global.fetch = getGlobalFetchMock(); - // eslint-disable-next-line rulesdir/no-multiple-api-calls - writeSpy = jest.spyOn(API, 'write').mockImplementation((command, params, options) => { - // Apply optimistic data for testing - if (options?.optimisticData) { - for (const update of options.optimisticData) { - if (update.onyxMethod === Onyx.METHOD.MERGE) { - Onyx.merge(update.key, update.value); - } else if (update.onyxMethod === Onyx.METHOD.SET) { - Onyx.set(update.key, update.value); - } - } - } - return Promise.resolve(); - }); - return Onyx.clear(); - }); - - afterEach(() => { - writeSpy.mockRestore(); - }); - - const createMockTransaction = (id: string, reportID: string, amount = 100): Transaction => ({ - ...createRandomTransaction(Number(id)), - transactionID: id, - reportID, - amount, - created: '2024-01-01 12:00:00', - currency: 'EUR', - merchant: 'Test Merchant', - modifiedMerchant: 'Updated Merchant', - comment: {comment: 'Updated comment'}, - category: 'Travel', - tag: 'UpdatedProject', - billable: true, - reimbursable: false, - }); - - const createMockViolations = () => [ - {name: CONST.VIOLATIONS.DUPLICATED_TRANSACTION, type: CONST.VIOLATION_TYPES.VIOLATION}, - {name: CONST.VIOLATIONS.MISSING_CATEGORY, type: CONST.VIOLATION_TYPES.VIOLATION}, - ]; - - const createMockIouAction = (transactionID: string, reportActionID: string, childReportID: string) => ({ - reportActionID, - actionName: CONST.REPORT.ACTIONS.TYPE.IOU, - originalMessage: { - IOUTransactionID: transactionID, - type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, - }, - message: [{type: 'TEXT', text: 'Test IOU message'}], - childReportID, - }); - - it('should resolve duplicate transactions successfully', async () => { - // Given: Set up test data with main transaction and duplicates - const reportID = 'report123'; - const mainTransactionID = 'main123'; - const duplicate1ID = 'dup456'; - const duplicate2ID = 'dup789'; - const duplicateTransactionIDs = [duplicate1ID, duplicate2ID]; - const childReportID1 = 'child456'; - const childReportID2 = 'child789'; - const mainChildReportID = 'mainChild123'; - - const mainTransaction = createMockTransaction(mainTransactionID, reportID, 150); - const duplicateTransaction1 = createMockTransaction(duplicate1ID, reportID, 100); - const duplicateTransaction2 = createMockTransaction(duplicate2ID, reportID, 50); - - const mainViolations = createMockViolations(); - const duplicate1Violations = createMockViolations(); - const duplicate2Violations = createMockViolations(); - - const iouAction1 = createMockIouAction(duplicate1ID, 'action456', childReportID1); - const iouAction2 = createMockIouAction(duplicate2ID, 'action789', childReportID2); - const mainIouAction = createMockIouAction(mainTransactionID, 'mainAction123', mainChildReportID); - - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`, mainTransaction); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate1ID}`, duplicateTransaction1); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate2ID}`, duplicateTransaction2); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${mainTransactionID}`, mainViolations); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate1ID}`, duplicate1Violations); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate2ID}`, duplicate2Violations); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, { - action456: iouAction1, - action789: iouAction2, - mainAction123: mainIouAction, - }); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${childReportID1}`, {}); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${childReportID2}`, {}); - await waitForBatchedUpdates(); - - const resolveParams = { - transactionID: mainTransactionID, - transactionIDList: duplicateTransactionIDs, - created: '2024-01-01 12:00:00', - merchant: 'Updated Merchant', - amount: 200, - currency: CONST.CURRENCY.EUR, - category: 'Travel', - comment: 'Updated comment', - billable: true, - reimbursable: false, - tag: 'UpdatedProject', - receiptID: 123, - reportID, - }; - - // When: Call resolveDuplicates - resolveDuplicates(resolveParams); - await waitForBatchedUpdates(); - - // Then: Verify main transaction was updated - const updatedMainTransaction = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`); - expect(updatedMainTransaction).toMatchObject({ - billable: true, - comment: {comment: 'Updated comment'}, - category: 'Travel', - created: '2024-01-01 12:00:00', - currency: CONST.CURRENCY.EUR, - modifiedMerchant: 'Updated Merchant', - reimbursable: false, - tag: 'UpdatedProject', - }); - - // Then: Verify duplicate transactions still exist (unlike mergeDuplicates) - const duplicateTransaction1Updated = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate1ID}`); - const duplicateTransaction2Updated = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate2ID}`); - expect(duplicateTransaction1Updated).not.toBeNull(); - expect(duplicateTransaction2Updated).not.toBeNull(); - - // Then: Verify violations were updated - main transaction should not have DUPLICATED_TRANSACTION or HOLD - const updatedMainViolations = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${mainTransactionID}`); - expect(updatedMainViolations).toEqual([{name: CONST.VIOLATIONS.MISSING_CATEGORY, type: CONST.VIOLATION_TYPES.VIOLATION}]); - - // Then: Verify duplicate transactions have HOLD violation added but DUPLICATED_TRANSACTION removed - const updatedDup1Violations = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate1ID}`); - const updatedDup2Violations = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate2ID}`); - - expect(updatedDup1Violations).toEqual( - expect.arrayContaining([ - {name: CONST.VIOLATIONS.HOLD, type: CONST.VIOLATION_TYPES.VIOLATION}, - {name: CONST.VIOLATIONS.MISSING_CATEGORY, type: CONST.VIOLATION_TYPES.VIOLATION}, - ]), - ); - expect(updatedDup2Violations).toEqual( - expect.arrayContaining([ - {name: CONST.VIOLATIONS.HOLD, type: CONST.VIOLATION_TYPES.VIOLATION}, - {name: CONST.VIOLATIONS.MISSING_CATEGORY, type: CONST.VIOLATION_TYPES.VIOLATION}, - ]), - ); - - // Then: Verify hold report actions were created in child report threads - const childReportActions1 = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${childReportID1}`); - const childReportActions2 = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${childReportID2}`); - - // Should have hold actions added - expect(Object.keys(childReportActions1 ?? {})).toHaveLength(1); - expect(Object.keys(childReportActions2 ?? {})).toHaveLength(1); - - // Then: Verify dismissed violation action was created in main transaction thread - const mainChildReportActions = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${mainChildReportID}`); - expect(Object.keys(mainChildReportActions ?? {})).toHaveLength(1); - - // Then: Verify API was called with correct parameters - expect(writeSpy).toHaveBeenCalledWith( - WRITE_COMMANDS.RESOLVE_DUPLICATES, - expect.objectContaining({ - transactionID: mainTransactionID, - transactionIDList: duplicateTransactionIDs, - reportActionIDList: expect.arrayContaining([]), - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - dismissedViolationReportActionID: expect.anything(), - }), - expect.objectContaining({ - optimisticData: expect.arrayContaining([]), - failureData: expect.arrayContaining([]), - }), - ); - }); - - it('should return early when transactionID is undefined', async () => { - // Given: Params with undefined transactionID - const resolveParams = { - transactionID: undefined, - transactionIDList: ['dup456'], - created: '2024-01-01 12:00:00', - merchant: 'Updated Merchant', - amount: 200, - currency: CONST.CURRENCY.EUR, - category: 'Travel', - comment: 'Updated comment', - billable: true, - reimbursable: false, - tag: 'UpdatedProject', - receiptID: 123, - reportID: 'report123', - }; - - // When: Call resolveDuplicates with undefined transactionID - resolveDuplicates(resolveParams); - await waitForBatchedUpdates(); - - // Then: Verify API was not called - expect(writeSpy).not.toHaveBeenCalled(); - }); - - it('should handle empty duplicate transaction list', async () => { - // Given: Set up test data with only main transaction - const reportID = 'report123'; - const mainTransactionID = 'main123'; - const mainChildReportID = 'mainChild123'; - - const mainTransaction = createMockTransaction(mainTransactionID, reportID); - const mainViolations = createMockViolations(); - const mainIouAction = createMockIouAction(mainTransactionID, 'mainAction123', mainChildReportID); - - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`, mainTransaction); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${mainTransactionID}`, mainViolations); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, { - mainAction123: mainIouAction, - }); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${mainChildReportID}`, {}); - await waitForBatchedUpdates(); - - const resolveParams = { - transactionID: mainTransactionID, - transactionIDList: [], - created: '2024-01-01 12:00:00', - merchant: 'Updated Merchant', - amount: 200, - currency: CONST.CURRENCY.EUR, - category: 'Travel', - comment: 'Updated comment', - billable: true, - reimbursable: false, - tag: 'UpdatedProject', - receiptID: 123, - reportID, - }; - - // When: Call resolveDuplicates with empty duplicate list - resolveDuplicates(resolveParams); - await waitForBatchedUpdates(); - - // Then: Verify main transaction was still updated - const updatedMainTransaction = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`); - expect(updatedMainTransaction).toMatchObject({ - billable: true, - category: 'Travel', - modifiedMerchant: 'Updated Merchant', - }); - - // Then: Verify main transaction violations were still filtered - const updatedMainViolations = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${mainTransactionID}`); - expect(updatedMainViolations).toEqual([{name: CONST.VIOLATIONS.MISSING_CATEGORY, type: CONST.VIOLATION_TYPES.VIOLATION}]); - - // Then: Verify API was called - // eslint-disable-next-line - expect(API.write).toHaveBeenCalledWith(WRITE_COMMANDS.RESOLVE_DUPLICATES, expect.objectContaining({}), expect.objectContaining({})); - }); - - it('should handle missing IOU actions gracefully', async () => { - // Given: Set up test data without IOU actions - const reportID = 'report123'; - const mainTransactionID = 'main123'; - const duplicate1ID = 'dup456'; - const duplicateTransactionIDs = [duplicate1ID]; - - const mainTransaction = createMockTransaction(mainTransactionID, reportID); - const duplicateTransaction = createMockTransaction(duplicate1ID, reportID); - const mainViolations = createMockViolations(); - const duplicateViolations = createMockViolations(); - - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`, mainTransaction); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate1ID}`, duplicateTransaction); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${mainTransactionID}`, mainViolations); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate1ID}`, duplicateViolations); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, {}); - await waitForBatchedUpdates(); - - const resolveParams = { - transactionID: mainTransactionID, - transactionIDList: duplicateTransactionIDs, - created: '2024-01-01 12:00:00', - merchant: 'Updated Merchant', - amount: 200, - currency: CONST.CURRENCY.EUR, - category: 'Travel', - comment: 'Updated comment', - billable: true, - reimbursable: false, - tag: 'UpdatedProject', - receiptID: 123, - reportID, - }; - - // When: Call resolveDuplicates without IOU actions - resolveDuplicates(resolveParams); - await waitForBatchedUpdates(); - - // Then: Verify function completed without errors - const updatedMainTransaction = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`); - expect(updatedMainTransaction).toMatchObject({ - category: 'Travel', - modifiedMerchant: 'Updated Merchant', - }); - - // Then: Verify violations were still processed - const updatedDuplicateViolations = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate1ID}`); - expect(updatedDuplicateViolations).toEqual( - expect.arrayContaining([ - {name: CONST.VIOLATIONS.HOLD, type: CONST.VIOLATION_TYPES.VIOLATION}, - {name: CONST.VIOLATIONS.MISSING_CATEGORY, type: CONST.VIOLATION_TYPES.VIOLATION}, - ]), - ); - - // Then: Verify API was called - expect(writeSpy).toHaveBeenCalledWith(WRITE_COMMANDS.RESOLVE_DUPLICATES, expect.objectContaining({}), expect.objectContaining({})); - }); - }); - describe('getPerDiemExpenseInformation', () => { it('should include policyRecentlyUsedCurrencies when provided', () => { const testCurrency = CONST.CURRENCY.GBP; diff --git a/tests/actions/IOUTest/DuplicateActionTest.ts b/tests/actions/IOUTest/DuplicateActionTest.ts index 3eb0ab8347dc..df351de2bb6a 100644 --- a/tests/actions/IOUTest/DuplicateActionTest.ts +++ b/tests/actions/IOUTest/DuplicateActionTest.ts @@ -2,11 +2,14 @@ /* eslint-disable @typescript-eslint/no-unsafe-assignment */ import type {OnyxEntry, OnyxInputValue} from 'react-native-onyx'; import Onyx from 'react-native-onyx'; +import {getReportPreviewAction} from '@libs/actions/IOU'; import {duplicateExpenseTransaction, mergeDuplicates, resolveDuplicates} from '@libs/actions/IOU/DuplicateAction'; import initOnyxDerivedValues from '@libs/actions/OnyxDerived'; +import {addComment, openReport} from '@libs/actions/Report'; import {WRITE_COMMANDS} from '@libs/API/types'; -import {getOriginalMessage} from '@libs/ReportActionsUtils'; -import {buildOptimisticIOUReport, buildOptimisticIOUReportAction} from '@libs/ReportUtils'; +import {getLoginsByAccountIDs} from '@libs/PersonalDetailsUtils'; +import {getOriginalMessage, getReportAction} from '@libs/ReportActionsUtils'; +import {buildOptimisticIOUReport, buildOptimisticIOUReportAction, buildTransactionThread} from '@libs/ReportUtils'; import {buildOptimisticTransaction} from '@libs/TransactionUtils'; import CONST from '@src/CONST'; import IntlStore from '@src/languages/IntlStore'; @@ -21,6 +24,7 @@ import type {TransactionCollectionDataSet} from '@src/types/onyx/Transaction'; import currencyList from '../../unit/currencyList.json'; import createRandomPolicy from '../../utils/collections/policies'; import createRandomPolicyCategories from '../../utils/collections/policyCategory'; +import createRandomReportAction from '../../utils/collections/reportActions'; import {createRandomReport} from '../../utils/collections/reports'; import createRandomTransaction from '../../utils/collections/transaction'; import getOnyxValue from '../../utils/getOnyxValue'; @@ -132,13 +136,14 @@ describe('actions/DuplicateAction', () => { {name: CONST.VIOLATIONS.MISSING_CATEGORY, type: CONST.VIOLATION_TYPES.VIOLATION}, ]; - const createMockIouAction = (transactionID: string, reportActionID: string, childReportID: string): ReportAction => ({ + const createMockIouAction = (transactionID: string, reportActionID: string, childReportID: string, IOUReportID?: string): ReportAction => ({ reportActionID, actionName: CONST.REPORT.ACTIONS.TYPE.IOU, created: '2024-01-01 12:00:00', originalMessage: { IOUTransactionID: transactionID, type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, + IOUReportID, } as OriginalMessageIOU, message: [{type: 'TEXT', text: 'Test IOU message'}], childReportID, @@ -341,6 +346,212 @@ describe('actions/DuplicateAction', () => { // Then: Verify API was still called expect(writeSpy).toHaveBeenCalledWith(WRITE_COMMANDS.MERGE_DUPLICATES, expect.objectContaining({}), expect.objectContaining({})); }); + + it('should delete the thread reports of the duplicated transactions and update the comment count of the preview report', async () => { + // Given: Set up test data with main transaction and duplicates + const chatReportID = 'report123'; + const reportID = 'report456'; + const mainTransactionID = 'main123'; + const duplicate1ID = 'dup456'; + const duplicate2ID = 'dup789'; + const duplicateTransactionIDs = [duplicate1ID, duplicate2ID]; + const previewActionID = 'action123'; + const iouAction1ID = 'action456'; + const iouAction2ID = 'action789'; + + const chatReport: Report = { + ...createRandomReport(0, undefined), + policyID: CONST.POLICY.ID_FAKE, + parentReportID: undefined, + parentReportActionID: undefined, + reportID: chatReportID, + type: 'chat', + }; + let previewAction: OnyxEntry = { + ...createRandomReportAction(0), + actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, + reportActionID: previewActionID, + childMoneyRequestCount: 3, + childVisibleActionCount: 0, + originalMessage: {linkedReportID: reportID}, + }; + const expenseReport: Report = { + ...createMockReport(reportID, 300), + chatReportID: chatReport.reportID, + parentReportID: chatReport.reportID, + parentReportActionID: previewAction.reportActionID, + }; + const mainTransaction = createMockTransaction(mainTransactionID, reportID, 100); + const duplicateTransaction1 = createMockTransaction(duplicate1ID, reportID, 100); + const duplicateTransaction2 = createMockTransaction(duplicate2ID, reportID, 100); + + const mainViolations = createMockViolations(); + const duplicate1Violations = createMockViolations(); + const duplicate2Violations = createMockViolations(); + + let iouAction1 = createMockIouAction(duplicate1ID, iouAction1ID, '', reportID) as OnyxEntry; + let iouAction2 = createMockIouAction(duplicate2ID, iouAction2ID, '', reportID) as OnyxEntry; + + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${mainTransactionID}`, mainTransaction); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate1ID}`, duplicateTransaction1); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${duplicate2ID}`, duplicateTransaction2); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, expenseReport); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`, chatReport); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${mainTransactionID}`, mainViolations); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate1ID}`, duplicate1Violations); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${duplicate2ID}`, duplicate2Violations); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReportID}`, { + [previewActionID]: previewAction, + }); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, { + [iouAction1ID]: iouAction1, + [iouAction2ID]: iouAction2, + }); + await waitForBatchedUpdates(); + + const transactionThreadReport1 = buildTransactionThread(iouAction1, expenseReport); + const transactionThreadReport2 = buildTransactionThread(iouAction2, expenseReport); + + expect(transactionThreadReport1.participants).toEqual({ + [RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}, + }); + expect(transactionThreadReport2.participants).toEqual({ + [RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}, + }); + + const participantAccountIDs = Object.keys(transactionThreadReport1.participants ?? {}).map(Number); + const userLogins = getLoginsByAccountIDs(participantAccountIDs); + jest.advanceTimersByTime(10); + openReport(transactionThreadReport1.reportID, '', userLogins, transactionThreadReport1, iouAction1?.reportActionID); + openReport(transactionThreadReport2.reportID, '', userLogins, transactionThreadReport1, iouAction2?.reportActionID); + await waitForBatchedUpdates(); + + let transactionThreadReportActions1: OnyxEntry; + let transactionThreadReportActions2: OnyxEntry; + Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReport1.reportID}`, + callback: (val) => (transactionThreadReportActions1 = val), + }); + Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionThreadReport2.reportID}`, + callback: (val) => (transactionThreadReportActions2 = val), + }); + await waitForBatchedUpdates(); + + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport1.reportID}`, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeTruthy(); + resolve(); + }, + }); + }); + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport2.reportID}`, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeTruthy(); + resolve(); + }, + }); + }); + + jest.advanceTimersByTime(10); + + // When a comment is added + const addCommentToThread = async (thread: Report, iouActionID: string, message: string) => { + const updatedIouAction = getReportAction(expenseReport.reportID, iouActionID); + const updatedPreviewAction = getReportAction(chatReport.reportID, previewActionID); + const ancestors = []; + ancestors.push(...(updatedIouAction ? [{report: expenseReport, reportAction: updatedIouAction, shouldDisplayNewMarker: false}] : [])); + ancestors.push(...(updatedPreviewAction ? [{report: chatReport, reportAction: updatedPreviewAction, shouldDisplayNewMarker: false}] : [])); + addComment(thread, thread.reportID, ancestors, message, CONST.DEFAULT_TIME_ZONE); + await waitForBatchedUpdates(); + }; + await addCommentToThread(transactionThreadReport1, iouAction1ID, 'Testing a comment'); + await addCommentToThread(transactionThreadReport1, iouAction1ID, 'Testing a comment1'); + await addCommentToThread(transactionThreadReport2, iouAction2ID, 'Testing a comment2'); + + // Then the report should have 3 actions + expect(Object.values(transactionThreadReportActions1 ?? {}).length).toBe(3); + // And the report should have 2 actions + expect(Object.values(transactionThreadReportActions2 ?? {}).length).toBe(2); + + iouAction1 = getReportAction(expenseReport.reportID, iouAction1ID); + iouAction2 = getReportAction(expenseReport.reportID, iouAction2ID); + previewAction = getReportAction(chatReport.reportID, previewActionID); + expect(iouAction1?.childVisibleActionCount).toBe(2); + expect(iouAction2?.childVisibleActionCount).toBe(1); + expect(previewAction?.childVisibleActionCount).toBe(3); + + await waitForBatchedUpdates(); + + const mergeParams = { + transactionID: mainTransactionID, + transactionIDList: duplicateTransactionIDs, + created: '2024-01-01 12:00:00', + merchant: 'Updated Merchant', + amount: 100, + currency: CONST.CURRENCY.EUR, + category: 'Travel', + comment: 'Updated comment', + billable: true, + reimbursable: false, + tag: 'UpdatedProject', + receiptID: 123, + reportID, + }; + + // When: Call mergeDuplicates + mergeDuplicates(mergeParams); + await waitForBatchedUpdates(); + + // Then we expect the reportPreview to update with new childVisibleActionCount + previewAction = getReportPreviewAction(chatReport?.reportID, expenseReport?.reportID) ?? undefined; + expect(previewAction).toBeTruthy(); + expect(previewAction?.childVisibleActionCount).toEqual(0); + expect(previewAction?.childCommenterCount).toEqual(0); + + // Then the transaction thread report should be ready to be deleted + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport1.reportID}`, + waitForCollectionCallback: false, + callback: (report) => { + Onyx.disconnect(connection); + expect(report?.reportID).toBeFalsy(); + resolve(); + }, + }); + }); + + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport2.reportID}`, + waitForCollectionCallback: false, + callback: (report) => { + Onyx.disconnect(connection); + expect(report?.reportID).toBeFalsy(); + resolve(); + }, + }); + }); + + // Then the transaction thread report should be deleted in the success onyx data + expect(writeSpy).toHaveBeenCalledWith( + WRITE_COMMANDS.MERGE_DUPLICATES, + expect.objectContaining(mergeParams), + expect.objectContaining({ + successData: expect.arrayContaining([ + expect.objectContaining({key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport1.reportID}`, value: null}), + expect.objectContaining({key: `${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReport2.reportID}`, value: null}), + ]), + }), + ); + }); }); describe('resolveDuplicates', () => { From 906843a26bff28f64f23bbbfd2fc7929fdeade2b Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Tue, 13 Jan 2026 11:44:56 +0700 Subject: [PATCH 10/20] fix ts and lint --- src/libs/actions/IOU/DuplicateAction.ts | 2 +- tests/actions/MergeTransactionTest.ts | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/libs/actions/IOU/DuplicateAction.ts b/src/libs/actions/IOU/DuplicateAction.ts index b1409506e586..0dca8378a355 100644 --- a/src/libs/actions/IOU/DuplicateAction.ts +++ b/src/libs/actions/IOU/DuplicateAction.ts @@ -25,12 +25,12 @@ import type * as OnyxTypes from '@src/types/onyx'; import type {Attendee} from '@src/types/onyx/IOU'; import type {WaypointCollection} from '@src/types/onyx/Transaction'; import type {CreateTrackExpenseParams, RequestMoneyInformation} from '.'; -import {getCleanUpTransactionThreadReportOnyxData} from '.'; import { getAllReportActionsFromIOU, getAllReports, getAllTransactions, getAllTransactionViolations, + getCleanUpTransactionThreadReportOnyxData, getCurrentUserEmail, getMoneyRequestParticipantsFromReport, getUserAccountID, diff --git a/tests/actions/MergeTransactionTest.ts b/tests/actions/MergeTransactionTest.ts index 12cfb672be46..91a167c05732 100644 --- a/tests/actions/MergeTransactionTest.ts +++ b/tests/actions/MergeTransactionTest.ts @@ -655,6 +655,8 @@ describe('mergeTransactionRequest', () => { mergeTransaction, targetTransaction, sourceTransaction, + targetTransactionThreadReport: {reportID: 'target-report-456'}, + targetTransactionThreadParentReport: undefined, allTransactionViolations: createAllTransactionViolations(targetTransaction.transactionID, sourceTransaction.transactionID, targetViolations, sourceViolations), policy: undefined, policyTags: undefined, @@ -785,6 +787,8 @@ describe('mergeTransactionRequest', () => { mergeTransaction, targetTransaction, sourceTransaction, + targetTransactionThreadReport: {reportID: 'target-report-456'}, + targetTransactionThreadParentReport: undefined, allTransactionViolations: createAllTransactionViolations(targetTransaction.transactionID, sourceTransaction.transactionID, targetViolations, sourceViolations), policy: undefined, policyTags: undefined, From 3fab5bb16d683582db3aff9d66afe127d2c43834 Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Thu, 15 Jan 2026 21:20:26 +0700 Subject: [PATCH 11/20] fix lint --- tests/actions/IOUTest.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/actions/IOUTest.ts b/tests/actions/IOUTest.ts index 254c728dfde9..943c5b4f0c7a 100644 --- a/tests/actions/IOUTest.ts +++ b/tests/actions/IOUTest.ts @@ -6035,7 +6035,15 @@ describe('actions/IOU', () => { mockFetch?.pause?.(); jest.advanceTimersByTime(10); if (transaction && createIOUAction) { - deleteMoneyRequest({transactionID: transaction.transactionID, reportAction: createIOUAction, transactions: {}, violations: {}, iouReport, chatReport}); + deleteMoneyRequest({ + transactionID: transaction.transactionID, + reportAction: createIOUAction, + transactions: {}, + violations: {}, + iouReport, + chatReport, + allTransactionViolationsParam: {}, + }); } await waitForBatchedUpdates(); From 926858e39524efcc997a6503b24e1709806b549b Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Fri, 16 Jan 2026 09:23:31 +0700 Subject: [PATCH 12/20] Fix - The "Reply" hyperlink below the expense preview is shown --- src/libs/actions/IOU/index.ts | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/libs/actions/IOU/index.ts b/src/libs/actions/IOU/index.ts index a86728cdfb99..66b13dc1db58 100644 --- a/src/libs/actions/IOU/index.ts +++ b/src/libs/actions/IOU/index.ts @@ -8944,8 +8944,10 @@ function getCleanUpTransactionThreadReportOnyxData({ const iouReportID = isMoneyRequestAction(reportAction) ? getOriginalMessage(reportAction)?.IOUReportID : undefined; const iouReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`]; const chatReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${iouReport?.chatReportID}`]; - let reportPreviewAction = updatedReportPreviewAction ?? getReportPreviewAction(chatReport?.reportID, iouReport?.reportID) ?? undefined; + let originalReportPreviewAction = getReportPreviewAction(chatReport?.reportID, iouReport?.reportID) ?? undefined; + let reportPreviewAction = updatedReportPreviewAction ?? originalReportPreviewAction; if ( + originalReportPreviewAction?.reportActionID && reportPreviewAction?.reportActionID && reportPreviewAction?.childVisibleActionCount && reportPreviewAction?.childVisibleActionCount > 0 && @@ -8987,10 +8989,10 @@ function getCleanUpTransactionThreadReportOnyxData({ key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReport?.reportID}`, value: { [reportPreviewAction.reportActionID]: { - childVisibleActionCount: reportPreviewAction.childVisibleActionCount, - childCommenterCount: reportPreviewAction.childCommenterCount, - childLastVisibleActionCreated: reportPreviewAction.childLastVisibleActionCreated, - childOldestFourAccountIDs: reportPreviewAction.childOldestFourAccountIDs, + childVisibleActionCount: originalReportPreviewAction.childVisibleActionCount, + childCommenterCount: originalReportPreviewAction.childCommenterCount, + childLastVisibleActionCreated: originalReportPreviewAction.childLastVisibleActionCreated, + childOldestFourAccountIDs: originalReportPreviewAction.childOldestFourAccountIDs, }, }, }); From f4d3291754c34cd6f7aadd90997124c27709f944 Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Fri, 16 Jan 2026 09:31:57 +0700 Subject: [PATCH 13/20] fix lint --- src/libs/actions/IOU/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libs/actions/IOU/index.ts b/src/libs/actions/IOU/index.ts index 66b13dc1db58..a79b16e18831 100644 --- a/src/libs/actions/IOU/index.ts +++ b/src/libs/actions/IOU/index.ts @@ -8944,7 +8944,7 @@ function getCleanUpTransactionThreadReportOnyxData({ const iouReportID = isMoneyRequestAction(reportAction) ? getOriginalMessage(reportAction)?.IOUReportID : undefined; const iouReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`]; const chatReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${iouReport?.chatReportID}`]; - let originalReportPreviewAction = getReportPreviewAction(chatReport?.reportID, iouReport?.reportID) ?? undefined; + const originalReportPreviewAction = getReportPreviewAction(chatReport?.reportID, iouReport?.reportID) ?? undefined; let reportPreviewAction = updatedReportPreviewAction ?? originalReportPreviewAction; if ( originalReportPreviewAction?.reportActionID && From 4e6552424b0fc1a7bb23de1096095322ced80fa1 Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Sun, 25 Jan 2026 17:11:18 +0700 Subject: [PATCH 14/20] Fix - The "Reply" hyperlink below the expense preview is shown --- src/libs/actions/IOU/Split.ts | 18 +- src/libs/actions/IOU/index.ts | 572 ----------- tests/actions/IOUTest.ts | 1498 +--------------------------- tests/actions/IOUTest/SplitTest.ts | 211 +++- 4 files changed, 216 insertions(+), 2083 deletions(-) diff --git a/src/libs/actions/IOU/Split.ts b/src/libs/actions/IOU/Split.ts index e95036ee241a..a988d99f148f 100644 --- a/src/libs/actions/IOU/Split.ts +++ b/src/libs/actions/IOU/Split.ts @@ -61,6 +61,7 @@ import { getAllPersonalDetails, getAllReports, getAllTransactions, + getCleanUpTransactionThreadReportOnyxData, getDeleteTrackExpenseInformation, getMoneyRequestInformation, getMoneyRequestParticipantsFromReport, @@ -1317,17 +1318,18 @@ function updateSplitTransactions({ errors: null, }, }; - const transactionThread = getAllReports()?.[`${ONYXKEYS.COLLECTION.REPORT}${firstIOU.childReportID}`] ?? null; - optimisticData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${firstIOU?.childReportID}`, - value: null, + const cleanUpTransactionThreadReportOnyxData = getCleanUpTransactionThreadReportOnyxData({ + transactionThreadID: firstIOU.childReportID, + shouldDeleteTransactionThread: !!firstIOU.childReportID, + reportAction: firstIOU, }); optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`, value: updatedReportAction, }); + optimisticData.push(...cleanUpTransactionThreadReportOnyxData.optimisticData); + successData.push(...cleanUpTransactionThreadReportOnyxData.successData); failureData.push({ onyxMethod: Onyx.METHOD.MERGE, @@ -1339,11 +1341,7 @@ function updateSplitTransactions({ }, }, }); - failureData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${firstIOU?.childReportID}`, - value: transactionThread ?? null, - }); + failureData.push(...cleanUpTransactionThreadReportOnyxData.failureData); } optimisticData.push({ diff --git a/src/libs/actions/IOU/index.ts b/src/libs/actions/IOU/index.ts index a2fc722c212c..b071fed1d880 100644 --- a/src/libs/actions/IOU/index.ts +++ b/src/libs/actions/IOU/index.ts @@ -12852,577 +12852,6 @@ function clearSplitTransactionDraftErrors(transactionID: string | undefined) { }); } -function updateSplitTransactions({ - allTransactionsList, - allReportsList, - allReportNameValuePairsList, - transactionData, - searchContext, - policyCategories, - policy, - policyRecentlyUsedCategories, - iouReport, - firstIOU, - isASAPSubmitBetaEnabled, - currentUserPersonalDetails, - transactionViolations, - quickAction, - policyRecentlyUsedCurrencies, -}: UpdateSplitTransactionsParams) { - const transactionReport = getReportOrDraftReport(transactionData?.reportID); - const parentTransactionReport = getReportOrDraftReport(transactionReport?.parentReportID); - const expenseReport = transactionReport?.type === CONST.REPORT.TYPE.EXPENSE ? transactionReport : parentTransactionReport; - - const originalTransactionID = transactionData?.originalTransactionID ?? CONST.IOU.OPTIMISTIC_TRANSACTION_ID; - const originalTransaction = allTransactionsList?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${originalTransactionID}`]; - const originalTransactionDetails = getTransactionDetails(originalTransaction); - - const policyTags = getPolicyTagsData(expenseReport?.policyID); - const participants = getMoneyRequestParticipantsFromReport(expenseReport, currentUserPersonalDetails.accountID); - const splitExpenses = transactionData?.splitExpenses ?? []; - - // List of all child transactions that have been created after split - const originalChildTransactions = getChildTransactions(allTransactionsList, allReportsList, originalTransactionID); - const processedChildTransactionIDs: string[] = []; - - const splitExpensesTotal = transactionData?.splitExpensesTotal ?? 0; - - const isCreationOfSplits = originalChildTransactions.length === 0; - const hasEditableSplitExpensesLeft = splitExpenses.some((expense) => (expense.statusNum ?? 0) < CONST.REPORT.STATUS_NUM.SUBMITTED); - const isReverseSplitOperation = splitExpenses.length === 1 && originalChildTransactions.length > 0 && hasEditableSplitExpensesLeft; - - let changesInReportTotal = 0; - // Validate custom unit rate before proceeding with split - const customUnitRateID = originalTransaction?.comment?.customUnit?.customUnitRateID; - const isPerDiem = isPerDiemRequestTransactionUtils(originalTransaction); - - if (customUnitRateID && policy && !isPerDiem) { - const customUnitRate = getDistanceRateCustomUnitRate(policy, customUnitRateID); - - // If the rate doesn't exist or is disabled, show an error and return early - if (!customUnitRate || !customUnitRate.enabled) { - // Show error to user - Onyx.merge(`${ONYXKEYS.COLLECTION.SPLIT_TRANSACTION_DRAFT}${originalTransactionID}`, { - errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.invalidRate'), - }); - return; - } - } - - const splits: SplitTransactionSplitsParam = - splitExpenses.map((split) => { - const currentDescription = getParsedComment(Parser.htmlToMarkdown(split.description ?? '')); - changesInReportTotal += split.amount; - return { - amount: split.amount, - category: split.category ?? '', - tag: split.tags?.[0] ?? '', - created: split.created, - merchant: split?.merchant ?? '', - transactionID: split.transactionID, - comment: { - comment: currentDescription, - }, - reimbursable: split?.reimbursable, - }; - }) ?? []; - changesInReportTotal -= splitExpensesTotal; - - const successData = [] as OnyxUpdate[]; - const failureData = [] as OnyxUpdate[]; - const optimisticData = [] as OnyxUpdate[]; - - // The split transactions can be in different reports, so we need to calculate the total for each report. - const reportTotals = new Map(); - const expenseReportID = expenseReport?.reportID; - - if (expenseReportID) { - const expenseReportKey = `${ONYXKEYS.COLLECTION.REPORT}${expenseReportID}`; - const expenseReportTotal = allReportsList?.[expenseReportKey]?.total ?? expenseReport?.total ?? 0; - reportTotals.set(expenseReportID, expenseReportTotal - changesInReportTotal); - } - - for (const expense of splitExpenses) { - const splitExpenseReportID = expense.reportID; - if (!splitExpenseReportID || reportTotals.has(splitExpenseReportID)) { - continue; - } - - const splitExpenseReport = allReportsList?.[`${ONYXKEYS.COLLECTION.REPORT}${splitExpenseReportID}`]; - reportTotals.set(splitExpenseReportID, splitExpenseReport?.total ?? 0); - } - - for (const [index, splitExpense] of splitExpenses.entries()) { - const existingTransactionID = isReverseSplitOperation ? originalTransactionID : splitExpense.transactionID; - const splitTransaction = allTransactionsList?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${existingTransactionID}`]; - if (splitTransaction) { - processedChildTransactionIDs.push(splitTransaction.transactionID); - } - - const splitReportActions = getAllReportActions(isReverseSplitOperation ? expenseReport?.reportID : splitTransaction?.reportID); - const currentReportAction = Object.values(splitReportActions).find((action) => { - const transactionID = isMoneyRequestAction(action) ? (getOriginalMessage(action)?.IOUTransactionID ?? CONST.DEFAULT_NUMBER_ID) : CONST.DEFAULT_NUMBER_ID; - return transactionID === existingTransactionID; - }); - - const requestMoneyInformation = { - participantParams: { - participant: participants.at(0) ?? ({} as Participant), - payeeEmail: currentUserPersonalDetails?.login ?? '', - payeeAccountID: currentUserPersonalDetails?.accountID ?? CONST.DEFAULT_NUMBER_ID, - }, - policyParams: { - policy, - policyCategories, - policyTags, - }, - transactionParams: { - amount: Math.abs(originalTransaction?.amount ?? 0), - modifiedAmount: splitExpense.amount ?? 0, - currency: originalTransactionDetails?.currency ?? CONST.CURRENCY.USD, - created: splitExpense.created, - merchant: splitExpense.merchant ?? '', - comment: splitExpense.description, - category: splitExpense.category, - tag: splitExpense.tags?.[0], - originalTransactionID, - attendees: originalTransactionDetails?.attendees, - source: CONST.IOU.TYPE.SPLIT, - linkedTrackedExpenseReportAction: currentReportAction, - pendingAction: splitTransaction ? null : CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD, - pendingFields: splitTransaction ? splitTransaction.pendingFields : undefined, - reimbursable: originalTransactionDetails?.reimbursable, - taxCode: originalTransactionDetails?.taxCode, - taxAmount: calculateIOUAmount(splitExpenses.length - 1, originalTransactionDetails?.taxAmount ?? 0, originalTransactionDetails?.currency ?? CONST.CURRENCY.USD, false), - billable: originalTransactionDetails?.billable, - }, - parentChatReport: getReportOrDraftReport(getReportOrDraftReport(expenseReport?.chatReportID)?.parentReportID), - existingTransaction: originalTransaction, - isASAPSubmitBetaEnabled, - currentUserAccountIDParam: currentUserPersonalDetails?.accountID, - currentUserEmailParam: currentUserPersonalDetails?.login ?? '', - transactionViolations, - quickAction, - policyRecentlyUsedCurrencies, - } as MoneyRequestInformationParams; - - if (isReverseSplitOperation) { - requestMoneyInformation.transactionParams = { - amount: splitExpense.amount ?? 0, - currency: originalTransactionDetails?.currency ?? CONST.CURRENCY.USD, - created: splitExpense.created, - merchant: splitExpense.merchant ?? '', - comment: splitExpense.description, - category: splitExpense.category, - tag: splitExpense.tags?.[0], - attendees: originalTransactionDetails?.attendees as Attendee[], - linkedTrackedExpenseReportAction: currentReportAction, - taxCode: originalTransactionDetails?.taxCode, - taxAmount: calculateIOUAmount(splitExpenses.length - 1, originalTransactionDetails?.taxAmount ?? 0, originalTransactionDetails?.currency ?? CONST.CURRENCY.USD, false), - billable: originalTransactionDetails?.billable, - }; - requestMoneyInformation.existingTransaction = undefined; - } - - const {participantParams, policyParams, transactionParams, parentChatReport, existingTransaction} = requestMoneyInformation; - const parsedComment = getParsedComment(Parser.htmlToMarkdown(transactionParams.comment ?? '')); - transactionParams.comment = parsedComment; - - const {transactionThreadReportID, createdReportActionIDForThread, onyxData, iouAction} = getMoneyRequestInformation({ - participantParams, - parentChatReport, - policyParams, - transactionParams, - moneyRequestReportID: splitExpense?.reportID, - existingTransaction, - existingTransactionID, - newReportTotal: reportTotals.get(splitExpense?.reportID ?? String(CONST.DEFAULT_NUMBER_ID)) ?? 0, - newNonReimbursableTotal: (transactionReport?.nonReimbursableTotal ?? 0) - changesInReportTotal, - isSplitExpense: true, - currentReportActionID: currentReportAction?.reportActionID, - isASAPSubmitBetaEnabled, - currentUserAccountIDParam: currentUserPersonalDetails?.accountID, - currentUserEmailParam: currentUserPersonalDetails?.login ?? '', - transactionViolations, - quickAction, - shouldGenerateTransactionThreadReport: !isReverseSplitOperation, - policyRecentlyUsedCurrencies, - }); - - let updateMoneyRequestParamsOnyxData: OnyxData = {}; - const currentSplit = splits.at(index); - - // For existing split transactions, update the field change messages - // For new transactions, skip this step - if (splitTransaction) { - const existing = getTransactionDetails(splitTransaction); - const transactionChanges = { - ...currentSplit, - comment: currentSplit?.comment?.comment, - } as TransactionChanges; - - if (currentSplit) { - currentSplit.reimbursable = splitTransaction.reimbursable; - currentSplit.billable = splitTransaction.billable; - } - - for (const key of Object.keys(transactionChanges)) { - const newValue = transactionChanges[key as keyof typeof transactionChanges]; - const oldValue = existing?.[key as keyof typeof existing]; - if (newValue === oldValue) { - delete transactionChanges[key as keyof typeof transactionChanges]; - // Ensure we pass the currency to getUpdateMoneyRequestParams as well, so the amount message is created correctly - } else if (key === 'amount') { - transactionChanges.currency = originalTransactionDetails?.currency; - } - } - - if (isReverseSplitOperation) { - delete transactionChanges.transactionID; - } - - if (Object.keys(transactionChanges).length > 0) { - const transactionThreadReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${isReverseSplitOperation ? splitExpense?.reportID : transactionThreadReportID}`]; - const transactionIOUReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${splitExpense?.reportID ?? transactionThreadReport?.parentReportID}`]; - const {onyxData: moneyRequestParamsOnyxData, params} = getUpdateMoneyRequestParams({ - transactionID: existingTransactionID, - transactionThreadReport, - iouReport: transactionIOUReport, - transactionChanges, - policy, - policyTagList: policyTags ?? null, - policyCategories: policyCategories ?? null, - newTransactionReportID: splitExpense?.reportID, - policyRecentlyUsedCategories, - currentUserAccountIDParam: currentUserPersonalDetails?.accountID, - currentUserEmailParam: currentUserPersonalDetails?.login ?? '', - isASAPSubmitBetaEnabled, - }); - if (currentSplit) { - currentSplit.modifiedExpenseReportActionID = params.reportActionID; - } - updateMoneyRequestParamsOnyxData = moneyRequestParamsOnyxData; - } - // For new split transactions, set the reportID once the transaction and associated report are created - } else if (currentSplit) { - currentSplit.reportID = splitExpense?.reportID; - } - - if (currentSplit) { - currentSplit.transactionThreadReportID = transactionThreadReportID; - currentSplit.createdReportActionIDForThread = createdReportActionIDForThread; - currentSplit.splitReportActionID = iouAction.reportActionID; - } - - optimisticData.push(...(onyxData.optimisticData ?? []), ...(updateMoneyRequestParamsOnyxData.optimisticData ?? [])); - successData.push(...(onyxData.successData ?? []), ...(updateMoneyRequestParamsOnyxData.successData ?? [])); - failureData.push(...(onyxData.failureData ?? []), ...(updateMoneyRequestParamsOnyxData.failureData ?? [])); - } - - // All transactions that were deleted in the split list will be marked as deleted in onyx - const undeletedTransactions = originalChildTransactions.filter( - (currentTransaction) => !processedChildTransactionIDs.includes(currentTransaction?.transactionID ?? CONST.IOU.OPTIMISTIC_TRANSACTION_ID), - ); - - for (const undeletedTransaction of undeletedTransactions) { - const splitTransaction = allTransactionsList?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${undeletedTransaction?.transactionID}`]; - const splitReportActions = getAllReportActions(splitTransaction?.reportID); - const reportNameValuePairs = allReportNameValuePairsList?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${splitTransaction?.reportID}`]; - const isReportArchived = isArchivedReport(reportNameValuePairs); - const currentReportAction = Object.values(splitReportActions).find((action) => { - const transactionID = isMoneyRequestAction(action) ? (getOriginalMessage(action)?.IOUTransactionID ?? CONST.DEFAULT_NUMBER_ID) : CONST.DEFAULT_NUMBER_ID; - return transactionID === undeletedTransaction?.transactionID; - }) as ReportAction; - - const { - optimisticData: deleteExpenseOptimisticData, - failureData: deleteExpenseFailureData, - successData: deleteExpenseSuccessData, - } = getDeleteTrackExpenseInformation( - splitTransaction?.reportID ?? String(CONST.DEFAULT_NUMBER_ID), - undeletedTransaction?.transactionID, - currentReportAction, - undefined, - undefined, - undefined, - undefined, - undefined, - isReportArchived, - ); - - optimisticData.push(...(deleteExpenseOptimisticData ?? [])); - successData.push(...(deleteExpenseSuccessData ?? [])); - failureData.push(...(deleteExpenseFailureData ?? [])); - } - - if (!isReverseSplitOperation) { - // Use SET to update originalTransaction more quickly in Onyx as compared to MERGE to prevent UI inconsistency - optimisticData.push({ - onyxMethod: Onyx.METHOD.SET, - key: `${ONYXKEYS.COLLECTION.TRANSACTION}${originalTransactionID}`, - value: { - ...originalTransaction, - reportID: CONST.REPORT.SPLIT_REPORT_ID, - }, - }); - - // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 - failureData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.TRANSACTION}${originalTransactionID}`, - value: originalTransaction, - }); - - if (firstIOU) { - const updatedReportAction = { - [firstIOU.reportActionID]: { - pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, - previousMessage: firstIOU.message, - message: [ - { - type: 'COMMENT', - html: '', - text: '', - isEdited: true, - isDeletedParentAction: true, - }, - ], - originalMessage: { - IOUTransactionID: null, - }, - errors: null, - }, - }; - const cleanUpTransactionThreadReportOnyxData = getCleanUpTransactionThreadReportOnyxData({ - transactionThreadID: firstIOU.childReportID, - shouldDeleteTransactionThread: !!firstIOU.childReportID, - reportAction: firstIOU, - }); - optimisticData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`, - value: updatedReportAction, - }); - optimisticData.push(...cleanUpTransactionThreadReportOnyxData.optimisticData); - successData.push(...cleanUpTransactionThreadReportOnyxData.successData); - - failureData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`, - value: { - [firstIOU.reportActionID]: { - ...firstIOU, - pendingAction: null, - }, - }, - }); - failureData.push(...cleanUpTransactionThreadReportOnyxData.failureData); - } - - optimisticData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.SNAPSHOT}${searchContext?.currentSearchHash}`, - value: { - data: { - [`${ONYXKEYS.COLLECTION.TRANSACTION}${originalTransactionID}`]: null, - }, - }, - }); - - // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 - failureData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.SNAPSHOT}${searchContext?.currentSearchHash}`, - value: { - data: { - [`${ONYXKEYS.COLLECTION.TRANSACTION}${originalTransactionID}`]: originalTransaction, - }, - }, - }); - } else { - optimisticData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.TRANSACTION}${originalTransactionID}`, - value: { - errors: null, - }, - }); - } - - if (isReverseSplitOperation) { - const parameters = { - ...splits.at(0), - comment: splits.at(0)?.comment?.comment, - } as RevertSplitTransactionParams; - API.write(WRITE_COMMANDS.REVERT_SPLIT_TRANSACTION, parameters, {optimisticData, successData, failureData}); - } else { - // Prepare splitApiParams for the Transaction_Split API call which requires a specific format for the splits - // The format is: splits[0][amount], splits[0][category], splits[0][tag] etc. - const splitApiParams = {} as Record; - for (const [i, split] of splits.entries()) { - for (const [key, value] of Object.entries(split)) { - splitApiParams[`splits[${i}][${key}]`] = value !== null && typeof value === 'object' ? JSON.stringify(value) : value; - } - } - if (isCreationOfSplits) { - const isTransactionOnHold = isOnHold(originalTransaction); - - if (isTransactionOnHold) { - const holdReportActionIDs: string[] = []; - const holdReportActionCommentIDs: string[] = []; - const transactionReportActions = getAllReportActions(firstIOU?.childReportID); - const holdReportAction = getReportAction(firstIOU?.childReportID, `${originalTransaction?.comment?.hold ?? ''}`); - - const holdReportActionComment = holdReportAction - ? Object.values(transactionReportActions ?? {}).find( - (action) => action?.actionName === CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT && action?.timestamp === holdReportAction.timestamp, - ) - : undefined; - - if (holdReportAction && holdReportActionComment) { - // Loop through all split expenses and add optimistic hold report actions for each split - for (const [index, splitExpense] of splits.entries()) { - const splitReportID = splitExpense?.transactionThreadReportID; - if (!splitReportID) { - continue; - } - - // Generate new IDs and timestamps for each split - const newHoldReportActionID = NumberUtils.rand64(); - const newHoldReportActionCommentID = NumberUtils.rand64(); - const timestamp = DateUtils.getDBTime(); - const reportActionTimestamp = DateUtils.addMillisecondsFromDateTime(timestamp, 1); - - // Store IDs for API parameters - holdReportActionIDs[index] = newHoldReportActionID; - holdReportActionCommentIDs[index] = newHoldReportActionCommentID; - - // Create new optimistic hold report action with new ID and timestamp, keeping other information - const newHoldReportAction = { - ...holdReportAction, - reportActionID: newHoldReportActionID, - created: timestamp, - pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD, - }; - - // Create new optimistic hold report action comment with new ID and timestamp, keeping other information - const newHoldReportActionComment = { - ...holdReportActionComment, - reportActionID: newHoldReportActionCommentID, - created: reportActionTimestamp, - pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD, - }; - - // Add to optimisticData for this split's reportActions - optimisticData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${splitReportID}`, - value: { - [newHoldReportActionID]: newHoldReportAction, - [newHoldReportActionCommentID]: newHoldReportActionComment, - }, - }); - - // Add successData to clear pendingAction after API call succeeds - successData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${splitReportID}`, - value: { - [newHoldReportActionID]: {pendingAction: null}, - [newHoldReportActionCommentID]: {pendingAction: null}, - }, - }); - - // Add failureData to remove optimistic hold report actions if the request fails - failureData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${splitReportID}`, - value: { - [newHoldReportActionID]: null, - [newHoldReportActionCommentID]: null, - }, - }); - } - - // Add hold report action IDs to API parameters - for (const [i, holdReportActionID] of holdReportActionIDs.entries()) { - if (holdReportActionID) { - splitApiParams[`splits[${i}][holdReportActionID]`] = holdReportActionID; - } - } - for (const [i, holdReportActionCommentID] of holdReportActionCommentIDs.entries()) { - if (holdReportActionCommentID) { - splitApiParams[`splits[${i}][holdReportActionCommentID]`] = holdReportActionCommentID; - } - } - } - } - } - - const splitParameters: SplitTransactionParams = { - ...splitApiParams, - transactionID: originalTransactionID, - }; - - if (isCreationOfSplits) { - // eslint-disable-next-line rulesdir/no-multiple-api-calls - API.write(WRITE_COMMANDS.SPLIT_TRANSACTION, splitParameters, {optimisticData, successData, failureData}); - } else { - // eslint-disable-next-line rulesdir/no-multiple-api-calls - API.write(WRITE_COMMANDS.UPDATE_SPLIT_TRANSACTION, splitParameters, {optimisticData, successData, failureData}); - } - } - // eslint-disable-next-line @typescript-eslint/no-deprecated - InteractionManager.runAfterInteractions(() => removeDraftSplitTransaction(originalTransactionID)); -} - -function updateSplitTransactionsFromSplitExpensesFlow(params: UpdateSplitTransactionsParams) { - updateSplitTransactions(params); - const transactionReport = getReportOrDraftReport(params.transactionData?.reportID); - const parentTransactionReport = getReportOrDraftReport(transactionReport?.parentReportID); - const expenseReport = transactionReport?.type === CONST.REPORT.TYPE.EXPENSE ? transactionReport : parentTransactionReport; - const isSearchPageTopmostFullScreenRoute = isSearchTopmostFullScreenRoute(); - const transactionThreadReportID = params.firstIOU?.childReportID; - const transactionThreadReportScreen = Navigation.getReportRouteByID(transactionThreadReportID); - - // Reset selected transactions in search after saving split expenses - const searchFullScreenRoutes = navigationRef.getRootState()?.routes.findLast((route) => route.name === NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR); - const lastRoute = searchFullScreenRoutes?.state?.routes?.at(-1); - const isUserOnSearchPage = isSearchTopmostFullScreenRoute() && lastRoute?.name === SCREENS.SEARCH.ROOT; - if (isUserOnSearchPage) { - params?.searchContext?.clearSelectedTransactions?.(undefined, true); - } else { - params?.searchContext?.clearSelectedTransactions?.(true); - } - - if (isSearchPageTopmostFullScreenRoute || !transactionReport?.parentReportID) { - Navigation.dismissToSuperWideRHP(); - - // After the modal is dismissed, remove the transaction thread report screen - // to avoid navigating back to a report removed by the split transaction. - requestAnimationFrame(() => { - if (!transactionThreadReportScreen?.key) { - return; - } - - Navigation.removeScreenByKey(transactionThreadReportScreen.key); - }); - - return; - } - Navigation.dismissModalWithReport({reportID: expenseReport?.reportID ?? String(CONST.DEFAULT_NUMBER_ID)}); - - // After the modal is dismissed, remove the transaction thread report screen - // to avoid navigating back to a report removed by the split transaction. - requestAnimationFrame(() => { - if (!transactionThreadReportScreen?.key) { - return; - } - - Navigation.removeScreenByKey(transactionThreadReportScreen.key); - }); -} - function assignReportToMe( report: OnyxTypes.Report, accountID: number, @@ -13781,7 +13210,6 @@ export { setMoneyRequestTimeRate, setMoneyRequestTimeCount, getCleanUpTransactionThreadReportOnyxData, - getDeleteTrackExpenseInformation, buildMinimalTransactionForFormula, buildOnyxDataForMoneyRequest, createSplitsAndOnyxData, diff --git a/tests/actions/IOUTest.ts b/tests/actions/IOUTest.ts index 0d76af8b2c0e..956b4589864a 100644 --- a/tests/actions/IOUTest.ts +++ b/tests/actions/IOUTest.ts @@ -61,16 +61,7 @@ import {rand64} from '@libs/NumberUtils'; import {getLoginsByAccountIDs} from '@libs/PersonalDetailsUtils'; // eslint-disable-next-line no-restricted-syntax import type * as PolicyUtils from '@libs/PolicyUtils'; -import { - getOriginalMessage, - getReportAction, - getReportActionHtml, - getReportActionMessage, - getReportActionText, - isActionableTrackExpense, - isActionOfType, - isMoneyRequestAction, -} from '@libs/ReportActionsUtils'; +import {getOriginalMessage, getReportActionHtml, getReportActionMessage, getReportActionText, isActionableTrackExpense, isActionOfType, isMoneyRequestAction} from '@libs/ReportActionsUtils'; import type {OptimisticChatReport} from '@libs/ReportUtils'; import {buildOptimisticIOUReport, buildOptimisticIOUReportAction, buildTransactionThread, createDraftTransactionAndNavigateToParticipantSelector, isIOUReport} from '@libs/ReportUtils'; import {buildOptimisticTransaction, getValidWaypoints, isDistanceRequest as isDistanceRequestUtil} from '@libs/TransactionUtils'; @@ -2722,1493 +2713,6 @@ describe('actions/IOU', () => { }); }); - describe('split expense', () => { - it('creates and updates new chats and IOUs as needed', () => { - jest.setTimeout(10 * 1000); - /* - * Given that: - * - Rory and Carlos have chatted before - * - Rory and Jules have chatted before and have an active IOU report - * - Rory and Vit have never chatted together before - * - There is no existing group chat with the four of them - */ - const amount = 400; - const comment = 'Yes, I am splitting a bill for $4 USD'; - const merchant = 'Yema Kitchen'; - let carlosChatReport: OnyxEntry = { - reportID: rand64(), - type: CONST.REPORT.TYPE.CHAT, - participants: {[RORY_ACCOUNT_ID]: RORY_PARTICIPANT, [CARLOS_ACCOUNT_ID]: CARLOS_PARTICIPANT}, - }; - const carlosCreatedAction: OnyxEntry = { - reportActionID: rand64(), - actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, - created: DateUtils.getDBTime(), - reportID: carlosChatReport.reportID, - }; - const julesIOUReportID = rand64(); - let julesChatReport: OnyxEntry = { - reportID: rand64(), - type: CONST.REPORT.TYPE.CHAT, - iouReportID: julesIOUReportID, - participants: {[RORY_ACCOUNT_ID]: RORY_PARTICIPANT, [JULES_ACCOUNT_ID]: JULES_PARTICIPANT}, - }; - const julesChatCreatedAction: OnyxEntry = { - reportActionID: rand64(), - actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, - created: DateUtils.getDBTime(), - reportID: julesChatReport.reportID, - }; - const julesCreatedAction: OnyxEntry = { - reportActionID: rand64(), - actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, - created: DateUtils.getDBTime(), - reportID: julesIOUReportID, - }; - jest.advanceTimersByTime(200); - const julesExistingTransaction: OnyxEntry = { - transactionID: rand64(), - amount: 1000, - comment: { - comment: 'This is an existing transaction', - attendees: [{email: 'text@expensify.com', displayName: 'Test User', avatarUrl: ''}], - }, - created: DateUtils.getDBTime(), - currency: '', - merchant: '', - reportID: '', - }; - let julesIOUReport: OnyxEntry = { - reportID: julesIOUReportID, - chatReportID: julesChatReport.reportID, - type: CONST.REPORT.TYPE.IOU, - ownerAccountID: RORY_ACCOUNT_ID, - managerID: JULES_ACCOUNT_ID, - currency: CONST.CURRENCY.USD, - total: julesExistingTransaction?.amount, - }; - const julesExistingIOUAction: OnyxEntry = { - reportActionID: rand64(), - actionName: CONST.REPORT.ACTIONS.TYPE.IOU, - actorAccountID: RORY_ACCOUNT_ID, - created: DateUtils.getDBTime(), - originalMessage: { - IOUReportID: julesIOUReportID, - IOUTransactionID: julesExistingTransaction?.transactionID, - amount: julesExistingTransaction?.amount ?? 0, - currency: CONST.CURRENCY.USD, - type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, - participantAccountIDs: [RORY_ACCOUNT_ID, JULES_ACCOUNT_ID], - }, - reportID: julesIOUReportID, - }; - - let carlosIOUReport: OnyxEntry; - let carlosIOUAction: OnyxEntry>; - let carlosIOUCreatedAction: OnyxEntry; - let carlosTransaction: OnyxEntry; - - let julesIOUAction: OnyxEntry>; - let julesIOUCreatedAction: OnyxEntry; - let julesTransaction: OnyxEntry; - - let vitChatReport: OnyxEntry; - let vitIOUReport: OnyxEntry; - let vitCreatedAction: OnyxEntry; - let vitIOUAction: OnyxEntry>; - let vitTransaction: OnyxEntry; - - let groupChat: OnyxEntry; - let groupCreatedAction: OnyxEntry; - let groupIOUAction: OnyxEntry>; - let groupTransaction: OnyxEntry; - - const reportCollectionDataSet = toCollectionDataSet(ONYXKEYS.COLLECTION.REPORT, [carlosChatReport, julesChatReport, julesIOUReport], (item) => item.reportID); - - const carlosActionsCollectionDataSet = toCollectionDataSet( - `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}`, - [ - { - [carlosCreatedAction.reportActionID]: carlosCreatedAction, - }, - ], - (item) => item[carlosCreatedAction.reportActionID].reportID, - ); - - const julesActionsCollectionDataSet = toCollectionDataSet( - `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}`, - [ - { - [julesCreatedAction.reportActionID]: julesCreatedAction, - [julesExistingIOUAction.reportActionID]: julesExistingIOUAction, - }, - ], - (item) => item[julesCreatedAction.reportActionID].reportID, - ); - - const julesCreatedActionsCollectionDataSet = toCollectionDataSet( - `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}`, - [ - { - [julesChatCreatedAction.reportActionID]: julesChatCreatedAction, - }, - ], - (item) => item[julesChatCreatedAction.reportActionID].reportID, - ); - - // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 - return Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT, { - ...reportCollectionDataSet, - }) - .then(() => - // @ts-expect-error - will be solved in https://github.com/Expensify/App/issues/73830 - Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT_ACTIONS, { - ...carlosActionsCollectionDataSet, - ...julesCreatedActionsCollectionDataSet, - ...julesActionsCollectionDataSet, - }), - ) - .then(() => Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${julesExistingTransaction?.transactionID}`, julesExistingTransaction)) - .then(() => { - // When we split a bill offline - mockFetch?.pause?.(); - splitBill( - // TODO: Migrate after the backend accepts accountIDs - { - participants: [ - [CARLOS_EMAIL, String(CARLOS_ACCOUNT_ID)], - [JULES_EMAIL, String(JULES_ACCOUNT_ID)], - [VIT_EMAIL, String(VIT_ACCOUNT_ID)], - ].map(([email, accountID]) => ({login: email, accountID: Number(accountID)})), - currentUserLogin: RORY_EMAIL, - currentUserAccountID: RORY_ACCOUNT_ID, - amount, - comment, - currency: CONST.CURRENCY.USD, - merchant, - created: '', - tag: '', - existingSplitChatReportID: '', - isASAPSubmitBetaEnabled: false, - transactionViolations: {}, - quickAction: undefined, - policyRecentlyUsedCurrencies: [], - policyRecentlyUsedTags: undefined, - }, - ); - return waitForBatchedUpdates(); - }) - .then( - () => - new Promise((resolve) => { - const connection = Onyx.connect({ - key: ONYXKEYS.COLLECTION.REPORT, - waitForCollectionCallback: true, - callback: (allReports) => { - Onyx.disconnect(connection); - - // There should now be 10 reports - expect(Object.values(allReports ?? {}).length).toBe(10); - - // 1. The chat report with Rory + Carlos - carlosChatReport = Object.values(allReports ?? {}).find((report) => report?.reportID === carlosChatReport?.reportID); - expect(isEmptyObject(carlosChatReport)).toBe(false); - expect(carlosChatReport?.pendingFields).toBeFalsy(); - - // 2. The IOU report with Rory + Carlos (new) - carlosIOUReport = Object.values(allReports ?? {}).find((report) => report?.type === CONST.REPORT.TYPE.IOU && report.managerID === CARLOS_ACCOUNT_ID); - expect(isEmptyObject(carlosIOUReport)).toBe(false); - expect(carlosIOUReport?.total).toBe(amount / 4); - - // 3. The chat report with Rory + Jules - julesChatReport = Object.values(allReports ?? {}).find((report) => report?.reportID === julesChatReport?.reportID); - expect(isEmptyObject(julesChatReport)).toBe(false); - expect(julesChatReport?.pendingFields).toBeFalsy(); - - // 4. The IOU report with Rory + Jules - julesIOUReport = Object.values(allReports ?? {}).find((report) => report?.reportID === julesIOUReport?.reportID); - expect(isEmptyObject(julesIOUReport)).toBe(false); - expect(julesChatReport?.pendingFields).toBeFalsy(); - expect(julesIOUReport?.total).toBe((julesExistingTransaction?.amount ?? 0) + amount / 4); - - // 5. The chat report with Rory + Vit (new) - vitChatReport = Object.values(allReports ?? {}).find( - (report) => - report?.type === CONST.REPORT.TYPE.CHAT && - deepEqual(report.participants, {[RORY_ACCOUNT_ID]: RORY_PARTICIPANT, [VIT_ACCOUNT_ID]: VIT_PARTICIPANT}), - ); - expect(isEmptyObject(vitChatReport)).toBe(false); - expect(vitChatReport?.pendingFields).toStrictEqual({createChat: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD}); - - // 6. The IOU report with Rory + Vit (new) - vitIOUReport = Object.values(allReports ?? {}).find((report) => report?.type === CONST.REPORT.TYPE.IOU && report.managerID === VIT_ACCOUNT_ID); - expect(isEmptyObject(vitIOUReport)).toBe(false); - expect(vitIOUReport?.total).toBe(amount / 4); - - // 7. The group chat with everyone - groupChat = Object.values(allReports ?? {}).find( - (report) => - report?.type === CONST.REPORT.TYPE.CHAT && - deepEqual(report.participants, { - [CARLOS_ACCOUNT_ID]: CARLOS_PARTICIPANT, - [JULES_ACCOUNT_ID]: JULES_PARTICIPANT, - [VIT_ACCOUNT_ID]: VIT_PARTICIPANT, - [RORY_ACCOUNT_ID]: RORY_PARTICIPANT, - }), - ); - expect(isEmptyObject(groupChat)).toBe(false); - expect(groupChat?.pendingFields).toStrictEqual({createChat: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD}); - - // The 1:1 chat reports and the IOU reports should be linked together - expect(carlosChatReport?.iouReportID).toBe(carlosIOUReport?.reportID); - expect(carlosIOUReport?.chatReportID).toBe(carlosChatReport?.reportID); - for (const participant of Object.values(carlosIOUReport?.participants ?? {})) { - expect(participant.notificationPreference).toBe(CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN); - } - - expect(julesChatReport?.iouReportID).toBe(julesIOUReport?.reportID); - expect(julesIOUReport?.chatReportID).toBe(julesChatReport?.reportID); - - expect(vitChatReport?.iouReportID).toBe(vitIOUReport?.reportID); - expect(vitIOUReport?.chatReportID).toBe(vitChatReport?.reportID); - - resolve(); - }, - }); - }), - ) - .then( - () => - new Promise((resolve) => { - const connection = Onyx.connect({ - key: ONYXKEYS.COLLECTION.REPORT_ACTIONS, - waitForCollectionCallback: true, - callback: (allReportActions) => { - Onyx.disconnect(connection); - - // There should be reportActions on all 7 chat reports + 3 IOU reports in each 1:1 chat - expect(Object.values(allReportActions ?? {}).length).toBe(10); - - const carlosReportActions = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${carlosChatReport?.iouReportID}`]; - const julesReportActions = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${julesChatReport?.iouReportID}`]; - const vitReportActions = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${vitChatReport?.iouReportID}`]; - const groupReportActions = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${groupChat?.reportID}`]; - - // Carlos DM should have two reportActions – the existing CREATED action and a pending IOU action - expect(Object.values(carlosReportActions ?? {}).length).toBe(2); - carlosIOUCreatedAction = Object.values(carlosReportActions ?? {}).find( - (reportAction): reportAction is ReportAction => reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED, - ); - carlosIOUAction = Object.values(carlosReportActions ?? {}).find((reportAction): reportAction is ReportAction => - isMoneyRequestAction(reportAction), - ); - const carlosOriginalMessage = carlosIOUAction ? getOriginalMessage(carlosIOUAction) : undefined; - - expect(carlosIOUAction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD); - expect(carlosOriginalMessage?.IOUReportID).toBe(carlosIOUReport?.reportID); - expect(carlosOriginalMessage?.amount).toBe(amount / 4); - expect(carlosOriginalMessage?.comment).toBe(comment); - expect(carlosOriginalMessage?.type).toBe(CONST.IOU.REPORT_ACTION_TYPE.CREATE); - expect(Date.parse(carlosIOUCreatedAction?.created ?? '')).toBeLessThan(Date.parse(carlosIOUAction?.created ?? '')); - - // Jules DM should have three reportActions, the existing CREATED action, the existing IOU action, and a new pending IOU action - expect(Object.values(julesReportActions ?? {}).length).toBe(3); - expect(julesReportActions?.[julesCreatedAction.reportActionID]).toStrictEqual(julesCreatedAction); - julesIOUCreatedAction = Object.values(julesReportActions ?? {}).find( - (reportAction): reportAction is ReportAction => reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED, - ); - julesIOUAction = Object.values(julesReportActions ?? {}).find( - (reportAction): reportAction is ReportAction => - reportAction.reportActionID !== julesCreatedAction.reportActionID && reportAction.reportActionID !== julesExistingIOUAction.reportActionID, - ); - const julesOriginalMessage = julesIOUAction ? getOriginalMessage(julesIOUAction) : undefined; - - expect(julesIOUAction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD); - expect(julesOriginalMessage?.IOUReportID).toBe(julesIOUReport?.reportID); - expect(julesOriginalMessage?.amount).toBe(amount / 4); - expect(julesOriginalMessage?.comment).toBe(comment); - expect(julesOriginalMessage?.type).toBe(CONST.IOU.REPORT_ACTION_TYPE.CREATE); - expect(Date.parse(julesIOUCreatedAction?.created ?? '')).toBeLessThan(Date.parse(julesIOUAction?.created ?? '')); - - // Vit DM should have two reportActions – a pending CREATED action and a pending IOU action - expect(Object.values(vitReportActions ?? {}).length).toBe(2); - vitCreatedAction = Object.values(vitReportActions ?? {}).find( - (reportAction): reportAction is ReportAction => reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED, - ); - vitIOUAction = Object.values(vitReportActions ?? {}).find((reportAction): reportAction is ReportAction => - isMoneyRequestAction(reportAction), - ); - const vitOriginalMessage = vitIOUAction ? getOriginalMessage(vitIOUAction) : undefined; - - expect(vitCreatedAction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD); - expect(vitIOUAction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD); - expect(vitOriginalMessage?.IOUReportID).toBe(vitIOUReport?.reportID); - expect(vitOriginalMessage?.amount).toBe(amount / 4); - expect(vitOriginalMessage?.comment).toBe(comment); - expect(vitOriginalMessage?.type).toBe(CONST.IOU.REPORT_ACTION_TYPE.CREATE); - expect(Date.parse(vitCreatedAction?.created ?? '')).toBeLessThan(Date.parse(vitIOUAction?.created ?? '')); - - // Group chat should have two reportActions – a pending CREATED action and a pending IOU action w/ type SPLIT - expect(Object.values(groupReportActions ?? {}).length).toBe(2); - groupCreatedAction = Object.values(groupReportActions ?? {}).find((reportAction) => reportAction.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED); - groupIOUAction = Object.values(groupReportActions ?? {}).find((reportAction): reportAction is ReportAction => - isMoneyRequestAction(reportAction), - ); - const groupOriginalMessage = groupIOUAction ? getOriginalMessage(groupIOUAction) : undefined; - - expect(groupCreatedAction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD); - expect(groupIOUAction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD); - expect(groupOriginalMessage).not.toHaveProperty('IOUReportID'); - expect(groupOriginalMessage?.type).toBe(CONST.IOU.REPORT_ACTION_TYPE.SPLIT); - expect(Date.parse(groupCreatedAction?.created ?? '')).toBeLessThanOrEqual(Date.parse(groupIOUAction?.created ?? '')); - - resolve(); - }, - }); - }), - ) - .then( - () => - new Promise((resolve) => { - const connection = Onyx.connect({ - key: ONYXKEYS.COLLECTION.TRANSACTION, - waitForCollectionCallback: true, - callback: (allTransactions) => { - Onyx.disconnect(connection); - - /* There should be 5 transactions - * – one existing one with Jules - * - one for each of the three IOU reports - * - one on the group chat w/ deleted report - */ - expect(Object.values(allTransactions ?? {}).length).toBe(5); - expect(allTransactions?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${julesExistingTransaction?.transactionID}`]).toBeTruthy(); - - carlosTransaction = Object.values(allTransactions ?? {}).find( - (transaction) => carlosIOUAction && transaction?.transactionID === getOriginalMessage(carlosIOUAction)?.IOUTransactionID, - ); - julesTransaction = Object.values(allTransactions ?? {}).find( - (transaction) => julesIOUAction && transaction?.transactionID === getOriginalMessage(julesIOUAction)?.IOUTransactionID, - ); - vitTransaction = Object.values(allTransactions ?? {}).find( - (transaction) => vitIOUAction && transaction?.transactionID === getOriginalMessage(vitIOUAction)?.IOUTransactionID, - ); - groupTransaction = Object.values(allTransactions ?? {}).find((transaction) => transaction?.reportID === CONST.REPORT.SPLIT_REPORT_ID); - - expect(carlosTransaction?.reportID).toBe(carlosIOUReport?.reportID); - expect(julesTransaction?.reportID).toBe(julesIOUReport?.reportID); - expect(vitTransaction?.reportID).toBe(vitIOUReport?.reportID); - expect(groupTransaction).toBeTruthy(); - - expect(carlosTransaction?.amount).toBe(amount / 4); - expect(julesTransaction?.amount).toBe(amount / 4); - expect(vitTransaction?.amount).toBe(amount / 4); - expect(groupTransaction?.amount).toBe(amount); - - expect(carlosTransaction?.comment?.comment).toBe(comment); - expect(julesTransaction?.comment?.comment).toBe(comment); - expect(vitTransaction?.comment?.comment).toBe(comment); - expect(groupTransaction?.comment?.comment).toBe(comment); - - expect(carlosTransaction?.merchant).toBe(merchant); - expect(julesTransaction?.merchant).toBe(merchant); - expect(vitTransaction?.merchant).toBe(merchant); - expect(groupTransaction?.merchant).toBe(merchant); - - expect(carlosTransaction?.comment?.source).toBe(CONST.IOU.TYPE.SPLIT); - expect(julesTransaction?.comment?.source).toBe(CONST.IOU.TYPE.SPLIT); - expect(vitTransaction?.comment?.source).toBe(CONST.IOU.TYPE.SPLIT); - - expect(carlosTransaction?.comment?.originalTransactionID).toBe(groupTransaction?.transactionID); - expect(julesTransaction?.comment?.originalTransactionID).toBe(groupTransaction?.transactionID); - expect(vitTransaction?.comment?.originalTransactionID).toBe(groupTransaction?.transactionID); - - expect(carlosTransaction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD); - expect(julesTransaction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD); - expect(vitTransaction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD); - expect(groupTransaction?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD); - - resolve(); - }, - }); - }), - ) - .then( - () => - new Promise((resolve) => { - const connection = Onyx.connect({ - key: ONYXKEYS.PERSONAL_DETAILS_LIST, - waitForCollectionCallback: false, - callback: (allPersonalDetails) => { - Onyx.disconnect(connection); - expect(allPersonalDetails).toMatchObject({ - [VIT_ACCOUNT_ID]: { - accountID: VIT_ACCOUNT_ID, - displayName: VIT_EMAIL, - login: VIT_EMAIL, - }, - }); - resolve(); - }, - }); - }), - ) - .then(mockFetch?.resume) - .then(waitForNetworkPromises) - .then( - () => - new Promise((resolve) => { - const connection = Onyx.connect({ - key: ONYXKEYS.COLLECTION.REPORT, - waitForCollectionCallback: true, - callback: (allReports) => { - Onyx.disconnect(connection); - for (const report of Object.values(allReports ?? {})) { - if (!report?.pendingFields) { - continue; - } - for (const pendingField of Object.values(report?.pendingFields)) { - expect(pendingField).toBeFalsy(); - } - } - resolve(); - }, - }); - }), - ) - .then( - () => - new Promise((resolve) => { - const connection = Onyx.connect({ - key: ONYXKEYS.COLLECTION.REPORT_ACTIONS, - waitForCollectionCallback: true, - callback: (allReportActions) => { - Onyx.disconnect(connection); - for (const reportAction of Object.values(allReportActions ?? {})) { - expect(reportAction?.pendingAction).toBeFalsy(); - } - resolve(); - }, - }); - }), - ) - .then( - () => - new Promise((resolve) => { - const connection = Onyx.connect({ - key: ONYXKEYS.COLLECTION.TRANSACTION, - waitForCollectionCallback: true, - callback: (allTransactions) => { - Onyx.disconnect(connection); - for (const transaction of Object.values(allTransactions ?? {})) { - expect(transaction?.pendingAction).toBeFalsy(); - } - resolve(); - }, - }); - }), - ); - }); - - it('should update split chat report lastVisibleActionCreated to the report preview action', async () => { - // Given a expense chat with no expenses - const workspaceReportID = '1'; - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${workspaceReportID}`, {reportID: workspaceReportID, isOwnPolicyExpenseChat: true}); - - // When the user split bill on the workspace - splitBill({ - participants: [{reportID: workspaceReportID}], - currentUserLogin: RORY_EMAIL, - currentUserAccountID: RORY_ACCOUNT_ID, - comment: '', - amount: 100, - currency: CONST.CURRENCY.USD, - merchant: 'test', - created: '', - existingSplitChatReportID: workspaceReportID, - isASAPSubmitBetaEnabled: false, - transactionViolations: {}, - quickAction: undefined, - policyRecentlyUsedCurrencies: [], - policyRecentlyUsedTags: undefined, - }); - - await waitForBatchedUpdates(); - - // Then the expense chat lastVisibleActionCreated should be updated to the report preview action created - const reportPreviewAction = await new Promise>((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${workspaceReportID}`, - callback: (reportActions) => { - Onyx.disconnect(connection); - resolve(Object.values(reportActions ?? {}).find((action) => action.actionName === CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW)); - }, - }); - }); - - await new Promise>((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${workspaceReportID}`, - callback: (report) => { - Onyx.disconnect(connection); - expect(report?.lastVisibleActionCreated).toBe(reportPreviewAction?.created); - resolve(report); - }, - }); - }); - }); - - it('correctly sets quickAction', async () => { - // Given a expense chat with no expenses - const workspaceReportID = '1'; - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${workspaceReportID}`, {reportID: workspaceReportID, isOwnPolicyExpenseChat: true}); - - splitBill({ - participants: [{reportID: workspaceReportID}], - currentUserLogin: RORY_EMAIL, - currentUserAccountID: RORY_ACCOUNT_ID, - comment: '', - amount: 100, - currency: CONST.CURRENCY.USD, - merchant: 'test', - created: '', - existingSplitChatReportID: workspaceReportID, - isASAPSubmitBetaEnabled: false, - transactionViolations: {}, - quickAction: undefined, - policyRecentlyUsedCurrencies: [], - policyRecentlyUsedTags: undefined, - }); - - await waitForBatchedUpdates(); - - expect(await getOnyxValue(ONYXKEYS.NVP_QUICK_ACTION_GLOBAL_CREATE)).toHaveProperty('isFirstQuickAction', true); - - splitBill({ - participants: [{reportID: workspaceReportID}], - currentUserLogin: RORY_EMAIL, - currentUserAccountID: RORY_ACCOUNT_ID, - comment: '', - amount: 100, - currency: CONST.CURRENCY.USD, - merchant: 'test', - created: '', - existingSplitChatReportID: workspaceReportID, - isASAPSubmitBetaEnabled: false, - transactionViolations: {}, - quickAction: {action: CONST.QUICK_ACTIONS.SEND_MONEY, chatReportID: '456'}, - policyRecentlyUsedCurrencies: [], - policyRecentlyUsedTags: undefined, - }); - await waitForBatchedUpdates(); - - expect(await getOnyxValue(ONYXKEYS.NVP_QUICK_ACTION_GLOBAL_CREATE)).toMatchObject({ - action: CONST.QUICK_ACTIONS.SPLIT_MANUAL, - isFirstQuickAction: false, - }); - }); - - it('merges policyRecentlyUsedCurrencies when splitting a bill', async () => { - const initialCurrencies = [CONST.CURRENCY.USD]; - await Onyx.set(ONYXKEYS.RECENTLY_USED_CURRENCIES, initialCurrencies); - - splitBill({ - participants: [{accountID: CARLOS_ACCOUNT_ID, login: CARLOS_EMAIL}], - currentUserLogin: RORY_EMAIL, - currentUserAccountID: RORY_ACCOUNT_ID, - comment: '', - amount: 100, - currency: CONST.CURRENCY.EUR, - merchant: 'test', - created: '', - existingSplitChatReportID: '', - isASAPSubmitBetaEnabled: false, - transactionViolations: {}, - quickAction: undefined, - policyRecentlyUsedCurrencies: initialCurrencies, - policyRecentlyUsedTags: undefined, - }); - - await waitForBatchedUpdates(); - - const recentlyUsedCurrencies = await getOnyxValue(ONYXKEYS.RECENTLY_USED_CURRENCIES); - expect(recentlyUsedCurrencies).toEqual([CONST.CURRENCY.EUR, ...initialCurrencies]); - }); - - it('should update split chat report lastVisibleActionCreated to the latest IOU action when split bill in a DM', async () => { - // Given a DM chat with no expenses - const reportID = '1'; - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, { - reportID, - type: CONST.REPORT.TYPE.CHAT, - participants: {[RORY_ACCOUNT_ID]: RORY_PARTICIPANT, [CARLOS_ACCOUNT_ID]: CARLOS_PARTICIPANT}, - }); - - // When the user split bill twice on the DM - splitBill({ - participants: [{accountID: CARLOS_ACCOUNT_ID, login: CARLOS_EMAIL}], - currentUserLogin: RORY_EMAIL, - currentUserAccountID: RORY_ACCOUNT_ID, - comment: '', - amount: 100, - currency: CONST.CURRENCY.USD, - merchant: 'test', - created: '', - existingSplitChatReportID: reportID, - isASAPSubmitBetaEnabled: false, - transactionViolations: {}, - quickAction: undefined, - policyRecentlyUsedCurrencies: [], - policyRecentlyUsedTags: undefined, - }); - - await waitForBatchedUpdates(); - - splitBill({ - participants: [{accountID: CARLOS_ACCOUNT_ID, login: CARLOS_EMAIL}], - currentUserLogin: RORY_EMAIL, - currentUserAccountID: RORY_ACCOUNT_ID, - comment: '', - amount: 200, - currency: CONST.CURRENCY.USD, - merchant: 'test', - created: '', - existingSplitChatReportID: reportID, - isASAPSubmitBetaEnabled: false, - transactionViolations: {}, - quickAction: undefined, - policyRecentlyUsedCurrencies: [], - policyRecentlyUsedTags: undefined, - }); - - await waitForBatchedUpdates(); - - // Then the DM lastVisibleActionCreated should be updated to the second IOU action created - const iouAction = await new Promise>((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, - callback: (reportActions) => { - Onyx.disconnect(connection); - resolve(Object.values(reportActions ?? {}).find((action) => isActionOfType(action, CONST.REPORT.ACTIONS.TYPE.IOU) && getOriginalMessage(action)?.amount === 200)); - }, - }); - }); - - const report = await new Promise>((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`, - callback: (reportVal) => { - Onyx.disconnect(connection); - resolve(reportVal); - }, - }); - }); - expect(report?.lastVisibleActionCreated).toBe(iouAction?.created); - }); - - it('optimistic transaction should be merged with the draft transaction if it is a distance request', async () => { - // Given a workspace expense chat and a draft split transaction - const workspaceReportID = '1'; - const transactionAmount = 100; - const draftTransaction = { - amount: transactionAmount, - currency: CONST.CURRENCY.USD, - merchant: 'test', - created: '', - iouRequestType: CONST.IOU.REQUEST_TYPE.DISTANCE, - splitShares: { - [workspaceReportID]: {amount: 100}, - }, - }; - - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${workspaceReportID}`, {reportID: workspaceReportID, isOwnPolicyExpenseChat: true}); - await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${CONST.IOU.OPTIMISTIC_TRANSACTION_ID}`, draftTransaction); - - // When doing a distance split expense - splitBill({ - participants: [{reportID: workspaceReportID}], - currentUserLogin: RORY_EMAIL, - currentUserAccountID: RORY_ACCOUNT_ID, - existingSplitChatReportID: workspaceReportID, - ...draftTransaction, - comment: '', - isASAPSubmitBetaEnabled: false, - transactionViolations: {}, - quickAction: undefined, - policyRecentlyUsedCurrencies: [], - policyRecentlyUsedTags: undefined, - }); - - await waitForBatchedUpdates(); - - const optimisticTransaction = await new Promise>((resolve) => { - const connection = Onyx.connect({ - key: ONYXKEYS.COLLECTION.TRANSACTION, - waitForCollectionCallback: true, - callback: (transactions) => { - Onyx.disconnect(connection); - resolve(Object.values(transactions ?? {}).find((transaction) => transaction?.amount === -(transactionAmount / 2))); - }, - }); - }); - - // Then the data from the transaction draft should be merged into the optimistic transaction - expect(optimisticTransaction?.iouRequestType).toBe(CONST.IOU.REQUEST_TYPE.DISTANCE); - }); - - it("should update the notification preference of the report to ALWAYS if it's previously hidden", async () => { - // Given a group chat with hidden notification preference - const reportID = '1'; - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, { - reportID, - type: CONST.REPORT.TYPE.CHAT, - chatType: CONST.REPORT.CHAT_TYPE.GROUP, - participants: { - [RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN}, - [CARLOS_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN}, - }, - }); - - // When the user split bill on the group chat - splitBill({ - participants: [{accountID: CARLOS_ACCOUNT_ID, login: CARLOS_EMAIL}], - currentUserLogin: RORY_EMAIL, - currentUserAccountID: RORY_ACCOUNT_ID, - comment: '', - amount: 100, - currency: CONST.CURRENCY.USD, - merchant: 'test', - created: '', - existingSplitChatReportID: reportID, - isASAPSubmitBetaEnabled: false, - transactionViolations: {}, - quickAction: undefined, - policyRecentlyUsedCurrencies: [], - policyRecentlyUsedTags: undefined, - }); - - await waitForBatchedUpdates(); - - // Then the DM notification preference should be updated to ALWAYS - const report = await new Promise>((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`, - callback: (reportVal) => { - Onyx.disconnect(connection); - resolve(reportVal); - }, - }); - }); - expect(report?.participants?.[RORY_ACCOUNT_ID].notificationPreference).toBe(CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS); - }); - - it('should update the policyRecentlyUsedTags when tag is provided', async () => { - // Given a policy recently used tags - const policyID = 'A'; - const transactionTag = 'new tag'; - const tagName = 'Tag'; - const policyRecentlyUsedTags: OnyxEntry = { - [tagName]: ['old tag'], - }; - - const policyExpenseChat = { - reportID: '2', - policyID, - isPolicyExpenseChat: true, - isOwnPolicyExpenseChat: true, - }; - - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${policyExpenseChat.reportID}`, policyExpenseChat); - await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_TAGS}${policyID}`, { - [tagName]: {name: tagName}, - }); - await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS}${policyID}`, policyRecentlyUsedTags); - - // When doing a split bill - splitBill({ - participants: [{isPolicyExpenseChat: true, policyID}], - existingSplitChatReportID: policyExpenseChat.reportID, - currentUserLogin: currentUserPersonalDetails.login ?? '', - currentUserAccountID: currentUserPersonalDetails.accountID, - amount: 1, - created: '', - comment: '', - merchant: '', - transactionViolations: undefined, - category: undefined, - tag: transactionTag, - currency: CONST.CURRENCY.USD, - taxCode: '', - taxAmount: 0, - isASAPSubmitBetaEnabled: false, - policyRecentlyUsedTags, - quickAction: {}, - policyRecentlyUsedCurrencies: [], - }); - - waitForBatchedUpdates(); - - // Then the transaction tag should be added to the recently used tags collection - const newPolicyRecentlyUsedTags: RecentlyUsedTags = await new Promise((resolve) => { - const connection = Onyx.connectWithoutView({ - key: `${ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS}${policyID}`, - callback: (recentlyUsedTags) => { - resolve(recentlyUsedTags ?? {}); - Onyx.disconnect(connection); - }, - }); - }); - expect(newPolicyRecentlyUsedTags[tagName].length).toBe(2); - expect(newPolicyRecentlyUsedTags[tagName].at(0)).toBe(transactionTag); - }); - - it('the description should not be parsed again after completing the scan split bill without changing the description', async () => { - const reportID = '1'; - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, { - reportID, - type: CONST.REPORT.TYPE.CHAT, - chatType: CONST.REPORT.CHAT_TYPE.GROUP, - participants: { - [RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS}, - [CARLOS_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS}, - }, - }); - - // Start a scan split bill - const {splitTransactionID} = startSplitBill({ - participants: [{accountID: CARLOS_ACCOUNT_ID, login: CARLOS_EMAIL}], - currentUserLogin: RORY_EMAIL, - currentUserAccountID: RORY_ACCOUNT_ID, - comment: '# test', - currency: CONST.CURRENCY.USD, - existingSplitChatReportID: reportID, - receipt: {}, - category: undefined, - tag: undefined, - taxCode: '', - taxAmount: 0, - quickAction: undefined, - policyRecentlyUsedCurrencies: [], - policyRecentlyUsedTags: undefined, - }); - - await waitForBatchedUpdates(); - - let splitTransaction = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${splitTransactionID}`); - - // Then the description should be parsed correctly - expect(splitTransaction?.comment?.comment).toBe('

test

'); - - const updatedSplitTransaction = splitTransaction - ? { - ...splitTransaction, - amount: 100, - } - : undefined; - - const reportActions = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`); - const iouAction = Object.values(reportActions ?? {}).find((action) => isActionOfType(action, CONST.REPORT.ACTIONS.TYPE.IOU)); - - expect(iouAction).toBeTruthy(); - - // Complete this split bill without changing the description - completeSplitBill(reportID, iouAction, updatedSplitTransaction, RORY_ACCOUNT_ID, false, undefined, {}, RORY_EMAIL); - - await waitForBatchedUpdates(); - - splitTransaction = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${splitTransactionID}`); - - // Then the description should be the same since it was not changed - expect(splitTransaction?.comment?.comment).toBe('

test

'); - }); - }); - - describe('startSplitBill', () => { - it('should update the policyRecentlyUsedTags when tag is provided', async () => { - // Given a policy recently used tags - const policyID = 'A'; - const transactionTag = 'new tag'; - const tagName = 'Tag'; - const policyRecentlyUsedTags: OnyxEntry = { - [tagName]: ['old tag'], - }; - - await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_TAGS}${policyID}`, { - [tagName]: {name: tagName}, - }); - await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS}${policyID}`, policyRecentlyUsedTags); - - // When doing a split bill with a receipt - startSplitBill({ - participants: [{isPolicyExpenseChat: true, policyID}], - currentUserLogin: currentUserPersonalDetails.login ?? '', - currentUserAccountID: currentUserPersonalDetails.accountID, - comment: '', - receipt: {}, - category: undefined, - tag: transactionTag, - currency: CONST.CURRENCY.USD, - taxCode: '', - taxAmount: 0, - policyRecentlyUsedTags, - quickAction: {}, - policyRecentlyUsedCurrencies: [], - }); - - waitForBatchedUpdates(); - - // Then the transaction tag should be added to the recently used tags collection - const newPolicyRecentlyUsedTags: RecentlyUsedTags = await new Promise((resolve) => { - const connection = Onyx.connectWithoutView({ - key: `${ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS}${policyID}`, - callback: (recentlyUsedTags) => { - resolve(recentlyUsedTags ?? {}); - Onyx.disconnect(connection); - }, - }); - }); - expect(newPolicyRecentlyUsedTags[tagName].length).toBe(2); - expect(newPolicyRecentlyUsedTags[tagName].at(0)).toBe(transactionTag); - }); - }); - - describe('updateSplitTransactionsFromSplitExpensesFlow', () => { - it('should delete the original transaction thread report', async () => { - const expenseReport: Report = { - ...createRandomReport(1, undefined), - type: CONST.REPORT.TYPE.EXPENSE, - }; - const transaction: Transaction = { - amount: 100, - currency: 'USD', - transactionID: '1', - reportID: expenseReport.reportID, - created: DateUtils.getDBTime(), - merchant: 'test', - }; - const transactionThread: Report = { - ...createRandomReport(2, undefined), - }; - const iouAction: ReportAction = { - ...buildOptimisticIOUReportAction({ - type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, - amount: transaction.amount, - currency: transaction.currency, - comment: '', - participants: [], - transactionID: transaction.transactionID, - iouReportID: expenseReport.reportID, - }), - childReportID: transactionThread.reportID, - }; - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`, expenseReport); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${transactionThread.reportID}`, transactionThread); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport.reportID}`, { - [iouAction.reportActionID]: iouAction, - }); - await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, transaction); - const draftTransaction: OnyxEntry = { - ...transaction, - comment: { - originalTransactionID: transaction.transactionID, - }, - }; - - let allTransactions: OnyxCollection; - let allReports: OnyxCollection; - let allReportNameValuePairs: OnyxCollection; - await getOnyxData({ - key: ONYXKEYS.COLLECTION.TRANSACTION, - waitForCollectionCallback: true, - callback: (value) => { - allTransactions = value; - }, - }); - await getOnyxData({ - key: ONYXKEYS.COLLECTION.REPORT, - waitForCollectionCallback: true, - callback: (value) => { - allReports = value; - }, - }); - await getOnyxData({ - key: ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, - waitForCollectionCallback: true, - callback: (value) => { - allReportNameValuePairs = value; - }, - }); - - updateSplitTransactionsFromSplitExpensesFlow({ - allTransactionsList: allTransactions, - allReportsList: allReports, - allReportNameValuePairsList: allReportNameValuePairs, - transactionData: { - reportID: draftTransaction?.reportID ?? String(CONST.DEFAULT_NUMBER_ID), - originalTransactionID: draftTransaction?.comment?.originalTransactionID ?? String(CONST.DEFAULT_NUMBER_ID), - splitExpenses: draftTransaction?.comment?.splitExpenses ?? [], - splitExpensesTotal: draftTransaction?.comment?.splitExpensesTotal, - }, - searchContext: { - currentSearchHash: -2, - }, - policyCategories: undefined, - policy: undefined, - policyRecentlyUsedCategories: [], - iouReport: expenseReport, - firstIOU: iouAction, - isASAPSubmitBetaEnabled: false, - currentUserPersonalDetails, - transactionViolations: {}, - policyRecentlyUsedCurrencies: [], - quickAction: undefined, - }); - - await waitForBatchedUpdates(); - - const originalTransactionThread = await new Promise>((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${iouAction.childReportID}`, - callback: (val) => { - Onyx.disconnect(connection); - resolve(val); - }, - }); - }); - expect(originalTransactionThread).toBe(undefined); - }); - - it('should delete the original transaction thread report regardless of whether there are visible comments, and update the comment count of the preview report', async () => { - const chatReportID = 'report123'; - const reportID = 'report456'; - const transactionID = 'transaction123'; - const previewActionID = 'action123'; - const iouActionID = 'action123'; - - const chatReport: Report = { - ...createRandomReport(0, undefined), - policyID: CONST.POLICY.ID_FAKE, - parentReportID: undefined, - parentReportActionID: undefined, - reportID: chatReportID, - type: 'chat', - }; - let previewAction: OnyxEntry = { - ...createRandomReportAction(0), - actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, - reportActionID: previewActionID, - childMoneyRequestCount: 1, - childVisibleActionCount: 0, - originalMessage: {linkedReportID: reportID}, - }; - const iouReport: Report = { - ...createRandomReport(1, undefined), - type: CONST.REPORT.TYPE.IOU, - chatReportID: chatReport.reportID, - parentReportID: chatReport.reportID, - parentReportActionID: previewAction.reportActionID, - reportID, - }; - const transaction: Transaction = { - amount: 100, - currency: 'USD', - transactionID, - reportID: iouReport.reportID, - created: DateUtils.getDBTime(), - merchant: 'test', - }; - - let iouAction: OnyxEntry = { - ...buildOptimisticIOUReportAction({ - type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, - amount: transaction.amount, - currency: transaction.currency, - comment: '', - participants: [], - transactionID: transaction.transactionID, - iouReportID: iouReport.reportID, - }), - reportActionID: iouActionID, - }; - - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, transaction); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, iouReport); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`, chatReport); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`, []); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReportID}`, { - [previewActionID]: previewAction, - }); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, { - [iouActionID]: iouAction, - }); - await waitForBatchedUpdates(); - - const thread = buildTransactionThread(iouAction, iouReport); - - expect(thread.participants).toEqual({ - [RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}, - }); - - const participantAccountIDs = Object.keys(thread.participants ?? {}).map(Number); - const userLogins = getLoginsByAccountIDs(participantAccountIDs); - jest.advanceTimersByTime(10); - openReport(thread.reportID, '', userLogins, thread, iouAction?.reportActionID); - await waitForBatchedUpdates(); - - let transactionThreadReportActions: OnyxEntry; - Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${thread.reportID}`, - callback: (val) => (transactionThreadReportActions = val), - }); - await waitForBatchedUpdates(); - - await new Promise((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, - callback: (report) => { - Onyx.disconnect(connection); - expect(report).toBeTruthy(); - resolve(); - }, - }); - }); - - jest.advanceTimersByTime(10); - - // When a comment is added - addComment( - thread, - thread.reportID, - [ - {report: iouReport, reportAction: iouAction, shouldDisplayNewMarker: false}, - {report: chatReport, reportAction: previewAction, shouldDisplayNewMarker: false}, - ], - 'test comment', - CONST.DEFAULT_TIME_ZONE, - ); - await waitForBatchedUpdates(); - - // Then the report should have 2 actions - expect(Object.values(transactionThreadReportActions ?? {}).length).toBe(2); - - iouAction = getReportAction(iouReport.reportID, iouActionID); - previewAction = getReportAction(chatReport.reportID, previewActionID); - expect(iouAction?.childVisibleActionCount).toBe(1); - expect(previewAction?.childVisibleActionCount).toBe(1); - - await waitForBatchedUpdates(); - - const draftTransaction: OnyxEntry = { - ...transaction, - comment: { - originalTransactionID: transaction.transactionID, - }, - }; - - let allTransactions: OnyxCollection; - let allReports: OnyxCollection; - let allReportNameValuePairs: OnyxCollection; - await getOnyxData({ - key: ONYXKEYS.COLLECTION.TRANSACTION, - waitForCollectionCallback: true, - callback: (value) => { - allTransactions = value; - }, - }); - await getOnyxData({ - key: ONYXKEYS.COLLECTION.REPORT, - waitForCollectionCallback: true, - callback: (value) => { - allReports = value; - }, - }); - await getOnyxData({ - key: ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, - waitForCollectionCallback: true, - callback: (value) => { - allReportNameValuePairs = value; - }, - }); - - updateSplitTransactionsFromSplitExpensesFlow({ - allTransactionsList: allTransactions, - allReportsList: allReports, - allReportNameValuePairsList: allReportNameValuePairs, - transactionData: { - reportID: draftTransaction?.reportID ?? String(CONST.DEFAULT_NUMBER_ID), - originalTransactionID: draftTransaction?.comment?.originalTransactionID ?? String(CONST.DEFAULT_NUMBER_ID), - splitExpenses: draftTransaction?.comment?.splitExpenses ?? [], - splitExpensesTotal: draftTransaction?.comment?.splitExpensesTotal, - }, - searchContext: { - currentSearchHash: -2, - }, - policyCategories: undefined, - policy: undefined, - policyRecentlyUsedCategories: [], - iouReport, - firstIOU: iouAction, - isASAPSubmitBetaEnabled: false, - currentUserPersonalDetails, - transactionViolations: {}, - policyRecentlyUsedCurrencies: [], - quickAction: undefined, - }); - - await waitForBatchedUpdates(); - - // Then we expect the reportPreview to update with new childVisibleActionCount - previewAction = getReportPreviewAction(chatReport?.reportID, iouReport?.reportID) ?? undefined; - expect(previewAction).toBeTruthy(); - expect(previewAction?.childVisibleActionCount).toEqual(0); - expect(previewAction?.childCommenterCount).toEqual(0); - - // Then the transaction thread report should be deleted - await new Promise((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, - waitForCollectionCallback: false, - callback: (report) => { - Onyx.disconnect(connection); - expect(report).toBeFalsy(); - resolve(); - }, - }); - }); - }); - - it('should remove the original transaction from the search snapshot data', async () => { - // Given a single expense - const expenseReport: Report = { - ...createRandomReport(1, undefined), - type: CONST.REPORT.TYPE.EXPENSE, - }; - const transaction: Transaction = { - amount: 100, - currency: 'USD', - transactionID: '1', - reportID: expenseReport.reportID, - created: DateUtils.getDBTime(), - merchant: 'test', - }; - const transactionThread: Report = { - ...createRandomReport(2, undefined), - }; - const iouAction: ReportAction = { - ...buildOptimisticIOUReportAction({ - type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, - amount: transaction.amount, - currency: transaction.currency, - comment: '', - participants: [], - transactionID: transaction.transactionID, - iouReportID: expenseReport.reportID, - }), - childReportID: transactionThread.reportID, - }; - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`, expenseReport); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${transactionThread.reportID}`, transactionThread); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport.reportID}`, { - [iouAction.reportActionID]: iouAction, - }); - await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, transaction); - const draftTransaction: OnyxEntry = { - ...transaction, - comment: { - originalTransactionID: transaction.transactionID, - }, - }; - - // When splitting the expense - const hash = 1; - - let allTransactions: OnyxCollection; - let allReports: OnyxCollection; - let allReportNameValuePairs: OnyxCollection; - await getOnyxData({ - key: ONYXKEYS.COLLECTION.TRANSACTION, - waitForCollectionCallback: true, - callback: (value) => { - allTransactions = value; - }, - }); - await getOnyxData({ - key: ONYXKEYS.COLLECTION.REPORT, - waitForCollectionCallback: true, - callback: (value) => { - allReports = value; - }, - }); - await getOnyxData({ - key: ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, - waitForCollectionCallback: true, - callback: (value) => { - allReportNameValuePairs = value; - }, - }); - updateSplitTransactionsFromSplitExpensesFlow({ - allTransactionsList: allTransactions, - allReportsList: allReports, - allReportNameValuePairsList: allReportNameValuePairs, - transactionData: { - reportID: draftTransaction?.reportID ?? String(CONST.DEFAULT_NUMBER_ID), - originalTransactionID: draftTransaction?.comment?.originalTransactionID ?? String(CONST.DEFAULT_NUMBER_ID), - splitExpenses: draftTransaction?.comment?.splitExpenses ?? [], - splitExpensesTotal: draftTransaction?.comment?.splitExpensesTotal, - }, - searchContext: { - currentSearchHash: hash, - }, - policyCategories: undefined, - policy: undefined, - policyRecentlyUsedCategories: [], - iouReport: expenseReport, - firstIOU: undefined, - isASAPSubmitBetaEnabled: false, - currentUserPersonalDetails, - transactionViolations: {}, - policyRecentlyUsedCurrencies: [], - quickAction: undefined, - }); - - await waitForBatchedUpdates(); - - // Then the original expense/transaction should be removed from the search snapshot data - const searchSnapshot = await new Promise>((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.SNAPSHOT}${hash}`, - callback: (val) => { - Onyx.disconnect(connection); - resolve(val); - }, - }); - }); - expect(searchSnapshot?.data[`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`]).toBe(undefined); - }); - - it('should add split transactions optimistically on search snapshot when current search filter is on unapprovedCash', async () => { - const chatReport: Report = createRandomReport(7, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT); - // Given a single expense - const expenseReport: Report = { - ...createRandomReport(1, undefined), - type: CONST.REPORT.TYPE.EXPENSE, - chatReportID: chatReport.reportID, - stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, - statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED, - }; - const transaction: Transaction = { - amount: 100, - currency: 'USD', - transactionID: '1', - reportID: expenseReport.reportID, - created: DateUtils.getDBTime(), - merchant: 'test', - }; - const transactionThread: Report = { - ...createRandomReport(2, undefined), - }; - const iouAction: ReportAction = { - ...buildOptimisticIOUReportAction({ - type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, - amount: transaction.amount, - currency: transaction.currency, - comment: '', - participants: [], - transactionID: transaction.transactionID, - iouReportID: expenseReport.reportID, - }), - childReportID: transactionThread.reportID, - }; - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`, chatReport); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`, expenseReport); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${transactionThread.reportID}`, transactionThread); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${expenseReport.reportID}`, { - [iouAction.reportActionID]: iouAction, - }); - await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, transaction); - const splitTransactionID1 = '34'; - const splitTransactionID2 = '35'; - const draftTransaction: OnyxEntry = { - ...transaction, - comment: { - originalTransactionID: transaction.transactionID, - splitExpenses: [ - {amount: transaction.amount / 2, transactionID: splitTransactionID1, created: ''}, - {amount: transaction.amount / 2, transactionID: splitTransactionID2, created: ''}, - ], - }, - }; - - // When splitting the expense - const hash = 1; - - let allTransactions: OnyxCollection; - let allReports: OnyxCollection; - let allReportNameValuePairs: OnyxCollection; - await getOnyxData({ - key: ONYXKEYS.COLLECTION.TRANSACTION, - waitForCollectionCallback: true, - callback: (value) => { - allTransactions = value; - }, - }); - await getOnyxData({ - key: ONYXKEYS.COLLECTION.REPORT, - waitForCollectionCallback: true, - callback: (value) => { - allReports = value; - }, - }); - await getOnyxData({ - key: ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, - waitForCollectionCallback: true, - callback: (value) => { - allReportNameValuePairs = value; - }, - }); - - updateSplitTransactionsFromSplitExpensesFlow({ - allTransactionsList: allTransactions, - allReportsList: allReports, - allReportNameValuePairsList: allReportNameValuePairs, - transactionData: { - reportID: draftTransaction?.reportID ?? String(CONST.DEFAULT_NUMBER_ID), - originalTransactionID: draftTransaction?.comment?.originalTransactionID ?? String(CONST.DEFAULT_NUMBER_ID), - splitExpenses: draftTransaction?.comment?.splitExpenses ?? [], - splitExpensesTotal: draftTransaction?.comment?.splitExpensesTotal, - }, - searchContext: { - currentSearchHash: hash, - }, - policyCategories: undefined, - policy: undefined, - policyRecentlyUsedCategories: [], - iouReport: expenseReport, - firstIOU: undefined, - isASAPSubmitBetaEnabled: false, - currentUserPersonalDetails, - transactionViolations: {}, - policyRecentlyUsedCurrencies: [], - quickAction: undefined, - }); - - await waitForBatchedUpdates(); - - // Then the split expenses/transactions should be added on the search snapshot data - const searchSnapshot = await new Promise>((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.SNAPSHOT}${unapprovedCashHash}`, - callback: (val) => { - Onyx.disconnect(connection); - resolve(val); - }, - }); - }); - expect(searchSnapshot?.data?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${splitTransactionID1}`]).toBeDefined(); - expect(searchSnapshot?.data?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${splitTransactionID2}`]).toBeDefined(); - }); - }); - describe('payMoneyRequestElsewhere', () => { it('clears outstanding IOUReport', () => { const amount = 10000; diff --git a/tests/actions/IOUTest/SplitTest.ts b/tests/actions/IOUTest/SplitTest.ts index 951804863c4f..b66c260080b3 100644 --- a/tests/actions/IOUTest/SplitTest.ts +++ b/tests/actions/IOUTest/SplitTest.ts @@ -3,19 +3,21 @@ import {deepEqual} from 'fast-equals'; import Onyx from 'react-native-onyx'; import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; -import {requestMoney} from '@libs/actions/IOU'; +import {getReportPreviewAction, requestMoney} from '@libs/actions/IOU'; import {putOnHold} from '@libs/actions/IOU/Hold'; import initOnyxDerivedValues from '@libs/actions/OnyxDerived'; import {createWorkspace, generatePolicyID, setWorkspaceApprovalMode} from '@libs/actions/Policy/Policy'; +import {addComment, openReport} from '@libs/actions/Report'; import {rand64} from '@libs/NumberUtils'; -import {getOriginalMessage, isActionOfType, isMoneyRequestAction} from '@libs/ReportActionsUtils'; -import {buildOptimisticIOUReportAction} from '@libs/ReportUtils'; +import {getLoginsByAccountIDs} from '@libs/PersonalDetailsUtils'; +import {getOriginalMessage, getReportAction, isActionOfType, isMoneyRequestAction} from '@libs/ReportActionsUtils'; +import {buildOptimisticIOUReportAction, buildTransactionThread} from '@libs/ReportUtils'; import {completeSplitBill, splitBill, startSplitBill, updateSplitTransactionsFromSplitExpensesFlow} from '@userActions/IOU/Split'; import CONST from '@src/CONST'; import IntlStore from '@src/languages/IntlStore'; import DateUtils from '@src/libs/DateUtils'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {RecentlyUsedTags, Report, ReportNameValuePairs, SearchResults} from '@src/types/onyx'; +import type {RecentlyUsedTags, Report, ReportActions, ReportNameValuePairs, SearchResults} from '@src/types/onyx'; import type {SplitExpense} from '@src/types/onyx/IOU'; import type {CurrentUserPersonalDetails} from '@src/types/onyx/PersonalDetails'; import type {Participant} from '@src/types/onyx/Report'; @@ -25,6 +27,7 @@ import {toCollectionDataSet} from '@src/types/utils/CollectionDataSet'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; import currencyList from '../../unit/currencyList.json'; import createPersonalDetails from '../../utils/collections/personalDetails'; +import createRandomReportAction from '../../utils/collections/reportActions'; import {createRandomReport} from '../../utils/collections/reports'; import getOnyxValue from '../../utils/getOnyxValue'; import type {MockFetch} from '../../utils/TestHelper'; @@ -1342,6 +1345,206 @@ describe('updateSplitTransactionsFromSplitExpensesFlow', () => { expect(originalTransactionThread).toBe(undefined); }); + it('should delete the original transaction thread report regardless of whether there are visible comments, and update the comment count of the preview report', async () => { + const chatReportID = 'report123'; + const reportID = 'report456'; + const transactionID = 'transaction123'; + const previewActionID = 'action123'; + const iouActionID = 'action123'; + + const chatReport: Report = { + ...createRandomReport(0, undefined), + policyID: CONST.POLICY.ID_FAKE, + parentReportID: undefined, + parentReportActionID: undefined, + reportID: chatReportID, + type: 'chat', + }; + let previewAction: OnyxEntry = { + ...createRandomReportAction(0), + actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, + reportActionID: previewActionID, + childMoneyRequestCount: 1, + childVisibleActionCount: 0, + originalMessage: {linkedReportID: reportID}, + }; + const iouReport: Report = { + ...createRandomReport(1, undefined), + type: CONST.REPORT.TYPE.IOU, + chatReportID: chatReport.reportID, + parentReportID: chatReport.reportID, + parentReportActionID: previewAction.reportActionID, + reportID, + }; + const transaction: Transaction = { + amount: 100, + currency: 'USD', + transactionID, + reportID: iouReport.reportID, + created: DateUtils.getDBTime(), + merchant: 'test', + }; + + let iouAction: OnyxEntry = { + ...buildOptimisticIOUReportAction({ + type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, + amount: transaction.amount, + currency: transaction.currency, + comment: '', + participants: [], + transactionID: transaction.transactionID, + iouReportID: iouReport.reportID, + }), + reportActionID: iouActionID, + }; + + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, transaction); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, iouReport); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`, chatReport); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`, []); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReportID}`, { + [previewActionID]: previewAction, + }); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, { + [iouActionID]: iouAction, + }); + await waitForBatchedUpdates(); + + const thread = buildTransactionThread(iouAction, iouReport); + + expect(thread.participants).toEqual({ + [RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}, + }); + + const participantAccountIDs = Object.keys(thread.participants ?? {}).map(Number); + const userLogins = getLoginsByAccountIDs(participantAccountIDs); + jest.advanceTimersByTime(10); + openReport(thread.reportID, '', userLogins, thread, iouAction?.reportActionID); + await waitForBatchedUpdates(); + + let transactionThreadReportActions: OnyxEntry; + Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${thread.reportID}`, + callback: (val) => (transactionThreadReportActions = val), + }); + await waitForBatchedUpdates(); + + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeTruthy(); + resolve(); + }, + }); + }); + + jest.advanceTimersByTime(10); + + // When a comment is added + addComment( + thread, + thread.reportID, + [ + {report: iouReport, reportAction: iouAction, shouldDisplayNewMarker: false}, + {report: chatReport, reportAction: previewAction, shouldDisplayNewMarker: false}, + ], + 'test comment', + CONST.DEFAULT_TIME_ZONE, + ); + await waitForBatchedUpdates(); + + // Then the report should have 2 actions + expect(Object.values(transactionThreadReportActions ?? {}).length).toBe(2); + + iouAction = getReportAction(iouReport.reportID, iouActionID); + previewAction = getReportAction(chatReport.reportID, previewActionID); + expect(iouAction?.childVisibleActionCount).toBe(1); + expect(previewAction?.childVisibleActionCount).toBe(1); + + await waitForBatchedUpdates(); + + const draftTransaction: OnyxEntry = { + ...transaction, + comment: { + originalTransactionID: transaction.transactionID, + }, + }; + + let allTransactions: OnyxCollection; + let allReports: OnyxCollection; + let allReportNameValuePairs: OnyxCollection; + await getOnyxData({ + key: ONYXKEYS.COLLECTION.TRANSACTION, + waitForCollectionCallback: true, + callback: (value) => { + allTransactions = value; + }, + }); + await getOnyxData({ + key: ONYXKEYS.COLLECTION.REPORT, + waitForCollectionCallback: true, + callback: (value) => { + allReports = value; + }, + }); + await getOnyxData({ + key: ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, + waitForCollectionCallback: true, + callback: (value) => { + allReportNameValuePairs = value; + }, + }); + + updateSplitTransactionsFromSplitExpensesFlow({ + allTransactionsList: allTransactions, + allReportsList: allReports, + allReportNameValuePairsList: allReportNameValuePairs, + transactionData: { + reportID: draftTransaction?.reportID ?? String(CONST.DEFAULT_NUMBER_ID), + originalTransactionID: draftTransaction?.comment?.originalTransactionID ?? String(CONST.DEFAULT_NUMBER_ID), + splitExpenses: draftTransaction?.comment?.splitExpenses ?? [], + splitExpensesTotal: draftTransaction?.comment?.splitExpensesTotal, + }, + searchContext: { + currentSearchHash: -2, + }, + policyCategories: undefined, + policy: undefined, + policyRecentlyUsedCategories: [], + iouReport, + firstIOU: iouAction, + isASAPSubmitBetaEnabled: false, + currentUserPersonalDetails, + transactionViolations: {}, + policyRecentlyUsedCurrencies: [], + quickAction: undefined, + iouReportNextStep: undefined, + }); + + await waitForBatchedUpdates(); + + // Then we expect the reportPreview to update with new childVisibleActionCount + previewAction = getReportPreviewAction(chatReport?.reportID, iouReport?.reportID) ?? undefined; + expect(previewAction).toBeTruthy(); + expect(previewAction?.childVisibleActionCount).toEqual(0); + expect(previewAction?.childCommenterCount).toEqual(0); + + // Then the transaction thread report should be deleted + await new Promise((resolve) => { + const connection = Onyx.connect({ + key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, + waitForCollectionCallback: false, + callback: (report) => { + Onyx.disconnect(connection); + expect(report).toBeFalsy(); + resolve(); + }, + }); + }); + }); + it('should remove the original transaction from the search snapshot data', async () => { // Given a single expense const expenseReport: Report = { From c2d4c021ec51e008e56af2832505fd7c18b360e4 Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Sun, 25 Jan 2026 17:21:16 +0700 Subject: [PATCH 15/20] fix ts --- tests/actions/MergeTransactionTest.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/actions/MergeTransactionTest.ts b/tests/actions/MergeTransactionTest.ts index 8631e0b1a809..0240f1fdd484 100644 --- a/tests/actions/MergeTransactionTest.ts +++ b/tests/actions/MergeTransactionTest.ts @@ -661,6 +661,7 @@ describe('mergeTransactionRequest', () => { sourceTransaction, targetTransactionThreadReport: {reportID: 'target-report-456'}, targetTransactionThreadParentReport: undefined, + targetTransactionThreadParentReportNextStep: undefined, allTransactionViolations: createAllTransactionViolations(targetTransaction.transactionID, sourceTransaction.transactionID, targetViolations, sourceViolations), policy: undefined, policyTags: undefined, @@ -793,6 +794,7 @@ describe('mergeTransactionRequest', () => { sourceTransaction, targetTransactionThreadReport: {reportID: 'target-report-456'}, targetTransactionThreadParentReport: undefined, + targetTransactionThreadParentReportNextStep: undefined, allTransactionViolations: createAllTransactionViolations(targetTransaction.transactionID, sourceTransaction.transactionID, targetViolations, sourceViolations), policy: undefined, policyTags: undefined, From 0cb91f7903d485836308ba26f65bbd7d55c91267 Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Wed, 4 Feb 2026 21:32:47 +0700 Subject: [PATCH 16/20] fix ts --- tests/actions/IOUTest.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/actions/IOUTest.ts b/tests/actions/IOUTest.ts index 79879d30a44f..a920ac70f7c8 100644 --- a/tests/actions/IOUTest.ts +++ b/tests/actions/IOUTest.ts @@ -7626,6 +7626,7 @@ describe('actions/IOU', () => { currentUserEmailParam: 'existing@example.com', policyRecentlyUsedCurrencies: [], quickAction: undefined, + isSelfTourViewed: false, }); } @@ -7724,6 +7725,7 @@ describe('actions/IOU', () => { iouReport, chatReport, allTransactionViolationsParam: {}, + currentUserAccountID: TEST_USER_ACCOUNT_ID, }); } @@ -7793,6 +7795,7 @@ describe('actions/IOU', () => { }; await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${selfDMReport.reportID}`, selfDMReport); + const recentWaypoints = (await getOnyxValue(ONYXKEYS.NVP_RECENT_WAYPOINTS)) ?? []; // Create a tracked expense trackExpense({ @@ -7817,6 +7820,7 @@ describe('actions/IOU', () => { introSelected: undefined, activePolicyID: undefined, quickAction: undefined, + recentWaypoints }); await waitForBatchedUpdates(); From 241205a8f6a857dc4b4a31069ff99f5db57accf1 Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Wed, 4 Feb 2026 21:35:19 +0700 Subject: [PATCH 17/20] fix prettier --- tests/actions/IOUTest.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/actions/IOUTest.ts b/tests/actions/IOUTest.ts index a920ac70f7c8..58a698c04bf7 100644 --- a/tests/actions/IOUTest.ts +++ b/tests/actions/IOUTest.ts @@ -7820,7 +7820,7 @@ describe('actions/IOU', () => { introSelected: undefined, activePolicyID: undefined, quickAction: undefined, - recentWaypoints + recentWaypoints, }); await waitForBatchedUpdates(); From d57f4fb7f7f19505dd8d0402ae7fcce4c661d41e Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Wed, 4 Feb 2026 22:10:48 +0700 Subject: [PATCH 18/20] fix ts --- tests/actions/IOUTest.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/actions/IOUTest.ts b/tests/actions/IOUTest.ts index e89b665ea693..65af223ae0e9 100644 --- a/tests/actions/IOUTest.ts +++ b/tests/actions/IOUTest.ts @@ -7820,6 +7820,7 @@ describe('actions/IOU', () => { policyRecentlyUsedCurrencies: [], quickAction: undefined, isSelfTourViewed: false, + personalDetails: {}, }); } From 679aefc5eefddf4acd76347e77606fff43924c32 Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Wed, 4 Feb 2026 22:17:46 +0700 Subject: [PATCH 19/20] Remove the changes to split transactions --- src/libs/actions/IOU/Split.ts | 18 +-- tests/actions/IOUTest/SplitTest.ts | 211 +---------------------------- 2 files changed, 14 insertions(+), 215 deletions(-) diff --git a/src/libs/actions/IOU/Split.ts b/src/libs/actions/IOU/Split.ts index aecf0851f3c4..0b2c9b255aad 100644 --- a/src/libs/actions/IOU/Split.ts +++ b/src/libs/actions/IOU/Split.ts @@ -61,7 +61,6 @@ import { getAllPersonalDetails, getAllReports, getAllTransactions, - getCleanUpTransactionThreadReportOnyxData, getDeleteTrackExpenseInformation, getMoneyRequestInformation, getMoneyRequestParticipantsFromReport, @@ -1343,18 +1342,17 @@ function updateSplitTransactions({ errors: null, }, }; - const cleanUpTransactionThreadReportOnyxData = getCleanUpTransactionThreadReportOnyxData({ - transactionThreadID: firstIOU.childReportID, - shouldDeleteTransactionThread: !!firstIOU.childReportID, - reportAction: firstIOU, + const transactionThread = getAllReports()?.[`${ONYXKEYS.COLLECTION.REPORT}${firstIOU.childReportID}`] ?? null; + optimisticData.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT}${firstIOU?.childReportID}`, + value: null, }); optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport?.reportID}`, value: updatedReportAction, }); - optimisticData.push(...cleanUpTransactionThreadReportOnyxData.optimisticData); - successData.push(...cleanUpTransactionThreadReportOnyxData.successData); failureData.push({ onyxMethod: Onyx.METHOD.MERGE, @@ -1366,7 +1364,11 @@ function updateSplitTransactions({ }, }, }); - failureData.push(...cleanUpTransactionThreadReportOnyxData.failureData); + failureData.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT}${firstIOU?.childReportID}`, + value: transactionThread ?? null, + }); } optimisticData.push({ diff --git a/tests/actions/IOUTest/SplitTest.ts b/tests/actions/IOUTest/SplitTest.ts index 87f8d449eb45..494b60e90418 100644 --- a/tests/actions/IOUTest/SplitTest.ts +++ b/tests/actions/IOUTest/SplitTest.ts @@ -3,21 +3,19 @@ import {deepEqual} from 'fast-equals'; import Onyx from 'react-native-onyx'; import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; -import {getReportPreviewAction, requestMoney} from '@libs/actions/IOU'; +import {requestMoney} from '@libs/actions/IOU'; import {putOnHold} from '@libs/actions/IOU/Hold'; import initOnyxDerivedValues from '@libs/actions/OnyxDerived'; import {createWorkspace, generatePolicyID, setWorkspaceApprovalMode} from '@libs/actions/Policy/Policy'; -import {addComment, openReport} from '@libs/actions/Report'; import {rand64} from '@libs/NumberUtils'; -import {getLoginsByAccountIDs} from '@libs/PersonalDetailsUtils'; -import {getOriginalMessage, getReportAction, isActionOfType, isMoneyRequestAction} from '@libs/ReportActionsUtils'; -import {buildOptimisticIOUReportAction, buildTransactionThread} from '@libs/ReportUtils'; +import {getOriginalMessage, isActionOfType, isMoneyRequestAction} from '@libs/ReportActionsUtils'; +import {buildOptimisticIOUReportAction} from '@libs/ReportUtils'; import {completeSplitBill, splitBill, startSplitBill, updateSplitTransactionsFromSplitExpensesFlow} from '@userActions/IOU/Split'; import CONST from '@src/CONST'; import IntlStore from '@src/languages/IntlStore'; import DateUtils from '@src/libs/DateUtils'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {RecentlyUsedTags, Report, ReportActions, ReportNameValuePairs, SearchResults} from '@src/types/onyx'; +import type {RecentlyUsedTags, Report, ReportNameValuePairs, SearchResults} from '@src/types/onyx'; import type {SplitExpense} from '@src/types/onyx/IOU'; import type {CurrentUserPersonalDetails} from '@src/types/onyx/PersonalDetails'; import type {Participant} from '@src/types/onyx/Report'; @@ -27,7 +25,6 @@ import {toCollectionDataSet} from '@src/types/utils/CollectionDataSet'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; import currencyList from '../../unit/currencyList.json'; import createPersonalDetails from '../../utils/collections/personalDetails'; -import createRandomReportAction from '../../utils/collections/reportActions'; import {createRandomReport} from '../../utils/collections/reports'; import getOnyxValue from '../../utils/getOnyxValue'; import type {MockFetch} from '../../utils/TestHelper'; @@ -1346,206 +1343,6 @@ describe('updateSplitTransactionsFromSplitExpensesFlow', () => { expect(originalTransactionThread).toBe(undefined); }); - it('should delete the original transaction thread report regardless of whether there are visible comments, and update the comment count of the preview report', async () => { - const chatReportID = 'report123'; - const reportID = 'report456'; - const transactionID = 'transaction123'; - const previewActionID = 'action123'; - const iouActionID = 'action123'; - - const chatReport: Report = { - ...createRandomReport(0, undefined), - policyID: CONST.POLICY.ID_FAKE, - parentReportID: undefined, - parentReportActionID: undefined, - reportID: chatReportID, - type: 'chat', - }; - let previewAction: OnyxEntry = { - ...createRandomReportAction(0), - actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, - reportActionID: previewActionID, - childMoneyRequestCount: 1, - childVisibleActionCount: 0, - originalMessage: {linkedReportID: reportID}, - }; - const iouReport: Report = { - ...createRandomReport(1, undefined), - type: CONST.REPORT.TYPE.IOU, - chatReportID: chatReport.reportID, - parentReportID: chatReport.reportID, - parentReportActionID: previewAction.reportActionID, - reportID, - }; - const transaction: Transaction = { - amount: 100, - currency: 'USD', - transactionID, - reportID: iouReport.reportID, - created: DateUtils.getDBTime(), - merchant: 'test', - }; - - let iouAction: OnyxEntry = { - ...buildOptimisticIOUReportAction({ - type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, - amount: transaction.amount, - currency: transaction.currency, - comment: '', - participants: [], - transactionID: transaction.transactionID, - iouReportID: iouReport.reportID, - }), - reportActionID: iouActionID, - }; - - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, transaction); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, iouReport); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`, chatReport); - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`, []); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReportID}`, { - [previewActionID]: previewAction, - }); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, { - [iouActionID]: iouAction, - }); - await waitForBatchedUpdates(); - - const thread = buildTransactionThread(iouAction, iouReport); - - expect(thread.participants).toEqual({ - [RORY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN, role: CONST.REPORT.ROLE.ADMIN}, - }); - - const participantAccountIDs = Object.keys(thread.participants ?? {}).map(Number); - const userLogins = getLoginsByAccountIDs(participantAccountIDs); - jest.advanceTimersByTime(10); - openReport(thread.reportID, '', userLogins, thread, iouAction?.reportActionID); - await waitForBatchedUpdates(); - - let transactionThreadReportActions: OnyxEntry; - Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${thread.reportID}`, - callback: (val) => (transactionThreadReportActions = val), - }); - await waitForBatchedUpdates(); - - await new Promise((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, - callback: (report) => { - Onyx.disconnect(connection); - expect(report).toBeTruthy(); - resolve(); - }, - }); - }); - - jest.advanceTimersByTime(10); - - // When a comment is added - addComment( - thread, - thread.reportID, - [ - {report: iouReport, reportAction: iouAction, shouldDisplayNewMarker: false}, - {report: chatReport, reportAction: previewAction, shouldDisplayNewMarker: false}, - ], - 'test comment', - CONST.DEFAULT_TIME_ZONE, - ); - await waitForBatchedUpdates(); - - // Then the report should have 2 actions - expect(Object.values(transactionThreadReportActions ?? {}).length).toBe(2); - - iouAction = getReportAction(iouReport.reportID, iouActionID); - previewAction = getReportAction(chatReport.reportID, previewActionID); - expect(iouAction?.childVisibleActionCount).toBe(1); - expect(previewAction?.childVisibleActionCount).toBe(1); - - await waitForBatchedUpdates(); - - const draftTransaction: OnyxEntry = { - ...transaction, - comment: { - originalTransactionID: transaction.transactionID, - }, - }; - - let allTransactions: OnyxCollection; - let allReports: OnyxCollection; - let allReportNameValuePairs: OnyxCollection; - await getOnyxData({ - key: ONYXKEYS.COLLECTION.TRANSACTION, - waitForCollectionCallback: true, - callback: (value) => { - allTransactions = value; - }, - }); - await getOnyxData({ - key: ONYXKEYS.COLLECTION.REPORT, - waitForCollectionCallback: true, - callback: (value) => { - allReports = value; - }, - }); - await getOnyxData({ - key: ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, - waitForCollectionCallback: true, - callback: (value) => { - allReportNameValuePairs = value; - }, - }); - - updateSplitTransactionsFromSplitExpensesFlow({ - allTransactionsList: allTransactions, - allReportsList: allReports, - allReportNameValuePairsList: allReportNameValuePairs, - transactionData: { - reportID: draftTransaction?.reportID ?? String(CONST.DEFAULT_NUMBER_ID), - originalTransactionID: draftTransaction?.comment?.originalTransactionID ?? String(CONST.DEFAULT_NUMBER_ID), - splitExpenses: draftTransaction?.comment?.splitExpenses ?? [], - splitExpensesTotal: draftTransaction?.comment?.splitExpensesTotal, - }, - searchContext: { - currentSearchHash: -2, - }, - policyCategories: undefined, - policy: undefined, - policyRecentlyUsedCategories: [], - iouReport, - firstIOU: iouAction, - isASAPSubmitBetaEnabled: false, - currentUserPersonalDetails, - transactionViolations: {}, - policyRecentlyUsedCurrencies: [], - quickAction: undefined, - iouReportNextStep: undefined, - }); - - await waitForBatchedUpdates(); - - // Then we expect the reportPreview to update with new childVisibleActionCount - previewAction = getReportPreviewAction(chatReport?.reportID, iouReport?.reportID) ?? undefined; - expect(previewAction).toBeTruthy(); - expect(previewAction?.childVisibleActionCount).toEqual(0); - expect(previewAction?.childCommenterCount).toEqual(0); - - // Then the transaction thread report should be deleted - await new Promise((resolve) => { - const connection = Onyx.connect({ - key: `${ONYXKEYS.COLLECTION.REPORT}${thread.reportID}`, - waitForCollectionCallback: false, - callback: (report) => { - Onyx.disconnect(connection); - expect(report).toBeFalsy(); - resolve(); - }, - }); - }); - }); - it('should remove the original transaction from the search snapshot data', async () => { // Given a single expense const expenseReport: Report = { From f22676bfbc115db673ee5b40474f5445a2caa50d Mon Sep 17 00:00:00 2001 From: dmkt9 Date: Thu, 5 Feb 2026 16:17:50 +0700 Subject: [PATCH 20/20] fix test --- tests/actions/IOUTest.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/actions/IOUTest.ts b/tests/actions/IOUTest.ts index 079aed3ffd52..29d303b8cdf4 100644 --- a/tests/actions/IOUTest.ts +++ b/tests/actions/IOUTest.ts @@ -8056,6 +8056,7 @@ describe('actions/IOU', () => { policyRecentlyUsedCurrencies: [], quickAction: undefined, isSelfTourViewed: false, + betas: [CONST.BETAS.ALL], personalDetails: {}, }); } @@ -8251,6 +8252,7 @@ describe('actions/IOU', () => { activePolicyID: undefined, quickAction: undefined, recentWaypoints, + betas: [CONST.BETAS.ALL], }); await waitForBatchedUpdates();