Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
72e106e
Add onboarding intent deeplink that creates a Submit workspace
abzokhattab Aug 18, 2026
1bf9098
Route the Submit deeplink through onboarding instead of racing it
abzokhattab Aug 18, 2026
06e18f0
Create the Submit workspace directly instead of routing through onboa…
abzokhattab Aug 18, 2026
f843d86
Act on the Submit deeplink only for users who already onboarded
abzokhattab Aug 18, 2026
8b21e71
Fix spellcheck failures in deeplink comments
abzokhattab Aug 18, 2026
3215c16
Fix native deeplink paths for the Submit onboarding intent
abzokhattab Aug 18, 2026
7fad41a
Parse the deeplink with getRouteFromLink instead of a local helper
abzokhattab Aug 20, 2026
8bb0054
Trim comments down to the parts that aren't evident from the code
abzokhattab Aug 20, 2026
22db33d
Build the encoded exitTo in tests instead of hardcoding the escapes
abzokhattab Aug 20, 2026
f1887b4
Apply the Submit intent at most once per app process
abzokhattab Aug 20, 2026
fca471c
Drop the unrelated comment fix in SubmitPlanWelcomeModal
abzokhattab Aug 20, 2026
120ac22
Merge remote-tracking branch 'origin/main' into abzokhattab/98644-sub…
abzokhattab Aug 22, 2026
a6e5615
Cover the bare-path magic link HybridApp passes to NewDot
abzokhattab Aug 23, 2026
418fd88
Drop the intent on supportal and pre-empt the welcome modal race
abzokhattab Aug 23, 2026
4273e1d
Merge remote-tracking branch 'origin/main' into abzokhattab/98644-sub…
abzokhattab Aug 30, 2026
e83da96
Revert the warm-link handling that wrote to the initial-URL context
abzokhattab Aug 30, 2026
b8a894a
Skip the intent for members of any workspace where reports can be cre…
abzokhattab Aug 30, 2026
d601473
Match the onboarding route on its boundary, not as a prefix
abzokhattab Aug 30, 2026
dbf9613
Drop the unused route param and tighten the comments
abzokhattab Aug 30, 2026
520bc99
Make the onboarding path check a type guard so the caller narrows
abzokhattab Aug 30, 2026
5c0c745
Fold the URL parser into the hook that consumes it
abzokhattab Aug 31, 2026
cc7a9a7
Merge branch 'main' of https://github.com/Expensify/App into abzokhat…
abzokhattab Aug 31, 2026
516d703
Test the deeplink intent hook across both URL sources
abzokhattab Aug 31, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/CONST/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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},
Expand Down Expand Up @@ -9688,6 +9695,9 @@ type IOUActionParams = ValueOf<typeof CONST.IOU.ACTION_PARAMS>;
type SubscriptionType = ValueOf<typeof CONST.SUBSCRIPTION.TYPE>;
type CancellationType = ValueOf<typeof CONST.CANCELLATION_TYPE>;

/** Valid values for the `intent` param on the onboarding deeplink */
type OnboardingIntent = ValueOf<typeof CONST.ONBOARDING_INTENTS>;

/** Valid `page` values for the Enable Payments flow */
type EnablePaymentsPageType = ValueOf<typeof CONST.ENABLE_PAYMENTS.PAGE_NAMES>;

Expand All @@ -9709,6 +9719,7 @@ export type {
CancellationType,
OnboardingInvite,
OnboardingAccounting,
OnboardingIntent,
IOUActionParams,
EnablePaymentsPageType,
EnablePaymentsSubPageType,
Expand Down
61 changes: 61 additions & 0 deletions src/hooks/useOnboardingDeeplinkIntent.ts
Original file line number Diff line number Diff line change
@@ -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<string>(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);
Comment thread
MelvinBot marked this conversation as resolved.
Resolved
Comment thread
MelvinBot marked this conversation as resolved.
Resolved
Comment thread
abzokhattab marked this conversation as resolved.
Resolved
}

