Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

add linksUsage & linksLimit

Steven Tey0739e651693a
diff --git a/apps/web/app/api/callback/stripe/route.ts b/apps/web/app/api/callback/stripe/route.ts
index 89e037d047..0d2a9a3aec 100644
--- a/apps/web/app/api/callback/stripe/route.ts
+++ b/apps/web/app/api/callback/stripe/route.ts
@@ -1,9 +1,8 @@
import { limiter } from "@/lib/cron";
import prisma from "@/lib/prisma";
import { stripe } from "@/lib/stripe";
-import { PRO_PLAN } from "@/lib/stripe/utils";
import { redis } from "@/lib/upstash";
-import { log } from "@dub/utils";
+import { getPlanFromPriceId, log } from "@dub/utils";
import { resend, sendEmail } from "emails";
import UpgradeEmail from "emails/upgrade-email";
import { NextResponse } from "next/server";
@@ -51,9 +50,14 @@ export const POST = async (req: Request) => {
checkoutSession.subscription as string,
);
const priceId = subscription.items.data[0].price.id;
+ const plan = getPlanFromPriceId(priceId);
- // we only process webhooks for pro plan
- if (!PRO_PLAN.priceIds.includes(priceId)) {
+ if (!plan) {
+ await log({
+ message: "Invalid price ID",
+ type: "cron",
+ mention: true,
+ });
return;
}
@@ -70,9 +74,9 @@ export const POST = async (req: Request) => {
data: {
stripeId,
billingCycleStart: new Date().getDate(),
- usageLimit: PRO_PLAN.usageLimit,
- linksLimit: PRO_PLAN.linksLimit,
- plan: "pro",
+ usageLimit: plan.limits.clicks!,
+ linksLimit: plan.limits.links!,
+ plan: plan.name.toLowerCase(),
},
select: {
users: {
@@ -98,11 +102,11 @@ export const POST = async (req: Request) => {
limiter.schedule(() =>
sendEmail({
email: user.email as string,
- subject: `Thank you for upgrading to Dub.co Pro!`,
+ subject: `Thank you for upgrading to Dub.co ${plan.name}!`,
react: UpgradeEmail({
name: user.name,
email: user.email as string,
- plan: "pro",
+ plan: plan.name.toLowerCase(),
}),
marketing: true,
}),
@@ -116,8 +120,14 @@ export const POST = async (req: Request) => {
const subscriptionUpdated = event.data.object as Stripe.Subscription;
const priceId = subscriptionUpdated.items.data[0].price.id;
- // we only process webhooks for pro plan
- if (!PRO_PLAN.priceIds.includes(priceId)) {
+ const plan = getPlanFromPriceId(priceId);
+
+ if (!plan) {
+ await log({
+ message: "Invalid price ID",
+ type: "cron",
+ mention: true,
+ });
return;
}
@@ -146,9 +156,9 @@ export const POST = async (req: Request) => {
stripeId,
},
data: {
- usageLimit: PRO_PLAN.usageLimit,
- linksLimit: PRO_PLAN.linksLimit,
- plan: "pro",
+ usageLimit: plan.limits.clicks!,
+ linksLimit: plan.limits.links!,
+ plan: plan.name.toLowerCase(),
},
select: {
users: {
@@ -221,6 +231,7 @@ export const POST = async (req: Request) => {
},
data: {
usageLimit: 1000,
+ linksLimit: 25,
plan: "free",
},
}),
diff --git a/apps/web/app/api/cron/usage/utils.ts b/apps/web/app/api/cron/usage/utils.ts
index 41f15c93a8..ed5a7d6fc5 100644
--- a/apps/web/app/api/cron/usage/utils.ts
+++ b/apps/web/app/api/cron/usage/utils.ts
@@ -29,6 +29,8 @@ export const updateUsage = async (skip?: number) => {
slug: true,
usage: true,
usageLimit: true,
+ linksUsage: true,
+ linksLimit: true,
plan: true,
billingCycleStart: true,
users: {
@@ -116,20 +118,9 @@ export const updateUsage = async (skip?: number) => {
project.createdAt.getTime() <
new Date().getTime() - 30 * 24 * 60 * 60 * 1000
) {
- const [createdLinks, topLinks] = await Promise.allSettled([
- prisma.link.count({
- where: {
- project: {
- id: project.id,
- },
- createdAt: {
- // in the last 30 days
- gte: new Date(new Date().setDate(new Date().getDate() - 30)),
- },
- },
- }),
+ const topLinks =
project.usage > 0
- ? getStats({
+ ? await getStats({
domain: project.domains.map((domain) => domain.slug).join(","),
endpoint: "top_links",
interval: "30d",
@@ -151,8 +142,7 @@ export const updateUsage = async (skip?: number) => {
}),
),
)
- : [],
- ]);
+ : [];
const emails = project.users.map((user) => user.user.email) as string[];
@@ -169,12 +159,8 @@ export const updateUsage = async (skip?: number) => {
projectName: project.name,
projectSlug: project.slug,
totalClicks: project.usage,
- createdLinks:
- createdLinks.status === "fulfilled"
- ? createdLinks.value
- : 0,
- topLinks:
- topLinks.status === "fulfilled" ? topLinks.value : [],
+ createdLinks: project.linksUsage,
+ topLinks,
}),
}),
);
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.ts
index 8f5af75ac9..82dbcecefe 100644
--- a/apps/web/app/api/links/[linkId]/route.ts
+++ b/apps/web/app/api/links/[linkId]/route.ts
@@ -1,12 +1,7 @@
import { withAuth } from "@/lib/auth";
import { deleteLink, editLink, processLink } from "@/lib/api/links";
import { NextResponse } from "next/server";
-import {
- APP_DOMAIN_WITH_NGROK,
- GOOGLE_FAVICON_URL,
- getApexDomain,
- log,
-} from "@dub/utils";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { qstash } from "@/lib/cron";
// GET /api/links/[linkId] – get a link
@@ -91,9 +86,6 @@ export const PUT = withAuth(
headers,
});
},
- {
- needNotExceededUsage: true,
- },
);
// DELETE /api/links/[linkId] – delete a link
diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.ts
index c7519dd559..a80c4e12ce 100644
--- a/apps/web/app/api/links/bulk/route.ts
+++ b/apps/web/app/api/links/bulk/route.ts
@@ -2,7 +2,7 @@ import { bulkCreateLinks, processLink } from "@/lib/api/links";
import { withAuth } from "@/lib/auth";
import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
-import { getBillingStartDate } from "@dub/utils";
+import { capitalize, getBillingStartDate } from "@dub/utils";
// POST /api/links/bulk – bulk create up to 100 links
export const POST = withAuth(
@@ -31,19 +31,13 @@ export const POST = withAuth(
headers,
});
}
- const linksUsage = await prisma.link.count({
- where: {
- projectId: project.id,
- createdAt: {
- gte: getBillingStartDate(project.billingCycleStart),
- },
- },
- });
- if (linksUsage + links.length > project.linksLimit) {
+ if (project.linksUsage + links.length > project.linksLimit) {
return new Response(
`You can only create ${
project.linksLimit
- } short links on the ${project.plan.toUpperCase()} plan. Upgrade to create more links.`,
+ }/month short links on the ${capitalize(
+ project.plan,
+ )} plan. Upgrade to create more links.`,
{ status: 403, headers },
);
}
@@ -71,6 +65,7 @@ export const POST = withAuth(
return NextResponse.json([...validLinksResponse, ...errors], { headers });
},
{
- requiredPlan: ["pro", "enterprise"],
+ needNotExceededLinks: true,
+ requiredPlan: ["pro", "business", "enterprise"],
},
);
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.ts
index ebb3758b70..649192bbfd 100644
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@ -105,7 +105,7 @@ export const POST = withAuth(
return NextResponse.json(response, { headers });
},
{
- needNotExceededUsage: true,
+ needNotExceededLinks: true,
allowAnonymous: true,
},
);
diff --git a/apps/web/app/api/projects/[slug]/billing/upgrade/route.ts b/apps/web/app/api/projects/[slug]/billing/upgrade/route.ts
index 4924ac5d86..15e157f998 100644
--- a/apps/web/app/api/projects/[slug]/billing/upgrade/route.ts
+++ b/apps/web/app/api/projects/[slug]/billing/upgrade/route.ts
@@ -4,18 +4,22 @@ import { APP_DOMAIN } from "@dub/utils";
import { NextResponse } from "next/server";
export const POST = withAuth(async ({ searchParams, project, session }) => {
- const { priceId } = searchParams;
+ const { price } = searchParams;
- if (!priceId) {
- return new Response("Missing price ID", { status: 400 });
+ if (!price) {
+ return new Response("Missing price", { status: 400 });
}
+ const prices = await stripe.prices.list({
+ lookup_keys: [price],
+ });
+
const stripeSession = await stripe.checkout.sessions.create({
customer_email: session.user.email,
billing_address_collection: "required",
success_url: `${APP_DOMAIN}/${project.slug}/settings/billing?success=true`,
cancel_url: `${APP_DOMAIN}/${project.slug}/settings/billing`,
- line_items: [{ price: priceId, quantity: 1 }],
+ line_items: [{ price: prices.data[0].id, quantity: 1 }],
automatic_tax: {
enabled: true,
},
diff --git a/apps/web/app/api/stats/[endpoint]/route.ts b/apps/web/app/api/stats/[endpoint]/route.ts
index 26c592f06a..dcfad1e3c2 100644
--- a/apps/web/app/api/stats/[endpoint]/route.ts
+++ b/apps/web/app/api/stats/[endpoint]/route.ts
@@ -39,6 +39,6 @@ export const GET = withAuth(
return NextResponse.json(response);
},
{
- needNotExceededUsage: true,
+ needNotExceededClicks: true,
},
);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/client.tsx
index b39303b615..0d43024adb 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/client.tsx
@@ -4,14 +4,14 @@ import useDomains from "@/lib/swr/use-domains";
import useProject from "@/lib/swr/use-project";
import LayoutLoader from "@/ui/layout/layout-loader";
import LinkNotFound from "@/ui/links/link-not-found";
-import ProjectExceededUsage from "@/ui/projects/project-exceeded-usage";
+import ProjectExceededClicks from "@/ui/projects/project-exceeded-clicks";
import { useSearchParams } from "next/navigation";
import { ReactNode } from "react";
export default function AnalyticsClient({ children }: { children: ReactNode }) {
- const { exceededUsage, loading } = useProject();
- if (exceededUsage) {
- return <ProjectExceededUsage />;
+ const { exceededClicks, loading } = useProject();
+ if (exceededClicks) {
+ return <ProjectExceededClicks />;
}
const { domains, loading: loadingDomains } = useDomains();
const searchParams = useSearchParams();
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx
index b404f9cb02..0f0daad833 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx
@@ -14,8 +14,13 @@ import { ChevronDown, FilePlus2, Sheet } from "lucide-react";
import { useRouter } from "next/navigation";
import { useContext, useState } from "react";
import { ModalContext } from "@/ui/modals/provider";
+import Link from "next/link";
+import { NumberTooltip } from "@dub/ui/src/tooltip";
+import { nFormatter } from "@dub/utils";
export default function ProjectLinksClient() {
+ const { slug, linksUsage, linksLimit } = useProject();
+
const { AddEditLinkModal, AddEditLinkButton } = useAddEditLinkModal();
return (
@@ -24,7 +29,24 @@ export default function ProjectLinksClient() {
<div className="flex h-36 items-center border-b border-gray-200 bg-white">
<MaxWidthWrapper>
<div className="flex items-center justify-between">
- <h1 className="text-2xl text-gray-600">Links</h1>
+ <div className="flex items-end space-x-2">
+ <h1 className="text-2xl text-gray-600">Links</h1>
+ <Link
+ href={`/${slug}/settings/billing`}
+ className="flex items-center space-x-2 rounded-lg px-2 py-1 transition-all hover:bg-gray-50"
+ >
+ {linksUsage !== undefined && linksLimit ? (
+ <p className="text-sm text-gray-600">
+ <NumberTooltip value={linksUsage}>
+ <span>{nFormatter(linksUsage)} </span>
+ </NumberTooltip>
+ / {nFormatter(linksLimit, { full: true })}
+ </p>
+ ) : (
+ <div className="h-5 w-32 animate-pulse rounded-md bg-gray-200" />
+ )}
+ </Link>
+ </div>
<div className="flex">
<AddEditLinkButton />
<AddLinkOptions />
@@ -39,7 +61,7 @@ export default function ProjectLinksClient() {
const AddLinkOptions = () => {
const router = useRouter();
- const { slug, exceededUsage } = useProject();
+ const { slug, exceededLinks } = useProject();
const [openPopover, setOpenPopover] = useState(false);
const { setShowUpgradePlanModal } = useContext(ModalContext);
@@ -48,11 +70,11 @@ const AddLinkOptions = () => {
content={
<div className="w-full divide-y divide-gray-200 md:w-52">
<div className="p-2">
- {slug && exceededUsage ? (
+ {slug && exceededLinks ? (
<Tooltip
content={
<TooltipContent
- title="Your project has exceeded its usage limit. We're still collecting data on your existing links, but you need to upgrade to add more links."
+ title="Your project has exceeded its monthly links limit. We're still collecting data on your existing links, but you need to upgrade to add more links."
cta="Upgrade to Pro"
onClick={() => {
setOpenPopover(false);
@@ -88,17 +110,17 @@ const AddLinkOptions = () => {
<img
src="/_static/icons/bitly.svg"
alt="Bitly logo"
- className="h-4 w-4 rounded-full"
+ className="h-4 w-4"
/>
}
/>
</button>
)}
- {slug && exceededUsage ? (
+ {slug && exceededLinks ? (
<Tooltip
content={
<TooltipContent
- title="Your project has exceeded its usage limit. We're still collecting data on your existing links, but you need to upgrade to add more links."
+ title="Your project has exceeded its monthly links limit. We're still collecting data on your existing links, but you need to upgrade to add more links."
cta="Upgrade to Pro"
onClick={() => {
setOpenPopover(false);
@@ -134,17 +156,17 @@ const AddLinkOptions = () => {
<img
src="/_static/icons/rebrandly.svg"
alt="Rebrandly logo"
- className="h-5 w-5"
+ className="h-4 w-4"
/>
}
/>
</button>
)}
- {slug && exceededUsage ? (
+ {slug && exceededLinks ? (
<Tooltip
content={
<TooltipContent
- title="Your project has exceeded its usage limit. We're still collecting data on your existing links, but you need to upgrade to add more links."
+ title="Your project has exceeded its monthly links limit. We're still collecting data on your existing links, but you need to upgrade to add more links."
cta="Upgrade to Pro"
onClick={() => {
setOpenPopover(false);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsx
index a9fb1a54bc..9191c4301a 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsx
@@ -3,26 +3,30 @@
import useProject from "@/lib/swr/use-project";
import { ModalContext } from "@/ui/modals/provider";
import PlanBadge from "@/ui/projects/plan-badge";
-import { Divider, InfinityIcon } from "@/ui/shared/icons";
+import ProgressBar from "@/ui/shared/progress-bar";
import { Button, InfoTooltip, NumberTooltip } from "@dub/ui";
-import { fetcher, getFirstAndLastDay, nFormatter } from "@dub/utils";
+import { HOME_DOMAIN, getFirstAndLastDay, nFormatter } from "@dub/utils";
import va from "@vercel/analytics";
import { motion } from "framer-motion";
import { useRouter, useSearchParams } from "next/navigation";
import { useContext, useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
-import useSWR, { mutate } from "swr";
+import { mutate } from "swr";
export default function ProjectBillingClient() {
const router = useRouter();
const searchParams = useSearchParams();
- const { slug, plan, usage, usageLimit, billingCycleStart } = useProject();
+ const {
+ slug,
+ plan,
+ usage,
+ usageLimit,
+ linksUsage,
+ linksLimit,
+ billingCycleStart,
+ } = useProject();
- const { data: links } = useSWR<number>(
- `/api/projects/${slug}/links/count`,
- fetcher,
- );
const [clicked, setClicked] = useState(false);
const [billingStart, billingEnd] = useMemo(() => {
@@ -87,73 +91,42 @@ export default function ProjectBillingClient() {
<div className="grid grid-cols-1 divide-y divide-gray-200 sm:grid-cols-2 sm:divide-x sm:divide-y-0">
<div className="p-10">
<div className="flex items-center space-x-2">
- <h3 className="font-medium">Total Link Clicks</h3>
- <InfoTooltip content="Number of billable link clicks across all your projects." />
+ <h3 className="font-medium">Link Clicks</h3>
+ <InfoTooltip content="Number of billable link clicks for your current billing cycle." />
</div>
- {plan === "enterprise" ? (
- <div className="mt-4 flex items-center">
- {usage || usage === 0 ? (
+ <div className="mt-2 flex flex-col space-y-2">
+ {usage !== undefined && usageLimit ? (
+ <p className="text-sm text-gray-600">
<NumberTooltip value={usage}>
- <p className="text-2xl font-semibold text-black">
- {nFormatter(usage)}
- </p>
+ <span>{nFormatter(usage)} </span>
</NumberTooltip>
- ) : (
- <div className="h-8 w-8 animate-pulse rounded-md bg-gray-200" />
- )}
- <Divider className="h-8 w-8 text-gray-500" />
- <InfinityIcon className="h-8 w-8 text-gray-500" />
- </div>
- ) : (
- <div className="mt-2 flex flex-col space-y-2">
- {usage !== undefined && usageLimit ? (
- <p className="text-sm text-gray-600">
- <NumberTooltip value={usage}>
- <span>{nFormatter(usage)} </span>
- </NumberTooltip>
- / {nFormatter(usageLimit)} clicks (
- {((usage / usageLimit) * 100).toFixed(1)}%)
- </p>
- ) : (
- <div className="h-5 w-32 animate-pulse rounded-md bg-gray-200" />
- )}
- <div className="h-3 w-full overflow-hidden rounded-full bg-gray-200">
- <motion.div
- initial={{ width: 0 }}
- animate={{
- width:
- usage !== undefined && usageLimit
- ? (usage / usageLimit) * 100 + "%"
- : "0%",
- }}
- transition={{ duration: 0.5, type: "spring" }}
- className={`${
- usage && usageLimit && usage > usageLimit
- ? "bg-red-500"
- : "bg-blue-500"
- } h-3 rounded-full`}
- />
- </div>
- </div>
- )}
+ / {nFormatter(usageLimit)} clicks (
+ {((usage / usageLimit) * 100).toFixed(1)}%)
+ </p>
+ ) : (
+ <div className="h-5 w-32 animate-pulse rounded-md bg-gray-200" />
+ )}
+ <ProgressBar value={usage} max={usageLimit} />
+ </div>
</div>
<div className="p-10">
<div className="flex items-center space-x-2">
- <h3 className="font-medium">Number of Links</h3>
- <InfoTooltip content="Number of short links in your project." />
+ <h3 className="font-medium">Created Links</h3>
+ <InfoTooltip content="Number of short links created in the current billing cycle." />
</div>
- <div className="mt-4 flex items-center">
- {links || links === 0 ? (
- <NumberTooltip value={links} unit="links">
- <p className="text-2xl font-semibold text-black">
- {nFormatter(links)}
- </p>
- </NumberTooltip>
+ <div className="mt-2 flex flex-col space-y-2">
+ {linksUsage !== undefined && linksLimit ? (
+ <p className="text-sm text-gray-600">
+ <NumberTooltip value={linksUsage}>
+ <span>{nFormatter(linksUsage)} </span>
+ </NumberTooltip>
+ / {nFormatter(linksLimit)} links (
+ {((linksUsage / linksLimit) * 100).toFixed(1)}%)
+ </p>
) : (
- <div className="h-8 w-8 animate-pulse rounded-md bg-gray-200" />
+ <div className="h-5 w-32 animate-pulse rounded-md bg-gray-200" />
)}
- <Divider className="h-8 w-8 text-gray-500" />
- <InfinityIcon className="h-8 w-8 text-gray-500" />
+ <ProgressBar value={linksUsage} max={linksLimit} />
</div>
</div>
</div>
@@ -162,9 +135,11 @@ export default function ProjectBillingClient() {
{plan ? (
<p className="text-sm text-gray-500">
{plan === "enterprise"
- ? "On the Enterprise plan, the sky's the limit! Thank you for your support."
+ ? "You're on the Enterprise plan."
+ : plan === "business"
+ ? "Need more clicks or links? Contact us for an Enterprise quote."
: `For higher limits, upgrade to the ${
- plan === "free" ? "Pro" : "Enterprise"
+ plan === "free" ? "Pro" : "Business"
} plan.`}
</p>
) : (
@@ -178,6 +153,14 @@ export default function ProjectBillingClient() {
onClick={() => setShowUpgradePlanModal(true)}
variant="success"
/>
+ ) : plan === "business" ? (
+ <a
+ href={`${HOME_DOMAIN}/enterprise`}
+ target="_blank"
+ className="inline-flex items-center justify-center rounded-md border border-violet-600 bg-violet-600 px-4 py-2 text-sm font-medium text-white transition-all hover:bg-white hover:text-violet-600 focus:outline-none"
+ >
+ Contact Sales
+ </a>
) : (
<Button
text="Manage Subscription"
diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.ts
index 4a2bfbc118..d8a78ecd77 100644
--- a/apps/web/lib/api/links.ts
+++ b/apps/web/lib/api/links.ts
@@ -12,6 +12,7 @@ import {
DUB_PROJECT_ID,
LEGAL_USER_ID,
SHORT_DOMAIN,
+ capitalize,
getBillingStartDate,
getDomainWithoutWWW,
getParamsFromURL,
@@ -269,20 +270,14 @@ export async function processLink({
status: 403,
};
}
- const linksUsage = await prisma.link.count({
- where: {
- projectId: project.id,
- createdAt: {
- gte: getBillingStartDate(project.billingCycleStart),
- },
- },
- });
- if (linksUsage >= project.linksLimit) {
+ if (project.linksUsage >= project.linksLimit) {
return {
link: payload,
error: `You can only create ${
project.linksLimit
- } short links on the ${project.plan.toUpperCase()} plan. Upgrade to create more links.`,
+ }/month short links on the ${capitalize(
+ project.plan,
+ )} plan. Upgrade to create more links.`,
status: 403,
};
}
diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.ts
index d04804f41c..d010ca3c82 100644
--- a/apps/web/lib/auth/index.ts
+++ b/apps/web/lib/auth/index.ts
@@ -63,16 +63,18 @@ export const withAuth =
(
handler: WithAuthHandler,
{
- requiredPlan = ["free", "pro", "enterprise"], // if the action needs a specific plan
+ requiredPlan = ["free", "pro", "business", "enterprise"], // if the action needs a specific plan
requiredRole = ["owner", "member"],
- needNotExceededUsage, // if the action needs the user to not have exceeded their usage
+ needNotExceededClicks, // if the action needs the user to not have exceeded their clicks usage
+ needNotExceededLinks, // if the action needs the user to not have exceeded their links usage
allowAnonymous, // special case for /api/links (POST /api/links) – allow no session
allowSelf, // special case for removing yourself from a project
skipLinkChecks, // special case for /api/links/exists – skip link checks
}: {
requiredPlan?: Array<PlanProps>;
requiredRole?: Array<"owner" | "member">;
- needNotExceededUsage?: boolean;
+ needNotExceededClicks?: boolean;
+ needNotExceededLinks?: boolean;
allowAnonymous?: boolean;
allowSelf?: boolean;
skipLinkChecks?: boolean;
@@ -211,6 +213,7 @@ export const withAuth =
logo: true,
usage: true,
usageLimit: true,
+ linksUsage: true,
linksLimit: true,
plan: true,
stripeId: true,
@@ -313,12 +316,26 @@ export const withAuth =
});
}
- // usage overage checks
- if (needNotExceededUsage && project.usage > project.usageLimit) {
- return new Response("Unauthorized: Usage limits exceeded.", {
- status: 403,
- headers,
- });
+ // clicks usage overage checks
+ if (needNotExceededClicks && project.usage > project.usageLimit) {
+ return new Response(
+ "Unauthorized: Clicks limits exceeded. Upgrade to get more clicks.",
+ {
+ status: 403,
+ headers,
+ },
+ );
+ }
+
+ // links usage overage checks
+ if (needNotExceededLinks && project.linksUsage > project.linksLimit) {
+ return new Response(
+ "Unauthorized: Links limits exceeded. Upgrade to get more links.",
+ {
+ status: 403,
+ headers,
+ },
+ );
}
// plan checks
diff --git a/apps/web/lib/stripe/utils.ts b/apps/web/lib/stripe/utils.ts
deleted file mode 100644
index 7a84399cb0..0000000000
--- a/apps/web/lib/stripe/utils.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-export const PRO_PLAN = {
- linksLimit: 10000,
- usageLimit: 1000000,
- priceIds: [
- "price_1LoytoAlJJEpqkPV2oPcQ63m",
- "price_1LodNLAlJJEpqkPVQSrt33Lc",
- "price_1LoytoAlJJEpqkPVsWjM4tB9",
- "price_1LodNLAlJJEpqkPVRxUyCQgZ",
- ],
- monthly: {
- amount: 25,
- priceIds: {
- test: "price_1LoytoAlJJEpqkPV2oPcQ63m",
- production: "price_1LodNLAlJJEpqkPVQSrt33Lc",
- },
- },
- yearly: {
- amount: 264,
- priceIds: {
- test: "price_1LoytoAlJJEpqkPVsWjM4tB9",
- production: "price_1LodNLAlJJEpqkPVRxUyCQgZ",
- },
- },
-};
diff --git a/apps/web/lib/swr/use-project.ts b/apps/web/lib/swr/use-project.ts
index a44570db0f..649e7fde5b 100644
--- a/apps/web/lib/swr/use-project.ts
+++ b/apps/web/lib/swr/use-project.ts
@@ -14,17 +14,11 @@ export default function useProject() {
dedupingInterval: 30000,
},
);
-
- const exceededUsage = useMemo(() => {
- if (project) {
- return project.usage > project.usageLimit;
- }
- }, [project]);
-
return {
...project,
isOwner: project?.users && project.users[0].role === "owner",
- exceededUsage,
+ exceededClicks: project && project.usage > project.usageLimit,
+ exceededLinks: project && project.linksUsage > project.linksLimit,
error,
loading: slug && !project && !error,
};
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 5e3e562bdf..61ec6f3c02 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -34,7 +34,7 @@ export type TagColorProps =
| "pink"
| "brown";
-export type PlanProps = "free" | "pro" | "enterprise";
+export type PlanProps = "free" | "pro" | "business" | "enterprise";
export interface ProjectProps {
id: string;
@@ -43,6 +43,7 @@ export interface ProjectProps {
logo?: string;
usage: number;
usageLimit: number;
+ linksUsage: number;
linksLimit: number;
plan: PlanProps;
stripeId?: string;
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index fd353f1887..29f2626c7b 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -88,12 +88,13 @@ model Project {
users ProjectUsers[]
invites ProjectInvite[]
- usage Int @default(0)
- usageLimit Int @default(1000)
- linksLimit Int @default(100)
plan String @default("free")
stripeId String? @unique // Stripe subscription ID
billingCycleStart Int // day of the month when the billing cycle starts
+ usage Int @default(0)
+ usageLimit Int @default(1000)
+ linksUsage Int @default(0)
+ linksLimit Int @default(25)
monitoringId String? @unique // cron job ID for monitoring
sentEmails SentEmail[]
diff --git a/apps/web/ui/layout/upgrade-banner.tsx b/apps/web/ui/layout/upgrade-banner.tsx
index 7968b0cf3d..57e696e21b 100644
--- a/apps/web/ui/layout/upgrade-banner.tsx
+++ b/apps/web/ui/layout/upgrade-banner.tsx
@@ -52,8 +52,8 @@ export default function UpgradeBanner() {
onClick={() => setShowUpgradePlanModal(true)}
className="mb-1 ml-3 hidden sm:block"
>
- <Badge variant="blue" className="px-3 py-1">
- Upgrade to Pro
+ <Badge variant="rainbow" className="px-3 py-1">
+ Upgrade
</Badge>
</button>
)}
diff --git a/apps/web/ui/links/link-card.tsx b/apps/web/ui/links/link-card.tsx
index 41b4e08eb6..736876ac06 100644
--- a/apps/web/ui/links/link-card.tsx
+++ b/apps/web/ui/links/link-card.tsx
@@ -78,7 +78,7 @@ export default function LinkCard({
const { slug } = params;
const { queryParams } = useRouterStuff();
- const { exceededUsage } = useProject();
+ const { exceededClicks } = useProject();
const { verified, loading } = useDomains({ domain });
const linkRef = useRef<any>();
@@ -87,7 +87,7 @@ export default function LinkCard({
const { data: clicks } = useSWR<number>(
isVisible &&
- !exceededUsage &&
+ !exceededClicks &&
`/api${
slug ? `/projects/${slug}` : ""
}/stats/clicks?domain=${domain}&key=${key}`,
diff --git a/apps/web/ui/modals/upgrade-plan-modal.tsx b/apps/web/ui/modals/upgrade-plan-modal.tsx
index 20648962e2..a53875382d 100644
--- a/apps/web/ui/modals/upgrade-plan-modal.tsx
+++ b/apps/web/ui/modals/upgrade-plan-modal.tsx
@@ -1,8 +1,12 @@
import { getStripe } from "@/lib/stripe/client";
-import { PRO_PLAN } from "@/lib/stripe/utils";
import { CheckCircleFill } from "@/ui/shared/icons";
import { Badge, Button, Logo, Modal } from "@dub/ui";
-import { HOME_DOMAIN, STAGGER_CHILD_VARIANTS, capitalize } from "@dub/utils";
+import {
+ HOME_DOMAIN,
+ PLANS,
+ STAGGER_CHILD_VARIANTS,
+ capitalize,
+} from "@dub/utils";
import { motion } from "framer-motion";
import Link from "next/link";
import {
@@ -27,7 +31,7 @@ function UpgradePlanModal({
}: {
showUpgradePlanModal: boolean;
setShowUpgradePlanModal: Dispatch<SetStateAction<boolean>>;
- defaultPlan: "Pro" | "Enterprise";
+ defaultPlan: "Pro" | "Business";
}) {
const router = useRouter();
const params = useParams() as { slug: string };
@@ -36,23 +40,10 @@ function UpgradePlanModal({
const welcomeFlow = pathname === "/welcome";
const slug = welcomeFlow ? searchParams?.get("slug") : params.slug;
- const [plan, setPlan] = useState<"Pro" | "Enterprise">(defaultPlan);
+ const [plan, setPlan] = useState<"Pro" | "Business">(defaultPlan);
const [period, setPeriod] = useState<"monthly" | "yearly">("yearly");
- const features = useMemo(() => {
- return [
- `Track ${
- plan === "Enterprise" ? "unlimited" : "50x more"
- } link clicks per month`,
- "Unlimited custom domains",
- "Unlimited team members",
- "Unlimited link history",
- "Unlimited tags",
- "Redirect your root domain",
- "Custom QR Code logo",
- "API Access",
- ...(plan === "Enterprise" ? ["SSO/SAML", "Priority support"] : []),
- ];
- }, [plan]);
+ const currentPlan = PLANS.find((p) => p.name === plan) ?? PLANS[0];
+ const features = PLANS.find((p) => p.name === plan)?.features ?? [];
const [clicked, setClicked] = useState(false);
return (
@@ -109,7 +100,8 @@ function UpgradePlanModal({
variant="neutral"
className="text-sm font-normal normal-case"
>
- ${PRO_PLAN[period].amount}/{period.replace("ly", "")}
+ ${currentPlan.price[period].toString()}/
+ {period.replace("ly", "")}
</Badge>
)}
</div>
@@ -124,7 +116,7 @@ function UpgradePlanModal({
className="text-xs text-gray-500 underline underline-offset-4 transition-colors hover:text-gray-800"
>
{period === "monthly"
- ? "Get 2 months free 🎁"
+ ? "Save 20% with yearly billing"
: "Switch to monthly"}
</button>
</div>
@@ -140,14 +132,14 @@ function UpgradePlanModal({
animate="show"
className="flex flex-col space-y-2"
>
- {features.map((feature, i) => (
+ {features.map(({ text }, i) => (
<motion.div
key={i}
variants={STAGGER_CHILD_VARIANTS}
className="flex items-center space-x-2 text-sm text-gray-500"
>
<CheckCircleFill className="h-5 w-5 text-green-500" />
- <span>{feature}</span>
+ <span>{text}</span>
</motion.div>
))}
</motion.div>
@@ -158,13 +150,7 @@ function UpgradePlanModal({
onClick={() => {
setClicked(true);
fetch(
- `/api/projects/${slug}/billing/upgrade?priceId=${
- PRO_PLAN[period].priceIds[
- process.env.NEXT_PUBLIC_VERCEL_ENV === "production"
- ? "production"
- : "test"
- ]
- }`,
+ `/api/projects/${slug}/billing/upgrade?price=${plan.toLowerCase()}_${period}`,
{
method: "POST",
},
@@ -192,7 +178,7 @@ function UpgradePlanModal({
<div className="flex items-center justify-center space-x-2">
<button
onClick={() => {
- setPlan(plan === "Pro" ? "Enterprise" : "Pro");
+ setPlan(plan === "Pro" ? "Business" : "Pro");
}}
className="text-center text-xs text-gray-500 underline-offset-4 transition-all hover:text-gray-800 hover:underline"
>
@@ -218,7 +204,7 @@ function UpgradePlanModal({
export function useUpgradePlanModal(
{ defaultPlan } = { defaultPlan: "Pro" } as {
- defaultPlan: "Pro" | "Enterprise";
+ defaultPlan: "Pro" | "Business";
},
) {
const [showUpgradePlanModal, setShowUpgradePlanModal] = useState(false);
diff --git a/apps/web/ui/projects/plan-badge.tsx b/apps/web/ui/projects/plan-badge.tsx
index 68812a847a..7e2564f89e 100644
--- a/apps/web/ui/projects/plan-badge.tsx
+++ b/apps/web/ui/projects/plan-badge.tsx
@@ -5,7 +5,13 @@ export default function PlanBadge({ plan }: { plan: PlanProps }) {
return (
<Badge
variant={
- plan === "enterprise" ? "violet" : plan === "pro" ? "blue" : "black"
+ plan === "enterprise"
+ ? "violet"
+ : plan === "business"
+ ? "sky"
+ : plan === "pro"
+ ? "blue"
+ : "black"
}
>
{plan}
diff --git a/apps/web/ui/projects/project-exceeded-usage.tsx b/apps/web/ui/projects/project-exceeded-clicks.tsx
similarity index 96%
rename from apps/web/ui/projects/project-exceeded-usage.tsx
rename to apps/web/ui/projects/project-exceeded-clicks.tsx
index 69d902eeaa..4f40ea89c8 100644
--- a/apps/web/ui/projects/project-exceeded-usage.tsx
+++ b/apps/web/ui/projects/project-exceeded-clicks.tsx
@@ -6,7 +6,7 @@ import { Lock } from "lucide-react";
import { useContext } from "react";
import { ModalContext } from "../modals/provider";
-export default function ProjectExceededUsage() {
+export default function ProjectExceededClicks() {
const { setShowUpgradePlanModal } = useContext(ModalContext);
return (
diff --git a/apps/web/ui/shared/progress-bar.tsx b/apps/web/ui/shared/progress-bar.tsx
new file mode 100644
index 0000000000..4568c4d514
--- /dev/null
+++ b/apps/web/ui/shared/progress-bar.tsx
@@ -0,0 +1,26 @@
+"use client";
+
+import { motion } from "framer-motion";
+
+export default function ProgressBar({
+ value,
+ max,
+}: {
+ value?: number;
+ max?: number;
+}) {
+ return (
+ <div className="h-3 w-full overflow-hidden rounded-full bg-gray-200">
+ <motion.div
+ initial={{ width: 0 }}
+ animate={{
+ width: value && max ? (value / max) * 100 + "%" : "0%",
+ }}
+ transition={{ duration: 0.5, type: "spring" }}
+ className={`${
+ value && max && value > max ? "bg-red-500" : "bg-blue-500"
+ } h-full`}
+ />
+ </div>
+ );
+}
diff --git a/packages/ui/package.json b/packages/ui/package.json
index e9ce92aa18..517fa0cab4 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -39,6 +39,7 @@
"@radix-ui/react-dialog": "1.0.5",
"@radix-ui/react-navigation-menu": "^1.1.2",
"@radix-ui/react-popover": "1.0.7",
+ "@radix-ui/react-progress": "^1.0.3",
"@radix-ui/react-switch": "^1.0.1",
"@radix-ui/react-tooltip": "^1.0.7",
"class-variance-authority": "^0.7.0",
diff --git a/packages/ui/src/badge.tsx b/packages/ui/src/badge.tsx
index 44759b1dac..abcf3210b8 100644
--- a/packages/ui/src/badge.tsx
+++ b/packages/ui/src/badge.tsx
@@ -9,9 +9,12 @@ const badgeVariants = cva(
default: "border-gray-400 text-gray-500",
violet: "border-violet-600 bg-violet-600 text-white",
blue: "border-blue-500 bg-blue-500 text-white",
+ sky: "border-sky-900 bg-sky-900 text-white",
black: "border-black bg-black text-white",
gray: "border-gray-200 bg-gray-200 text-gray-800",
neutral: "border-gray-400 text-gray-500",
+ rainbow:
+ "bg-gradient-to-r from-violet-600 to-pink-600 text-white border-transparent",
},
},
defaultVariants: {
diff --git a/packages/ui/src/tooltip.tsx b/packages/ui/src/tooltip.tsx
index 127dc9e1a0..20bf2cb4b4 100644
--- a/packages/ui/src/tooltip.tsx
+++ b/packages/ui/src/tooltip.tsx
@@ -110,7 +110,6 @@ export function SimpleTooltipContent({
<a
href={href}
target="_blank"
- rel="noopener noreferrer"
className="inline-flex text-gray-500 underline underline-offset-4 hover:text-gray-800"
>
{cta}
diff --git a/packages/utils/src/constants/index.ts b/packages/utils/src/constants/index.ts
index d858df7674..cb2d1d4782 100644
--- a/packages/utils/src/constants/index.ts
+++ b/packages/utils/src/constants/index.ts
@@ -1,3 +1,7 @@
+export { default as ccTLDs } from "./cctlds";
+export { default as COUNTRIES } from "./countries";
+export { PLANS } from "./pricing";
+
export const LOCALHOST_GEO_DATA = {
city: "San Francisco",
region: "CA",
@@ -169,9 +173,6 @@ export const ALL_TOOLS = [
{ name: "Link Inspector", slug: "inspector" },
];
-export { default as ccTLDs } from "./cctlds";
-export { default as COUNTRIES } from "./countries";
-
export const SECOND_LEVEL_DOMAINS = new Set([
"com",
"co",
diff --git a/packages/utils/src/constants/pricing.tsx b/packages/utils/src/constants/pricing.tsx
new file mode 100644
index 0000000000..84eaf3fcc9
--- /dev/null
+++ b/packages/utils/src/constants/pricing.tsx
@@ -0,0 +1,185 @@
+import { APP_DOMAIN, HOME_DOMAIN } from ".";
+
+export const PLANS = [
+ {
+ name: "Free",
+ tagline: "For hobby & side projects",
+ price: {
+ monthly: {
+ amount: 0,
+ },
+ yearly: {
+ amount: 0,
+ },
+ },
+ limits: {
+ links: 25,
+ clicks: 1000,
+ },
+ colors: {
+ bg: "bg-black",
+ text: "text-black",
+ },
+ cta: {
+ text: "Start for free",
+ href: APP_DOMAIN,
+ color: "bg-black border-black hover:text-black",
+ },
+ featureTitle: "What's included:",
+ features: [
+ { text: " 25 links/mo" },
+ {
+ text: " 1K tracked clicks/mo",
+ },
+ { text: "30-day analytics retention" },
+ { text: "1 custom domain" },
+ { text: "1 user" },
+ {
+ text: "Community support",
+ footnote: "Help center + GitHub discussions.",
+ },
+ {
+ text: "API Access",
+ footnote: {
+ title: "Programatically manage your links using our REST API.",
+ cta: "Learn more.",
+ href: `${HOME_DOMAIN}/docs/api-reference/introduction`,
+ },
+ },
+ ],
+ },
+ {
+ name: "Pro",
+ tagline: "For startups & small businesses",
+ price: {
+ monthly: 24,
+ yearly: 19,
+ ids: [
+ "price_1LodNLAlJJEpqkPVQSrt33Lc", // old monthly
+ "price_1LodNLAlJJEpqkPVRxUyCQgZ", // old yearly
+ ],
+ },
+ limits: {
+ links: 250,
+ clicks: 25000,
+ },
+ colors: {
+ bg: "bg-blue-500",
+ text: "text-blue-500",
+ },
+ cta: {
+ text: "Get started with Pro",
+ shortText: "Get started",
+ href: APP_DOMAIN,
+ color: "bg-blue-500 border-blue-500 hover:text-blue-500",
+ },
+ featureTitle: "Everything in Free, plus:",
+ features: [
+ { text: " 250 links/mo" },
+ {
+ text: " 25K tracked clicks/mo",
+ },
+ { text: "1-year analytics retention" },
+ { text: "10 custom domains" },
+ { text: "5 users" },
+ { text: "Basic support", footnote: "Basic email support." },
+ {
+ text: "Root domain redirect",
+ footnote: {
+ title:
+ "Redirect vistors that land on the root of your domain (e.g. yourdomain.com) to a page of your choice.",
+ cta: "Learn more.",
+ href: `${HOME_DOMAIN}/help/article/how-to-redirect-root-domain`,
+ },
+ },
+ {
+ text: "Advanced link features",
+ footnote:
+ "Custom social media cards, password-protected links, link expiration, link cloaking, device targeting, geo targeting, link aliases, link monitoring etc.",
+ },
+ ],
+ },
+ {
+ name: "Business",
+ tagline: "For larger teams with increased usage",
+ price: {
+ monthly: 49,
+ yearly: 39,
+ ids: [],
+ },
+ limits: {
+ links: 1000,
+ clicks: 100000,
+ },
+ colors: {
+ bg: "bg-sky-900",
+ text: "text-sky-900",
+ },
+ cta: {
+ text: "Get started with Business",
+ shortText: "Get started",
+ href: APP_DOMAIN,
+ color: "bg-sky-900 border-sky-900 hover:text-sky-900",
+ },
+ featureTitle: "Everything in Pro, plus:",
+ features: [
+ { text: " 1,000 links/mo" },
+ {
+ text: " 100K tracked clicks/mo",
+ },
+ { text: "2-year analytics retention" },
+ { text: "20 custom domains" },
+ { text: "15 users" },
+ { text: "Elevated support", footnote: "Email and chat support." },
+ {
+ text: "Custom branding",
+ footnote: {
+ title:
+ "Set custom QR code logos, password-protected links logos, and more.",
+ cta: "Learn more.",
+ href: `${HOME_DOMAIN}/help/article/custom-qr-codes`,
+ },
+ },
+ {
+ text: "Event callbacks",
+ footnote: "Get notified when someone clicks on your links.",
+ },
+ ],
+ },
+ {
+ name: "Enterprise",
+ price: {
+ monthly: {
+ amount: null,
+ },
+ yearly: {
+ amount: null,
+ },
+ },
+ limits: {
+ links: null,
+ clicks: null,
+ },
+ colors: {
+ bg: "bg-violet-600",
+ text: "text-violet-600",
+ },
+ cta: {
+ text: "Contact us",
+ href: "/enterprise",
+ color: "bg-violet-600 border-violet-600 hover:text-violet-600",
+ },
+ featureTitle: "Everything in Business, plus:",
+ features: [
+ { text: "Custom usage limits" },
+ { text: "Volume discounts" },
+ { text: "SSO/SAML" },
+ { text: "Role-based access controls" },
+ { text: "Custom contract & SLA" },
+ { text: "Whiteglove onboarding" },
+ { text: "Dedicated success manager" },
+ { text: "Priority support" },
+ { text: "Dedicated Slack channel" },
+ ],
+ },
+];
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index e53d72985f..9ad54862b3 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -7,6 +7,7 @@ import { twMerge } from "tailwind-merge";
import {
DUB_DOMAINS,
HOME_DOMAIN,
+ PLANS,
SECOND_LEVEL_DOMAINS,
SPECIAL_APEX_DOMAINS,
ccTLDs,
@@ -277,6 +278,10 @@ export const getBillingStartDate = (billingCycleStart: number) => {
}
};
+export const getPlanFromPriceId = (priceId: string) => {
+ return PLANS.find((plan) => plan.price.ids?.includes(priceId)) || null;
+};
+
export const generateDomainFromName = (name: string) => {
const normalizedName = slugify(name, { separator: "" });
if (normalizedName.length < 3) {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7943062984..bf64dc1c34 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -657,6 +657,9 @@ importers:
'@radix-ui/react-popover':
specifier: 1.0.7
+ '@radix-ui/react-progress':
+ specifier: ^1.0.3
'@radix-ui/react-switch':
specifier: ^1.0.1
@@ -6097,6 +6100,27 @@ packages:
react-dom: 18.2.0([email protected])
dev: false
+ resolution: {integrity: sha512-5G6Om/tYSxjSeEdrb1VfKkfZfn/1IlPWd731h2RfPuSbIfNUgfqAwbKfJCg/PP6nuUCTrYzalwHSpSinoWoCag==}
+ peerDependencies:
+ '@types/react': '*'
+ '@types/react-dom': '*'
+ react: ^16.8 || ^17.0 || ^18.0
+ react-dom: ^16.8 || ^17.0 || ^18.0
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+ dependencies:
+ '@babel/runtime': 7.23.2
+ '@radix-ui/react-context': 1.0.1(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 1.0.3(@types/[email protected])(@types/[email protected])([email protected])([email protected])
+ '@types/react': 18.2.14
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ dev: false
+
resolution: {integrity: sha512-TB76u5TIxKpqMpUAuYH2VqMhHYKa+4Vs1NHygo/llLvlffN6mLVsFhz0AnSFlSBAvTBYVHYAkHAyEt7x1gPJOA==}
peerDependencies: