diff --git a/config/eslint/eslint.seatbelt.tsv b/config/eslint/eslint.seatbelt.tsv index deccb27ae793..d70df2e323c9 100644 --- a/config/eslint/eslint.seatbelt.tsv +++ b/config/eslint/eslint.seatbelt.tsv @@ -1857,7 +1857,7 @@ "../../tests/actions/ReportPreviewActionUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 29 "../../tests/actions/ReportPreviewActionUtilsTest.ts" "no-restricted-imports" 2 "../../tests/actions/ReportTest.ts" "@typescript-eslint/no-deprecated/buildNextStepNew" 1 -"../../tests/actions/ReportTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 58 +"../../tests/actions/ReportTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 50 "../../tests/actions/ReportTest.ts" "no-restricted-imports" 1 "../../tests/actions/SessionTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 12 "../../tests/actions/SubscriptionTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 2 diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 7d37ca62ac30..6af28c7ac397 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -6592,6 +6592,7 @@ const CONST = { SUBMIT: 'submit', HOLD: 'hold', MERGE: 'merge', + MERGE_REPORTS: 'mergeReports', UNHOLD: 'unhold', DELETE: 'delete', REJECT: 'reject', diff --git a/src/libs/API/parameters/MergeReportsParams.ts b/src/libs/API/parameters/MergeReportsParams.ts new file mode 100644 index 000000000000..46359b5397ff --- /dev/null +++ b/src/libs/API/parameters/MergeReportsParams.ts @@ -0,0 +1,7 @@ +type MergeReportsParams = { + destinationReportID: string; + sourceReportIDs: string[]; + transactionIDToReportActionAndThreadData: string; // A map of transactionID to TransactionThreadInfo +}; + +export default MergeReportsParams; diff --git a/src/libs/API/parameters/index.ts b/src/libs/API/parameters/index.ts index c7d8933002e4..1880fdf8d747 100644 --- a/src/libs/API/parameters/index.ts +++ b/src/libs/API/parameters/index.ts @@ -495,6 +495,7 @@ export type {SaveCorpayOnboardingCompanyDetailsParams} from './SaveCorpayOnboard export type {default as AcceptSpotnanaTermsParams} from './AcceptSpotnanaTermsParams'; export type {default as SaveCorpayOnboardingBeneficialOwnerParams} from './SaveCorpayOnboardingBeneficialOwnerParams'; export type {default as DeleteAppReportParams} from './DeleteAppReportParams'; +export type {default as MergeReportsParams} from './MergeReportsParams'; export type {default as SaveCorpayOnboardingDirectorInformationParams} from './SaveCorpayOnboardingDirectorInformationParams'; export type {default as AskForCorpaySignerInformationParams} from './AskForCorpaySignerInformationParams'; export type {default as MoveIOUReportToPolicyAndInviteSubmitterParams} from './MoveIOUReportToPolicyAndInviteSubmitterParams'; diff --git a/src/libs/API/types.ts b/src/libs/API/types.ts index a8844655049c..0b094f6a4762 100644 --- a/src/libs/API/types.ts +++ b/src/libs/API/types.ts @@ -602,6 +602,7 @@ const WRITE_COMMANDS = { SAVE_CORPAY_ONBOARDING_COMPANY_DETAILS: 'SaveCorpayOnboardingCompanyDetails', SAVE_CORPAY_ONBOARDING_BENEFICIAL_OWNER: 'SaveCorpayOnboardingBeneficialOwner', DELETE_APP_REPORT: 'DeleteAppReport', + MERGE_REPORTS: 'MergeReports', SAVE_CORPAY_ONBOARDING_DIRECTOR_INFORMATION: 'SaveCorpayOnboardingDirectorInformation', ASK_FOR_CORPAY_SIGNER_INFORMATION: 'AskForCorpaySignerInformation', SEND_REMINDER_FOR_CORPAY_SINGER_INFORMATION: 'SendReminderForCorpaySignerInformation', @@ -1276,6 +1277,7 @@ type WriteCommandParameters = { // Dismiss Product Training [WRITE_COMMANDS.DISMISS_PRODUCT_TRAINING]: Parameters.DismissProductTrainingParams; [WRITE_COMMANDS.DELETE_APP_REPORT]: Parameters.DeleteAppReportParams; + [WRITE_COMMANDS.MERGE_REPORTS]: Parameters.MergeReportsParams; // Merge accounts API [WRITE_COMMANDS.GET_VALIDATE_CODE_FOR_ACCOUNT_MERGE]: Parameters.GetValidateCodeForAccountMergeParams; diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 06dc39974fb2..0f0acdc5a931 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -3052,7 +3052,7 @@ function canSubmitAndIsAwaitingForCurrentUser( function hasOutstandingChildRequest( chatReport: Report, - iouReportOrID: OnyxEntry | string, + iouReportOrIDorArray: OnyxEntry | string | Array>, currentUserEmailParam: string, currentUserAccountIDParam: number, allTransactionViolations: OnyxCollection, @@ -3061,18 +3061,29 @@ function hasOutstandingChildRequest( const reportActions = getAllReportActions(chatReport.reportID); // This will be fixed as part of https://github.com/Expensify/Expensify/issues/507850 const policy = getPolicy(chatReport.policyID); + + const excludedReportIDSet = new Set(); + if (typeof iouReportOrIDorArray === 'string') { + excludedReportIDSet.add(iouReportOrIDorArray); + } else if (Array.isArray(iouReportOrIDorArray)) { + for (const iouReport of iouReportOrIDorArray) { + if (!iouReport?.reportID) { + continue; + } + excludedReportIDSet.add(iouReport.reportID); + } + } + return Object.values(reportActions).some((action) => { const iouReportID = getIOUReportIDFromReportActionPreview(action); - if ( - !iouReportID || - action.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || - isDeletedAction(action) || - (typeof iouReportOrID === 'string' && iouReportID === iouReportOrID) - ) { + if (!iouReportID || action.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || isDeletedAction(action) || excludedReportIDSet.has(iouReportID)) { return false; } - const iouReport = typeof iouReportOrID !== 'string' && iouReportOrID?.reportID === iouReportID ? iouReportOrID : getReportOrDraftReport(iouReportID); + const iouReport = + typeof iouReportOrIDorArray !== 'string' && !Array.isArray(iouReportOrIDorArray) && iouReportOrIDorArray?.reportID === iouReportID + ? iouReportOrIDorArray + : getReportOrDraftReport(iouReportID); const transactions = getReportTransactions(iouReportID); const reportMetadata = allReportMetadata?.[`${ONYXKEYS.COLLECTION.REPORT_METADATA}${iouReportID}`]; const invoiceReceiverPolicyID = chatReport?.invoiceReceiver && 'policyID' in chatReport.invoiceReceiver ? chatReport.invoiceReceiver.policyID : undefined; diff --git a/src/libs/actions/Report/index.ts b/src/libs/actions/Report/index.ts index 4d41032a1c90..f59581f64bd3 100644 --- a/src/libs/actions/Report/index.ts +++ b/src/libs/actions/Report/index.ts @@ -22,6 +22,7 @@ import type { LeaveRoomParams, MarkAsExportedParams, MarkAsUnreadParams, + MergeReportsParams, MoveIOUReportToExistingPolicyParams, MoveIOUReportToPolicyAndInviteSubmitterParams, OpenReportParams, @@ -189,6 +190,7 @@ import { resolveOpenReportDuplicationConflictAction, } from '@userActions/RequestConflictUtils'; import {isAnonymousUser} from '@userActions/Session'; +import {getChangeTransactionsReportOnyxData} from '@userActions/Transaction'; import {onServerDataReady} from '@userActions/Welcome'; import {getOnboardingMessages} from '@userActions/Welcome/OnboardingFlow'; import type {OnboardingCompanySize, OnboardingMessage} from '@userActions/Welcome/OnboardingFlow'; @@ -214,9 +216,11 @@ import type { Pages, PersonalDetailsList, Policy, + PolicyCategories, PolicyEmployee, PolicyEmployeeList, PolicyReportField, + PolicyTagLists, RecentlyUsedReportFields, Report, ReportAction, @@ -225,6 +229,7 @@ import type { ReportUserIsTyping, SidePanelContext, Transaction, + TransactionViolation, TransactionViolations, VisibleReportActionsDerivedValue, } from '@src/types/onyx'; @@ -420,6 +425,25 @@ type AddAttachmentWithCommentParams = { conciergeReportID: string | undefined; }; +type MergeReportsProps = { + destinationReportID: string; + sourceReportIDs: string[]; + isASAPSubmitBetaEnabled: boolean; + accountID: number; + email: string; + policy: OnyxEntry; + reportNextStep?: OnyxEntry; + policyCategories?: OnyxEntry; + policyTagList: OnyxEntry; + allTransactionViolation?: OnyxCollection; + allReports: OnyxCollection; + allReportsTransactions?: Record; + hash?: number; + bankAccountList: OnyxEntry; + isTrackIntentUser: boolean | undefined; + personalPolicyOutputCurrency: string | undefined; +}; + const addNewMessageWithText = new Set([WRITE_COMMANDS.ADD_COMMENT, WRITE_COMMANDS.ADD_TEXT_AND_ATTACHMENT]); // map of reportID to all reportActions for that report const allReportActions: OnyxCollection = {}; @@ -6280,6 +6304,112 @@ type DeleteAppReportProps = { hash?: number; }; +function buildOptimisticDeleteParentReportAction( + parentReportID: string | undefined, + parentReportActionID: string, + parentReportAction?: OnyxEntry, + shouldDeleteParentReportAction = false, +) { + // Mirror the per-transaction delete path: mark the preview's message as deleted so `isDeletedAction` treats it as + // removed. `pendingAction` alone isn't inspected by `isDeletedAction`, so without this the chat keeps surfacing a + // stale "Mark as done"/action badge in the LHN while the report is queued for deletion offline. The message can be + // either the legacy array shape or the newer object shape, so handle both to match how `isDeletedAction` reads them. + const parentPreviewMessage = parentReportAction?.message; + let deletedPreviewMessage; + if (Array.isArray(parentPreviewMessage)) { + deletedPreviewMessage = cloneDeep(parentPreviewMessage); + const firstPreviewMessage = deletedPreviewMessage.at(0); + if (firstPreviewMessage) { + firstPreviewMessage.deleted = DateUtils.getDBTime(); + } + } else if (parentPreviewMessage) { + deletedPreviewMessage = cloneDeep(parentPreviewMessage); + deletedPreviewMessage.deleted = DateUtils.getDBTime(); + } + + const optimisticData: Array> = [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${parentReportID}`, + value: { + [parentReportActionID]: { + pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + ...(deletedPreviewMessage ? {message: deletedPreviewMessage} : {}), + }, + }, + }, + ]; + + const successData: Array> = [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${parentReportID}`, + value: { + [parentReportActionID]: shouldDeleteParentReportAction + ? null + : { + pendingAction: null, + errors: null, + }, + }, + }, + ]; + + const failureData: Array> = [ + { + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${parentReportID}`, + value: { + [parentReportActionID]: { + ...parentReportAction, + errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericDeleteFailureMessage'), + }, + }, + }, + ]; + + return {optimisticData, successData, failureData}; +} + +function clearChatIOUReportID( + reports: Array>, + currentUserEmailParam: string, + currentUserAccountIDParam: number, + allTransactionViolations: OnyxCollection, + bankAccountList: OnyxEntry, +) { + const optimisticData: Array> = []; + const failureData: Array> = []; + + // Multiple reports are currently only used by `mergeReports`. + // `mergeReports` currently only supports merging reports with the same policy and the same `ownerAccountID`, + // so they will always belong to the same parentReportID. + const chatReport = getReportOrDraftReport(reports.find((report) => !!report?.parentReportID)?.parentReportID); + // Only clear the pointer when the chat still references the report being deleted, so we don't nullify a different active expense report. + const shouldClearChatIOUReportID = reports.some((report) => chatReport?.iouReportID === report?.reportID); + if (chatReport) { + optimisticData.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`, + value: { + hasOutstandingChildRequest: hasOutstandingChildRequest(chatReport, reports, currentUserEmailParam, currentUserAccountIDParam, allTransactionViolations, bankAccountList), + ...(shouldClearChatIOUReportID ? {iouReportID: null} : {}), + }, + }); + + failureData.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT}${chatReport.reportID}`, + value: { + hasOutstandingChildRequest: chatReport.hasOutstandingChildRequest, + ...(shouldClearChatIOUReportID ? {iouReportID: chatReport.iouReportID} : {}), + }, + }); + } + + return {optimisticData, failureData}; +} + /** Deletes a report and un-reports all transactions on the report along with its reportActions, any linked reports and any linked IOU report actions. */ function deleteAppReport({ report, @@ -6613,86 +6743,25 @@ function deleteAppReport({ const parentReportID = report?.parentReportID; if (reportActionID) { - // Mirror the per-transaction delete path: mark the preview's message as deleted so `isDeletedAction` treats it as - // removed. `pendingAction` alone isn't inspected by `isDeletedAction`, so without this the chat keeps surfacing a - // stale "Mark as done"/action badge in the LHN while the report is queued for deletion offline. The message can be - // either the legacy array shape or the newer object shape, so handle both to match how `isDeletedAction` reads them. - const parentPreviewMessage = parentReportAction?.message; - let deletedPreviewMessage; - if (Array.isArray(parentPreviewMessage)) { - deletedPreviewMessage = cloneDeep(parentPreviewMessage); - const firstPreviewMessage = deletedPreviewMessage.at(0); - if (firstPreviewMessage) { - firstPreviewMessage.deleted = DateUtils.getDBTime(); - } - } else if (parentPreviewMessage) { - deletedPreviewMessage = cloneDeep(parentPreviewMessage); - deletedPreviewMessage.deleted = DateUtils.getDBTime(); - } - - optimisticData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${parentReportID}`, - value: { - [reportActionID]: { - pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, - ...(deletedPreviewMessage ? {message: deletedPreviewMessage} : {}), - }, - }, - }); - - successData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${parentReportID}`, - value: { - [reportActionID]: { - pendingAction: null, - errors: null, - }, - }, - }); - - failureData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${parentReportID}`, - value: { - [reportActionID]: { - ...parentReportAction, - errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericDeleteFailureMessage'), - }, - }, - }); - } - - const chatReport = getReportOrDraftReport(report?.parentReportID); - // Only clear the pointer when the chat still references the report being deleted, so we don't nullify a different active expense report. - const shouldClearChatIOUReportID = chatReport?.iouReportID === reportID; - if (chatReport) { - optimisticData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${report?.parentReportID}`, - value: { - hasOutstandingChildRequest: hasOutstandingChildRequest( - chatReport, - report?.reportID, - currentUserEmailParam, - currentUserAccountIDParam, - allTransactionViolations, - bankAccountList, - ), - ...(shouldClearChatIOUReportID ? {iouReportID: null} : {}), - }, - }); - } - - failureData.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT}${report?.parentReportID}`, - value: { - hasOutstandingChildRequest: report?.hasOutstandingChildRequest, - ...(shouldClearChatIOUReportID ? {iouReportID: chatReport?.iouReportID} : {}), - }, - }); + const { + optimisticData: parentOptimisticData, + successData: parentSuccessData, + failureData: parentFailureData, + } = buildOptimisticDeleteParentReportAction(parentReportID, reportActionID, parentReportAction); + optimisticData.push(...parentOptimisticData); + successData.push(...parentSuccessData); + failureData.push(...parentFailureData); + } + + const {optimisticData: clearChatIOUOptimisticData, failureData: clearChatIOUFailureData} = clearChatIOUReportID( + [report], + currentUserEmailParam, + currentUserAccountIDParam, + allTransactionViolations, + bankAccountList, + ); + optimisticData.push(...clearChatIOUOptimisticData); + failureData.push(...clearChatIOUFailureData); if (hash) { // Initializing as an empty typed object to allow dynamic key assignment resolves TypeScript type inference issue @@ -8012,6 +8081,203 @@ function setViewingPublicRoomReportID(reportID: string) { Onyx.set(ONYXKEYS.VIEWING_PUBLIC_ROOM_REPORT_ID, reportID); } +function mergeReports({ + destinationReportID, + sourceReportIDs, + hash, + isASAPSubmitBetaEnabled, + accountID, + email, + policy, + reportNextStep, + policyCategories, + policyTagList, + allTransactionViolation, + allReportsTransactions, + bankAccountList, + allReports: allReportsParam, + isTrackIntentUser, + personalPolicyOutputCurrency, +}: MergeReportsProps) { + const reports = allReportsParam ?? allReports; + const destinationReport = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${destinationReportID}`]; + + const transactionsToMove: Transaction[] = []; + const transactionIDsToMove: string[] = []; + for (const sourceReportID of sourceReportIDs) { + const transactions = getReportTransactions(sourceReportID, allReportsTransactions); + transactionsToMove.push(...transactions); + transactionIDsToMove.push(...transactions.map((t) => t.transactionID)); + } + + const changeTransactionsReportOnyxData = getChangeTransactionsReportOnyxData({ + transactionIDs: transactionIDsToMove, + isASAPSubmitBetaEnabled, + accountID, + email, + newReport: destinationReport, + policy, + reportNextStep, + policyCategories, + policyTagList: policyTagList ?? {}, + transactions: transactionsToMove, + allTransactionViolation, + allReports: reports, + skippedReportIDs: sourceReportIDs, + isTrackIntentUser, + personalPolicyOutputCurrency, + }); + + const { + optimisticData: moveOptimisticData = [], + successData: moveSuccessData = [], + failureData: moveFailureData = [], + transactionIDToReportActionAndThreadData = {}, + updatedReportTotals, + updatedReportTransactionCounts, + updatedReportNonReimbursableTotals, + updatedReportUnheldNonReimbursableTotals, + updatedReportReimbursableTotals, + updatedReportUnheldReimbursableTotals, + } = changeTransactionsReportOnyxData ?? {}; + + const deleteOptimisticData: Array> = []; + const deleteSuccessData: Array> = []; + const deleteFailureData: Array> = []; + + const allSourceReport: Report[] = []; + for (const sourceReportID of sourceReportIDs) { + const sourceReport = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${sourceReportID}`]; + if (!sourceReport) { + continue; + } + allSourceReport.push(sourceReport); + + // Mark source report as deleted + deleteOptimisticData.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT}${sourceReportID}`, + value: { + pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + pendingFields: { + preview: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + }, + }, + }); + + deleteSuccessData.push({ + onyxMethod: Onyx.METHOD.SET, + key: `${ONYXKEYS.COLLECTION.REPORT}${sourceReportID}`, + value: null, + }); + + deleteFailureData.push({ + onyxMethod: Onyx.METHOD.SET, + key: `${ONYXKEYS.COLLECTION.REPORT}${sourceReportID}`, + value: sourceReport, + }); + + // Mark comments on the source report as deleted + const reportActions = allReportActions?.[sourceReportID]; + deleteOptimisticData.push({ + onyxMethod: Onyx.METHOD.SET, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${sourceReportID}`, + value: null, + }); + + deleteFailureData.push({ + onyxMethod: Onyx.METHOD.SET, + key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${sourceReportID}`, + value: reportActions ?? null, + }); + + // Mark parent report preview action as deleted (if exists) + const parentReportID = sourceReport.parentReportID; + const parentReportActionID = sourceReport.parentReportActionID; + if (parentReportID && parentReportActionID) { + const parentReportAction = allReportActions?.[parentReportID]?.[parentReportActionID]; + const { + optimisticData: parentOptimisticData, + successData: parentSuccessData, + failureData: parentFailureData, + } = buildOptimisticDeleteParentReportAction(parentReportID, parentReportActionID, parentReportAction, true); + deleteOptimisticData.push(...parentOptimisticData); + deleteSuccessData.push(...parentSuccessData); + deleteFailureData.push(...parentFailureData); + } + } + + const {optimisticData: clearChatIOUOptimisticData, failureData: clearChatIOUFailureData} = clearChatIOUReportID( + allSourceReport, + email, + accountID, + allTransactionViolation, + bankAccountList, + ); + deleteOptimisticData.push(...clearChatIOUOptimisticData); + deleteFailureData.push(...clearChatIOUFailureData); + + const optimisticData = [...moveOptimisticData, ...deleteOptimisticData]; + const successData = [...moveSuccessData, ...deleteSuccessData]; + const failureData = [...moveFailureData, ...deleteFailureData]; + + if (hash) { + const optimisticSnapshotData: SearchResultDataType = {}; + const failureSnapshotData: SearchResultDataType = {}; + for (const sourceReportID of sourceReportIDs) { + const sourceReport = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${sourceReportID}`]; + if (sourceReport) { + optimisticSnapshotData[`${ONYXKEYS.COLLECTION.REPORT}${sourceReportID}`] = { + ...sourceReport, + pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + }; + + failureSnapshotData[`${ONYXKEYS.COLLECTION.REPORT}${sourceReportID}`] = {...sourceReport, pendingAction: sourceReport.pendingAction ?? null}; + } + } + if (destinationReport) { + optimisticSnapshotData[`${ONYXKEYS.COLLECTION.REPORT}${destinationReportID}`] = { + ...destinationReport, + total: updatedReportTotals?.[destinationReportID] ?? destinationReport.total, + transactionCount: updatedReportTransactionCounts?.[destinationReportID] ?? destinationReport.transactionCount, + reimbursableTotal: updatedReportReimbursableTotals?.[destinationReportID] ?? destinationReport.reimbursableTotal, + unheldReimbursableTotal: updatedReportUnheldReimbursableTotals?.[destinationReportID] ?? destinationReport.unheldReimbursableTotal, + nonReimbursableTotal: updatedReportNonReimbursableTotals?.[destinationReportID] ?? destinationReport.nonReimbursableTotal, + unheldNonReimbursableTotal: updatedReportUnheldNonReimbursableTotals?.[destinationReportID] ?? destinationReport.unheldNonReimbursableTotal, + }; + + failureSnapshotData[`${ONYXKEYS.COLLECTION.REPORT}${destinationReportID}`] = {...destinationReport}; + } + + optimisticData.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.SNAPSHOT}${hash}`, + value: { + data: optimisticSnapshotData, + }, + }); + failureData.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.SNAPSHOT}${hash}`, + value: { + data: failureSnapshotData, + }, + }); + } + + const parameters: MergeReportsParams = { + destinationReportID, + sourceReportIDs, + transactionIDToReportActionAndThreadData: JSON.stringify(transactionIDToReportActionAndThreadData), + }; + + API.write(WRITE_COMMANDS.MERGE_REPORTS, parameters, { + optimisticData, + successData, + failureData, + }); +} + export type {Video, GuidedSetupData, TaskForParameters, IntroSelected, OpenReportActionParams}; export { @@ -8118,6 +8384,7 @@ export { updateRoomVisibility, updateWriteCapability, deleteAppReport, + mergeReports, getOptimisticChatReport, saveReportDraft, moveIOUReportToPolicy, diff --git a/src/libs/actions/Transaction.ts b/src/libs/actions/Transaction.ts index 39d9f173b32a..6643ec81652e 100644 --- a/src/libs/actions/Transaction.ts +++ b/src/libs/actions/Transaction.ts @@ -844,11 +844,13 @@ type ChangeTransactionsReportProps = { transactions: Transaction[]; allTransactionViolation?: OnyxCollection; allReports: OnyxCollection; + /** Report IDs that should be skipped when generating Onyx updates (e.g. because they are being deleted) */ + skippedReportIDs?: string[]; isTrackIntentUser: boolean | undefined; personalPolicyOutputCurrency: string | undefined; }; -function changeTransactionsReport({ +function getChangeTransactionsReportOnyxData({ transactionIDs, isASAPSubmitBetaEnabled, accountID, @@ -861,6 +863,7 @@ function changeTransactionsReport({ transactions, allTransactionViolation = {}, allReports: allReportsParam, + skippedReportIDs, isTrackIntentUser, personalPolicyOutputCurrency, }: ChangeTransactionsReportProps) { @@ -916,6 +919,8 @@ function changeTransactionsReport({ > > = []; + const skippedReportIDsSet = new Set(skippedReportIDs ?? []); + const existingSelfDMReportID = findSelfDMReportID(); let selfDMReport: Report | undefined; let selfDMCreatedReportAction: ReportAction | undefined; @@ -1444,7 +1449,7 @@ function changeTransactionsReport({ }, }); - if (oldIOUAction) { + if (oldIOUAction && !skippedReportIDsSet.has(isUnreportedExpense ? (selfDMReportID ?? CONST.REPORT.UNREPORTED_REPORT_ID) : oldReportID)) { optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${isUnreportedExpense ? selfDMReportID : oldReportID}`, @@ -1484,7 +1489,7 @@ function changeTransactionsReport({ [newIOUAction.reportActionID]: null, }, }); - if (oldIOUAction) { + if (oldIOUAction && !skippedReportIDsSet.has(isUnreportedExpense ? (selfDMReportID ?? CONST.REPORT.UNREPORTED_REPORT_ID) : oldReportID)) { failureData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${isUnreportedExpense ? selfDMReportID : oldReportID}`, @@ -1669,6 +1674,9 @@ function changeTransactionsReport({ // 8. Update the report totals for (const [reportIDToUpdate, total] of Object.entries(updatedReportTotals)) { + if (skippedReportIDsSet.has(reportIDToUpdate)) { + continue; + } optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT}${reportIDToUpdate}`, @@ -1682,6 +1690,9 @@ function changeTransactionsReport({ }); } for (const [reportIDToUpdate, transactionCount] of Object.entries(updatedReportTransactionCounts)) { + if (skippedReportIDsSet.has(reportIDToUpdate)) { + continue; + } optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT}${reportIDToUpdate}`, @@ -1695,6 +1706,9 @@ function changeTransactionsReport({ } for (const [reportIDToUpdate, total] of Object.entries(updatedReportNonReimbursableTotals)) { + if (skippedReportIDsSet.has(reportIDToUpdate)) { + continue; + } optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT}${reportIDToUpdate}`, @@ -1709,6 +1723,9 @@ function changeTransactionsReport({ } for (const [reportIDToUpdate, total] of Object.entries(updatedReportUnheldNonReimbursableTotals)) { + if (skippedReportIDsSet.has(reportIDToUpdate)) { + continue; + } optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT}${reportIDToUpdate}`, @@ -1725,6 +1742,9 @@ function changeTransactionsReport({ } for (const reportIDToUpdate of Object.keys(updatedReportStateNums)) { + if (skippedReportIDsSet.has(reportIDToUpdate)) { + continue; + } optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT}${reportIDToUpdate}`, @@ -1745,6 +1765,9 @@ function changeTransactionsReport({ } for (const [reportIDToUpdate, total] of Object.entries(updatedReportReimbursableTotals)) { + if (skippedReportIDsSet.has(reportIDToUpdate)) { + continue; + } optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT}${reportIDToUpdate}`, @@ -1759,6 +1782,9 @@ function changeTransactionsReport({ } for (const [reportIDToUpdate, total] of Object.entries(updatedReportUnheldReimbursableTotals)) { + if (skippedReportIDsSet.has(reportIDToUpdate)) { + continue; + } optimisticData.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT}${reportIDToUpdate}`, @@ -1812,6 +1838,9 @@ function changeTransactionsReport({ } for (const affectedReportID of affectedReportIDs) { + if (skippedReportIDsSet.has(affectedReportID)) { + continue; + } const affectedReport = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${affectedReportID}`] ?? (affectedReportID === newReport?.reportID ? newReport : undefined) ?? @@ -1914,8 +1943,32 @@ function changeTransactionsReport({ }); } + return { + optimisticData, + successData, + failureData, + transactionIDToReportActionAndThreadData, + transactionIDToUpdatedCustomUnitRateID, + updatedReportTotals, + updatedReportTransactionCounts, + updatedReportNonReimbursableTotals, + updatedReportUnheldNonReimbursableTotals, + updatedReportReimbursableTotals, + updatedReportUnheldReimbursableTotals, + }; +} + +function changeTransactionsReport(props: ChangeTransactionsReportProps) { + const changeTransactionsReportOnyxData = getChangeTransactionsReportOnyxData(props); + if (!changeTransactionsReportOnyxData) { + return; + } + const {optimisticData, successData, failureData, transactionIDToReportActionAndThreadData, transactionIDToUpdatedCustomUnitRateID} = changeTransactionsReportOnyxData; + + const reportID = props.newReport?.reportID ?? CONST.REPORT.UNREPORTED_REPORT_ID; + const parameters: ChangeTransactionsReportParams = { - transactionList: transactionIDs.join(','), + transactionList: props.transactionIDs.join(','), reportID, transactionIDToReportActionAndThreadData: JSON.stringify(transactionIDToReportActionAndThreadData), ...(Object.keys(transactionIDToUpdatedCustomUnitRateID).length > 0 && { @@ -1968,6 +2021,7 @@ export { getLastModifiedExpense, revert, changeTransactionsReport, + getChangeTransactionsReportOnyxData, setTransactionReport, getDefaultP2PMileageRate, mergeTransactionIdsHighlightOnSearchRoute, diff --git a/tests/actions/ReportTest.ts b/tests/actions/ReportTest.ts index b8bdf6016a06..792f287b55d0 100644 --- a/tests/actions/ReportTest.ts +++ b/tests/actions/ReportTest.ts @@ -198,6 +198,8 @@ const TEST_INTRO_SELECTED: OnyxTypes.IntroSelected = { isInviteOnboardingComplete: false, }; +const getMockFetch = (fetch: typeof global.fetch) => fetch as MockFetch; + type APIWriteSpy = jest.SpiedFunction; describe('actions/Report', () => { @@ -2658,7 +2660,7 @@ describe('actions/Report', () => { it('should create new report and "create report" quick action, when createNewReport gets called', async () => { const accountID = 1234; const policyID = '5678'; - const mockFetchData = fetch as MockFetch; + const mockFetchData = getMockFetch(fetch); // Given a policy with harvesting is disabled const policy = { ...createRandomPolicy(Number(policyID)), @@ -2734,7 +2736,7 @@ describe('actions/Report', () => { it('should set hasOnceLoadedReportActions for parent report metadata when creating a new report', async () => { const accountID = 1234; const policyID = '5678'; - const mockFetchData = fetch as MockFetch; + const mockFetchData = getMockFetch(fetch); const policy = { ...createRandomPolicy(Number(policyID)), isPolicyExpenseChatEnabled: true, @@ -3132,7 +3134,7 @@ describe('actions/Report', () => { ...createRandomReport(1, undefined), description: '

