The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
"use client";
import { getStripe } from "@/lib/stripe/client";
import { isEligibleForTrial } from "@/lib/stripe/is-eligible-for-trial";
import useWorkspace from "@/lib/swr/use-workspace";
import { Button, ButtonProps } from "@dub/ui";
import {
APP_DOMAIN,
capitalize,
DUB_TRIAL_PERIOD_DAYS,
isWorkspaceBillingTrialActive,
SELF_SERVE_PAID_PLANS,
} from "@dub/utils";
import { useSession } from "next-auth/react";
import { usePlausible } from "next-plausible";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useState } from "react";
import { useStartPaidPlanModal } from "../modals/start-paid-plan-modal";
import { useSwitchTrialPlanModal } from "../modals/switch-trial-plan-modal";
export function UpgradePlanButton({
plan,
tier,
period,
...rest
}: {
plan: string;
tier?: number;
period: "monthly" | "yearly";
} & Partial<ButtonProps>) {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const { data: session } = useSession();
const workspace = useWorkspace();
const {
slug: workspaceSlug,
plan: currentPlan,
planPeriod: currentPlanPeriod,
stripeId,
trialEndsAt,
} = workspace;
const plausible = usePlausible();
const product = searchParams.get("product");
const isTrialActive = isWorkspaceBillingTrialActive(trialEndsAt);
const selectedPlan =
SELF_SERVE_PAID_PLANS.find(
(p) => p.name.toLowerCase() === plan.toLowerCase(),
) ?? SELF_SERVE_PAID_PLANS[0];
const [clicked, setClicked] = useState(false);
const queryString = searchParams.toString();
const isCurrentPlanAndPeriod =
currentPlan === selectedPlan.name.toLowerCase() &&
period === currentPlanPeriod;
const performUpgrade = async () => {
setClicked(true);
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",
}),
},
);
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) }),
plan: capitalize(selectedPlan.name),
planPeriod: capitalize(period),
},
});
const stripe = await getStripe();
stripe?.redirectToCheckout({ sessionId });
} else {
const { url } = await res.json();
router.push(url);
}
} catch (err) {
alert(err);
} finally {
setClicked(false);
}
};
const { StartPaidPlanModal, setShowStartPaidPlanModal } =
useStartPaidPlanModal();
const isSwitchingTrialPlan =
isTrialActive && !isCurrentPlanAndPeriod && currentPlan !== "free";
const { SwitchTrialPlanModal, setShowSwitchTrialPlanModal } =
useSwitchTrialPlanModal({
newPlan: plan,
newPeriod: period,
newTier: tier,
onConfirm: performUpgrade,
});
const handleClick = () => {
if (isCurrentPlanAndPeriod && isTrialActive) {
setShowStartPaidPlanModal(true);
return;
}
if (isSwitchingTrialPlan) {
setShowSwitchTrialPlanModal(true);
return;
} else {
performUpgrade();
}
};
return (
<>
<StartPaidPlanModal />
<SwitchTrialPlanModal />
<Button
// these are the default text for onboarding plan selector
text={
!currentPlan
? "Loading..."
: isCurrentPlanAndPeriod
? isTrialActive
? "Activate plan"
: "Current plan"
: isEligibleForTrial({ workspace, session })
? `Start ${DUB_TRIAL_PERIOD_DAYS}-day trial · ${selectedPlan.name} ${capitalize(period)}`
: `Upgrade to ${selectedPlan.name} ${capitalize(period)}`
}
loading={clicked || !currentPlan}
disabled={!workspaceSlug || (isCurrentPlanAndPeriod && !isTrialActive)}
onClick={handleClick}
{...rest}
/>
</>
);
}