diff --git a/src/libs/actions/ClearReportActionErrors.ts b/src/libs/actions/ClearReportActionErrors.ts index fa6d53930616..dbe7df2e86dc 100644 --- a/src/libs/actions/ClearReportActionErrors.ts +++ b/src/libs/actions/ClearReportActionErrors.ts @@ -8,7 +8,7 @@ import ONYXKEYS from '@src/ONYXKEYS'; import type * as OnyxTypes from '@src/types/onyx'; import type ReportAction from '@src/types/onyx/ReportAction'; import type {SearchResultDataType} from '@src/types/onyx/SearchResults'; -import {deleteReport} from './Report'; +import deleteReport from './Report/DeleteReport'; type IgnoreDirection = 'parent' | 'child'; diff --git a/src/libs/actions/Report/DeleteReport.ts b/src/libs/actions/Report/DeleteReport.ts new file mode 100644 index 000000000000..22b334189607 --- /dev/null +++ b/src/libs/actions/Report/DeleteReport.ts @@ -0,0 +1,66 @@ +import Onyx from 'react-native-onyx'; +import type {OnyxCollection} from 'react-native-onyx'; +import Log from '@libs/Log'; +import {getOriginalMessage, isMoneyRequestAction} from '@libs/ReportActionsUtils'; +import type CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {Report, ReportAction, ReportActions} from '@src/types/onyx'; + +// We use connectWithoutView because deleteReport doesn't affect the UI rendering +// and this avoids unnecessary re-rendering because we recursively delete the report and its children +// which requires us to subscribe to the whole report and report actions collection. +let allReports: OnyxCollection; +Onyx.connectWithoutView({ + key: ONYXKEYS.COLLECTION.REPORT, + waitForCollectionCallback: true, + callback: (value) => (allReports = value), +}); + +let allReportActions: OnyxCollection; +Onyx.connectWithoutView({ + key: ONYXKEYS.COLLECTION.REPORT_ACTIONS, + waitForCollectionCallback: true, + callback: (value) => (allReportActions = value), +}); + +/** Deletes a report, along with its reportActions, any linked reports, and any linked IOU report. */ +function deleteReport(reportID: string | undefined, shouldDeleteChildReports = false) { + if (!reportID) { + Log.warn('[Report] deleteReport called with no reportID'); + return; + } + const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]; + const onyxData: Record = { + [`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]: null, + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`]: null, + }; + + // Delete linked transactions + const reportActionsForReport = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`]; + + const transactionIDs = Object.values(reportActionsForReport ?? {}) + .filter((reportAction): reportAction is ReportAction => isMoneyRequestAction(reportAction)) + .map((reportAction) => getOriginalMessage(reportAction)?.IOUTransactionID); + + for (const transactionID of [...new Set(transactionIDs)]) { + onyxData[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`] = null; + } + + Onyx.multiSet(onyxData); + + if (shouldDeleteChildReports) { + for (const reportAction of Object.values(reportActionsForReport ?? {})) { + if (!reportAction.childReportID) { + continue; + } + deleteReport(reportAction.childReportID, shouldDeleteChildReports); + } + } + + // Delete linked IOU report + if (report?.iouReportID) { + deleteReport(report.iouReportID, shouldDeleteChildReports); + } +} + +export default deleteReport; diff --git a/src/libs/actions/Report/index.ts b/src/libs/actions/Report/index.ts index c5bfa6d6c1e6..c8d51a595aaa 100644 --- a/src/libs/actions/Report/index.ts +++ b/src/libs/actions/Report/index.ts @@ -236,6 +236,7 @@ import type {SearchResultDataType} from '@src/types/onyx/SearchResults'; import type {FileObject} from '@src/types/utils/Attachment'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; import type {Dimensions} from '@src/types/utils/Layout'; +import deleteReport from './DeleteReport'; type SubscriberCallback = (isFromCurrentUser: boolean, reportAction: ReportAction | undefined) => void; @@ -4360,46 +4361,6 @@ function addPolicyReport(policyReport: OptimisticChatReport) { API.write(WRITE_COMMANDS.ADD_WORKSPACE_ROOM, parameters, {optimisticData, successData, failureData}); } -/** Deletes a report, along with its reportActions, any linked reports, and any linked IOU report. */ -function deleteReport(reportID: string | undefined, shouldDeleteChildReports = false) { - if (!reportID) { - Log.warn('[Report] deleteReport called with no reportID'); - return; - } - const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]; - const onyxData: Record = { - [`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]: null, - [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`]: null, - }; - - // Delete linked transactions - const reportActionsForReport = allReportActions?.[reportID]; - - const transactionIDs = Object.values(reportActionsForReport ?? {}) - .filter((reportAction): reportAction is ReportAction => ReportActionsUtils.isMoneyRequestAction(reportAction)) - .map((reportAction) => ReportActionsUtils.getOriginalMessage(reportAction)?.IOUTransactionID); - - for (const transactionID of [...new Set(transactionIDs)]) { - onyxData[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`] = null; - } - - Onyx.multiSet(onyxData); - - if (shouldDeleteChildReports) { - for (const reportAction of Object.values(reportActionsForReport ?? {})) { - if (!reportAction.childReportID) { - continue; - } - deleteReport(reportAction.childReportID, shouldDeleteChildReports); - } - } - - // Delete linked IOU report - if (report?.iouReportID) { - deleteReport(report.iouReportID, shouldDeleteChildReports); - } -} - /** * @param reportID The reportID of the policy report (workspace room) */ @@ -7836,7 +7797,6 @@ export { completeOnboarding, extractRHPVariantFromResponse, createNewReport, - deleteReport, clearAllReportActionDrafts, deleteReportComment, deleteReportField, diff --git a/tests/actions/IOU/RequestMoneyTest.ts b/tests/actions/IOU/RequestMoneyTest.ts index 2daf540888e6..5669507fd325 100644 --- a/tests/actions/IOU/RequestMoneyTest.ts +++ b/tests/actions/IOU/RequestMoneyTest.ts @@ -6,7 +6,8 @@ import type {SearchQueryJSON, SearchStatus} from '@components/Search/types'; import {clearAllRelatedReportActionErrors} from '@libs/actions/ClearReportActionErrors'; import {requestMoney, trackExpense} from '@libs/actions/IOU/TrackExpense'; import initOnyxDerivedValues from '@libs/actions/OnyxDerived'; -import {deleteReport, notifyNewAction} from '@libs/actions/Report'; +import {notifyNewAction} from '@libs/actions/Report'; +import deleteReport from '@libs/actions/Report/DeleteReport'; import {subscribeToUserEvents} from '@libs/actions/User'; import type {ApiCommand} from '@libs/API/types'; import {WRITE_COMMANDS} from '@libs/API/types'; diff --git a/tests/unit/DeleteReportTest.ts b/tests/unit/DeleteReportTest.ts new file mode 100644 index 000000000000..adeeb4b275c8 --- /dev/null +++ b/tests/unit/DeleteReportTest.ts @@ -0,0 +1,114 @@ +import Onyx from 'react-native-onyx'; +import deleteReport from '@libs/actions/Report/DeleteReport'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {ReportAction} from '@src/types/onyx'; +import createRandomReportAction from '../utils/collections/reportActions'; +import {createRandomReport} from '../utils/collections/reports'; +import createRandomTransaction from '../utils/collections/transaction'; +import getOnyxValue from '../utils/getOnyxValue'; +import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; + +// Mock Log to avoid noise in tests +jest.mock('@libs/Log'); + +describe('actions/Report/DeleteReport', () => { + beforeAll(() => { + Onyx.init({ + keys: ONYXKEYS, + }); + }); + + beforeEach(() => { + return Onyx.clear(); + }); + + it('should delete a report, its actions, and linked transactions', async () => { + // Given a report with an IOU action and a linked transaction + const reportID = '1'; + const transactionID = '123'; + const report = createRandomReport(1, undefined); + const transaction = createRandomTransaction(Number(transactionID)); + const reportAction: ReportAction = { + ...createRandomReportAction(100), + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + previousMessage: [], + message: [{text: '', html: 'iou', type: 'COMMENT'}], + originalMessage: { + type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, + IOUTransactionID: transaction.transactionID, + IOUDetails: { + amount: transaction.amount, + currency: transaction.currency, + comment: '', + }, + }, + }; + + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, report); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, { + [reportAction.reportActionID]: reportAction, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, transaction); + + // When we delete the report + deleteReport(reportID); + + await waitForBatchedUpdates(); + + // Then the report, its actions, and the linked transaction should be deleted + expect(await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`)).toBeUndefined(); + expect(await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`)).toBeUndefined(); + expect(await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`)).toBeUndefined(); + }); + + it('should delete child reports recursively when shouldDeleteChildReports is true', async () => { + // Given a parent report with a child report + const parentReportID = '1'; + const childReportID = '2'; + const parentReport = createRandomReport(Number(parentReportID), undefined); + const childReport = createRandomReport(Number(childReportID), undefined); + const parentAction = { + ...createRandomReportAction(100), + childReportID, + }; + + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${parentReportID}`, parentReport); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${childReportID}`, childReport); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${parentReportID}`, { + [parentAction.reportActionID]: parentAction, + }); + + // When we delete the parent report with shouldDeleteChildReports set to true + deleteReport(parentReportID, true); + + await waitForBatchedUpdates(); + + // Then both the parent and child reports should be deleted + expect(await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${parentReportID}`)).toBeUndefined(); + expect(await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${childReportID}`)).toBeUndefined(); + }); + + it('should delete linked IOU reports recursively', async () => { + // Given a report with a linked IOU report + const reportID = '1'; + const iouReportID = '2'; + const report = { + ...createRandomReport(Number(reportID), undefined), + iouReportID, + }; + const iouReport = createRandomReport(Number(iouReportID), undefined); + + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, report); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`, iouReport); + + // When we delete the report + deleteReport(reportID); + + await waitForBatchedUpdates(); + + // Then both reports should be deleted + expect(await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`)).toBeUndefined(); + expect(await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`)).toBeUndefined(); + }); +});