diff --git a/src/pages/RestrictedAction/Workspace/WorkspaceOwnerRestrictedAction/index.native.tsx b/src/pages/RestrictedAction/Workspace/WorkspaceOwnerRestrictedAction/index.native.tsx index 7e3a012ddbea..923d2993f1a7 100644 --- a/src/pages/RestrictedAction/Workspace/WorkspaceOwnerRestrictedAction/index.native.tsx +++ b/src/pages/RestrictedAction/Workspace/WorkspaceOwnerRestrictedAction/index.native.tsx @@ -17,7 +17,7 @@ import variables from '@styles/variables'; import CONST from '@src/CONST'; import ROUTES from '@src/ROUTES'; -import React, {useCallback, useMemo} from 'react'; +import React from 'react'; import {View} from 'react-native'; function WorkspaceOwnerRestrictedAction() { @@ -26,11 +26,18 @@ function WorkspaceOwnerRestrictedAction() { const styles = useThemeStyles(); const expensifyIcons = useMemoizedLazyExpensifyIcons(['Unlock']); - const activeRoute = useMemo(() => Navigation.getActiveRoute(), []); - const goToSubscription = useCallback(() => { - Navigation.closeRHPFlow(); - Navigation.navigate(ROUTES.SETTINGS_SUBSCRIPTION.getRoute(activeRoute)); - }, [activeRoute]); + const goToSubscription = () => { + // Read the active route at press time rather than snapshotting it at mount. This screen stays + // mounted underneath the Subscription page, so a mount-time snapshot can be taken while + // Subscription is the focused route, which would make `backTo` point at Subscription itself. + // `linkTo` then drops the navigation as a no-op and the button stops working after a swipe back. + // A press can only happen while this screen is on top, so reading it here always resolves to + // the restricted-action route. + // + // Don't close the RHP here either. Doing so pops this screen off the root stack, so the native + // swipe-back gesture lands on whatever was underneath instead of returning here. + Navigation.navigate(ROUTES.SETTINGS_SUBSCRIPTION.getRoute(Navigation.getActiveRoute())); + }; return ( openSubscriptionPage(gracePeriodsRef.current), - }); - - // Fetch fresh billing NVPs from the server on mount. - // The cached billing data may be stale, causing the restriction to persist - // even after the workspace owner has resolved their billing issue. - // Skip when offline since the API call won't go through and the optimistic - // clear would incorrectly lift the restriction. + const {isOffline} = useNetwork(); + + // Fetch fresh billing NVPs from the server on mount, and again whenever this screen regains focus or the + // device reconnects. The cached billing data may be stale, causing the restriction to persist even after + // the workspace owner has resolved their billing issue. + // + // Skip when offline since the API call won't go through and the optimistic clear would incorrectly lift + // the restriction. Skip while unfocused too: this screen stays mounted underneath the Subscription page, + // which runs the same fetch itself, so firing ours as well would duplicate the request and flip the + // shared `isLoadingSubscriptionData` flag out from under the focused page. + // + // A `useNetwork({onReconnect})` callback is deliberately not used here. `isOffline` flipping back to + // false already re-runs this effect on reconnect, so the callback only fired the same request a second + // time. It also fired outside this focus guard. useEffect(() => { - if (isOffline) { + if (isOffline || !isFocused) { return; } openSubscriptionPage(gracePeriodsRef.current); - }, [isOffline]); + }, [isOffline, isFocused]); // Navigate back if the fresh server data shows the restriction no longer applies. + // Only do this while focused, since this screen stays mounted underneath the Subscription page. + // Resolving the billing issue there would otherwise pop the Subscription page out from under the user. useEffect(() => { - if (isLoadingSubscriptionData !== false) { + if (isLoadingSubscriptionData !== false || !isFocused) { return; } if (!shouldRestrictUserBillableActions(policy, ownerBillingGracePeriodEnd, userBillingGracePeriods, amountOwed, accountID)) { Navigation.goBack(); } - }, [policy, isLoadingSubscriptionData, userBillingGracePeriods, ownerBillingGracePeriodEnd, amountOwed, accountID]); + }, [policy, isLoadingSubscriptionData, userBillingGracePeriods, ownerBillingGracePeriodEnd, amountOwed, accountID, isFocused]); // Show a loading indicator while waiting for fresh billing data from the server, // instead of flashing the restriction UI which may no longer apply. // Skip the loading indicator when offline since the API call won't go through. - if (isLoadingSubscriptionData !== false && !isOffline) { + // Also skip it while unfocused: this screen stays mounted underneath the Subscription page, whose + // own fetch toggles the same global loading flag. Swapping the content out here would needlessly + // unmount and remount the restriction UI behind the user's back, discarding its state. + if (isLoadingSubscriptionData !== false && !isOffline && isFocused) { return ; } diff --git a/tests/unit/pages/RestrictedAction/WorkspaceOwnerRestrictedActionTest.tsx b/tests/unit/pages/RestrictedAction/WorkspaceOwnerRestrictedActionTest.tsx index aac3db77174d..ecfe857939ff 100644 --- a/tests/unit/pages/RestrictedAction/WorkspaceOwnerRestrictedActionTest.tsx +++ b/tests/unit/pages/RestrictedAction/WorkspaceOwnerRestrictedActionTest.tsx @@ -12,11 +12,15 @@ import React from 'react'; // Jest resolves index.native.tsx by default in the RN test environment; load web implementation explicitly. const {default: WorkspaceOwnerRestrictedActionWeb} = jest.requireActual<{default: React.ComponentType}>('@src/pages/RestrictedAction/Workspace/WorkspaceOwnerRestrictedAction/index.tsx'); +// Held in a variable so tests can change the active route between render and press, which is what +// happens on device when this screen is covered by the Subscription page. +const mockGetActiveRoute = jest.fn(() => 'r/123'); + jest.mock('@libs/Navigation/Navigation', () => ({ dismissModal: jest.fn(), closeRHPFlow: jest.fn(), navigate: jest.fn(), - getActiveRoute: jest.fn(() => 'r/123'), + getActiveRoute: () => mockGetActiveRoute(), goBack: jest.fn(), })); @@ -113,6 +117,7 @@ function getDismissModalAfterTransition(): (() => void) | undefined { describe('WorkspaceOwnerRestrictedAction', () => { beforeEach(() => { jest.clearAllMocks(); + mockGetActiveRoute.mockReturnValue('r/123'); }); it('dismisses modal before navigating to add payment card on web', () => { @@ -132,14 +137,36 @@ describe('WorkspaceOwnerRestrictedAction', () => { expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.SETTINGS_SUBSCRIPTION_ADD_PAYMENT_CARD); }); - it('uses unchanged native handler to navigate to subscription route', () => { + it('navigates to subscription without closing the RHP so swiping back returns to the restricted screen', () => { + // Given the native restricted action screen, which is rendered inside the RHP render(); + // When the owner taps "Go to Subscription" fireEvent.press(screen.getByText('workspace.restrictedAction.goToSubscription')); - expect(Navigation.closeRHPFlow).toHaveBeenCalledTimes(1); + // Then the RHP must stay on the root stack. Closing it pops this screen off the stack, and the + // native swipe-back gesture would then reveal whatever was underneath instead of coming back here. + expect(Navigation.closeRHPFlow).not.toHaveBeenCalled(); expect(Navigation.navigate).toHaveBeenCalledTimes(1); expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.SETTINGS_SUBSCRIPTION.getRoute('r/123')); expect(Navigation.dismissModal).not.toHaveBeenCalled(); }); + + it('resolves backTo at press time so the button still works after swiping back from subscription', () => { + // Given this screen mounting while the Subscription page is the focused route. That really happens: + // the screen stays mounted underneath Subscription, and Subscription's own billing fetch toggles the + // shared loading flag that swaps this screen's content out and back in while it is covered. + mockGetActiveRoute.mockReturnValue('settings/subscription?backTo=r%2F123'); + render(); + + // When the user swipes back, re-focusing this screen, and taps "Go to Subscription" again + mockGetActiveRoute.mockReturnValue('r/123'); + fireEvent.press(screen.getByText('workspace.restrictedAction.goToSubscription')); + + // Then backTo must be the restricted-action route, not Subscription. A mount-time snapshot of the + // active route could be captured while Subscription was on top, making backTo self-referential. + // `linkTo` discards such a navigation as a no-op and the button silently stops working. + expect(Navigation.navigate).toHaveBeenCalledTimes(1); + expect(Navigation.navigate).toHaveBeenCalledWith(ROUTES.SETTINGS_SUBSCRIPTION.getRoute('r/123')); + }); }); diff --git a/tests/unit/pages/RestrictedAction/WorkspaceRestrictedActionPageTest.tsx b/tests/unit/pages/RestrictedAction/WorkspaceRestrictedActionPageTest.tsx new file mode 100644 index 000000000000..ccb96cbe5427 --- /dev/null +++ b/tests/unit/pages/RestrictedAction/WorkspaceRestrictedActionPageTest.tsx @@ -0,0 +1,254 @@ +import {render, screen} from '@testing-library/react-native'; + +import {openSubscriptionPage} from '@libs/actions/Subscription'; +import Navigation from '@libs/Navigation/Navigation'; +import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; +import type {RestrictedActionParamList} from '@libs/Navigation/types'; +import type * as SubscriptionUtils from '@libs/SubscriptionUtils'; + +import type ONYXKEYS from '@src/ONYXKEYS'; +import WorkspaceRestrictedActionPage from '@src/pages/RestrictedAction/Workspace/WorkspaceRestrictedActionPage'; +import type SCREENS from '@src/SCREENS'; + +import type * as ReactNavigationNative from '@react-navigation/native'; +import type ReactNative from 'react-native'; + +import React from 'react'; + +import createMock from '../../../utils/createMock'; + +const mockIsFocused = jest.fn(() => true); +const mockShouldRestrictUserBillableActions = jest.fn>(() => false); + +jest.mock('@react-navigation/native', () => ({ + ...jest.requireActual('@react-navigation/native'), + useIsFocused: () => mockIsFocused(), +})); + +jest.mock('@libs/Navigation/Navigation', () => ({ + goBack: jest.fn(), +})); + +// Only the restriction gate is replaced. Keeping the rest of the module real means a child that starts +// importing another `SubscriptionUtils` export does not silently resolve it to `undefined`. +jest.mock('@libs/SubscriptionUtils', () => ({ + ...jest.requireActual('@libs/SubscriptionUtils'), + shouldRestrictUserBillableActions: (...args: Parameters) => mockShouldRestrictUserBillableActions(...args), +})); + +jest.mock('@libs/actions/Subscription', () => ({ + openSubscriptionPage: jest.fn(), +})); + +jest.mock('@libs/PolicyUtils', () => ({ + isPolicyOwner: jest.fn(() => true), + isPolicyAdmin: jest.fn(() => false), + isPolicyAuditor: jest.fn(() => false), + isPolicyUser: jest.fn(() => false), +})); + +// `isLoadingSubscriptionData` gates both the goBack effect and the loading indicator, so the tests drive it. +// The key is read from the real `ONYXKEYS` inside the factory (a top-level import cannot be referenced from a +// hoisted `jest.mock`), so renaming the constant breaks this mock loudly instead of returning `undefined`. +const mockIsLoadingSubscriptionData = jest.fn(() => false); +jest.mock('@hooks/useOnyx', () => { + const {default: actualOnyxKeys} = jest.requireActual<{default: typeof ONYXKEYS}>('@src/ONYXKEYS'); + // Mirrors the real `[value, result]` tuple so a migration to `result.status` does not read `undefined`. + return (key: string) => [key === actualOnyxKeys.IS_LOADING_SUBSCRIPTION_DATA ? mockIsLoadingSubscriptionData() : undefined, {status: 'loaded'}]; +}); + +jest.mock('@hooks/useCurrentUserPersonalDetails', () => jest.fn(() => ({accountID: 1, email: 'owner@example.com'}))); + +// Referentially stable, like the real `usePolicy`. Returning a fresh object per render would change a +// dependency of the goBack effect on every render, re-running it no matter what the dependency array says +// and masking a removed `isFocused` dependency. +const mockPolicy = {id: 'policyID1'}; +jest.mock('@hooks/usePolicy', () => jest.fn(() => mockPolicy)); + +// Drivable so the offline branch of the loading condition and the reconnect refetch are both reachable. +const mockIsOffline = jest.fn(() => false); +jest.mock('@hooks/useNetwork', () => jest.fn(() => ({isOffline: mockIsOffline()}))); + +jest.mock('@hooks/useThemeStyles', () => jest.fn(() => new Proxy({}, {get: () => ({})}))); + +// Renders identifiable text so the tests can tell the restriction UI apart from the loading indicator. +jest.mock('@src/pages/RestrictedAction/Workspace/WorkspaceOwnerRestrictedAction', () => { + const {Text} = jest.requireActual('react-native'); + function MockWorkspaceOwnerRestrictedAction() { + return owner-restriction-ui; + } + return MockWorkspaceOwnerRestrictedAction; +}); + +jest.mock('@src/pages/RestrictedAction/Workspace/WorkspaceAdminRestrictedAction', () => { + function MockWorkspaceAdminRestrictedAction() { + return null; + } + return MockWorkspaceAdminRestrictedAction; +}); + +jest.mock('@src/pages/RestrictedAction/Workspace/WorkspaceUserRestrictedAction', () => { + function MockWorkspaceUserRestrictedAction() { + return null; + } + return MockWorkspaceUserRestrictedAction; +}); + +type PageProps = PlatformStackScreenProps; + +// The page only reads route.params.policyID. The navigation double just satisfies the navigator-provided prop. +const props = { + route: createMock({params: {policyID: 'policyID1'}}), + navigation: createMock({}), +} satisfies PageProps; + +describe('WorkspaceRestrictedActionPage', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockIsFocused.mockReturnValue(true); + mockShouldRestrictUserBillableActions.mockReturnValue(false); + mockIsLoadingSubscriptionData.mockReturnValue(false); + mockIsOffline.mockReturnValue(false); + }); + + it('dismisses itself when focused and the restriction no longer applies', () => { + // Given a focused restricted action screen whose billing restriction has been resolved + mockIsFocused.mockReturnValue(true); + + // When the page renders with fresh server data + render(); + + // Then it navigates back, since there is nothing left to restrict + expect(Navigation.goBack).toHaveBeenCalledTimes(1); + + // And the gate is asked about this policy and this user, in that order. Asserting the arguments + // catches a refactor that reorders them or drops the grace period collection, which would otherwise + // leave every test in this file passing against a gate that is being called wrong. + expect(mockShouldRestrictUserBillableActions).toHaveBeenCalledWith(mockPolicy, undefined, undefined, undefined, 1); + }); + + it('stays put while unfocused so it cannot pop the screen the user is actually on', () => { + // Given the restricted action screen is still mounted in the RHP but the user has moved on to + // the Subscription page, where they just resolved the billing issue + mockIsFocused.mockReturnValue(false); + + // When the fresh server data lifts the restriction + render(); + + // Then this unfocused screen must not navigate back, which would yank the Subscription page + // out from under the user mid-payment + expect(Navigation.goBack).not.toHaveBeenCalled(); + }); + + it('dismisses itself once focus returns after the restriction was lifted elsewhere', () => { + // Given the restricted action screen mounted but covered by the Subscription page + mockIsFocused.mockReturnValue(false); + const {rerender} = render(); + expect(Navigation.goBack).not.toHaveBeenCalled(); + + // When the user resolves billing there and swipes back, re-focusing this screen + mockIsFocused.mockReturnValue(true); + rerender(); + + // Then the effect re-runs and dismisses the now-obsolete restriction. Without `isFocused` in the + // effect's dependency array the guard would permanently disable auto-dismiss instead of deferring + // it, stranding the user on a restriction that no longer applies. + expect(Navigation.goBack).toHaveBeenCalledTimes(1); + }); + + it('does not dismiss itself while the restriction still applies', () => { + // Given a focused restricted action screen whose billing restriction is still in force + mockShouldRestrictUserBillableActions.mockReturnValue(true); + + // When the page renders + render(); + + // Then the restriction UI stays up + expect(Navigation.goBack).not.toHaveBeenCalled(); + }); + + it('shows the loading indicator while focused and waiting on fresh billing data', () => { + // Given a focused restricted action screen whose billing fetch is still in flight + mockShouldRestrictUserBillableActions.mockReturnValue(true); + mockIsLoadingSubscriptionData.mockReturnValue(true); + + // When the page renders + render(); + + // Then it shows the loading indicator rather than flashing a restriction that may no longer apply + expect(screen.queryByText('owner-restriction-ui')).toBeNull(); + }); + + it('keeps the restriction UI mounted while unfocused and the shared loading flag is set', () => { + // Given the restricted action screen still mounted in the RHP underneath the Subscription page, + // whose own billing fetch has set the shared `isLoadingSubscriptionData` flag + mockShouldRestrictUserBillableActions.mockReturnValue(true); + mockIsLoadingSubscriptionData.mockReturnValue(true); + mockIsFocused.mockReturnValue(false); + + // When the page re-renders behind the user's back + render(); + + // Then it must not swap its content for the loading indicator. Doing so unmounts the restriction UI + // while it is covered, discarding state it captured on mount. + expect(screen.getByText('owner-restriction-ui')).toBeTruthy(); + }); + + it('skips the loading indicator while offline', () => { + // Given a focused restricted action screen with the shared loading flag set, but no connectivity + mockShouldRestrictUserBillableActions.mockReturnValue(true); + mockIsLoadingSubscriptionData.mockReturnValue(true); + mockIsOffline.mockReturnValue(true); + + // When the page renders + render(); + + // Then it shows the restriction instead of a spinner that would never resolve: the fetch that + // clears the flag is itself skipped while offline. + expect(screen.getByText('owner-restriction-ui')).toBeTruthy(); + }); + + it('does not fetch fresh billing data while offline', () => { + // Given no connectivity + mockIsOffline.mockReturnValue(true); + + // When the page mounts + render(); + + // Then it skips the fetch. The request would not go through, and its optimistic clear of the grace + // period collection would lift the restriction without the server ever confirming it. + expect(openSubscriptionPage).not.toHaveBeenCalled(); + }); + + it('does not refetch on reconnect while unfocused', () => { + // Given the restricted action screen mounted underneath the Subscription page, with no connectivity + mockShouldRestrictUserBillableActions.mockReturnValue(true); + mockIsFocused.mockReturnValue(false); + mockIsOffline.mockReturnValue(true); + const {rerender} = render(); + + // When the device reconnects while the user is still on Subscription + mockIsOffline.mockReturnValue(false); + rerender(); + + // Then this covered screen stays quiet. The focused Subscription page issues the same fetch, and + // duplicating it here would flip the shared `isLoadingSubscriptionData` flag out from under it. + expect(openSubscriptionPage).not.toHaveBeenCalled(); + }); + + it('fetches fresh billing data once focus returns', () => { + // Given the restricted action screen mounted underneath the Subscription page + mockShouldRestrictUserBillableActions.mockReturnValue(true); + mockIsFocused.mockReturnValue(false); + const {rerender} = render(); + expect(openSubscriptionPage).not.toHaveBeenCalled(); + + // When the user swipes back, re-focusing this screen + mockIsFocused.mockReturnValue(true); + rerender(); + + // Then the deferred fetch runs, so the screen decides whether to stay up using server data rather + // than whatever was cached before the user left for Subscription. + expect(openSubscriptionPage).toHaveBeenCalledTimes(1); + }); +});