-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathSearchMoneyRequestReportPage.tsx
More file actions
424 lines (363 loc) · 20 KB
/
Copy pathSearchMoneyRequestReportPage.tsx
File metadata and controls
424 lines (363 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
import FullPageNotFoundView from '@components/BlockingViews/FullPageNotFoundView';
import DragAndDropProvider from '@components/DragAndDrop/Provider';
import MoneyRequestReportView from '@components/MoneyRequestReportView/MoneyRequestReportView';
import ScreenWrapper from '@components/ScreenWrapper';
import {useSearchResultsContext} from '@components/Search/SearchContext';
import useRHPWidth from '@components/WideRHPContextProvider/useRHPWidth';
import WideRHPOverlayWrapper from '@components/WideRHPOverlayWrapper';
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import useDismissOnMoneyRequestReportRemoval from '@hooks/useDismissOnMoneyRequestReportRemoval';
import useDocumentTitle from '@hooks/useDocumentTitle';
import useIsReportReadyToDisplay from '@hooks/useIsReportReadyToDisplay';
import useNetwork from '@hooks/useNetwork';
import useOnyx from '@hooks/useOnyx';
import useParentReportAction from '@hooks/useParentReportAction';
import usePrevious from '@hooks/usePrevious';
import useReportIsArchived from '@hooks/useReportIsArchived';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useSubmitToDestinationVisible from '@hooks/useSubmitToDestinationVisible';
import useThemeStyles from '@hooks/useThemeStyles';
import useTransactionsAndViolationsForReport from '@hooks/useTransactionsAndViolationsForReport';
import useTransactionThreadReportID from '@hooks/useTransactionThreadReportID';
import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID';
import Log from '@libs/Log';
import {getAllNonDeletedTransactions} from '@libs/MoneyRequestReportUtils';
import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types';
import TransitionTracker from '@libs/Navigation/TransitionTracker';
import type {RightModalNavigatorParamList} from '@libs/Navigation/types';
import {getIOUActionForTransactionID, getReportAction, isMoneyRequestAction} from '@libs/ReportActionsUtils';
import {deprecatedGetReportName} from '@libs/ReportNameUtils';
import {isMoneyRequestReportPendingDeletion, isValidReportIDFromPath} from '@libs/ReportUtils';
import {cancelSpansByPrefix} from '@libs/telemetry/activeSpans';
import {doesDeleteNavigateBackUrlIncludeDuplicatesReview, getParentReportActionDeletionStatus, hasLoadedReportActions, isThreadReportDeleted} from '@libs/TransactionNavigationUtils';
import Navigation from '@navigation/Navigation';
import {ActionListContextProvider} from '@pages/inbox/ActionListContext';
import ReactionListWrapper from '@pages/inbox/ReactionListWrapper';
import {ReportActionEditMessageContextProvider} from '@pages/inbox/report/ReportActionEditMessageContext';
import useClearReportActionDraftsOnReportChange from '@pages/inbox/report/useClearReportActionDraftsOnReportChange';
import {clearDeleteTransactionNavigateBackUrl, createTransactionThreadReport, openReport, updateLastVisitTime} from '@userActions/Report';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import SCREENS from '@src/SCREENS';
import type {ReportAttributesDerivedValue, Transaction, TransactionViolations} from '@src/types/onyx';
import type {OnyxEntry} from 'react-native-onyx';
import {PortalHost} from '@gorhom/portal';
import {useIsFocused} from '@react-navigation/native';
import reportByIDsSelector from '@selectors/ReportAttributes';
import React, {useCallback, useEffect, useMemo, useRef} from 'react';
type SearchMoneyRequestPageProps =
| PlatformStackScreenProps<RightModalNavigatorParamList, typeof SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT>
| PlatformStackScreenProps<RightModalNavigatorParamList, typeof SCREENS.RIGHT_MODAL.EXPENSE_REPORT>;
const defaultReportLoadingState = {
isLoadingInitialReportActions: true,
isLoadingOlderReportActions: false,
hasLoadingOlderReportActionsError: false,
isLoadingNewerReportActions: false,
hasLoadingNewerReportActionsError: false,
hasOnceLoadedReportActions: false,
};
function SearchMoneyRequestReportPage({route}: SearchMoneyRequestPageProps) {
const {shouldUseNarrowLayout} = useResponsiveLayout();
const styles = useThemeStyles();
const {isOffline} = useNetwork();
const reportIDFromRoute = getNonEmptyStringOnyxID(route.params?.reportID);
const {currentSearchResults: snapshot} = useSearchResultsContext();
const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportIDFromRoute}`);
const [hasReportActions] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportIDFromRoute}`, {selector: Boolean});
const [deleteTransactionNavigateBackUrl] = useOnyx(ONYXKEYS.NVP_DELETE_TRANSACTION_NAVIGATE_BACK_URL);
const parentReportAction = useParentReportAction(report);
const handleSubmitToDestinationVisibleLayout = useSubmitToDestinationVisible(
[CONST.TELEMETRY.SUBMIT_FOLLOW_UP_ACTION.DISMISS_MODAL_AND_OPEN_REPORT, CONST.TELEMETRY.SUBMIT_FOLLOW_UP_ACTION.DISMISS_MODAL_ONLY],
reportIDFromRoute,
[CONST.TELEMETRY.SUBMIT_TO_DESTINATION_VISIBLE_TRIGGER.LAYOUT, CONST.TELEMETRY.SUBMIT_TO_DESTINATION_VISIBLE_TRIGGER.FOCUS],
);
const [parentReportLoadingState] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${report?.parentReportID}`);
const {email: currentUserEmail, accountID: currentUserAccountID} = useCurrentUserPersonalDetails();
const isFocused = useIsFocused();
useDismissOnMoneyRequestReportRemoval(reportIDFromRoute);
useEffect(() => {
// Update last visit time when the expense super wide RHP report is focused
if (!reportIDFromRoute || !isFocused || route.name !== SCREENS.RIGHT_MODAL.EXPENSE_REPORT) {
return;
}
updateLastVisitTime(reportIDFromRoute);
}, [reportIDFromRoute, isFocused, route.name]);
useEffect(() => {
if (isFocused || !deleteTransactionNavigateBackUrl) {
return;
}
if (doesDeleteNavigateBackUrlIncludeDuplicatesReview(deleteTransactionNavigateBackUrl)) {
return;
}
// Clear the URL only after we navigate away to avoid a brief Not Found flash.
const handle = TransitionTracker.runAfterTransitions({
callback: () => {
requestAnimationFrame(clearDeleteTransactionNavigateBackUrl);
},
waitForUpcomingTransition: true,
});
return () => handle.cancel();
}, [isFocused, deleteTransactionNavigateBackUrl]);
const [reportLoadingState = defaultReportLoadingState] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${reportIDFromRoute}`);
const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP);
const isReportArchived = useReportIsArchived(report?.reportID);
const {isEditingDisabled, isCurrentReportLoadedFromOnyx} = useIsReportReadyToDisplay(report, reportIDFromRoute, isReportArchived);
const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED);
const [betas] = useOnyx(ONYXKEYS.BETAS);
const {transactions: allReportTransactions, violations: allReportViolations} = useTransactionsAndViolationsForReport(reportIDFromRoute);
const {transactionThreadReportID, effectiveTransactionThreadReportID, reportActions} = useTransactionThreadReportID(reportIDFromRoute);
const reportTransactions = useMemo(() => getAllNonDeletedTransactions(allReportTransactions, reportActions), [allReportTransactions, reportActions]);
const visibleTransactions = useMemo(
() => reportTransactions?.filter((transaction) => isOffline || transaction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE),
[reportTransactions, isOffline],
);
const oneTransactionID = reportTransactions.at(0)?.transactionID;
const reportID = report?.reportID;
const reportAttributesSelector = useCallback((attributes: OnyxEntry<ReportAttributesDerivedValue>) => reportByIDsSelector(reportID ? [reportID] : [])(attributes), [reportID]);
const [reportAttributes] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, {selector: reportAttributesSelector});
useDocumentTitle(deprecatedGetReportName(report, reportAttributes));
const doesReportIDLookValid = isValidReportIDFromPath(reportID);
const hasLoadedReportActionsForAccessError = hasLoadedReportActions(reportLoadingState, isOffline);
const isReportPendingDeletion = isMoneyRequestReportPendingDeletion(report);
const isThreadReportDeletedForReview = isThreadReportDeleted(report, reportLoadingState, isOffline);
const {wasParentActionDeleted} = getParentReportActionDeletionStatus({
parentReportID: report?.parentReportID,
parentReportActionID: report?.parentReportActionID,
parentReportAction,
parentReportLoadingState,
isOffline,
});
// Prevents creating duplicate transaction threads for legacy transactions
const hasCreatedLegacyThreadRef = useRef(false);
// Get transaction from search snapshot if not available in main collections
const {snapshotTransaction, snapshotViolations} = useMemo(() => {
if (!snapshot?.data || Object.keys(allReportTransactions).length > 0) {
return {snapshotTransaction: undefined, snapshotViolations: undefined};
}
const transactionKey = Object.keys(snapshot.data).find((key) => key.startsWith(ONYXKEYS.COLLECTION.TRANSACTION));
if (!transactionKey) {
return {snapshotTransaction: undefined, snapshotViolations: undefined};
}
const snapshotData = snapshot.data as Record<string, unknown>;
const transaction = snapshotData[transactionKey] as Transaction;
if (transaction.reportID !== reportIDFromRoute) {
return {snapshotTransaction: undefined, snapshotViolations: undefined};
}
const violationKey = `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transaction.transactionID}`;
const violations = snapshotData[violationKey] as TransactionViolations | undefined;
return {snapshotTransaction: transaction, snapshotViolations: violations};
}, [snapshot?.data, allReportTransactions, reportIDFromRoute]);
// If there is more than one transaction, display the report in Super Wide RHP, otherwise it will be shown in Wide RHP
const shouldShowSuperWideRHP = visibleTransactions.length > 1;
useRHPWidth(shouldShowSuperWideRHP ? 'super-wide' : 'wide');
// Tracks initial mount to ensure openReport is called once for multi-transaction reports
const isInitialMountRef = useRef(true);
const prevReportIDFromRoute = usePrevious(reportIDFromRoute);
useEffect(() => {
// Reset flag when reportID changes (screen stays mounted but navigates to different report)
if (prevReportIDFromRoute !== reportIDFromRoute) {
isInitialMountRef.current = true;
}
// Guard prevents calling openReport for multi-transaction reports
if (visibleTransactions.length > 2 && !isInitialMountRef.current) {
return;
}
if (transactionThreadReportID === CONST.FAKE_REPORT_ID && oneTransactionID) {
const iouAction = getIOUActionForTransactionID(reportActions, oneTransactionID);
createTransactionThreadReport({
introSelected,
currentUserLogin: currentUserEmail ?? '',
currentUserAccountID,
betas,
iouReport: report,
iouReportAction: iouAction,
});
return;
}
openReport({reportID: reportIDFromRoute, introSelected, betas, hasReportActions, currentUserAccountID});
isInitialMountRef.current = false;
// oneTransactionID dependency handles the case when deleting a transaction:
// oneTransactionID updates after transactionThreadReportID,
// so we need it in dependencies to re-run the effect with the correct remaining transaction.
// For more details see https://github.com/Expensify/App/pull/80107
// We don't want this hook to re-run on the every report change
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [reportIDFromRoute, transactionThreadReportID, oneTransactionID, betas]);
useEffect(() => {
hasCreatedLegacyThreadRef.current = false;
return () => {
// Cancel any pending send-message spans to prevent orphaned spans when navigating away
cancelSpansByPrefix(CONST.TELEMETRY.SPAN_SEND_MESSAGE);
};
}, [reportIDFromRoute]);
// Create transaction thread for legacy transactions that don't have one yet.
// Wait for all data to load to avoid duplicates or stale data when navigating between reports.
useEffect(() => {
if (
hasCreatedLegacyThreadRef.current ||
transactionThreadReportID ||
(Object.keys(allReportTransactions).length !== 1 && !snapshotTransaction) ||
!reportLoadingState?.hasOnceLoadedReportActions ||
reportActions.length === 0
) {
return;
}
// Because when switching between reports, reportActions may contain data from the previous report.
// So we need to check that reportActions belongs to the current report.
const isFirstActionBelongsToCurrentReport = !!getReportAction(reportIDFromRoute, reportActions.at(0)?.reportActionID);
if (report?.reportID && reportActions.length === 1 && !isFirstActionBelongsToCurrentReport) {
return;
}
// Use main collection transaction or fallback to snapshot
const transaction = Object.values(allReportTransactions).at(0) ?? snapshotTransaction;
if (!transaction || (transaction && transaction.reportID !== reportIDFromRoute)) {
return;
}
// Check that reportActions belong to the current report to avoid using stale data from the previous report
const hasMatchingReportActions = reportActions.some((action) => {
const iouReportID = isMoneyRequestAction(action) ? action?.reportID : undefined;
return iouReportID?.toString() === reportIDFromRoute;
});
if (!hasMatchingReportActions && reportActions.length > 1) {
return;
}
const iouAction = getIOUActionForTransactionID(reportActions, transaction.transactionID);
if (iouAction || transaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD || !!transaction.linkedTrackedExpenseReportAction?.childReportID) {
return;
}
hasCreatedLegacyThreadRef.current = true;
const violations = allReportViolations[transaction.transactionID] ?? snapshotViolations;
createTransactionThreadReport({
introSelected,
currentUserLogin: currentUserEmail ?? '',
currentUserAccountID,
betas,
iouReport: report,
transaction,
transactionViolations: violations,
});
}, [
allReportTransactions,
allReportViolations,
introSelected,
currentUserEmail,
currentUserAccountID,
betas,
report,
reportActions,
reportIDFromRoute,
reportLoadingState?.hasOnceLoadedReportActions,
reportLoadingState?.isLoadingInitialReportActions,
snapshot,
snapshotTransaction,
snapshotViolations,
transactionThreadReportID,
visibleTransactions,
]);
const shouldUseSnapshotTransaction = reportTransactions.length === 0 && !!snapshotTransaction;
const activeTransactionsCount = useMemo(() => {
if (shouldUseSnapshotTransaction) {
return snapshotTransaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE ? 0 : 1;
}
return reportTransactions.filter((transaction) => transaction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE).length;
}, [reportTransactions, shouldUseSnapshotTransaction, snapshotTransaction?.pendingAction]);
const hasAnyTransactions = reportTransactions.length > 0 || shouldUseSnapshotTransaction;
const wereAllTransactionsDeleted = useMemo(() => hasAnyTransactions && activeTransactionsCount === 0, [hasAnyTransactions, activeTransactionsCount]);
const shouldShowAccessErrorPage = useMemo((): boolean => {
if (isLoadingApp !== false) {
return false;
}
if (deleteTransactionNavigateBackUrl) {
return false;
}
if (!!reportID && !doesReportIDLookValid) {
return true;
}
if (isReportPendingDeletion || wereAllTransactionsDeleted || wasParentActionDeleted || isThreadReportDeletedForReview) {
return true;
}
return !reportID && hasLoadedReportActionsForAccessError && !hasAnyTransactions;
// isLoadingApp intentionally omitted to avoid re-computing after initial load completes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
reportID,
hasLoadedReportActionsForAccessError,
doesReportIDLookValid,
isReportPendingDeletion,
wereAllTransactionsDeleted,
hasAnyTransactions,
deleteTransactionNavigateBackUrl,
wasParentActionDeleted,
isThreadReportDeletedForReview,
]);
useEffect(() => {
if (!shouldShowAccessErrorPage) {
return;
}
Log.info('[SearchMoneyRequestReportPage] Displaying NotFound Page', false, {
reportID,
hasLoadedReportActionsForAccessError,
doesReportIDLookValid,
isReportPendingDeletion,
wereAllTransactionsDeleted,
hasAnyTransactions,
deleteTransactionNavigateBackUrl,
wasParentActionDeleted,
isThreadReportDeletedForReview,
shouldUseSnapshotTransaction,
});
}, [
shouldShowAccessErrorPage,
reportID,
hasLoadedReportActionsForAccessError,
doesReportIDLookValid,
isReportPendingDeletion,
wereAllTransactionsDeleted,
hasAnyTransactions,
deleteTransactionNavigateBackUrl,
wasParentActionDeleted,
isThreadReportDeletedForReview,
shouldUseSnapshotTransaction,
]);
useClearReportActionDraftsOnReportChange(reportIDFromRoute);
return (
<ReportActionEditMessageContextProvider
reportID={reportIDFromRoute}
effectiveTransactionThreadReportID={effectiveTransactionThreadReportID}
>
<WideRHPOverlayWrapper>
<ActionListContextProvider>
<ReactionListWrapper>
<ScreenWrapper
testID="SearchMoneyRequestReportPage"
shouldEnableMaxHeight
offlineIndicatorStyle={styles.mtAuto}
>
<FullPageNotFoundView
shouldShow={shouldShowAccessErrorPage}
subtitleKey="notFound.noAccess"
subtitleStyle={[styles.textSupporting]}
shouldDisplaySearchRouter
shouldShowBackButton={shouldUseNarrowLayout}
onBackButtonPress={Navigation.goBack}
>
<DragAndDropProvider isDisabled={isEditingDisabled}>
<MoneyRequestReportView
report={report}
reportLoadingState={reportLoadingState}
shouldDisplayReportFooter={isCurrentReportLoadedFromOnyx}
key={report?.reportID}
onLayout={handleSubmitToDestinationVisibleLayout}
backToRoute={route.params.backTo}
/>
<PortalHost name="suggestions" />
</DragAndDropProvider>
</FullPageNotFoundView>
</ScreenWrapper>
</ReactionListWrapper>
</ActionListContextProvider>
</WideRHPOverlayWrapper>
</ReportActionEditMessageContextProvider>
);
}
export default SearchMoneyRequestReportPage;