test

', }; - const mockFetch = fetch as MockFetch; + const mockFetch = getMockFetch(fetch); await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${report.reportID}`, report); @@ -3837,7 +3839,7 @@ describe('actions/Report', () => { const ownerAccountID = 999; const ownerEmail = 'submitter@test.com'; const adminEmail = 'admin@test.com'; - const mockFetch = TestHelper.getGlobalFetchMock() as MockFetch; + const mockFetch = getMockFetch(TestHelper.getGlobalFetchMock()); const expenseReport: OnyxTypes.Report = { ...createRandomReport(1, undefined), @@ -4120,7 +4122,7 @@ describe('actions/Report', () => { await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${targetPolicy.id}`, targetPolicy); await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, {[ownerAccountID]: {login: ownerEmail, accountID: ownerAccountID}}); - const mockFetch = TestHelper.getGlobalFetchMock() as MockFetch; + const mockFetch = getMockFetch(TestHelper.getGlobalFetchMock()); global.fetch = mockFetch; mockFetch.pause?.(); @@ -4386,7 +4388,7 @@ describe('actions/Report', () => { it('correctly implements RedBrickRoad error handling for MoveIOUReportToPolicyAndInviteSubmitter when the request fails to add a new user to workspace', async () => { const ownerAccountID = 999; const ownerEmail = 'submitter@test.com'; - const mockFetch = TestHelper.getGlobalFetchMock() as MockFetch; + const mockFetch = getMockFetch(TestHelper.getGlobalFetchMock()); const iouReport: OnyxTypes.Report = { ...createRandomReport(1, undefined), @@ -7976,7 +7978,7 @@ describe('actions/Report', () => { Report.navigateToAndOpenReportWithAccountIDs([PARTICIPANT_ACCOUNT_ID], TEST_USER_ACCOUNT_ID, testIntroSelected, false, undefined, {}, true); await waitForBatchedUpdates(); - const openReportCalls = (global.fetch as MockFetch).mock.calls.filter((c) => c[0] === `https://www.expensify.com.dev/api/${WRITE_COMMANDS.OPEN_REPORT}?`); + const openReportCalls = getMockFetch(global.fetch).mock.calls.filter((c) => c[0] === `https://www.expensify.com.dev/api/${WRITE_COMMANDS.OPEN_REPORT}?`); expect(openReportCalls.length).toBeGreaterThanOrEqual(1); const openReportParamsList = openReportCalls.map((call) => { const body = (call.at(1) as RequestInit)?.body; @@ -7997,7 +7999,7 @@ describe('actions/Report', () => { await waitForBatchedUpdates(); TestHelper.expectAPICommandToHaveBeenCalled(WRITE_COMMANDS.ADD_COMMENT, 1); - const addCommentCalls = (global.fetch as MockFetch).mock.calls.filter((c) => c[0] === `https://www.expensify.com.dev/api/${WRITE_COMMANDS.ADD_COMMENT}?`); + const addCommentCalls = getMockFetch(global.fetch).mock.calls.filter((c) => c[0] === `https://www.expensify.com.dev/api/${WRITE_COMMANDS.ADD_COMMENT}?`); const addCommentBody = (addCommentCalls.at(-1)?.at(1) as RequestInit)?.body; const addCommentParams = addCommentBody instanceof FormData ? Object.fromEntries(addCommentBody) : {}; expect(addCommentParams.reportID).toBe(MOCK_FALLBACK_DM_REPORT_ID); @@ -8714,7 +8716,7 @@ describe('actions/Report', () => { }); it('should remove optimistically added participants on failure rollback', async () => { - const mockFetch = TestHelper.getGlobalFetchMock() as MockFetch; + const mockFetch = getMockFetch(TestHelper.getGlobalFetchMock()); global.fetch = mockFetch; const REPORT_ID = '3'; @@ -9108,6 +9110,318 @@ describe('actions/Report', () => { }); }); + describe('mergeReports', () => { + const currentUserAccountID = 1; + const currentUserEmail = 'test@example.com'; + + const POLICY_ID = 'policy_123'; + const WORKSPACE_CHAT_REPORT_ID = 'workspace_chat_456'; + const DESTINATION_REPORT_ID = 'destination_report_789'; + const SOURCE_REPORT_1_ID = 'source_report_101'; + const SOURCE_REPORT_2_ID = 'source_report_102'; + const REPORT_PREVIEW_ACTION_1_ID = 'preview_action_201'; + const REPORT_PREVIEW_ACTION_2_ID = 'preview_action_202'; + const TRANSACTION_1_ID = 'transaction_301'; + const TRANSACTION_2_ID = 'transaction_302'; + const SNAPSHOT_HASH = 999; + + const policy = createMock({ + ...createRandomPolicy(1), + id: POLICY_ID, + ownerAccountID: currentUserAccountID, + owner: currentUserEmail, + role: CONST.POLICY.ROLE.ADMIN, + type: CONST.POLICY.TYPE.TEAM, + }); + + const workspaceChatReport = createMock({ + ...createRandomReport(0, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT), + reportID: WORKSPACE_CHAT_REPORT_ID, + policyID: POLICY_ID, + type: CONST.REPORT.TYPE.CHAT, + chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, + }); + + const destinationReport = createMock({ + ...createRandomReport(0, undefined), + reportID: DESTINATION_REPORT_ID, + policyID: POLICY_ID, + type: CONST.REPORT.TYPE.EXPENSE, + managerID: currentUserAccountID, + ownerAccountID: currentUserAccountID, + stateNum: CONST.REPORT.STATE_NUM.OPEN, + statusNum: CONST.REPORT.STATUS_NUM.OPEN, + currency: CONST.CURRENCY.USD, + total: 0, + transactionCount: 0, + }); + + const sourceReport1 = createMock({ + ...createRandomReport(0, undefined), + reportID: SOURCE_REPORT_1_ID, + policyID: POLICY_ID, + type: CONST.REPORT.TYPE.EXPENSE, + managerID: currentUserAccountID, + ownerAccountID: currentUserAccountID, + stateNum: CONST.REPORT.STATE_NUM.OPEN, + statusNum: CONST.REPORT.STATUS_NUM.OPEN, + currency: CONST.CURRENCY.USD, + parentReportID: WORKSPACE_CHAT_REPORT_ID, + parentReportActionID: REPORT_PREVIEW_ACTION_1_ID, + total: -1000, + transactionCount: 1, + }); + + const sourceReport2 = createMock({ + ...createRandomReport(0, undefined), + reportID: SOURCE_REPORT_2_ID, + policyID: POLICY_ID, + type: CONST.REPORT.TYPE.EXPENSE, + managerID: currentUserAccountID, + ownerAccountID: currentUserAccountID, + stateNum: CONST.REPORT.STATE_NUM.OPEN, + statusNum: CONST.REPORT.STATUS_NUM.OPEN, + currency: CONST.CURRENCY.USD, + parentReportID: WORKSPACE_CHAT_REPORT_ID, + parentReportActionID: REPORT_PREVIEW_ACTION_2_ID, + total: -2000, + transactionCount: 1, + }); + + const reportPreviewAction1 = createMock({ + ...createRandomReportAction(0), + reportActionID: REPORT_PREVIEW_ACTION_1_ID, + actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, + message: [{type: 'COMMENT', html: 'Report preview', text: 'Report preview'}], + originalMessage: { + linkedReportID: SOURCE_REPORT_1_ID, + }, + }); + + const reportPreviewAction2 = createMock({ + ...createRandomReportAction(0), + reportActionID: REPORT_PREVIEW_ACTION_2_ID, + actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, + message: [{type: 'COMMENT', html: 'Report preview', text: 'Report preview'}], + originalMessage: { + linkedReportID: SOURCE_REPORT_2_ID, + }, + }); + + const transaction1 = createMock({ + ...createRandomTransaction(0), + transactionID: TRANSACTION_1_ID, + reportID: SOURCE_REPORT_1_ID, + amount: -1000, + currency: CONST.CURRENCY.USD, + }); + + const transaction2 = createMock({ + ...createRandomTransaction(0), + transactionID: TRANSACTION_2_ID, + reportID: SOURCE_REPORT_2_ID, + amount: -2000, + currency: CONST.CURRENCY.USD, + }); + + let mockFetch: MockFetch; + beforeEach(async () => { + await Onyx.merge(ONYXKEYS.SESSION, { + accountID: currentUserAccountID, + email: currentUserEmail, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`, policy); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${WORKSPACE_CHAT_REPORT_ID}`, workspaceChatReport); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${DESTINATION_REPORT_ID}`, destinationReport); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_1_ID}`, sourceReport1); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_2_ID}`, sourceReport2); + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_1_ID}`, transaction1); + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_2_ID}`, transaction2); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${WORKSPACE_CHAT_REPORT_ID}`, { + [REPORT_PREVIEW_ACTION_1_ID]: reportPreviewAction1, + [REPORT_PREVIEW_ACTION_2_ID]: reportPreviewAction2, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${SOURCE_REPORT_1_ID}`, { + someAction: createRandomReportAction(203), + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${SOURCE_REPORT_2_ID}`, { + someAction: createRandomReportAction(204), + }); + await waitForBatchedUpdates(); + + global.fetch = TestHelper.getGlobalFetchMock(); + mockFetch = getMockFetch(global.fetch); + // Clear the queue before each test to avoid test pollution + SequentialQueue.resetQueue(); + }); + + afterEach(() => { + jest.clearAllMocks(); + PusherHelper.teardown(); + }); + + it('handles success case: moves transactions, deletes source reports, and updates parent preview actions in Onyx', async () => { + mockFetch.pause(); + + Report.mergeReports({ + destinationReportID: DESTINATION_REPORT_ID, + sourceReportIDs: [SOURCE_REPORT_1_ID, SOURCE_REPORT_2_ID], + isASAPSubmitBetaEnabled: false, + accountID: currentUserAccountID, + email: currentUserEmail, + policy, + policyTagList: {}, + allReports: { + [`${ONYXKEYS.COLLECTION.REPORT}${DESTINATION_REPORT_ID}`]: destinationReport, + [`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_1_ID}`]: sourceReport1, + [`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_2_ID}`]: sourceReport2, + }, + bankAccountList: undefined, + isTrackIntentUser: false, + personalPolicyOutputCurrency: undefined, + }); + await waitForBatchedUpdates(); + + // Verify optimistic state in Onyx + // Transactions moved to destination report + const tx1 = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_1_ID}`); + expect(tx1?.reportID).toBe(DESTINATION_REPORT_ID); + const tx2 = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_2_ID}`); + expect(tx2?.reportID).toBe(DESTINATION_REPORT_ID); + const destReport = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${DESTINATION_REPORT_ID}`); + expect(destReport?.total).toBe(-3000); + expect(destReport?.transactionCount).toBe(2); + + // Source reports marked as deleted + const rep1 = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_1_ID}`); + expect(rep1?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE); + const rep2 = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_2_ID}`); + expect(rep2?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE); + + // Source report actions cleared optimistically + const actions1 = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${SOURCE_REPORT_1_ID}`); + expect(actions1).toBeFalsy(); + const actions2 = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${SOURCE_REPORT_2_ID}`); + expect(actions2).toBeFalsy(); + + // Parent report preview actions marked as deleted + const parentActions = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${WORKSPACE_CHAT_REPORT_ID}`); + expect(parentActions?.[REPORT_PREVIEW_ACTION_1_ID]?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE); + expect(parentActions?.[REPORT_PREVIEW_ACTION_2_ID]?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE); + + await mockFetch.resume(); + await waitForBatchedUpdates(); + + // Verify success state in Onyx + // Source reports deleted (null) + const rep1AfterSuccess = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_1_ID}`); + expect(rep1AfterSuccess).toBeFalsy(); + + const rep2AfterSuccess = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_2_ID}`); + expect(rep2AfterSuccess).toBeFalsy(); + + // Parent preview actions cleared + const parentActionsAfterSuccess = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${WORKSPACE_CHAT_REPORT_ID}`); + expect(parentActionsAfterSuccess?.[REPORT_PREVIEW_ACTION_1_ID]).toBeFalsy(); + expect(parentActionsAfterSuccess?.[REPORT_PREVIEW_ACTION_2_ID]).toBeFalsy(); + }); + + it('handles failure case: rolls back transaction moves, restores source reports, and restores parent preview actions in Onyx', async () => { + mockFetch.pause(); + + Report.mergeReports({ + destinationReportID: DESTINATION_REPORT_ID, + sourceReportIDs: [SOURCE_REPORT_1_ID, SOURCE_REPORT_2_ID], + isASAPSubmitBetaEnabled: false, + accountID: currentUserAccountID, + email: currentUserEmail, + policy, + policyTagList: {}, + allReports: { + [`${ONYXKEYS.COLLECTION.REPORT}${DESTINATION_REPORT_ID}`]: destinationReport, + [`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_1_ID}`]: sourceReport1, + [`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_2_ID}`]: sourceReport2, + }, + bankAccountList: undefined, + isTrackIntentUser: false, + personalPolicyOutputCurrency: undefined, + }); + await waitForBatchedUpdates(); + + mockFetch.fail(); + await mockFetch.resume(); + await waitForBatchedUpdates(); + + // Verify failure state in Onyx + // Transactions rolled back to source reports + const tx1 = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_1_ID}`); + expect(tx1?.reportID).toBe(SOURCE_REPORT_1_ID); + + const tx2 = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_2_ID}`); + expect(tx2?.reportID).toBe(SOURCE_REPORT_2_ID); + + // Source reports restored + const rep1 = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_1_ID}`); + expect(rep1?.reportID).toBe(SOURCE_REPORT_1_ID); + expect(rep1?.pendingAction).toBeUndefined(); + + const rep2 = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_2_ID}`); + expect(rep2?.reportID).toBe(SOURCE_REPORT_2_ID); + expect(rep2?.pendingAction).toBeUndefined(); + + // Parent preview actions restored with errors and keep pendingAction as DELETE + const parentActions = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${WORKSPACE_CHAT_REPORT_ID}`); + expect(parentActions?.[REPORT_PREVIEW_ACTION_1_ID]?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE); + expect(parentActions?.[REPORT_PREVIEW_ACTION_1_ID]?.errors).toBeDefined(); + expect(parentActions?.[REPORT_PREVIEW_ACTION_2_ID]?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE); + expect(parentActions?.[REPORT_PREVIEW_ACTION_2_ID]?.errors).toBeDefined(); + + const destReport = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${DESTINATION_REPORT_ID}`); + expect(destReport?.total).toBe(0); + expect(destReport?.transactionCount).toBe(0); + }); + + it('correctly handles snapshot updates when hash is provided', async () => { + mockFetch.pause(); + + Report.mergeReports({ + destinationReportID: DESTINATION_REPORT_ID, + sourceReportIDs: [SOURCE_REPORT_1_ID, SOURCE_REPORT_2_ID], + isASAPSubmitBetaEnabled: false, + accountID: currentUserAccountID, + email: currentUserEmail, + policy, + policyTagList: {}, + allReports: { + [`${ONYXKEYS.COLLECTION.REPORT}${DESTINATION_REPORT_ID}`]: destinationReport, + [`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_1_ID}`]: sourceReport1, + [`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_2_ID}`]: sourceReport2, + }, + hash: SNAPSHOT_HASH, + bankAccountList: undefined, + isTrackIntentUser: false, + personalPolicyOutputCurrency: undefined, + }); + await waitForBatchedUpdates(); + + // Check snapshot update in optimisticData via Onyx + const snapshotOptimistic = await getOnyxValue(`${ONYXKEYS.COLLECTION.SNAPSHOT}${SNAPSHOT_HASH}`); + expect(snapshotOptimistic?.data?.[`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_1_ID}`]?.pendingAction).toBe(CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE); + expect(snapshotOptimistic?.data?.[`${ONYXKEYS.COLLECTION.REPORT}${DESTINATION_REPORT_ID}`]?.total).toBe(-3000); + expect(snapshotOptimistic?.data?.[`${ONYXKEYS.COLLECTION.REPORT}${DESTINATION_REPORT_ID}`]?.transactionCount).toBe(2); + + mockFetch.fail(); + await mockFetch.resume(); + await waitForBatchedUpdates(); + + // Check snapshot update in failureData via Onyx + const snapshotFailure = await getOnyxValue(`${ONYXKEYS.COLLECTION.SNAPSHOT}${SNAPSHOT_HASH}`); + expect(snapshotFailure?.data?.[`${ONYXKEYS.COLLECTION.REPORT}${SOURCE_REPORT_1_ID}`]?.reportID).toBe(SOURCE_REPORT_1_ID); + expect(snapshotFailure?.data?.[`${ONYXKEYS.COLLECTION.REPORT}${DESTINATION_REPORT_ID}`]?.total).toBe(0); + expect(snapshotFailure?.data?.[`${ONYXKEYS.COLLECTION.REPORT}${DESTINATION_REPORT_ID}`]?.transactionCount).toBe(0); + }); + }); + describe('prepareOnyxDataForCleanUpOptimisticParticipants', () => { const REPORT_ID = '1'; const OPTIMISTIC_ACCOUNT_ID = 100;