diff --git a/src/ONYXKEYS.ts b/src/ONYXKEYS.ts index 2b6932e29d3d..74c8faa25b49 100755 --- a/src/ONYXKEYS.ts +++ b/src/ONYXKEYS.ts @@ -866,6 +866,10 @@ const ONYXKEYS = { /** List of transaction IDs used when navigating to prev/next transaction when viewing it in RHP */ TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS: 'transactionThreadNavigationTransactionIDs', + /** Hash of the search snapshot that holds the transactions referenced by TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS. + * Used to fall back to snapshot data when the live transaction collection hasn't loaded those transactions yet (e.g. opening an expense from the Spend page as an approver). */ + TRANSACTION_THREAD_NAVIGATION_SNAPSHOT_HASH: 'transactionThreadNavigationSnapshotHash', + /** Optional map of transactionID -> sibling descriptor for prev/next navigation in snapshot-backed flows (e.g. Home "Recently added"), where siblings may be absent from the main Onyx collections. When set, navigation resolves (and lazily creates) each sibling's thread on demand from its descriptor. */ TRANSACTION_THREAD_NAVIGATION_THREAD_REPORT_IDS: 'transactionThreadNavigationThreadReportIDs', @@ -1910,6 +1914,7 @@ type OnyxValuesMapping = { [ONYXKEYS.REPORT_NAVIGATION_LAST_SEARCH_QUERY]: OnyxTypes.LastSearchParams; [ONYXKEYS.NVP_LAST_ANDROID_LOGIN]: string; [ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS]: string[]; + [ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_SNAPSHOT_HASH]: number; [ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_THREAD_REPORT_IDS]: Record; [ONYXKEYS.NVP_INTEGRATION_SERVER_EXPORT_TEMPLATES]: OnyxTypes.ExportTemplate[]; [ONYXKEYS.ONBOARDING_USER_REPORTED_INTEGRATION]: OnboardingAccounting; diff --git a/src/ROUTES.ts b/src/ROUTES.ts index b622e2275fae..89edfa0247ec 100644 --- a/src/ROUTES.ts +++ b/src/ROUTES.ts @@ -2105,14 +2105,18 @@ const ROUTES = { }, SEARCH_REPORT: { route: 'search/view/:reportID/:reportActionID?', - getRoute: ({reportID, reportActionID, backTo}: {reportID: string | undefined; reportActionID?: string; backTo?: string}) => { + getRoute: ({reportID, reportActionID, backTo, anchorTransactionID}: {reportID: string | undefined; reportActionID?: string; backTo?: string; anchorTransactionID?: string}) => { if (!reportID) { Log.warn('Invalid reportID is used to build the SEARCH_REPORT route'); } const baseRoute = reportActionID ? (`search/view/${reportID}/${reportActionID}` as const) : (`search/view/${reportID}` as const); + // Which expense in the prev/next carousel this screen is anchored to. The header falls back to it while + // the thread's own parent report action is still loading, so the carousel doesn't wink out of existence + // on a cold open (e.g. straight after clearing the cache). + const routeWithAnchor = anchorTransactionID ? (`${baseRoute}?anchorTransactionID=${anchorTransactionID}` as const) : baseRoute; - return getUrlWithBackToParam(baseRoute, backTo); + return getUrlWithBackToParam(routeWithAnchor, backTo); }, }, diff --git a/src/components/MoneyReportHeader.tsx b/src/components/MoneyReportHeader.tsx index ae0b2ffaf4a1..84c1bbdc682d 100644 --- a/src/components/MoneyReportHeader.tsx +++ b/src/components/MoneyReportHeader.tsx @@ -1,5 +1,7 @@ +import useCarouselTransactionIDs from '@hooks/useCarouselTransactionIDs'; import useLocalize from '@hooks/useLocalize'; import useMobileSelectionMode from '@hooks/useMobileSelectionMode'; +import useMoneyReportHeaderMoreContentVisibility from '@hooks/useMoneyReportHeaderMoreContentVisibility'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import useReportPrimaryAction from '@hooks/useReportPrimaryAction'; @@ -9,16 +11,21 @@ import useThemeStyles from '@hooks/useThemeStyles'; import useTransactionsAndViolationsForReport from '@hooks/useTransactionsAndViolationsForReport'; import {turnOffMobileSelectionMode} from '@libs/actions/MobileSelectionMode'; +import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import type {PlatformStackRouteProp} from '@libs/Navigation/PlatformStackNavigation/types'; import type {ReportsSplitNavigatorParamList, RightModalNavigatorParamList} from '@libs/Navigation/types'; +import {getOriginalMessage, isMoneyRequestAction} from '@libs/ReportActionsUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {Route} from '@src/ROUTES'; import SCREENS from '@src/SCREENS'; +import type * as OnyxTypes from '@src/types/onyx'; + +import type {OnyxEntry} from 'react-native-onyx'; import {useIsFocused, useRoute} from '@react-navigation/native'; -import React, {useEffect} from 'react'; +import React, {useCallback, useEffect} from 'react'; import {View} from 'react-native'; import HeaderLoadingBar from './HeaderLoadingBar'; @@ -26,6 +33,8 @@ import HeaderWithBackButton from './HeaderWithBackButton'; import MoneyReportHeaderActions from './MoneyReportHeaderActions'; import MoneyReportHeaderModals from './MoneyReportHeaderModals'; import MoneyReportHeaderMoreContent from './MoneyReportHeaderMoreContent'; +import MoneyRequestReportNavigation from './MoneyRequestReportView/MoneyRequestReportNavigation'; +import MoneyRequestReportTransactionsNavigation from './MoneyRequestReportView/MoneyRequestReportTransactionsNavigation'; import {PaymentAnimationsProvider} from './PaymentAnimationsContext'; import {useSearchSelectionActions} from './Search/SearchContext'; @@ -75,15 +84,49 @@ function MoneyReportHeaderContent({reportID: reportIDProp, shouldDisplayBackButt const transactions = Object.values(reportTransactions); + // The same filtered list MoneyRequestReportTransactionsNavigation renders from, so the two agree on whether + // there is an expense carousel to show. Gating on the raw Onyx list let this pick the expense branch while the + // carousel found nothing to page through, leaving the user with neither set of arrows. + const {transactionIDs: activeTransactionIDs} = useCarouselTransactionIDs(); + + const singleTransactionID = transactions.length === 1 ? transactions.at(0)?.transactionID : undefined; + + const threadParentReportActionID = moneyRequestReport?.parentReportActionID; + const threadTransactionIDSelector = useCallback( + (parentReportActions: OnyxEntry) => { + const parentReportAction = threadParentReportActionID ? parentReportActions?.[threadParentReportActionID] : undefined; + return isMoneyRequestAction(parentReportAction) ? getOriginalMessage(parentReportAction)?.IOUTransactionID : undefined; + }, + [threadParentReportActionID], + ); + const [threadTransactionID] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${getNonEmptyStringOnyxID(moneyRequestReport?.parentReportID)}`, {selector: threadTransactionIDSelector}); + + const anchorTransactionIDFromRoute = route.name === SCREENS.RIGHT_MODAL.SEARCH_REPORT ? route.params.anchorTransactionID : undefined; + const routeAnchorTransactionID = anchorTransactionIDFromRoute && activeTransactionIDs.includes(anchorTransactionIDFromRoute) ? anchorTransactionIDFromRoute : undefined; + const carouselAnchorTransactionID = route.name === SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT ? undefined : (singleTransactionID ?? threadTransactionID ?? routeAnchorTransactionID); + const shouldShowTransactionNavigation = + route.name !== SCREENS.REPORT && !!carouselAnchorTransactionID && activeTransactionIDs.length > 1 && activeTransactionIDs.includes(carouselAnchorTransactionID); + const styles = useThemeStyles(); const {isWideRHPDisplayedOnWideLayout, isSuperWideRHPDisplayedOnWideLayout, shouldUseNarrowLayout: shouldUseNarrowLayoutOnWideRHP} = useResponsiveLayoutOnWideRHP(); const shouldShowHeaderButtonsInHeaderRow = isInLandscapeMode || !shouldDisplayNarrowVersion || isWideRHPDisplayedOnWideLayout || isSuperWideRHPDisplayedOnWideLayout; + const isReportInRHP = route.name !== SCREENS.REPORT; - const shouldDisplaySearchRouter = !isReportInRHP || isSmallScreenWidth; const isReportInSearch = route.name === SCREENS.RIGHT_MODAL.SEARCH_REPORT || route.name === SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT; + // The report-level arrows page through search results, so they are search-only; the expense carousel takes + // precedence wherever this report is anchored to one. + const shouldShowReportNavigation = !shouldShowTransactionNavigation && isReportInSearch; + + const {statusBarType, shouldShowNextStep, hasStatusOrNextStep} = useMoneyReportHeaderMoreContentVisibility(reportIDProp); + const shouldRenderActionsInHeaderRow = shouldShowHeaderButtonsInHeaderRow && !hasStatusOrNextStep; + // A narrow header has room for one control beside the title, and prev/next wins it: the arrows are the only way + // to reach this expense's siblings, whereas the search router is still one back-press away on the screen the + // user came from. Where no arrows are rendered the magnifier keeps its place, as it did before. + const shouldDisplaySearchRouter = !isReportInRHP || (isSmallScreenWidth && !shouldShowTransactionNavigation && !shouldShowReportNavigation); + const backTo = (route.params as {backTo?: Route} | undefined)?.backTo; const primaryAction = useReportPrimaryAction(reportIDProp); @@ -138,14 +181,29 @@ function MoneyReportHeaderContent({reportID: reportIDProp, shouldDisplayBackButt shouldEnableDetailPageNavigation openParentReportInCurrentTab > - {shouldShowHeaderButtonsInHeaderRow && ( - - )} + + {shouldRenderActionsInHeaderRow && ( + + )} + {shouldShowTransactionNavigation && !!carouselAnchorTransactionID ? ( + + ) : ( + shouldShowReportNavigation && ( + + ) + )} + {!shouldShowHeaderButtonsInHeaderRow && ( )} - + ); diff --git a/src/components/MoneyReportHeaderMoreContent.tsx b/src/components/MoneyReportHeaderMoreContent.tsx index b8a5494fa99e..61be77fbf67e 100644 --- a/src/components/MoneyReportHeaderMoreContent.tsx +++ b/src/components/MoneyReportHeaderMoreContent.tsx @@ -1,17 +1,12 @@ -import useMoneyReportHeaderStatusBar from '@hooks/useMoneyReportHeaderStatusBar'; import useOnyx from '@hooks/useOnyx'; -import useResponsiveLayout from '@hooks/useResponsiveLayout'; -import useResponsiveLayoutOnWideRHP from '@hooks/useResponsiveLayoutOnWideRHP'; import useThemeStyles from '@hooks/useThemeStyles'; -import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import type {PlatformStackRouteProp} from '@libs/Navigation/PlatformStackNavigation/types'; import type {ReportsSplitNavigatorParamList, RightModalNavigatorParamList} from '@libs/Navigation/types'; -import {isGroupPolicy} from '@libs/PolicyUtils'; -import {isInvoiceReport as isInvoiceReportUtil} from '@libs/ReportUtils'; import type CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; +import type {Route} from '@src/ROUTES'; import SCREENS from '@src/SCREENS'; import type * as OnyxTypes from '@src/types/onyx'; @@ -22,20 +17,37 @@ import {useRoute} from '@react-navigation/native'; import React from 'react'; import {View} from 'react-native'; +import type {MoneyReportHeaderActionsProps} from './MoneyReportHeaderActions/types'; + +import MoneyReportHeaderActions from './MoneyReportHeaderActions'; import MoneyReportHeaderNextStep from './MoneyReportHeaderNextStep'; import MoneyReportHeaderStatusBarSection from './MoneyReportHeaderStatusBarSection'; import {useMoneyReportTransactionThread} from './MoneyReportTransactionThreadContext'; -import MoneyRequestReportNavigation from './MoneyRequestReportView/MoneyRequestReportNavigation'; type MoneyReportHeaderMoreContentProps = { reportID: string | undefined; + + /** The report's primary action, forwarded to the actions row */ + primaryAction: MoneyReportHeaderActionsProps['primaryAction']; + + /** Route to navigate back to */ + backTo: Route | undefined; + + /** Which status bar to render, resolved by the header via useMoneyReportHeaderMoreContentVisibility */ + statusBarType: ValueOf | undefined; + + /** Whether the next step bar should be rendered, resolved alongside `statusBarType` */ + shouldShowNextStep: boolean; + + /** Whether the report actions belong at the end of this row. The header renders them itself when this row is empty. */ + shouldRenderActionsInRow: boolean; }; /** - * Cheap visibility gate — fetches minimal data to decide whether the more-content section - * should render at all, avoiding expensive hooks in the body when nothing is shown. + * Cheap visibility gate that decides whether the more-content section should render at all, + * avoiding expensive hooks in the body when nothing is shown. */ -function MoneyReportHeaderMoreContent({reportID}: MoneyReportHeaderMoreContentProps) { +function MoneyReportHeaderMoreContent({reportID, primaryAction, backTo, statusBarType, shouldShowNextStep, shouldRenderActionsInRow}: MoneyReportHeaderMoreContentProps) { const route = useRoute< | PlatformStackRouteProp | PlatformStackRouteProp @@ -45,13 +57,9 @@ function MoneyReportHeaderMoreContent({reportID}: MoneyReportHeaderMoreContentPr const isReportInSearch = route.name === SCREENS.RIGHT_MODAL.SEARCH_REPORT || route.name === SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT; const [moneyRequestReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`); - const [policy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${getNonEmptyStringOnyxID(moneyRequestReport?.policyID)}`); - const {shouldShowStatusBar, statusBarType} = useMoneyReportHeaderStatusBar(reportID, moneyRequestReport?.chatReportID); - - const isInvoiceReport = isInvoiceReportUtil(moneyRequestReport); - const shouldShowNextStep = isGroupPolicy(policy) && !isInvoiceReport && !shouldShowStatusBar; - const shouldShowMoreContent = shouldShowNextStep || !!statusBarType || isReportInSearch; + const hasStatusOrNextStep = shouldShowNextStep || !!statusBarType; + const shouldShowMoreContent = hasStatusOrNextStep || shouldRenderActionsInRow; if (!shouldShowMoreContent) { return null; @@ -63,6 +71,9 @@ function MoneyReportHeaderMoreContent({reportID}: MoneyReportHeaderMoreContentPr statusBarType={statusBarType} isReportInSearch={isReportInSearch} shouldShowNextStep={shouldShowNextStep} + primaryAction={primaryAction} + backTo={backTo} + shouldRenderActionsInRow={shouldRenderActionsInRow} /> ); } @@ -72,14 +83,21 @@ type MoneyReportHeaderMoreContentBodyProps = { statusBarType: ValueOf | undefined; isReportInSearch: boolean; shouldShowNextStep: boolean; + primaryAction: MoneyReportHeaderActionsProps['primaryAction']; + backTo: Route | undefined; + shouldRenderActionsInRow: boolean; }; -function MoneyReportHeaderMoreContentBody({moneyRequestReport, statusBarType, isReportInSearch, shouldShowNextStep}: MoneyReportHeaderMoreContentBodyProps) { +function MoneyReportHeaderMoreContentBody({ + moneyRequestReport, + statusBarType, + isReportInSearch, + shouldShowNextStep, + primaryAction, + backTo, + shouldRenderActionsInRow, +}: MoneyReportHeaderMoreContentBodyProps) { const styles = useThemeStyles(); - const {shouldUseNarrowLayout, isMediumScreenWidth} = useResponsiveLayout(); - const shouldDisplayNarrowVersion = shouldUseNarrowLayout || isMediumScreenWidth; - const {isWideRHPDisplayedOnWideLayout, isSuperWideRHPDisplayedOnWideLayout} = useResponsiveLayoutOnWideRHP(); - const shouldDisplayNarrowMoreButton = !shouldDisplayNarrowVersion || isWideRHPDisplayedOnWideLayout || isSuperWideRHPDisplayedOnWideLayout; const reportID = moneyRequestReport?.reportID; const {iouTransactionID} = useMoneyReportTransactionThread(); @@ -94,10 +112,12 @@ function MoneyReportHeaderMoreContentBody({moneyRequestReport, statusBarType, is iouTransactionID={iouTransactionID} /> - {isReportInSearch && ( - )} diff --git a/src/components/MoneyRequestHeader.tsx b/src/components/MoneyRequestHeader.tsx index 785e0a7fba3c..1512eb5f643e 100644 --- a/src/components/MoneyRequestHeader.tsx +++ b/src/components/MoneyRequestHeader.tsx @@ -67,7 +67,7 @@ function MoneyRequestHeader({reportID: reportIDProp, onBackButtonPress}: MoneyRe // We need to use isSmallScreenWidth instead of shouldUseNarrowLayout to use a correct layout for the hold expense modal https://github.com/Expensify/App/pull/47990#issuecomment-2362382026 // eslint-disable-next-line rulesdir/prefer-shouldUseNarrowLayout-instead-of-isSmallScreenWidth - const {shouldUseNarrowLayout, isSmallScreenWidth} = useResponsiveLayout(); + const {shouldUseNarrowLayout, isSmallScreenWidth, isMediumScreenWidth, isInLandscapeMode} = useResponsiveLayout(); const route = useRoute< | PlatformStackRouteProp | PlatformStackRouteProp @@ -101,8 +101,17 @@ function MoneyRequestHeader({reportID: reportIDProp, onBackButtonPress}: MoneyRe const isReportInRHP = route.name === SCREENS.RIGHT_MODAL.SEARCH_REPORT; const isFromReviewDuplicates = !!route.params.backTo && /\/duplicates\/review\/[^/]+$/.test(route.params.backTo.replaceAll(/\?.*/g, '')); const shouldDisplayTransactionNavigation = !!(reportID && isReportInRHP); + // `transaction` is resolved through this thread's parent report action, which isn't necessarily loaded yet on + // a cold open (e.g. opening an expense from the Spend page right after clearing the cache). The route carries + // the expense the screen was opened for, so fall back to it rather than hiding the carousel until data lands. + const anchorTransactionIDFromRoute = route.name === SCREENS.RIGHT_MODAL.SEARCH_REPORT ? route.params.anchorTransactionID : undefined; + const carouselTransactionID = transaction?.transactionID ?? anchorTransactionIDFromRoute; const shouldOpenParentReportInCurrentTab = !isSelfDM(parentReport); const shouldDisplayButtonsInSeparateLine = useShouldDisplayButtonsInSeparateLine() && (wideRHPRouteKeys.length === 0 || isSmallScreenWidth); + // Only the carousel counter reads this, and MoneyReportHeader counts tablet-portrait as cramped for the same + // counter. The two have to agree: derived from different breakpoints, the counter was hidden on a report and + // shown on its own expense thread at one window size, popping into existence as the user stepped inward. + const shouldDisplayNarrowVersion = shouldDisplayButtonsInSeparateLine || (isMediumScreenWidth && !isInLandscapeMode); const getStatusIcon: (src: IconAsset) => ReactNode = (src) => ( - {!shouldDisplayButtonsInSeparateLine && ( + {!shouldDisplayButtonsInSeparateLine && !statusBarProps && ( )} - {shouldDisplayTransactionNavigation && !!transaction && ( + {shouldDisplayTransactionNavigation && !!carouselTransactionID && ( )} @@ -199,11 +209,19 @@ function MoneyRequestHeader({reportID: reportIDProp, onBackButtonPress}: MoneyRe /> )} {!!statusBarProps && ( - - + + + + + {!shouldDisplayButtonsInSeparateLine && ( + + )} )} diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportNavigation.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportNavigation.tsx index d3506a09dd0f..bc7c4220eaec 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportNavigation.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportNavigation.tsx @@ -3,6 +3,7 @@ import {useSearchResultsContext} from '@components/Search/SearchContext'; import Text from '@components/Text'; import useFilterPendingDeleteReports from '@hooks/useFilterPendingDeleteReports'; +import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import useSearchSections from '@hooks/useSearchSections'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -21,6 +22,7 @@ import type LastSearchParams from '@src/types/onyx/ReportNavigation'; import type {OnyxEntry} from 'react-native-onyx'; +import {useIsFocused} from '@react-navigation/native'; import React, {startTransition, useEffect, useState} from 'react'; import {View} from 'react-native'; @@ -53,6 +55,13 @@ const selectQueryHash = (lastSearchQuery: OnyxEntry): number | const searchLoadingSelector = (snapshot: OnyxEntry): boolean => !!snapshot?.search?.isLoading; +/** + * Search sections can yield entries that aren't openable reports. An unreported (self-DM) expense is grouped under + * the "0" placeholder rather than a real report, so paging onto it lands the user on an empty report. It also + * inflates the "x of y" counter with a report the Reports list never showed them. + */ +const isNavigableReportID = (reportID: string | undefined): reportID is string => !!reportID && reportID !== CONST.REPORT.UNREPORTED_REPORT_ID; + const isSameReportList = (a: Array, b: Array | null): boolean => { if (a === b) { return true; @@ -105,7 +114,8 @@ function MoneyRequestReportNavigationStandalone({onReportsChange}: MoneyRequestR useEffect(() => { // Guard by content, not reference: useSearchSections rebuilds allReports via filter/map each // render, so an identity check would refire this update every render and loop. - onReportsChange((previousReports) => (isSameReportList(allReports, previousReports) ? previousReports : allReports)); + const navigableReports = allReports.filter(isNavigableReportID); + onReportsChange((previousReports) => (isSameReportList(navigableReports, previousReports) ? previousReports : navigableReports)); }, [allReports, onReportsChange]); return null; @@ -113,6 +123,8 @@ function MoneyRequestReportNavigationStandalone({onReportsChange}: MoneyRequestR function MoneyRequestReportNavigationContent({reportID, shouldDisplayNarrowVersion, contextReports}: MoneyRequestReportNavigationContentProps) { const styles = useThemeStyles(); + const {translate} = useLocalize(); + const isFocused = useIsFocused(); // Lightweight subscriptions only: the current search query and its loading flag. These never mount // the heavy useSearchSections subscription set, so the fast context path stays cheap. @@ -151,7 +163,7 @@ function MoneyRequestReportNavigationContent({reportID, shouldDisplayNarrowVersi const shouldDisplayNavigationArrows = effectiveAllReports.length > 1 && currentIndex !== -1 && !!lastSearchQuery?.queryJSON; useEffect(() => { - if (!lastSearchQuery?.queryJSON) { + if (!isFocused || !lastSearchQuery?.queryJSON) { return; } @@ -181,7 +193,7 @@ function MoneyRequestReportNavigationContent({reportID, shouldDisplayNarrowVersi ...lastSearchQuery, previousLengthOfResults: effectiveAllReports.length, }); - }, [currentIndex, allReportsCount, effectiveAllReports.length, lastSearchQuery?.queryJSON, lastSearchQuery]); + }, [isFocused, currentIndex, allReportsCount, effectiveAllReports.length, lastSearchQuery?.queryJSON, lastSearchQuery]); const goToReportId = (reportId?: string) => { if (!reportId) { @@ -242,7 +254,11 @@ function MoneyRequestReportNavigationContent({reportID, shouldDisplayNarrowVersi {!shouldUseContextReports && } {shouldDisplayNavigationArrows && ( - {!shouldDisplayNarrowVersion && {`${currentIndex + 1} of ${allReportsCount}`}} + {!shouldDisplayNarrowVersion && ( + + {translate('common.currentOfTotal', {current: currentIndex + 1, total: allReportsCount})} + + )} t.transactionID === activeTransactionID), siblingTransactionIDs: visualOrderTransactionIDs, + // Not `carouselSource`: this list unmounts behind the expense it just opened, and its teardown must + // not clear the carousel it seeded for that expense. + carouselSource: CAROUSEL_SOURCE.reportRow(report?.reportID), }); }; diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx index c1ca42771c85..b32101cdbb08 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx @@ -1,119 +1,206 @@ import {usePersonalDetails} from '@components/OnyxListItemProvider'; import PrevNextButtons from '@components/PrevNextButtons'; +import Text from '@components/Text'; import {useWideRHPActions} from '@components/WideRHPContextProvider'; +import useCarouselTransactionIDs from '@hooks/useCarouselTransactionIDs'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; +import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; +import useThemeStyles from '@hooks/useThemeStyles'; -import {createTransactionThreadReport, openReport, setOptimisticTransactionThread} from '@libs/actions/Report'; +import {openReport, setOptimisticTransactionThread} from '@libs/actions/Report'; import {clearActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; import type {RightModalNavigatorParamList} from '@libs/Navigation/types'; -import {getOriginalMessage, isMoneyRequestAction} from '@libs/ReportActionsUtils'; +import {getExpenseCreationTransactionID} from '@libs/ReportActionsUtils'; +import {findSelfDMReportID, isOneTransactionReport} from '@libs/ReportUtils'; +import type {TransactionThreadNavigationDescriptor} from '@libs/TransactionThreadNavigationUtils'; import {getReportIDToOpenForExpense} from '@libs/TransactionThreadNavigationUtils'; import Navigation from '@navigation/Navigation'; import navigationRef from '@navigation/navigationRef'; +import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import SCREENS from '@src/SCREENS'; import type * as OnyxTypes from '@src/types/onyx'; import getEmptyArray from '@src/types/utils/getEmptyArray'; import type {GestureResponderEvent} from 'react-native'; -import type {OnyxCollection} from 'react-native-onyx'; +import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import {findFocusedRoute, useIsFocused} from '@react-navigation/native'; import {guidedSetupAndTourStatusSelector} from '@selectors/Onboarding'; import React, {startTransition, useCallback, useEffect, useMemo, useRef} from 'react'; +import {View} from 'react-native'; + +const CAROUSEL_PRESERVING_SCREENS = [ + SCREENS.RIGHT_MODAL.SEARCH_REPORT, + SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT, + SCREENS.RIGHT_MODAL.EXPENSE_REPORT, + SCREENS.TRANSACTION_DUPLICATE.DYNAMIC_REVIEW, +] as const; type MoneyRequestReportRHPNavigationButtonsProps = { currentTransactionID: string; isFromReviewDuplicates?: boolean; + shouldDisplayNarrowVersion?: boolean; +}; + +type PrevNextParentReportActions = { + prevParentReportAction: OnyxTypes.ReportAction | undefined; + nextParentReportAction: OnyxTypes.ReportAction | undefined; +}; + +/** + * Only the prev/next parent actions are ever read, so resolve them while scanning instead of collecting every money + * request action on the parent reports (fast-equals compares the resulting collection on every Onyx update). + */ +const collectParentReportActions = ( + reportActions: OnyxEntry, + prevTransactionID: string | undefined, + nextTransactionID: string | undefined, + parentActions: PrevNextParentReportActions, +) => { + for (const action of Object.values(reportActions ?? {})) { + const transactionID = getExpenseCreationTransactionID(action); + if (!transactionID) { + continue; + } + if (transactionID === prevTransactionID && !parentActions.prevParentReportAction) { + // eslint-disable-next-line no-param-reassign -- intentionally mutates the shared accumulator so callers can resolve both actions in a single pass across multiple report-action sources + parentActions.prevParentReportAction = action; + } + if (transactionID === nextTransactionID && !parentActions.nextParentReportAction) { + // eslint-disable-next-line no-param-reassign -- intentionally mutates the shared accumulator so callers can resolve both actions in a single pass across multiple report-action sources + parentActions.nextParentReportAction = action; + } + } }; -function MoneyRequestReportTransactionsNavigation({currentTransactionID, isFromReviewDuplicates}: MoneyRequestReportRHPNavigationButtonsProps) { - const [transactionIDsList = getEmptyArray()] = useOnyx(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS); +function MoneyRequestReportTransactionsNavigation({currentTransactionID, isFromReviewDuplicates, shouldDisplayNarrowVersion}: MoneyRequestReportRHPNavigationButtonsProps) { + const styles = useThemeStyles(); + const {translate} = useLocalize(); + // Shared with the header, which uses the same filtered list to decide whether to render this carousel at all. + const {transactionIDs: transactionIDsList, snapshot} = useCarouselTransactionIDs(); + // Snapshot-backed flows (e.g. Home "Recently added") seed a descriptor per sibling so the carousel can + // resolve (and lazily create) each sibling's thread on demand even when the sibling isn't in the live collection. const [siblingDescriptorsByTransactionID] = useOnyx(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_THREAD_REPORT_IDS); + const {markReportRHPWidth} = useWideRHPActions(); + // Values required to create a transaction thread on the fly when paging onto an expense that has no thread yet. + const {accountID, email} = useCurrentUserPersonalDetails(); const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); const [conciergeChat] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); const [guidedSetupAndTourStatus] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: guidedSetupAndTourStatusSelector}); const personalDetails = usePersonalDetails(); - const {email: currentUserEmail, accountID: currentUserAccountID} = useCurrentUserPersonalDetails(); - const {markReportRHPWidth} = useWideRHPActions(); const {isOffline} = useNetwork(); const isFocused = useIsFocused(); + const currentTransactionIndex = transactionIDsList.findIndex((id) => id === currentTransactionID); + + // A press made before the sibling's parent action has loaded is parked here and replayed once it arrives. const pendingSiblingRef = useRef<{transactionID: string; originRoute: string} | null>(null); const {prevTransactionID, nextTransactionID} = useMemo(() => { - if (!transactionIDsList || transactionIDsList.length < 2) { + if (transactionIDsList.length < 2 || currentTransactionIndex === -1) { return {prevTransactionID: undefined, nextTransactionID: undefined}; } - const currentTransactionIndex = transactionIDsList.findIndex((id) => id === currentTransactionID); - - const prevID = currentTransactionIndex > 0 ? transactionIDsList.at(currentTransactionIndex - 1) : undefined; - const nextID = transactionIDsList.at(currentTransactionIndex + 1); - return { - prevTransactionID: prevID, - nextTransactionID: nextID, + prevTransactionID: currentTransactionIndex > 0 ? transactionIDsList.at(currentTransactionIndex - 1) : undefined, + nextTransactionID: transactionIDsList.at(currentTransactionIndex + 1), }; - }, [currentTransactionID, transactionIDsList]); + }, [currentTransactionIndex, transactionIDsList]); const prevNextTransactionsSelector = useCallback( (allTransactions: OnyxCollection) => - [currentTransactionID, prevTransactionID, nextTransactionID].map((transactionID) => allTransactions?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]), - [currentTransactionID, nextTransactionID, prevTransactionID], + [currentTransactionID, prevTransactionID, nextTransactionID].map((transactionID) => { + const key = `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}` as const; + return allTransactions?.[key] ?? snapshot?.data?.[key]; + }), + [currentTransactionID, nextTransactionID, prevTransactionID, snapshot], ); const [[currentTransaction, prevTransaction, nextTransaction] = getEmptyArray()] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION, { selector: prevNextTransactionsSelector, }); + const prevTransactionReportID = prevTransaction?.reportID; + const nextTransactionReportID = nextTransaction?.reportID; + // Only the prev/next parent actions are ever read, so resolve them inside the selector instead of returning // a Map of every money request action on the three parent reports (fast-equals compares Maps in O(n^2)). const parentReportActionsSelector = useCallback( (allReportActions: OnyxCollection) => { - let prevParentReportAction: OnyxTypes.ReportAction | undefined; - let nextParentReportAction: OnyxTypes.ReportAction | undefined; + // An unreported (self-DM) sibling's IOU action lives in the self-DM, since report "0" holds no actions + // of its own. Looking it up there is the only way such a sibling resolves from live data at all. + const isPrevUnreported = prevTransactionReportID === CONST.REPORT.UNREPORTED_REPORT_ID; + const isNextUnreported = nextTransactionReportID === CONST.REPORT.UNREPORTED_REPORT_ID; + const selfDMReportID = isPrevUnreported || isNextUnreported ? findSelfDMReportID() : undefined; + const prevActionsReportID = isPrevUnreported ? selfDMReportID : prevTransactionReportID; + const nextActionsReportID = isNextUnreported ? selfDMReportID : nextTransactionReportID; + // Whether the sibling's parent report has any actions at all, which is what separates "not fetched yet" + // from "fetched, but this expense has no creation action". Only the former is worth waiting for. + const hasPrevParentReportActions = !!Object.keys(allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${prevActionsReportID}`] ?? {}).length; + const hasNextParentReportActions = !!Object.keys(allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${nextActionsReportID}`] ?? {}).length; + const parentActions: PrevNextParentReportActions = {prevParentReportAction: undefined, nextParentReportAction: undefined}; if (!prevTransactionID && !nextTransactionID) { - return {prevParentReportAction, nextParentReportAction}; + return {...parentActions, hasPrevParentReportActions, hasNextParentReportActions}; } - const parentReportIDs = new Set([currentTransaction?.reportID, prevTransaction?.reportID, nextTransaction?.reportID]); + const parentReportIDs = new Set([currentTransaction?.reportID, prevActionsReportID, nextActionsReportID]); for (const parentReportID of parentReportIDs) { - for (const action of Object.values(allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${parentReportID}`] ?? {})) { - const transactionID = isMoneyRequestAction(action) ? getOriginalMessage(action)?.IOUTransactionID : undefined; - if (!transactionID) { - continue; - } - if (transactionID === prevTransactionID) { - prevParentReportAction = action; - } - if (transactionID === nextTransactionID) { - nextParentReportAction = action; - } - } + const key = `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${parentReportID}` as const; + collectParentReportActions(allReportActions?.[key], prevTransactionID, nextTransactionID, parentActions); } - return {prevParentReportAction, nextParentReportAction}; + return {...parentActions, hasPrevParentReportActions, hasNextParentReportActions}; }, - [currentTransaction?.reportID, nextTransaction?.reportID, nextTransactionID, prevTransaction?.reportID, prevTransactionID], + [currentTransaction?.reportID, nextTransactionReportID, nextTransactionID, prevTransactionReportID, prevTransactionID], ); - const [parentReportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS, { + const [reportedParentReportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS, { selector: parentReportActionsSelector, }); - const prevParentReportAction = parentReportActions?.prevParentReportAction; - const nextParentReportAction = parentReportActions?.nextParentReportAction; - - const [prevParentReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${prevTransaction?.reportID}`); - const [nextParentReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${nextTransaction?.reportID}`); - const [prevThreadReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${prevParentReportAction?.childReportID}`); - const [nextThreadReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${nextParentReportAction?.childReportID}`); + // The live pass above resolves a sibling from its parent report's actions (the self-DM's, for an unreported + // one), so it only finds what has already been fetched into Onyx. Scanning the snapshot's report actions is + // what resolves a sibling whose parent actions were never loaded in this session. + const snapshotData = snapshot?.data; + const snapshotParentReportActions = useMemo(() => { + const parentActions: PrevNextParentReportActions = {prevParentReportAction: undefined, nextParentReportAction: undefined}; + if (snapshotData && (prevTransactionID ?? nextTransactionID)) { + for (const [key, reportActionsForReport] of Object.entries(snapshotData)) { + if (key.startsWith(ONYXKEYS.COLLECTION.REPORT_ACTIONS)) { + collectParentReportActions(reportActionsForReport as OnyxTypes.ReportActions, prevTransactionID, nextTransactionID, parentActions); + } + } + } + return parentActions; + }, [nextTransactionID, prevTransactionID, snapshotData]); + + // Live report actions win over the snapshot: the snapshot only fills in siblings the live pass couldn't resolve + // (i.e. unreported ones). A search snapshot is a point-in-time copy, so for a reported transaction it can hold an + // older copy of the same IOU action, for example one still missing the childReportID of a thread that has since + // been created. Letting that stale copy win would make prev/next believe the sibling has no thread and create a + // duplicate one instead of navigating to the existing thread. + const prevParentReportAction = reportedParentReportActions?.prevParentReportAction ?? snapshotParentReportActions.prevParentReportAction; + const nextParentReportAction = reportedParentReportActions?.nextParentReportAction ?? snapshotParentReportActions.nextParentReportAction; + + const prevParentReportID = prevParentReportAction?.reportID ?? prevTransaction?.reportID; + const nextParentReportID = nextParentReportAction?.reportID ?? nextTransaction?.reportID; + + const [livePrevThreadReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${prevParentReportAction?.childReportID}`); + const [liveNextThreadReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${nextParentReportAction?.childReportID}`); + const [livePrevTransactionParentReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${prevParentReportID}`); + const [liveNextTransactionParentReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${nextParentReportID}`); + + // Fall back to the search snapshot for reports that aren't in the live collection yet. + const prevThreadReport = livePrevThreadReport ?? snapshot?.data?.[`${ONYXKEYS.COLLECTION.REPORT}${prevParentReportAction?.childReportID}`]; + const nextThreadReport = liveNextThreadReport ?? snapshot?.data?.[`${ONYXKEYS.COLLECTION.REPORT}${nextParentReportAction?.childReportID}`]; + const prevTransactionParentReport = livePrevTransactionParentReport ?? snapshot?.data?.[`${ONYXKEYS.COLLECTION.REPORT}${prevParentReportID}`]; + const nextTransactionParentReport = liveNextTransactionParentReport ?? snapshot?.data?.[`${ONYXKEYS.COLLECTION.REPORT}${nextParentReportID}`]; /** * We clear the sibling transactionThreadIDs when unmounting this component @@ -122,7 +209,7 @@ function MoneyRequestReportTransactionsNavigation({currentTransactionID, isFromR useEffect(() => { return () => { const focusedRoute = findFocusedRoute(navigationRef.getRootState()); - if (focusedRoute?.name === SCREENS.RIGHT_MODAL.SEARCH_REPORT || focusedRoute?.name === SCREENS.TRANSACTION_DUPLICATE.DYNAMIC_REVIEW) { + if (focusedRoute?.name && (CAROUSEL_PRESERVING_SCREENS as readonly string[]).includes(focusedRoute.name)) { return; } clearActiveTransactionIDs(); @@ -130,176 +217,196 @@ function MoneyRequestReportTransactionsNavigation({currentTransactionID, isFromR }, []); const stageSiblingPress = (transactionID: string | undefined, parentReportID: string | undefined) => { - // Offline there is no fetch to wait for, so the caller builds the thread optimistically instead. - if (!transactionID || !parentReportID || isOffline) { + // Offline there is no fetch to wait for, so the caller resolves the sibling with what it already has. + // Report "0" isn't a report that can be fetched either, so an unreported sibling never waits. + if (!transactionID || !parentReportID || parentReportID === CONST.REPORT.UNREPORTED_REPORT_ID || isOffline) { return false; } pendingSiblingRef.current = {transactionID, originRoute: Navigation.getActiveRoute()}; // Always true here: we are fetching this report's actions, so it must not overwrite its cached name. - openReport({reportID: parentReportID, introSelected, conciergeChat, currentUserAccountID, hasReportActions: true}); + openReport({reportID: parentReportID, introSelected, conciergeChat, currentUserAccountID: accountID, hasReportActions: true}); return true; }; - const onNext = (e: GestureResponderEvent | KeyboardEvent | undefined) => { - e?.preventDefault(); - + const getBackTo = () => { let backTo = Navigation.getActiveRoute(); if (isFromReviewDuplicates) { const currentRoute = navigationRef.getCurrentRoute(); const params = currentRoute?.params as RightModalNavigatorParamList[typeof SCREENS.RIGHT_MODAL.SEARCH_REPORT] | undefined; backTo = params?.backTo ?? backTo; } + return backTo; + }; + + const resolveContext = { + introSelected, + conciergeChat, + currentUserEmail: email, + currentUserAccountID: accountID, + personalDetails, + isSelfTourViewed: guidedSetupAndTourStatus?.isSelfTourViewed, + hasCompletedGuidedSetupFlow: guidedSetupAndTourStatus?.hasCompletedGuidedSetupFlow, + }; + + /** + * Resolves which report shows a sibling expense, creating its transaction thread only when one doesn't exist. + * + * Both directions run through here so they can't drift apart: an earlier version resolved "next" and "previous" + * with two near-identical copies of this logic, and stepping forward then back could land on a different screen + * than the one the user started on. + */ + const resolveSiblingReportID = ( + siblingTransactionID: string | undefined, + siblingTransaction: OnyxTypes.Transaction | undefined, + siblingParentReportAction: OnyxTypes.ReportAction | undefined, + siblingParentReport: OnyxEntry, + siblingThreadReport: OnyxEntry, + ): string | undefined => { + if (!siblingTransactionID) { + return undefined; + } + + const isReported = !!siblingTransaction?.reportID && siblingTransaction.reportID !== CONST.REPORT.UNREPORTED_REPORT_ID; + + // A report holding a single expense *is* that expense's view, so open it directly rather than its thread. + // Home's "Review expenses" entry point applies the same rule, so stepping back returns the user to the + // screen they came from. + if (isReported && isOneTransactionReport(siblingParentReport)) { + return siblingTransaction?.reportID; + } // Snapshot-backed flows (e.g. Home "Recently added") seed a descriptor per sibling because the sibling // transactions may be absent from the main Onyx collections. Resolve the target sibling lazily here so // we only ever create a thread for the expense the user actually navigates to, then let OpenReport // hydrate it on arrival. - const nextDescriptor = nextTransactionID ? siblingDescriptorsByTransactionID?.[nextTransactionID] : undefined; - if (nextDescriptor) { - requestAnimationFrame(() => { - const nextReportID = getReportIDToOpenForExpense(nextDescriptor, { - introSelected, - conciergeChat, - isSelfTourViewed: guidedSetupAndTourStatus?.isSelfTourViewed, - hasCompletedGuidedSetupFlow: guidedSetupAndTourStatus?.hasCompletedGuidedSetupFlow, - currentUserEmail, - currentUserAccountID, - personalDetails, - }); - markReportRHPWidth(nextReportID, 'wide'); - requestAnimationFrame(() => - startTransition(() => - Navigation.setParams({ - reportID: nextReportID, - reportActionID: undefined, - backTo, - }), - ), - ); - }); - return; + const descriptor: TransactionThreadNavigationDescriptor | undefined = siblingDescriptorsByTransactionID?.[siblingTransactionID]; + if (descriptor) { + return getReportIDToOpenForExpense(descriptor, resolveContext); } - // A thread created before the parent action loads would have no parent, so wait for the fetch. - if (!nextParentReportAction && stageSiblingPress(nextTransactionID, nextTransaction?.reportID)) { - return; + const threadReportID = siblingParentReportAction?.childReportID; + if (threadReportID) { + if (!siblingThreadReport) { + // The thread exists server-side but hasn't been fetched, so materialize it before navigating. + setOptimisticTransactionThread(threadReportID, siblingParentReport?.reportID, siblingParentReportAction?.reportActionID, siblingParentReport?.policyID); + } + return threadReportID; } - const nextThreadReportID = nextParentReportAction?.childReportID; - const navigationParams = { - reportID: nextThreadReportID, - reportActionID: undefined, - backTo, - }; + if (!siblingTransaction) { + return undefined; + } - requestAnimationFrame(() => { - if (nextThreadReportID) { - markReportRHPWidth(nextThreadReportID, 'wide'); - } - // We know that the next thread report exists, it just wasn't fetched to Onyx yet, so we set it optimistically. - if (!nextThreadReport && nextThreadReportID) { - setOptimisticTransactionThread(nextThreadReportID, nextParentReport?.reportID, nextParentReportAction?.reportActionID, nextParentReport?.policyID); - } - // The transaction thread doesn't exist yet, so we should create it - if (!nextThreadReportID) { - const transactionThreadReport = createTransactionThreadReport({ - introSelected, - conciergeChat, - isSelfTourViewed: guidedSetupAndTourStatus?.isSelfTourViewed, - hasCompletedGuidedSetupFlow: guidedSetupAndTourStatus?.hasCompletedGuidedSetupFlow, - currentUserLogin: currentUserEmail ?? '', - currentUserAccountID, - iouReport: nextParentReport, - iouReportAction: nextParentReportAction, - transaction: nextTransaction, - personalDetails, - }); - navigationParams.reportID = transactionThreadReport?.reportID; - } - // Wait for the next frame to ensure Onyx has processed the optimistic data updates from setOptimisticTransactionThread or createTransactionThreadReport before navigating - requestAnimationFrame(() => startTransition(() => Navigation.setParams(navigationParams))); - }); + // No thread yet. The shared resolver creates one, including for an unreported (self-DM) expense, whose IOU + // action lives in the self-DM rather than under report "0". Those used to fall through with no target at + // all and dump the user in their self-DM. + return getReportIDToOpenForExpense( + { + reportID: siblingTransaction.reportID ?? CONST.REPORT.UNREPORTED_REPORT_ID, + transaction: siblingTransaction, + reportAction: siblingParentReportAction, + report: siblingParentReport ?? undefined, + }, + resolveContext, + ); }; - const onPrevious = (e: GestureResponderEvent | KeyboardEvent | undefined) => { - e?.preventDefault(); - - let backTo = Navigation.getActiveRoute(); - if (isFromReviewDuplicates) { - const currentRoute = navigationRef.getCurrentRoute(); - const params = currentRoute?.params as RightModalNavigatorParamList[typeof SCREENS.RIGHT_MODAL.SEARCH_REPORT] | undefined; - backTo = params?.backTo ?? backTo; + /** + * Whether a press on a sibling's arrow can land anywhere, without the side effects `resolveSiblingReportID` + * has (it creates threads). Every resolution path there needs the sibling to be known from at least one of + * a descriptor, an existing thread on its parent action, or its transaction. + * + * The arrows used to be disabled from list *position* alone, with resolvability consulted only inside the + * handler, which bailed silently - an enabled arrow whose press did nothing, with no spinner and no error. + */ + const canResolveSibling = ( + siblingTransactionID: string | undefined, + siblingTransaction: OnyxTypes.Transaction | undefined, + siblingParentReportAction: OnyxTypes.ReportAction | undefined, + ) => { + if (!siblingTransactionID) { + return false; } + // An existing thread or a descriptor resolves on its own, with nothing else needed. + if (!!siblingParentReportAction?.childReportID || !!siblingDescriptorsByTransactionID?.[siblingTransactionID]) { + return true; + } + // Everything else is resolved from the transaction: it is what a thread gets created from. + if (!siblingTransaction) { + return false; + } + // A reported expense can always fall back on its own report, and its parent's actions can still be fetched + // to find (or create) its thread. An unreported one has neither: report "0" isn't a report to open or to + // fetch actions from, and its IOU action lives in the self-DM. Unless that action is already resolved - + // from the self-DM, the search snapshot or a descriptor - a press would have nowhere to go, so don't offer + // an arrow that can't move. + return siblingTransaction.reportID !== CONST.REPORT.UNREPORTED_REPORT_ID || !!siblingParentReportAction; + }; - // See onNext: resolve the target sibling lazily from its descriptor when present. - const prevDescriptor = prevTransactionID ? siblingDescriptorsByTransactionID?.[prevTransactionID] : undefined; - if (prevDescriptor) { - requestAnimationFrame(() => { - const prevReportID = getReportIDToOpenForExpense(prevDescriptor, { - introSelected, - conciergeChat, - isSelfTourViewed: guidedSetupAndTourStatus?.isSelfTourViewed, - hasCompletedGuidedSetupFlow: guidedSetupAndTourStatus?.hasCompletedGuidedSetupFlow, - currentUserEmail, - currentUserAccountID, - personalDetails, - }); - markReportRHPWidth(prevReportID, 'wide'); - requestAnimationFrame(() => - startTransition(() => - Navigation.setParams({ - reportID: prevReportID, - reportActionID: undefined, - backTo, - }), - ), - ); - }); + const navigateToSibling = ( + e: GestureResponderEvent | KeyboardEvent | undefined, + siblingTransactionID: string | undefined, + siblingTransaction: OnyxTypes.Transaction | undefined, + siblingParentReportAction: OnyxTypes.ReportAction | undefined, + siblingParentReport: OnyxEntry, + siblingThreadReport: OnyxEntry, + hasSiblingParentReportActions: boolean, + ) => { + e?.preventDefault(); + const backTo = getBackTo(); + + // A thread created before the parent action loads would have no parent, so wait for the fetch - but only + // when there is a fetch that could produce it. A parent report whose actions are already loaded won't grow + // a creation action by being re-fetched, a descriptor-backed sibling carries its own resolution, and a + // one-transaction report is opened directly; all three fall through to the resolver instead of waiting. + const hasDescriptor = !!siblingTransactionID && !!siblingDescriptorsByTransactionID?.[siblingTransactionID]; + const isSingleExpenseReport = !!siblingTransaction?.reportID && siblingTransaction.reportID !== CONST.REPORT.UNREPORTED_REPORT_ID && isOneTransactionReport(siblingParentReport); + if ( + !siblingParentReportAction && + !hasSiblingParentReportActions && + !hasDescriptor && + !isSingleExpenseReport && + stageSiblingPress(siblingTransactionID, siblingTransaction?.reportID) + ) { return; } - // A thread created before the parent action loads would have no parent, so wait for the fetch. - if (!prevParentReportAction && stageSiblingPress(prevTransactionID, prevTransaction?.reportID)) { + const targetReportID = resolveSiblingReportID(siblingTransactionID, siblingTransaction, siblingParentReportAction, siblingParentReport, siblingThreadReport); + + // Report "0" is the unreported placeholder, not a report that can be opened. Navigating to it lands the user + // on their self-DM (or a "not here" page), so stay put instead. + if (!siblingTransactionID || !targetReportID || targetReportID === CONST.REPORT.UNREPORTED_REPORT_ID) { return; } - const prevThreadReportID = prevParentReportAction?.childReportID; - const navigationParams = { - reportID: prevThreadReportID, - reportActionID: undefined, - backTo, - }; - - requestAnimationFrame(() => { - if (prevThreadReportID) { - markReportRHPWidth(prevThreadReportID, 'wide'); - } - // We know that the previous thread report exists, it just wasn't fetched to Onyx yet, so we set it optimistically. - if (!prevThreadReport && prevThreadReportID) { - setOptimisticTransactionThread(prevThreadReportID, prevParentReport?.reportID, prevParentReportAction?.reportActionID, prevParentReport?.policyID); - } - // The transaction thread doesn't exist yet, so we should create it - if (!prevThreadReportID) { - const transactionThreadReport = createTransactionThreadReport({ - introSelected, - conciergeChat, - isSelfTourViewed: guidedSetupAndTourStatus?.isSelfTourViewed, - hasCompletedGuidedSetupFlow: guidedSetupAndTourStatus?.hasCompletedGuidedSetupFlow, - currentUserLogin: currentUserEmail ?? '', - currentUserAccountID, - iouReport: prevParentReport, - iouReportAction: prevParentReportAction, - transaction: prevTransaction, - personalDetails, - }); - navigationParams.reportID = transactionThreadReport?.reportID; - } - // Wait for the next frame to ensure Onyx has processed the optimistic data updates from setOptimisticTransactionThread or createTransactionThreadReport before navigating - requestAnimationFrame(() => startTransition(() => Navigation.setParams(navigationParams))); - }); + markReportRHPWidth(targetReportID, 'wide'); + // Wait for the next frame to ensure Onyx has processed any optimistic thread data before navigating + requestAnimationFrame(() => startTransition(() => Navigation.setParams({reportID: targetReportID, reportActionID: undefined, anchorTransactionID: siblingTransactionID, backTo}))); }; - // Replays a staged press once its parent action arrives, but only if the user is still where they pressed — + const onNext = (e: GestureResponderEvent | KeyboardEvent | undefined) => + navigateToSibling( + e, + nextTransactionID, + nextTransaction, + nextParentReportAction, + nextTransactionParentReport, + nextThreadReport, + !!reportedParentReportActions?.hasNextParentReportActions, + ); + + const onPrevious = (e: GestureResponderEvent | KeyboardEvent | undefined) => + navigateToSibling( + e, + prevTransactionID, + prevTransaction, + prevParentReportAction, + prevTransactionParentReport, + prevThreadReport, + !!reportedParentReportActions?.hasPrevParentReportActions, + ); + + // Replays a staged press once its parent action arrives, but only if the user is still where they pressed - // this screen stays mounted under a pushed RHP, and resuming from there would yank them out with a stale backTo. useEffect(() => { const pending = pendingSiblingRef.current; @@ -322,17 +429,27 @@ function MoneyRequestReportTransactionsNavigation({currentTransactionID, isFromR // eslint-disable-next-line react-hooks/exhaustive-deps -- onNext/onPrevious are rebuilt every render, so listing them would defeat the dependency list }, [isFocused, nextTransactionID, nextParentReportAction, prevTransactionID, prevParentReportAction]); - if (transactionIDsList.length < 2) { + // Two entries are the minimum for there to be anything to page between, and an anchor that isn't in the list + // means this expense doesn't belong to the active carousel at all. The list belongs to a screen the user has + // since left. Showing arrows then would step to an unrelated expense. + if (transactionIDsList.length < 2 || currentTransactionIndex === -1) { return; } return ( - + + {!shouldDisplayNarrowVersion && ( + + {translate('common.currentOfTotal', {current: currentTransactionIndex + 1, total: transactionIDsList.length})} + + )} + + ); } diff --git a/src/components/MoneyRequestReportView/useMoneyRequestReportActiveTransactionIDs.ts b/src/components/MoneyRequestReportView/useMoneyRequestReportActiveTransactionIDs.ts index 02abfe48df34..2201ff67b620 100644 --- a/src/components/MoneyRequestReportView/useMoneyRequestReportActiveTransactionIDs.ts +++ b/src/components/MoneyRequestReportView/useMoneyRequestReportActiveTransactionIDs.ts @@ -1,50 +1,62 @@ -import {clearActiveTransactionIDs, getActiveTransactionIDs, setActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; +import {CAROUSEL_SOURCE, clearActiveTransactionIDsForSource, getActiveTransactionIDs, setActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; import {navigationRef} from '@libs/Navigation/Navigation'; import SCREENS from '@src/SCREENS'; import {findFocusedRoute} from '@react-navigation/native'; -import {useEffect} from 'react'; +import {useEffect, useRef} from 'react'; /** * When this report is open in the super-wide RHP, seeds the transaction-thread carousel with the * transaction IDs in the order the user sees them, and clears them again on unmount. */ -function useMoneyRequestReportActiveTransactionIDs(visualOrderTransactionIDs: string[]) { - // Primitive proxy for visualOrderTransactionIDs used as the effect dependency below. - // Other callers (e.g. TransactionDuplicateReview.onPreviewPressed) can write to the same - // Onyx key with a different ordering. Using the raw array reference would cause the effect - // to re-fire on every referential change and overwrite those IDs. The joined string ensures - // the effect only re-fires when the actual content changes. +function useMoneyRequestReportActiveTransactionIDs(visualOrderTransactionIDs: string[], reportID: string | undefined) { const visualOrderTransactionIDsKey = visualOrderTransactionIDs.join(','); + const carouselSource = CAROUSEL_SOURCE.report(reportID); + const hasSeededCarouselRef = useRef(false); + useEffect(() => { const focusedRoute = findFocusedRoute(navigationRef.getRootState()); if (focusedRoute?.name !== SCREENS.RIGHT_MODAL.SEARCH_REPORT) { return; } - // Don't take over a snapshot-backed carousel (identified by its sibling descriptors, e.g. the Home - // "Recently added" flow) that belongs to the transaction thread sitting underneath this report. - // Overwriting and then clearing it would drop that carousel when the user navigates back. Row presses - // still seed the correct siblings lazily via useNavigateToTransactionThread. - const {ids: activeIDs, descriptors: activeDescriptors} = getActiveTransactionIDs(); + + const {ids: activeIDs, descriptors: activeDescriptors, source: activeSource} = getActiveTransactionIDs(); if (activeDescriptors) { return; } + + if (visualOrderTransactionIDs.length === 0 || (visualOrderTransactionIDs.length < 2 && activeSource !== carouselSource)) { + return; + } + // A report preview press seeds these arrows in the carousel's order, which can differ from this list's order. // Keep that seed while it still covers exactly these rows, and re-seed only when the rows themselves change. - if (activeIDs && activeIDs.length === visualOrderTransactionIDs.length) { + // A carousel this list already owns is exempt: sorting a column moves the rows the arrows walk without + // changing which rows they are, and freezing the seed at the order it was first written in would leave + // "next" jumping to a row that is no longer below the current one on screen. + if (activeSource !== carouselSource && activeIDs && activeIDs.length === visualOrderTransactionIDs.length) { const activeIDSet = new Set(activeIDs); if (visualOrderTransactionIDs.every((transactionID) => activeIDSet.has(transactionID))) { return; } } - setActiveTransactionIDs(visualOrderTransactionIDs); + + setActiveTransactionIDs(visualOrderTransactionIDs, {source: carouselSource}); + hasSeededCarouselRef.current = true; + // eslint-disable-next-line react-hooks/exhaustive-deps -- visualOrderTransactionIDsKey is an order-sensitive proxy for the array + }, [visualOrderTransactionIDsKey, carouselSource]); + + useEffect(() => { return () => { - clearActiveTransactionIDs(); + if (!hasSeededCarouselRef.current) { + return; + } + hasSeededCarouselRef.current = false; + clearActiveTransactionIDsForSource(carouselSource); }; - // eslint-disable-next-line react-hooks/exhaustive-deps -- visualOrderTransactionIDsKey is a primitive proxy for the array to avoid re-firing on referential-only changes - }, [visualOrderTransactionIDsKey]); + }, [carouselSource]); } export default useMoneyRequestReportActiveTransactionIDs; diff --git a/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx b/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx index 9e21cc804c92..59c937384b99 100644 --- a/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx +++ b/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx @@ -14,7 +14,7 @@ import useThemeStyles from '@hooks/useThemeStyles'; import useTransactionViolations from '@hooks/useTransactionViolations'; import {createTransactionThreadReport, openReport, setOptimisticTransactionThread} from '@libs/actions/Report'; -import {clearActiveTransactionIDs, getActiveTransactionIDs, setActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; +import {CAROUSEL_SOURCE, clearActiveTransactionIDsForSource, getActiveTransactionIDs, setActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import { getAllReportActions, @@ -283,19 +283,23 @@ function MoneyRequestReportPreview({ .filter((pressedTransaction) => !isTransactionPendingDelete(pressedTransaction)) .map((pressedTransaction) => pressedTransaction.transactionID); + // This press owns the carousel it seeds. Without a source the list was unowned, so no screen could + // release it and every other writer was free to overwrite it while the expense was still open. + const carouselSource = CAROUSEL_SOURCE.reportPreview(iouReportID); + if (isSmallScreenWidth && iouReportID) { const {wasPressedFromReport, backTo} = resolvePressOrigin(routeAtPress, `r/${iouReportID}`); const reportRoute = ROUTES.REPORT_WITH_ID.getRoute(iouReportID, undefined, undefined, backTo); if (!wasPressedFromReport) { Navigation.navigate(reportRoute); } - setActiveTransactionIDs(openableTransactionIDs); + setActiveTransactionIDs(openableTransactionIDs, {source: carouselSource}); Navigation.navigate(ROUTES.SEARCH_REPORT.getRoute({reportID: childReportID, backTo: reportRoute})); return; } if (isSmallScreenWidth) { - setActiveTransactionIDs(openableTransactionIDs); + setActiveTransactionIDs(openableTransactionIDs, {source: carouselSource}); Navigation.navigate(ROUTES.SEARCH_REPORT.getRoute({reportID: childReportID, backTo: routeAtPress})); return; } @@ -307,7 +311,7 @@ function MoneyRequestReportPreview({ if (!wasPressedFromReport) { Navigation.navigate(reportRoute); } - const seeded = setActiveTransactionIDs(openableTransactionIDs); + const seeded = setActiveTransactionIDs(openableTransactionIDs, {source: carouselSource}); markReportRHPWidth(childReportID, 'wide'); const release = () => { unmarkReportRHPWidth(childReportID); @@ -317,7 +321,7 @@ function MoneyRequestReportPreview({ if (getActiveTransactionIDs().ids !== openableTransactionIDs) { return; } - clearActiveTransactionIDs(); + clearActiveTransactionIDsForSource(carouselSource); }); }; const timer = setTimeout(() => { @@ -332,7 +336,7 @@ function MoneyRequestReportPreview({ return; } - setActiveTransactionIDs(openableTransactionIDs).then(() => { + setActiveTransactionIDs(openableTransactionIDs, {source: carouselSource}).then(() => { markReportRHPWidth(childReportID, 'wide'); Navigation.navigate(ROUTES.SEARCH_REPORT.getRoute({reportID: childReportID, backTo: routeAtPress})); }); diff --git a/src/components/Search/SearchList/ListItem/TransactionGroupListExpanded.tsx b/src/components/Search/SearchList/ListItem/TransactionGroupListExpanded.tsx index 9e15299628fc..a320342b65f3 100644 --- a/src/components/Search/SearchList/ListItem/TransactionGroupListExpanded.tsx +++ b/src/components/Search/SearchList/ListItem/TransactionGroupListExpanded.tsx @@ -36,7 +36,7 @@ import {createAndOpenSearchTransactionThread, getColumnsToShow, getGroupColumnWi import {isDeletedTransaction, isTransactionPendingDelete} from '@libs/TransactionUtils'; import type {TransactionPreviewData} from '@userActions/Search'; -import {setActiveTransactionIDs} from '@userActions/TransactionThreadNavigation'; +import {CAROUSEL_SOURCE, setActiveTransactionIDs} from '@userActions/TransactionThreadNavigation'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -229,7 +229,7 @@ function TransactionGroupListExpandedImpl({ shouldNavigate: false, }); if (targetReportID) { - openInternalRouteInNewTab(ROUTES.SEARCH_REPORT.getRoute({reportID: targetReportID, backTo}), event); + openInternalRouteInNewTab(ROUTES.SEARCH_REPORT.getRoute({reportID: targetReportID, backTo, anchorTransactionID: transactionItem.transactionID}), event); } return; } @@ -250,7 +250,7 @@ function TransactionGroupListExpandedImpl({ return; } markReportRHPWidth(reportID, 'wide'); - const route = ROUTES.SEARCH_REPORT.getRoute({reportID, backTo}); + const route = ROUTES.SEARCH_REPORT.getRoute({reportID, backTo, anchorTransactionID: transactionItem.transactionID}); if (openInternalRouteInNewTab(route, event)) { return; } @@ -269,13 +269,14 @@ function TransactionGroupListExpandedImpl({ // When opening the transaction thread in RHP we need to find every other ID for the rest of transactions // to display prev/next arrows in RHP for navigation + const carouselOptions = {source: CAROUSEL_SOURCE.search(transactionsQueryJSON?.hash), snapshotHash: transactionsQueryJSON?.hash}; if (isModifiedMousePress(event)) { - setActiveTransactionIDs(siblingTransactionIDs); + setActiveTransactionIDs(siblingTransactionIDs, carouselOptions); navigateToTransactionThread(); return; } - setActiveTransactionIDs(siblingTransactionIDs).then(navigateToTransactionThread); + setActiveTransactionIDs(siblingTransactionIDs, carouselOptions).then(navigateToTransactionThread); }; const onShowMoreButtonPress = () => { diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx index c41b4750d50f..aec4f8946e52 100644 --- a/src/components/Search/index.tsx +++ b/src/components/Search/index.tsx @@ -25,6 +25,13 @@ import {turnOffMobileSelectionMode} from '@libs/actions/MobileSelectionMode'; import {saveLastSearchParams} from '@libs/actions/ReportNavigation'; import type {TransactionPreviewData} from '@libs/actions/Search'; import {consumePageRequestedSearch, setOptimisticDataForTransactionThreadPreview} from '@libs/actions/Search'; +import { + CAROUSEL_SOURCE, + clearActiveTransactionIDsForSource, + disownActiveTransactionIDs, + setActiveTransactionIDs, + shouldRefreshActiveTransactionIDs, +} from '@libs/actions/TransactionThreadNavigation'; import Log from '@libs/Log'; import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; import openInternalRouteInNewTab, {isModifiedMousePress} from '@libs/Navigation/helpers/openInternalRouteInNewTab'; @@ -63,7 +70,7 @@ import { getNavigateToReportsSpans, } from '@libs/telemetry/navigateToReportsSpans'; import {cancelSubmitFollowUpActionSpan, getPendingSubmitFollowUpAction} from '@libs/telemetry/submitFollowUpAction'; -import {isTransactionPendingDelete, shouldShowAttendees} from '@libs/TransactionUtils'; +import {isDeletedTransaction, isTransactionPendingDelete, shouldShowAttendees} from '@libs/TransactionUtils'; import Navigation, {navigationRef} from '@navigation/Navigation'; import type {SearchFullscreenNavigatorParamList} from '@navigation/types'; @@ -600,6 +607,39 @@ function Search({ }, 0); }, [areItemsGrouped, filteredData]); + const carouselSiblingTransactionIDs = useMemo( + () => + (filteredData as SearchListItem[]) + .filter( + (t): t is TransactionListItemType => !!t && isTransactionListItemType(t) && t.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE && !isDeletedTransaction(t), + ) + .map((t) => t.transactionID), + [filteredData], + ); + + // This search results list owns the carousel it seeds. Drilling into a report hands ownership over to that + // report's own list; the refresh effect below then leaves the carousel alone until the user comes back out. + const carouselSource = CAROUSEL_SOURCE.search(hash); + const hasSeededCarouselRef = useRef(false); + + // Hands this list's expenses to the carousel for the expense the user is opening in *this* tab. + // + // It is called at each in-tab navigation rather than once at the top of `onSelectRow`, because a Cmd/Ctrl+click + // opens a background tab without navigating here: seeding up front rewrote the carousel of whatever was already + // open in the RHP, which then paged through unrelated Spend results. Releasing is scoped to this source for the + // same reason - the unscoped clear used to wipe a carousel another screen owned. + const seedCarouselForOpenedExpense = useCallback(() => { + if (carouselSiblingTransactionIDs.length > 1) { + setActiveTransactionIDs(carouselSiblingTransactionIDs, {source: carouselSource, snapshotHash: hash}); + // Mark the seed so the release effect below knows this instance owns a carousel. Without it an instance + // that only ever seeded from a row press skipped its own cleanup and stranded `search:` behind. + hasSeededCarouselRef.current = true; + return; + } + clearActiveTransactionIDsForSource(carouselSource); + hasSeededCarouselRef.current = false; + }, [carouselSiblingTransactionIDs, carouselSource, hash]); + const onSelectRow = useCallback( (item: SearchListItem, transactionPreviewData?: TransactionPreviewData, event?: ModifiedMouseEvent) => { if (item.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) { @@ -608,11 +648,17 @@ function Search({ const isTransactionItem = isTransactionListItemType(item); const backTo = Navigation.getActiveRoute(); + // If we're trying to open a transaction without a transaction thread, let's create the thread and navigate the user if (isTransactionItem && !item?.reportAction?.childReportID) { // If the report is unreported (self DM), we want to open the track expense thread instead of a report with an ID of 0 const shouldOpenTransactionThread = !isOneTransactionReport(item.report) || item.reportID === CONST.REPORT.UNREPORTED_REPORT_ID; const shouldOpenTransactionThreadInNewTab = shouldOpenTransactionThread && isModifiedMousePress(event); + // When opening an expense from the Spend page (flat transaction list), populate the carousel + // with all sibling transactions so prev/next navigation works in the RHP transaction view. + if (shouldOpenTransactionThread && !shouldOpenTransactionThreadInNewTab) { + seedCarouselForOpenedExpense(); + } const targetReportID = createAndOpenSearchTransactionThread({ conciergeChat, getCurrencyDecimals, @@ -629,7 +675,7 @@ function Search({ shouldNavigate: shouldOpenTransactionThread && !shouldOpenTransactionThreadInNewTab, }); if (shouldOpenTransactionThreadInNewTab && targetReportID) { - openInternalRouteInNewTab(ROUTES.SEARCH_REPORT.getRoute({reportID: targetReportID, backTo}), event); + openInternalRouteInNewTab(ROUTES.SEARCH_REPORT.getRoute({reportID: targetReportID, backTo, anchorTransactionID: item.transactionID}), event); } if (shouldOpenTransactionThread) { return; @@ -765,10 +811,13 @@ function Search({ setOptimisticDataForTransactionThreadPreview(transactionItem, transactionPreviewData, getCurrencyDecimals, delegateAccountID, transactionItem?.reportAction?.childReportID); } - const route = ROUTES.SEARCH_REPORT.getRoute({reportID, backTo}); + const route = ROUTES.SEARCH_REPORT.getRoute({reportID, backTo, anchorTransactionID: isTransactionItem ? transactionItem.transactionID : undefined}); if (openInternalRouteInNewTab(route, event)) { return; } + if (isTransactionItem) { + seedCarouselForOpenedExpense(); + } requestAnimationFrame(() => Navigation.navigate(route)); }, [ @@ -785,12 +834,81 @@ function Search({ offset, searchResults?.search?.hasMoreResults, currentSearchKey, + seedCarouselForOpenedExpense, getCurrencyDecimals, conciergeChat, delegateAccountID, ], ); + const carouselSiblingsKey = carouselSiblingTransactionIDs.join(','); + const [activeCarouselTransactionIDs] = useOnyx(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS); + + // This list stays mounted behind the RHP, so it keeps the carousel in step with the results (an expense + // deleted from the list has to leave the carousel too). The active IDs are a dependency, not just a guard, so + // that it re-runs and stands down when another screen takes ownership - see TransactionThreadNavigation.ts. + useEffect(() => { + if (shouldShowLoadingState) { + return; + } + // The release below clears the carousel on the way out, which flips the active IDs and re-runs this effect. + // Without this guard that re-run would immediately re-seed the carousel the user just left behind. + if (!isSearchTopmostFullScreenRoute()) { + return; + } + if (!shouldRefreshActiveTransactionIDs(carouselSource, carouselSiblingTransactionIDs)) { + return; + } + setActiveTransactionIDs(carouselSiblingTransactionIDs, {source: carouselSource, snapshotHash: hash}); + hasSeededCarouselRef.current = true; + // eslint-disable-next-line react-hooks/exhaustive-deps -- carouselSiblingsKey is an order-sensitive proxy for the array, which is rebuilt on every search data change + }, [carouselSiblingsKey, activeCarouselTransactionIDs, carouselSource, hash, shouldShowLoadingState, isFocused]); + + // The effect above seeds the carousel with no row press, so this list has to release it when the user leaves + // for another tab - otherwise the Spend page's expenses page on inside any one-transaction report opened later. + // + // Blur, not unmount: the Spend tab uses `freezeOnBlur` without `unmountOnBlur`, so leaving it for the Inbox + // never unmounts this component. Hence `isFocused` as a dependency. Opening the RHP over Search also blurs it, + // so the release stands down while Search is still the topmost full-screen route, which also keeps a re-sort + // from stripping the arrows of an expense open in the RHP. + // + // Teardown is deliberately separate from the seeding effect: folding it in would run the cleanup on every + // re-seed, and a run that then bailed at one of the guards would leave the carousel cleared. + useEffect(() => { + return () => { + if (!hasSeededCarouselRef.current) { + return; + } + if (isSearchTopmostFullScreenRoute()) { + return; + } + hasSeededCarouselRef.current = false; + clearActiveTransactionIDsForSource(carouselSource); + }; + }, [carouselSource, isFocused]); + + // An unmounting instance always gives up ownership, even while Search is still the topmost full-screen route. + // This page is keyed by the query hash, so sorting, filtering or switching Spend tabs unmounts this instance + // and mounts a new one under `search:`. The blur-time release above stands down in that moment + // (Search is still topmost), which left `search:` owning the carousel with no mounted screen able to + // refresh or release it, so the replacement list could never seed and the stale one kept driving the arrows. + // + // It hands ownership over rather than clearing: the expense open in the RHP keeps its arrows while the new + // results load, instead of losing them for the duration - and for good, when the new results no longer hold + // that expense. The header already drops the arrows on its own once the open expense isn't in the list. + // + // `carouselSource` is constant for an instance's lifetime (the hash is its React key), so this runs on + // unmount only. + useEffect(() => { + return () => { + if (!hasSeededCarouselRef.current) { + return; + } + hasSeededCarouselRef.current = false; + disownActiveTransactionIDs(carouselSource); + }; + }, [carouselSource]); + // getColumnsToShow allocates a fresh array on every call; preserve the previous reference // when contents are equal so downstream consumers don't re-render on Onyx snapshot churn // (e.g. opening a report bumps searchResults.data) that doesn't actually change the columns. diff --git a/src/hooks/useCarouselTransactionIDs.ts b/src/hooks/useCarouselTransactionIDs.ts new file mode 100644 index 000000000000..65441a95a9c0 --- /dev/null +++ b/src/hooks/useCarouselTransactionIDs.ts @@ -0,0 +1,50 @@ +import {isDeletedTransaction, isTransactionPendingDelete} from '@libs/TransactionUtils'; + +import ONYXKEYS from '@src/ONYXKEYS'; +import type * as OnyxTypes from '@src/types/onyx'; +import getEmptyArray from '@src/types/utils/getEmptyArray'; +import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; + +import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; + +import useOnyx from './useOnyx'; + +type CarouselTransactionIDs = { + /** The seeded carousel IDs, minus the expenses that are gone */ + transactionIDs: string[]; + + /** The search snapshot the carousel was seeded from, when it was seeded from one */ + snapshot: OnyxEntry; +}; + +function useCarouselTransactionIDs(): CarouselTransactionIDs { + const [seededTransactionIDs = getEmptyArray()] = useOnyx(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS); + const [snapshotHash] = useOnyx(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_SNAPSHOT_HASH); + const [snapshot] = useOnyx(`${ONYXKEYS.COLLECTION.SNAPSHOT}${snapshotHash}`); + const [siblingDescriptors] = useOnyx(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_THREAD_REPORT_IDS); + + const validTransactionIDsSelector = (allTransactions: OnyxCollection) => + seededTransactionIDs.filter((transactionID) => { + const key = `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}` as const; + + // A live `null` means the expense was deleted, so don't let the stale snapshot copy bring it back. + const liveTransaction = allTransactions?.[key]; + if (liveTransaction === null) { + return false; + } + + // A sibling that hasn't landed in the live collection yet (snapshot-backed flows) is read from the snapshot instead. + const transaction = liveTransaction ?? snapshot?.data?.[key]; + + if (!transaction) { + // Nothing to inspect, so keep the ID only while a descriptor still vouches for the sibling. + return !!siblingDescriptors?.[transactionID]; + } + return !isTransactionPendingDelete(transaction) && !isDeletedTransaction(transaction); + }); + const [validTransactionIDs = getEmptyArray(), transactionsMetadata] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION, {selector: validTransactionIDsSelector}); + + return {transactionIDs: isLoadingOnyxValue(transactionsMetadata) ? seededTransactionIDs : validTransactionIDs, snapshot}; +} + +export default useCarouselTransactionIDs; diff --git a/src/hooks/useMoneyReportHeaderMoreContentVisibility.ts b/src/hooks/useMoneyReportHeaderMoreContentVisibility.ts new file mode 100644 index 000000000000..0bd91309b9d8 --- /dev/null +++ b/src/hooks/useMoneyReportHeaderMoreContentVisibility.ts @@ -0,0 +1,46 @@ +import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; +import {isGroupPolicy} from '@libs/PolicyUtils'; +import {isInvoiceReport as isInvoiceReportUtil} from '@libs/ReportUtils'; + +import type CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; + +import type {ValueOf} from 'type-fest'; + +import useMoneyReportHeaderStatusBar from './useMoneyReportHeaderStatusBar'; +import useOnyx from './useOnyx'; + +type MoneyReportHeaderMoreContentVisibility = { + /** Which status bar to render below the header, if any */ + statusBarType: ValueOf | undefined; + + /** Whether the next step bar should be rendered below the header */ + shouldShowNextStep: boolean; + + /** Whether the more-content row has anything to show on its own */ + hasStatusOrNextStep: boolean; +}; + +/** + * Resolves what the money report header's more-content row (status bar / next step) will display. + * + * The header needs this before it renders, because it decides where the report actions go: they normally sit at + * the end of the more-content row so they line up with its text, but when that row has nothing to show they + * would be stranded alone under the title, and belong in the header row instead. + */ +function useMoneyReportHeaderMoreContentVisibility(reportID: string | undefined): MoneyReportHeaderMoreContentVisibility { + const [moneyRequestReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(reportID)}`); + const [policy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${getNonEmptyStringOnyxID(moneyRequestReport?.policyID)}`); + const {shouldShowStatusBar, statusBarType} = useMoneyReportHeaderStatusBar(reportID, moneyRequestReport?.chatReportID); + + const isInvoiceReport = isInvoiceReportUtil(moneyRequestReport); + const shouldShowNextStep = isGroupPolicy(policy) && !isInvoiceReport && !shouldShowStatusBar; + + return { + statusBarType, + shouldShowNextStep, + hasStatusOrNextStep: shouldShowNextStep || !!statusBarType, + }; +} + +export default useMoneyReportHeaderMoreContentVisibility; diff --git a/src/hooks/useNavigateToTransactionThread.ts b/src/hooks/useNavigateToTransactionThread.ts index a27ee37d3c58..792f97bcf8e4 100644 --- a/src/hooks/useNavigateToTransactionThread.ts +++ b/src/hooks/useNavigateToTransactionThread.ts @@ -4,7 +4,7 @@ import {useWideRHPActions} from '@components/WideRHPContextProvider'; import {createTransactionThreadReport, setOptimisticTransactionThread} from '@libs/actions/Report'; import {setActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; import Navigation from '@libs/Navigation/Navigation'; -import {getIOUActionForTransactionID} from '@libs/ReportActionsUtils'; +import {getExpenseCreationIOUActionForTransactionID} from '@libs/ReportActionsUtils'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; @@ -33,6 +33,9 @@ type NavigateToTransactionThreadParams = { /** Ordered list of sibling transaction IDs used to drive the prev/next carousel in the thread RHP */ siblingTransactionIDs: string[]; + /** Identity of the screen seeding the carousel, so it can later refresh or release only its own list */ + carouselSource?: string; + /** Route to return to when navigating back; defaults to the current active route */ backTo?: string; }; @@ -55,15 +58,22 @@ function useNavigateToTransactionThread() { const [conciergeChat] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); const [guidedSetupAndTourStatus] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: guidedSetupAndTourStatusSelector}); - return ({transactionID, reportActions, report, transaction, siblingTransactionIDs, backTo}: NavigateToTransactionThreadParams) => { - const iouAction = getIOUActionForTransactionID(reportActions, transactionID); + return ({transactionID, reportActions, report, transaction, siblingTransactionIDs, carouselSource, backTo}: NavigateToTransactionThreadParams) => { + // The action that created the expense, not merely one referencing it. In an approved or paid report the + // approval and payment actions carry the same IOUTransactionID, and matching one of those would open its + // system message thread instead of the expense. The carousel this seeds resolves siblings the same way, so + // using the loose lookup here made a row press and a prev/next step onto the same expense disagree. + const iouAction = getExpenseCreationIOUActionForTransactionID(reportActions, transactionID); const routeAtPress = Navigation.getActiveRoute(); const resolvedBackTo = backTo ?? routeAtPress; let reportIDToNavigate = iouAction?.childReportID; - const routeParams: {reportID: string | undefined; reportActionID?: string; backTo?: string} = { + const routeParams: {reportID: string | undefined; reportActionID?: string; backTo?: string; anchorTransactionID?: string} = { reportID: reportIDToNavigate, backTo: resolvedBackTo, + // Anchors the thread to this expense so the header can show the carousel before the thread's own + // parent report action has loaded. + anchorTransactionID: transactionID, }; if (!reportIDToNavigate) { @@ -88,8 +98,10 @@ function useNavigateToTransactionThread() { } // Single transaction report opens in RHP. We seed every sibling transaction ID so the RHP can - // display prev/next arrows for navigation between expenses. - setActiveTransactionIDs(siblingTransactionIDs).then(() => { + // display prev/next arrows for navigation between expenses. The pressed row's own screen takes ownership + // of the carousel: an earlier version kept a broader list (e.g. the Spend page's) alive here, which left + // the report showing a counter and arrows for expenses that weren't in it. + setActiveTransactionIDs(siblingTransactionIDs, {source: carouselSource}).then(() => { // A second press made before this resolves would stack its expense on top of the first. if (Navigation.getActiveRoute() !== routeAtPress) { return; diff --git a/src/languages/de.ts b/src/languages/de.ts index 77210bf49061..b5ed266f6837 100644 --- a/src/languages/de.ts +++ b/src/languages/de.ts @@ -514,6 +514,7 @@ const translations: TranslationDeepObject = { previousYear: 'Vorheriges Jahr', nextYear: 'Nächstes Jahr', avatar: 'Avatar', + currentOfTotal: ({current, total}: {current: number; total: number}) => `${current} von ${total}`, editor: 'Editor', restrictions: 'Beschränkungen', tryAgain: 'Erneut versuchen', diff --git a/src/languages/el.ts b/src/languages/el.ts index da36ef996bf0..ffcadf77e931 100644 --- a/src/languages/el.ts +++ b/src/languages/el.ts @@ -336,6 +336,7 @@ const translations: TranslationDeepObject = { automatic: 'Αυτόματο', showing: 'Εμφανίζονται', of: 'του', + currentOfTotal: ({current, total}: {current: number; total: number}) => `${current} από ${total}`, default: 'Προεπιλογή', update: 'Ενημέρωση', member: 'Μέλος', diff --git a/src/languages/en.ts b/src/languages/en.ts index 9b75c28f0d1f..2716d5e94684 100644 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -380,6 +380,8 @@ const translations = { automatic: 'Automatic', showing: 'Showing', of: 'of', + // @context Carousel pagination counter showing the current item's position out of the total (e.g. "3 of 50"). + currentOfTotal: ({current, total}: {current: number; total: number}) => `${current} of ${total}`, default: 'Default', update: 'Update', member: 'Member', diff --git a/src/languages/es.ts b/src/languages/es.ts index 5a7cdb7afe48..a26b26946946 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -504,6 +504,7 @@ const translations: TranslationDeepObject = { goToConcierge: 'Ir a Concierge', allSet: '¡Todo listo!', enterDigitLabel: ({digitIndex, totalDigits}: {digitIndex: number; totalDigits: number}) => `introducir dígito ${digitIndex} de ${totalDigits}`, + currentOfTotal: ({current, total}: {current: number; total: number}) => `${current} de ${total}`, apiKey: 'Clave API', editor: 'Editor', restrictions: 'Restricciones', diff --git a/src/languages/fr.ts b/src/languages/fr.ts index 4c69c6e0f201..aae84ecae101 100644 --- a/src/languages/fr.ts +++ b/src/languages/fr.ts @@ -513,6 +513,7 @@ const translations: TranslationDeepObject = { previousYear: 'Année précédente', nextYear: 'L’an prochain', avatar: 'Avatar', + currentOfTotal: ({current, total}: {current: number; total: number}) => `${current} sur ${total}`, editor: 'Éditeur', restrictions: 'Restrictions', tryAgain: 'Réessayer', diff --git a/src/languages/it.ts b/src/languages/it.ts index 72700cfbafd2..1a1f1b7deb5b 100644 --- a/src/languages/it.ts +++ b/src/languages/it.ts @@ -513,6 +513,7 @@ const translations: TranslationDeepObject = { previousYear: 'Anno precedente', nextYear: "L'anno prossimo", avatar: 'Avatar', + currentOfTotal: ({current, total}: {current: number; total: number}) => `${current} di ${total}`, editor: 'Editor', restrictions: 'Restrizioni', tryAgain: 'Riprova', diff --git a/src/languages/ja.ts b/src/languages/ja.ts index 1275388be355..ac19dbfa0ef3 100644 --- a/src/languages/ja.ts +++ b/src/languages/ja.ts @@ -512,6 +512,7 @@ const translations: TranslationDeepObject = { previousYear: '前年', nextYear: '来年', avatar: 'アバター', + currentOfTotal: ({current, total}: {current: number; total: number}) => `${total} 件中 ${current} 件目`, editor: '編集者', restrictions: '制限', tryAgain: '再試行', diff --git a/src/languages/nl.ts b/src/languages/nl.ts index 2ea5aa4ad286..0ec20cd78664 100644 --- a/src/languages/nl.ts +++ b/src/languages/nl.ts @@ -513,6 +513,7 @@ const translations: TranslationDeepObject = { previousYear: 'Vorig jaar', nextYear: 'Volgend jaar', avatar: 'Avatar', + currentOfTotal: ({current, total}: {current: number; total: number}) => `${current} van ${total}`, editor: 'Editor', restrictions: 'Beperkingen', tryAgain: 'Probeer het opnieuw', diff --git a/src/languages/pl.ts b/src/languages/pl.ts index 4e2df173645b..92e3f17d8963 100644 --- a/src/languages/pl.ts +++ b/src/languages/pl.ts @@ -516,6 +516,7 @@ const translations: TranslationDeepObject = { previousYear: 'Poprzedni rok', nextYear: 'W przyszłym roku', avatar: 'Avatar', + currentOfTotal: ({current, total}: {current: number; total: number}) => `${current} z ${total}`, editor: 'Edytor', restrictions: 'Ograniczenia', tryAgain: 'Spróbuj ponownie', diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts index 4b9a4c81d21f..03241c8c750a 100644 --- a/src/languages/pt-BR.ts +++ b/src/languages/pt-BR.ts @@ -512,6 +512,7 @@ const translations: TranslationDeepObject = { previousYear: 'Ano anterior', nextYear: 'Ano que vem', avatar: 'Avatar', + currentOfTotal: ({current, total}: {current: number; total: number}) => `${current} de ${total}`, editor: 'Editor', restrictions: 'Restrições', tryAgain: 'Tentar novamente', diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts index 3e66dcc9fc45..23b46af5f6a7 100644 --- a/src/languages/zh-hans.ts +++ b/src/languages/zh-hans.ts @@ -508,6 +508,7 @@ const translations: TranslationDeepObject = { previousYear: '上一年', nextYear: '明年', avatar: '头像', + currentOfTotal: ({current, total}: {current: number; total: number}) => `第 ${current} 项(共 ${total} 项)`, editor: '编辑', restrictions: '限制', tryAgain: '重试', diff --git a/src/libs/ExportOnyxState/masking.ts b/src/libs/ExportOnyxState/masking.ts index d6312161bfdd..e4b779bae3d9 100644 --- a/src/libs/ExportOnyxState/masking.ts +++ b/src/libs/ExportOnyxState/masking.ts @@ -361,6 +361,7 @@ const safeOnyxKeys = new Set([ ONYXKEYS.SUBSCRIPTION_RETRY_BILLING_STATUS_FAILED, ONYXKEYS.SUBSCRIPTION_RETRY_BILLING_STATUS_PENDING, ONYXKEYS.SUBSCRIPTION_RETRY_BILLING_STATUS_SUCCESSFUL, + ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_SNAPSHOT_HASH, ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS, ONYXKEYS.TRAVEL_BILLING_STATEMENT, ONYXKEYS.VALIDATE_DOMAIN_TWO_FACTOR_CODE, diff --git a/src/libs/Navigation/types.ts b/src/libs/Navigation/types.ts index 2a3238e5335b..7786455e58de 100644 --- a/src/libs/Navigation/types.ts +++ b/src/libs/Navigation/types.ts @@ -3062,6 +3062,7 @@ type RightModalNavigatorParamList = { [SCREENS.RIGHT_MODAL.SEARCH_REPORT]: { reportID: string; reportActionID?: string; + anchorTransactionID?: string; shouldReplaceWithExpenseReportRHP?: string; // eslint-disable-next-line no-restricted-syntax -- `backTo` usages in this file are legacy. Do not add new `backTo` params to screens. See contributingGuides/NAVIGATION.md backTo?: Routes; diff --git a/src/libs/ReportActionsUtils.ts b/src/libs/ReportActionsUtils.ts index 74e8ae7399b3..68d0330c368b 100644 --- a/src/libs/ReportActionsUtils.ts +++ b/src/libs/ReportActionsUtils.ts @@ -2844,6 +2844,43 @@ function getIOUActionForTransactionID(reportActions: ReportAction[], transaction return reportActions.find((reportAction) => isMatch(reportAction) && isLive(reportAction)) ?? firstMatch; } +/** IOU action types that reference a transaction without being the action that created the expense. */ +const nonExpenseCreationIOUTypes = new Set>([ + CONST.IOU.REPORT_ACTION_TYPE.PAY, + CONST.IOU.REPORT_ACTION_TYPE.APPROVE, + CONST.IOU.REPORT_ACTION_TYPE.REJECT, + CONST.IOU.REPORT_ACTION_TYPE.CANCEL, + CONST.IOU.REPORT_ACTION_TYPE.DELETE, +]); + +/** + * The transaction an action created, or undefined when the action merely references one. + * + * Several IOU actions carry the same `IOUTransactionID`. Paying, approving or rejecting an expense all reference + * the transaction they act on, and each has its own thread. Callers that want the expense itself (to open it, or + * to page to it in the prev/next carousel) must not match those, or they land the user on, say, the + * "marked as paid" system message thread instead of the expense. + * + * Actions with no `type` are kept: legacy IOU actions predate the field and are expense-creating. + */ +function getExpenseCreationTransactionID(reportAction: ReportAction): string | undefined { + if (!isMoneyRequestAction(reportAction)) { + return undefined; + } + const originalMessage = getOriginalMessage(reportAction); + if (!originalMessage?.IOUTransactionID) { + return undefined; + } + return !originalMessage.type || !nonExpenseCreationIOUTypes.has(originalMessage.type) ? originalMessage.IOUTransactionID : undefined; +} + +/** + * Get the action that created an expense, for a transactionID, from the given reportActions. + */ +function getExpenseCreationIOUActionForTransactionID(reportActions: ReportAction[], transactionID: string): OnyxEntry { + return reportActions.find((reportAction) => getExpenseCreationTransactionID(reportAction) === transactionID); +} + /** * Get the track expense actionable whisper of the corresponding track expense */ @@ -5280,6 +5317,8 @@ export { getLatestConciergeFeedbackActionIDFromReportActions, getIOUActionForReportID, getIOUActionForTransactionID, + getExpenseCreationIOUActionForTransactionID, + getExpenseCreationTransactionID, getIOUReportIDFromReportActionPreview, getLastVisibleAction, getLastVisibleActionIncludingTransactionThread, diff --git a/src/libs/TransactionThreadNavigationUtils.ts b/src/libs/TransactionThreadNavigationUtils.ts index 93c90aa1b993..c609c7572efb 100644 --- a/src/libs/TransactionThreadNavigationUtils.ts +++ b/src/libs/TransactionThreadNavigationUtils.ts @@ -3,7 +3,7 @@ import type {IntroSelected, PersonalDetailsList, Report, ReportAction, Transacti import type {OnyxEntry} from 'react-native-onyx'; import {createTransactionThreadReport, setOptimisticTransactionThread} from './actions/Report'; -import {getIOUActionForReportID} from './ReportActionsUtils'; +import {getAllReportActions, getExpenseCreationIOUActionForTransactionID} from './ReportActionsUtils'; import {findSelfDMReportID, getReportOrDraftReport} from './ReportUtils'; import {isExpenseUnreported} from './TransactionUtils'; @@ -37,6 +37,20 @@ type ResolveReportContext = { hasCompletedGuidedSetupFlow: boolean | undefined; }; +/** + * The action that created an expense, looked up in a report's own actions. + * + * Deliberately not `getIOUActionForReportID`: paying, approving or rejecting an expense produces further IOU + * actions carrying the same `IOUTransactionID`, each with its own thread, and opening one of those shows a system + * message instead of the expense. + */ +function getExpenseCreationIOUActionForReportID(reportID: string | undefined, transactionID: string | undefined): OnyxEntry { + if (!reportID || !transactionID) { + return undefined; + } + return getExpenseCreationIOUActionForTransactionID(Object.values(getAllReportActions(reportID)), transactionID); +} + /** * Resolves which report to open for a single expense, creating its transaction thread only if necessary. * @@ -47,23 +61,21 @@ function getReportIDToOpenForExpense(expense: TransactionThreadNavigationDescrip const {transaction, reportID} = expense; const isUnreported = isExpenseUnreported(transaction); - // Unreported (tracked) expenses live in the self-DM; their transaction thread is the expense view to open, - // since report "0" does not exist. Prefer the snapshot-resolved thread, but fall back to local report actions - // so an optimistic (offline) expense — absent from the snapshot — still resolves to its real thread. - if (isUnreported) { - return expense.reportAction?.childReportID ?? getIOUActionForReportID(findSelfDMReportID(), transaction.transactionID)?.childReportID ?? reportID; - } - // Prefer the transaction thread resolved from the Search snapshot. The main reportActions_ collection - // may be empty (e.g. right after clearing Onyx) so getIOUActionForReportID can fail and incorrectly + // may be empty (e.g. right after clearing Onyx) so the local lookup can fail and incorrectly // fall back to the whole parent expense report; the snapshot already carries the correct childReportID. if (expense.reportAction?.childReportID) { return expense.reportAction.childReportID; } + // An unreported (tracked) expense's IOU action lives in the self-DM, not under report "0", so that is where + // its thread has to be resolved from. Falling back to local report actions also lets an optimistic (offline) + // expense — absent from the snapshot — resolve to its real thread. + const iouActionReportID = isUnreported ? findSelfDMReportID() : reportID; + // Prefer the live action from the main collection (it may carry a newer childReportID), fall back to the // snapshot action carried on the descriptor so a snapshot-only expense can still resolve/create its thread. - const iouAction = getIOUActionForReportID(reportID, transaction.transactionID) ?? expense.reportAction; + const iouAction = getExpenseCreationIOUActionForReportID(iouActionReportID, transaction.transactionID) ?? expense.reportAction; if (!iouAction) { return reportID; } @@ -71,6 +83,10 @@ function getReportIDToOpenForExpense(expense: TransactionThreadNavigationDescrip return iouAction.childReportID; } + // No thread yet, so create one. An unreported expense used to return report "0" here instead, which is not a + // report that can be opened: the prev/next carousel enabled its arrow from the transaction alone and then had + // nowhere to navigate, so the press did nothing. createTransactionThreadReport recognizes an unreported + // transaction and parents the new thread to the self-DM. const transactionThreadReport = createTransactionThreadReport({ introSelected: context.introSelected, conciergeChat: context.conciergeChat, @@ -78,7 +94,9 @@ function getReportIDToOpenForExpense(expense: TransactionThreadNavigationDescrip hasCompletedGuidedSetupFlow: context.hasCompletedGuidedSetupFlow, currentUserLogin: context.currentUserEmail ?? '', currentUserAccountID: context.currentUserAccountID, - iouReport: getReportOrDraftReport(reportID) ?? expense.report, + // An unreported expense has no parent expense report to build the thread from; report "0" is a + // placeholder, not a row in the collection. + iouReport: isUnreported ? undefined : (getReportOrDraftReport(reportID) ?? expense.report), iouReportAction: iouAction, transaction, personalDetails: context.personalDetails, diff --git a/src/libs/actions/TransactionThreadNavigation.ts b/src/libs/actions/TransactionThreadNavigation.ts index e84373b19b47..026ec10e4d70 100644 --- a/src/libs/actions/TransactionThreadNavigation.ts +++ b/src/libs/actions/TransactionThreadNavigation.ts @@ -15,11 +15,66 @@ import Onyx from 'react-native-onyx'; * (e.g. the Home "Recently added" section) where the sibling transactions are not guaranteed to live in the * main Onyx collections, so the prev/next navigation can't re-derive the thread report from them. When the map * is provided, navigation resolves (and lazily creates) each sibling's thread on demand from its descriptor. + * + * The carousel is a single global value written by several different screens (the Spend page's flat expense + * list, a report's own transaction list, the Home "Recently added" widget, duplicate review). To keep those + * writers from clobbering each other, every writer stamps the list with a `source` that identifies it, and + * only ever refreshes or clears a carousel it still owns. Ownership lives in module state rather than Onyx + * because it only ever arbitrates writes within a single JS session. + */ + +/** + * Identities for the screens that can seed the carousel. Every writer stamps its list with one of these so it + * can later refresh or clear only a carousel it still owns. */ +const CAROUSEL_SOURCE = { + /** A report's own transaction list */ + report: (reportID: string | undefined) => `report:${reportID}`, + + /** + * A row pressed inside a report's transaction list. Distinct from `report` so that the list tearing down + * behind the opened expense doesn't clear the carousel it just handed to that expense. + */ + reportRow: (reportID: string | undefined) => `reportRow:${reportID}`, + + /** A search results list (the Spend page and its grouped variants) */ + search: (hash: number | undefined) => `search:${hash}`, + + /** The Home "Recently added" widget */ + homeRecentlyAdded: 'home:recentlyAdded', + + /** The Home "Review X expenses" row */ + homeReviewFlagged: 'home:reviewFlagged', + + /** A transaction row pressed inside a report preview in a chat */ + reportPreview: (reportID: string | undefined) => `reportPreview:${reportID}`, + + /** The duplicate-review flow */ + duplicateReview: (transactionID: string | undefined) => `duplicateReview:${transactionID}`, +} as const; let lastSetIDs: string[] | null = null; +let lastSetSource: string | null = null; +let lastSetSnapshotHash: number | null = null; let lastSetDescriptors: Record | null = null; +type SetActiveTransactionIDsOptions = { + /** + * Stable identity of the screen that owns this carousel, e.g. `search:` or `report:`. + * Writers pass their own source so they can later refresh or clear the carousel only while they still own it. + */ + source?: string; + + /** + * Hash of the search snapshot backing these IDs. The carousel falls back to that snapshot when a sibling + * hasn't landed in the live Onyx collections yet. + */ + snapshotHash?: number; + + /** Optional map of transactionID -> sibling descriptor for snapshot-backed flows. */ + descriptors?: Record; +}; + function areDescriptorMapsEqual(a: Record | null, b: Record | null) { if (a === b) { return true; @@ -44,38 +99,130 @@ function areDescriptorMapsEqual(a: Record id === b.at(index)); +} + /** - * Idempotent: skips the Onyx write when the IDs and the descriptor map haven't changed. + * Idempotent: skips the Onyx write when the IDs, source, snapshot hash, and descriptor map haven't changed. * This lets callers (e.g. useEffect in MoneyRequestReportTransactionList) fire * freely without worrying about referential equality of the input array. */ -function setActiveTransactionIDs(ids: string[], siblingDescriptorsByTransactionID?: Record) { - const nextDescriptors = siblingDescriptorsByTransactionID ?? null; - const sameIDs = lastSetIDs?.length === ids.length && lastSetIDs.every((id, i) => id === ids.at(i)); - const isUnchanged = sameIDs && areDescriptorMapsEqual(lastSetDescriptors, nextDescriptors); +function setActiveTransactionIDs(ids: string[], {source, snapshotHash, descriptors}: SetActiveTransactionIDsOptions = {}) { + const nextSource = source ?? null; + const nextSnapshotHash = snapshotHash ?? null; + const nextDescriptors = descriptors ?? null; + const isUnchanged = + areIDListsEqual(lastSetIDs, ids) && lastSetSource === nextSource && lastSetSnapshotHash === nextSnapshotHash && areDescriptorMapsEqual(lastSetDescriptors, nextDescriptors); // Track the newest array even when the write is skipped: callers compare this reference by identity to tell // "my seed is still active" from "someone re-seeded after me", and a stale one makes a newer seed look older. lastSetIDs = ids; + lastSetSource = nextSource; + lastSetSnapshotHash = nextSnapshotHash; lastSetDescriptors = nextDescriptors; if (isUnchanged) { return Promise.resolve(); } - return Promise.all([Onyx.set(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS, ids), Onyx.set(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_THREAD_REPORT_IDS, nextDescriptors)]); + return Promise.all([ + Onyx.set(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS, ids), + Onyx.set(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_SNAPSHOT_HASH, nextSnapshotHash), + Onyx.set(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_THREAD_REPORT_IDS, nextDescriptors), + ]); } /** - * Returns the currently active transaction IDs and sibling descriptors. Used by screens that would otherwise - * take over the carousel context (e.g. a money request report opened on top of an existing transaction thread) - * so they can detect a snapshot-backed carousel (one with descriptors) and avoid clobbering it. + * Returns the currently active transaction IDs, their owner, the backing snapshot hash, and sibling descriptors. + * Used by screens that would otherwise take over the carousel context (e.g. a money request report opened on top + * of an existing transaction thread) so they can detect a snapshot-backed carousel (one with descriptors) and + * avoid clobbering it. It returns every field `setActiveTransactionIDs` accepts so a screen that temporarily + * takes the carousel over (duplicate review) can hand the previous owner's carousel back intact. */ -function getActiveTransactionIDs(): {ids: string[] | null; descriptors: Record | null} { - return {ids: lastSetIDs, descriptors: lastSetDescriptors}; +function getActiveTransactionIDs(): { + ids: string[] | null; + descriptors: Record | null; + source: string | null; + snapshotHash: number | null; +} { + return {ids: lastSetIDs, descriptors: lastSetDescriptors, source: lastSetSource, snapshotHash: lastSetSnapshotHash}; +} + +/** + * Whether a writer that stays mounted behind the RHP (e.g. the Spend page's list under an open expense) should + * push a refreshed list into the carousel. + * + * It may only do so when it still owns the carousel, or when nothing owns it yet. Once the user drills into a + * screen that seeds its own carousel, such as a report's transaction list, that screen becomes the owner and the + * background list must leave it alone until the user comes back out to it. + */ +function shouldRefreshActiveTransactionIDs(source: string, ids: string[]): boolean { + if (!lastSetIDs?.length) { + // Nothing to defer to: only seed a carousel for a list there is actually something to page through. + return ids.length > 1; + } + + if (!lastSetSource) { + return !areIDListsEqual(lastSetIDs, ids); + } + if (lastSetSource !== source) { + return false; + } + + return !areIDListsEqual(lastSetIDs, ids); } function clearActiveTransactionIDs() { lastSetIDs = null; + lastSetSource = null; + lastSetSnapshotHash = null; lastSetDescriptors = null; - return Promise.all([Onyx.set(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS, null), Onyx.set(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_THREAD_REPORT_IDS, null)]); + return Promise.all([ + Onyx.set(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS, null), + Onyx.set(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_SNAPSHOT_HASH, null), + Onyx.set(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_THREAD_REPORT_IDS, null), + ]); +} + +/** + * Clears the carousel only when `source` still owns it. + * + * A writer that unmounts must not wipe a carousel another screen has since taken over. That is how the arrows + * used to vanish when a screen re-seeded the list while the previous owner was tearing down. + */ +function clearActiveTransactionIDsForSource(source: string) { + if (lastSetSource !== source) { + return Promise.resolve(); + } + return clearActiveTransactionIDs(); +} + +/** + * Gives up ownership of the carousel without clearing it, for a writer that unmounts while the list it seeded is + * still driving the arrows of an expense open on top of it. + * + * Search is keyed by its query hash, so re-sorting or re-filtering unmounts one list and mounts another. Clearing + * on the way out stripped the open expense's arrows until the replacement finished loading, and left them gone for + * good when the new results no longer contained that expense. Dropping only the stamp keeps the arrows working in + * the meantime and lets the replacement take the carousel over once it has results of its own. + */ +function disownActiveTransactionIDs(source: string) { + if (lastSetSource !== source) { + return; + } + lastSetSource = null; } -export {setActiveTransactionIDs, clearActiveTransactionIDs, getActiveTransactionIDs}; +export { + setActiveTransactionIDs, + clearActiveTransactionIDs, + clearActiveTransactionIDsForSource, + disownActiveTransactionIDs, + getActiveTransactionIDs, + shouldRefreshActiveTransactionIDs, + CAROUSEL_SOURCE, +}; diff --git a/src/pages/TransactionDuplicate/DuplicateTransactionItem.tsx b/src/pages/TransactionDuplicate/DuplicateTransactionItem.tsx index 261ca3982d5e..012f1f347f50 100644 --- a/src/pages/TransactionDuplicate/DuplicateTransactionItem.tsx +++ b/src/pages/TransactionDuplicate/DuplicateTransactionItem.tsx @@ -32,7 +32,7 @@ type DuplicateTransactionItemProps = { isSelected: boolean; shouldShowSelection?: boolean; onSelectTransaction: (transactionID: string) => void; - onPreviewPressed: (reportID: string) => void; + onPreviewPressed: (reportID: string, transactionID: string | undefined) => void; }; function DuplicateTransactionItem({transaction, isLastItem, isSelected, shouldShowSelection = true, onSelectTransaction, onPreviewPressed}: DuplicateTransactionItemProps) { @@ -67,7 +67,7 @@ function DuplicateTransactionItem({transaction, isLastItem, isSelected, shouldSh } if (action.childReportID) { - onPreviewPressed(action.childReportID); + onPreviewPressed(action.childReportID, transaction?.transactionID); return; } @@ -87,7 +87,7 @@ function DuplicateTransactionItem({transaction, isLastItem, isSelected, shouldSh return; } - onPreviewPressed(transactionThreadReport.reportID); + onPreviewPressed(transactionThreadReport.reportID, transaction?.transactionID); }; if (!action || !report || !transaction) { diff --git a/src/pages/TransactionDuplicate/DuplicateTransactionsList.tsx b/src/pages/TransactionDuplicate/DuplicateTransactionsList.tsx index 6cd5b1b37df2..21474a464da1 100644 --- a/src/pages/TransactionDuplicate/DuplicateTransactionsList.tsx +++ b/src/pages/TransactionDuplicate/DuplicateTransactionsList.tsx @@ -15,7 +15,7 @@ type DuplicateTransactionsListProps = { selectedTransactionID?: string; shouldShowSelection?: boolean; onSelectTransaction: (transactionID: string) => void; - onPreviewPressed: (reportID: string) => void; + onPreviewPressed: (reportID: string, transactionID: string | undefined) => void; }; function DuplicateTransactionsList({transactions, selectedTransactionID, shouldShowSelection = true, onSelectTransaction, onPreviewPressed}: DuplicateTransactionsListProps) { diff --git a/src/pages/TransactionDuplicate/DynamicReviewPage.tsx b/src/pages/TransactionDuplicate/DynamicReviewPage.tsx index 44db85a6cfb5..b053d14073b4 100644 --- a/src/pages/TransactionDuplicate/DynamicReviewPage.tsx +++ b/src/pages/TransactionDuplicate/DynamicReviewPage.tsx @@ -21,7 +21,7 @@ import useTransactionViolations from '@hooks/useTransactionViolations'; import {clearDeleteTransactionNavigateBackUrl, openReport} from '@libs/actions/Report'; import {dismissDuplicateTransactionViolation, getDuplicateTransactionDetails} from '@libs/actions/Transaction'; -import {setActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; +import {CAROUSEL_SOURCE, getActiveTransactionIDs, setActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackRouteProp} from '@libs/Navigation/PlatformStackNavigation/types'; import type {TransactionDuplicateNavigatorParamList} from '@libs/Navigation/types'; @@ -30,6 +30,7 @@ import {getLinkedTransactionID, getReportAction} from '@libs/ReportActionsUtils' import {isReportIDApproved, isSettled} from '@libs/ReportUtils'; import {doesDeleteNavigateBackUrlIncludeSpecificDuplicatesReview, getParentReportActionDeletionStatus, hasLoadedReportActions, isThreadReportDeleted} from '@libs/TransactionNavigationUtils'; import {getReviewNavigationRoute} from '@libs/TransactionPreviewUtils'; +import type {TransactionThreadNavigationDescriptor} from '@libs/TransactionThreadNavigationUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -66,13 +67,28 @@ function DynamicReviewPage() { const [allTransactions] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION); const [allTransactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS); const [transactionIDsList = getEmptyArray()] = useOnyx(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS); + // Read alongside the IDs so the fallback below can hand a snapshot-backed carousel back intact. The module + // mirror is empty after a reload (it only ever lives for one JS session), and rebuilding from the IDs alone + // dropped the hash and the descriptors, which is exactly the data the siblings are resolved from. + const [activeSnapshotHash] = useOnyx(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_SNAPSHOT_HASH); + const [activeSiblingDescriptors] = useOnyx(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_THREAD_REPORT_IDS); const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); const [conciergeChat] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); const [guidedSetupAndTourStatus] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: guidedSetupAndTourStatusSelector}); const [rules] = useOnyx(ONYXKEYS.COLLECTION.RULE); - const originalTransactionIDsListRef = useRef(null); + // The whole carousel this screen is about to displace, so the restore effect below can hand it back exactly as + // it was. The owner has to be the screen the carousel came from (Search, or a report's list): re-seeding the + // previous screen's list under duplicate review's own source would leave that screen unable to refresh or + // release its own carousel. The snapshot hash and descriptors have to come back too, or a snapshot-backed + // carousel loses the data its siblings are resolved from. + const displacedCarouselRef = useRef<{ + ids: string[]; + source: string | undefined; + snapshotHash: number | undefined; + descriptors: Record | undefined; + } | null>(null); const isASAPSubmitBetaEnabled = isBetaEnabled(CONST.BETAS.ASAP_SUBMIT); const reportAction = getReportAction(report?.parentReportID, report?.parentReportActionID); @@ -171,23 +187,32 @@ function DynamicReviewPage() { useFocusEffect( useCallback(() => { - if (!originalTransactionIDsListRef.current) { + const displaced = displacedCarouselRef.current; + if (!displaced) { return; } - setActiveTransactionIDs(originalTransactionIDsListRef.current); + setActiveTransactionIDs(displaced.ids, {source: displaced.source, snapshotHash: displaced.snapshotHash, descriptors: displaced.descriptors}); }, []), ); - const onPreviewPressed = (reportID: string) => { + const onPreviewPressed = (reportID: string, pressedTransactionID: string | undefined) => { + // Capture the carousel we are about to displace before overwriting it, on the first press only, so the + // restore effect re-seeds what was active when this screen mounted. setActiveTransactionIDs updates the + // module mirror synchronously, so reading it afterwards would only ever return our own write back. + if (!displacedCarouselRef.current) { + const active = getActiveTransactionIDs(); + displacedCarouselRef.current = { + ids: active.ids ?? transactionIDsList, + source: active.source ?? undefined, + snapshotHash: active.snapshotHash ?? activeSnapshotHash, + descriptors: active.descriptors ?? activeSiblingDescriptors, + }; + } + const siblingTransactionIDsList = transactions.map((transaction) => transaction.transactionID); - setActiveTransactionIDs(siblingTransactionIDsList).then(() => { - Navigation.navigate(ROUTES.SEARCH_REPORT.getRoute({reportID, backTo: Navigation.getActiveRoute()})); + setActiveTransactionIDs(siblingTransactionIDsList, {source: CAROUSEL_SOURCE.duplicateReview(transactionID)}).then(() => { + Navigation.navigate(ROUTES.SEARCH_REPORT.getRoute({reportID, backTo: Navigation.getActiveRoute(), anchorTransactionID: pressedTransactionID})); }); - // Store the initial value of transactionIDsList and only save it when the item is clicked for the first time - // to ensure that transactionIDsList reflects its original value when this component is mounted - if (!originalTransactionIDsListRef.current) { - originalTransactionIDsListRef.current = transactionIDsList; - } }; const currentTransactionViolations = transactionIDs.map((id) => ({ diff --git a/src/pages/home/ForYouSection/useReviewFlaggedExpenses.ts b/src/pages/home/ForYouSection/useReviewFlaggedExpenses.ts index 826181772b36..83d806751b07 100644 --- a/src/pages/home/ForYouSection/useReviewFlaggedExpenses.ts +++ b/src/pages/home/ForYouSection/useReviewFlaggedExpenses.ts @@ -2,6 +2,7 @@ import useNavigateToTransactionThread from '@hooks/useNavigateToTransactionThrea import useOnyx from '@hooks/useOnyx'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; +import {CAROUSEL_SOURCE, setActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import Navigation from '@libs/Navigation/Navigation'; import {isOneTransactionReport} from '@libs/ReportUtils'; @@ -170,16 +171,23 @@ function useReviewFlaggedExpenses(): ReviewFlaggedExpenses { const firstFlaggedReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${firstFlaggedExpense.reportID}`]; const firstFlaggedTransaction = allTransactions?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${firstFlaggedExpense.transactionID}`]; - // With a single flagged expense the review carousel has nothing to navigate between, and for a - // one-transaction report the transaction thread is a redundant duplicate of the report itself. - // Gate on the report's transaction count (not its type) so a lone flagged expense inside a - // multi-transaction report still opens that expense's thread rather than the whole report. - if (flaggedExpenses.length === 1 && isOneTransactionReport(firstFlaggedReport)) { - Navigation.navigate( - shouldUseNarrowLayout - ? ROUTES.REPORT_WITH_ID.getRoute(firstFlaggedExpense.reportID, undefined, undefined, ROUTES.HOME) - : ROUTES.EXPENSE_REPORT_RHP.getRoute({reportID: firstFlaggedExpense.reportID, backTo: ROUTES.HOME}), - ); + const siblingTransactionIDs = flaggedExpenses.map((flaggedExpense) => flaggedExpense.transactionID); + + if (isOneTransactionReport(firstFlaggedReport) && (flaggedExpenses.length === 1 || !shouldUseNarrowLayout)) { + // A lone flagged expense has nothing to page between, so it skips seeding the carousel entirely. + const shouldSeedCarousel = flaggedExpenses.length > 1; + const openReport = () => + Navigation.navigate( + shouldUseNarrowLayout + ? ROUTES.REPORT_WITH_ID.getRoute(firstFlaggedExpense.reportID, undefined, undefined, ROUTES.HOME) + : ROUTES.EXPENSE_REPORT_RHP.getRoute({reportID: firstFlaggedExpense.reportID, backTo: ROUTES.HOME}), + ); + + if (!shouldSeedCarousel) { + openReport(); + return; + } + setActiveTransactionIDs(siblingTransactionIDs, {source: CAROUSEL_SOURCE.homeReviewFlagged}).then(openReport); return; } @@ -188,7 +196,8 @@ function useReviewFlaggedExpenses(): ReviewFlaggedExpenses { reportActions: Object.values(firstFlaggedReportActions ?? {}), report: firstFlaggedReport, transaction: firstFlaggedTransaction, - siblingTransactionIDs: flaggedExpenses.map((flaggedExpense) => flaggedExpense.transactionID), + siblingTransactionIDs, + carouselSource: CAROUSEL_SOURCE.homeReviewFlagged, backTo: ROUTES.HOME, }); } diff --git a/src/pages/home/RecentlyAddedSection/index.tsx b/src/pages/home/RecentlyAddedSection/index.tsx index 14231d5b6183..931acf6c286d 100644 --- a/src/pages/home/RecentlyAddedSection/index.tsx +++ b/src/pages/home/RecentlyAddedSection/index.tsx @@ -11,7 +11,7 @@ import useOnyx from '@hooks/useOnyx'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useThemeStyles from '@hooks/useThemeStyles'; -import {setActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; +import {CAROUSEL_SOURCE, setActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; import Navigation from '@libs/Navigation/Navigation'; import {buildQueryStringFromFilterFormValues} from '@libs/SearchQueryUtils'; import type {TransactionThreadNavigationDescriptor} from '@libs/TransactionThreadNavigationUtils'; @@ -83,9 +83,12 @@ function RecentlyAddedSection() { // Each row opens a single-expense view that always lands in (Wide) RHP on both layouts so the carousel // arrows are available. Marking the report as an expense lets the RHP open wide immediately, before its // data loads, instead of flickering from narrow to wide. - setActiveTransactionIDs(siblingTransactionIDs, siblingDescriptorsByTransactionID).then(() => { + setActiveTransactionIDs(siblingTransactionIDs, {source: CAROUSEL_SOURCE.homeRecentlyAdded, descriptors: siblingDescriptorsByTransactionID}).then(() => { markReportRHPWidth(reportID, 'wide'); - Navigation.navigate(ROUTES.SEARCH_REPORT.getRoute({reportID, backTo: ROUTES.HOME})); + // The anchor is what lets the header show the carousel on a cold open: getReportIDToOpenForExpense + // resolves the snapshot's childReportID without materializing the thread, so the header has no + // transaction of its own until OpenReport round-trips, and the counter would pop in only after that. + Navigation.navigate(ROUTES.SEARCH_REPORT.getRoute({reportID, backTo: ROUTES.HOME, anchorTransactionID: expense.transactionID})); }); }; diff --git a/src/pages/home/RecentlyAddedSection/useRecentlyAddedData.ts b/src/pages/home/RecentlyAddedSection/useRecentlyAddedData.ts index 4b8f82966c7e..6bd3d3ff6f70 100644 --- a/src/pages/home/RecentlyAddedSection/useRecentlyAddedData.ts +++ b/src/pages/home/RecentlyAddedSection/useRecentlyAddedData.ts @@ -4,7 +4,7 @@ import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import {search} from '@libs/actions/Search'; -import {getIOUActionForTransactionID} from '@libs/ReportActionsUtils'; +import {getExpenseCreationIOUActionForTransactionID} from '@libs/ReportActionsUtils'; import {buildQueryStringFromFilterFormValues, buildSearchQueryJSON} from '@libs/SearchQueryUtils'; import {getAmount, getCreated, getCurrency, getMerchantName, getTransactionPendingAction} from '@libs/TransactionUtils'; @@ -271,7 +271,7 @@ function useRecentlyAddedData(): RecentlyAddedData { // displayed amount must be negated for them (mirrors the Search transaction list). amount: getAmount(sourceTransaction, isFromExpenseReport, isFromTrackedExpense), currency: getCurrency(sourceTransaction), - reportAction: getIOUActionForTransactionID(snapshotReportActions, transaction.transactionID), + reportAction: getExpenseCreationIOUActionForTransactionID(snapshotReportActions, transaction.transactionID), report: reportByReportID.get(transaction.reportID), // Derive from the local copy so an offline edit (which sets `pendingFields`, not `pendingAction`) // still surfaces the pending state, alongside offline creates (ADD) and deletes (DELETE). diff --git a/src/setup/index.ts b/src/setup/index.ts index 29e659bf6181..5aa98887fb48 100644 --- a/src/setup/index.ts +++ b/src/setup/index.ts @@ -7,6 +7,7 @@ import registerReportActionsPagination from '@libs/registerReportActionsPaginati import {setDeviceID} from '@userActions/Device'; import initOnyxDerivedValues from '@userActions/OnyxDerived'; +import {clearActiveTransactionIDs} from '@userActions/TransactionThreadNavigation'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -106,6 +107,12 @@ export default function () { cleanupPreMountedDraftReports(); + // The carousel's sibling list belongs to the screen that seeded it, and that ownership lives in module state + // which dies with the JS runtime. A list that survives in storage is therefore orphaned the moment the app + // reloads: no mounted screen can refresh or release it, and an expense opened straight from a deeplink would + // pick it up and page through whatever the user last saw. Drop it before anything can read it. + clearActiveTransactionIDs(); + // Register the commands after Onyx is initialized so every JS runtime can process paginated // responses. Initial snapshots remain asynchronous and gate only pagination, not app startup. registerReportActionsPagination(); diff --git a/src/styles/index.ts b/src/styles/index.ts index b41ef660d45a..0d6f1218db7b 100644 --- a/src/styles/index.ts +++ b/src/styles/index.ts @@ -534,6 +534,11 @@ const staticStyles = (theme: ThemeColors) => lineHeight: lineHeightScale.label, }, + /** Gives every digit the same advance so a counter doesn't shift sideways as its digits change. */ + tabularNums: { + fontVariant: ['tabular-nums'], + }, + mutedNormalTextLabel: { color: theme.textSupporting, fontSize: fontScale.label, diff --git a/tests/ui/MoneyRequestReportPreview.test.tsx b/tests/ui/MoneyRequestReportPreview.test.tsx index 7b2071ac4193..c7f2638e4fd2 100644 --- a/tests/ui/MoneyRequestReportPreview.test.tsx +++ b/tests/ui/MoneyRequestReportPreview.test.tsx @@ -830,7 +830,14 @@ describe('MoneyRequestReportPreview', () => { await pressSecondTransaction(); // Online, delete-pending rows are already filtered upstream, so the seed must equal the full visible list. - expect(setActiveTransactionIDsSpy).toHaveBeenCalledWith(defaultPreviewTransactions.map((transaction) => transaction.transactionID)); + expect(setActiveTransactionIDsSpy).toHaveBeenCalledWith( + defaultPreviewTransactions.map((transaction) => transaction.transactionID), + { + // Stamped so the press owns the carousel it seeds: an unowned list can't be released by any screen + // and any other writer is free to overwrite it while the expense is still open. + source: TransactionThreadNavigation.CAROUSEL_SOURCE.reportPreview(mockIOUReport.reportID), + }, + ); }); it('still renders an offline-deleted expense card in the carousel', async () => { @@ -1229,8 +1236,8 @@ describe('MoneyRequestReportPreview', () => { fireEvent.press(screen.getByText(getTransactionDisplayAmountAndMetadataText(olderTransaction).transactionDisplayAmount)); await waitForBatchedUpdatesWithAct(); - expect(setActiveTransactionIDsSpy).toHaveBeenCalledWith([olderTransaction.transactionID, newerTransaction.transactionID]); - expect(setActiveTransactionIDsSpy).not.toHaveBeenCalledWith([newerTransaction.transactionID, olderTransaction.transactionID]); + expect(setActiveTransactionIDsSpy).toHaveBeenCalledWith([olderTransaction.transactionID, newerTransaction.transactionID], expect.anything()); + expect(setActiveTransactionIDsSpy).not.toHaveBeenCalledWith([newerTransaction.transactionID, olderTransaction.transactionID], expect.anything()); }); it('does not open the pressed expense over the report when "View" is tapped during the cascade delay', async () => { @@ -1287,7 +1294,10 @@ describe('MoneyRequestReportPreview', () => { fireEvent.press(screen.getByText(getTransactionDisplayAmountAndMetadataText(many.at(0) ?? mockTransaction).transactionDisplayAmount)); await waitForBatchedUpdatesWithAct(); - expect(setActiveTransactionIDsSpy).toHaveBeenCalledWith(many.map((transaction) => transaction.transactionID)); + expect(setActiveTransactionIDsSpy).toHaveBeenCalledWith( + many.map((transaction) => transaction.transactionID), + expect.anything(), + ); }); it('opens the report instead of the lone expense for a single-expense report', async () => { diff --git a/tests/ui/MoneyRequestReportTransactionsNavigationTest.tsx b/tests/ui/MoneyRequestReportTransactionsNavigationTest.tsx index 47aa8f6c718b..5bb5c274d029 100644 --- a/tests/ui/MoneyRequestReportTransactionsNavigationTest.tsx +++ b/tests/ui/MoneyRequestReportTransactionsNavigationTest.tsx @@ -225,11 +225,10 @@ describe('MoneyRequestReportTransactionsNavigation', () => { expect(createThreadSpy).not.toHaveBeenCalled(); }); - it('still builds the thread optimistically when offline, rather than leaving the arrow dead', async () => { + it('resolves the sibling offline rather than leaving the arrow dead', async () => { mockIsOffline.value = true; const openReportSpy = jest.spyOn(ReportActions, 'openReport').mockImplementation(() => {}); - const createThreadSpy = jest.spyOn(ReportActions, 'createTransactionThreadReport'); - jest.spyOn(Navigation, 'setParams').mockImplementation(() => {}); + const setParamsSpy = jest.spyOn(Navigation, 'setParams').mockImplementation(() => {}); render(); await waitForBatchedUpdates(); @@ -241,9 +240,11 @@ describe('MoneyRequestReportTransactionsNavigation', () => { } fireEvent.press(nextButton); - // Offline there is nothing to fetch, so the press must fall through instead of being staged. + // Offline there is nothing to fetch, so the press must fall through instead of being staged. Without a + // cached IOU action there is no thread to resolve either, so the sibling's own report is the target: a + // thread minted from a missing parent action could not be built at all. await waitFor(() => { - expect(createThreadSpy).toHaveBeenCalled(); + expect(setParamsSpy).toHaveBeenCalledWith(expect.objectContaining({reportID: IOU_REPORT_ID, anchorTransactionID: SECOND_TRANSACTION_ID})); }); expect(openReportSpy).not.toHaveBeenCalled(); }); diff --git a/tests/ui/RecentlyAddedSectionTest.tsx b/tests/ui/RecentlyAddedSectionTest.tsx index 4fe5aa89360c..6ac402f7ad8f 100644 --- a/tests/ui/RecentlyAddedSectionTest.tsx +++ b/tests/ui/RecentlyAddedSectionTest.tsx @@ -323,7 +323,7 @@ describe('RecentlyAddedSection', () => { await waitForBatchedUpdatesWithAct(); expect(mockNavigate).toHaveBeenCalledTimes(1); - expect(mockNavigate).toHaveBeenCalledWith(ROUTES.SEARCH_REPORT.getRoute({reportID: ROW_1.reportID, backTo: ROUTES.HOME})); + expect(mockNavigate).toHaveBeenCalledWith(ROUTES.SEARCH_REPORT.getRoute({reportID: ROW_1.reportID, backTo: ROUTES.HOME, anchorTransactionID: ROW_1.transactionID})); }); it('navigates to SEARCH_REPORT with backTo Home on narrow layout (carousel available on both layouts)', async () => { @@ -337,7 +337,7 @@ describe('RecentlyAddedSection', () => { await waitForBatchedUpdatesWithAct(); expect(mockNavigate).toHaveBeenCalledTimes(1); - expect(mockNavigate).toHaveBeenCalledWith(ROUTES.SEARCH_REPORT.getRoute({reportID: ROW_1.reportID, backTo: ROUTES.HOME})); + expect(mockNavigate).toHaveBeenCalledWith(ROUTES.SEARCH_REPORT.getRoute({reportID: ROW_1.reportID, backTo: ROUTES.HOME, anchorTransactionID: ROW_1.transactionID})); }); it('opens the tapped expense in a multi-expense report by navigating to its transaction thread', async () => { @@ -366,7 +366,7 @@ describe('RecentlyAddedSection', () => { await waitForBatchedUpdatesWithAct(); expect(mockNavigate).toHaveBeenCalledTimes(1); - expect(mockNavigate).toHaveBeenCalledWith(ROUTES.SEARCH_REPORT.getRoute({reportID: threadReportID, backTo: ROUTES.HOME})); + expect(mockNavigate).toHaveBeenCalledWith(ROUTES.SEARCH_REPORT.getRoute({reportID: threadReportID, backTo: ROUTES.HOME, anchorTransactionID: ROW_1.transactionID})); }); it('opens (creating if needed) the transaction thread for an expense in a one-transaction report, not the parent report', async () => { @@ -390,7 +390,7 @@ describe('RecentlyAddedSection', () => { expect(mockCreateTransactionThreadReport).toHaveBeenCalledTimes(1); expect(mockNavigate).toHaveBeenCalledTimes(1); - expect(mockNavigate).toHaveBeenCalledWith(ROUTES.SEARCH_REPORT.getRoute({reportID: 'created_thread_report', backTo: ROUTES.HOME})); + expect(mockNavigate).toHaveBeenCalledWith(ROUTES.SEARCH_REPORT.getRoute({reportID: 'created_thread_report', backTo: ROUTES.HOME, anchorTransactionID: ROW_1.transactionID})); }); it('seeds the prev/next carousel with the IDs and a lazy descriptor for every recently added expense', async () => { diff --git a/tests/ui/components/MoneyReportHeaderActionsPlacementTest.tsx b/tests/ui/components/MoneyReportHeaderActionsPlacementTest.tsx new file mode 100644 index 000000000000..5b9a84c8e9ae --- /dev/null +++ b/tests/ui/components/MoneyReportHeaderActionsPlacementTest.tsx @@ -0,0 +1,357 @@ +import {render} from '@testing-library/react-native'; + +import MoneyReportHeader from '@components/MoneyReportHeader'; +import MoneyReportHeaderActions from '@components/MoneyReportHeaderActions'; +import MoneyReportHeaderMoreContent from '@components/MoneyReportHeaderMoreContent'; + +import useMoneyReportHeaderMoreContentVisibility from '@hooks/useMoneyReportHeaderMoreContentVisibility'; +import useOnyx from '@hooks/useOnyx'; +import useReportPrimaryAction from '@hooks/useReportPrimaryAction'; +import useResponsiveLayout from '@hooks/useResponsiveLayout'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import SCREENS from '@src/SCREENS'; +import type {Report} from '@src/types/onyx'; + +import type * as ReactNavigationNative from '@react-navigation/native'; + +import {useRoute} from '@react-navigation/native'; +import React from 'react'; + +const REPORT_ID = '1001'; +const CHAT_REPORT_ID = '2001'; + +const HEADER_ROW_TEST_ID = 'header-row'; +const ACTIONS_TEST_ID = 'header-actions'; +const REPORT_CAROUSEL_TEST_ID = 'report-carousel'; +const TRANSACTIONS_CAROUSEL_TEST_ID = 'transactions-carousel'; + +const PARENT_REPORT_ID = '3001'; +const PARENT_ACTION_ID = 'parentAction1'; +const THREAD_TRANSACTION_ID = 'thread-tx-1'; + +/** A 1:1 DM IOU report: `isDM` is true for its chat report, and there is no next step or status bar to show. */ +const iouReport = {reportID: REPORT_ID, chatReportID: CHAT_REPORT_ID, type: CONST.REPORT.TYPE.IOU} as Report; +const dmChatReport = {reportID: CHAT_REPORT_ID, type: CONST.REPORT.TYPE.CHAT} as Report; + +jest.mock('@hooks/useOnyx', () => jest.fn()); +jest.mock('@hooks/useResponsiveLayout', () => jest.fn()); +jest.mock('@hooks/useReportPrimaryAction', () => jest.fn()); +jest.mock('@hooks/useMoneyReportHeaderMoreContentVisibility', () => jest.fn()); +jest.mock('@hooks/useResponsiveLayoutOnWideRHP', () => jest.fn(() => ({isWideRHPDisplayedOnWideLayout: false, isSuperWideRHPDisplayedOnWideLayout: false}))); +jest.mock('@hooks/useNetwork', () => jest.fn(() => ({isOffline: false}))); +jest.mock('@hooks/useMobileSelectionMode', () => jest.fn(() => false)); +jest.mock('@hooks/useTransactionsAndViolationsForReport', () => jest.fn(() => ({transactions: {}, violations: {}}))); +jest.mock('@hooks/useLocalize', () => jest.fn(() => ({translate: (key: string) => key}))); + +// useThemeStyles throws without a ; return a proxy that yields an empty style object +// for any key so the (mostly-mocked) tree renders without wiring up the full provider stack. +jest.mock('@hooks/useThemeStyles', () => { + const styleProxy = new Proxy({}, {get: () => ({})}); + return jest.fn(() => styleProxy); +}); + +// Only `useRoute` and `useIsFocused` are stubbed: the rest of the module is used by the navigation imports +// ReportUtils pulls in. The header reads `useIsFocused` to decide whether it owns the shared mobile selection mode, +// and these tests render it on its own rather than inside a navigator, so there is no navigation object to read. +jest.mock('@react-navigation/native', () => ({ + ...jest.requireActual('@react-navigation/native'), + __esModule: true, + useRoute: jest.fn(), + useIsFocused: () => true, +})); + +// The providers only supply context to the (mocked) leaves, so pass children straight through. +jest.mock('@components/MoneyReportHeaderModals', () => { + const reactModule = jest.requireActual('react'); + return jest.fn(({children}: {children: React.ReactNode}) => reactModule.createElement(reactModule.Fragment, null, children)); +}); +jest.mock('@components/PaymentAnimationsContext', () => { + const reactModule = jest.requireActual('react'); + return { + __esModule: true, + PaymentAnimationsProvider: jest.fn(({children}: {children: React.ReactNode}) => reactModule.createElement(reactModule.Fragment, null, children)), + }; +}); +jest.mock('@components/Search/SearchContext', () => ({ + __esModule: true, + useSearchSelectionActions: jest.fn(() => ({clearSelectedTransactions: jest.fn()})), +})); + +// HeaderWithBackButton stands in for the title row: it renders only its children, tagged so the test can +// assert what landed on the title row and in which order. +jest.mock('@components/HeaderWithBackButton', () => { + const reactModule = jest.requireActual('react'); + const {View} = jest.requireActual<{View: React.ComponentType<{testID?: string; children?: React.ReactNode}>}>('react-native'); + return jest.fn(({children}: {children: React.ReactNode}) => reactModule.createElement(View, {testID: 'header-row'}, children)); +}); +jest.mock('@components/HeaderLoadingBar', () => jest.fn(() => null)); +jest.mock('@components/MoneyReportHeaderActions', () => { + const reactModule = jest.requireActual('react'); + const {View} = jest.requireActual<{View: React.ComponentType<{testID?: string; children?: React.ReactNode}>}>('react-native'); + return jest.fn(() => reactModule.createElement(View, {testID: 'header-actions'})); +}); +jest.mock('@components/MoneyReportHeaderMoreContent', () => jest.fn(() => null)); +jest.mock('@components/MoneyRequestReportView/MoneyRequestReportNavigation', () => { + const reactModule = jest.requireActual('react'); + const {View} = jest.requireActual<{View: React.ComponentType<{testID?: string; children?: React.ReactNode}>}>('react-native'); + return jest.fn(() => reactModule.createElement(View, {testID: 'report-carousel'})); +}); +jest.mock('@components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation', () => { + const reactModule = jest.requireActual('react'); + const {View} = jest.requireActual<{View: React.ComponentType<{testID?: string; children?: React.ReactNode}>}>('react-native'); + return jest.fn(() => reactModule.createElement(View, {testID: 'transactions-carousel'})); +}); + +const mockedUseOnyx = jest.mocked(useOnyx); +const mockedUseRoute = jest.mocked(useRoute); +const mockedUseResponsiveLayout = jest.mocked(useResponsiveLayout); +const mockedUseReportPrimaryAction = jest.mocked(useReportPrimaryAction); +const mockedMoreContentVisibility = jest.mocked(useMoneyReportHeaderMoreContentVisibility); +const mockedActions = jest.mocked(MoneyReportHeaderActions); +const mockedMoreContent = jest.mocked(MoneyReportHeaderMoreContent); + +/** Collects the tagged testIDs in render order so the test can assert left-to-right placement on the title row. */ +function getHeaderRowTestIDs(node: ReturnType['toJSON']>): string[] { + const found: string[] = []; + const walk = (current: unknown, isInsideHeaderRow: boolean) => { + if (!current || typeof current !== 'object') { + return; + } + if (Array.isArray(current)) { + for (const child of current) { + walk(child, isInsideHeaderRow); + } + return; + } + const element = current as {props?: Record; children?: unknown}; + const testID = element.props?.testID; + const isHeaderRow = testID === HEADER_ROW_TEST_ID; + if (isInsideHeaderRow && typeof testID === 'string' && testID !== HEADER_ROW_TEST_ID) { + found.push(testID); + } + walk(element.children, isInsideHeaderRow || isHeaderRow); + }; + walk(node, false); + return found; +} + +function renderHeader() { + return render( + , + ); +} + +/** + * Regression guard for https://github.com/Expensify/App/issues/98200: the report actions must sit on the title row + * whenever the more-content row would otherwise be blank, no matter whether the report was opened directly or from + * Search. Placement used to flip between the two entry points, moving the buttons onto a row of their own in Search. + */ +describe('MoneyReportHeader actions placement', () => { + beforeEach(() => { + jest.clearAllMocks(); + + // A wide layout, so the header-row placement is in play at all. + mockedUseResponsiveLayout.mockReturnValue({ + shouldUseNarrowLayout: false, + isSmallScreenWidth: false, + isInNarrowPaneModal: false, + isExtraSmallScreenHeight: false, + isMediumScreenWidth: false, + isLargeScreenWidth: true, + isExtraLargeScreenWidth: false, + isExtraSmallScreenWidth: false, + isSmallScreen: false, + onboardingIsMediumOrLargerScreenWidth: true, + isInLandscapeMode: false, + }); + mockedUseReportPrimaryAction.mockReturnValue(CONST.REPORT.PRIMARY_ACTIONS.PAY); + mockedMoreContentVisibility.mockReturnValue({statusBarType: undefined, shouldShowNextStep: false, hasStatusOrNextStep: false}); + mockedUseOnyx.mockImplementation((key) => { + if (key === `${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`) { + return [iouReport, {status: 'loaded'}]; + } + if (key === `${ONYXKEYS.COLLECTION.REPORT}${CHAT_REPORT_ID}`) { + return [dmChatReport, {status: 'loaded'}]; + } + return [undefined, {status: 'loaded'}]; + }); + }); + + it.each([ + ['opened directly', SCREENS.REPORT], + ['opened from Search', SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT], + ['opened from Search as an expense', SCREENS.RIGHT_MODAL.SEARCH_REPORT], + ])('keeps the actions on the title row when the report is %s', (_label, routeName) => { + mockedUseRoute.mockReturnValue({key: 'route-1', name: routeName, params: {}}); + + const {toJSON} = renderHeader(); + + expect(getHeaderRowTestIDs(toJSON())).toContain(ACTIONS_TEST_ID); + // The actions row under the title must stay empty, otherwise the buttons would render twice. + expect(mockedMoreContent).toHaveBeenCalled(); + expect(mockedMoreContent.mock.calls.at(-1)?.at(0)).toEqual(expect.objectContaining({shouldRenderActionsInRow: false})); + }); + + it.each([ + ['an invoice report, whose chat report is an invoice room', {reportID: CHAT_REPORT_ID, type: CONST.REPORT.TYPE.CHAT, chatType: CONST.REPORT.CHAT_TYPE.POLICY_ROOM} as Report], + [ + 'a workspace report, whose chat report is a policy expense chat', + {reportID: CHAT_REPORT_ID, type: CONST.REPORT.TYPE.CHAT, chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT} as Report, + ], + ])('keeps the actions on the title row for %s', (_label, chatReport) => { + mockedUseOnyx.mockImplementation((key) => { + if (key === `${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`) { + return [iouReport, {status: 'loaded'}]; + } + if (key === `${ONYXKEYS.COLLECTION.REPORT}${CHAT_REPORT_ID}`) { + return [chatReport, {status: 'loaded'}]; + } + return [undefined, {status: 'loaded'}]; + }); + mockedUseRoute.mockReturnValue({key: 'route-1', name: SCREENS.REPORT, params: {}}); + + const {toJSON} = renderHeader(); + + expect(getHeaderRowTestIDs(toJSON())).toContain(ACTIONS_TEST_ID); + expect(mockedMoreContent.mock.calls.at(-1)?.at(0)).toEqual(expect.objectContaining({shouldRenderActionsInRow: false})); + }); + + it('renders the actions before the carousel so the carousel stays pinned to the top right', () => { + mockedUseRoute.mockReturnValue({key: 'route-1', name: SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT, params: {}}); + + const {toJSON} = renderHeader(); + + expect(getHeaderRowTestIDs(toJSON())).toEqual([ACTIONS_TEST_ID, REPORT_CAROUSEL_TEST_ID]); + }); + + it('moves the actions down to the more-content row when that row has a status or next step', () => { + mockedMoreContentVisibility.mockReturnValue({statusBarType: CONST.REPORT.STATUS_BAR_TYPE.ON_HOLD, shouldShowNextStep: false, hasStatusOrNextStep: true}); + mockedUseRoute.mockReturnValue({key: 'route-1', name: SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT, params: {}}); + + const {toJSON} = renderHeader(); + + expect(getHeaderRowTestIDs(toJSON())).not.toContain(ACTIONS_TEST_ID); + expect(mockedActions).not.toHaveBeenCalled(); + expect(mockedMoreContent.mock.calls.at(-1)?.at(0)).toEqual(expect.objectContaining({shouldRenderActionsInRow: true})); + }); +}); + +describe('MoneyReportHeader transaction carousel anchor', () => { + const threadReport = { + reportID: REPORT_ID, + chatReportID: CHAT_REPORT_ID, + parentReportID: PARENT_REPORT_ID, + parentReportActionID: PARENT_ACTION_ID, + type: CONST.REPORT.TYPE.CHAT, + } as Report; + + const parentIOUAction = { + reportActionID: PARENT_ACTION_ID, + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + originalMessage: {IOUTransactionID: THREAD_TRANSACTION_ID, type: CONST.IOU.REPORT_ACTION_TYPE.CREATE}, + }; + + function mockThread({ + activeIDs, + parentActions, + transactions = Object.fromEntries(activeIDs.map((id) => [`${ONYXKEYS.COLLECTION.TRANSACTION}${id}`, {transactionID: id, reportID: PARENT_REPORT_ID}])), + }: { + activeIDs: string[]; + parentActions: Record | undefined; + transactions?: Record; + }) { + // The anchor is read through a `selector`, so the mock has to apply it the way useOnyx does. + mockedUseOnyx.mockImplementation((key, options) => { + const rawValue = (() => { + if (key === `${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`) { + return threadReport; + } + if (key === ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS) { + return activeIDs; + } + if (key === ONYXKEYS.COLLECTION.TRANSACTION) { + return transactions; + } + if (key === `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${PARENT_REPORT_ID}`) { + return parentActions; + } + return undefined; + })(); + const {selector} = options ?? {}; + const value = selector ? selector(rawValue) : rawValue; + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- useOnyx's result type can't express "value depends on the key", and each branch above returns the shape its own key really holds + return [value as NonNullable | undefined, {status: 'loaded'}]; + }); + mockedUseRoute.mockReturnValue({key: 'route-1', name: SCREENS.RIGHT_MODAL.SEARCH_REPORT, params: {}}); + } + + beforeEach(() => { + mockedMoreContentVisibility.mockReturnValue({statusBarType: undefined, shouldShowNextStep: false, hasStatusOrNextStep: false}); + mockedUseReportPrimaryAction.mockReturnValue(CONST.REPORT.PRIMARY_ACTIONS.PAY); + }); + + it('renders the transaction carousel using the parent IOU action when the derived index is cold', () => { + mockThread({activeIDs: ['other-tx', THREAD_TRANSACTION_ID], parentActions: {[PARENT_ACTION_ID]: parentIOUAction}}); + + const {toJSON} = renderHeader(); + + expect(getHeaderRowTestIDs(toJSON())).toContain(TRANSACTIONS_CAROUSEL_TEST_ID); + }); + + it('does not render it when the resolved expense is not one of the carousel siblings', () => { + mockThread({activeIDs: ['other-tx', 'unrelated-tx'], parentActions: {[PARENT_ACTION_ID]: parentIOUAction}}); + + const {toJSON} = renderHeader(); + + expect(getHeaderRowTestIDs(toJSON())).not.toContain(TRANSACTIONS_CAROUSEL_TEST_ID); + }); + + it('does not render it when the parent action is unavailable, so there is no expense to anchor to', () => { + mockThread({activeIDs: ['other-tx', THREAD_TRANSACTION_ID], parentActions: undefined}); + + const {toJSON} = renderHeader(); + + expect(getHeaderRowTestIDs(toJSON())).not.toContain(TRANSACTIONS_CAROUSEL_TEST_ID); + }); + + it('falls through to the report carousel when a sibling has been deleted out from under the list', () => { + mockThread({ + activeIDs: ['other-tx', THREAD_TRANSACTION_ID], + parentActions: {[PARENT_ACTION_ID]: parentIOUAction}, + transactions: { + // 'other-tx' is absent: a confirmed delete SETs its key to null, leaving one sibling behind. + [`${ONYXKEYS.COLLECTION.TRANSACTION}${THREAD_TRANSACTION_ID}`]: {transactionID: THREAD_TRANSACTION_ID, reportID: PARENT_REPORT_ID}, + }, + }); + + const {toJSON} = renderHeader(); + + expect(getHeaderRowTestIDs(toJSON())).not.toContain(TRANSACTIONS_CAROUSEL_TEST_ID); + expect(getHeaderRowTestIDs(toJSON())).toContain(REPORT_CAROUSEL_TEST_ID); + }); + + it('does not render the expense carousel in the Inbox central pane', () => { + mockThread({activeIDs: ['other-tx', THREAD_TRANSACTION_ID], parentActions: {[PARENT_ACTION_ID]: parentIOUAction}}); + mockedUseRoute.mockReturnValue({key: 'route-1', name: SCREENS.REPORT, params: {}}); + + const {toJSON} = renderHeader(); + + expect(getHeaderRowTestIDs(toJSON())).not.toContain(TRANSACTIONS_CAROUSEL_TEST_ID); + expect(getHeaderRowTestIDs(toJSON())).not.toContain(REPORT_CAROUSEL_TEST_ID); + }); + + it('keeps the report carousel on a report opened from the Reports list', () => { + mockThread({activeIDs: ['other-tx', THREAD_TRANSACTION_ID], parentActions: {[PARENT_ACTION_ID]: parentIOUAction}}); + mockedUseRoute.mockReturnValue({key: 'route-1', name: SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT, params: {}}); + + const {toJSON} = renderHeader(); + + expect(getHeaderRowTestIDs(toJSON())).not.toContain(TRANSACTIONS_CAROUSEL_TEST_ID); + expect(getHeaderRowTestIDs(toJSON())).toContain(REPORT_CAROUSEL_TEST_ID); + }); +}); diff --git a/tests/ui/components/MoneyReportHeaderMoreContentTest.tsx b/tests/ui/components/MoneyReportHeaderMoreContentTest.tsx deleted file mode 100644 index 0cb04c080d37..000000000000 --- a/tests/ui/components/MoneyReportHeaderMoreContentTest.tsx +++ /dev/null @@ -1,120 +0,0 @@ -import {render} from '@testing-library/react-native'; - -import MoneyReportHeaderMoreContent from '@components/MoneyReportHeaderMoreContent'; -import MoneyReportHeaderNextStep from '@components/MoneyReportHeaderNextStep'; - -import useMoneyReportHeaderStatusBar from '@hooks/useMoneyReportHeaderStatusBar'; -import useOnyx from '@hooks/useOnyx'; - -import CONST from '@src/CONST'; -import ONYXKEYS from '@src/ONYXKEYS'; -import type {Policy, Report} from '@src/types/onyx'; - -import type {UseOnyxResult} from 'react-native-onyx'; - -import React from 'react'; - -import createRandomPolicy from '../../utils/collections/policies'; - -const TEST_REPORT_ID = '1001'; -const TEST_POLICY_ID = 'policy1'; - -const report = { - reportID: TEST_REPORT_ID, - policyID: TEST_POLICY_ID, - type: CONST.REPORT.TYPE.EXPENSE, -} as Report; - -function createOnyxResult(value: NonNullable | undefined): UseOnyxResult { - return [value, {status: 'loaded'}]; -} - -// `useRoute` is only used to detect Search routes; default to a regular report route so `isReportInSearch` is false. -// Spread the real module so navigation internals (e.g. createNavigationContainerRef) pulled in by the real -// PolicyUtils import chain keep working. -jest.mock('@react-navigation/native', () => { - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const actualNavigation = jest.requireActual('@react-navigation/native'); - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return { - ...actualNavigation, - __esModule: true, - useRoute: jest.fn(() => ({name: 'report'})), - }; -}); - -// The next-step bar is the element under test; render nothing but track whether it was mounted via the visibility gate. -jest.mock('@components/MoneyReportHeaderNextStep', () => ({__esModule: true, default: jest.fn(() => null)})); -jest.mock('@components/MoneyReportHeaderStatusBarSection', () => ({__esModule: true, default: () => null})); -jest.mock('@components/MoneyRequestReportView/MoneyRequestReportNavigation', () => ({__esModule: true, default: () => null})); -jest.mock('@components/MoneyReportTransactionThreadContext', () => ({__esModule: true, useMoneyReportTransactionThread: jest.fn(() => ({iouTransactionID: undefined}))})); - -// Spread the real module: the live PolicyUtils import chain relies on many other ReportUtils exports. -jest.mock('@libs/ReportUtils', () => { - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const actualReportUtils = jest.requireActual('@libs/ReportUtils'); - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return { - ...actualReportUtils, - __esModule: true, - isInvoiceReport: jest.fn(() => false), - }; -}); - -jest.mock('@hooks/useThemeStyles', () => ({__esModule: true, default: jest.fn(() => ({}))})); -jest.mock('@hooks/useResponsiveLayout', () => ({__esModule: true, default: jest.fn(() => ({shouldUseNarrowLayout: false, isMediumScreenWidth: false}))})); -jest.mock('@hooks/useResponsiveLayoutOnWideRHP', () => ({__esModule: true, default: jest.fn(() => ({isWideRHPDisplayedOnWideLayout: false, isSuperWideRHPDisplayedOnWideLayout: false}))})); -jest.mock('@hooks/useMoneyReportHeaderStatusBar', () => ({__esModule: true, default: jest.fn(() => ({shouldShowStatusBar: false, statusBarType: undefined}))})); -jest.mock('@hooks/useOnyx', () => jest.fn()); - -const mockedUseOnyx = jest.mocked(useOnyx); -const mockedStatusBar = jest.mocked(useMoneyReportHeaderStatusBar); -const mockedNextStepBar = jest.mocked(MoneyReportHeaderNextStep); - -let policyValue: Policy | undefined; - -function mockPolicyType(type: Policy['type']) { - policyValue = {...createRandomPolicy(1, type), id: TEST_POLICY_ID}; -} - -describe('MoneyReportHeaderMoreContent', () => { - beforeEach(() => { - jest.clearAllMocks(); - policyValue = undefined; - mockedStatusBar.mockReturnValue({shouldShowStatusBar: false, statusBarType: undefined}); - mockedUseOnyx.mockImplementation((key) => { - if (key === `${ONYXKEYS.COLLECTION.REPORT}${TEST_REPORT_ID}`) { - return createOnyxResult(report); - } - if (key === `${ONYXKEYS.COLLECTION.POLICY}${TEST_POLICY_ID}`) { - return createOnyxResult(policyValue); - } - return createOnyxResult(undefined); - }); - }); - - it('renders the next step bar for a Submit workspace', () => { - mockPolicyType(CONST.POLICY.TYPE.SUBMIT); - render(); - expect(mockedNextStepBar).toHaveBeenCalled(); - }); - - it('renders the next step bar for a paid (team) workspace', () => { - mockPolicyType(CONST.POLICY.TYPE.TEAM); - render(); - expect(mockedNextStepBar).toHaveBeenCalled(); - }); - - it('does not render the next step bar for a personal workspace', () => { - mockPolicyType(CONST.POLICY.TYPE.PERSONAL); - render(); - expect(mockedNextStepBar).not.toHaveBeenCalled(); - }); - - it('does not render the next step bar when a status bar is shown', () => { - mockPolicyType(CONST.POLICY.TYPE.SUBMIT); - mockedStatusBar.mockReturnValue({shouldShowStatusBar: true, statusBarType: CONST.REPORT.STATUS_BAR_TYPE.ON_HOLD}); - render(); - expect(mockedNextStepBar).not.toHaveBeenCalled(); - }); -}); diff --git a/tests/ui/components/MoneyReportHeaderMoreContentVisibilityTest.tsx b/tests/ui/components/MoneyReportHeaderMoreContentVisibilityTest.tsx new file mode 100644 index 000000000000..d52e54138a91 --- /dev/null +++ b/tests/ui/components/MoneyReportHeaderMoreContentVisibilityTest.tsx @@ -0,0 +1,120 @@ +import {renderHook} from '@testing-library/react-native'; + +import useMoneyReportHeaderMoreContentVisibility from '@hooks/useMoneyReportHeaderMoreContentVisibility'; +import useMoneyReportHeaderStatusBar from '@hooks/useMoneyReportHeaderStatusBar'; +import useOnyx from '@hooks/useOnyx'; + +import {isInvoiceReport} from '@libs/ReportUtils'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {Policy, Report} from '@src/types/onyx'; + +import type {UseOnyxResult} from 'react-native-onyx'; + +import createRandomPolicy from '../../utils/collections/policies'; + +const TEST_REPORT_ID = '1001'; +const TEST_POLICY_ID = 'policy1'; + +const report = { + reportID: TEST_REPORT_ID, + policyID: TEST_POLICY_ID, + type: CONST.REPORT.TYPE.EXPENSE, +} as Report; + +function createOnyxResult(value: NonNullable | undefined): UseOnyxResult { + return [value, {status: 'loaded'}]; +} + +// Spread the real module: the live PolicyUtils import chain relies on many other ReportUtils exports. +jest.mock('@libs/ReportUtils', () => { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const actualReportUtils = jest.requireActual('@libs/ReportUtils'); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return { + ...actualReportUtils, + __esModule: true, + isInvoiceReport: jest.fn(() => false), + }; +}); + +jest.mock('@hooks/useMoneyReportHeaderStatusBar', () => ({__esModule: true, default: jest.fn(() => ({shouldShowStatusBar: false, statusBarType: undefined}))})); +jest.mock('@hooks/useOnyx', () => jest.fn()); + +const mockedUseOnyx = jest.mocked(useOnyx); +const mockedStatusBar = jest.mocked(useMoneyReportHeaderStatusBar); +const mockedIsInvoiceReport = jest.mocked(isInvoiceReport); + +let policyValue: Policy | undefined; + +function mockPolicyType(type: Policy['type']) { + policyValue = {...createRandomPolicy(1, type), id: TEST_POLICY_ID}; +} + +/** + * `hasStatusOrNextStep` is what the header uses to decide where the report actions go: at the end of the + * more-content row when that row has its own content, or in the header row when it would otherwise be blank. + */ +describe('useMoneyReportHeaderMoreContentVisibility', () => { + beforeEach(() => { + jest.clearAllMocks(); + policyValue = undefined; + mockedIsInvoiceReport.mockReturnValue(false); + mockedStatusBar.mockReturnValue({shouldShowStatusBar: false, statusBarType: undefined}); + mockedUseOnyx.mockImplementation((key) => { + if (key === `${ONYXKEYS.COLLECTION.REPORT}${TEST_REPORT_ID}`) { + return createOnyxResult(report); + } + if (key === `${ONYXKEYS.COLLECTION.POLICY}${TEST_POLICY_ID}`) { + return createOnyxResult(policyValue); + } + return createOnyxResult(undefined); + }); + }); + + it('shows the next step for a Submit workspace', () => { + mockPolicyType(CONST.POLICY.TYPE.SUBMIT); + const {result} = renderHook(() => useMoneyReportHeaderMoreContentVisibility(TEST_REPORT_ID)); + expect(result.current.shouldShowNextStep).toBe(true); + expect(result.current.hasStatusOrNextStep).toBe(true); + }); + + it('shows the next step for a paid (team) workspace', () => { + mockPolicyType(CONST.POLICY.TYPE.TEAM); + const {result} = renderHook(() => useMoneyReportHeaderMoreContentVisibility(TEST_REPORT_ID)); + expect(result.current.shouldShowNextStep).toBe(true); + expect(result.current.hasStatusOrNextStep).toBe(true); + }); + + it('does not show the next step for a personal workspace', () => { + mockPolicyType(CONST.POLICY.TYPE.PERSONAL); + const {result} = renderHook(() => useMoneyReportHeaderMoreContentVisibility(TEST_REPORT_ID)); + expect(result.current.shouldShowNextStep).toBe(false); + }); + + it('does not show the next step when a status bar is shown', () => { + mockPolicyType(CONST.POLICY.TYPE.SUBMIT); + mockedStatusBar.mockReturnValue({shouldShowStatusBar: true, statusBarType: CONST.REPORT.STATUS_BAR_TYPE.ON_HOLD}); + const {result} = renderHook(() => useMoneyReportHeaderMoreContentVisibility(TEST_REPORT_ID)); + expect(result.current.shouldShowNextStep).toBe(false); + // A status bar still fills the more-content row, so the actions stay in it. + expect(result.current.hasStatusOrNextStep).toBe(true); + }); + + it('reports an empty more-content row for a personal workspace with no status bar', () => { + mockPolicyType(CONST.POLICY.TYPE.PERSONAL); + const {result} = renderHook(() => useMoneyReportHeaderMoreContentVisibility(TEST_REPORT_ID)); + // This is the 1:1 DM IOU case: nothing to show, so the actions move up into the header row + // instead of sitting alone on a blank line under the title. + expect(result.current.hasStatusOrNextStep).toBe(false); + }); + + it('reports an empty more-content row for an invoice report, even on a paid workspace', () => { + mockPolicyType(CONST.POLICY.TYPE.TEAM); + mockedIsInvoiceReport.mockReturnValue(true); + const {result} = renderHook(() => useMoneyReportHeaderMoreContentVisibility(TEST_REPORT_ID)); + expect(result.current.shouldShowNextStep).toBe(false); + expect(result.current.hasStatusOrNextStep).toBe(false); + }); +}); diff --git a/tests/ui/components/MoneyReportHeaderSelectionModeTest.tsx b/tests/ui/components/MoneyReportHeaderSelectionModeTest.tsx index a6b2bf67464b..323e51a4fca4 100644 --- a/tests/ui/components/MoneyReportHeaderSelectionModeTest.tsx +++ b/tests/ui/components/MoneyReportHeaderSelectionModeTest.tsx @@ -5,6 +5,7 @@ import MoneyReportHeader from '@components/MoneyReportHeader'; import MoneyReportHeaderActions from '@components/MoneyReportHeaderActions'; import useMobileSelectionMode from '@hooks/useMobileSelectionMode'; +import useMoneyReportHeaderMoreContentVisibility from '@hooks/useMoneyReportHeaderMoreContentVisibility'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; @@ -57,6 +58,12 @@ jest.mock('@components/MoneyReportHeaderActions', () => jest.fn(() => null)); jest.mock('@components/MoneyReportHeaderMoreContent', () => jest.fn(() => null)); jest.mock('@components/HeaderLoadingBar', () => jest.fn(() => null)); +// The route mocked above is a search route, so the wide branch of the header renders the report carousel beside the +// title. These tests are about which header branch renders, not about the arrows, and the real carousels read the +// search contexts and Onyx directly, which the mocks below deliberately do not provide. +jest.mock('@components/MoneyRequestReportView/MoneyRequestReportNavigation', () => jest.fn(() => null)); +jest.mock('@components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation', () => jest.fn(() => null)); + // The modal host and the payment animation provider only wrap the content, so render each as a plain // wrapper that yields its children instead of wiring up their full Onyx/context dependency chains. jest.mock('@components/MoneyReportHeaderModals', () => { @@ -79,6 +86,10 @@ jest.mock('@components/Search/SearchContext', () => ({__esModule: true, useSearc jest.mock('@libs/actions/MobileSelectionMode', () => ({__esModule: true, turnOffMobileSelectionMode: jest.fn(), turnOnMobileSelectionMode: jest.fn()})); jest.mock('@hooks/useMobileSelectionMode', () => jest.fn()); +// The more-content row decides whether the actions sit in the header row or under it. These tests are about the +// selection-mode branch rather than that placement, and the row's real visibility is derived from the filler +// transactions below, so it is pinned to "nothing to show" and the actions stay in the header row. +jest.mock('@hooks/useMoneyReportHeaderMoreContentVisibility', () => jest.fn()); jest.mock('@hooks/useNetwork', () => jest.fn()); jest.mock('@hooks/useOnyx', () => jest.fn()); jest.mock('@hooks/useResponsiveLayout', () => jest.fn()); @@ -91,6 +102,7 @@ jest.mock('@hooks/useLocalize', () => jest.fn(() => ({translate: jest.fn((key: s const mockHeaderWithBackButton = jest.mocked(HeaderWithBackButton); const mockMoneyReportHeaderActions = jest.mocked(MoneyReportHeaderActions); const mockUseMobileSelectionMode = jest.mocked(useMobileSelectionMode); +const mockUseMoneyReportHeaderMoreContentVisibility = jest.mocked(useMoneyReportHeaderMoreContentVisibility); const mockUseNetwork = jest.mocked(useNetwork); const mockUseOnyx = jest.mocked(useOnyx); const mockUseResponsiveLayout = jest.mocked(useResponsiveLayout); @@ -188,6 +200,7 @@ describe('MoneyReportHeader selection mode header', () => { mockUseNetwork.mockReturnValue({isOffline: false}); mockUseMobileSelectionMode.mockReturnValue(true); + mockUseMoneyReportHeaderMoreContentVisibility.mockReturnValue({statusBarType: undefined, shouldShowNextStep: false, hasStatusOrNextStep: false}); mockUseOnyx.mockImplementation((key) => { if (key === `${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`) { return createOnyxResult(report); diff --git a/tests/unit/components/MoneyRequestReportNavigation.test.tsx b/tests/unit/components/MoneyRequestReportNavigation.test.tsx index 91001e8f7070..3e112b433414 100644 --- a/tests/unit/components/MoneyRequestReportNavigation.test.tsx +++ b/tests/unit/components/MoneyRequestReportNavigation.test.tsx @@ -1,5 +1,6 @@ import {renderHook} from '@testing-library/react-native'; +import {isNavigableReportID} from '@components/MoneyRequestReportView/MoneyRequestReportNavigation'; import {useSearchResultsContext} from '@components/Search/SearchContext'; import useFilterPendingDeleteReports from '@hooks/useFilterPendingDeleteReports'; @@ -64,7 +65,7 @@ const isSameReportList = (a: Array, b: Array 0 && !isSearchLoading ? contextReports : standaloneReports; @@ -79,6 +80,28 @@ function useNavigationSource(reportID: string | undefined) { return {source: contextReports.length > 0 && !isSearchLoading ? 'fast' : 'full', allReports, effectiveAllReports}; } +/** + * Regression guard for https://github.com/Expensify/App/issues/99627: an unreported (self-DM) expense is grouped + * under the "0" placeholder rather than a real report, so it inflated the "x of y" counter with an entry the Reports + * list never showed, and paging onto it landed the user on an empty report. + */ +describe('isNavigableReportID', () => { + it('accepts a real report', () => { + expect(isNavigableReportID('12345')).toBe(true); + }); + + it('rejects the unreported placeholder', () => { + expect(isNavigableReportID(CONST.REPORT.UNREPORTED_REPORT_ID)).toBe(false); + }); + + it.each([ + ['undefined', undefined], + ['an empty string', ''], + ])('rejects %s', (_label, reportID) => { + expect(isNavigableReportID(reportID)).toBe(false); + }); +}); + describe('MoneyRequestReportNavigation', () => { beforeEach(() => { mockSortedReportIDs = CONST.EMPTY_ARRAY; diff --git a/tests/unit/components/MoneyRequestReportTransactionsNavigation.test.tsx b/tests/unit/components/MoneyRequestReportTransactionsNavigation.test.tsx new file mode 100644 index 000000000000..1259a7c7bdd1 --- /dev/null +++ b/tests/unit/components/MoneyRequestReportTransactionsNavigation.test.tsx @@ -0,0 +1,732 @@ +import {fireEvent, render, screen} from '@testing-library/react-native'; + +import MoneyRequestReportTransactionsNavigation from '@components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation'; + +import {createTransactionThreadReport} from '@libs/actions/Report'; +import {clearActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; +import {getReportIDToOpenForExpense} from '@libs/TransactionThreadNavigationUtils'; + +import Navigation from '@navigation/Navigation'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import SCREENS from '@src/SCREENS'; + +import React from 'react'; + +/** + * These tests verify the navigation resolution of MoneyRequestReportTransactionsNavigation: + * given a transaction list (and optionally a search snapshot), pressing prev/next should resolve + * and navigate to the correct target reportID for each direction. The heavy hooks are mocked so + * the real selectors and the onNext/onPrevious branching logic are exercised in isolation. + */ + +type MockOnyxState = { + transactionIDsList: string[] | undefined; + snapshotHash: string | undefined; + snapshot: {data: Record} | undefined; + siblingDescriptors: Record | undefined; + transactionsCollection: Record; + /** Fetch status of the `transactions_` subscription, which is how the carousel tells "not loaded" from "gone" */ + transactionsStatus: 'loading' | 'loaded'; + reportActionsCollection: Record; + reportsCollection: Record; +}; + +const mockState: MockOnyxState = { + transactionIDsList: undefined, + snapshotHash: undefined, + snapshot: undefined, + siblingDescriptors: undefined, + transactionsCollection: {}, + transactionsStatus: 'loaded', + reportActionsCollection: {}, + reportsCollection: {}, +}; + +const mockUseOnyx = jest.fn(); +const mockMarkReportRHPWidth = jest.fn(); + +jest.mock('@hooks/useOnyx', () => ({ + __esModule: true, + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + default: (...args: unknown[]) => mockUseOnyx(...args), +})); + +jest.mock('@hooks/useThemeStyles', () => ({ + __esModule: true, + default: () => ({}), +})); + +jest.mock('@hooks/useLocalize', () => ({ + __esModule: true, + default: () => ({translate: (key: string, params?: Record) => (params ? `${key}:${JSON.stringify(params)}` : key)}), +})); + +jest.mock('@hooks/useCurrentUserPersonalDetails', () => ({ + __esModule: true, + default: () => ({accountID: 1, email: 'me@example.com'}), +})); + +jest.mock('@components/WideRHPContextProvider', () => ({ + useWideRHPActions: () => ({markReportRHPWidth: mockMarkReportRHPWidth}), +})); + +jest.mock('@components/OnyxListItemProvider', () => ({ + usePersonalDetails: () => ({}), +})); + +const mockIsOffline = {value: false}; + +jest.mock('@hooks/useNetwork', () => ({ + __esModule: true, + default: () => ({isOffline: mockIsOffline.value}), +})); + +// Only useIsFocused is overridden; findFocusedRoute is the real one, since the teardown assertions depend on it. +jest.mock('@react-navigation/native', () => ({ + ...jest.requireActual>('@react-navigation/native'), + useIsFocused: () => true, +})); + +type ReactActual = {createElement: typeof React.createElement; Fragment: typeof React.Fragment}; +type ReactNativeActual = { + Pressable: React.ComponentType<{testID?: string; accessibilityState?: {disabled?: boolean}; onPress?: () => void}>; + Text: React.ComponentType<{children?: React.ReactNode}>; +}; + +jest.mock('@components/Text', () => { + const {Text} = jest.requireActual('react-native'); + return {__esModule: true, default: Text}; +}); + +// The disabled flag is recorded on `accessibilityState` rather than forwarded to `Pressable`'s `disabled` prop +// on purpose. A disabled Pressable returns `onStartShouldSetResponder: () => false`, RNTL then refuses to dispatch +// the event, and `expect(setParams).not.toHaveBeenCalled()` becomes vacuous: it can't tell "correctly disabled" +// from "handler bailed silently". Keeping the press live makes the two assertions independent. +jest.mock('@components/PrevNextButtons', () => { + const ReactLib = jest.requireActual('react'); + const {Pressable} = jest.requireActual('react-native'); + return { + __esModule: true, + default: (props: {onNext: () => void; onPrevious: () => void; isNextButtonDisabled?: boolean; isPrevButtonDisabled?: boolean}) => + ReactLib.createElement( + ReactLib.Fragment, + null, + ReactLib.createElement(Pressable, {testID: 'prev-button', accessibilityState: {disabled: !!props.isPrevButtonDisabled}, onPress: () => props.onPrevious()}), + ReactLib.createElement(Pressable, {testID: 'next-button', accessibilityState: {disabled: !!props.isNextButtonDisabled}, onPress: () => props.onNext()}), + ), + }; +}); + +jest.mock('@navigation/Navigation', () => ({ + __esModule: true, + default: { + setParams: jest.fn(), + getActiveRoute: jest.fn(() => 'active-route'), + }, +})); + +const makeRootState = (focusedRouteName: string) => ({index: 0, routes: [{key: 'k', name: focusedRouteName}]}); +const mockGetRootState = jest.fn(() => makeRootState('testRoute')); + +jest.mock('@navigation/navigationRef', () => ({ + __esModule: true, + default: { + getRootState: () => mockGetRootState(), + getCurrentRoute: jest.fn(() => undefined), + }, +})); + +jest.mock('@libs/actions/Report', () => ({ + createTransactionThreadReport: jest.fn(() => undefined), + setOptimisticTransactionThread: jest.fn(), + openReport: jest.fn(), +})); + +jest.mock('@libs/actions/TransactionThreadNavigation', () => ({ + clearActiveTransactionIDs: jest.fn(), +})); + +jest.mock('@libs/TransactionThreadNavigationUtils', () => ({ + getReportIDToOpenForExpense: jest.fn(() => 'resolved-descriptor-report'), +})); + +const makeIOUAction = (transactionID: string, {childReportID, reportID}: {childReportID?: string; reportID: string}) => ({ + reportActionID: `action_${transactionID}`, + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + originalMessage: {IOUTransactionID: transactionID, type: 'create'}, + childReportID, + reportID, +}); + +const CURRENT_ID = 'tCur'; +const PREV_ID = 'tPrev'; +const NEXT_ID = 'tNext'; + +const resetMockState = () => { + mockState.transactionIDsList = [PREV_ID, CURRENT_ID, NEXT_ID]; + mockState.snapshotHash = undefined; + mockState.snapshot = undefined; + mockState.siblingDescriptors = undefined; + mockState.transactionsCollection = {}; + mockState.transactionsStatus = 'loaded'; + mockState.reportActionsCollection = {}; + mockState.reportsCollection = {}; + mockGetRootState.mockReturnValue(makeRootState('testRoute')); + mockIsOffline.value = false; +}; + +const setupUseOnyx = () => { + mockUseOnyx.mockImplementation((key: string, options?: {selector?: (data: unknown) => unknown}) => { + const selector = options?.selector; + // Every branch returns the full `[value, metadata]` tuple `useOnyx` returns. Consumers read the metadata + // (`useCarouselTransactionIDs` gates on its `status`), so a value-only mock isn't the hook's contract. + const loaded = (value: unknown) => [value, {status: 'loaded'}]; + if (key === ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS) { + return loaded(mockState.transactionIDsList); + } + if (key === ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_SNAPSHOT_HASH) { + return loaded(mockState.snapshotHash); + } + if (key === `${ONYXKEYS.COLLECTION.SNAPSHOT}${mockState.snapshotHash}`) { + return loaded(mockState.snapshot); + } + if (key === ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_THREAD_REPORT_IDS) { + return loaded(mockState.siblingDescriptors); + } + if (key === ONYXKEYS.COLLECTION.TRANSACTION) { + return [selector ? selector(mockState.transactionsCollection) : undefined, {status: mockState.transactionsStatus}]; + } + if (key === ONYXKEYS.COLLECTION.REPORT_ACTIONS) { + return loaded(selector ? selector(mockState.reportActionsCollection) : undefined); + } + if (key.startsWith(ONYXKEYS.COLLECTION.REPORT)) { + return loaded(mockState.reportsCollection[key]); + } + // NVP_ONBOARDING (selector-based), NVP_INTRO_SELECTED, BETAS and anything else are not relevant to resolution. + return loaded(undefined); + }); +}; + +const renderNavigation = () => render(); + +// Navigation.setParams is deferred inside requestAnimationFrame. Run it synchronously so the resolved +// navigation happens during the press and can be asserted immediately afterwards. +const expectArrowDisabled = (testID: string, isDisabled: boolean) => { + expect(screen.getByTestId(testID).props.accessibilityState).toEqual({disabled: isDisabled}); +}; + +const press = (testID: string) => { + global.requestAnimationFrame = (callback: FrameRequestCallback) => { + callback(0); + return 0; + }; + fireEvent.press(screen.getByTestId(testID)); +}; + +describe('MoneyRequestReportTransactionsNavigation', () => { + beforeEach(() => { + jest.clearAllMocks(); + resetMockState(); + setupUseOnyx(); + }); + + describe('one-transaction parent report', () => { + beforeEach(() => { + mockState.transactionsCollection = { + [`${ONYXKEYS.COLLECTION.TRANSACTION}${CURRENT_ID}`]: {transactionID: CURRENT_ID, reportID: 'rCur'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${PREV_ID}`]: {transactionID: PREV_ID, reportID: 'rPrev'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${NEXT_ID}`]: {transactionID: NEXT_ID, reportID: 'rNext'}, + }; + mockState.reportsCollection = { + [`${ONYXKEYS.COLLECTION.REPORT}rPrev`]: {reportID: 'rPrev', transactionCount: 1}, + [`${ONYXKEYS.COLLECTION.REPORT}rNext`]: {reportID: 'rNext', transactionCount: 1}, + }; + }); + + it('navigates next to the parent reportID', () => { + renderNavigation(); + + press('next-button'); + + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'rNext', reportActionID: undefined, anchorTransactionID: NEXT_ID})); + expect(mockMarkReportRHPWidth).toHaveBeenCalledWith('rNext', 'wide'); + }); + + it('navigates previous to the parent reportID', () => { + renderNavigation(); + + press('prev-button'); + + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'rPrev', reportActionID: undefined, anchorTransactionID: PREV_ID})); + expect(mockMarkReportRHPWidth).toHaveBeenCalledWith('rPrev', 'wide'); + }); + }); + + describe('resolves siblings and parents from the search snapshot', () => { + beforeEach(() => { + // Live collections are intentionally empty; everything is only in the snapshot. + mockState.snapshotHash = 'hash1'; + mockState.snapshot = { + data: { + [`${ONYXKEYS.COLLECTION.TRANSACTION}${CURRENT_ID}`]: {transactionID: CURRENT_ID, reportID: 'rCur'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${PREV_ID}`]: {transactionID: PREV_ID, reportID: 'rPrev'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${NEXT_ID}`]: {transactionID: NEXT_ID, reportID: 'rNext'}, + [`${ONYXKEYS.COLLECTION.REPORT}rPrev`]: {reportID: 'rPrev', transactionCount: 1}, + [`${ONYXKEYS.COLLECTION.REPORT}rNext`]: {reportID: 'rNext', transactionCount: 1}, + }, + }; + }); + + it('navigates next using snapshot-only data', () => { + renderNavigation(); + + press('next-button'); + + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'rNext', anchorTransactionID: NEXT_ID})); + }); + + it('navigates previous using snapshot-only data', () => { + renderNavigation(); + + press('prev-button'); + + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'rPrev', anchorTransactionID: PREV_ID})); + }); + }); + + describe('multi-transaction parent with an existing thread', () => { + beforeEach(() => { + mockState.transactionsCollection = { + [`${ONYXKEYS.COLLECTION.TRANSACTION}${CURRENT_ID}`]: {transactionID: CURRENT_ID, reportID: 'rCur'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${PREV_ID}`]: {transactionID: PREV_ID, reportID: 'rPrev'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${NEXT_ID}`]: {transactionID: NEXT_ID, reportID: 'rNext'}, + }; + mockState.reportActionsCollection = { + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}rPrev`]: {actionPrev: makeIOUAction(PREV_ID, {childReportID: 'threadPrev', reportID: 'rPrev'})}, + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}rNext`]: {actionNext: makeIOUAction(NEXT_ID, {childReportID: 'threadNext', reportID: 'rNext'})}, + }; + mockState.reportsCollection = { + [`${ONYXKEYS.COLLECTION.REPORT}rPrev`]: {reportID: 'rPrev', transactionCount: 2}, + [`${ONYXKEYS.COLLECTION.REPORT}rNext`]: {reportID: 'rNext', transactionCount: 2}, + }; + }); + + it('navigates next to the existing transaction thread reportID', () => { + renderNavigation(); + + press('next-button'); + + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'threadNext', anchorTransactionID: NEXT_ID})); + expect(mockMarkReportRHPWidth).toHaveBeenCalledWith('threadNext', 'wide'); + }); + + it('navigates previous to the existing transaction thread reportID', () => { + renderNavigation(); + + press('prev-button'); + + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'threadPrev', anchorTransactionID: PREV_ID})); + expect(mockMarkReportRHPWidth).toHaveBeenCalledWith('threadPrev', 'wide'); + }); + }); + + describe('live report actions take precedence over a stale snapshot copy', () => { + beforeEach(() => { + mockState.transactionsCollection = { + [`${ONYXKEYS.COLLECTION.TRANSACTION}${CURRENT_ID}`]: {transactionID: CURRENT_ID, reportID: 'rCur'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${PREV_ID}`]: {transactionID: PREV_ID, reportID: 'rPrev'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${NEXT_ID}`]: {transactionID: NEXT_ID, reportID: 'rNext'}, + }; + mockState.reportActionsCollection = { + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}rPrev`]: {actionPrev: makeIOUAction(PREV_ID, {childReportID: 'threadPrev', reportID: 'rPrev'})}, + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}rNext`]: {actionNext: makeIOUAction(NEXT_ID, {childReportID: 'threadNext', reportID: 'rNext'})}, + }; + mockState.reportsCollection = { + [`${ONYXKEYS.COLLECTION.REPORT}rPrev`]: {reportID: 'rPrev', transactionCount: 2}, + [`${ONYXKEYS.COLLECTION.REPORT}rNext`]: {reportID: 'rNext', transactionCount: 2}, + }; + mockState.snapshotHash = 'hash1'; + mockState.snapshot = { + data: { + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}rPrev`]: {actionPrev: makeIOUAction(PREV_ID, {reportID: 'rPrev'})}, + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}rNext`]: {actionNext: makeIOUAction(NEXT_ID, {reportID: 'rNext'})}, + }, + }; + }); + + it('navigates next to the live thread instead of creating a duplicate', () => { + renderNavigation(); + + press('next-button'); + + expect(createTransactionThreadReport).not.toHaveBeenCalled(); + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'threadNext', anchorTransactionID: NEXT_ID})); + }); + + it('navigates previous to the live thread instead of creating a duplicate', () => { + renderNavigation(); + + press('prev-button'); + + expect(createTransactionThreadReport).not.toHaveBeenCalled(); + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'threadPrev', anchorTransactionID: PREV_ID})); + }); + }); + + describe('multi-transaction parent without a thread', () => { + beforeEach(() => { + mockState.transactionsCollection = { + [`${ONYXKEYS.COLLECTION.TRANSACTION}${CURRENT_ID}`]: {transactionID: CURRENT_ID, reportID: 'rCur'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${PREV_ID}`]: {transactionID: PREV_ID, reportID: 'rPrev'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${NEXT_ID}`]: {transactionID: NEXT_ID, reportID: 'rNext'}, + }; + mockState.reportActionsCollection = { + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}rPrev`]: {actionPrev: makeIOUAction(PREV_ID, {reportID: 'rPrev'})}, + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}rNext`]: {actionNext: makeIOUAction(NEXT_ID, {reportID: 'rNext'})}, + }; + mockState.reportsCollection = { + [`${ONYXKEYS.COLLECTION.REPORT}rPrev`]: {reportID: 'rPrev', transactionCount: 2}, + [`${ONYXKEYS.COLLECTION.REPORT}rNext`]: {reportID: 'rNext', transactionCount: 2}, + }; + }); + + // Thread creation is delegated to the shared resolver so that both directions, and the other screens that + // open a single expense, agree on where an expense opens. + it('resolves the target through the shared resolver and navigates next', () => { + jest.mocked(getReportIDToOpenForExpense).mockReturnValue('createdNext'); + renderNavigation(); + + press('next-button'); + + expect(getReportIDToOpenForExpense).toHaveBeenCalledWith( + expect.objectContaining({reportID: 'rNext', transaction: expect.objectContaining({transactionID: NEXT_ID})}), + expect.anything(), + ); + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'createdNext', anchorTransactionID: NEXT_ID})); + }); + + it('resolves the target through the shared resolver and navigates previous', () => { + jest.mocked(getReportIDToOpenForExpense).mockReturnValue('createdPrev'); + renderNavigation(); + + press('prev-button'); + + expect(getReportIDToOpenForExpense).toHaveBeenCalledWith( + expect.objectContaining({reportID: 'rPrev', transaction: expect.objectContaining({transactionID: PREV_ID})}), + expect.anything(), + ); + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'createdPrev', anchorTransactionID: PREV_ID})); + }); + }); + + describe('snapshot-backed sibling descriptors', () => { + beforeEach(() => { + mockState.transactionsCollection = { + [`${ONYXKEYS.COLLECTION.TRANSACTION}${CURRENT_ID}`]: {transactionID: CURRENT_ID, reportID: 'rCur'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${PREV_ID}`]: {transactionID: PREV_ID, reportID: 'rPrev'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${NEXT_ID}`]: {transactionID: NEXT_ID, reportID: 'rNext'}, + }; + // No parent report present -> not a one-transaction report, so resolution uses the descriptor. + mockState.siblingDescriptors = { + [PREV_ID]: {reportID: 'rPrev'}, + [NEXT_ID]: {reportID: 'rNext'}, + }; + }); + + it('navigates next to the descriptor-resolved reportID', () => { + jest.mocked(getReportIDToOpenForExpense).mockReturnValue('descNext'); + renderNavigation(); + + press('next-button'); + + expect(getReportIDToOpenForExpense).toHaveBeenCalled(); + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'descNext', anchorTransactionID: NEXT_ID})); + }); + + it('navigates previous to the descriptor-resolved reportID', () => { + jest.mocked(getReportIDToOpenForExpense).mockReturnValue('descPrev'); + renderNavigation(); + + press('prev-button'); + + expect(getReportIDToOpenForExpense).toHaveBeenCalled(); + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'descPrev', anchorTransactionID: PREV_ID})); + }); + }); + + it('does not render navigation when there are fewer than two transactions', () => { + mockState.transactionIDsList = [CURRENT_ID]; + + renderNavigation(); + + expect(screen.queryByTestId('next-button')).toBeNull(); + }); + + /** + * The carousel list is a snapshot of what another screen was showing when it seeded it, and it goes stale. + * Validating it here is what keeps the counter and the arrows agreeing with what the user can actually reach. + */ + describe('validates the seeded list against live transaction data', () => { + const counterFor = (current: number, total: number) => `common.currentOfTotal:${JSON.stringify({current, total})}`; + + it('counts every sibling when they are all still live', () => { + mockState.transactionsCollection = { + [`${ONYXKEYS.COLLECTION.TRANSACTION}${CURRENT_ID}`]: {transactionID: CURRENT_ID, reportID: 'rCur'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${PREV_ID}`]: {transactionID: PREV_ID, reportID: 'rPrev'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${NEXT_ID}`]: {transactionID: NEXT_ID, reportID: 'rNext'}, + }; + + renderNavigation(); + + expect(screen.getByText(counterFor(2, 3))).toBeTruthy(); + }); + + // Regression guard for https://github.com/Expensify/App/issues/99617 (the counter kept counting a deleted + // expense) and https://github.com/Expensify/App/issues/99614 (its arrow led to a "not here" page). + it('drops a sibling that is queued for deletion', () => { + mockState.transactionsCollection = { + [`${ONYXKEYS.COLLECTION.TRANSACTION}${CURRENT_ID}`]: {transactionID: CURRENT_ID, reportID: 'rCur'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${PREV_ID}`]: {transactionID: PREV_ID, reportID: 'rPrev'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${NEXT_ID}`]: { + transactionID: NEXT_ID, + reportID: 'rNext', + pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, + }, + }; + + renderNavigation(); + + expect(screen.getByText(counterFor(2, 2))).toBeTruthy(); + // The deleted expense is no longer reachable: it was the last entry, so there is nothing after it. + expectArrowDisabled('next-button', true); + press('next-button'); + expect(Navigation.setParams).not.toHaveBeenCalled(); + }); + + it('drops a sibling that has already been deleted', () => { + mockState.transactionsCollection = { + [`${ONYXKEYS.COLLECTION.TRANSACTION}${CURRENT_ID}`]: {transactionID: CURRENT_ID, reportID: 'rCur'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${PREV_ID}`]: {transactionID: PREV_ID, reportID: CONST.REPORT.TRASH_REPORT_ID}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${NEXT_ID}`]: {transactionID: NEXT_ID, reportID: 'rNext'}, + }; + + renderNavigation(); + + expect(screen.getByText(counterFor(1, 2))).toBeTruthy(); + expectArrowDisabled('prev-button', true); + press('prev-button'); + expect(Navigation.setParams).not.toHaveBeenCalled(); + }); + + // A transaction that hasn't loaded yet is not a transaction that is gone: dropping those would shrink the + // carousel under the user on a cold open (https://github.com/Expensify/App/issues/99641). + it('keeps siblings while the transaction collection is still loading', () => { + mockState.transactionsCollection = {}; + mockState.transactionsStatus = 'loading'; + + renderNavigation(); + + expect(screen.getByText(counterFor(2, 3))).toBeTruthy(); + }); + + // The other half of that rule, and the regression guard that matters: a confirmed delete SETs + // `transactions_` to null, so once the collection has loaded, absence means the expense is gone. Keeping + // it would re-admit a deleted expense one network round-trip after the optimistic delete dropped it, which is + // https://github.com/Expensify/App/issues/99617 and https://github.com/Expensify/App/issues/99614 again. + it('drops siblings that are absent once the transaction collection has loaded', () => { + mockState.transactionsCollection = { + [`${ONYXKEYS.COLLECTION.TRANSACTION}${CURRENT_ID}`]: {transactionID: CURRENT_ID, reportID: 'rCur'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${PREV_ID}`]: {transactionID: PREV_ID, reportID: 'rPrev'}, + }; + + renderNavigation(); + + expect(screen.getByText(counterFor(2, 2))).toBeTruthy(); + // An arrow that leads nowhere must not be pressable in the first place: deriving the disabled state from + // list position alone left it enabled, and the press then bailed silently with no spinner and no error. + expectArrowDisabled('next-button', true); + press('next-button'); + expect(Navigation.setParams).not.toHaveBeenCalled(); + }); + + // Siblings seeded by a snapshot-backed flow (Home "Recently added") carry a descriptor precisely because + // they may never reach the live collection, so their absence there is expected rather than a deletion. + it('keeps descriptor-backed siblings that are absent from the collection', () => { + mockState.transactionsCollection = { + [`${ONYXKEYS.COLLECTION.TRANSACTION}${CURRENT_ID}`]: {transactionID: CURRENT_ID, reportID: 'rCur'}, + }; + mockState.siblingDescriptors = { + [PREV_ID]: {reportID: 'rPrev', transaction: {transactionID: PREV_ID}}, + [NEXT_ID]: {reportID: 'rNext', transaction: {transactionID: NEXT_ID}}, + }; + + renderNavigation(); + + expect(screen.getByText(counterFor(2, 3))).toBeTruthy(); + }); + + // Regression guard for https://github.com/Expensify/App/issues/99616: after backing out of a report, the + // report's list was left driving a thread that was never part of it, so the thread showed a foreign "x of y". + it('renders nothing when the current expense is not one of the siblings', () => { + mockState.transactionIDsList = [PREV_ID, NEXT_ID]; + + renderNavigation(); + + expect(screen.queryByTestId('next-button')).toBeNull(); + expect(screen.queryByTestId('prev-button')).toBeNull(); + }); + }); + + /** + * Regression guard for https://github.com/Expensify/App/issues/99611: paying, approving or rejecting an expense + * produces further IOU actions carrying the same IOUTransactionID, each with its own thread. Paging onto one of + * those opens a system message ("marked as paid") instead of the expense. + */ + describe('ignores IOU actions that did not create the expense', () => { + const makePayAction = (transactionID: string, {childReportID, reportID}: {childReportID: string; reportID: string}) => ({ + reportActionID: `pay_${transactionID}`, + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + originalMessage: {IOUTransactionID: transactionID, type: CONST.IOU.REPORT_ACTION_TYPE.PAY}, + childReportID, + reportID, + }); + + beforeEach(() => { + mockState.transactionsCollection = { + [`${ONYXKEYS.COLLECTION.TRANSACTION}${CURRENT_ID}`]: {transactionID: CURRENT_ID, reportID: 'rCur'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${PREV_ID}`]: {transactionID: PREV_ID, reportID: 'rPrev'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${NEXT_ID}`]: {transactionID: NEXT_ID, reportID: 'rNext'}, + }; + mockState.reportsCollection = { + [`${ONYXKEYS.COLLECTION.REPORT}rNext`]: {reportID: 'rNext', transactionCount: 2}, + }; + }); + + it('prefers the expense-creating action over the pay action on the same transaction', () => { + mockState.reportActionsCollection = { + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}rNext`]: { + payNext: makePayAction(NEXT_ID, {childReportID: 'payThreadNext', reportID: 'rNext'}), + actionNext: makeIOUAction(NEXT_ID, {childReportID: 'threadNext', reportID: 'rNext'}), + }, + }; + + renderNavigation(); + + press('next-button'); + + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'threadNext', anchorTransactionID: NEXT_ID})); + }); + + it('does not open the pay action thread when it is the only action on the transaction', () => { + jest.mocked(getReportIDToOpenForExpense).mockReturnValue('rNext'); + mockState.reportActionsCollection = { + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}rNext`]: {payNext: makePayAction(NEXT_ID, {childReportID: 'payThreadNext', reportID: 'rNext'})}, + }; + + renderNavigation(); + + press('next-button'); + + expect(Navigation.setParams).not.toHaveBeenCalledWith(expect.objectContaining({reportID: 'payThreadNext'})); + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'rNext', anchorTransactionID: NEXT_ID})); + }); + }); + + /** + * Regression guard for https://github.com/Expensify/App/issues/99612: an unreported (self-DM) sibling used to + * fall through with no resolved target, and the resulting navigation dumped the user in their self-DM. + */ + it('stays put rather than navigating to the unreported placeholder report', () => { + jest.mocked(getReportIDToOpenForExpense).mockReturnValue(CONST.REPORT.UNREPORTED_REPORT_ID); + mockState.transactionsCollection = { + [`${ONYXKEYS.COLLECTION.TRANSACTION}${CURRENT_ID}`]: {transactionID: CURRENT_ID, reportID: 'rCur'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${PREV_ID}`]: {transactionID: PREV_ID, reportID: CONST.REPORT.UNREPORTED_REPORT_ID}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${NEXT_ID}`]: {transactionID: NEXT_ID, reportID: CONST.REPORT.UNREPORTED_REPORT_ID}, + }; + + renderNavigation(); + + press('next-button'); + + expect(Navigation.setParams).not.toHaveBeenCalled(); + expect(mockMarkReportRHPWidth).not.toHaveBeenCalled(); + }); + + /** + * An unreported (self-DM) sibling is the one case the transaction alone doesn't make resolvable: report "0" is + * neither a report to open nor one whose actions can be fetched, so without its IOU action the arrow has + * nowhere to go. It used to stay enabled and bail silently on press. + */ + describe('unreported (self-DM) siblings', () => { + beforeEach(() => { + mockState.transactionsCollection = { + [`${ONYXKEYS.COLLECTION.TRANSACTION}${CURRENT_ID}`]: {transactionID: CURRENT_ID, reportID: 'rCur'}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${PREV_ID}`]: {transactionID: PREV_ID, reportID: CONST.REPORT.UNREPORTED_REPORT_ID}, + [`${ONYXKEYS.COLLECTION.TRANSACTION}${NEXT_ID}`]: {transactionID: NEXT_ID, reportID: CONST.REPORT.UNREPORTED_REPORT_ID}, + }; + }); + + it('disables the arrow when the sibling has no IOU action to resolve or create a thread from', () => { + renderNavigation(); + + expectArrowDisabled('next-button', true); + expectArrowDisabled('prev-button', true); + }); + + it('keeps the arrow enabled and creates the thread once the IOU action is known', () => { + // The self-DM's actions, as the search snapshot carries them. The action has no childReportID, so the + // shared resolver creates the thread rather than leaving the press with report "0" and no target. + mockState.snapshotHash = 'hash1'; + mockState.snapshot = { + data: { + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}selfDM`]: { + [`action_${NEXT_ID}`]: makeIOUAction(NEXT_ID, {reportID: 'selfDM'}), + }, + }, + }; + jest.mocked(getReportIDToOpenForExpense).mockReturnValue('created-self-dm-thread'); + + renderNavigation(); + + expectArrowDisabled('next-button', false); + expectArrowDisabled('prev-button', true); + + press('next-button'); + + expect(Navigation.setParams).toHaveBeenCalledWith(expect.objectContaining({reportID: 'created-self-dm-thread', anchorTransactionID: NEXT_ID})); + }); + }); + + describe('clearing the carousel on unmount', () => { + const setFocusedRoute = (name: string) => { + mockGetRootState.mockReturnValue(makeRootState(name)); + }; + + // Unmounting onto one of these means we're still inside the expense-navigation flow, and a screen lower in + // the RHP stack may still depend on the carousel. In particular, opening the parent report from the + // subtitle link pushes an EXPENSE_REPORT / SEARCH_MONEY_REQUEST_REPORT RHP on top of the transaction + // thread, so backing out of an expense onto it must not wipe the underlying thread's carousel (#90366). + it.each([ + ['SEARCH_REPORT', SCREENS.RIGHT_MODAL.SEARCH_REPORT], + ['SEARCH_MONEY_REQUEST_REPORT', SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT], + ['EXPENSE_REPORT', SCREENS.RIGHT_MODAL.EXPENSE_REPORT], + ['TRANSACTION_DUPLICATE.DYNAMIC_REVIEW', SCREENS.TRANSACTION_DUPLICATE.DYNAMIC_REVIEW], + ])('keeps the active transaction IDs when unmounting onto %s', (_label, screenName) => { + setFocusedRoute(screenName); + + renderNavigation().unmount(); + + expect(clearActiveTransactionIDs).not.toHaveBeenCalled(); + }); + + it('clears the active transaction IDs when unmounting onto an unrelated screen', () => { + setFocusedRoute(SCREENS.SEARCH.ROOT); + + renderNavigation().unmount(); + + expect(clearActiveTransactionIDs).toHaveBeenCalled(); + }); + }); +}); diff --git a/tests/unit/hooks/useNavigateToTransactionThread.test.ts b/tests/unit/hooks/useNavigateToTransactionThread.test.ts new file mode 100644 index 000000000000..ef95ab2e01c7 --- /dev/null +++ b/tests/unit/hooks/useNavigateToTransactionThread.test.ts @@ -0,0 +1,98 @@ +import {renderHook} from '@testing-library/react-native'; + +import useNavigateToTransactionThread from '@hooks/useNavigateToTransactionThread'; + +import {CAROUSEL_SOURCE, setActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; +import Navigation from '@libs/Navigation/Navigation'; +import {getExpenseCreationIOUActionForTransactionID} from '@libs/ReportActionsUtils'; + +import type {Report} from '@src/types/onyx'; + +import createRandomReportAction from '../../utils/collections/reportActions'; +import {createExpenseReport} from '../../utils/collections/reports'; +import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; + +const TRANSACTION_ID = 'B2'; +const SIBLING_TRANSACTION_IDS = ['B1', 'B2']; +const THREAD_REPORT_ID = 'thread-1'; +const CAROUSEL_SOURCE_FOR_REPORT = 'reportRow:reportB'; + +const report: Report = {...createExpenseReport(1), reportID: 'reportB'}; +// An IOU action that already has a thread, so the hook takes the short path to navigation. +const iouAction = {...createRandomReportAction(1), reportActionID: 'action1', childReportID: THREAD_REPORT_ID}; + +jest.mock('@libs/actions/TransactionThreadNavigation', () => ({ + setActiveTransactionIDs: jest.fn(() => Promise.resolve()), + CAROUSEL_SOURCE: {reportRow: (reportID: string | undefined) => `reportRow:${reportID}`}, +})); + +jest.mock('@libs/actions/Report', () => ({ + createTransactionThreadReport: jest.fn(), + setOptimisticTransactionThread: jest.fn(), +})); + +jest.mock('@libs/Navigation/Navigation', () => ({ + __esModule: true, + default: {getActiveRoute: jest.fn(() => '/search'), navigate: jest.fn()}, +})); + +jest.mock('@libs/ReportActionsUtils', () => ({getExpenseCreationIOUActionForTransactionID: jest.fn()})); + +jest.mock('@components/WideRHPContextProvider', () => ({useWideRHPActions: jest.fn(() => ({markReportRHPWidth: jest.fn()}))})); + +// The personal details context is only forwarded to createTransactionThreadReport (mocked above), so an empty map is enough. +jest.mock('@components/OnyxListItemProvider', () => ({usePersonalDetails: jest.fn(() => ({}))})); + +jest.mock('@hooks/useCurrentUserPersonalDetails', () => jest.fn(() => ({email: 'a@b.com', accountID: 1}))); +jest.mock('@hooks/useOnyx', () => jest.fn(() => [undefined, {status: 'loaded'}])); + +const mockedGetIOUAction = jest.mocked(getExpenseCreationIOUActionForTransactionID); +const mockedSetActiveTransactionIDs = jest.mocked(setActiveTransactionIDs); +const mockedNavigate = jest.mocked(Navigation.navigate); + +function callHook(overrides?: {carouselSource?: string}) { + const {result} = renderHook(() => useNavigateToTransactionThread()); + result.current({ + transactionID: TRANSACTION_ID, + reportActions: [iouAction], + report, + transaction: undefined, + siblingTransactionIDs: SIBLING_TRANSACTION_IDS, + ...overrides, + }); + return waitForBatchedUpdates(); +} + +describe('useNavigateToTransactionThread', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockedGetIOUAction.mockReturnValue(iouAction); + mockedSetActiveTransactionIDs.mockReturnValue(Promise.resolve()); + }); + + it('seeds the carousel with the given siblings', async () => { + await callHook(); + + expect(mockedSetActiveTransactionIDs).toHaveBeenCalledWith(SIBLING_TRANSACTION_IDS, {source: undefined}); + }); + + /** + * Regression guard for https://github.com/Expensify/App/issues/99609: the pressed row's screen has to take + * ownership of the carousel. An earlier fix kept a broader list (e.g. the Spend page's) alive here, which left the + * report showing a counter and arrows covering expenses that weren't in it. + */ + it('stamps the carousel with the source that seeded it', async () => { + await callHook({carouselSource: CAROUSEL_SOURCE.reportRow(report.reportID)}); + + expect(mockedSetActiveTransactionIDs).toHaveBeenCalledWith(SIBLING_TRANSACTION_IDS, {source: CAROUSEL_SOURCE_FOR_REPORT}); + }); + + it('anchors the opened thread to the pressed expense so the header can show the carousel before data loads', async () => { + await callHook(); + + expect(mockedNavigate).toHaveBeenCalledTimes(1); + const route = mockedNavigate.mock.calls.at(0)?.at(0); + expect(route).toContain(THREAD_REPORT_ID); + expect(route).toContain(`anchorTransactionID=${TRANSACTION_ID}`); + }); +}); diff --git a/tests/unit/hooks/useReviewFlaggedExpenses.test.ts b/tests/unit/hooks/useReviewFlaggedExpenses.test.ts index 86ae660fecd9..9f2a60c6cc86 100644 --- a/tests/unit/hooks/useReviewFlaggedExpenses.test.ts +++ b/tests/unit/hooks/useReviewFlaggedExpenses.test.ts @@ -16,6 +16,15 @@ import waitForBatchedUpdatesWithAct from '../../utils/waitForBatchedUpdatesWithA const mockNavigateToTransactionThread = jest.fn(); jest.mock('@hooks/useNavigateToTransactionThread', () => jest.fn(() => mockNavigateToTransactionThread)); +const mockNavigate = jest.fn(); +jest.mock('@libs/Navigation/Navigation', () => ({__esModule: true, default: {navigate: (route: string) => mockNavigate(route)}})); + +const mockSetActiveTransactionIDs = jest.fn, [string[], {source?: string} | undefined]>(() => Promise.resolve()); +jest.mock('@libs/actions/TransactionThreadNavigation', () => ({ + setActiveTransactionIDs: (ids: string[], options?: {source?: string}) => mockSetActiveTransactionIDs(ids, options), + CAROUSEL_SOURCE: {homeReviewFlagged: 'home:reviewFlagged'}, +})); + // The hook gates its O(n) scan on useIsFocused(). Mock it with a toggleable flag so tests can exercise the // focused (live scan) and blurred (scan skipped, last count retained) paths. let mockIsFocused = true; @@ -27,6 +36,14 @@ jest.mock('@react-navigation/native', () => { }; }); +// The one-transaction-report branch opens full-screen on narrow layout and in the RHP on wide, and only the RHP +// renders the carousel, so tests have to drive this deliberately rather than inherit the test env's default. +let mockShouldUseNarrowLayout = false; +jest.mock('@hooks/useResponsiveLayout', () => ({ + __esModule: true, + default: () => ({shouldUseNarrowLayout: mockShouldUseNarrowLayout}), +})); + const ACCOUNT_ID = 1; /** @@ -59,6 +76,7 @@ describe('useReviewFlaggedExpenses', () => { beforeEach(async () => { mockIsFocused = true; + mockShouldUseNarrowLayout = false; await act(async () => { await Onyx.set(ONYXKEYS.SESSION, {accountID: ACCOUNT_ID, email: 'test@example.com'}); }); @@ -129,6 +147,7 @@ describe('useReviewFlaggedExpenses', () => { transaction: expect.objectContaining({transactionID: 't1'}), reportActions: expect.arrayContaining([expect.objectContaining({reportActionID: 'action1', childReportID: 'thread-r1'})]), siblingTransactionIDs: ['t1', 't2'], + carouselSource: 'home:reviewFlagged', backTo: ROUTES.HOME, }), ); @@ -177,6 +196,78 @@ describe('useReviewFlaggedExpenses', () => { ); }); + /** + * Regression guard for https://github.com/Expensify/App/issues/99621: the prev/next carousel opens a + * one-transaction report directly rather than its (redundant) transaction thread. This entry point has to agree, + * or stepping forward and back drops the user on the report when they started on the thread. + */ + it('opens the report and seeds the carousel when the flagged expenses sit in one-transaction reports', async () => { + mockShouldUseNarrowLayout = false; + await act(async () => { + await seedFlaggedExpenses({transactionID: 't1', reportID: 'r1'}, {transactionID: 't2', reportID: 'r2'}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}r1`, {transactionCount: 1}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}r2`, {transactionCount: 1}); + }); + await waitForBatchedUpdatesWithAct(); + + const {result} = renderHook(() => useReviewFlaggedExpenses()); + await waitForBatchedUpdatesWithAct(); + + expect(result.current.count).toBe(2); + + await act(async () => { + result.current.reviewExpenses(); + await waitForBatchedUpdatesWithAct(); + }); + + expect(mockNavigateToTransactionThread).not.toHaveBeenCalled(); + expect(mockSetActiveTransactionIDs).toHaveBeenCalledWith(['t1', 't2'], {source: 'home:reviewFlagged'}); + expect(mockNavigate).toHaveBeenCalledTimes(1); + expect(mockNavigate.mock.calls.at(0)?.at(0)).toContain('r1'); + }); + + it('keeps the thread route for a multi-expense review on narrow layout', async () => { + mockShouldUseNarrowLayout = true; + await act(async () => { + await seedFlaggedExpenses({transactionID: 't1', reportID: 'r1'}, {transactionID: 't2', reportID: 'r2'}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}r1`, {transactionCount: 1}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}r2`, {transactionCount: 1}); + }); + await waitForBatchedUpdatesWithAct(); + + const {result} = renderHook(() => useReviewFlaggedExpenses()); + await waitForBatchedUpdatesWithAct(); + + await act(async () => { + result.current.reviewExpenses(); + await waitForBatchedUpdatesWithAct(); + }); + + expect(mockNavigate).not.toHaveBeenCalled(); + expect(mockNavigateToTransactionThread).toHaveBeenCalledWith( + expect.objectContaining({transactionID: 't1', siblingTransactionIDs: ['t1', 't2'], carouselSource: 'home:reviewFlagged'}), + ); + }); + + it('does not seed a carousel for a lone flagged expense in a one-transaction report', async () => { + await act(async () => { + await seedFlaggedExpenses({transactionID: 't1', reportID: 'r1'}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}r1`, {transactionCount: 1}); + }); + await waitForBatchedUpdatesWithAct(); + + const {result} = renderHook(() => useReviewFlaggedExpenses()); + await waitForBatchedUpdatesWithAct(); + + await act(async () => { + result.current.reviewExpenses(); + await waitForBatchedUpdatesWithAct(); + }); + + expect(mockSetActiveTransactionIDs).not.toHaveBeenCalled(); + expect(mockNavigate).toHaveBeenCalledTimes(1); + }); + it('updates the count live while the Home tab stays focused', async () => { await act(async () => { await seedFlaggedExpenses({transactionID: 't1', reportID: 'r1'}); diff --git a/tests/unit/libs/TransactionThreadNavigationUtilsTest.ts b/tests/unit/libs/TransactionThreadNavigationUtilsTest.ts index 3cf386421a7c..e6978cc5e679 100644 --- a/tests/unit/libs/TransactionThreadNavigationUtilsTest.ts +++ b/tests/unit/libs/TransactionThreadNavigationUtilsTest.ts @@ -111,6 +111,62 @@ describe('getReportIDToOpenForExpense', () => { expect(getReportIDToOpenForExpense(expense, CONTEXT)).toBe('parent4'); expect(mockCreateTransactionThreadReport).not.toHaveBeenCalled(); }); + + /** + * An unreported (tracked) expense keeps its IOU action in the self-DM, since report "0" is a placeholder rather + * than a report. Resolving from there is the only way such an expense opens at all. + */ + describe('unreported (tracked) expenses', () => { + const buildUnreportedExpense = (transactionID: string, reportAction?: ReportAction): TransactionThreadNavigationDescriptor => ({ + reportID: CONST.REPORT.UNREPORTED_REPORT_ID, + transaction: buildTransaction(transactionID, CONST.REPORT.UNREPORTED_REPORT_ID), + reportAction, + }); + + beforeEach(async () => { + await Onyx.set(ONYXKEYS.SELF_DM_REPORT_ID, 'selfDM'); + await waitForBatchedUpdates(); + }); + + it("resolves the thread from the self-DM's report actions when the snapshot has no thread", async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}selfDM`, {a1: buildIOUAction('a1', 'self_dm_thread')}); + await waitForBatchedUpdates(); + + expect(getReportIDToOpenForExpense(buildUnreportedExpense(transactionR14932.transactionID), CONTEXT)).toBe('self_dm_thread'); + expect(mockCreateTransactionThreadReport).not.toHaveBeenCalled(); + }); + + /** + * Regression guard: this used to fall through to report "0", which is not a report that can be opened. The + * prev/next carousel enabled the arrow from the transaction alone and then had nowhere to navigate, so the + * press did nothing at all. + */ + it("creates the thread when the self-DM's IOU action has none yet", async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}selfDM`, {a1: buildIOUAction('a1')}); + await waitForBatchedUpdates(); + + expect(getReportIDToOpenForExpense(buildUnreportedExpense(transactionR14932.transactionID), CONTEXT)).toBe('created_thread'); + expect(mockCreateTransactionThreadReport).toHaveBeenCalledWith( + expect.objectContaining({ + // Report "0" is a placeholder, so there is no parent expense report to build the thread from; + // createTransactionThreadReport parents it to the self-DM off the transaction instead. + iouReport: undefined, + iouReportAction: expect.objectContaining({reportActionID: 'a1'}), + transaction: expect.objectContaining({transactionID: transactionR14932.transactionID}), + }), + ); + }); + + it('creates the thread from the snapshot action when the self-DM actions were never fetched', () => { + expect(getReportIDToOpenForExpense(buildUnreportedExpense('t5', buildIOUAction('a5')), CONTEXT)).toBe('created_thread'); + expect(mockCreateTransactionThreadReport).toHaveBeenCalledWith(expect.objectContaining({iouReportAction: expect.objectContaining({reportActionID: 'a5'})})); + }); + + it('falls back to the unreported placeholder when no IOU action exists anywhere', () => { + expect(getReportIDToOpenForExpense(buildUnreportedExpense('t6'), CONTEXT)).toBe(CONST.REPORT.UNREPORTED_REPORT_ID); + expect(mockCreateTransactionThreadReport).not.toHaveBeenCalled(); + }); + }); }); describe('getOrCreateTransactionThreadReportID', () => { diff --git a/tests/unit/libs/actions/TransactionThreadNavigationTest.ts b/tests/unit/libs/actions/TransactionThreadNavigationTest.ts new file mode 100644 index 000000000000..b0fabc4c81f3 --- /dev/null +++ b/tests/unit/libs/actions/TransactionThreadNavigationTest.ts @@ -0,0 +1,282 @@ +import { + CAROUSEL_SOURCE, + clearActiveTransactionIDs, + clearActiveTransactionIDsForSource, + disownActiveTransactionIDs, + getActiveTransactionIDs, + setActiveTransactionIDs, + shouldRefreshActiveTransactionIDs, +} from '@libs/actions/TransactionThreadNavigation'; + +import ONYXKEYS from '@src/ONYXKEYS'; + +import type {OnyxEntry, OnyxKey, OnyxValue} from 'react-native-onyx'; + +import Onyx from 'react-native-onyx'; + +import createRandomTransaction from '../../../utils/collections/transaction'; +import waitForBatchedUpdates from '../../../utils/waitForBatchedUpdates'; + +const SEARCH_HASH = 959171759; +const SEARCH_SOURCE = CAROUSEL_SOURCE.search(SEARCH_HASH); +const OTHER_SEARCH_SOURCE = CAROUSEL_SOURCE.search(123456); +const REPORT_SOURCE = CAROUSEL_SOURCE.report('B'); + +// The Spend page's expense list, as the carousel was seeded with it when a row was pressed. +const SEEDED_IDS = ['A1', 'A2', 'A3']; + +// The Spend page holds one expense from report A and two from report B; report B owns only its own two. +const SPEND_PAGE_IDS = ['A1', 'B1', 'B2']; +const REPORT_B_IDS = ['B1', 'B2']; + +describe('TransactionThreadNavigation carousel ownership', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(async () => { + await clearActiveTransactionIDs(); + await waitForBatchedUpdates(); + }); + + /** Reads the three carousel keys straight out of Onyx, which is where every consumer actually reads them. */ + async function readCarouselFromOnyx() { + await waitForBatchedUpdates(); + const readOnce = (key: TKey) => + new Promise>>((resolve) => { + const connection = Onyx.connect({ + key, + callback: (value) => { + Onyx.disconnect(connection); + resolve(value); + }, + }); + }); + const [ids, snapshotHash, descriptors] = await Promise.all([ + readOnce(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS), + readOnce(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_SNAPSHOT_HASH), + readOnce(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_THREAD_REPORT_IDS), + ]); + return {ids, snapshotHash, descriptors}; + } + + describe('setActiveTransactionIDs', () => { + it('records the owning source alongside the IDs', async () => { + await setActiveTransactionIDs(SEEDED_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + + expect(getActiveTransactionIDs()).toEqual({ids: SEEDED_IDS, descriptors: null, source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + }); + + /** + * `getActiveTransactionIDs` reads the in-module mirror, which only arbitrates writes within one session. + * Every consumer - the header, the carousel - reads Onyx, so the Onyx writes need asserting on their own: + * without this, deleting them would leave the suite green while the arrows vanished app-wide. + */ + it('writes the IDs, snapshot hash and descriptors through to Onyx', async () => { + const descriptors = {A1: {reportID: 'rA', transaction: {...createRandomTransaction(1), transactionID: 'A1'}}}; + await setActiveTransactionIDs(SEEDED_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH, descriptors}); + + await expect(readCarouselFromOnyx()).resolves.toEqual({ids: SEEDED_IDS, snapshotHash: SEARCH_HASH, descriptors}); + }); + + it('clears all three Onyx keys when the carousel is released', async () => { + await setActiveTransactionIDs(SEEDED_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + await clearActiveTransactionIDsForSource(SEARCH_SOURCE); + + await expect(readCarouselFromOnyx()).resolves.toEqual({ids: undefined, snapshotHash: undefined, descriptors: undefined}); + }); + + it('lets a different screen take ownership of the carousel', async () => { + await setActiveTransactionIDs(SPEND_PAGE_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + await setActiveTransactionIDs(REPORT_B_IDS, {source: REPORT_SOURCE}); + + expect(getActiveTransactionIDs()).toEqual({ids: REPORT_B_IDS, descriptors: null, source: REPORT_SOURCE, snapshotHash: null}); + }); + + /** + * Duplicate review takes the carousel over while it is open and hands the previous one back on refocus. It + * can only do that if everything it read back is also something it can write, so a restored carousel keeps + * its original owner (which is what lets that screen refresh and release it) along with the snapshot hash + * and descriptors its siblings are resolved from. + */ + it('round-trips a displaced carousel back to its original owner', async () => { + const descriptors = {A1: {reportID: 'rA', transaction: {...createRandomTransaction(1), transactionID: 'A1'}}}; + await setActiveTransactionIDs(SEEDED_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH, descriptors}); + const displaced = getActiveTransactionIDs(); + + await setActiveTransactionIDs(REPORT_B_IDS, {source: CAROUSEL_SOURCE.duplicateReview('B1')}); + await setActiveTransactionIDs(displaced.ids ?? [], { + source: displaced.source ?? undefined, + snapshotHash: displaced.snapshotHash ?? undefined, + descriptors: displaced.descriptors ?? undefined, + }); + + expect(getActiveTransactionIDs()).toEqual({ids: SEEDED_IDS, descriptors, source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + // The original owner can refresh its own carousel again, which is what the source is for. + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, SPEND_PAGE_IDS)).toBe(true); + }); + }); + + /** + * Regression guard for https://github.com/Expensify/App/issues/99609 and + * https://github.com/Expensify/App/issues/99617: a search list left mounted behind the RHP used to keep pushing + * its own (broader, or stale) list over the carousel of whatever screen the user had drilled into. + */ + describe('shouldRefreshActiveTransactionIDs', () => { + it('seeds when no carousel is active', () => { + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, SEEDED_IDS)).toBe(true); + }); + + it('does not seed a list with nothing to page between', () => { + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, ['A1'])).toBe(false); + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, [])).toBe(false); + }); + + /** + * That length rule applies only to taking the carousel over, never to the screen that already owns it. + * Applied to the owner too, it let a list grow its carousel but never shrink or release it, so a list that + * dropped to a single expense left the old, longer list active and the arrows still showing. + */ + it('lets its owner shrink the carousel down to nothing to page between', async () => { + await setActiveTransactionIDs(SEEDED_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, ['A1'])).toBe(true); + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, [])).toBe(true); + }); + + it('refreshes its own carousel when the list gained an expense', async () => { + await setActiveTransactionIDs(SEEDED_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, ['A0', ...SEEDED_IDS])).toBe(true); + }); + + it('refreshes its own carousel when the list lost an expense', async () => { + await setActiveTransactionIDs(SEEDED_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, ['A1', 'A3'])).toBe(true); + }); + + it('refreshes its own carousel when only the order changed', async () => { + await setActiveTransactionIDs(SEEDED_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, ['A3', 'A2', 'A1'])).toBe(true); + }); + + it('skips the write when its own carousel is already up to date', async () => { + await setActiveTransactionIDs(SEEDED_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, [...SEEDED_IDS])).toBe(false); + }); + + it('leaves a carousel owned by another screen alone', async () => { + await setActiveTransactionIDs(REPORT_B_IDS, {source: REPORT_SOURCE}); + + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, SPEND_PAGE_IDS)).toBe(false); + }); + + it('leaves a carousel owned by a different search alone', async () => { + await setActiveTransactionIDs(SEEDED_IDS, {source: OTHER_SEARCH_SOURCE, snapshotHash: 123456}); + + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, SPEND_PAGE_IDS)).toBe(false); + }); + + it('re-seeds once the owning screen releases the carousel', async () => { + await setActiveTransactionIDs(REPORT_B_IDS, {source: REPORT_SOURCE}); + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, SPEND_PAGE_IDS)).toBe(false); + + await clearActiveTransactionIDsForSource(REPORT_SOURCE); + + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, SPEND_PAGE_IDS)).toBe(true); + }); + + it('ignores a carousel that only exists in persisted Onyx state', async () => { + // The Onyx key is persisted, so on a fresh load it can hold a carousel from an earlier session. Without a + // recorded owner there is nothing to defer to, so the visible list wins. + await Onyx.set(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS, SPEND_PAGE_IDS); + await waitForBatchedUpdates(); + + expect(shouldRefreshActiveTransactionIDs(SEARCH_SOURCE, SEEDED_IDS)).toBe(true); + }); + }); + + /** + * Regression guard for https://github.com/Expensify/App/issues/99630: a screen tearing down used to clear the + * carousel unconditionally, wiping the list another screen had already taken over and leaving no arrows at all. + */ + describe('clearActiveTransactionIDsForSource', () => { + it('clears a carousel it still owns', async () => { + await setActiveTransactionIDs(REPORT_B_IDS, {source: REPORT_SOURCE}); + + await clearActiveTransactionIDsForSource(REPORT_SOURCE); + + expect(getActiveTransactionIDs()).toEqual({ids: null, descriptors: null, source: null, snapshotHash: null}); + }); + + it('leaves a carousel another screen has taken over', async () => { + await setActiveTransactionIDs(REPORT_B_IDS, {source: REPORT_SOURCE}); + await setActiveTransactionIDs(SPEND_PAGE_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + + await clearActiveTransactionIDsForSource(REPORT_SOURCE); + + expect(getActiveTransactionIDs()).toEqual({ids: SPEND_PAGE_IDS, descriptors: null, source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + }); + }); + + /** + * Search is keyed by its query hash, so re-sorting or re-filtering unmounts the list that seeded the carousel + * and mounts a replacement under a new source. Clearing on the way out stripped the arrows of an expense open + * in the RHP until the replacement had loaded - and for good, when the new results no longer held it. + */ + describe('disownActiveTransactionIDs', () => { + it('keeps the list so an expense open on top of it keeps its arrows', async () => { + await setActiveTransactionIDs(SEEDED_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + + disownActiveTransactionIDs(SEARCH_SOURCE); + + expect(getActiveTransactionIDs()).toEqual({ids: SEEDED_IDS, descriptors: null, source: null, snapshotHash: SEARCH_HASH}); + expect((await readCarouselFromOnyx()).ids).toEqual(SEEDED_IDS); + }); + + it('lets the screen that replaces the previous writer take the carousel over', async () => { + await setActiveTransactionIDs(SEEDED_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + expect(shouldRefreshActiveTransactionIDs(OTHER_SEARCH_SOURCE, SPEND_PAGE_IDS)).toBe(false); + + disownActiveTransactionIDs(SEARCH_SOURCE); + + expect(shouldRefreshActiveTransactionIDs(OTHER_SEARCH_SOURCE, SPEND_PAGE_IDS)).toBe(true); + }); + + /** + * Regression guard for https://github.com/Expensify/App/pull/100331#issuecomment-5812384643: switching from + * Spend > Expenses to Spend > Reports unmounts the expense list (which disowns its carousel) and mounts a + * list of report groups with no transaction rows to seed from. Refusing that empty write left the Expenses + * tab's list active, so the first one-expense report the user paged onto swapped its report arrows for that + * stale expense carousel and paged them out of the reports they were browsing. + */ + it('lets the screen that replaces the previous writer retire a disowned carousel', async () => { + await setActiveTransactionIDs(SEEDED_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + + disownActiveTransactionIDs(SEARCH_SOURCE); + + expect(shouldRefreshActiveTransactionIDs(OTHER_SEARCH_SOURCE, ['A1'])).toBe(true); + expect(shouldRefreshActiveTransactionIDs(OTHER_SEARCH_SOURCE, [])).toBe(true); + }); + + it('leaves a disowned carousel alone when the replacement list is identical', async () => { + await setActiveTransactionIDs(SEEDED_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + + disownActiveTransactionIDs(SEARCH_SOURCE); + + expect(shouldRefreshActiveTransactionIDs(OTHER_SEARCH_SOURCE, SEEDED_IDS)).toBe(false); + }); + + it('leaves a carousel another screen has taken over', async () => { + await setActiveTransactionIDs(REPORT_B_IDS, {source: REPORT_SOURCE}); + await setActiveTransactionIDs(SPEND_PAGE_IDS, {source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + + disownActiveTransactionIDs(REPORT_SOURCE); + + expect(getActiveTransactionIDs()).toEqual({ids: SPEND_PAGE_IDS, descriptors: null, source: SEARCH_SOURCE, snapshotHash: SEARCH_HASH}); + }); + }); +}); diff --git a/tests/unit/useMoneyRequestReportActiveTransactionIDsTest.ts b/tests/unit/useMoneyRequestReportActiveTransactionIDsTest.ts index c3a76001f7ae..3fb9b4dbc767 100644 --- a/tests/unit/useMoneyRequestReportActiveTransactionIDsTest.ts +++ b/tests/unit/useMoneyRequestReportActiveTransactionIDsTest.ts @@ -2,7 +2,7 @@ import {renderHook} from '@testing-library/react-native'; import useMoneyRequestReportActiveTransactionIDs from '@components/MoneyRequestReportView/useMoneyRequestReportActiveTransactionIDs'; -import {clearActiveTransactionIDs, getActiveTransactionIDs, setActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; +import {clearActiveTransactionIDsForSource, getActiveTransactionIDs, setActiveTransactionIDs} from '@libs/actions/TransactionThreadNavigation'; import {navigationRef} from '@libs/Navigation/Navigation'; import SCREENS from '@src/SCREENS'; @@ -15,8 +15,9 @@ import createMock from '../utils/createMock'; // Mock the TransactionThreadNavigation module jest.mock('@libs/actions/TransactionThreadNavigation', () => ({ setActiveTransactionIDs: jest.fn(() => Promise.resolve()), - clearActiveTransactionIDs: jest.fn(() => Promise.resolve()), - getActiveTransactionIDs: jest.fn(() => ({ids: null, descriptors: null})), + clearActiveTransactionIDsForSource: jest.fn(() => Promise.resolve()), + getActiveTransactionIDs: jest.fn(() => ({ids: null, descriptors: null, source: null})), + CAROUSEL_SOURCE: {report: (reportID: string | undefined) => `report:${reportID}`}, })); // Mock the navigation module @@ -34,16 +35,19 @@ jest.mock('@react-navigation/native', () => ({ useFocusEffect: jest.fn(), })); +const REPORT_ID = 'reportA'; +const CAROUSEL_SOURCE_FOR_REPORT = `report:${REPORT_ID}`; + describe('useMoneyRequestReportActiveTransactionIDs', () => { const mockSetActiveTransactionIDs = jest.mocked(setActiveTransactionIDs); - const mockClearActiveTransactionIDs = jest.mocked(clearActiveTransactionIDs); + const mockClearActiveTransactionIDsForSource = jest.mocked(clearActiveTransactionIDsForSource); const mockGetActiveTransactionIDs = jest.mocked(getActiveTransactionIDs); const mockFindFocusedRoute = jest.mocked(findFocusedRoute); const mockGetRootState = jest.spyOn(navigationRef, 'getRootState'); beforeEach(() => { jest.clearAllMocks(); - mockGetActiveTransactionIDs.mockReturnValue({ids: null, descriptors: null}); + mockGetActiveTransactionIDs.mockReturnValue({ids: null, descriptors: null, source: null, snapshotHash: null}); mockGetRootState.mockReturnValue(createMock>>({})); }); @@ -54,10 +58,10 @@ describe('useMoneyRequestReportActiveTransactionIDs', () => { const transactionIDs = ['trans1', 'trans2', 'trans3']; // When the hook is rendered - renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs)); + renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs, REPORT_ID)); - // Then setActiveTransactionIDs should be called with the transaction IDs - expect(mockSetActiveTransactionIDs).toHaveBeenCalledWith(transactionIDs); + // Then setActiveTransactionIDs should be called with the transaction IDs, stamped with this report's source + expect(mockSetActiveTransactionIDs).toHaveBeenCalledWith(transactionIDs, {source: CAROUSEL_SOURCE_FOR_REPORT}); }); it('should NOT call setActiveTransactionIDs when focused route is NOT SEARCH_REPORT', () => { @@ -67,7 +71,7 @@ describe('useMoneyRequestReportActiveTransactionIDs', () => { const transactionIDs = ['trans1', 'trans2']; // When the hook is rendered - renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs)); + renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs, REPORT_ID)); // Then setActiveTransactionIDs should NOT be called expect(mockSetActiveTransactionIDs).not.toHaveBeenCalled(); @@ -77,45 +81,62 @@ describe('useMoneyRequestReportActiveTransactionIDs', () => { // Given there is no focused route mockFindFocusedRoute.mockReturnValue(undefined); - const transactionIDs = ['trans1']; + const transactionIDs = ['trans1', 'trans2']; // When the hook is rendered - renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs)); + renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs, REPORT_ID)); // Then setActiveTransactionIDs should NOT be called expect(mockSetActiveTransactionIDs).not.toHaveBeenCalled(); }); - it('should call clearActiveTransactionIDs on unmount when route was SEARCH_REPORT', () => { + // A report with one expense (or none) has nothing to page between. Seeding it would clobber the broader carousel + // the user drilled in from, and leave the header rendering an empty expense carousel. + it.each([ + ['a single transaction', ['trans1']], + ['no transactions', [] as string[]], + ])('should NOT seed the carousel for a report with %s', (_label, transactionIDs) => { + // Given the focused route is SEARCH_REPORT + mockFindFocusedRoute.mockReturnValue({name: SCREENS.RIGHT_MODAL.SEARCH_REPORT, key: 'test-key'}); + + // When the hook is rendered for a report that has nothing to page between + renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs, REPORT_ID)); + + // Then nothing is written through + expect(mockSetActiveTransactionIDs).not.toHaveBeenCalled(); + }); + + it('should release the carousel on unmount when route was SEARCH_REPORT', () => { // Given the focused route is SEARCH_REPORT mockFindFocusedRoute.mockReturnValue({name: SCREENS.RIGHT_MODAL.SEARCH_REPORT, key: 'test-key'}); const transactionIDs = ['trans1', 'trans2']; // When the hook is rendered and then unmounted - const {unmount} = renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs)); + const {unmount} = renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs, REPORT_ID)); - expect(mockClearActiveTransactionIDs).not.toHaveBeenCalled(); + expect(mockClearActiveTransactionIDsForSource).not.toHaveBeenCalled(); unmount(); - // Then clearActiveTransactionIDs should be called - expect(mockClearActiveTransactionIDs).toHaveBeenCalledTimes(1); + // Then it should release only its own carousel, not whatever is active + expect(mockClearActiveTransactionIDsForSource).toHaveBeenCalledTimes(1); + expect(mockClearActiveTransactionIDsForSource).toHaveBeenCalledWith(CAROUSEL_SOURCE_FOR_REPORT); }); - it('should NOT call clearActiveTransactionIDs on unmount when route was NOT SEARCH_REPORT', () => { + it('should NOT release the carousel on unmount when route was NOT SEARCH_REPORT', () => { // Given the focused route is NOT SEARCH_REPORT mockFindFocusedRoute.mockReturnValue({name: 'SomeOtherRoute', key: 'test-key'}); - const transactionIDs = ['trans1']; + const transactionIDs = ['trans1', 'trans2']; // When the hook is rendered and then unmounted - const {unmount} = renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs)); + const {unmount} = renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs, REPORT_ID)); unmount(); - // Then clearActiveTransactionIDs should NOT be called (since the effect returned early, no cleanup was registered) - expect(mockClearActiveTransactionIDs).not.toHaveBeenCalled(); + // Then nothing was seeded, so nothing should be released + expect(mockClearActiveTransactionIDsForSource).not.toHaveBeenCalled(); }); it('should update active transaction IDs when the list changes', () => { @@ -125,12 +146,12 @@ describe('useMoneyRequestReportActiveTransactionIDs', () => { const initialTransactionIDs = ['trans1', 'trans2']; // When the hook is rendered - const {rerender} = renderHook(({ids}) => useMoneyRequestReportActiveTransactionIDs(ids), { + const {rerender} = renderHook(({ids}) => useMoneyRequestReportActiveTransactionIDs(ids, REPORT_ID), { initialProps: {ids: initialTransactionIDs}, }); expect(mockSetActiveTransactionIDs).toHaveBeenCalledTimes(1); - expect(mockSetActiveTransactionIDs).toHaveBeenLastCalledWith(initialTransactionIDs); + expect(mockSetActiveTransactionIDs).toHaveBeenLastCalledWith(initialTransactionIDs, {source: CAROUSEL_SOURCE_FOR_REPORT}); // When the transaction IDs change const newTransactionIDs = ['trans1', 'trans2', 'trans3']; @@ -138,23 +159,28 @@ describe('useMoneyRequestReportActiveTransactionIDs', () => { // Then setActiveTransactionIDs should be called again with the new IDs expect(mockSetActiveTransactionIDs).toHaveBeenCalledTimes(2); - expect(mockSetActiveTransactionIDs).toHaveBeenLastCalledWith(newTransactionIDs); + expect(mockSetActiveTransactionIDs).toHaveBeenLastCalledWith(newTransactionIDs, {source: CAROUSEL_SOURCE_FOR_REPORT}); }); - it('should clear the previous seed before re-seeding when the rows change', () => { + /** + * Regression guard for https://github.com/Expensify/App/issues/99630: teardown used to be the seeding effect's + * own cleanup, so React ran it on every re-seed. Any run that then bailed out at a guard left the carousel + * cleared, and the arrows vanished after an action that changed the report's transactions (duplicating an + * expense, for instance). + */ + it('should NOT release the carousel while re-seeding it', () => { // Given the focused route is SEARCH_REPORT and the hook seeded the carousel mockFindFocusedRoute.mockReturnValue({name: SCREENS.RIGHT_MODAL.SEARCH_REPORT, key: 'test-key'}); - const {rerender} = renderHook(({ids}) => useMoneyRequestReportActiveTransactionIDs(ids), { + + const {rerender} = renderHook(({ids}) => useMoneyRequestReportActiveTransactionIDs(ids, REPORT_ID), { initialProps: {ids: ['trans1', 'trans2']}, }); - // When the rows change - rerender({ids: ['trans1']}); + // When the rows change and the carousel is re-seeded + rerender({ids: ['trans1', 'trans2', 'trans3']}); - // Then the old seed is cleared by the effect cleanup before the new one is written - expect(mockClearActiveTransactionIDs).toHaveBeenCalledTimes(1); - expect(mockClearActiveTransactionIDs.mock.invocationCallOrder.at(0)).toBeLessThan(mockSetActiveTransactionIDs.mock.invocationCallOrder.at(1) ?? 0); - expect(mockSetActiveTransactionIDs).toHaveBeenLastCalledWith(['trans1']); + // Then the carousel is never released in between, so the arrows stay on screen + expect(mockClearActiveTransactionIDsForSource).not.toHaveBeenCalled(); }); it('should NOT re-fire when array reference changes but content is the same', () => { @@ -164,7 +190,7 @@ describe('useMoneyRequestReportActiveTransactionIDs', () => { const initialTransactionIDs = ['trans1', 'trans2']; // When the hook is rendered - const {rerender} = renderHook(({ids}) => useMoneyRequestReportActiveTransactionIDs(ids), { + const {rerender} = renderHook(({ids}) => useMoneyRequestReportActiveTransactionIDs(ids, REPORT_ID), { initialProps: {ids: initialTransactionIDs}, }); @@ -177,7 +203,7 @@ describe('useMoneyRequestReportActiveTransactionIDs', () => { // Then the effect should NOT re-fire because the join(',') key hasn't changed. // This prevents overwriting IDs set by other callers (e.g. TransactionDuplicateReview.onPreviewPressed). expect(mockSetActiveTransactionIDs).toHaveBeenCalledTimes(1); - expect(mockClearActiveTransactionIDs).not.toHaveBeenCalled(); + expect(mockClearActiveTransactionIDsForSource).not.toHaveBeenCalled(); }); it('should NOT take over a snapshot-backed carousel that already has sibling descriptors', () => { @@ -186,63 +212,104 @@ describe('useMoneyRequestReportActiveTransactionIDs', () => { mockGetActiveTransactionIDs.mockReturnValue({ ids: ['recentlyAdded1', 'recentlyAdded2'], descriptors: {recentlyAdded1: {reportID: 'r1', transaction: {...createRandomTransaction(1), transactionID: 'recentlyAdded1'}}}, + source: 'home:recentlyAdded', + snapshotHash: null, }); const transactionIDs = ['trans1', 'trans2', 'trans3']; // When the hook is rendered and then unmounted - const {unmount} = renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs)); + const {unmount} = renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs, REPORT_ID)); // Then it should neither overwrite nor clear the existing carousel context expect(mockSetActiveTransactionIDs).not.toHaveBeenCalled(); unmount(); - expect(mockClearActiveTransactionIDs).not.toHaveBeenCalled(); + expect(mockClearActiveTransactionIDsForSource).not.toHaveBeenCalled(); }); it('should keep an active seed that covers the same rows in a different order', () => { // Given the focused route is SEARCH_REPORT and a report preview press seeded the same rows in carousel order mockFindFocusedRoute.mockReturnValue({name: SCREENS.RIGHT_MODAL.SEARCH_REPORT, key: 'test-key'}); - mockGetActiveTransactionIDs.mockReturnValue({ids: ['trans3', 'trans1', 'trans2'], descriptors: null}); + mockGetActiveTransactionIDs.mockReturnValue({ids: ['trans3', 'trans1', 'trans2'], descriptors: null, source: null, snapshotHash: null}); const transactionIDs = ['trans1', 'trans2', 'trans3']; // When the hook is rendered and then unmounted - const {unmount} = renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs)); + const {unmount} = renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs, REPORT_ID)); // Then it should neither overwrite the carousel order nor clear it expect(mockSetActiveTransactionIDs).not.toHaveBeenCalled(); unmount(); - expect(mockClearActiveTransactionIDs).not.toHaveBeenCalled(); + expect(mockClearActiveTransactionIDsForSource).not.toHaveBeenCalled(); }); - it('should re-seed when the active seed covers different rows', () => { - // Given the focused route is SEARCH_REPORT and the active seed is missing one of the rows + it('should re-seed a carousel it owns when the same rows are re-ordered', () => { + // Given the focused route is SEARCH_REPORT and this report owns a seed holding exactly these rows, in the + // order they were rendered before the user sorted a column mockFindFocusedRoute.mockReturnValue({name: SCREENS.RIGHT_MODAL.SEARCH_REPORT, key: 'test-key'}); - mockGetActiveTransactionIDs.mockReturnValue({ids: ['trans2', 'trans1'], descriptors: null}); + mockGetActiveTransactionIDs.mockReturnValue({ids: ['trans1', 'trans2', 'trans3'], descriptors: null, source: CAROUSEL_SOURCE_FOR_REPORT, snapshotHash: null}); - const transactionIDs = ['trans1', 'trans2', 'trans3']; + const sortedTransactionIDs = ['trans3', 'trans1', 'trans2']; + + // When the rows come back in a different order + renderHook(() => useMoneyRequestReportActiveTransactionIDs(sortedTransactionIDs, REPORT_ID)); + + // Then the new order is written through: the arrows walk the rows the user is looking at, so a seed this + // list owns has to follow the rendered order rather than stay frozen at the order it was first seeded in + expect(mockSetActiveTransactionIDs).toHaveBeenCalledWith(sortedTransactionIDs, {source: CAROUSEL_SOURCE_FOR_REPORT}); + }); + + it('should NOT take over a carousel it does not own with fewer than two rows', () => { + // Given the focused route is SEARCH_REPORT, a broader carousel is active, and this report has one row left + mockFindFocusedRoute.mockReturnValue({name: SCREENS.RIGHT_MODAL.SEARCH_REPORT, key: 'test-key'}); + mockGetActiveTransactionIDs.mockReturnValue({ids: ['spend1', 'spend2', 'spend3'], descriptors: null, source: 'search:1234', snapshotHash: 1234}); // When the hook is rendered - renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs)); + renderHook(() => useMoneyRequestReportActiveTransactionIDs(['trans1'], REPORT_ID)); - // Then setActiveTransactionIDs should be called with the visual order - expect(mockSetActiveTransactionIDs).toHaveBeenCalledWith(transactionIDs); + // Then the broader carousel is left alone + expect(mockSetActiveTransactionIDs).not.toHaveBeenCalled(); }); - it('should handle empty transaction IDs array', () => { - // Given the focused route is SEARCH_REPORT + it('should shrink a carousel it owns when the report drops below two rows', () => { + // Given the focused route is SEARCH_REPORT and this report owns a two-entry carousel + mockFindFocusedRoute.mockReturnValue({name: SCREENS.RIGHT_MODAL.SEARCH_REPORT, key: 'test-key'}); + mockGetActiveTransactionIDs.mockReturnValue({ids: ['trans1', 'trans2'], descriptors: null, source: CAROUSEL_SOURCE_FOR_REPORT, snapshotHash: null}); + + // When one of the expenses leaves the report (e.g. it was moved to another report) + renderHook(() => useMoneyRequestReportActiveTransactionIDs(['trans1'], REPORT_ID)); + + // Then the shorter list is written through, so the counter and arrows stop offering the expense that left + expect(mockSetActiveTransactionIDs).toHaveBeenCalledWith(['trans1'], {source: CAROUSEL_SOURCE_FOR_REPORT}); + }); + + it('should NOT write an empty list over a carousel it owns', () => { + // Given the focused route is SEARCH_REPORT and this report owns the carousel + mockFindFocusedRoute.mockReturnValue({name: SCREENS.RIGHT_MODAL.SEARCH_REPORT, key: 'test-key'}); + mockGetActiveTransactionIDs.mockReturnValue({ids: ['trans1', 'trans2'], descriptors: null, source: CAROUSEL_SOURCE_FOR_REPORT, snapshotHash: null}); + + // When the report renders with no rows at all + renderHook(() => useMoneyRequestReportActiveTransactionIDs([], REPORT_ID)); + + // Then nothing is written: an empty list carries no information the header can act on + expect(mockSetActiveTransactionIDs).not.toHaveBeenCalled(); + }); + + it('should re-seed when the active seed covers different rows', () => { + // Given the focused route is SEARCH_REPORT and the active seed is missing one of the rows mockFindFocusedRoute.mockReturnValue({name: SCREENS.RIGHT_MODAL.SEARCH_REPORT, key: 'test-key'}); + mockGetActiveTransactionIDs.mockReturnValue({ids: ['trans2', 'trans1'], descriptors: null, source: null, snapshotHash: null}); - const emptyTransactionIDs: string[] = []; + const transactionIDs = ['trans1', 'trans2', 'trans3']; - // When the hook is rendered with empty array - renderHook(() => useMoneyRequestReportActiveTransactionIDs(emptyTransactionIDs)); + // When the hook is rendered + renderHook(() => useMoneyRequestReportActiveTransactionIDs(transactionIDs, REPORT_ID)); - // Then setActiveTransactionIDs should be called with empty array - expect(mockSetActiveTransactionIDs).toHaveBeenCalledWith([]); + // Then setActiveTransactionIDs should be called with the visual order, stamped with this report's source + expect(mockSetActiveTransactionIDs).toHaveBeenCalledWith(transactionIDs, {source: CAROUSEL_SOURCE_FOR_REPORT}); }); });