diff --git a/src/CONST/index.ts b/src/CONST/index.ts index d3434930f045..28b89ed700fe 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -147,6 +147,12 @@ const createExpenseOnboardingChoices = { SUBMIT: backendOnboardingChoices.SUBMIT, } as const; +// Values accepted by the `intent` param on the onboarding deeplink. Deliberately not the internal onboarding choice +// strings (`newDotEmployer`), so renaming those can't break links already sitting in someone's inbox. +const onboardingIntents = { + SUBMIT: 'submit', +} as const; + const signupQualifiers = { INDIVIDUAL: 'individual', VSB: 'vsb', @@ -6748,6 +6754,7 @@ const CONST = { EXPENSIFY_ICON_NAME: 'Expensify', ONBOARDING_CHOICES: {...onboardingChoices}, + ONBOARDING_INTENTS: {...onboardingIntents}, SELECTABLE_ONBOARDING_CHOICES: {...selectableOnboardingChoices}, CREATE_EXPENSE_ONBOARDING_CHOICES: {...createExpenseOnboardingChoices}, ONBOARDING_SIGNUP_QUALIFIERS: {...signupQualifiers}, @@ -9688,6 +9695,9 @@ type IOUActionParams = ValueOf; type SubscriptionType = ValueOf; type CancellationType = ValueOf; +/** Valid values for the `intent` param on the onboarding deeplink */ +type OnboardingIntent = ValueOf; + /** Valid `page` values for the Enable Payments flow */ type EnablePaymentsPageType = ValueOf; @@ -9709,6 +9719,7 @@ export type { CancellationType, OnboardingInvite, OnboardingAccounting, + OnboardingIntent, IOUActionParams, EnablePaymentsPageType, EnablePaymentsSubPageType, diff --git a/src/hooks/useOnboardingDeeplinkIntent.ts b/src/hooks/useOnboardingDeeplinkIntent.ts new file mode 100644 index 000000000000..4d51716fdd9d --- /dev/null +++ b/src/hooks/useOnboardingDeeplinkIntent.ts @@ -0,0 +1,61 @@ +import {useInitialURLState} from '@components/InitialURLContextProvider'; + +import getCurrentUrl from '@libs/Navigation/currentUrl'; +import {getRouteFromLink} from '@libs/ReportUtils'; +import {getSearchParamFromPath} from '@libs/Url'; + +import type {OnboardingIntent} from '@src/CONST'; +import CONST from '@src/CONST'; +import ROUTES from '@src/ROUTES'; + +import {useState} from 'react'; + +function isOnboardingIntent(value: string | null): value is OnboardingIntent { + return !!value && Object.values(CONST.ONBOARDING_INTENTS).includes(value); +} + +// Matching on the boundary rather than the prefix keeps sibling routes like `onboarding/work-email` out. +function isOnboardingPath(path: string | null): path is string { + return path === ROUTES.ONBOARDING_ROOT.route || !!path?.startsWith(`${ROUTES.ONBOARDING_ROOT.route}?`); +} + +/** + * Reads the `intent` param of the onboarding deeplink (e.g. `onboarding?intent=submit`). + * + * It arrives either directly, or nested in the `exitTo` of a transition or magic link. Nesting it in `exitTo` is what + * carries the intent across the logged-out to logged-in transition, since the deeplink outlives the sign-in itself. + */ +function getOnboardingIntentFromUrl(url: string | null | undefined): OnboardingIntent | undefined { + if (!url) { + return undefined; + } + + // getRouteFromLink strips whichever linking-config prefix matched, so web URLs, the desktop `app://-/` origin and + // the native scheme all reduce to the same route. It leaves the leading slash on in-app paths. + const pathWithQuery = getRouteFromLink(url).replace(/^\/+/, ''); + const onboardingPathWithQuery = isOnboardingPath(pathWithQuery) ? pathWithQuery : getSearchParamFromPath(pathWithQuery, 'exitTo'); + + if (!isOnboardingPath(onboardingPathWithQuery)) { + return undefined; + } + + const intent = getSearchParamFromPath(onboardingPathWithQuery, 'intent'); + return isOnboardingIntent(intent) ? intent : undefined; +} + +/** + * Resolves the onboarding outcome requested by the deeplink this session was opened with, e.g. `onboarding?intent=submit`. + * + * Two sources because neither covers both platforms. On web the link is in the address bar, but only until the app + * navigates and rewrites it, hence latching at mount. On native there is no address bar, so it arrives instead through + * the initial-URL context. Links opened while the app is already running reach neither, so they are not supported. + */ +function useOnboardingDeeplinkIntent(): OnboardingIntent | undefined { + const {initialURL} = useInitialURLState(); + const [urlAtMount] = useState(getCurrentUrl); + + return getOnboardingIntentFromUrl(urlAtMount) ?? getOnboardingIntentFromUrl(initialURL); +} + +export default useOnboardingDeeplinkIntent; +export {getOnboardingIntentFromUrl}; diff --git a/src/libs/Navigation/AppNavigator/AuthScreens.tsx b/src/libs/Navigation/AppNavigator/AuthScreens.tsx index 7b55de5ae473..8caf57b9ada1 100644 --- a/src/libs/Navigation/AppNavigator/AuthScreens.tsx +++ b/src/libs/Navigation/AppNavigator/AuthScreens.tsx @@ -73,6 +73,7 @@ import OnboardingModalNavigator from './Navigators/OnboardingModalNavigator'; import SubmitPlanWelcomeModalNavigator from './Navigators/SubmitPlanWelcomeModalNavigator'; import TestToolsModalNavigator from './Navigators/TestToolsModalNavigator'; import {loadRightModalNavigator, loadSearchRouterPage} from './searchRouterLazyLoaders'; +import SubmitIntentDeeplinkHandler from './SubmitIntentDeeplinkHandler'; import TestDriveDemoNavigator from './TestDriveDemoNavigator'; import ThreeDSAuthHandler from './ThreeDSAuthHandler'; import useModalCardStyleInterpolator from './useModalCardStyleInterpolator'; @@ -165,6 +166,7 @@ function AuthScreens() { <> + diff --git a/src/libs/Navigation/AppNavigator/SubmitIntentDeeplinkHandler/ApplySubmitOnboardingIntent.tsx b/src/libs/Navigation/AppNavigator/SubmitIntentDeeplinkHandler/ApplySubmitOnboardingIntent.tsx new file mode 100644 index 000000000000..aa15dd80c9f6 --- /dev/null +++ b/src/libs/Navigation/AppNavigator/SubmitIntentDeeplinkHandler/ApplySubmitOnboardingIntent.tsx @@ -0,0 +1,71 @@ +import useAutoCreateSubmitWorkspace from '@hooks/useAutoCreateSubmitWorkspace'; +import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; +import useOnyx from '@hooks/useOnyx'; + +import {releaseWelcomeModalForSubmitDeeplink, suppressWelcomeModalForSubmitDeeplink} from '@libs/Navigation/guards/SubmitPlanWelcomeModalGuard'; +import {getGroupPoliciesWhereReportCanBeCreated} from '@libs/PolicyUtils'; + +import {setSubmitMigrationModalShown} from '@userActions/User'; + +import ONYXKEYS from '@src/ONYXKEYS'; + +import {hasCompletedGuidedSetupFlowSelector} from '@selectors/Onboarding'; +import {emailSelector, isSupportalSessionSelector} from '@selectors/Session'; +import {useEffect} from 'react'; + +// Module scope rather than a ref so it survives a remount: the initial URL outlives sign-out, so signing into a second +// account would otherwise replay the intent and create that account a workspace it never asked for. +let hasAppliedIntent = false; + +/** + * Creates the Submit workspace requested by an `intent=submit` onboarding deeplink. + * + * The link only goes to existing users, so it acts solely on recipients who have finished guided setup. Anyone who + * still has onboarding ahead of them is left to it, since that flow already offers the Submit outcome. + */ +function ApplySubmitOnboardingIntent() { + const {firstName, lastName} = useCurrentUserPersonalDetails(); + const autoCreateSubmitWorkspace = useAutoCreateSubmitWorkspace(); + + // Waiting on HAS_LOADED_APP keeps the eligibility checks inside useAutoCreateSubmitWorkspace from running + // against a half-populated store, where they would miss an existing workspace and create a duplicate. + const [hasLoadedApp] = useOnyx(ONYXKEYS.HAS_LOADED_APP); + const [isOnboardingCompleted] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: hasCompletedGuidedSetupFlowSelector}); + const [isSupportalSession] = useOnyx(ONYXKEYS.SESSION, {selector: isSupportalSessionSelector}); + const [currentUserEmail] = useOnyx(ONYXKEYS.SESSION, {selector: emailSelector}); + + // Plain membership counts here, unlike the admin-level check inside useAutoCreateSubmitWorkspace, which would + // hand a personal Submit workspace to someone who can already submit on their employer's. + const [belongsToWorkspaceForReports] = useOnyx(ONYXKEYS.COLLECTION.POLICY, { + selector: (policies) => getGroupPoliciesWhereReportCanBeCreated(policies, currentUserEmail).length > 0, + }); + + // At mount, ahead of the work below that waits on HAS_LOADED_APP — the same signal that opens the guard's modal. + useEffect(() => { + suppressWelcomeModalForSubmitDeeplink(); + }, []); + + useEffect(() => { + if (hasAppliedIntent || !hasLoadedApp || isOnboardingCompleted === undefined) { + return; + } + hasAppliedIntent = true; + + // Marked applied above before these checks, since they are reasons to drop the intent rather than to wait for + // it to become actionable. Returning without consuming would leave it live for whoever signs in next. + if (!isOnboardingCompleted || isSupportalSession || belongsToWorkspaceForReports) { + releaseWelcomeModalForSubmitDeeplink(); + return; + } + + // Persists the suppression applied above, so the modal stays away in later sessions too. + setSubmitMigrationModalShown(); + + // `false` skips CompleteGuidedSetup, which is already done. + autoCreateSubmitWorkspace(firstName ?? '', lastName ?? '', false); + }, [autoCreateSubmitWorkspace, belongsToWorkspaceForReports, firstName, hasLoadedApp, isOnboardingCompleted, isSupportalSession, lastName]); + + return null; +} + +export default ApplySubmitOnboardingIntent; diff --git a/src/libs/Navigation/AppNavigator/SubmitIntentDeeplinkHandler/index.tsx b/src/libs/Navigation/AppNavigator/SubmitIntentDeeplinkHandler/index.tsx new file mode 100644 index 000000000000..436403abd3de --- /dev/null +++ b/src/libs/Navigation/AppNavigator/SubmitIntentDeeplinkHandler/index.tsx @@ -0,0 +1,22 @@ +import useOnboardingDeeplinkIntent from '@hooks/useOnboardingDeeplinkIntent'; + +import CONST from '@src/CONST'; + +import React from 'react'; + +import ApplySubmitOnboardingIntent from './ApplySubmitOnboardingIntent'; + +/** + * Recognizes the `intent=submit` onboarding deeplink and hands off to the component that acts on it. + */ +function SubmitIntentDeeplinkHandler() { + const onboardingDeeplinkIntent = useOnboardingDeeplinkIntent(); + + if (onboardingDeeplinkIntent !== CONST.ONBOARDING_INTENTS.SUBMIT) { + return null; + } + + return ; +} + +export default SubmitIntentDeeplinkHandler; diff --git a/src/libs/Navigation/guards/SubmitPlanWelcomeModalGuard.ts b/src/libs/Navigation/guards/SubmitPlanWelcomeModalGuard.ts index 29bd1e4d9205..7eaa6446b4fd 100644 --- a/src/libs/Navigation/guards/SubmitPlanWelcomeModalGuard.ts +++ b/src/libs/Navigation/guards/SubmitPlanWelcomeModalGuard.ts @@ -39,6 +39,21 @@ let hasLoadedApp = false; let hasRedirectedToSubmitPlanModal = false; let isEvaluationScheduled = false; +// An `intent=submit` deeplink delivers the same outcome as this modal without asking, so the modal must not open on +// top of it. Recorded outside Onyx because the deeplink can only mark the modal shown from a React effect, which runs +// after the microtask that schedules the proactive redirect below. +let hasPendingSubmitDeeplink = false; + +function suppressWelcomeModalForSubmitDeeplink() { + hasPendingSubmitDeeplink = true; +} + +// Called when the deeplink decides not to create anything, so a later account in this process isn't left with the +// modal suppressed by an intent that never acted. +function releaseWelcomeModalForSubmitDeeplink() { + hasPendingSubmitDeeplink = false; +} + const SUBMIT_PLAN_WELCOME_ENTRY_SCREENS = new Set(DYNAMIC_ROUTES.SUBMIT_PLAN_WELCOME.entryScreens); /** @@ -74,6 +89,7 @@ function getSubmitPlanWelcomeModalRoute(basePath?: string): Route { function resetSessionFlag() { hasRedirectedToSubmitPlanModal = false; + hasPendingSubmitDeeplink = false; } /** @@ -110,6 +126,7 @@ function isPolicyCreationRestricted(): boolean { */ function navigateToSubmitPlanWelcomeModalIfReady() { if ( + hasPendingSubmitDeeplink || isSupportalSessionSelector(session) || !session?.authToken || isLoadingApp || @@ -291,7 +308,7 @@ const SubmitPlanWelcomeModalGuard: NavigationGuard = { return {type: 'ALLOW'}; } - if (context.isSupportalSession || !shouldShowSubmitPlanWelcomeModal()) { + if (hasPendingSubmitDeeplink || context.isSupportalSession || !shouldShowSubmitPlanWelcomeModal()) { return {type: 'ALLOW'}; } @@ -305,4 +322,4 @@ const SubmitPlanWelcomeModalGuard: NavigationGuard = { }; export default SubmitPlanWelcomeModalGuard; -export {resetSessionFlag}; +export {resetSessionFlag, suppressWelcomeModalForSubmitDeeplink, releaseWelcomeModalForSubmitDeeplink}; diff --git a/tests/unit/Navigation/guards/SubmitPlanWelcomeModalGuard.test.ts b/tests/unit/Navigation/guards/SubmitPlanWelcomeModalGuard.test.ts index 7afa45ce70cc..41cd1286180f 100644 --- a/tests/unit/Navigation/guards/SubmitPlanWelcomeModalGuard.test.ts +++ b/tests/unit/Navigation/guards/SubmitPlanWelcomeModalGuard.test.ts @@ -1,4 +1,4 @@ -import SubmitPlanWelcomeModalGuard, {resetSessionFlag} from '@libs/Navigation/guards/SubmitPlanWelcomeModalGuard'; +import SubmitPlanWelcomeModalGuard, {resetSessionFlag, suppressWelcomeModalForSubmitDeeplink} from '@libs/Navigation/guards/SubmitPlanWelcomeModalGuard'; import type {GuardContext} from '@libs/Navigation/guards/types'; import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; // eslint-disable-next-line no-restricted-imports -- type-only namespace import used solely to type jest.requireActual for the module mock below @@ -183,6 +183,14 @@ describe('SubmitPlanWelcomeModalGuard', () => { expect(secondResult.type).toBe('ALLOW'); }); + it('should allow when an intent=submit deeplink is creating the workspace already', async () => { + await setUpEligibleUser(); + suppressWelcomeModalForSubmitDeeplink(); + + const result = SubmitPlanWelcomeModalGuard.evaluate(mockState, mockAction, defaultContext); + expect(result.type).toBe('ALLOW'); + }); + it('should allow when already on the submit plan welcome modal screen', async () => { await setUpEligibleUser(); @@ -215,6 +223,16 @@ describe('SubmitPlanWelcomeModalGuard', () => { expect(mockNavigate).toHaveBeenCalledWith(submitPlanWelcomeRoute); }); + it('should not navigate when an intent=submit deeplink is creating the workspace already', async () => { + await setUpEligibleUser(); + suppressWelcomeModalForSubmitDeeplink(); + mockNavigate.mockClear(); + + await markSessionReady({authToken: 'test-token', accountID: 123}); + + expect(mockNavigate).not.toHaveBeenCalled(); + }); + it('should not navigate when there is no session', async () => { await setUpEligibleUser(); mockNavigate.mockClear(); diff --git a/tests/unit/getOnboardingIntentFromUrlTest.ts b/tests/unit/getOnboardingIntentFromUrlTest.ts new file mode 100644 index 000000000000..cf1eddaf6d35 --- /dev/null +++ b/tests/unit/getOnboardingIntentFromUrlTest.ts @@ -0,0 +1,67 @@ +import {getOnboardingIntentFromUrl} from '@hooks/useOnboardingDeeplinkIntent'; + +import CONST from '@src/CONST'; + +describe('getOnboardingIntentFromUrl', () => { + const encodedOnboardingRoute = encodeURIComponent('onboarding?intent=submit'); + + it('reads the intent from a direct onboarding link', () => { + expect(getOnboardingIntentFromUrl('https://new.expensify.com/onboarding?intent=submit')).toBe(CONST.ONBOARDING_INTENTS.SUBMIT); + }); + + it('reads the intent from a custom scheme link, where the route sits where a host would', () => { + expect(getOnboardingIntentFromUrl('new-expensify://onboarding?intent=submit')).toBe(CONST.ONBOARDING_INTENTS.SUBMIT); + }); + + it('reads the intent from a custom scheme link with a placeholder host', () => { + expect(getOnboardingIntentFromUrl('app://-/onboarding?intent=submit')).toBe(CONST.ONBOARDING_INTENTS.SUBMIT); + }); + + it('reads the intent from the exitTo of a custom scheme magic link', () => { + expect(getOnboardingIntentFromUrl(`new-expensify://v/12345/678910?exitTo=${encodedOnboardingRoute}`)).toBe(CONST.ONBOARDING_INTENTS.SUBMIT); + }); + + it('reads the intent from a link served on a port, as the dev server does', () => { + expect(getOnboardingIntentFromUrl('https://dev.new.expensify.com:8082/onboarding?intent=submit')).toBe(CONST.ONBOARDING_INTENTS.SUBMIT); + }); + + it('reads the intent from an in-app path without an origin', () => { + expect(getOnboardingIntentFromUrl('/onboarding?intent=submit')).toBe(CONST.ONBOARDING_INTENTS.SUBMIT); + }); + + // HybridApp hands NewDot the deeplink as a bare path rather than a full URL, which is the shape the emailed + // magic link arrives in on mobile. + it('reads the intent from the exitTo of a magic link passed as a bare path', () => { + expect(getOnboardingIntentFromUrl(`v/12345/678910?exitTo=${encodedOnboardingRoute}`)).toBe(CONST.ONBOARDING_INTENTS.SUBMIT); + }); + + it('reads the intent from the exitTo of an OldDot transition link', () => { + const url = `https://new.expensify.com/transition?email=${encodeURIComponent('me@example.com')}&shortLivedAuthToken=abc123&exitTo=${encodedOnboardingRoute}`; + + expect(getOnboardingIntentFromUrl(url)).toBe(CONST.ONBOARDING_INTENTS.SUBMIT); + }); + + it('reads the intent from the exitTo of a magic link', () => { + const url = `https://new.expensify.com/v/12345/678910?exitTo=${encodedOnboardingRoute}`; + + expect(getOnboardingIntentFromUrl(url)).toBe(CONST.ONBOARDING_INTENTS.SUBMIT); + }); + + it('reads the intent from an unencoded exitTo, which OldDot mobile does not encode', () => { + const url = 'https://new.expensify.com/transition?shortLivedAuthToken=abc123&exitTo=onboarding?intent=submit'; + + expect(getOnboardingIntentFromUrl(url)).toBe(CONST.ONBOARDING_INTENTS.SUBMIT); + }); + + it.each([ + ['no url', undefined], + ['an empty url', ''], + ['an onboarding link without an intent', 'https://new.expensify.com/onboarding'], + ['an unknown intent value', 'https://new.expensify.com/onboarding?intent=notARealIntent'], + ['an intent on a non-onboarding route', 'https://new.expensify.com/settings/profile?intent=submit'], + ['an intent on a route that merely starts with onboarding', 'https://new.expensify.com/onboarding/work-email?intent=submit'], + ['an intent on a non-onboarding exitTo', `https://new.expensify.com/transition?exitTo=${encodeURIComponent('workspace/new?intent=submit')}`], + ])('returns undefined for %s', (_description, url) => { + expect(getOnboardingIntentFromUrl(url)).toBeUndefined(); + }); +}); diff --git a/tests/unit/hooks/useOnboardingDeeplinkIntent.test.ts b/tests/unit/hooks/useOnboardingDeeplinkIntent.test.ts new file mode 100644 index 000000000000..9e681c62aa9b --- /dev/null +++ b/tests/unit/hooks/useOnboardingDeeplinkIntent.test.ts @@ -0,0 +1,62 @@ +import {renderHook} from '@testing-library/react-native'; + +import useOnboardingDeeplinkIntent from '@hooks/useOnboardingDeeplinkIntent'; + +import CONST from '@src/CONST'; + +const mockGetCurrentUrl = jest.fn(); +jest.mock('@libs/Navigation/currentUrl', () => ({ + __esModule: true, + default: () => mockGetCurrentUrl(), +})); + +const mockUseInitialURLState = jest.fn<{initialURL: string | null; isAuthenticatedAtStartup: boolean}, []>(); +jest.mock('@components/InitialURLContextProvider', () => ({ + useInitialURLState: () => mockUseInitialURLState(), +})); + +const ONBOARDING_LINK = 'https://new.expensify.com/onboarding?intent=submit'; + +describe('useOnboardingDeeplinkIntent', () => { + beforeEach(() => { + jest.clearAllMocks(); + // The two platform defaults: no address bar on native, no initial URL on web. + mockGetCurrentUrl.mockReturnValue(''); + mockUseInitialURLState.mockReturnValue({initialURL: null, isAuthenticatedAtStartup: false}); + }); + + it('reads the intent from the address bar, as on web', () => { + mockGetCurrentUrl.mockReturnValue(ONBOARDING_LINK); + + const {result} = renderHook(() => useOnboardingDeeplinkIntent()); + + expect(result.current).toBe(CONST.ONBOARDING_INTENTS.SUBMIT); + }); + + it('reads the intent from the initial URL when there is no address bar, as on native', () => { + mockUseInitialURLState.mockReturnValue({initialURL: 'new-expensify://onboarding?intent=submit', isAuthenticatedAtStartup: false}); + + const {result} = renderHook(() => useOnboardingDeeplinkIntent()); + + expect(result.current).toBe(CONST.ONBOARDING_INTENTS.SUBMIT); + }); + + it('keeps the intent after the app navigates and rewrites the address bar', () => { + mockGetCurrentUrl.mockReturnValue(ONBOARDING_LINK); + + const {result, rerender} = renderHook(() => useOnboardingDeeplinkIntent()); + mockGetCurrentUrl.mockReturnValue('https://new.expensify.com/home'); + rerender({}); + + expect(result.current).toBe(CONST.ONBOARDING_INTENTS.SUBMIT); + expect(mockGetCurrentUrl).toHaveBeenCalledTimes(1); + }); + + it('returns undefined when neither source carries an intent', () => { + mockGetCurrentUrl.mockReturnValue('https://new.expensify.com/home'); + + const {result} = renderHook(() => useOnboardingDeeplinkIntent()); + + expect(result.current).toBeUndefined(); + }); +});