Skip to content

Onboarding - add nextPath logic after email verification #12342

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 28, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
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
6 changes: 5 additions & 1 deletion packages/twenty-front/src/generated/graphql.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1177,6 +1177,7 @@ export type MutationSignUpArgs = {
email: Scalars['String'];
locale?: InputMaybe<Scalars['String']>;
password: Scalars['String'];
verifyEmailNextPath?: InputMaybe<Scalars['String']>;
workspaceId?: InputMaybe<Scalars['String']>;
workspaceInviteHash?: InputMaybe<Scalars['String']>;
workspacePersonalInviteToken?: InputMaybe<Scalars['String']>;
Expand Down Expand Up @@ -2672,6 +2673,7 @@ export type SignUpMutationVariables = Exact<{
captchaToken?: InputMaybe<Scalars['String']>;
workspaceId?: InputMaybe<Scalars['String']>;
locale?: InputMaybe<Scalars['String']>;
verifyEmailNextPath?: InputMaybe<Scalars['String']>;
}>;


Expand Down Expand Up @@ -4059,7 +4061,7 @@ export type ResendEmailVerificationTokenMutationHookResult = ReturnType<typeof u
export type ResendEmailVerificationTokenMutationResult = Apollo.MutationResult<ResendEmailVerificationTokenMutation>;
export type ResendEmailVerificationTokenMutationOptions = Apollo.BaseMutationOptions<ResendEmailVerificationTokenMutation, ResendEmailVerificationTokenMutationVariables>;
export const SignUpDocument = gql`
mutation SignUp($email: String!, $password: String!, $workspaceInviteHash: String, $workspacePersonalInviteToken: String = null, $captchaToken: String, $workspaceId: String, $locale: String) {
mutation SignUp($email: String!, $password: String!, $workspaceInviteHash: String, $workspacePersonalInviteToken: String = null, $captchaToken: String, $workspaceId: String, $locale: String, $verifyEmailNextPath: String) {
signUp(
email: $email
password: $password
Expand All @@ -4068,6 +4070,7 @@ export const SignUpDocument = gql`
captchaToken: $captchaToken
workspaceId: $workspaceId
locale: $locale
verifyEmailNextPath: $verifyEmailNextPath
) {
loginToken {
...AuthTokenFragment
Expand Down Expand Up @@ -4104,6 +4107,7 @@ export type SignUpMutationFn = Apollo.MutationFunction<SignUpMutation, SignUpMut
* captchaToken: // value for 'captchaToken'
* workspaceId: // value for 'workspaceId'
* locale: // value for 'locale'
* verifyEmailNextPath: // value for 'verifyEmailNextPath'
* },
* });
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useDefaultHomePagePath } from '@/navigation/hooks/useDefaultHomePagePat
import { useOnboardingStatus } from '@/onboarding/hooks/useOnboardingStatus';
import { AppPath } from '@/types/AppPath';
import { useIsWorkspaceActivationStatusEqualsTo } from '@/workspace/hooks/useIsWorkspaceActivationStatusEqualsTo';
import { expect } from '@storybook/test';
import { useParams } from 'react-router-dom';
import { useRecoilValue } from 'recoil';

Expand Down Expand Up @@ -57,10 +58,14 @@ const setupMockUseParams = (objectNamePlural?: string) => {
};

