The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Switch trial plan (#3840)
Pedro Ladeira633134182cd4
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.tsindex 1d9a3680f0..65e01ae1c2 100644--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts@@ -63,8 +63,26 @@ export const POST = withWorkspace(}}- // if the user has an active or trialing subscription, create billing portal to upgradeif (workspace.stripeId && existingSubscription) {+ if (existingSubscription.status === "trialing") {+ await stripe.subscriptions.update(existingSubscription.id, {+ items: [+ {+ id: existingSubscription.items.data[0].id,+ price: prices.data[0].id,+ },+ ],+ proration_behavior: "none", // no invoice is created and no charge is issued+ });++ const successUrl = new URL(baseUrl);+ successUrl.searchParams.set("upgraded", "true");+ successUrl.searchParams.set("plan", plan);+ successUrl.searchParams.set("period", period);+ return NextResponse.json({ url: successUrl.toString() });+ }++ // Active subscriptions: use the billing portal's plan-change confirmation flow.const { url } = await stripe.billingPortal.sessions.create({customer: workspace.stripeId,return_url: baseUrl,diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page.tsxindex 949bc07b83..4a079f673d 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page.tsx@@ -278,7 +278,9 @@ export default function WorkspaceBillingUpgradePage() {? `Switch to ${period}`: isDowngrade? "Downgrade"- : "Upgrade"+ : isWorkspaceBillingTrialActive(trialEndsAt)+ ? "Switch trial"+ : "Upgrade"}variant={isDowngrade ? "secondary" : "primary"}className="h-8 shadow-sm"diff --git a/apps/web/ui/modals/plan-change-confirmation-modal.tsx b/apps/web/ui/modals/plan-change-confirmation-modal.tsxindex 0355bd6d25..bc08a728bc 100644--- a/apps/web/ui/modals/plan-change-confirmation-modal.tsx+++ b/apps/web/ui/modals/plan-change-confirmation-modal.tsx@@ -5,7 +5,14 @@ import useProgram from "@/lib/swr/use-program";import useWorkspace from "@/lib/swr/use-workspace";import { Button, Modal } from "@dub/ui";import { TriangleWarning } from "@dub/ui/icons";-import { OG_AVATAR_URL, pluralize } from "@dub/utils";+import {+ capitalize,+ getPlanDetails,+ OG_AVATAR_URL,+ pluralize,+} from "@dub/utils";+import NumberFlow from "@number-flow/react";+import { ArrowDown } from "lucide-react";import {Dispatch,SetStateAction,@@ -16,6 +23,48 @@ import {} from "react";import { Markdown } from "../shared/markdown";+function PlanCard({+ label,+ name,+ price,+ period,+}: {+ label: string;+ name: string;+ price: number | null;+ period: "monthly" | "yearly";+}) {+ const billingLabel =+ period === "yearly" ? "per month, billed yearly" : "per month";++ return (+ <div className="rounded-xl border border-neutral-200 bg-neutral-100 p-1 pt-0">+ <h3 className="px-1.5 py-2 text-xs font-medium leading-4 text-neutral-500">+ {label}+ </h3>+ <div className="rounded-lg border border-neutral-200 bg-white p-3">+ <p className="text-base font-semibold leading-none text-neutral-800">+ {name}+ </p>+ {price != null && (+ <div className="mt-1.5 flex items-baseline gap-1">+ <NumberFlow+ value={price}+ className="text-sm font-medium tabular-nums text-neutral-900"+ format={{+ style: "currency",+ currency: "USD",+ minimumFractionDigits: 0,+ }}+ />+ <span className="text-sm text-neutral-500">{billingLabel}</span>+ </div>+ )}+ </div>+ </div>+ );+}+export type PlanChangeConfirmationMode =| "program-downgrade"| "advanced-downgrade";@@ -24,18 +73,27 @@ function PlanChangeConfirmationModal({showPlanChangeConfirmationModal,setShowPlanChangeConfirmationModal,confirmationMode,+ newPlan,+ newPeriod,+ newTier = 1,onConfirm,}: {showPlanChangeConfirmationModal: boolean;setShowPlanChangeConfirmationModal: Dispatch<SetStateAction<boolean>>;confirmationMode: PlanChangeConfirmationMode;- onConfirm: () => void | Promise<void>;+ newPlan: string;+ newPeriod: "monthly" | "yearly";+ newTier?: number;+ onConfirm: () => Promise<void>;}) {const {slug,name: workspaceName,logo: workspaceLogo,defaultProgramId,+ plan: currentPlan,+ planPeriod: currentPlanPeriod,+ planTier: currentPlanTier = 1,} = useWorkspace();const { program } = useProgram({@@ -50,6 +108,24 @@ function PlanChangeConfirmationModal({const [isSubmitting, setIsSubmitting] = useState(false);+ const currentPeriod: "monthly" | "yearly" =+ currentPlanPeriod === "yearly" ? "yearly" : "monthly";++ const currentPlanDetails = useMemo(() => {+ if (!currentPlan || currentPlan === "free" || currentPlan === "enterprise")+ return null;+ return getPlanDetails({ plan: currentPlan, planTier: currentPlanTier });+ }, [currentPlan, currentPlanTier]);++ const newPlanDetails = useMemo(+ () => getPlanDetails({ plan: newPlan, planTier: newTier }),+ [newPlan, newTier],+ );++ const currentPrice = currentPlanDetails?.price?.[currentPeriod] ?? null;+ const newPrice = newPlanDetails?.price?.[newPeriod] ?? null;+ const newPlanLabel = newPlanDetails?.name ?? capitalize(newPlan);+const displayName = program?.name ?? workspaceName ?? "";const logoSrc =program?.logo ??@@ -84,6 +160,29 @@ function PlanChangeConfirmationModal({</div><div className="flex flex-col gap-4 bg-neutral-50 p-4 sm:p-6">+ <div className="flex flex-col gap-3">+ <PlanCard+ label="Current plan"+ name={+ currentPlanDetails?.name ?? capitalize(currentPlan ?? "") ?? ""+ }+ price={currentPrice}+ period={currentPeriod}+ />++ <ArrowDown+ className="ml-7 size-5 text-neutral-400"+ aria-hidden="true"+ />++ <PlanCard+ label="New plan"+ name={newPlanLabel}+ price={newPrice}+ period={newPeriod}+ />+ </div>+<div className="flex flex-col gap-1 rounded-lg bg-amber-100 p-1"><div className="flex items-center gap-2 p-2"><TriangleWarning className="size-4 shrink-0 text-amber-500" />@@ -149,10 +248,16 @@ function PlanChangeConfirmationModal({}export function usePlanChangeConfirmationModal({+ newPlan,+ newPeriod,+ newTier,onConfirm,confirmationMode = "program-downgrade",}: {- onConfirm: () => void | Promise<void>;+ newPlan: string;+ newPeriod: "monthly" | "yearly";+ newTier?: number;+ onConfirm: () => Promise<void>;confirmationMode?: PlanChangeConfirmationMode;}) {const [showPlanChangeConfirmationModal, setShowPlanChangeConfirmationModal] =@@ -165,12 +270,24 @@ export function usePlanChangeConfirmationModal({const confirmationModeRef = useRef(confirmationMode);confirmationModeRef.current = confirmationMode;+ const newPlanRef = useRef(newPlan);+ newPlanRef.current = newPlan;++ const newPeriodRef = useRef(newPeriod);+ newPeriodRef.current = newPeriod;++ const newTierRef = useRef(newTier);+ newTierRef.current = newTier;+const PlanChangeConfirmationModalCallback = useCallback(() => {return (<PlanChangeConfirmationModalshowPlanChangeConfirmationModal={showPlanChangeConfirmationModal}setShowPlanChangeConfirmationModal={setShowPlanChangeConfirmationModal}confirmationMode={confirmationModeRef.current}+ newPlan={newPlanRef.current}+ newPeriod={newPeriodRef.current}+ newTier={newTierRef.current}onConfirm={() => onConfirmRef.current()}/>);diff --git a/apps/web/ui/modals/switch-trial-plan-modal.tsx b/apps/web/ui/modals/switch-trial-plan-modal.tsxnew file mode 100644index 0000000000..f3eafdb421--- /dev/null+++ b/apps/web/ui/modals/switch-trial-plan-modal.tsx@@ -0,0 +1,252 @@+"use client";++import useWorkspace from "@/lib/swr/use-workspace";+import { Button, Modal } from "@dub/ui";+import {+ capitalize,+ getPlanDetails,+ isWorkspaceBillingTrialActive,+} from "@dub/utils";+import NumberFlow from "@number-flow/react";+import { ArrowDown } from "lucide-react";+import {+ Dispatch,+ SetStateAction,+ useCallback,+ useMemo,+ useRef,+ useState,+} from "react";++type SwitchTrialPlanModalProps = {+ showModal: boolean;+ setShowModal: Dispatch<SetStateAction<boolean>>;+ newPlan: string;+ newPeriod: "monthly" | "yearly";+ newTier?: number;+ onConfirm: () => Promise<void>;+};++function PlanCard({+ label,+ name,+ price,+ period,+}: {+ label: string;+ name: string;+ price: number | null;+ period: "monthly" | "yearly";+}) {+ const billingLabel =+ period === "yearly" ? "per month, billed yearly" : "per month";++ return (+ <div className="rounded-xl border border-neutral-200 bg-neutral-100 p-1 pt-0">+ <h3 className="px-1.5 py-2 text-xs font-medium leading-4 text-neutral-500">+ {label}+ </h3>+ <div className="rounded-lg border border-neutral-200 bg-white p-3">+ <p className="text-base font-semibold leading-none text-neutral-800">+ {name}+ </p>+ {price != null && (+ <div className="mt-1.5 flex items-baseline gap-1">+ <NumberFlow+ value={price}+ className="text-sm font-medium tabular-nums text-neutral-900"+ format={{+ style: "currency",+ currency: "USD",+ minimumFractionDigits: 0,+ }}+ />+ <span className="text-sm text-neutral-500">{billingLabel}</span>+ </div>+ )}+ </div>+ </div>+ );+}++function SwitchTrialPlanModal({+ showModal,+ setShowModal,+ newPlan,+ newPeriod,+ newTier = 1,+ onConfirm,+}: SwitchTrialPlanModalProps) {+ const {+ plan: currentPlan,+ planPeriod: currentPlanPeriod,+ planTier: currentPlanTier = 1,+ trialEndsAt,+ } = useWorkspace();++ const [isSubmitting, setIsSubmitting] = useState(false);++ const currentPeriod: "monthly" | "yearly" =+ currentPlanPeriod === "yearly" ? "yearly" : "monthly";++ const currentPlanDetails = useMemo(() => {+ if (!currentPlan || currentPlan === "free" || currentPlan === "enterprise")+ return null;+ return getPlanDetails({ plan: currentPlan, planTier: currentPlanTier });+ }, [currentPlan, currentPlanTier]);++ const newPlanDetails = useMemo(+ () => getPlanDetails({ plan: newPlan, planTier: newTier }),+ [newPlan, newTier],+ );++ const currentPrice = currentPlanDetails?.price?.[currentPeriod] ?? null;+ const newPrice = newPlanDetails?.price?.[newPeriod] ?? null;++ const trialEndDate =+ trialEndsAt && isWorkspaceBillingTrialActive(trialEndsAt)+ ? new Date(trialEndsAt).toLocaleDateString("en-US", {+ month: "long",+ day: "numeric",+ year: "numeric",+ })+ : null;++ const newPlanLabel = newPlanDetails?.name ?? capitalize(newPlan);+ const newPriceBillingLabel =+ newPeriod === "yearly" ? "per month, billed yearly" : "month";++ return (+ <Modal+ showModal={showModal}+ setShowModal={setShowModal}+ className="max-w-md"+ >+ <div className="flex items-center gap-2 border-b border-neutral-200 p-4 sm:p-6">+ <h3 className="text-lg font-medium leading-none">Switch trial plan</h3>+ </div>++ <div className="flex flex-col gap-2 bg-neutral-50 p-4 sm:p-6">+ <div className="flex flex-col gap-3">+ <PlanCard+ label="Current plan"+ name={+ currentPlanDetails?.name ?? capitalize(currentPlan ?? "") ?? ""+ }+ price={currentPrice}+ period={currentPeriod}+ />++ <ArrowDown+ className="ml-7 size-5 text-neutral-400"+ aria-hidden="true"+ />++ <PlanCard+ label="New plan"+ name={newPlanLabel}+ price={newPrice}+ period={newPeriod}+ />+ </div>++ <p className="mt-2 text-sm text-neutral-600">+ Your trial will continue on the{" "}+ <span className="font-semibold text-neutral-900">+ {newPlanLabel} plan+ </span>+ {trialEndDate && newPrice != null ? (+ <>+ , and you'll be charged{" "}+ <span className="font-semibold text-neutral-900">+ <NumberFlow+ value={newPrice}+ className="inline tabular-nums"+ format={{+ style: "currency",+ currency: "USD",+ minimumFractionDigits: 0,+ }}+ />+ /{newPriceBillingLabel}+ </span>{" "}+ starting{" "}+ <span className="font-semibold text-neutral-900">+ {trialEndDate}+ </span>+ </>+ ) : (+ <>, and you'll be charged the new rate when your trial ends</>+ )}+ .+ </p>+ </div>++ <div className="flex items-center justify-between gap-2 border-t border-neutral-200 px-4 py-5 sm:px-6">+ <Button+ variant="secondary"+ className="h-8 rounded-lg px-3 text-sm"+ text="Cancel"+ onClick={() => setShowModal(false)}+ disabled={isSubmitting}+ />+ <Button+ variant="primary"+ className="h-8 rounded-lg px-3 text-sm"+ text="Switch plan"+ loading={isSubmitting}+ onClick={async () => {+ if (isSubmitting) return;+ setIsSubmitting(true);+ try {+ await onConfirm();+ } finally {+ setShowModal(false);+ setIsSubmitting(false);+ }+ }}+ />+ </div>+ </Modal>+ );+}++export function useSwitchTrialPlanModal({+ newPlan,+ newPeriod,+ newTier,+ onConfirm,+}: {+ newPlan: string;+ newPeriod: "monthly" | "yearly";+ newTier?: number;+ onConfirm: () => Promise<void>;+}) {+ const [showModal, setShowModal] = useState(false);++ // Ref keeps the modal wrapper callback stable when the parent re-renders with a+ // new onConfirm (e.g. performUpgrade) so inner state like isSubmitting is not reset.+ const onConfirmRef = useRef(onConfirm);+ onConfirmRef.current = onConfirm;++ const SwitchTrialPlanModalCallback = useCallback(() => {+ return (+ <SwitchTrialPlanModal+ showModal={showModal}+ setShowModal={setShowModal}+ newPlan={newPlan}+ newPeriod={newPeriod}+ newTier={newTier}+ onConfirm={() => onConfirmRef.current()}+ />+ );+ }, [showModal, newPlan, newPeriod, newTier]);++ return useMemo(+ () => ({+ setShowSwitchTrialPlanModal: setShowModal,+ SwitchTrialPlanModal: SwitchTrialPlanModalCallback,+ }),+ [setShowModal, SwitchTrialPlanModalCallback],+ );+}diff --git a/apps/web/ui/workspaces/subscription-menu.tsx b/apps/web/ui/workspaces/subscription-menu.tsxindex a0d5bfc57e..7bbee57944 100644--- a/apps/web/ui/workspaces/subscription-menu.tsx+++ b/apps/web/ui/workspaces/subscription-menu.tsx@@ -87,6 +87,9 @@ export default function SubscriptionMenu() {const { setShowPlanChangeConfirmationModal, PlanChangeConfirmationModal } =usePlanChangeConfirmationModal({+ newPlan: "free",+ newPeriod: "monthly",+ newTier: 1,onConfirm: async () => {await cancelSubscription();setShowPlanChangeConfirmationModal(false);diff --git a/apps/web/ui/workspaces/upgrade-plan-button.tsx b/apps/web/ui/workspaces/upgrade-plan-button.tsxindex 442257d454..1ced6e1ffc 100644--- a/apps/web/ui/workspaces/upgrade-plan-button.tsx+++ b/apps/web/ui/workspaces/upgrade-plan-button.tsx@@ -18,6 +18,7 @@ import { usePathname, useRouter, useSearchParams } from "next/navigation";import { useMemo, useState } from "react";import { usePlanChangeConfirmationModal } from "../modals/plan-change-confirmation-modal";import { useStartPaidPlanModal } from "../modals/start-paid-plan-modal";+import { useSwitchTrialPlanModal } from "../modals/switch-trial-plan-modal";export function UpgradePlanButton({plan,@@ -79,28 +80,35 @@ export function UpgradePlanButton({};}, [currentPlan, defaultProgramId, selectedPlan.name]);- const performUpgrade = () => {+ const performUpgrade = async () => {setClicked(true);- fetch(`/api/workspaces/${workspaceSlug}/billing/upgrade`, {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- plan,- tier,- period,- baseUrl: `${APP_DOMAIN}${pathname}${queryString.length > 0 ? `?${queryString}` : ""}`,- onboarding: searchParams.get("workspace") ? "true" : "false",- isTrialVariant: isTrialVariant ? "true" : "false",- }),- })- .then(async (res) => {- if (!res.ok) {- const body = await res.json().catch(() => null);- throw new Error(body?.error?.message ?? "Failed to start checkout.");- }+ try {+ const res = await fetch(+ `/api/workspaces/${workspaceSlug}/billing/upgrade`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ plan,+ tier,+ period,+ baseUrl: `${APP_DOMAIN}${pathname}${queryString.length > 0 ? `?${queryString}` : ""}`,+ onboarding: searchParams.get("workspace") ? "true" : "false",+ isTrialVariant: isTrialVariant ? "true" : "false",+ }),+ },+ );++ if (!res.ok) {+ const body = await res.json().catch(() => null);+ throw new Error(body?.error?.message ?? "Failed to start checkout.");+ }+ if (!stripeId || currentPlan === "free") {+ const data = await res.json();+ const { id: sessionId } = data;plausible("Opened Checkout", {props: {...(product && { product: capitalize(product) }),@@ -108,26 +116,24 @@ export function UpgradePlanButton({planPeriod: capitalize(period),},});- if (!stripeId || currentPlan === "free") {- const data = await res.json();- const { id: sessionId } = data;- const stripe = await getStripe();- stripe?.redirectToCheckout({ sessionId });- } else {- const { url } = await res.json();- router.push(url);- }- })- .catch((err) => {- alert(err);- })- .finally(() => {- setClicked(false);- });+ const stripe = await getStripe();+ stripe?.redirectToCheckout({ sessionId });+ } else {+ const { url } = await res.json();+ router.push(url);+ }+ } catch (err) {+ alert(err);+ } finally {+ setClicked(false);+ }};const { setShowPlanChangeConfirmationModal, PlanChangeConfirmationModal } =usePlanChangeConfirmationModal({+ newPlan: plan,+ newPeriod: period,+ newTier: tier,onConfirm: performUpgrade,confirmationMode:losesAdvancedFeatures && !losesPartnerAccess@@ -138,6 +144,17 @@ export function UpgradePlanButton({const { StartPaidPlanModal, setShowStartPaidPlanModal } =useStartPaidPlanModal();+ const isSwitchingTrialPlan =+ isTrialActive && !isCurrentPlan && currentPlan !== "free";++ const { SwitchTrialPlanModal, setShowSwitchTrialPlanModal } =+ useSwitchTrialPlanModal({+ newPlan: plan,+ newPeriod: period,+ newTier: tier,+ onConfirm: performUpgrade,+ });+const handleClick = () => {if (isCurrentPlan && isTrialActive) {setShowStartPaidPlanModal(true);@@ -145,6 +162,11 @@ export function UpgradePlanButton({}if (losesPartnerAccess || losesAdvancedFeatures) {setShowPlanChangeConfirmationModal(true);+ return;+ }+ if (isSwitchingTrialPlan) {+ setShowSwitchTrialPlanModal(true);+ return;} else {performUpgrade();}@@ -154,6 +176,7 @@ export function UpgradePlanButton({<><PlanChangeConfirmationModal /><StartPaidPlanModal />+ <SwitchTrialPlanModal /><Buttontext={!currentPlan@@ -166,7 +189,9 @@ export function UpgradePlanButton({? isTrialVariant? `Start ${DUB_TRIAL_PERIOD_DAYS}-day trial · ${selectedPlan.name} ${capitalize(period)}`: `Upgrade to ${selectedPlan.name} ${capitalize(period)}`- : `Switch to ${selectedPlan.name} ${capitalize(period)}`+ : isTrialActive+ ? `Switch trial to ${selectedPlan.name} ${capitalize(period)}`+ : `Switch to ${selectedPlan.name} ${capitalize(period)}`}loading={clicked || !currentPlan}disabled={!workspaceSlug || (isCurrentPlan && !isTrialActive)}