Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(onboarding): chg checkout flow (#5230)
teoeaf11194f9b3
diff --git a/apps/web/src/features/onboarding/use-onboarding-checkout.test.ts b/apps/web/src/features/onboarding/use-onboarding-checkout.test.tsindex f5bae24bc9..a7fe3cd6bb 100644--- a/apps/web/src/features/onboarding/use-onboarding-checkout.test.ts+++ b/apps/web/src/features/onboarding/use-onboarding-checkout.test.ts@@ -21,7 +21,7 @@ beforeEach(() => {});describe('createOnboardingCheckoutSession', () => {- it('uses the supported v2 checkout endpoint and onboarding return URL', async () => {+ it('uses the supported v2 checkout endpoint and returns both legs to the flow', async () => {mocks.createCheckoutSessionV2.mockResolvedValue('https://checkout.test/1');await expect(createOnboardingCheckoutSession('premium')).resolves.toEqual({@@ -29,7 +29,8 @@ describe('createOnboardingCheckoutSession', () => {});expect(mocks.createCheckoutSessionV2).toHaveBeenCalledOnce();expect(mocks.createCheckoutSessionV2).toHaveBeenCalledWith({- successUrl: `${window.location.origin}/app/welcome?subscriptionSuccess=true&type=premium`,+ successUrl: `${window.location.origin}/app/onboarding?subscriptionSuccess=true&type=premium`,+ cancelUrl: `${window.location.origin}/app/onboarding?subscriptionCancel=true`,});});diff --git a/apps/web/src/features/onboarding/use-onboarding-checkout.ts b/apps/web/src/features/onboarding/use-onboarding-checkout.tsindex bfc9464cf7..7849fb752f 100644--- a/apps/web/src/features/onboarding/use-onboarding-checkout.ts+++ b/apps/web/src/features/onboarding/use-onboarding-checkout.ts@@ -18,13 +18,19 @@ interface OnboardingCheckoutResult {checkoutUrl: string;}-/** Creates a Stripe checkout session that returns to onboarding completion. */+/**+ * Creates a Stripe checkout session whose round-trip returns to the+ * onboarding flow: the flow is still incomplete during checkout, so both+ * legs land back on the plan step (restored from sessionStorage), which+ * reads the query params to show the paid or cancelled state.+ */export async function createOnboardingCheckoutSession(tier: PaidPlanTier): Promise<OnboardingCheckoutResult> {- const successUrl = `${window.location.origin}${ROUTER_BASE_CONCAT}welcome?subscriptionSuccess=true&type=${tier}`;+ const onboardingUrl = `${window.location.origin}${ROUTER_BASE_CONCAT}onboarding`;const checkoutUrl = await stripeServiceClient.createCheckoutSessionV2({- successUrl,+ successUrl: `${onboardingUrl}?subscriptionSuccess=true&type=${tier}`,+ cancelUrl: `${onboardingUrl}?subscriptionCancel=true`,});if (!checkoutUrl) {diff --git a/apps/web/src/features/setup/flow/OnboardingFlow.tsx b/apps/web/src/features/setup/flow/OnboardingFlow.tsxindex cfea1276fc..40fe0af65b 100644--- a/apps/web/src/features/setup/flow/OnboardingFlow.tsx+++ b/apps/web/src/features/setup/flow/OnboardingFlow.tsx@@ -69,7 +69,10 @@ interface StepControls {skip: () => void;finishing: () => boolean;finishFree: (planSkipped: boolean) => void;- finishPremium: (tier: 'premium') => void;+ /** Redirect to Stripe checkout without completing the flow. */+ startPremiumCheckout: (tier: 'premium') => void;+ /** Finish after checkout confirmed payment (or an existing license). */+ finishPremium: () => void;}interface ConnectorStepCopy {@@ -187,7 +190,8 @@ function buildSteps(<PlanStepfinishing={controls.finishing()}onFree={controls.finishFree}- onPremium={controls.finishPremium}+ onStartCheckout={controls.startPremiumCheckout}+ onPremiumPaid={controls.finishPremium}/>),},@@ -330,7 +334,8 @@ function FlowContent() {skip: () => advance('skipped'),finishing: finish.finishing,finishFree: (planSkipped) => void finish.finishFree(planSkipped),- finishPremium: (tier) => void finish.finishPremium(tier),+ startPremiumCheckout: (tier) => void finish.startPremiumCheckout(tier),+ finishPremium: () => void finish.finishPremium(),};// Heal a half-landed finish: NewOnboardingRedirect keys offdiff --git a/apps/web/src/features/setup/flow/PlanStep.tsx b/apps/web/src/features/setup/flow/PlanStep.tsxindex 71bf842831..84b979ceee 100644--- a/apps/web/src/features/setup/flow/PlanStep.tsx+++ b/apps/web/src/features/setup/flow/PlanStep.tsx@@ -3,97 +3,173 @@ import {PLANS,type PlanTier,} from '@app/features/paywall/plans';+import { useAnalytics } from '@app/lib/analytics/analytics-context';import ArrowRight from '@phosphor/arrow-right.svg';import Check from '@phosphor/check.svg';+import { useUserInfoQuery } from '@queries/auth/user-info';+import { useSearchParams } from '@solidjs/router';import { Button, cn } from '@ui';-import { createSignal, Index, Show } from 'solid-js';+import { createSignal, Index, onCleanup, onMount, Show } from 'solid-js';import { SkipButton } from './shared';-/** Free vs paid. The last step: continuing or skipping marks onboarding- * complete; skippers land exactly where finishers do. */+// The license flips via Stripe webhook after checkout; poll briefly so the+// app already reflects Premium when the user continues in.+const LICENSE_POLL_ATTEMPTS = 10;+const LICENSE_POLL_INTERVAL_MS = 1_000;++/** Free vs paid. The last step: free/skip finishes immediately; premium+ * round-trips through Stripe checkout (the flow stays incomplete, so both+ * checkout legs land back here) and finishes once payment is confirmed. */export function PlanStep(props: {finishing: boolean;onFree: (planSkipped: boolean) => void;- onPremium: (tier: Exclude<PlanTier, 'free'>) => void;+ onStartCheckout: (tier: Exclude<PlanTier, 'free'>) => void;+ onPremiumPaid: () => void;}) {+ const [searchParams] = useSearchParams();+ const userInfoQuery = useUserInfoQuery();+ const analytics = useAnalytics();const [selected, setSelected] = createSignal<PlanTier>('free');+ const returnedFromCheckout = searchParams.subscriptionSuccess === 'true';+ const hasPaidAccess = () =>+ userInfoQuery.data?.licenseStatus === 'active' ||+ userInfoQuery.data?.licenseStatus === 'trialing';+ // Back from a successful checkout, or the license is already active (an+ // abandoned checkout return, or a team/enterprise license) — creating+ // another checkout session for these users would just be rejected.+ const premiumActive = () => returnedFromCheckout || hasPaidAccess();++ onMount(() => {+ if (!returnedFromCheckout) return;+ analytics.track('subscription_success', { type: searchParams.type });+ let cancelled = false;+ onCleanup(() => {+ cancelled = true;+ });+ void (async () => {+ for (let attempt = 0; attempt < LICENSE_POLL_ATTEMPTS; attempt++) {+ if (cancelled || hasPaidAccess()) return;+ await new Promise((resolve) =>+ setTimeout(resolve, LICENSE_POLL_INTERVAL_MS)+ );+ if (cancelled) return;+ await userInfoQuery.refetch().catch(() => {});+ }+ })();+ });+const finish = () => {const tier = selected();if (tier === 'free') props.onFree(false);- else props.onPremium(tier);+ else props.onStartCheckout(tier);};return (- <div class="flex flex-col gap-6">- <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">- <Index each={PLANS}>- {(plan) => (- <button- type="button"- onClick={() => setSelected(plan().tier)}- class={cn(- 'flex flex-col gap-4 rounded-xl border p-5 text-left transition-colors cursor-default',- selected() === plan().tier- ? 'border-ink/40 ring-1 ring-ink/20'- : 'border-edge hover:border-edge-muted'- )}- >- <div class="flex items-center justify-between">- <span class="text-sm font-semibold text-ink">- {plan().name}- </span>- <span- class={cn(- 'flex items-center justify-center size-4 rounded-full border',- selected() === plan().tier- ? 'border-ink bg-ink text-surface'- : 'border-edge'- )}- >- <Show when={selected() === plan().tier}>- <Check class="size-3" />- </Show>- </span>- </div>- <div class="flex items-baseline gap-1">- <span class="text-2xl font-semibold tracking-tight text-ink">- ${plan().price}- </span>- <span class="text-xs text-ink-muted">- {plan().price === 0 ? 'forever' : 'per user / month'}- </span>- </div>- <ul class="flex flex-col gap-2">- <Index each={PLAN_FEATURES}>- {(feature) => (- <li class="flex items-center justify-between gap-2 text-xs">- <span class="text-ink-muted">{feature().label}</span>- <span class="text-ink font-medium">- {feature().values[plan().tier]}- </span>- </li>- )}- </Index>- </ul>- </button>- )}- </Index>- </div>+ <Show+ when={!premiumActive()}+ fallback={+ <div class="flex flex-col gap-6">+ <div class="flex flex-col items-start gap-3 rounded-xl border border-edge p-5">+ <span class="flex size-8 items-center justify-center rounded-full bg-accent/15 text-accent">+ <Check class="size-4" />+ </span>+ <div class="flex flex-col gap-1">+ <span class="text-sm font-semibold text-ink">+ {returnedFromCheckout+ ? 'Payment successful'+ : 'Premium is already active'}+ </span>+ <p class="text-sm leading-relaxed text-ink-muted">+ {returnedFromCheckout+ ? 'Premium is now active on your account.'+ : 'Your account already has Premium access — no payment needed.'}+ </p>+ </div>+ </div>+ <Button+ variant="cta"+ disabled={props.finishing}+ onClick={() => props.onPremiumPaid()}+ >+ {props.finishing ? 'Setting up your workspace…' : 'Continue'}+ <ArrowRight class="size-4" />+ </Button>+ </div>+ }+ >+ <div class="flex flex-col gap-6">+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <Index each={PLANS}>+ {(plan) => (+ <button+ type="button"+ onClick={() => setSelected(plan().tier)}+ class={cn(+ 'flex flex-col gap-4 rounded-xl border p-5 text-left transition-colors cursor-default',+ selected() === plan().tier+ ? 'border-ink/40 ring-1 ring-ink/20'+ : 'border-edge hover:border-edge-muted'+ )}+ >+ <div class="flex items-center justify-between">+ <span class="text-sm font-semibold text-ink">+ {plan().name}+ </span>+ <span+ class={cn(+ 'flex items-center justify-center size-4 rounded-full border',+ selected() === plan().tier+ ? 'border-ink bg-ink text-surface'+ : 'border-edge'+ )}+ >+ <Show when={selected() === plan().tier}>+ <Check class="size-3" />+ </Show>+ </span>+ </div>+ <div class="flex items-baseline gap-1">+ <span class="text-2xl font-semibold tracking-tight text-ink">+ ${plan().price}+ </span>+ <span class="text-xs text-ink-muted">+ {plan().price === 0 ? 'forever' : 'per user / month'}+ </span>+ </div>+ <ul class="flex flex-col gap-2">+ <Index each={PLAN_FEATURES}>+ {(feature) => (+ <li class="flex items-center justify-between gap-2 text-xs">+ <span class="text-ink-muted">{feature().label}</span>+ <span class="text-ink font-medium">+ {feature().values[plan().tier]}+ </span>+ </li>+ )}+ </Index>+ </ul>+ </button>+ )}+ </Index>+ </div>- <div class="flex flex-col gap-3">- <Button variant="cta" disabled={props.finishing} onClick={finish}>- {props.finishing- ? 'Setting up your workspace…'- : `Continue with ${selected() === 'free' ? 'Free' : 'Premium'}`}- <ArrowRight class="size-4" />- </Button>- <SkipButton- label="Decide later"- disabled={props.finishing}- onClick={() => props.onFree(true)}- />+ <div class="flex flex-col gap-3">+ <Button variant="cta" disabled={props.finishing} onClick={finish}>+ {props.finishing+ ? selected() === 'free'+ ? 'Setting up your workspace…'+ : 'Heading to checkout…'+ : `Continue with ${selected() === 'free' ? 'Free' : 'Premium'}`}+ <ArrowRight class="size-4" />+ </Button>+ <SkipButton+ label="Decide later"+ disabled={props.finishing}+ onClick={() => props.onFree(true)}+ />+ </div></div>- </div>+ </Show>);}diff --git a/apps/web/src/features/setup/flow/createFlowFinish.ts b/apps/web/src/features/setup/flow/createFlowFinish.tsindex b09963de10..46fbf17bcb 100644--- a/apps/web/src/features/setup/flow/createFlowFinish.ts+++ b/apps/web/src/features/setup/flow/createFlowFinish.ts@@ -4,7 +4,7 @@ import { useAnalytics } from '@app/lib/analytics/analytics-context';import { toast } from '@core/component/Toast/Toast';import { authKeys } from '@queries/auth/keys';import { useCompleteTutorialMutation } from '@queries/auth/tutorial';-import { useUserInfoQuery } from '@queries/auth/user-info';+import type { UserInfoData } from '@queries/auth/user-info';import { queryClient } from '@queries/client';import { useCompleteOnboardingMutation } from '@queries/onboarding';import { useNavigate, useSearchParams } from '@solidjs/router';@@ -26,7 +26,6 @@ export function createFlowFinish(options?: {}) {const navigate = useNavigate();const [searchParams] = useSearchParams();- const userInfoQuery = useUserInfoQuery();const completeOnboarding = useCompleteOnboardingMutation();const completeTutorial = useCompleteTutorialMutation();const analytics = useAnalytics();@@ -81,7 +80,13 @@ export function createFlowFinish(options?: {await queryClient.refetchQueries({ queryKey: authKeys.userInfo.queryKey }).catch(() => {});- if (userInfoQuery.data?.tutorialComplete !== true) {+ // Read the cache, not the query observer: observer stores flush on a+ // scheduled task, so right after the await they still hold the+ // pre-PATCH value and the guard would fail on a fresh success.+ const userInfo = queryClient.getQueryData<UserInfoData>(+ authKeys.userInfo.queryKey+ );+ if (userInfo?.tutorialComplete !== true) {toast.failure("Couldn't finish setup — please try again");return false;}@@ -105,22 +110,33 @@ export function createFlowFinish(options?: {};/**- * Finish on a paid tier: complete the flow FIRST (the checkout round-trip- * must not bounce back into onboarding), then hand the page to Stripe.+ * Hand the page to Stripe WITHOUT completing the flow: the onboarding+ * redirect plus the persisted step bring both checkout legs (success and+ * cancel) back to the plan step, which finishes only once payment is+ * confirmed. On failure the user stays on the plan step and can retry or+ * pick free.*/- const finishPremium = async (tier: PaidPlanTier) => {+ const startPremiumCheckout = async (tier: PaidPlanTier) => {if (finishing()) return;setFinishing(true);try {- if (!(await completeFlow())) return;- trackCompleted('premium', false);- try {- const { checkoutUrl } = await createOnboardingCheckoutSession(tier);- window.location.href = checkoutUrl;- } catch {- toast.failure(- "Couldn't start checkout — you can upgrade anytime from settings"- );+ const { checkoutUrl } = await createOnboardingCheckoutSession(tier);+ // Deliberately leave `finishing` set: the page is navigating away,+ // and re-enabling the buttons mid-unload invites a double checkout.+ window.location.href = checkoutUrl;+ } catch {+ toast.failure("Couldn't start checkout — please try again");+ setFinishing(false);+ }+ };++ /** Finish after checkout confirmed payment (or an existing license). */+ const finishPremium = async () => {+ if (finishing()) return;+ setFinishing(true);+ try {+ if (await completeFlow()) {+ trackCompleted('premium', false);navigate(afterTarget(), { replace: true });}} finally {@@ -128,5 +144,11 @@ export function createFlowFinish(options?: {}};- return { finishing, finishFree, finishPremium, afterTarget };+ return {+ finishing,+ finishFree,+ startPremiumCheckout,+ finishPremium,+ afterTarget,+ };}diff --git a/apps/web/src/lib/service-clients/service-stripe/client.ts b/apps/web/src/lib/service-clients/service-stripe/client.tsindex 4c8b09233b..51778d6154 100644--- a/apps/web/src/lib/service-clients/service-stripe/client.ts+++ b/apps/web/src/lib/service-clients/service-stripe/client.ts@@ -44,9 +44,11 @@ export const stripeServiceClient = {discount?: string;/** Override the default success URL. Useful for flows that want the user returned to a specific page. */successUrl?: string;+ /** Override the default cancel URL. Useful for flows that want cancellation to return to a specific page. */+ cancelUrl?: string;} = {}) => {- const { type = '', discount, successUrl } = args;+ const { type = '', discount, successUrl, cancelUrl } = args;const gaClientId = await getGaClientId();const { fbp, fbc } = getMetaIds();@@ -54,7 +56,8 @@ export const stripeServiceClient = {successUrl:successUrl ??`${window.location.origin}/app/?subscriptionSuccess=true${type ? `&type=${type}` : ''}`,- cancelUrl: `${window.location.origin}/app?subscriptionCancel=true`,+ cancelUrl:+ cancelUrl ?? `${window.location.origin}/app?subscriptionCancel=true`,discount: discount ?? null,metadata: {gaClientId: gaClientId ?? null,