jest.mock('recoil');
const setupMockRecoil = (objectNamePlural?: string) => {
const setupMockRecoil = (
objectNamePlural?: string,
verifyEmailNextPath?: string,
) => {
jest
.mocked(useRecoilValue)
.mockReturnValueOnce([{ namePlural: objectNamePlural ?? '' }]);
.mockReturnValueOnce([{ namePlural: objectNamePlural ?? '' }])
.mockReturnValueOnce(verifyEmailNextPath);
};

// prettier-ignore
Expand All @@ -72,6 +77,7 @@ const testCases: {
res: string | undefined;
objectNamePluralFromParams?: string;
objectNamePluralFromMetadata?: string;
verifyEmailNextPath?: string;
}[] = [
{ loc: AppPath.Verify, isLoggedIn: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.PLAN_REQUIRED, res: AppPath.PlanRequired },
{ loc: AppPath.Verify, isLoggedIn: true, isWorkspaceSuspended: true, onboardingStatus: OnboardingStatus.COMPLETED, res: '/settings/billing' },
Expand Down Expand Up @@ -110,7 +116,9 @@ const testCases: {
{ loc: AppPath.ResetPassword, isLoggedIn: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.COMPLETED, res: undefined },

{ loc: AppPath.VerifyEmail, isLoggedIn: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.PLAN_REQUIRED, res: AppPath.PlanRequired },
{ loc: AppPath.VerifyEmail, isLoggedIn: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.PLAN_REQUIRED, verifyEmailNextPath: '/nextPath?key=value', res: '/nextPath?key=value' },
{ loc: AppPath.VerifyEmail, isLoggedIn: true, isWorkspaceSuspended: true, onboardingStatus: OnboardingStatus.COMPLETED, res: '/settings/billing' },
{ loc: AppPath.VerifyEmail, isLoggedIn: false, isWorkspaceSuspended: false, onboardingStatus: undefined, verifyEmailNextPath: '/nextPath?key=value', res: undefined },
{ loc: AppPath.VerifyEmail, isLoggedIn: false, isWorkspaceSuspended: false, onboardingStatus: undefined, res: undefined },
{ loc: AppPath.VerifyEmail, isLoggedIn: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.WORKSPACE_ACTIVATION, res: AppPath.CreateWorkspace },
{ loc: AppPath.VerifyEmail, isLoggedIn: true, isWorkspaceSuspended: false, onboardingStatus: OnboardingStatus.PROFILE_CREATION, res: AppPath.CreateProfile },
Expand Down Expand Up @@ -275,14 +283,15 @@ describe('usePageChangeEffectNavigateLocation', () => {
isLoggedIn,
objectNamePluralFromParams,
objectNamePluralFromMetadata,
verifyEmailNextPath,
res,
}) => {
setupMockIsMatchingLocation(loc);
setupMockOnboardingStatus(onboardingStatus);
setupMockIsWorkspaceActivationStatusEqualsTo(isWorkspaceSuspended);
setupMockIsLogged(isLoggedIn);
setupMockUseParams(objectNamePluralFromParams);
setupMockRecoil(objectNamePluralFromMetadata);
setupMockRecoil(objectNamePluralFromMetadata, verifyEmailNextPath);

expect(usePageChangeEffectNavigateLocation()).toEqual(res);
},
Expand All @@ -294,7 +303,8 @@ describe('usePageChangeEffectNavigateLocation', () => {
(Object.keys(OnboardingStatus).length +
['isWorkspaceSuspended:true', 'isWorkspaceSuspended:false']
.length) +
['nonExistingObjectInParam', 'existingObjectInParam:false'].length,
['nonExistingObjectInParam', 'existingObjectInParam:false'].length +
['caseWithRedirectionToVerifyEmailNextPath', 'caseWithout'].length,
);
});
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { verifyEmailNextPathState } from '@/app/states/verifyEmailNextPathState';
import { useIsLogged } from '@/auth/hooks/useIsLogged';
import { useDefaultHomePagePath } from '@/navigation/hooks/useDefaultHomePagePath';
import { objectMetadataItemsState } from '@/object-metadata/states/objectMetadataItemsState';
Expand Down Expand Up @@ -43,6 +44,7 @@ export const usePageChangeEffectNavigateLocation = () => {
const objectMetadataItem = objectMetadataItems.find(
(objectMetadataItem) => objectMetadataItem.namePlural === objectNamePlural,
);
const verifyEmailNextPath = useRecoilValue(verifyEmailNextPathState);
Copy link
Contributor

Choose a reason for hiding this comment

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

style: Consider adding a type annotation for verifyEmailNextPath to make the expected type more explicit


if (
!isLoggedIn &&
Expand All @@ -58,6 +60,12 @@ export const usePageChangeEffectNavigateLocation = () => {
onboardingStatus === OnboardingStatus.PLAN_REQUIRED &&
!someMatchingLocationOf([AppPath.PlanRequired, AppPath.PlanRequiredSuccess])
) {
if (
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Not entirely satisfied of nesting verifyEmail redirection condition here (because it should not be dependant of billing), but without, chooseYouPlan modal blinks.

isMatchingLocation(location, AppPath.VerifyEmail) &&
isDefined(verifyEmailNextPath)
) {
return verifyEmailNextPath;
}
return AppPath.PlanRequired;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,62 +1,59 @@
import { useRecoilCallback } from 'recoil';

import { isQueryParamInitializedState } from '@/app/states/isQueryParamInitializedState';
import { billingCheckoutSessionState } from '@/auth/states/billingCheckoutSessionState';
import { BillingCheckoutSession } from '@/auth/types/billingCheckoutSession.type';
import { BILLING_CHECKOUT_SESSION_DEFAULT_VALUE } from '@/billing/constants/BillingCheckoutSessionDefaultValue';
import deepEqual from 'deep-equal';

// Initialize state that are hydrated from query parameters
// We used to use recoil-sync to do this, but it was causing issues with Firefox
export const useInitializeQueryParamState = () => {
const initializeQueryParamState = useRecoilCallback(
({ set, snapshot }) =>
() => {
const isInitialized = snapshot
.getLoadable(isQueryParamInitializedState)
.getValue();

if (!isInitialized) {
const handlers = {
billingCheckoutSession: (value: string) => {
try {
const parsedValue = JSON.parse(decodeURIComponent(value));

if (
typeof parsedValue === 'object' &&
parsedValue !== null &&
'plan' in parsedValue &&
'interval' in parsedValue &&
'requirePaymentMethod' in parsedValue
) {
set(
billingCheckoutSessionState,
parsedValue as BillingCheckoutSession,
);
}
} catch (error) {
// eslint-disable-next-line no-console
console.error(
'Failed to parse billingCheckoutSession from URL',
error,
);
const handlers = {
billingCheckoutSession: (value: string) => {
const billingCheckoutSession = snapshot
.getLoadable(billingCheckoutSessionState)
.getValue();

try {
const parsedValue = JSON.parse(decodeURIComponent(value));

if (
typeof parsedValue === 'object' &&
parsedValue !== null &&
'plan' in parsedValue &&
'interval' in parsedValue &&
'requirePaymentMethod' in parsedValue &&
!deepEqual(billingCheckoutSession, parsedValue)
) {
set(
billingCheckoutSessionState,
BILLING_CHECKOUT_SESSION_DEFAULT_VALUE,
parsedValue as BillingCheckoutSession,
);
}
},
};
} catch (error) {
// eslint-disable-next-line no-console
console.error(
'Failed to parse billingCheckoutSession from URL',
error,
);
set(
billingCheckoutSessionState,
BILLING_CHECKOUT_SESSION_DEFAULT_VALUE,
);
}
},
};

const queryParams = new URLSearchParams(window.location.search);
const queryParams = new URLSearchParams(window.location.search);

for (const [paramName, handler] of Object.entries(handlers)) {
const value = queryParams.get(paramName);
if (value !== null) {
handler(value);
}
for (const [paramName, handler] of Object.entries(handlers)) {
const value = queryParams.get(paramName);
if (value !== null) {
handler(value);
}

set(isQueryParamInitializedState, true);
}
},
[],
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { createState } from 'twenty-ui/utilities';

export const verifyEmailNextPathState = createState<string | undefined>({
key: 'verifyEmailNextPathState',
defaultValue: undefined,
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ import { SnackBarVariant } from '@/ui/feedback/snack-bar-manager/components/Snac
import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
import { ApolloError } from '@apollo/client';

import { verifyEmailNextPathState } from '@/app/states/verifyEmailNextPathState';
import { useVerifyLogin } from '@/auth/hooks/useVerifyLogin';
import { useRedirectToWorkspaceDomain } from '@/domain-manager/hooks/useRedirectToWorkspaceDomain';
import { Modal } from '@/ui/layout/modal/components/Modal';
import { useLingui } from '@lingui/react/macro';
import { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useSetRecoilState } from 'recoil';
import { isDefined } from 'twenty-shared/utils';
import { useNavigateApp } from '~/hooks/useNavigateApp';
import { getWorkspaceUrl } from '~/utils/getWorkspaceUrl';
import { EmailVerificationSent } from '../sign-in-up/components/EmailVerificationSent';
Expand All @@ -22,8 +25,11 @@ export const VerifyEmailEffect = () => {
const [searchParams] = useSearchParams();
const [isError, setIsError] = useState(false);

const setVerifyEmailNextPath = useSetRecoilState(verifyEmailNextPathState);

const email = searchParams.get('email');
const emailVerificationToken = searchParams.get('emailVerificationToken');
const verifyEmailNextPath = searchParams.get('nextPath');

const navigate = useNavigateApp();
const { redirectToWorkspaceDomain } = useRedirectToWorkspaceDomain();
Expand Down Expand Up @@ -58,6 +64,11 @@ export const VerifyEmailEffect = () => {
loginToken: loginToken.token,
});
}

if (isDefined(verifyEmailNextPath)) {
setVerifyEmailNextPath(verifyEmailNextPath);
}

verifyLoginToken(loginToken.token);
} catch (error) {
const message: string =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export const SIGN_UP = gql`
$captchaToken: String
$workspaceId: String
$locale: String
$verifyEmailNextPath: String
) {
signUp(
email: $email
Expand All @@ -18,6 +19,7 @@ export const SIGN_UP = gql`
captchaToken: $captchaToken
workspaceId: $workspaceId
locale: $locale
verifyEmailNextPath: $verifyEmailNextPath
) {
loginToken {
...AuthTokenFragment
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ describe('useAuth', () => {
const { result } = renderHooks();

await act(async () => {
await result.current.signUpWithCredentials(email, password);
await result.current.signUpWithCredentials({ email, password });
});

expect(mocks[2].result).toHaveBeenCalled();
Expand Down
23 changes: 16 additions & 7 deletions packages/twenty-front/src/modules/auth/hooks/useAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -397,13 +397,21 @@ export const useAuth = () => {
}, [clearSession]);

const handleCredentialsSignUp = useCallback(
async (
email: string,
password: string,
workspaceInviteHash?: string,
workspacePersonalInviteToken?: string,
captchaToken?: string,
) => {
async ({
email,
password,
workspaceInviteHash,
workspacePersonalInviteToken,
captchaToken,
verifyEmailNextPath,
}: {
email: string;
password: string;
workspaceInviteHash?: string;
workspacePersonalInviteToken?: string;
captchaToken?: string;
verifyEmailNextPath?: string;
}) => {
const signUpResult = await signUp({
variables: {
email,
Expand All @@ -415,6 +423,7 @@ export const useAuth = () => {
...(workspacePublicData?.id
? { workspaceId: workspacePublicData.id }
: {}),
verifyEmailNextPath,
},
});

Expand Down
Loading
Loading