export default useOnboardingDeeplinkIntent;
export {getOnboardingIntentFromUrl};
2 changes: 2 additions & 0 deletions src/libs/Navigation/AppNavigator/AuthScreens.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -165,6 +166,7 @@ function AuthScreens() {
<>
<AuthScreensInitHandler />
<SearchRouterWarmup />
<SubmitIntentDeeplinkHandler />
<ThreeDSAuthHandler />
<UserStatusHandler />
<SupportalPermissionDeniedModal />
Expand Down
Original file line number Diff line number Diff line change
@@ -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);
Comment thread
abzokhattab marked this conversation as resolved.
Resolved
}, [autoCreateSubmitWorkspace, belongsToWorkspaceForReports, firstName, hasLoadedApp, isOnboardingCompleted, isSupportalSession, lastName]);

return null;
}

export default ApplySubmitOnboardingIntent;
Original file line number Diff line number Diff line change
@@ -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 <ApplySubmitOnboardingIntent />;
}
Comment on lines +12 to +20

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MelvinBot What's the current logic to handle all deeplink nowaday in App? Do we really need to create a specific one here for submit?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Short answer: the component isn't bespoke — it's the fourth sibling of an established pattern. The URL is the problem. onboarding is a route that OnboardingGuard deliberately redirects to HOME for exactly this PR's audience (users who finished guided setup), because the onboarding navigator isn't even mounted for them. So none of the generic routing machinery can carry this link, and the PR has to sniff the raw URL out-of-band instead. A dedicated route would let the existing machinery do it and delete 3 of the 4 new files — if the email URL is still changeable.

Current deeplink handling, in three layers

  1. React Navigation linking — the canonical path. linkingConfig → prefixes stripped → getAdaptedStateFromPath → nav state. Same primitives back in-app Navigation.navigate.
  2. Navigation guards — the interception chokepoint. RootStackRouter.getStateForAction runs handleNavigationGuards first, before any routing. Three registered today: OnboardingGuard, MigratedUserWelcomeModalGuard, SubmitPlanWelcomeModalGuard.
  3. Narrow legacy side-channels. openReportFromDeepLink — for signed-in users it says "Navigation for signed users is handled by react-navigation" and returns; it only serves anonymous/just-signed-in. Plus four separate exitTo consumers.

Why the PR couldn't just reuse one

I checked the four obvious candidates:

Candidate Verdict
setUpPoliciesAndNavigate's exitTo=workspace/new branch No. It's the same shape (deeplink creates a workspace), but it's web-only (getCurrentUrl() is '' on native), requires a /transition URL, and calls a plain function — whereas useAutoCreateSubmitWorkspace is a hook and can't be called from an action module.
A guard Decision only. GuardResult is ALLOW|BLOCK|REDIRECT — no "do work". It'd still need a screen to redirect to.
Auto-selecting EMPLOYER in the onboarding flow No. The navigator isn't mounted for completed users, and OnboardingGuard bounces them to HOME.
A dedicated route Yes, and it's the cleanest. See below.

The one thing worth pushing on

exitTo=<real-route> already gets the signed-out magic-link case for free via handleExitToNavigation (waitForUserSignIn → waitForProtectedRoutes → navigate). A real route + screen (mirroring SubmitPlanWelcomeModalNavigator, whose handleConfirm already calls autoCreateSubmitWorkspace(firstName, lastName, false) — the exact call needed, just behind a button) would let you drop getOnboardingIntentFromUrl.ts, useOnboardingDeeplinkIntent.ts, the DeepLinkHandler hook, and the hasAppliedIntent module global. The screen mount is the one-shot.

The catch: the CONST comment says these values are "embedded in emails we can't redeploy". abzokhattab — is that URL already live in sent emails, or is it still changeable? That's the deciding input.

Two smaller notes

