The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Pricing updates (#3034)
Tim Wilsonb6f6c2a9b433
diff --git a/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.ts b/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.tsindex f20d1a95df..6e220fa775 100644--- a/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.ts@@ -11,7 +11,7 @@ import { sendBatchEmail } from "@dub/email";import UpgradeEmail from "@dub/email/templates/upgrade-email";import { prisma } from "@dub/prisma";import { User } from "@dub/prisma/client";-import { getPlanFromPriceId, log } from "@dub/utils";+import { getPlanAndTierFromPriceId, log } from "@dub/utils";import Stripe from "stripe";export async function checkoutSessionCompleted(event: Stripe.Event) {@@ -37,7 +37,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {);const priceId = subscription.items.data[0].price.id;- const plan = getPlanFromPriceId(priceId);+ const { plan, planTier } = getPlanAndTierFromPriceId({ priceId });if (!plan) {console.log(@@ -62,16 +62,17 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {stripeId,billingCycleStart: new Date().getDate(),plan: planName,- usageLimit: plan.limits.clicks!,- linksLimit: plan.limits.links!,- payoutsLimit: plan.limits.payouts!,- domainsLimit: plan.limits.domains!,- aiLimit: plan.limits.ai!,- tagsLimit: plan.limits.tags!,- foldersLimit: plan.limits.folders!,- groupsLimit: plan.limits.groups!,- networkInvitesLimit: plan.limits.networkInvites!,- usersLimit: plan.limits.users!,+ planTier: planTier,+ usageLimit: plan.limits.clicks,+ linksLimit: plan.limits.links,+ payoutsLimit: plan.limits.payouts,+ domainsLimit: plan.limits.domains,+ aiLimit: plan.limits.ai,+ tagsLimit: plan.limits.tags,+ foldersLimit: plan.limits.folders,+ groupsLimit: plan.limits.groups,+ networkInvitesLimit: plan.limits.networkInvites,+ usersLimit: plan.limits.users,paymentFailedAt: null,},select: {@@ -118,6 +119,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {name: user.name,email: user.email as string,plan: plan.name,+ planTier: planTier,}),variant: "marketing",})),diff --git a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.tsindex a1694521c5..822f4c73f2 100644--- a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts@@ -6,7 +6,7 @@ import { stripe } from "@/lib/stripe";import { recordLink } from "@/lib/tinybird";import { webhookCache } from "@/lib/webhook/cache";import { prisma } from "@dub/prisma";-import { capitalize, FREE_PLAN, getPlanFromPriceId, log } from "@dub/utils";+import { capitalize, FREE_PLAN, log } from "@dub/utils";import { NextResponse } from "next/server";import Stripe from "stripe";import { sendCancellationFeedback } from "./utils/send-cancellation-feedback";@@ -27,6 +27,7 @@ export async function customerSubscriptionDeleted(event: Stripe.Event) {id: true,slug: true,plan: true,+ planTier: true,foldersUsage: true,paymentFailedAt: true,payoutsLimit: true,@@ -85,11 +86,9 @@ export async function customerSubscriptionDeleted(event: Stripe.Event) {if (activeSubscriptions.length > 0) {const activeSubscription = activeSubscriptions[0];const priceId = activeSubscription.items.data[0].price.id;- const plan = getPlanFromPriceId(priceId);await updateWorkspacePlan({workspace,- plan,priceId,});diff --git a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.tsindex e73f887b0f..b28c6bbb52 100644--- a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts@@ -1,5 +1,5 @@import { prisma } from "@dub/prisma";-import { getPlanFromPriceId } from "@dub/utils";+import { getPlanAndTierFromPriceId } from "@dub/utils";import { NextResponse } from "next/server";import Stripe from "stripe";import { sendCancellationFeedback } from "./utils/send-cancellation-feedback";@@ -9,7 +9,7 @@ export async function customerSubscriptionUpdated(event: Stripe.Event) {const subscriptionUpdated = event.data.object as Stripe.Subscription;const priceId = subscriptionUpdated.items.data[0].price.id;- const plan = getPlanFromPriceId(priceId);+ const { plan } = getPlanAndTierFromPriceId({ priceId });if (!plan) {console.log(@@ -27,6 +27,7 @@ export async function customerSubscriptionUpdated(event: Stripe.Event) {select: {id: true,plan: true,+ planTier: true,paymentFailedAt: true,payoutsLimit: true,foldersUsage: true,@@ -66,7 +67,6 @@ export async function customerSubscriptionUpdated(event: Stripe.Event) {await updateWorkspacePlan({workspace,- plan,priceId,});diff --git a/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts b/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.tsindex 0b89c58ff5..806087aa9a 100644--- a/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts@@ -4,17 +4,17 @@ import { getPlanCapabilities } from "@/lib/plan-capabilities";import { WorkspaceProps } from "@/lib/types";import { webhookCache } from "@/lib/webhook/cache";import { prisma } from "@dub/prisma";-import { getPlanFromPriceId } from "@dub/utils";+import { getPlanAndTierFromPriceId } from "@dub/utils";import { NEW_BUSINESS_PRICE_IDS } from "@dub/utils/src";export async function updateWorkspacePlan({workspace,- plan,priceId,}: {workspace: Pick<WorkspaceProps,| "id"+ | "planTier"| "paymentFailedAt"| "payoutsLimit"| "foldersUsage"@@ -25,14 +25,14 @@ export async function updateWorkspacePlan({hashedKey: string;}[];};- plan: ReturnType<typeof getPlanFromPriceId>;priceId: string;}) {- if (!plan) {- return;- }+ const { plan: newPlan, planTier: newPlanTier } = getPlanAndTierFromPriceId({+ priceId,+ });+ if (!newPlan) return;- const newPlanName = plan.name.toLowerCase();+ const newPlanName = newPlan.name.toLowerCase();const shouldDisableWebhooks = newPlanName === "free" || newPlanName === "pro";const shouldDeleteFolders =newPlanName === "free" && workspace.foldersUsage > 0;@@ -42,7 +42,8 @@ export async function updateWorkspacePlan({// update their usage limit in the databaseif (workspace.plan !== newPlanName ||- (workspace.payoutsLimit < plan.limits.payouts &&+ workspace.planTier !== newPlanTier ||+ (workspace.payoutsLimit < newPlan.limits.payouts &&NEW_BUSINESS_PRICE_IDS.includes(priceId))) {await Promise.allSettled([@@ -52,16 +53,17 @@ export async function updateWorkspacePlan({},data: {plan: newPlanName,- usageLimit: plan.limits.clicks!,- linksLimit: plan.limits.links!,- payoutsLimit: plan.limits.payouts!,- domainsLimit: plan.limits.domains!,- aiLimit: plan.limits.ai!,- tagsLimit: plan.limits.tags!,- foldersLimit: plan.limits.folders!,- groupsLimit: plan.limits.groups!,- networkInvitesLimit: plan.limits.networkInvites!,- usersLimit: plan.limits.users!,+ planTier: newPlanTier,+ usageLimit: newPlan.limits.clicks,+ linksLimit: newPlan.limits.links,+ payoutsLimit: newPlan.limits.payouts,+ domainsLimit: newPlan.limits.domains,+ aiLimit: newPlan.limits.ai,+ tagsLimit: newPlan.limits.tags,+ foldersLimit: newPlan.limits.folders,+ groupsLimit: newPlan.limits.groups,+ networkInvitesLimit: newPlan.limits.networkInvites,+ usersLimit: newPlan.limits.users,paymentFailedAt: null,...(shouldDeleteFolders && { foldersUsage: 0 }),},@@ -72,7 +74,7 @@ export async function updateWorkspacePlan({projectId: workspace.id,},data: {- rateLimit: plan.limits.api,+ rateLimit: newPlan.limits.api,},}),diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.tsindex 92f6cb38ff..b1db165677 100644--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts@@ -2,33 +2,39 @@ import { DubApiError } from "@/lib/api/errors";import { isDubAdmin, withWorkspace } from "@/lib/auth";import { getDubCustomer } from "@/lib/dub";import { stripe } from "@/lib/stripe";+import { booleanQuerySchema } from "@/lib/zod/schemas/misc";import { APP_DOMAIN } from "@dub/utils";import { NextResponse } from "next/server";+import { z } from "zod";++const upgradePlanSchema = z.object({+ plan: z.enum(["pro", "business", "advanced"]),+ period: z.enum(["monthly", "yearly"]),+ tier: z.number().min(1).max(3).optional().default(1),+ baseUrl: z.string().refine((url) => url.startsWith(APP_DOMAIN), {+ message: "Invalid baseUrl.",+ }),+ onboarding: booleanQuerySchema.nullish(),+});// POST /api/workspaces/[idOrSlug]/billing/upgradeexport const POST = withWorkspace(async ({ req, workspace, session }) => {- let { plan, period, baseUrl, onboarding } = await req.json();+ let { plan, period, tier, baseUrl, onboarding } = upgradePlanSchema.parse(+ await req.json(),+ );- if (!baseUrl.startsWith(APP_DOMAIN)) {- throw new DubApiError({- code: "unprocessable_entity",- message: "Invalid baseUrl.",- });- }+ const lookupKey = tier > 1 ? `${plan}${tier}_${period}` : `${plan}_${period}`;+ const prices = await stripe.prices.list({+ lookup_keys: [lookupKey],+ });- if (!plan || !period) {+ if (prices.data.length === 0) {throw new DubApiError({- code: "unprocessable_entity",- message: "Invalid plan or period.",+ code: "not_found",+ message: `Price not found for lookup key: ${lookupKey}`,});}- plan = plan.replace(" ", "+");-- const prices = await stripe.prices.list({- lookup_keys: [`${plan}_${period}`],- });-const activeSubscription = workspace.stripeId? await stripe.subscriptions.list({diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsxindex 0167aa2ef5..fb1cc8bb6d 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/plan-usage.tsx@@ -6,8 +6,9 @@ import useTagsCount from "@/lib/swr/use-tags-count";import useUsage from "@/lib/swr/use-usage";import useWorkspace from "@/lib/swr/use-workspace";import useWorkspaceUsers from "@/lib/swr/use-workspace-users";+import { useManageUsageModal } from "@/ui/modals/manage-usage-modal";import SubscriptionMenu from "@/ui/workspaces/subscription-menu";-import { buttonVariants, Icon, Tooltip, useRouterStuff } from "@dub/ui";+import { Button, buttonVariants, Icon, Tooltip, useRouterStuff } from "@dub/ui";import {CirclePercentage,CreditCard,@@ -97,14 +98,14 @@ export default function PlanUsage() {const tabs = [{- id: "events",+ id: "events" as const,icon: CursorRays,title: "Events tracked",usage: usage,limit: usageLimit,},{- id: "links",+ id: "links" as const,icon: Hyperlink,title: "Links created",usage:@@ -268,7 +269,7 @@ function UsageTabCard({unit,requiresUpgrade,}: {- id: string;+ id: "links" | "events";icon: Icon;title: string;usage?: number;@@ -277,7 +278,11 @@ function UsageTabCard({requiresUpgrade?: boolean;}) {const { queryParams } = useRouterStuff();- const { slug } = useWorkspace();+ const { slug, plan } = useWorkspace();++ const { ManageUsageModal, setShowManageUsageModal } = useManageUsageModal({+ type: id,+ });const { activeResource } = useUsage();@@ -294,105 +299,119 @@ function UsageTabCard({const prefix = unit || "";return (- <button- className={cn(- "rounded-lg border border-neutral-300 bg-white px-4 py-3 text-left transition-colors duration-75",- "outline-none focus-visible:border-blue-600 focus-visible:ring-1 focus-visible:ring-blue-600",- activeResource === id && "border-neutral-900 ring-1 ring-neutral-900",- requiresUpgrade- ? "border-neutral-100 bg-neutral-100 hover:bg-neutral-100"- : "hover:bg-neutral-50 lg:px-5 lg:py-4",- )}- aria-selected={activeResource === id}- onClick={() => !requiresUpgrade && queryParams({ set: { tab: id } })}- disabled={requiresUpgrade}- >- <Icon className="size-4 text-neutral-600" />- <div className="mt-1.5 flex items-center gap-2 text-sm text-neutral-600">- {title}- {requiresUpgrade && (- <Tooltip- content={- <div className="max-w-xs px-4 py-2 text-center text-sm text-neutral-600">- Upgrade to Business to unlock conversion tracking.{" "}- <Link- href={`/${slug}/upgrade`}- className="underline underline-offset-2 hover:text-neutral-800"- >- View pricing plans- </Link>- </div>- }- >- <span className="flex items-center gap-1 rounded-full border border-neutral-300 px-2 py-0.5 text-xs text-neutral-500">- <CrownSmall className="size-" />- Business- </span>- </Tooltip>+ <div className="relative">+ <ManageUsageModal />+ <button+ className={cn(+ "w-full rounded-lg border border-neutral-300 bg-white px-4 py-3 text-left transition-colors duration-75",+ "outline-none focus-visible:border-blue-600 focus-visible:ring-1 focus-visible:ring-blue-600",+ activeResource === id && "border-neutral-900 ring-1 ring-neutral-900",+ requiresUpgrade+ ? "border-neutral-100 bg-neutral-100 hover:bg-neutral-100"+ : "hover:bg-neutral-50 lg:px-5 lg:py-4",)}- </div>- <div className="mt-2">- {!loading ? (- <NumberFlow- value={usage}- className="text-xl leading-none text-neutral-900"- format={- unit === "$"- ? {- style: "currency",- currency: "USD",- // @ts-ignore – trailingZeroDisplay is a valid option but TS is outdated- trailingZeroDisplay: "stripIfInteger",- }- : {- notation: usage < INFINITY_NUMBER ? "standard" : "compact",- }- }- />- ) : (- <div className="h-5 w-16 animate-pulse rounded-md bg-neutral-200" />- )}- </div>- <div className="mt-5">- <div- className={cn(- "h-1 w-full overflow-hidden rounded-full bg-neutral-900/10 transition-colors",- loading && "bg-neutral-900/5",- )}- >- {!loading && !unlimited && (- <div- className="animate-slide-right-fade size-full"- style={{ "--offset": "-100%" } as CSSProperties}+ aria-selected={activeResource === id}+ onClick={() => !requiresUpgrade && queryParams({ set: { tab: id } })}+ disabled={requiresUpgrade}+ >+ <Icon className="size-4 text-neutral-600" />+ <div className="mt-1.5 flex items-center gap-2 text-sm text-neutral-600">+ {title}+ {requiresUpgrade && (+ <Tooltip+ content={+ <div className="max-w-xs px-4 py-2 text-center text-sm text-neutral-600">+ Upgrade to Business to unlock conversion tracking.{" "}+ <Link+ href={`/${slug}/upgrade`}+ className="underline underline-offset-2 hover:text-neutral-800"+ >+ View pricing plans+ </Link>+ </div>+ }>+ <span className="flex items-center gap-1 rounded-full border border-neutral-300 px-2 py-0.5 text-xs text-neutral-500">+ <CrownSmall className="size-4" />+ Business+ </span>+ </Tooltip>+ )}+ </div>+ <div className="mt-2">+ {!loading ? (+ <NumberFlow+ value={usage}+ className="text-xl leading-none text-neutral-900"+ format={+ unit === "$"+ ? {+ style: "currency",+ currency: "USD",+ // @ts-ignore – trailingZeroDisplay is a valid option but TS is outdated+ trailingZeroDisplay: "stripIfInteger",+ }+ : {+ notation:+ usage < INFINITY_NUMBER ? "standard" : "compact",+ }+ }+ />+ ) : (+ <div className="h-5 w-16 animate-pulse rounded-md bg-neutral-200" />+ )}+ </div>+ <div className="mt-5">+ <div+ className={cn(+ "h-1 w-full overflow-hidden rounded-full bg-neutral-900/10 transition-colors",+ loading && "bg-neutral-900/5",+ )}+ >+ {!loading && !unlimited && (<div- className={cn(- "size-full rounded-full",- requiresUpgrade- ? "bg-neutral-900/10"- : "bg-gradient-to-r from-blue-500/80 to-blue-600",- warning && "from-neutral-900/10 via-red-500 to-red-600",- )}- style={{- transform: `translateX(-${100 - Math.max(Math.floor((usage / Math.max(0, usage, limit)) * 100), usage === 0 ? 0 : 1)}%)`,- }}- />- </div>+ className="animate-slide-right-fade size-full"+ style={{ "--offset": "-100%" } as CSSProperties}+ >+ <div+ className={cn(+ "size-full rounded-full",+ requiresUpgrade+ ? "bg-neutral-900/10"+ : "bg-gradient-to-r from-blue-500/80 to-blue-600",+ warning && "from-neutral-900/10 via-red-500 to-red-600",+ )}+ style={{+ transform: `translateX(-${100 - Math.max(Math.floor((usage / Math.max(0, usage, limit)) * 100), usage === 0 ? 0 : 1)}%)`,+ }}+ />+ </div>+ )}+ </div>+ </div>+ <div className="mt-2 leading-none">+ {!loading ? (+ <span className="text-xs leading-none text-neutral-600">+ {unlimited+ ? "Unlimited"+ : `${prefix}${nFormatter(remaining, { full: true })} remaining of ${prefix}${nFormatter(limit, { full: limit < INFINITY_NUMBER })}`}+ </span>+ ) : (+ <div className="h-4 w-20 animate-pulse rounded-md bg-neutral-200" />)}</div>- </div>- <div className="mt-2 leading-none">- {!loading ? (- <span className="text-xs leading-none text-neutral-600">- {unlimited- ? "Unlimited"- : `${prefix}${nFormatter(remaining, { full: true })} remaining of ${prefix}${nFormatter(limit, { full: limit < INFINITY_NUMBER })}`}- </span>- ) : (- <div className="h-4 w-20 animate-pulse rounded-md bg-neutral-200" />- )}- </div>- </button>+ </button>+ {["links", "events"].includes(id) && plan !== "enterprise" && (+ <div className="absolute right-3 top-3">+ <Button+ onClick={() => setShowManageUsageModal(true)}+ text={warning ? "Upgrade" : "Manage"}+ variant={warning ? "primary" : "secondary"}+ className="h-6 px-1.5 text-xs"+ />+ </div>+ )}+ </div>);}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/adjust-usage-row.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/adjust-usage-row.tsxnew file mode 100644index 0000000000..06b4cb953f--- /dev/null+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/adjust-usage-row.tsx@@ -0,0 +1,149 @@+import useWorkspace from "@/lib/swr/use-workspace";+import { Button, Grid, Slider } from "@dub/ui";+import {+ ENTERPRISE_PLAN,+ SELF_SERVE_PAID_PLANS,+ cn,+ getPlanDetails,+} from "@dub/utils";+import NumberFlow from "@number-flow/react";+import { motion } from "motion/react";+import { useSearchParams } from "next/navigation";+import { useEffect, useMemo, useState } from "react";++export function AdjustUsageRow({+ onLinksUsageChange,+ onEventsUsageChange,+}: {+ onLinksUsageChange: (value: number) => void;+ onEventsUsageChange: (value: number) => void;+}) {+ const [isExpanded, setIsExpanded] = useState(false);++ return (+ <div className="relative">+ <motion.div+ initial={false}+ animate={{ height: isExpanded ? "auto" : 0 }}+ transition={{ duration: 0.15, ease: "easeOut" }}+ inert={!isExpanded}+ className={cn(+ "overflow-hidden transition-opacity ease-out",+ isExpanded ? "duration-500" : "opacity-0 duration-150",+ )}+ >+ <div className="grid grid-cols-1 gap-10 p-6 lg:grid-cols-2">+ <UsageSlider type="links" onChange={onLinksUsageChange} />+ <UsageSlider type="events" onChange={onEventsUsageChange} />+ </div>+ </motion.div>+ <div className="relative flex items-center justify-center overflow-hidden rounded-b-[12px] py-2">+ <div className="absolute inset-0 [mask-image:radial-gradient(70%_120%_at_50%_100%,black_50%,transparent)]">+ <Grid+ cellSize={21}+ patternOffset={[-1, 0]}+ className="text-border-subtle"+ />+ </div>++ <Button+ variant="secondary"+ text={isExpanded ? "Close" : "Adjust usage"}+ onClick={() => setIsExpanded((e) => !e)}+ className="relative h-6 w-fit rounded-lg px-1.5 text-xs"+ />+ </div>+ </div>+ );+}++function UsageSlider({+ type,+ onChange,+}: {+ type: "links" | "events";+ onChange: (value: number) => void;+}) {+ const workspace = useWorkspace();++ const limitKey = { events: "clicks" }[type] ?? type;+ const workspaceLimitKey = { events: "usageLimit", links: "linksLimit" }[type];++ const usageSteps = useMemo(+ () => [+ ...new Set(+ [...SELF_SERVE_PAID_PLANS, ENTERPRISE_PLAN]+ .flatMap((p) => [+ p.limits[limitKey],+ ...Object.values(p.tiers ?? {}).map(+ ({ limits }) => limits[limitKey],+ ),+ ])+ .sort((a, b) => a - b),+ ),+ ],+ [limitKey],+ );++ const searchParams = useSearchParams();+ const planParam = searchParams.get("plan");+ const planTierParam = Number(searchParams.get("planTier")) || 1;++ const defaultValue = useMemo(() => {+ // we're not including planParam in the dependency array+ // to allow the slider to update when the plan changes+ if (planParam) {+ const planDetails = getPlanDetails({+ plan: planParam,+ planTier: planTierParam,+ });+ if (planDetails) {+ return planDetails.limits[limitKey];+ }+ }+ const currentLimit = workspace[workspaceLimitKey];+ return usageSteps.reduce((prev, curr) =>+ Math.abs(curr - currentLimit) < Math.abs(prev - currentLimit)+ ? curr+ : prev,+ );+ }, [usageSteps, workspace, workspaceLimitKey]);++ const [selectedValue, setSelectedValue] = useState<number | null>(null);++ useEffect(() => {+ onChange(selectedValue ?? defaultValue);+ }, [selectedValue, defaultValue, onChange]);++ if (usageSteps.length < 2) return null;++ return (+ <div className="flex flex-col">+ <span className="text-content-default text-sm font-medium">+ {+ {+ events: "Events tracked per month",+ links: "Links created per month",+ }[type]+ }+ </span>+ <span className="text-content-emphasis text-lg font-semibold">+ <NumberFlow value={selectedValue ?? defaultValue} />+ {workspace[workspaceLimitKey] === (selectedValue ?? defaultValue) && (+ <span className="animate-fade-in"> (current plan)</span>+ )}+ </span>++ <div className="mt-1">+ <Slider+ value={usageSteps.indexOf(selectedValue ?? defaultValue)}+ min={0}+ max={usageSteps.length - 1}+ onChange={(idx) => setSelectedValue(usageSteps[idx])}+ marks={usageSteps.map((_, idx) => idx)}+ className="[--thumb-radius:10px] [--track-height:14px]"+ />+ </div>+ </div>+ );+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page-client.tsxindex a363653c0a..c5f8a9d5ed 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/upgrade/page-client.tsx@@ -15,13 +15,21 @@ import {ToggleGroup,Users2,} from "@dub/ui";-import { cn, isDowngradePlan, PLAN_COMPARE_FEATURES, PLANS } from "@dub/utils";+import {+ cn,+ getSuggestedPlan,+ isDowngradePlan,+ PLAN_COMPARE_FEATURES,+ PlanDetails,+ PLANS,+} from "@dub/utils";import { isLegacyBusinessPlan } from "@dub/utils/src/constants/pricing";import NumberFlow from "@number-flow/react";import { ChevronLeft, ChevronRight } from "lucide-react";import Link from "next/link";import { useSearchParams } from "next/navigation";-import { CSSProperties, useEffect, useState } from "react";+import { CSSProperties, useEffect, useMemo, useState } from "react";+import { AdjustUsageRow } from "./adjust-usage-row";const COMPARE_FEATURE_ICONS: Record<(typeof PLAN_COMPARE_FEATURES)[number]["category"],@@ -36,12 +44,14 @@ const COMPARE_FEATURE_ICONS: Record<API: Plug2,};-const plans = ["Pro", "Business", "Advanced", "Enterprise"].map(- (p) => PLANS.find(({ name }) => name === p)!,-);-export function WorkspaceBillingUpgradePageClient() {- const { slug, plan: currentPlan, stripeId, payoutsLimit } = useWorkspace();+ const {+ slug,+ plan: currentPlan,+ planTier: currentPlanTier = 1,+ stripeId,+ payoutsLimit,+ } = useWorkspace();const [mobilePlanIndex, setMobilePlanIndex] = useState(0);const [period, setPeriod] = useState<"monthly" | "yearly">("monthly");@@ -58,6 +68,33 @@ export function WorkspaceBillingUpgradePageClient() {}}, [searchParams]);+ const [eventsUsage, setEventsUsage] = useState<number | null>(null);+ const [linksUsage, setLinksUsage] = useState<number | null>(null);++ const recommendedPlan = useMemo(() => {+ if (!eventsUsage || !linksUsage) return null;++ return getSuggestedPlan({+ events: eventsUsage,+ links: linksUsage,+ });+ }, [linksUsage, eventsUsage]);++ const plans: { plan: PlanDetails; planTier: number }[] = useMemo(+ () =>+ ["Pro", "Business", "Advanced", "Enterprise"].map((p) => {+ const planDetails = PLANS.find(({ name }) => name === p)!;+ if (+ recommendedPlan &&+ recommendedPlan.plan.name.toLowerCase() === p.toLowerCase()+ ) {+ return recommendedPlan;+ }+ return { plan: planDetails, planTier: 1 };+ }),+ [recommendedPlan],+ );+return (<div>{partnersUpgradeModal}@@ -81,7 +118,7 @@ export function WorkspaceBillingUpgradePageClient() {{ label: "Yearly (2 months free)", value: "yearly" },]}selected={period}- selectAction={(option) => setPeriod(option as "monthly" | "monthly")}+ selectAction={(option) => setPeriod(option as "monthly" | "yearly")}className="rounded-lg border-neutral-300 bg-neutral-100 p-0.5"optionClassName="text-xs text-neutral-800 data-[selected=true]:text-neutral-800 px-3 sm:px-5 py-2 leading-none"indicatorClassName="bg-white border-neutral-200 rounded-md"@@ -104,15 +141,16 @@ export function WorkspaceBillingUpgradePageClient() {} as CSSProperties}>- {plans.map((plan, idx) => {+ {plans.map(({ plan, planTier }, idx) => {// disable upgrade button if user has a Stripe ID and is on the current plan// (if there's no stripe id, they could be on a free trial so they should be able to upgrade)// edge case:// if the user is on the business plan and has a payout limit of 0,- // it means they're on the legacy business plan – prompt them to upgrade to the new business plan+ // it means they're on the legacy business plan – prompt them to upgrade to the new business planconst disableCurrentPlan = Boolean(stripeId &&plan.name.toLowerCase() === currentPlan &&+ planTier === currentPlanTier &&!isLegacyBusinessPlan({plan: currentPlan,payoutsLimit,@@ -121,23 +159,40 @@ export function WorkspaceBillingUpgradePageClient() {// show downgrade button if user has a stripe id and is on the current planconst isDowngrade = Boolean(- stripeId && isDowngradePlan(currentPlan || "free", plan.name),+ stripeId &&+ isDowngradePlan({+ currentPlan: currentPlan || "free",+ currentTier: currentPlanTier,+ newPlan: plan.name,+ newTier: planTier,+ }),);return (<divkey={plan.name}className={cn(- "relative top-0 flex h-full flex-col gap-6 bg-white p-5",+ "relative top-0 flex h-full flex-col gap-6 bg-white p-5 lg:p-3 xl:p-5","max-lg:rounded-xl max-lg:border max-lg:border-neutral-200",idx !== mobilePlanIndex && "max-lg:opacity-0",)}><div>- <h3 className="py-1 text-base font-semibold leading-none text-neutral-800">- {plan.name}- </h3>+ <div className="flex items-start justify-between gap-2">+ <h3 className="py-1 text-base font-semibold leading-none text-neutral-800">+ {plan.name}+ </h3>+ {recommendedPlan &&+ !isDowngrade &&+ plan.name === recommendedPlan.plan.name &&+ planTier === recommendedPlan.planTier &&+ !disableCurrentPlan && (+ <div className="animate-fade-in flex h-6 min-w-0 items-center rounded-lg border border-blue-100 bg-blue-50 px-1.5 text-xs font-medium text-blue-600">+ <span className="truncate">Recommended</span>+ </div>+ )}+ </div><div className="relative mt-0.5 flex items-center gap-1">{plan.name === "Enterprise" ? (<span className="text-sm font-medium text-neutral-900">@@ -172,7 +227,7 @@ export function WorkspaceBillingUpgradePageClient() {><ChevronLeft className="size-5 text-neutral-800" /></button>- {plan.name === "Enterprise" ? (+ {plan.name === "Enterprise" && !disableCurrentPlan ? (<Linkhref="https://dub.co/contact/sales"target="_blank"@@ -181,21 +236,24 @@ export function WorkspaceBillingUpgradePageClient() {"border border-neutral-200 bg-white text-neutral-900 shadow-sm hover:bg-neutral-50",)}>- {plan.name === "Enterprise"- ? "Contact us"- : "Get started"}+ Contact us</Link>) : (<UpgradePlanButtonplan={plan.name.toLowerCase()}+ tier={planTier > 1 ? planTier : undefined}period={period}- disabled={disableCurrentPlan}+ disabled={+ disableCurrentPlan || currentPlan === "enterprise"+ }text={- disableCurrentPlan- ? "Current plan"- : isDowngrade- ? "Downgrade"- : "Upgrade"+ currentPlan === "enterprise"+ ? "Contact support"+ : disableCurrentPlan+ ? "Current plan"+ : isDowngrade+ ? "Downgrade"+ : "Upgrade"}variant={isDowngrade ? "secondary" : "primary"}className="h-8 shadow-sm"@@ -215,6 +273,16 @@ export function WorkspaceBillingUpgradePageClient() {})}</div></div>++ <div className="relative -z-10 bg-white">+ <div className="bg-bg-muted border-subtle absolute inset-x-0 -top-2.5 bottom-0 rounded-b-[12px] border" />++ <AdjustUsageRow+ onLinksUsageChange={(value) => setLinksUsage(value)}+ onEventsUsageChange={(value) => setEventsUsage(value)}+ />+ </div>+<div className="h-8 bg-gradient-to-b from-white" /></div><div className="flex flex-col gap-8 pb-12">@@ -252,8 +320,8 @@ export function WorkspaceBillingUpgradePageClient() {><thead className="sr-only"><tr>- {plans.map(({ name }) => (- <th key={name}>{name}</th>+ {plans.map(({ plan }) => (+ <th key={plan.name}>{plan.name}</th>))}</tr></thead>@@ -263,7 +331,7 @@ export function WorkspaceBillingUpgradePageClient() {return (<tr key={idx} className="contents bg-white">- {plans.map((plan) => {+ {plans.map(({ plan }) => {const id = plan.name.toLowerCase();const isChecked =typeof check === "boolean"diff --git a/apps/web/lib/zod/schemas/workspaces.ts b/apps/web/lib/zod/schemas/workspaces.tsindex 46f4ba466c..fdc45aba07 100644--- a/apps/web/lib/zod/schemas/workspaces.ts+++ b/apps/web/lib/zod/schemas/workspaces.ts@@ -28,6 +28,10 @@ export const WorkspaceSchema = z.describe("The invite code of the workspace."),plan: planSchema,+ planTier: z+ .number()+ .nullable()+ .describe("The tier of the workspace's plan."),stripeId: z.string().nullable().describe("The Stripe ID of the workspace."),billingCycleStart: z.number()diff --git a/apps/web/ui/modals/manage-usage-modal.tsx b/apps/web/ui/modals/manage-usage-modal.tsxnew file mode 100644index 0000000000..ec39b42922--- /dev/null+++ b/apps/web/ui/modals/manage-usage-modal.tsx@@ -0,0 +1,286 @@+import useWorkspace from "@/lib/swr/use-workspace";+import { CursorRays, Hyperlink, Modal, Slider, ToggleGroup } from "@dub/ui";+import {+ ENTERPRISE_PLAN,+ SELF_SERVE_PAID_PLANS,+ cn,+ getSuggestedPlan,+ isDowngradePlan,+} from "@dub/utils";+import NumberFlow from "@number-flow/react";+import Link from "next/link";+import {+ Dispatch,+ SetStateAction,+ useCallback,+ useMemo,+ useState,+} from "react";+import { UpgradePlanButton } from "../workspaces/upgrade-plan-button";++type ManageUsageModalProps = {+ type: "links" | "events";+ showManageUsageModal: boolean;+ setShowManageUsageModal: Dispatch<SetStateAction<boolean>>;+};++function ManageUsageModalContent({ type }: ManageUsageModalProps) {+ const workspace = useWorkspace();+ const { slug, plan, planTier, usageLimit, linksLimit } = workspace;++ const usageSteps = useMemo(() => {+ const limitKey = { events: "clicks" }[type] ?? type;++ return [+ ...new Set(+ [...SELF_SERVE_PAID_PLANS, ENTERPRISE_PLAN]+ .flatMap((p) => [+ p.limits[limitKey],+ ...Object.values(p.tiers ?? {}).map(+ ({ limits }) => limits[limitKey],+ ),+ ])+ .sort((a, b) => a - b),+ ),+ ];+ }, [type]);++ const defaultValue = useMemo(() => {+ const currentLimit =+ workspace[{ events: "usageLimit", links: "linksLimit" }[type]];+ return usageSteps.reduce((prev, curr) =>+ Math.abs(curr - currentLimit) < Math.abs(prev - currentLimit)+ ? curr+ : prev,+ );+ }, [usageSteps, workspace]);++ const [selectedValue, setSelectedValue] = useState<number | null>(null);+ const [period, setPeriod] = useState<"monthly" | "yearly">("monthly");++ const { plan: suggestedPlan, planTier: suggestedPlanTier } = getSuggestedPlan(+ {+ [type]: selectedValue ?? defaultValue,+ },+ );++ const isCurrentPlanSuggested =+ plan === suggestedPlan.name.toLowerCase() &&+ suggestedPlanTier === (planTier ?? 1);++ const isDowngradeSuggested =+ plan &&+ isDowngradePlan({+ currentPlan: plan,+ newPlan: suggestedPlan.name,+ currentTier: planTier ?? 1,+ newTier: suggestedPlanTier,+ });++ if (usageSteps.length < 2) return null;++ return (+ <div className="bg-neutral-50">+ <div className="border-b border-neutral-200 bg-white px-5 py-6">+ <h3 className="text-lg font-medium leading-none">Manage {type}</h3>+ </div>++ <div className="px-5 py-6">+ <p className="text-content-default text-sm font-medium">+ {+ {+ events: "Events tracked per month",+ links: "Links created per month",+ }[type]+ }+ </p>+ <NumberFlow+ value={selectedValue ?? defaultValue}+ className="text-content-emphasis mb-4 text-lg font-semibold"+ />++ <Slider+ value={usageSteps.indexOf(selectedValue ?? defaultValue)}+ min={0}+ max={usageSteps.length - 1}+ onChange={(idx) => setSelectedValue(usageSteps[idx])}+ marks={usageSteps.map((_, idx) => idx)}+ />++ <div className="mt-6">+ <ToggleGroup+ options={[+ { value: "monthly", label: "Monthly" },+ {+ value: "yearly",+ label: "Yearly (2 months free)",+ },+ ]}+ className="flex overflow-hidden rounded-lg bg-transparent p-0.5"+ indicatorClassName="rounded-md bg-white shadow-md"+ optionClassName="text-xs py-2 px-5 normal-case grow justify-center text-center"+ selected={period}+ selectAction={(period) => setPeriod(period as "monthly" | "yearly")}+ />++ <div className="border-border-subtle bg-bg-default mt-3 flex flex-col gap-5 rounded-xl border p-4 shadow-sm">+ <div>+ <span className="text-content-emphasis block text-xl font-semibold">+ {suggestedPlan.name}+ </span>+ <div className="relative flex items-center gap-1">+ {!suggestedPlan.price[period] ? (+ <span className="pb-px text-sm font-medium text-neutral-900">+ Custom+ </span>+ ) : (+ <>+ <NumberFlow+ value={suggestedPlan.price[period]!}+ className="text-sm font-medium tabular-nums text-neutral-700"+ format={{+ style: "currency",+ currency: "USD",+ minimumFractionDigits: 0,+ }}+ continuous+ />+ <span className="text-sm font-medium text-neutral-400">+ per month+ {period === "yearly" && ", billed yearly"}+ </span>+ </>+ )}+ </div>+ </div>++ {suggestedPlan.name === "Enterprise" ? (+ <Link+ href="https://dub.co/contact/sales"+ target="_blank"+ className={cn(+ "flex h-8 w-full items-center justify-center rounded-lg text-center text-sm transition-all duration-200 ease-in-out",+ "hover:ring-border-subtle border border-black bg-black text-white shadow-sm hover:ring-4",+ )}+ >+ Contact us+ </Link>+ ) : (+ <UpgradePlanButton+ plan={suggestedPlan.name.toLowerCase()}+ tier={suggestedPlanTier}+ period={period}+ disabled={isCurrentPlanSuggested}+ text={+ isCurrentPlanSuggested+ ? "Current plan"+ : isDowngradeSuggested+ ? "Downgrade"+ : "Upgrade"+ }+ variant={isDowngradeSuggested ? "secondary" : "primary"}+ className="h-8 rounded-lg shadow-sm"+ />+ )}++ <div className="flex flex-col gap-2.5">+ {[+ {+ icon: CursorRays,+ value: suggestedPlan.limits.clicks,+ label: `total tracked events/mo`,+ difference: suggestedPlan.limits.clicks - (usageLimit ?? 0),+ },+ {+ icon: Hyperlink,+ value: suggestedPlan.limits.links,+ label: `new links/mo`,+ difference: suggestedPlan.limits.links - (linksLimit ?? 0),+ },+ ].map(({ icon: Icon, value, label, difference }) => (+ <div+ key={label}+ className="text-content-default flex items-center gap-2 text-sm"+ >+ <Icon+ className={cn("size-4", difference > 0 && "text-blue-600")}+ />+ <span>+ <NumberFlow+ value={value}+ className="tabular-nums"+ format={{+ notation: "compact",+ }}+ continuous+ />{" "}+ {label}+ </span>+ {difference !== 0 && (+ <span+ className={cn(+ "flex h-[18px] items-center rounded-full px-1.5 text-[0.5rem] font-semibold uppercase leading-none",+ difference > 0+ ? "bg-blue-100 text-blue-600"+ : "text-content-default bg-bg-subtle",+ )}+ >+ {difference > 0 ? "Increases" : "Decreases"}+ </span>+ )}+ </div>+ ))}+ </div>+ </div>++ <div className="mt-4 flex justify-center">+ <Link+ href={`/${slug}/settings/billing/upgrade`}+ className="text-content-subtle hover:text-content-default block text-xs font-medium underline underline-offset-2"+ >+ View all plans+ </Link>+ </div>+ </div>+ </div>+ </div>+ );+}++function ManageUsageModal(props: ManageUsageModalProps) {+ return (+ <Modal+ showModal={props.showManageUsageModal}+ setShowModal={props.setShowManageUsageModal}+ >+ <ManageUsageModalContent {...props} />+ </Modal>+ );+}++export function useManageUsageModal(+ props: Omit<+ ManageUsageModalProps,+ "showManageUsageModal" | "setShowManageUsageModal"+ >,+) {+ const [showManageUsageModal, setShowManageUsageModal] = useState(false);++ const ManageUsageModalCallback = useCallback(() => {+ return (+ <ManageUsageModal+ showManageUsageModal={showManageUsageModal}+ setShowManageUsageModal={setShowManageUsageModal}+ {...props}+ />+ );+ }, [showManageUsageModal, setShowManageUsageModal]);++ return useMemo(+ () => ({+ setShowManageUsageModal,+ ManageUsageModal: ManageUsageModalCallback,+ }),+ [setShowManageUsageModal, ManageUsageModalCallback],+ );+}diff --git a/apps/web/ui/modals/upgraded-modal.tsx b/apps/web/ui/modals/upgraded-modal.tsxindex cf341d89bf..c46d29cf35 100644--- a/apps/web/ui/modals/upgraded-modal.tsx+++ b/apps/web/ui/modals/upgraded-modal.tsx@@ -39,7 +39,7 @@ function UpgradedModal({const handlePlanUpgrade = async () => {if (planId) {- const currentPlan = getPlanDetails(planId);+ const currentPlan = getPlanDetails({ plan: planId });const period = searchParams.get("period");if (currentPlan && period) {plausible(`Upgraded to ${currentPlan.name}`);diff --git a/apps/web/ui/modals/welcome-modal.tsx b/apps/web/ui/modals/welcome-modal.tsxindex 8bc71b4ef8..cf88c63400 100644--- a/apps/web/ui/modals/welcome-modal.tsx+++ b/apps/web/ui/modals/welcome-modal.tsx@@ -33,7 +33,7 @@ function WelcomeModal({const handlePlanUpgrade = async () => {if (planId) {- const currentPlan = getPlanDetails(planId);+ const currentPlan = getPlanDetails({ plan: planId });const period = searchParams.get("period");if (currentPlan && period) {plausible(`Upgraded to ${currentPlan.name}`);diff --git a/apps/web/ui/workspaces/upgrade-plan-button.tsx b/apps/web/ui/workspaces/upgrade-plan-button.tsxindex 85b5d01bd7..deda8cda49 100644--- a/apps/web/ui/workspaces/upgrade-plan-button.tsx+++ b/apps/web/ui/workspaces/upgrade-plan-button.tsx@@ -11,10 +11,12 @@ import { useState } from "react";export function UpgradePlanButton({plan,+ tier,period,...rest}: {plan: string;+ tier?: number;period: "monthly" | "yearly";} & Partial<ButtonProps>) {const router = useRouter();@@ -55,9 +57,10 @@ export function UpgradePlanButton({},body: JSON.stringify({plan,+ tier,period,baseUrl: `${APP_DOMAIN}${pathname}${queryString.length > 0 ? `?${queryString}` : ""}`,- onboarding: searchParams.get("workspace"),+ onboarding: searchParams.get("workspace") ? "true" : "false",}),}).then(async (res) => {diff --git a/packages/email/src/templates/clicks-exceeded.tsx b/packages/email/src/templates/clicks-exceeded.tsxindex 237ee6b3ab..03607197a2 100644--- a/packages/email/src/templates/clicks-exceeded.tsx+++ b/packages/email/src/templates/clicks-exceeded.tsx@@ -1,4 +1,4 @@-import { DUB_WORDMARK, capitalize, getNextPlan, nFormatter } from "@dub/utils";+import { APP_DOMAIN, DUB_WORDMARK, capitalize, nFormatter } from "@dub/utils";import {Body,Container,@@ -32,7 +32,6 @@ export default function ClicksExceeded({type: "firstUsageLimitEmail" | "secondUsageLimitEmail";}) {const { slug, name, usage, usageLimit, plan } = workspace;- const nextPlan = getNextPlan(plan as string);return (<Html>@@ -69,19 +68,19 @@ export default function ClicksExceeded({</Text><Text className="text-sm leading-6 text-black">All your existing links will continue to work, and we are still- collecting data on them, but you'll need to upgrade to the{" "}+ collecting data on them, but you'll need to{" "}<Link- href={nextPlan.link}+ href={`${APP_DOMAIN}/${slug}/settings/billing`}className="font-medium text-blue-600 no-underline">- {nextPlan.name} plan+ upgrade to a higher plan</Link>{" "}to view their stats.</Text><Section className="my-8"><LinkclassName="rounded-lg bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"- href={`https://app.dub.co/${slug}/upgrade`}+ href={`${APP_DOMAIN}/${slug}/settings/billing`}>Upgrade my plan</Link>diff --git a/packages/email/src/templates/links-limit.tsx b/packages/email/src/templates/links-limit.tsxindex cfc9d2b1af..8f9e6633a9 100644--- a/packages/email/src/templates/links-limit.tsx+++ b/packages/email/src/templates/links-limit.tsx@@ -1,4 +1,4 @@-import { DUB_WORDMARK, capitalize, getNextPlan, nFormatter } from "@dub/utils";+import { APP_DOMAIN, DUB_WORDMARK, capitalize, nFormatter } from "@dub/utils";import {Body,Container,@@ -37,7 +37,6 @@ export default function LinksLimitAlert({plan: string;};const percentage = Math.round((linksUsage / linksLimit) * 100);- const nextPlan = getNextPlan(plan as string);return (<Html>@@ -82,23 +81,23 @@ export default function LinksLimitAlert({) : percentage === 100 ? (<Text className="text-sm leading-6 text-black">All your existing links will continue to work, and we are still- collecting data on them, but you'll need to upgrade the{" "}+ collecting data on them, but you'll need to{" "}<Link- href={nextPlan.link}+ href={`${APP_DOMAIN}/${slug}/settings/billing`}className="font-medium text-blue-600 no-underline">- {nextPlan.name} plan+ upgrade to a higher plan</Link>{" "}- add more links.+ to add more links.</Text>) : (<Text className="text-sm leading-6 text-black">- Once you hit your limit, you'll need to upgrade to the{" "}+ Once you hit your limit, you'll need to{" "}<Link- href={nextPlan.link}+ href={`${APP_DOMAIN}/${slug}/settings/billing`}className="font-medium text-blue-600 no-underline">- {nextPlan.name} plan+ upgrade to a higher plan</Link>{" "}to add more links.</Text>@@ -106,7 +105,7 @@ export default function LinksLimitAlert({<Section className="mb-8"><LinkclassName="rounded-lg bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"- href={`https://app.dub.co/${slug}/upgrade`}+ href={`${APP_DOMAIN}/${slug}/settings/billing`}>Upgrade my plan</Link>diff --git a/packages/email/src/templates/upgrade-email.tsx b/packages/email/src/templates/upgrade-email.tsxindex eabafb31b1..462261e9ed 100644--- a/packages/email/src/templates/upgrade-email.tsx+++ b/packages/email/src/templates/upgrade-email.tsx@@ -18,12 +18,14 @@ export default function UpgradeEmail({name = "Brendon Urie",email = "[email protected]",plan = "Business",+ planTier = 1,}: {name: string | null;email: string;plan: string;+ planTier: number;}) {- const planDetails = getPlanDetails(plan);+ const planDetails = getPlanDetails({ plan, planTier });return (<Html><Head />diff --git a/packages/prisma/schema/workspace.prisma b/packages/prisma/schema/workspace.prismaindex 93273a19e2..9930478c3a 100644--- a/packages/prisma/schema/workspace.prisma+++ b/packages/prisma/schema/workspace.prisma@@ -7,6 +7,7 @@ model Project {defaultProgramId String? @unique // default affiliate program ID for the workspaceplan String @default("free")+ planTier Int @default(1)stripeId String? @unique // Stripe subscription IDbillingCycleStart Int // day of the month when the billing cycle startspaymentFailedAt DateTime?diff --git a/packages/ui/src/icons/plan-feature-icons.tsx b/packages/ui/src/icons/plan-feature-icons.tsxindex 3439fcfe9c..8941931b98 100644--- a/packages/ui/src/icons/plan-feature-icons.tsx+++ b/packages/ui/src/icons/plan-feature-icons.tsx@@ -3,6 +3,7 @@ import {Calendar6,ChartLine,CirclePercentage,+ ConnectedDots4,CursorRays,Flask,Folder,@@ -65,6 +66,6 @@ export const PLAN_FEATURE_ICONS = {flexiblerewards: Shuffle,ailandingpage: Sparkle3,customerinsights: UserFocus,- partners: Users2,+ partners: ConnectedDots4,embeddedreferrals: SquareLayoutGrid5,};diff --git a/packages/ui/src/slider.tsx b/packages/ui/src/slider.tsxindex 73d5bbfcec..a6a5802a80 100644--- a/packages/ui/src/slider.tsx+++ b/packages/ui/src/slider.tsx@@ -35,10 +35,15 @@ export function Slider({];return (- <div className={cn("relative z-0", className)}>+ <div+ className={cn(+ "relative z-0 [--thumb-radius:13px] [--track-height:16px]",+ className,+ )}+ ><div className="w-full"><RadixSlider.Root- className="relative flex h-8 w-full items-center [--thumb-radius:13px]"+ className="relative flex h-8 w-full items-center"value={[value]}min={min}max={max}@@ -47,12 +52,12 @@ export function Slider({disabled={disabled}aria-label="Slider">- <RadixSlider.Track className="relative h-4 w-full overflow-visible rounded-full bg-neutral-200">+ <RadixSlider.Track className="relative h-[var(--track-height)] w-full overflow-visible rounded-full bg-neutral-200">{/* Start of filled track (since actual filled track is inset by the thumb radius) */}<div className="absolute left-0 top-0 h-full w-[var(--thumb-radius)] rounded-l-full bg-black" /><div className="pointer-events-none absolute inset-x-[var(--thumb-radius)] inset-y-0">- <RadixSlider.Range className="absolute h-4 bg-black" />+ <RadixSlider.Range className="absolute h-[var(--track-height)] bg-black" />{sliderMarks.map((mark) => {const left = ((mark - min) / (max - min)) * 100;@@ -69,7 +74,7 @@ export function Slider({</RadixSlider.Track><RadixSlider.Thumb className="z-20 flex size-[calc(var(--thumb-radius)*2)] items-center justify-center rounded-full border-0 bg-white shadow-[0_2px_2px_rgba(0,0,0,0.10),0_3px_3px_rgba(0,0,0,0.09)]">- <span className="block size-4 rounded-full bg-[#171717]" />+ <span className="block size-[calc(var(--thumb-radius)*1.23)] rounded-full bg-[#171717]" /></RadixSlider.Thumb></RadixSlider.Root>diff --git a/packages/utils/src/constants/pricing.tsx b/packages/utils/src/constants/pricing.tsxindex c97fee0f98..f9d548c850 100644--- a/packages/utils/src/constants/pricing.tsx+++ b/packages/utils/src/constants/pricing.tsx@@ -1,3 +1,4 @@+import { nFormatter } from "../functions";import { INFINITY_NUMBER } from "./misc";export type PlanFeature = {@@ -10,6 +11,44 @@ export type PlanFeature = {};};+export type PlanDetails = {+ name: string;+ price: {+ monthly: number | null;+ yearly: number | null;+ ids?: string[];+ };+ limits: {+ links: number;+ clicks: number;+ payouts: number;+ domains: number;+ tags: number;+ folders: number;+ groups: number;+ networkInvites: number;+ users: number;+ ai: number;+ api: number;+ retention: string;+ };+ tiers?: {+ [key: number]: {+ price: {+ monthly: number | null;+ yearly: number | null;+ ids: string[];+ };+ limits: {+ links: number;+ clicks: number;+ };+ };+ };+ featureTitle?: string;+ features?: PlanFeature[];+};+const LEGACY_PRO_PRICE_IDS = ["price_1LodNLAlJJEpqkPVQSrt33Lc", // old monthly"price_1LodNLAlJJEpqkPVRxUyCQgZ", // old yearly@@ -19,12 +58,22 @@ const LEGACY_PRO_PRICE_IDS = ["price_1OYJeBAlJJEpqkPVnPGEZeb0", // new yearly (prod)];+const PRO_TIER_PRICE_IDS = {+ 2: [+ "price_1SQtg3AlJJEpqkPVVhDSyd9u", // yearly (prod)+ "price_1SQtg3AlJJEpqkPVNHYhTRy7", // monthly (prod)+ "price_1SQ8hiAlJJEpqkPVIy8pfvAC", // yearly (test)+ "price_1SQ8gwAlJJEpqkPVb78Oc9Yc", // monthly (test)+ ],+};+// 2025 pricingconst NEW_PRO_PRICE_IDS = ["price_1R8XtyAlJJEpqkPV5WZ4c0jF", // yearly"price_1R8XtEAlJJEpqkPV4opVvVPq", // monthly"price_1R8XxZAlJJEpqkPVqGi0wOqD", // yearly (test),"price_1R7oeBAlJJEpqkPVh6q5q3h8", // monthly (test),+ ...Object.values(PRO_TIER_PRICE_IDS).flat(),];const LEGACY_BUSINESS_PRICE_IDS = [@@ -37,15 +86,48 @@ const LEGACY_BUSINESS_PRICE_IDS = ["price_1OzOXMAlJJEpqkPV9ERrjjbw", // new yearly (prod)];+const BUSINESS_TIER_PRICE_IDS = {+ 2: [+ "price_1SQtdxAlJJEpqkPV4kNkRHZr", // yearly (prod)+ "price_1SQtdxAlJJEpqkPV7cvJTv4g", // monthly (prod)+ "price_1SQ8iwAlJJEpqkPVEGmKd6Lg", // yearly (test)+ "price_1SQ8iSAlJJEpqkPVQ5crmBtF", // monthly (test)+ ],+};+// 2025 pricingexport const NEW_BUSINESS_PRICE_IDS = ["price_1R3j01AlJJEpqkPVXuG1eNzm", // yearly"price_1R6JedAlJJEpqkPVMUkfjch4", // monthly"price_1R8XypAlJJEpqkPVdjzOcYUC", // yearly (test),"price_1R7ofLAlJJEpqkPV3MlgDpyx", // monthly (test),+ ...Object.values(BUSINESS_TIER_PRICE_IDS).flat(),];-export const PLANS = [+const ADVANCED_TIER_PRICE_IDS = {+ 2: [+ "price_1SQtg6AlJJEpqkPVAJdrStq7", // yearly (prod)+ "price_1SQtg6AlJJEpqkPVaZNisQdm", // monthly (prod)+ "price_1SQ8jlAlJJEpqkPV6EanvSXl", // yearly (test)+ "price_1SQ8jJAlJJEpqkPVIwY9QZSP", // monthly (test)+ ],+ 3: [+ "price_1SQtg8AlJJEpqkPVvQVU7uQ3", // yearly (prod)+ "price_1SQtg8AlJJEpqkPV4Nks8MkS", // monthly (prod)+ "price_1SQ8lqAlJJEpqkPVzBaioV3I", // yearly (test)+ "price_1SQ8lOAlJJEpqkPVz2R8SRss", // monthly (test)+ ],+};++const ADVANCED_PRICE_IDS = [+ "price_1R8Xw4AlJJEpqkPV6nwdink9", // yearly+ "price_1R3j0qAlJJEpqkPVkfGNXRwb", // monthly+ "price_1R8XztAlJJEpqkPVnHmIU2tf", // yearly (test),+ "price_1R7ofzAlJJEpqkPV0L2TwyJo", // monthly (test),+ ...Object.values(ADVANCED_TIER_PRICE_IDS).flat(),+];++export const PLANS: PlanDetails[] = [{name: "Free",price: {@@ -69,7 +151,6 @@ export const PLANS = [},{name: "Pro",- link: "https://dub.co/help/article/pro-plan",price: {monthly: 30,yearly: 25,@@ -89,6 +170,19 @@ export const PLANS = [api: 600,retention: "1-year",},+ tiers: {+ 2: {+ price: {+ monthly: 60,+ yearly: 50,+ ids: PRO_TIER_PRICE_IDS[2],+ },+ limits: {+ links: 5_000,+ clicks: 150_000,+ },+ },+ },featureTitle: "Everything in Free, plus:",features: [{ id: "clicks", text: "50K tracked clicks/mo" },@@ -164,6 +258,19 @@ export const PLANS = [api: 1_200,retention: "3-year",},+ tiers: {+ 2: {+ price: {+ monthly: 180,+ yearly: 150,+ ids: BUSINESS_TIER_PRICE_IDS[2],+ },+ limits: {+ links: 25_000,+ clicks: 500_000,+ },+ },+ },featureTitle: "Everything in Pro, plus:",features: [{@@ -192,19 +299,9 @@ export const PLANS = [id: "users",text: "10 users",},- {- id: "events",- text: "Real-time events stream",- tooltip: {- title:- "Get more data on your link clicks and QR code scans with a detailed, real-time stream of events in your workspace",- cta: "Learn more.",- href: "https://dub.co/help/article/real-time-events-stream",- },- },{id: "partners",- text: "Partner management",+ text: "Dub Partners",tooltip: {title: "Use Dub Partners to manage and pay out your affiliates.",cta: "Learn more.",@@ -212,11 +309,7 @@ export const PLANS = [},},{- id: "tests",- text: "A/B testing",- },- {- id: "roles",+ id: "customerinsights",text: "Customer insights",tooltip: {title:@@ -225,6 +318,16 @@ export const PLANS = [href: "https://dub.co/help/article/customer-insights",},},+ {+ id: "events",+ text: "Real-time events stream",+ tooltip: {+ title:+ "Get more data on your link clicks and QR code scans with a detailed, real-time stream of events in your workspace",+ cta: "Learn more.",+ href: "https://dub.co/help/article/real-time-events-stream",+ },+ },{id: "webhooks",text: "Event webhooks",@@ -235,6 +338,10 @@ export const PLANS = [href: "https://dub.co/docs/concepts/webhooks/introduction",},},+ {+ id: "tests",+ text: "A/B testing",+ },] as PlanFeature[],},{@@ -242,12 +349,7 @@ export const PLANS = [price: {monthly: 300,yearly: 250,- ids: [- "price_1R8Xw4AlJJEpqkPV6nwdink9", // yearly- "price_1R3j0qAlJJEpqkPVkfGNXRwb", // monthly- "price_1R8XztAlJJEpqkPVnHmIU2tf", // yearly (test),- "price_1R7ofzAlJJEpqkPV0L2TwyJo", // monthly (test),- ],+ ids: ADVANCED_PRICE_IDS,},limits: {links: 50_000,@@ -263,6 +365,30 @@ export const PLANS = [api: 3_000,retention: "5-year",},+ tiers: {+ 2: {+ price: {+ monthly: 600,+ yearly: 500,+ ids: ADVANCED_TIER_PRICE_IDS[2],+ },+ limits: {+ links: 150_000,+ clicks: 2_000_000,+ },+ },+ 3: {+ price: {+ monthly: 900,+ yearly: 750,+ ids: ADVANCED_TIER_PRICE_IDS[3],+ },+ limits: {+ links: 300_000,+ clicks: 3_500_000,+ },+ },+ },featureTitle: "Everything in Business, plus:",features: [{@@ -320,13 +446,13 @@ export const PLANS = [},},{- id: "api",- text: "Partners API",+ id: "email",+ text: "Email campaigns",tooltip: {title:- "Leverage our partners API to build a bespoke, white-labeled referral program that lives within your app.",+ "Send marketing and transactional emails to your partners to increase engagement and drive conversions.",cta: "Learn more.",- href: "https://dub.co/docs/api-reference/endpoint/create-a-partner",+ href: "https://dub.co/help/article/email-campaigns",},},{@@ -362,6 +488,9 @@ export const FREE_PLAN = PLANS.find((plan) => plan.name === "Free")!;export const PRO_PLAN = PLANS.find((plan) => plan.name === "Pro")!;export const BUSINESS_PLAN = PLANS.find((plan) => plan.name === "Business")!;export const ADVANCED_PLAN = PLANS.find((plan) => plan.name === "Advanced")!;+export const ENTERPRISE_PLAN = PLANS.find(+ (plan) => plan.name === "Enterprise",+)!;export const SELF_SERVE_PAID_PLANS = PLANS.filter((p) =>["Pro", "Business", "Advanced"].includes(p.name),@@ -369,14 +498,70 @@ export const SELF_SERVE_PAID_PLANS = PLANS.filter((p) =>export const FREE_WORKSPACES_LIMIT = 2;-export const getPlanFromPriceId = (priceId: string) => {- return PLANS.find((plan) => plan.price.ids?.includes(priceId)) || null;+const enrichPlanWithTierData = (+ planDetails: PlanDetails,+ planTier: number,+): PlanDetails => {+ const tierData =+ planDetails.tiers && planTier > 1 ? planDetails.tiers[planTier] : undefined;+ const tierLimits = tierData?.limits ?? planDetails.limits;++ return {+ ...planDetails,+ limits: {+ ...planDetails.limits,+ ...tierLimits,+ },+ price: {+ ...planDetails.price,+ ...tierData?.price,+ },+ features: planDetails.features?.map((feature) => ({+ ...feature,+ text:+ feature.id === "clicks"+ ? `${nFormatter(tierLimits.clicks)} tracked clicks/mo`+ : feature.id === "links"+ ? `${nFormatter(tierLimits.links)} new links/mo`+ : feature.text,+ })),+ };+};++export const getPlanAndTierFromPriceId = ({+ priceId,+}: {+ priceId: string;+}): { plan: PlanDetails | null; planTier: number } => {+ const planDetails = PLANS.find((plan) => plan.price.ids?.includes(priceId));+ if (!planDetails) return { plan: null, planTier: 1 };++ const planTier = planDetails.tiers+ ? Number(+ Object.entries(planDetails.tiers).find(([_, { price }]) =>+ price.ids.includes(priceId),+ )?.[0],+ ) || 1+ : 1;++ return {+ plan: enrichPlanWithTierData(planDetails, planTier),+ planTier,+ };};-export const getPlanDetails = (plan: string) => {- return SELF_SERVE_PAID_PLANS.find(+export const getPlanDetails = ({+ plan,+ planTier = 1,+}: {+ plan: string;+ planTier?: number;+}) => {+ const planDetails = PLANS.find((p) => p.name.toLowerCase() === plan.toLowerCase(),)!;++ return enrichPlanWithTierData(planDetails, planTier);};export const getCurrentPlan = (plan: string) => {@@ -397,14 +582,65 @@ export const getNextPlan = (plan?: string | null) => {];};-export const isDowngradePlan = (currentPlan: string, newPlan: string) => {+export const isDowngradePlan = ({+ currentPlan,+ newPlan,+ currentTier,+ newTier,+}: {+ currentPlan: string;+ newPlan: string;+ currentTier?: number;+ newTier?: number;+}) => {const currentPlanIndex = PLANS.findIndex((p) => p.name.toLowerCase() === currentPlan.toLowerCase(),);const newPlanIndex = PLANS.findIndex((p) => p.name.toLowerCase() === newPlan.toLowerCase(),);- return currentPlanIndex > newPlanIndex;+ return (+ currentPlanIndex > newPlanIndex ||+ (currentPlanIndex === newPlanIndex && (currentTier ?? 1) > (newTier ?? 1))+ );+};++export const getSuggestedPlan = ({+ events,+ links,+ suggestFree = false,+}: {+ events?: number;+ links?: number;+ suggestFree?: boolean;+}): { plan: PlanDetails; planTier: number } => {+ let match: { plan: PlanDetails; planTier: number } | null = null;++ for (const p of PLANS) {+ if (!suggestFree && p.price.monthly === 0) continue;++ const matchingTier = [+ 1,+ ...Object.keys(p.tiers ?? {})+ .map(Number)+ .filter((tier) => tier >= 2),+ ].find((tier) => {+ const limits =+ tier === 1 ? p.limits : p.tiers?.[tier]?.limits ?? p.limits;+ return limits.clicks >= (events ?? 0) && limits.links >= (links ?? 0);+ });++ if (matchingTier !== undefined) {+ match = {+ plan: enrichPlanWithTierData(p, matchingTier),+ planTier: matchingTier,+ };++ break;+ }+ }++ return match ?? { plan: ENTERPRISE_PLAN, planTier: 1 };};export const isLegacyBusinessPlan = ({