|
| 1 | +import {DeviceEventEmitter, InteractionManager} from 'react-native'; |
| 2 | +import type {OnyxCollection} from 'react-native-onyx'; |
| 3 | +import Onyx from 'react-native-onyx'; |
| 4 | +import Navigation, {navigationRef} from '@libs/Navigation/Navigation'; |
| 5 | +import {isMoneyRequest, isMoneyRequestReport} from '@libs/ReportUtils'; |
| 6 | +import ONYXKEYS from '@src/ONYXKEYS'; |
| 7 | +import type {Route} from '@src/ROUTES'; |
| 8 | +import SCREENS from '@src/SCREENS'; |
| 9 | +import type {Report, ReportActions} from '@src/types/onyx'; |
| 10 | +import {saveReportDraftComment} from './Report'; |
| 11 | + |
| 12 | +/** |
| 13 | + * replaceOptimisticReportWithActualReport |
| 14 | + * |
| 15 | + * This module handles a specific edge case in the Expensify app's offline-first architecture. |
| 16 | + * |
| 17 | + * THE PROBLEM: |
| 18 | + * When a user creates a new DM or group chat, we optimistically create a report with a temporary |
| 19 | + * reportID so they can start using it immediately (offline-first UX). However, when the API request |
| 20 | + * completes, the server might respond that a report already exists for that set of participants |
| 21 | + * (e.g., if the user previously had a DM with that person). In this case, the API returns a |
| 22 | + * `preexistingReportID` indicating which report should be used instead of the optimistic one. |
| 23 | + * |
| 24 | + * THE SOLUTION: |
| 25 | + * This module listens to the REPORT collection in Onyx. When a report comes in with a |
| 26 | + * `preexistingReportID` field set, it means we need to: |
| 27 | + * 1. Delete the optimistically created report (the one with the temporary ID) |
| 28 | + * 2. Redirect the user to the preexisting report (if they're currently viewing the optimistic one) |
| 29 | + * 3. Transfer any draft comment from the optimistic report to the preexisting report |
| 30 | + * 4. Clean up associated data like parent report actions for money request reports |
| 31 | + * |
| 32 | + */ |
| 33 | + |
| 34 | +let allReportDraftComments: Record<string, string | undefined> = {}; |
| 35 | +// Draft comments are cached only for transferring to the preexisting report; no UI subscribes, so connectWithoutView() is used. |
| 36 | +Onyx.connectWithoutView({ |
| 37 | + key: ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT, |
| 38 | + waitForCollectionCallback: true, |
| 39 | + callback: (value) => (allReportDraftComments = value ?? {}), |
| 40 | +}); |
| 41 | + |
| 42 | +let allReports: OnyxCollection<Report>; |
| 43 | + |
| 44 | +const allReportActions: OnyxCollection<ReportActions> = {}; |
| 45 | +// Report actions are cached only to resolve parent actions for IOU cleanup; no UI subscribes, so connectWithoutView() is used. |
| 46 | +Onyx.connectWithoutView({ |
| 47 | + key: ONYXKEYS.COLLECTION.REPORT_ACTIONS, |
| 48 | + callback: (actions, key) => { |
| 49 | + if (!key || !actions) { |
| 50 | + return; |
| 51 | + } |
| 52 | + const reportID = key.replace(ONYXKEYS.COLLECTION.REPORT_ACTIONS, ''); |
| 53 | + allReportActions[reportID] = actions; |
| 54 | + }, |
| 55 | +}); |
| 56 | + |
| 57 | +function replaceOptimisticReportWithActualReport(report: Report, draftReportComment: string | undefined) { |
| 58 | + const {reportID, preexistingReportID, parentReportID, parentReportActionID} = report; |
| 59 | + |
| 60 | + if (!reportID || !preexistingReportID) { |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + // Handle cleanup of stale optimistic IOU report and its report preview separately |
| 65 | + if ((isMoneyRequestReport(report) || isMoneyRequest(report)) && parentReportID && parentReportActionID) { |
| 66 | + const parentReportAction = allReportActions?.[parentReportID]?.[parentReportActionID]; |
| 67 | + if (parentReportAction?.childReportID === reportID) { |
| 68 | + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${parentReportID}`, { |
| 69 | + [parentReportActionID]: null, |
| 70 | + }); |
| 71 | + } |
| 72 | + Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, null); |
| 73 | + return; |
| 74 | + } |
| 75 | + |
| 76 | + // eslint-disable-next-line @typescript-eslint/no-deprecated |
| 77 | + InteractionManager.runAfterInteractions(() => { |
| 78 | + // It is possible that we optimistically created a DM/group-DM for a set of users for which a report already exists. |
| 79 | + // In this case, the API will let us know by returning a preexistingReportID. |
| 80 | + // We should clear out the optimistically created report and re-route the user to the preexisting report. |
| 81 | + let callback = () => { |
| 82 | + const existingReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${preexistingReportID}`]; |
| 83 | + |
| 84 | + Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, null); |
| 85 | + Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${preexistingReportID}`, { |
| 86 | + ...report, |
| 87 | + reportID: preexistingReportID, |
| 88 | + preexistingReportID: null, |
| 89 | + // Replacing the existing report's participants to avoid duplicates |
| 90 | + participants: existingReport?.participants ?? report.participants, |
| 91 | + }); |
| 92 | + Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${reportID}`, null); |
| 93 | + }; |
| 94 | + |
| 95 | + if (!navigationRef.isReady()) { |
| 96 | + callback(); |
| 97 | + return; |
| 98 | + } |
| 99 | + |
| 100 | + // Use Navigation.getActiveRoute() instead of navigationRef.getCurrentRoute()?.path because |
| 101 | + // getCurrentRoute().path can be undefined during first navigation. |
| 102 | + // We still need getCurrentRoute() for params and screen name as getActiveRoute() only returns the path string. |
| 103 | + const activeRoute = Navigation.getActiveRoute(); |
| 104 | + const currentRouteInfo = navigationRef.getCurrentRoute(); |
| 105 | + const backTo = (currentRouteInfo?.params as {backTo?: Route})?.backTo; |
| 106 | + const screenName = currentRouteInfo?.name; |
| 107 | + |
| 108 | + const isOptimisticReportFocused = activeRoute.includes(`/r/${reportID}`); |
| 109 | + |
| 110 | + // Fix specific case: https://github.com/Expensify/App/pull/77657#issuecomment-3678696730. |
| 111 | + // When user is editing a money request report (/e/:reportID route) and has |
| 112 | + // an optimistic report in the background that should be replaced with preexisting report |
| 113 | + const isOptimisticReportInBackground = screenName === SCREENS.RIGHT_MODAL.EXPENSE_REPORT && backTo && backTo.includes(`/r/${reportID}`); |
| 114 | + |
| 115 | + // Only re-route them if they are still looking at the optimistically created report |
| 116 | + if (isOptimisticReportFocused || isOptimisticReportInBackground) { |
| 117 | + const currCallback = callback; |
| 118 | + callback = () => { |
| 119 | + currCallback(); |
| 120 | + if (isOptimisticReportFocused) { |
| 121 | + Navigation.setParams({reportID: preexistingReportID.toString()}); |
| 122 | + } else if (isOptimisticReportInBackground) { |
| 123 | + // Navigate to the correct backTo route with the preexisting report ID |
| 124 | + Navigation.navigate(backTo.replace(`/r/${reportID}`, `/r/${preexistingReportID}`) as Route); |
| 125 | + } |
| 126 | + }; |
| 127 | + |
| 128 | + // The report screen will listen to this event and transfer the draft comment to the existing report |
| 129 | + // This will allow the newest draft comment to be transferred to the existing report |
| 130 | + DeviceEventEmitter.emit(`switchToPreExistingReport_${reportID}`, { |
| 131 | + preexistingReportID, |
| 132 | + callback, |
| 133 | + }); |
| 134 | + |
| 135 | + return; |
| 136 | + } |
| 137 | + |
| 138 | + // In case the user is not on the report screen, we will transfer the report draft comment directly to the existing report |
| 139 | + // after that clear the optimistically created report |
| 140 | + if (!draftReportComment) { |
| 141 | + callback(); |
| 142 | + return; |
| 143 | + } |
| 144 | + |
| 145 | + saveReportDraftComment(preexistingReportID, draftReportComment, callback); |
| 146 | + }); |
| 147 | +} |
| 148 | + |
| 149 | +// Reports are observed only to detect preexistingReportID and run replacement; no UI subscribes, so connectWithoutView() is used. |
| 150 | +Onyx.connectWithoutView({ |
| 151 | + key: ONYXKEYS.COLLECTION.REPORT, |
| 152 | + waitForCollectionCallback: true, |
| 153 | + callback: (value: OnyxCollection<Report>) => { |
| 154 | + allReports = value; |
| 155 | + |
| 156 | + if (!value) { |
| 157 | + return; |
| 158 | + } |
| 159 | + |
| 160 | + for (const report of Object.values(value)) { |
| 161 | + if (!report) { |
| 162 | + continue; |
| 163 | + } |
| 164 | + |
| 165 | + replaceOptimisticReportWithActualReport(report, allReportDraftComments?.[`${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${report.reportID}`]); |
| 166 | + } |
| 167 | + }, |
| 168 | +}); |
| 169 | + |
| 170 | +export {replaceOptimisticReportWithActualReport}; |
| 171 | + |
| 172 | +export default {}; |
0 commit comments