The component pattern is fine. SubmitIntentDeeplinkHandler sits between SearchRouterWarmup and ThreeDSAuthHandler, alongside AuthScreensInitHandler and UserStatusHandler — null-rendering handlers mounted in AuthScreens are the convention, not an invention. Other side-effect deeplinks use it too (DelegatorConnectGate for ?delegatorEmail=, ReportFetchHandler for ?secureKey=).

Even if the route stays, the modal race can be fixed structurally. The hasPendingSubmitDeeplink module global exists only because two decisions live in different modules on different clocks (React mount effect vs. the guard's HAS_LOADED_APP microtask). Folding the intent check into navigateToSubmitPlanWelcomeModalIfReady() — same function, same subscription, same microtask — makes it a local condition and the race impossible rather than merely sequenced around.

Also worth knowing: guards only run on navigation actions, never on cold-start initial state, which is why both welcome-modal guards need a second Onyx-driven "proactive" path.


view run

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good question — the closest existing machinery is setUpPoliciesAndNavigate, which does create a workspace off a URL param (exitTo=workspace/new). It doesn't cover this case though: it returns early unless the URL contains exitTo, its creation branch requires a /transition OldDot handoff, it builds a generic workspace rather than a Submit plan landing on Spend + #admins, and it runs at AuthScreens mount without waiting for HAS_LOADED_APP — we have to wait for that, or the existing-workspace checks read a half-loaded store and create a duplicate.

The bigger blocker is that Submit creation is a hook (useAutoCreateSubmitWorkspace → useOnboardingWorkspaceCreationState, which aggregates ~15 values plus four useOnyx subscriptions) while setUpPoliciesAndNavigate is an imperative action, so reusing it there would mean duplicating that state gathering and forking the Submit creation path in two.

The split into two files is deliberate for the same reason: index.tsx returns null unless the intent is present, so that heavy hook only mounts on sessions actually launched from this link rather than on every authenticated session.

what do you think @MelvinBot

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All four setUpPoliciesAndNavigate points check out, and the split is more defensible than you argued. I also need to walk back part of what I said about the route alternative. But the deciding question is still unanswered.

Your setUpPoliciesAndNavigate case is sound — and understated. The strongest point isn't in your list: getCurrentUrl() returns '' on native, so the function returns at App.ts:856 before it ever reaches the exitTo check. It's not that it doesn't cover this case — it's web-only. And /transition is a hard gate, not incidental: three required conjuncts.

The split is mandatory, not stylistic. Rules of Hooks forbid conditional hook calls, so gating that hook tree requires a second component — the only real question is one file or two. And the cost avoided is bigger than "heavy": 23 transitive useOnyx subscriptions and 5 full POLICY-collection scans, on every authenticated session. Precedent is the line directly above yours — SearchRouterWarmup at AuthScreens.tsx:167 is the same cheap-gate/heavy-child shape. Only nit: the more common house style is two components in one file — e.g. DelegatorConnectGate.tsx:21-23 in the same folder. Take it or leave it.

Correcting myself on the dedicated route. I oversold it. The deletion list is two files plus hasAppliedIntent — not the module globals generally. hasPendingSubmitDeeplink survives either way, because the guard's proactive redirect still fires on a HAS_LOADED_APP microtask that beats any exitTo navigation gated on waitForUserSignIn(). And a route costs ~10-12 registration touch points (SCREENS, NAVIGATORS, ROUTES, linkingConfig, three spots in types.ts, navigator, screen, AuthScreens, EXCLUDE_FROM_LAST_VISITED_PATH). Against your current 4 new source files, that's roughly a wash. I'm not pushing it.

What I'd still put to you. Two of your last five commits are the argument I was reaching for: reverting warm-link support, and fixing isOnboardingPath to match on a boundary after onboarding/work-email?intent=submit matched. Both are costs of hand-parsing a URL the router already parses. That's not fatal, but it's the recurring bill.

So the deciding input is still the one from my last comment, and it's unanswered: is the emailed URL locked yet? If it isn't, there's a cheaper option nobody has costed — submit-plan-welcome is already a registered, linkable route, and its confirm button already calls autoCreateSubmitWorkspace(firstName, lastName, false). An exitTo=<entryScreen>/submit-plan-welcome link might ship this with zero new code, trading one-click for one tap. Unverified — I didn't confirm handleExitToNavigation's goBack + navigate sequence resolves that dynamic-suffix path. Worth 20 minutes before committing to 276 lines.

Claim-by-claim verification, plus one thing to check before merge
Your claim Verdict Anchor
Returns early unless URL contains exitTo True (also requires session; and it's a raw includes() on the href, not a param lookup) App.ts:854-857
Creation branch requires a /transition handoff True — hard requirement App.ts:870-872
Builds a generic workspace, not Submit + Spend/#admins True — it passes no type, which is typed TEAM|CORPORATE, so it structurally can't produce Submit; defaults to TEAM and lands on workspace settings App.ts:592, Policy.ts:2571 vs useAutoCreateSubmitWorkspace.ts:85
Runs at mount without waiting for HAS_LOADED_APP True — AuthScreensInitHandler.tsx:192 sits in a []-dep effect and the file never reads HAS_LOADED_APP/IS_LOADING_APP same
"~15 values plus four useOnyx" Four is exact; the aggregate is 17 returned / 16 destructured, and 18 transitive subscriptions. Understated, not overstated useAutoCreateSubmitWorkspace.ts:51-60

Worth checking before merge: isNavigatingToOnboardingFlow only matches NAVIGATE/PUSH actions. A cold boot straight to /onboarding?intent=submit builds initial state from the linking config with no navigation action, so OnboardingGuard never fires — and the onboarding navigator isn't mounted for completed users either. Your videos suggest it's fine in practice, but it'd be good to know what's on screen during the window before navigateToSubmitWorkspaceAfterOnboardingWithMicrotaskQueue runs, especially on a slow connection. I tried to check this in a browser myself and couldn't — my test session lost auth before I could navigate, so I learned nothing about the PR either way.


view run


export default SubmitIntentDeeplinkHandler;
21 changes: 19 additions & 2 deletions src/libs/Navigation/guards/SubmitPlanWelcomeModalGuard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>(DYNAMIC_ROUTES.SUBMIT_PLAN_WELCOME.entryScreens);

/**
Expand Down Expand Up @@ -74,6 +89,7 @@ function getSubmitPlanWelcomeModalRoute(basePath?: string): Route {

function resetSessionFlag() {
hasRedirectedToSubmitPlanModal = false;
hasPendingSubmitDeeplink = false;
}

/**
Expand Down Expand Up @@ -110,6 +126,7 @@ function isPolicyCreationRestricted(): boolean {
*/
function navigateToSubmitPlanWelcomeModalIfReady() {
if (
hasPendingSubmitDeeplink ||
isSupportalSessionSelector(session) ||
!session?.authToken ||
isLoadingApp ||
Expand Down Expand Up @@ -291,7 +308,7 @@ const SubmitPlanWelcomeModalGuard: NavigationGuard = {
return {type: 'ALLOW'};
}

if (context.isSupportalSession || !shouldShowSubmitPlanWelcomeModal()) {
if (hasPendingSubmitDeeplink || context.isSupportalSession || !shouldShowSubmitPlanWelcomeModal()) {
return {type: 'ALLOW'};
}

Expand All @@ -305,4 +322,4 @@ const SubmitPlanWelcomeModalGuard: NavigationGuard = {
};

export default SubmitPlanWelcomeModalGuard;
export {resetSessionFlag};
export {resetSessionFlag, suppressWelcomeModalForSubmitDeeplink, releaseWelcomeModalForSubmitDeeplink};
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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();
Expand Down
67 changes: 67 additions & 0 deletions tests/unit/getOnboardingIntentFromUrlTest.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
Loading
Loading