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.

stashed some changes

Steven Teyd4eba19857b2
diff --git a/components/app/link-card.tsx b/components/app/link-card.tsx
index dfb2f819d9..f5c2ef968f 100644
--- a/components/app/link-card.tsx
+++ b/components/app/link-card.tsx
@@ -22,7 +22,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {
const { project } = useProject();
const { domain } = project || {};
- const { exceededUsage } = useUsage(project);
+ const { exceededUsage } = useUsage();
const { data: clicks, isValidating } = useSWR<string>(
domain
@@ -92,7 +92,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {
<TooltipContent
title="You have exceeded your usage limit. We're still collecting data on your existing links, but you need to upgrade to edit them."
cta="Upgrade"
- ctaLink={`/${slug}/settings`}
+ ctaLink={`/settings`}
/>
}
>
diff --git a/components/app/modals/add-edit-link-modal.tsx b/components/app/modals/add-edit-link-modal.tsx
index 1b9959a046..5f31017314 100644
--- a/components/app/modals/add-edit-link-modal.tsx
+++ b/components/app/modals/add-edit-link-modal.tsx
@@ -36,8 +36,8 @@ function AddEditLinkModal({
}) {
const router = useRouter();
const { slug } = router.query as { slug: string };
-
- const { project: { domain, plan } = {} } = useProject();
+ const { project: { domain } = {} } = useProject();
+ const { plan } = useUsage();
const [keyExistsError, setKeyExistsError] = useState(false);
const [generatingSlug, setGeneratingSlug] = useState(false);
@@ -308,7 +308,7 @@ function AddEditLinkModal({
</div>
</div>
- {plan === "pro" && slug && (
+ {plan?.startsWith("Pro") && slug && (
<AdvancedSettings
data={data}
setData={setData}
@@ -493,7 +493,7 @@ function AddEditLinkButton({
const { slug } = router.query as { slug?: string };
const { project } = useProject();
- const { exceededUsage } = useUsage(project);
+ const { exceededUsage } = useUsage();
return project && !project.domainVerified ? (
<Tooltip
@@ -516,7 +516,7 @@ start adding links."
<TooltipContent
title="You have exceeded your usage limit. We're still collecting data on your existing links, but you need to upgrade to add more links."
cta="Upgrade"
- ctaLink={`/${slug}/settings`}
+ ctaLink={`/settings`}
/>
}
>
diff --git a/components/app/settings/plan-usage.tsx b/components/app/settings/plan-usage.tsx
index b2a57cb5fa..9b9759fdf9 100644
--- a/components/app/settings/plan-usage.tsx
+++ b/components/app/settings/plan-usage.tsx
@@ -1,8 +1,8 @@
import useSWR from "swr";
import { useMemo, useState } from "react";
-import { fetcher, nFormatter } from "@/lib/utils";
+import { nFormatter } from "@/lib/utils";
import { useRouter } from "next/router";
-import Tooltip from "@/components/shared/tooltip";
+import Tooltip, { ProTiers } from "@/components/shared/tooltip";
import {
Divider,
Infinity,
@@ -11,26 +11,21 @@ import {
} from "@/components/shared/icons";
import { motion } from "framer-motion";
import { getStripe } from "@/lib/stripe/client";
-import useProject from "@/lib/swr/use-project";
import useUsage from "@/lib/swr/use-usage";
+import { PLAN_FROM_USAGE_LIMIT } from "@/lib/constants";
export default function PlanUsage() {
const router = useRouter();
- const { slug } = router.query as { slug: string };
-
- const { project } = useProject();
- const { usage } = useUsage(project);
-
- const { data: linkCount } = useSWR<number>(
- project && `/api/projects/${slug}/domains/${project.domain}/links/count`,
- fetcher
- );
+ const {
+ data: { usage, usageLimit, lastBilled, projectCount } = {},
+ loading,
+ } = useUsage({ settingsPage: true });
const [clicked, setClicked] = useState(false);
const [billingStart, billingEnd] = useMemo(() => {
- if (project?.lastBilled) {
- const lastBilledDate = new Date(project.lastBilled);
+ if (lastBilled) {
+ const lastBilledDate = new Date(lastBilled);
const start = lastBilledDate.toLocaleDateString("en-us", {
month: "short",
day: "numeric",
@@ -43,8 +38,10 @@ export default function PlanUsage() {
});
return [start, end];
}
- return ["", ""];
- }, [project?.lastBilled]);
+ return [];
+ }, [lastBilled]);
+
+ const plan = usageLimit && PLAN_FROM_USAGE_LIMIT[usageLimit];
return (
<div className="bg-white rounded-lg border border-gray-200">
@@ -52,17 +49,17 @@ export default function PlanUsage() {
<h2 className="text-xl font-medium">Plan &amp; Usage</h2>
<p className="text-gray-500 text-sm">
You are currently on the{" "}
- {project ? (
+ {!loading ? (
<span
className={`capitalize ${
- project.plan === "enterprise"
+ plan.startsWith("Enterprise")
? "bg-violet-600 border-violet-600 text-white"
- : project.plan === "pro"
+ : plan.startsWith("Pro")
? "bg-blue-500 border-blue-500 text-white"
: "bg-black border-black text-white"
} border rounded-full px-2 py-0.5 text-xs font-medium`}
>
- {project.plan}
+ {plan}
</span>
) : (
<span className="bg-gray-200 text-gray-200 rounded-full px-2 py-0.5 text-xs">
@@ -70,7 +67,7 @@ export default function PlanUsage() {
</span>
)}{" "}
plan.
- {project?.plan !== "free" && (
+ {billingStart && billingEnd && (
<>
{" "}
Current billing cycle:{" "}
@@ -86,17 +83,17 @@ export default function PlanUsage() {
<div className="grid grid-cols-1 sm:grid-cols-2 divide-y sm:divide-y-0 sm:divide-x divide-gray-200">
<div className="p-10 flex flex-col space-y-2">
<div className="flex items-center">
- <h3 className="font-medium">Link Clicks</h3>
- <Tooltip content="Number of link clicks that your project has had this month.">
+ <h3 className="font-medium">Total Link Clicks</h3>
+ <Tooltip content="Number of billable link clicks across all your projects.">
<div className="flex justify-center w-8 h-4">
<QuestionCircle className="w-4 h-4 text-gray-600" />
</div>
</Tooltip>
</div>
- {typeof usage === "number" ? (
+ {!loading ? (
<p className="text-sm text-gray-600">
- {nFormatter(usage)} / {nFormatter(project.usageLimit)} clicks (
- {((usage / project.usageLimit) * 100).toFixed(1)}%)
+ {nFormatter(usage)} / {nFormatter(usageLimit)} clicks (
+ {((usage / usageLimit) * 100).toFixed(1)}%)
</p>
) : (
<div className="h-5 w-32 bg-gray-200 rounded-md animate-pulse" />
@@ -105,24 +102,21 @@ export default function PlanUsage() {
<motion.div
initial={{ width: 0 }}
animate={{
- width:
- project && usage
- ? (usage / project.usageLimit) * 100 + "%"
- : "0%",
+ width: !loading ? (usage / usageLimit) * 100 + "%" : "0%",
}}
transition={{ duration: 0.5, type: "spring" }}
className={`${
- usage > project?.usageLimit ? "bg-red-500" : "bg-blue-500"
+ usage > usageLimit ? "bg-red-500" : "bg-blue-500"
} rounded-full h-3`}
/>
</div>
</div>
<div className="p-10">
- <h3 className="font-medium">Number of Links</h3>
+ <h3 className="font-medium">Number of Projects</h3>
<div className="flex items-center mt-4">
- {typeof linkCount === "number" ? (
+ {projectCount ? (
<p className="text-2xl font-semibold text-black">
- {nFormatter(linkCount)}
+ {nFormatter(projectCount)}
</p>
) : (
<div className="w-8 h-8 bg-gray-200 rounded-md animate-pulse" />
@@ -134,55 +128,32 @@ export default function PlanUsage() {
</div>
<div className="border-b border-gray-200" />
<div className="px-10 py-4 flex justify-between items-center">
- {project?.plan === "free" ? (
- <p className="text-gray-500 text-sm">
- For{" "}
- <Tooltip content="1 million link clicks per month">
- <span className="font-medium text-gray-700 underline underline-offset-2 cursor-default hover:text-black">
- increased limits
- </span>
- </Tooltip>
- , upgrade to the Pro plan.
- </p>
- ) : project?.plan === "pro" ? (
- <p className="text-gray-500 text-sm">
- To remove limits, contact us to upgrade to the Enterprise plan.
- </p>
+ {plan ? (
+ plan === "Pro 1M" ? (
+ <p className="text-gray-500 text-sm">
+ For higher limits, contact us to upgrade to the Enterprise plan.
+ </p>
+ ) : (
+ <p className="text-gray-500 text-sm">
+ {plan === "Free" ? "For " : "To "}
+ <Tooltip content={<ProTiers usageLimit={usageLimit} />}>
+ {/* TODO - a simpler version of the homepage slider */}
+ <span className="font-medium text-gray-700 underline underline-offset-2 cursor-default hover:text-black">
+ {plan === "Free"
+ ? "increased limits"
+ : "change your monthly click limits"}
+ </span>
+ </Tooltip>
+ {plan === "Free"
+ ? ", upgrade to a Pro subscription."
+ : ", manage your subscription on Stripe."}
+ </p>
+ )
) : (
<div className="h-3 w-28 bg-gray-200 rounded-full animate-pulse" />
)}
- {project ? (
- project.plan === "free" ? (
- <button
- onClick={() => {
- alert(
- "we're fixing up the checkout flow, this will be ready very soon!"
- );
- // setClicked(true);
- // fetch(`/api/projects/${slug}/upgrade`, {
- // method: "POST",
- // })
- // .then(async (res) => {
- // const data = await res.json();
- // const { id: sessionId } = data;
- // const stripe = await getStripe();
- // stripe.redirectToCheckout({ sessionId });
- // })
- // .catch((err) => {
- // alert(err);
- // setClicked(false);
- // });
- }}
- disabled={clicked}
- className={`${
- clicked
- ? "cursor-not-allowed bg-gray-100 border-gray-200"
- : "bg-blue-500 text-white border-blue-500 hover:text-blue-500 hover:bg-white"
- } h-9 w-24 text-sm border rounded-md focus:outline-none transition-all ease-in-out duration-150`}
- >
- {clicked ? <LoadingDots /> : "Upgrade"}
- </button>
- ) : project.plan === "pro" ? (
+ {plan ? (
+ plan === "Pro 1M" ? (
<div className="flex space-x-3">
<a
href="mailto:[email protected]?subject=Upgrade%20to%20Enterprise%20Plan"
@@ -193,7 +164,7 @@ export default function PlanUsage() {
<button
onClick={() => {
setClicked(true);
- fetch(`/api/projects/${slug}/manage-subscription`, {
+ fetch(`/api/stripe/manage-subscription`, {
method: "POST",
})
.then(async (res) => {
@@ -215,7 +186,34 @@ export default function PlanUsage() {
{clicked ? <LoadingDots /> : "Manage Subscription"}
</button>
</div>
- ) : null
+ ) : (
+ <button
+ onClick={() => {
+ setClicked(true);
+ fetch(`/api/upgrade`, {
+ method: "POST",
+ })
+ .then(async (res) => {
+ const data = await res.json();
+ const { id: sessionId } = data;
+ const stripe = await getStripe();
+ stripe.redirectToCheckout({ sessionId });
+ })
+ .catch((err) => {
+ alert(err);
+ setClicked(false);
+ });
+ }}
+ disabled={clicked}
+ className={`${
+ clicked
+ ? "cursor-not-allowed bg-gray-100 border-gray-200"
+ : "bg-blue-500 text-white border-blue-500 hover:text-blue-500 hover:bg-white"
+ } h-9 w-24 text-sm border rounded-md focus:outline-none transition-all ease-in-out duration-150`}
+ >
+ {clicked ? <LoadingDots /> : "Upgrade"}
+ </button>
+ )
) : (
<div className="h-9 w-24 bg-gray-200 rounded-md animate-pulse" />
)}
diff --git a/components/home/pricing.tsx b/components/home/pricing.tsx
index 27a68e6e5b..1d6b90149b 100644
--- a/components/home/pricing.tsx
+++ b/components/home/pricing.tsx
@@ -9,6 +9,7 @@ import Tooltip, { OGImageProxy } from "@/components/shared/tooltip";
import { useState } from "react";
import Slider from "@/components/shared/slider";
import { nFormatter } from "@/lib/utils";
+import { PRO_TIERS } from "@/lib/constants";
const pricingItems = [
{
@@ -85,33 +86,6 @@ const pricingItems = [
},
];
-const proTiers = [
- {
- price: 9,
- quota: 10000,
- },
- {
- price: 19,
- quota: 25000,
- },
- {
- price: 29,
- quota: 50000,
- },
- {
- price: 49,
- quota: 100000,
- },
- {
- price: 79,
- quota: 500000,
- },
- {
- price: 99,
- quota: 1000000,
- },
-];
-
const Pricing = () => {
const [tier, setTier] = useState(0);
@@ -157,7 +131,7 @@ const Pricing = () => {
) : (
<div className="my-5 flex justify-center">
<p className="text-6xl font-display font-semibold">
- ${plan === "Pro" ? proTiers[tier].price : 0}
+ ${plan === "Pro" ? PRO_TIERS[tier].price : 0}
</p>
</div>
)}
@@ -169,11 +143,11 @@ const Pricing = () => {
<Slider
value={tier}
setValue={setTier}
- maxValue={proTiers.length - 1}
+ maxValue={PRO_TIERS.length - 1}
/>
<div className="flex items-center">
<p className="text-gray-600 text-sm">
- Up to {nFormatter(proTiers[tier].quota)} link clicks/mo
+ Up to {nFormatter(PRO_TIERS[tier].quota)} link clicks/mo
</p>
<Tooltip content="If you exceed your monthly usage, your existing links will still work, but you need to upgrade to view their stats/add more links. Link clicks are shared across all projects.">
<div className="flex justify-center w-6 h-4">
diff --git a/components/layout/app/list-box.tsx b/components/layout/app/list-box.tsx
index 3afd595f81..7ccac022c1 100644
--- a/components/layout/app/list-box.tsx
+++ b/components/layout/app/list-box.tsx
@@ -8,9 +8,11 @@ import { fetcher } from "@/lib/utils";
import { ProjectProps } from "@/lib/types";
import { useSession } from "next-auth/react";
import { useAddProjectModal } from "@/components/app/modals/add-project-modal";
+import useUsage from "@/lib/swr/use-usage";
export default function ListBox() {
const { data: projects } = useSWR<ProjectProps[]>("/api/projects", fetcher);
+ const { plan } = useUsage();
const { setShowAddProjectModal, AddProjectModal } = useAddProjectModal({});
@@ -111,15 +113,20 @@ export default function ListBox() {
) : null}
</Listbox.Option>
))}
- <Listbox.Option
- key="add"
- onClick={() => setShowAddProjectModal(true)}
- value={{ name: "Add a new project", slug: "Add a new project" }}
- className="flex items-center space-x-2 w-full cursor-pointer p-2 rounded-md hover:bg-gray-100 active:scale-95 transition-all duration-75"
- >
- <PlusCircle className="w-7 h-7 text-gray-600" />
- <span className="block truncate">Add a new project</span>
- </Listbox.Option>
+ {!(plan === "Free" && projects.length >= 1) && (
+ <Listbox.Option
+ key="add"
+ onClick={() => setShowAddProjectModal(true)}
+ value={{
+ name: "Add a new project",
+ slug: "Add a new project",
+ }}
+ className="flex items-center space-x-2 w-full cursor-pointer p-2 rounded-md hover:bg-gray-100 active:scale-95 transition-all duration-75"
+ >
+ <PlusCircle className="w-7 h-7 text-gray-600" />
+ <span className="block truncate">Add a new project</span>
+ </Listbox.Option>
+ )}
</Listbox.Options>
</Transition>
</div>
diff --git a/components/layout/app/nav-tabs.tsx b/components/layout/app/nav-tabs.tsx
index 2cf8f831fb..4e955866a3 100644
--- a/components/layout/app/nav-tabs.tsx
+++ b/components/layout/app/nav-tabs.tsx
@@ -18,6 +18,7 @@ const TabsHelper = (router: NextRouter): { name: string; href: string }[] => {
return [
{ name: "Projects", href: `/` },
{ name: "Dub.sh Links", href: `/links` },
+ { name: "Settings", href: `/settings` },
];
};
diff --git a/components/shared/tooltip.tsx b/components/shared/tooltip.tsx
index 0b06f8411b..0701d826e8 100644
--- a/components/shared/tooltip.tsx
+++ b/components/shared/tooltip.tsx
@@ -1,6 +1,9 @@
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { ReactNode, useRef, useState } from "react";
import { motion, AnimatePresence, useAnimation } from "framer-motion";
+import { PRO_TIERS } from "@/lib/constants";
+import Slider from "@/components/shared/slider";
+import { nFormatter } from "@/lib/utils";
export default function Tooltip({
children,
@@ -153,3 +156,17 @@ export function OGImageProxy() {
</div>
);
}
+
+export function ProTiers({ usageLimit }: { usageLimit: number }) {
+ const [tier, setTier] = useState(
+ PRO_TIERS.map((t) => t.quota).indexOf(usageLimit)
+ );
+ return (
+ <div className="max-w-md flex flex-col text-center items-center space-y-2 p-5">
+ <Slider value={tier} setValue={setTier} maxValue={PRO_TIERS.length - 1} />
+ <p className="text-gray-600 text-sm">
+ Up to {nFormatter(PRO_TIERS[tier].quota)} link clicks/mo
+ </p>
+ </div>
+ );
+}
diff --git a/lib/auth.ts b/lib/auth.ts
index 67303642c1..89426e4108 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -2,7 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import { unstable_getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import prisma from "@/lib/prisma";
-import { getUsage } from "./upstash";
+import { ProjectProps, UsageProps, UserProps } from "@/lib/types";
interface Session {
user: {
@@ -21,21 +21,27 @@ export async function getSession(req: NextApiRequest, res: NextApiResponse) {
return session;
}
-import { ProjectProps } from "@/lib/types";
-
-interface CustomNextApiHandler {
+interface WithProjectNextApiHandler {
(
req: NextApiRequest,
res: NextApiResponse,
- project: ProjectProps
+ project?: ProjectProps
): Promise<void>;
}
const withProjectAuth =
- (handler: CustomNextApiHandler, extraAuth?: boolean) =>
- // TODO - fix `handler` type when we figure it out
- // `isWriteEditLink` is only true when it's a POST or PUT request for links
- // (you can't add/edit a link when domain is not configured)
+ (
+ handler: WithProjectNextApiHandler,
+ {
+ needVerifiedDomain, // if the action needs a verified domain
+ needProSubscription, // if the action needs a pro subscription
+ needNotExceededUsage, // if the action needs the user to not have exceeded their usage
+ }: {
+ needVerifiedDomain?: boolean;
+ needProSubscription?: boolean;
+ needNotExceededUsage?: boolean;
+ } = {}
+ ) =>
async (req: NextApiRequest, res: NextApiResponse) => {
const session = await getSession(req, res);
if (!session?.user.id) return res.status(401).end("Unauthorized");
@@ -61,31 +67,35 @@ const withProjectAuth =
slug: true,
domain: true,
domainVerified: true,
- plan: true,
- usageLimit: true,
- stripeId: true,
- lastBilled: true,
},
})) as ProjectProps;
if (!project) return res.status(404).json({ error: "Project not found" });
- if (extraAuth && req.method !== "GET") {
- if (!project.domainVerified) {
- return res
- .status(401)
- .end(
- "Unauthorized: Cannot add or edit links when domain is not verified."
- );
- } else {
- const usage = await getUsage(project.domain);
- if (usage > project.usageLimit) {
- return res
- .status(403)
- .end(
- "Unauthorized: Cannot add or edit links when usage limits are exceeded."
- );
- }
+ if (req.method === "GET") return handler(req, res, project);
+
+ if (needVerifiedDomain && !project.domainVerified) {
+ return res.status(403).json({ error: "Domain not verified." });
+ }
+
+ if (needNotExceededUsage || needProSubscription) {
+ const user = (await prisma.user.findUnique({
+ where: {
+ id: session.user.id,
+ },
+ select: {
+ usage: true,
+ usageLimit: true,
+ },
+ })) as UsageProps;
+ const exceededUsage = user.usage >= user.usageLimit;
+ if (needNotExceededUsage && exceededUsage) {
+ return res.status(403).end("Unauthorized: Usage limits exceeded.");
+ }
+
+ const freePlan = user.usageLimit === 1000;
+ if (needProSubscription && freePlan) {
+ return res.status(403).end("Unauthorized: Need pro subscription");
}
}
@@ -93,3 +103,68 @@ const withProjectAuth =
};
export { withProjectAuth };
+
+interface WithUsertNextApiHandler {
+ (
+ req: NextApiRequest,
+ res: NextApiResponse,
+ userId: string,
+ user?: UserProps
+ ): Promise<void>;
+}
+
+const withUserAuth =
+ (
+ handler: WithUsertNextApiHandler,
+ {
+ needUserDetails, // if the action needs the user's details
+ needProSubscription, // if the action needs a pro subscription
+ }: {
+ needUserDetails?: boolean;
+ needProSubscription?: boolean;
+ } = {}
+ ) =>
+ async (req: NextApiRequest, res: NextApiResponse) => {
+ const session = await getSession(req, res);
+ if (!session?.user.id) return res.status(401).end("Unauthorized");
+
+ if (req.method === "GET") return handler(req, res, session.user.id);
+
+ if (needUserDetails || needProSubscription) {
+ const user = (await prisma.user.findUnique({
+ where: {
+ id: session.user.id,
+ },
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ stripeId: true,
+ usageLimit: true,
+ ...(needProSubscription && {
+ projects: {
+ where: {
+ role: "owner",
+ },
+ select: {
+ projectId: true,
+ },
+ },
+ }),
+ },
+ })) as UserProps;
+
+ const freePlan = user.usageLimit === 1000;
+ if (needProSubscription && freePlan && user.projects.length === 1) {
+ return res
+ .status(403)
+ .end("Unauthorized: Can't add more projects, need pro subscription");
+ }
+
+ return handler(req, res, session.user.id, user);
+ }
+
+ return handler(req, res, session.user.id);
+ };
+
+export { withUserAuth };
diff --git a/lib/constants.ts b/lib/constants.ts
index 228ddf73f3..30e9e784b4 100644
--- a/lib/constants.ts
+++ b/lib/constants.ts
@@ -13,6 +13,44 @@ export const FRAMER_MOTION_LIST_ITEM_VARIANTS = {
show: { scale: 1, opacity: 1, transition: { type: "spring" } },
};
+export const PLAN_FROM_USAGE_LIMIT = {
+ 1000: "Free",
+ 10000: "Pro 10K",
+ 25000: "Pro 25K",
+ 50000: "Pro 50K",
+ 100000: "Pro 100K",
+ 500000: "Pro 500K",
+ 1000000: "Pro 1M",
+ 5000000: "Enterprise 5M",
+};
+
+export const PRO_TIERS = [
+ {
+ price: 9,
+ quota: 10000,
+ },
+ {
+ price: 19,
+ quota: 25000,
+ },
+ {
+ price: 29,
+ quota: 50000,
+ },
+ {
+ price: 49,
+ quota: 100000,
+ },
+ {
+ price: 79,
+ quota: 500000,
+ },
+ {
+ price: 99,
+ quota: 1000000,
+ },
+];
+
export const HOME_HOSTNAMES = new Set([
// comment for better diffs
"dub.sh",
@@ -48,6 +86,7 @@ export const DEFAULT_REDIRECTS = {
app: "https://app.dub.sh",
dashboard: "https://app.dub.sh",
links: "https://app.dub.sh/links",
+ settings: "https://app.dub.sh/settings",
};
export const COUNTRIES: { [key: string]: string } = {
diff --git a/lib/cron.ts b/lib/cron.ts
index 5ddcac81b5..051058b616 100644
--- a/lib/cron.ts
+++ b/lib/cron.ts
@@ -1,5 +1,5 @@
import prisma from "@/lib/prisma";
-import { redis, deleteProject } from "@/lib/upstash";
+import { redis, deleteProject, getUsage } from "@/lib/upstash";
import { removeDomain } from "./domains";
export const handleDomainUpdates = async (
@@ -45,6 +45,87 @@ export const handleDomainUpdates = async (
return;
};
+export const updateProjectUsage = async () => {
+ const projects = await prisma.project.findMany({
+ select: {
+ domain: true,
+ },
+ where: {
+ domainVerified: true,
+ },
+ });
+
+ const response = await Promise.all(
+ projects.map(async ({ domain }) => {
+ const usage = await getUsage(domain);
+ return await prisma.project.update({
+ where: {
+ domain,
+ },
+ data: {
+ usage,
+ },
+ });
+ })
+ );
+
+ return response;
+};
+
+export const updateUsage = async () => {
+ const users = await prisma.user.findMany({
+ select: {
+ id: true,
+ email: true,
+ usageLimit: true,
+ lastBilled: true,
+ projects: {
+ select: {
+ project: {
+ select: {
+ domain: true,
+ },
+ },
+ },
+ where: {
+ role: "owner",
+ },
+ },
+ },
+ });
+
+ const response = await Promise.all(
+ users.map(async ({ id, email, usageLimit, lastBilled, projects }) => {
+ // if user has no projects, don't update usage
+ if (projects.length === 0) return;
+
+ const usageArr = await Promise.all(
+ projects.map(async ({ project: { domain } }) => {
+ return await getUsage(domain, lastBilled);
+ })
+ );
+ const totalUsage = usageArr.reduce((a, b) => a + b, 0);
+
+ if (totalUsage > usageLimit) {
+ await log(
+ `${email} is over usage limit. Usage: ${totalUsage}, Limit: ${usageLimit}`
+ );
+ }
+
+ return await prisma.user.update({
+ where: {
+ id,
+ },
+ data: {
+ usage: totalUsage,
+ },
+ });
+ })
+ );
+
+ return response;
+};
+
export const log = async (message: string) => {
/* Log a message to the console */
if (!process.env.DUB_SLACK_HOOK) return;
diff --git a/lib/swr/use-usage.ts b/lib/swr/use-usage.ts
index 5f0d62e66f..18d120e135 100644
--- a/lib/swr/use-usage.ts
+++ b/lib/swr/use-usage.ts
@@ -1,36 +1,32 @@
import useSWR from "swr";
import { useMemo } from "react";
import { fetcher } from "@/lib/utils";
-import { useRouter } from "next/router";
-import { ProjectProps } from "@/lib/types";
+import { UsageProps } from "@/lib/types";
+import { PLAN_FROM_USAGE_LIMIT } from "../constants";
-export default function useUsage(project: ProjectProps) {
- const router = useRouter();
-
- const { slug } = router.query as {
- slug: string;
- };
-
- const { data: usage, error } = useSWR<number>(
- router.isReady &&
- project &&
- `/api/projects/${slug}/domains/${project.domain}/usage`,
- fetcher,
- {
- dedupingInterval: 10000,
- }
+export default function useUsage({ settingsPage } = { settingsPage: false }) {
+ const { data, error } = useSWR<UsageProps>(
+ `/api/usage${settingsPage ? "?settingsPage=1" : ""}`,
+ fetcher
);
const exceededUsage = useMemo(() => {
- if (usage && project) {
- return usage > project?.usageLimit;
+ if (data) {
+ return data.usage > data.usageLimit;
+ }
+ }, [data]);
+
+ const plan = useMemo(() => {
+ if (data) {
+ return PLAN_FROM_USAGE_LIMIT[data.usageLimit];
}
- }, [usage, project]);
+ }, [data]);
return {
- usage,
+ data,
exceededUsage,
- loading: !error && !usage,
+ plan,
+ loading: !error && !data,
error,
};
}
diff --git a/lib/types.ts b/lib/types.ts
index 4615c838e1..8debb308e7 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -19,6 +19,22 @@ export interface ProjectProps {
domainVerified: boolean;
}
+export interface UsageProps {
+ usage: number;
+ usageLimit: number;
+ projectCount?: number;
+ lastBilled?: number;
+}
+
+export interface UserProps {
+ id: string;
+ name: string;
+ email: string;
+ stripeId: string;
+ usageLimit: number;
+ projects?: { projectId: string }[];
+}
+
export type DomainVerificationStatusProps =
| "Valid Configuration"
| "Invalid Configuration"
diff --git a/lib/upstash.ts b/lib/upstash.ts
index 2b9fc332cc..b9719e6729 100644
--- a/lib/upstash.ts
+++ b/lib/upstash.ts
@@ -246,8 +246,14 @@ export async function deleteLink(domain: string, key: string, userId?: string) {
return await pipeline.exec();
}
-export async function getUsage(userId: string, projects: ProjectProps[]) {
- const cachedUsage = await redis.get(`usage:${userId}`);
+/**
+ * Get the usage for a project
+ **/
+export async function getUsage(
+ hostname: string,
+ billingCycleStart?: Date
+): Promise<number> {
+ const cachedUsage = await redis.get<number>(`usage:${hostname}`);
if (cachedUsage) {
return cachedUsage;
}
diff --git a/pages/api/cron/usage.ts b/pages/api/cron/usage.ts
new file mode 100644
index 0000000000..c49568980e
--- /dev/null
+++ b/pages/api/cron/usage.ts
@@ -0,0 +1,32 @@
+import type { NextApiRequest, NextApiResponse } from "next";
+import { verifySignature } from "@upstash/qstash/nextjs";
+import { updateUsage } from "@/lib/cron";
+
+/**
+ * Cron to update the usage stats of each project.
+ * Runs once a day.
+ * TODO: Update the aggregated usage stats for a user and send them an email if they're over their limit.
+ **/
+
+async function handler(_req: NextApiRequest, res: NextApiResponse) {
+ try {
+ const results = await updateUsage();
+ res.status(200).json(results);
+ } catch (error) {
+ res.status(500).json({ error: error.message });
+ }
+}
+
+/**
+ * verifySignature will try to load `QSTASH_CURRENT_SIGNING_KEY` and `QSTASH_NEXT_SIGNING_KEY` from the environment.
+
+ * To test out the endpoint manually (wihtout using QStash), you can do `export default handler` instead and
+ * hit this endpoint via http://localhost:3000/api/cron/domains
+ */
+export default verifySignature(handler);
+
+export const config = {
+ api: {
+ bodyParser: false,
+ },
+};
diff --git a/pages/api/projects/[slug]/domains/[domain]/index.ts b/pages/api/projects/[slug]/domains/[domain]/index.ts
index 8f541544fb..8ebaf7a7f4 100644
--- a/pages/api/projects/[slug]/domains/[domain]/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/index.ts
@@ -7,6 +7,7 @@ import { addDomain, removeDomain } from "@/lib/domains";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
+ // PUT /api/projects/[slug]/domains/[domain] edit a project's domain
if (req.method === "PUT") {
const { slug, domain } = req.query as { slug: string; domain: string }; // slug is the domain
const newDomain = req.body;
diff --git a/pages/api/projects/[slug]/domains/[domain]/links/[key]/clicks.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/clicks.ts
index 0a209f6cf0..c8f28dbdfe 100644
--- a/pages/api/projects/[slug]/domains/[domain]/links/[key]/clicks.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/clicks.ts
@@ -4,6 +4,7 @@ import { getLinkClicksCount, redis } from "@/lib/upstash";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
+ // GET /api/projects/[slug]/domains/[domain]/links/[key]/clicks - get link clicks
if (req.method === "GET") {
const { domain, key } = req.query as { domain: string; key: string };
const response = await getLinkClicksCount(domain, key);
diff --git a/pages/api/projects/[slug]/domains/[domain]/links/[key]/exists.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/exists.ts
index efb6ab316e..fea3bbf0ef 100644
--- a/pages/api/projects/[slug]/domains/[domain]/links/[key]/exists.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/exists.ts
@@ -4,6 +4,7 @@ import { withProjectAuth } from "@/lib/auth";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
+ // GET /api/projects/[slug]/domains/[domain]/links/[key]/exists - check if a key exists
if (req.method === "GET") {
const { domain, key } = req.query as { domain: string; key: string };
const response = await checkIfKeyExists(domain, key);
diff --git a/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts
index 2596aa2db4..57bfc1a1c5 100644
--- a/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts
@@ -15,7 +15,7 @@ export default withProjectAuth(
key: string;
};
- // PUT /api/projects/[slug]/domains/[domain]/links/[key] - edit link
+ // PUT /api/projects/[slug]/domains/[domain]/links/[key] - edit a link
if (req.method === "PUT") {
let { key, url, title, timestamp, description, image } = req.body;
if (!key || !url || !title || !timestamp) {
@@ -69,5 +69,8 @@ export default withProjectAuth(
.json({ error: `Method ${req.method} Not Allowed` });
}
},
- true
+ {
+ needVerifiedDomain: true,
+ needNotExceededUsage: true,
+ }
);
diff --git a/pages/api/projects/[slug]/domains/[domain]/links/[key]/stats.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/stats.ts
index 0311ae19a1..ad522682b6 100644
--- a/pages/api/projects/[slug]/domains/[domain]/links/[key]/stats.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/stats.ts
@@ -10,6 +10,7 @@ import {
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
+ // GET /api/projects/[slug]/domains/[domain]/links/[key]/stats - get link stats
if (req.method === "GET") {
const { domain, key, interval } = req.query as {
domain: string;
diff --git a/pages/api/projects/[slug]/domains/[domain]/links/index.ts b/pages/api/projects/[slug]/domains/[domain]/links/index.ts
index 062dc24b97..8179925b01 100644
--- a/pages/api/projects/[slug]/domains/[domain]/links/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/index.ts
@@ -44,5 +44,8 @@ export default withProjectAuth(
.json({ error: `Method ${req.method} Not Allowed` });
}
},
- true
+ {
+ needVerifiedDomain: true,
+ needNotExceededUsage: true,
+ }
);
diff --git a/pages/api/projects/[slug]/domains/[domain]/root/clicks.ts b/pages/api/projects/[slug]/domains/[domain]/root/clicks.ts
index 71053f5932..4658607bda 100644
--- a/pages/api/projects/[slug]/domains/[domain]/root/clicks.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/root/clicks.ts
@@ -19,6 +19,5 @@ export default withProjectAuth(
.status(405)
.json({ error: `Method ${req.method} Not Allowed` });
}
- },
- true
+ }
);
diff --git a/pages/api/projects/[slug]/domains/[domain]/root/index.ts b/pages/api/projects/[slug]/domains/[domain]/root/index.ts
index 45893d8b0d..455d5858e1 100644
--- a/pages/api/projects/[slug]/domains/[domain]/root/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/root/index.ts
@@ -23,5 +23,10 @@ export default withProjectAuth(
.json({ error: `Method ${req.method} Not Allowed` });
}
},
- true
+ {
+ needVerifiedDomain: true,
+ needNotExceededUsage: true,
+ // TODO: For when we make this a pro feature
+ // needProSubscription: true,
+ }
);
diff --git a/pages/api/projects/[slug]/domains/[domain]/verify.ts b/pages/api/projects/[slug]/domains/[domain]/verify.ts
index f49c75f057..c94e9f44d3 100644
--- a/pages/api/projects/[slug]/domains/[domain]/verify.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/verify.ts
@@ -10,6 +10,7 @@ import {
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
+ // GET /api/projects/[slug]/domains/[domain]/verify - get domain verification status
if (req.method === "GET") {
const { slug, domain } = req.query as { slug: string; domain: string };
let status: DomainVerificationStatusProps = "Valid Configuration";
diff --git a/pages/api/projects/[slug]/index.ts b/pages/api/projects/[slug]/index.ts
index f03daad64c..e212850447 100644
--- a/pages/api/projects/[slug]/index.ts
+++ b/pages/api/projects/[slug]/index.ts
@@ -14,10 +14,10 @@ export default withProjectAuth(
.json({ error: "Missing or misconfigured project slug" });
}
- // GET /api/projects/[slug] – get a specific project with it's links
+ // GET /api/projects/[slug] – get a specific project
if (req.method === "GET") {
return res.status(200).json(project);
- // DELETE /api/projects/[slug] – edit a project
+ // DELETE /api/projects/[slug] – delete a project
} else if (req.method === "DELETE") {
const domain = req.body;
if (!domain || typeof domain !== "string") {
diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.ts
index 93b0c858ab..353c3536f1 100644
--- a/pages/api/projects/index.ts
+++ b/pages/api/projects/index.ts
@@ -1,96 +1,99 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { getSession } from "@/lib/auth";
+import { getSession, withUserAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { validDomainRegex } from "@/lib/utils";
import { addDomain, removeDomain } from "@/lib/domains";
import { RESERVED_KEYS, DEFAULT_REDIRECTS } from "@/lib/constants";
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse
-) {
- const session = await getSession(req, res);
- if (!session?.user.id) return res.status(401).end("Unauthorized");
-
- // GET /api/projects – get all projects associated with the authenticated user
- if (req.method === "GET") {
- const response = await prisma.project.findMany({
- where: {
- users: {
- some: {
- userId: session.user.id,
- },
- },
- },
- });
- return res.status(200).json(response);
-
- // POST /api/projects – create a new project
- } else if (req.method === "POST") {
- const { name, slug, domain } = req.body;
- if (!name || !slug || !domain) {
- return res.status(422).json({ error: "Missing name or slug or domain" });
- }
- let slugError = null;
- if (slug.includes(" ") || slug.includes(".")) {
- slugError = "Slug cannot contain spaces or periods";
- } else if (RESERVED_KEYS.has(slug) || DEFAULT_REDIRECTS[slug]) {
- slugError = "Cannot use reserved slugs";
- }
- const validDomain =
- validDomainRegex.test(domain) && !domain.endsWith(".dub.sh");
- if (slugError || !validDomain) {
- return res.status(422).json({
- slugError,
- domainError: validDomain ? null : "Invalid domain",
- });
- }
- const [slugExist, domainExist] = await Promise.all([
- prisma.project.findUnique({
- where: {
- slug,
- },
- select: {
- slug: true,
- },
- }),
- prisma.project.findUnique({
+export default withUserAuth(
+ async (req: NextApiRequest, res: NextApiResponse, userId: string) => {
+ // GET /api/projects – get all projects associated with the authenticated user
+ if (req.method === "GET") {
+ const response = await prisma.project.findMany({
where: {
- domain,
- },
- select: {
- domain: true,
+ users: {
+ some: {
+ userId,
+ },
+ },
},
- }),
- ]);
- if (slugExist || domainExist) {
- return res.status(422).json({
- slugError: slugExist ? "Slug is already in use." : null,
- domainError: domainExist ? "Domain is already in use." : null,
});
- }
+ return res.status(200).json(response);
- const [prismaResponse, domainResponse] = await Promise.all([
- prisma.project.create({
- data: {
- name,
- slug,
- domain,
- users: {
- create: {
- userId: session.user.id,
- role: "owner",
+ // POST /api/projects – create a new project
+ } else if (req.method === "POST") {
+ const { name, slug, domain } = req.body;
+ if (!name || !slug || !domain) {
+ return res
+ .status(422)
+ .json({ error: "Missing name or slug or domain" });
+ }
+ let slugError = null;
+ if (slug.includes(" ") || slug.includes(".")) {
+ slugError = "Slug cannot contain spaces or periods";
+ } else if (RESERVED_KEYS.has(slug) || DEFAULT_REDIRECTS[slug]) {
+ slugError = "Cannot use reserved slugs";
+ }
+ const validDomain =
+ validDomainRegex.test(domain) && !domain.endsWith(".dub.sh");
+ if (slugError || !validDomain) {
+ return res.status(422).json({
+ slugError,
+ domainError: validDomain ? null : "Invalid domain",
+ });
+ }
+ const [slugExist, domainExist] = await Promise.all([
+ prisma.project.findUnique({
+ where: {
+ slug,
+ },
+ select: {
+ slug: true,
+ },
+ }),
+ prisma.project.findUnique({
+ where: {
+ domain,
+ },
+ select: {
+ domain: true,
+ },
+ }),
+ ]);
+ if (slugExist || domainExist) {
+ return res.status(422).json({
+ slugError: slugExist ? "Slug is already in use." : null,
+ domainError: domainExist ? "Domain is already in use." : null,
+ });
+ }
+
+ const [prismaResponse, domainResponse] = await Promise.all([
+ prisma.project.create({
+ data: {
+ name,
+ slug,
+ domain,
+ users: {
+ create: {
+ userId,
+ role: "owner",
+ },
},
},
- },
- }),
- addDomain(domain),
- ]);
- return res
- .status(200)
- .json({ project: prismaResponse, domain: domainResponse });
- } else {
- res.setHeader("Allow", ["GET", "POST"]);
- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }),
+ addDomain(domain),
+ ]);
+ return res
+ .status(200)
+ .json({ project: prismaResponse, domain: domainResponse });
+ } else {
+ res.setHeader("Allow", ["GET", "POST"]);
+ return res
+ .status(405)
+ .json({ error: `Method ${req.method} Not Allowed` });
+ }
+ },
+ {
+ needProSubscription: true,
}
-}
+);
diff --git a/pages/api/projects/usage.ts b/pages/api/projects/usage.ts
deleted file mode 100644
index 12d5895246..0000000000
--- a/pages/api/projects/usage.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-import { getSession } from "@/lib/auth";
-import { getUsage } from "@/lib/upstash";
-import { ProjectProps } from "@/lib/types";
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
- project: ProjectProps
-) {
- const session = await getSession(req, res);
- if (!session?.user.id) return res.status(401).end("Unauthorized");
-
- // GET /api/projects/usage – get a user's usage over all their projects
- if (req.method === "GET") {
- const projects = await prisma.project.findMany({
- where: {
- users: {
- some: {
- userId: session.user.id,
- },
- },
- },
- });
- const usage = projects ? await getUsage(session.user.id, projects) : 0;
- return res.status(200).json(usage);
- } else {
- res.setHeader("Allow", ["GET"]);
- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
- }
-}
diff --git a/pages/api/projects/[slug]/manage-subscription.ts b/pages/api/stripe/manage-subscription.ts
similarity index 65%
rename from pages/api/projects/[slug]/manage-subscription.ts
rename to pages/api/stripe/manage-subscription.ts
index 61c375bc2d..106f500555 100644
--- a/pages/api/projects/[slug]/manage-subscription.ts
+++ b/pages/api/stripe/manage-subscription.ts
@@ -1,15 +1,20 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { withProjectAuth } from "@/lib/auth";
+import { withUserAuth } from "@/lib/auth";
import { stripe } from "@/lib/stripe";
-import { ProjectProps } from "@/lib/types";
+import { UserProps } from "@/lib/types";
-export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
- // POST /api/projects/[slug]/upgrade – upgrade a project
+export default withUserAuth(
+ async (
+ req: NextApiRequest,
+ res: NextApiResponse,
+ userId: string,
+ user: UserProps
+ ) => {
+ // POST /api/stripe/manage-subscription – manage a user's subscription
if (req.method === "POST") {
const { slug } = req.query as { slug: string };
const { url } = await stripe.billingPortal.sessions.create({
- customer: project.stripeId,
+ customer: user.stripeId,
return_url: `${
process.env.VERCEL === "1"
? "https://app.dub.sh"
diff --git a/pages/api/projects/[slug]/upgrade.ts b/pages/api/stripe/upgrade.ts
similarity index 86%
rename from pages/api/projects/[slug]/upgrade.ts
rename to pages/api/stripe/upgrade.ts
index 24836b882b..752d310408 100644
--- a/pages/api/projects/[slug]/upgrade.ts
+++ b/pages/api/stripe/upgrade.ts
@@ -1,10 +1,10 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { withProjectAuth } from "@/lib/auth";
+import { withProjectAuth, withUserAuth } from "@/lib/auth";
import { stripe } from "@/lib/stripe";
-export default withProjectAuth(
+export default withUserAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
- // POST /api/projects/[slug]/upgrade – upgrade a project
+ // POST /api/stripe/upgrade – upgrade a user's account from free to pro
if (req.method === "POST") {
const { slug } = req.query as { slug: string };
const session = await stripe.checkout.sessions.create({
diff --git a/pages/api/usage/index.ts b/pages/api/usage/index.ts
new file mode 100644
index 0000000000..137574a16c
--- /dev/null
+++ b/pages/api/usage/index.ts
@@ -0,0 +1,42 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { withUserAuth } from "@/lib/auth";
+
+export default withUserAuth(
+ async (req: NextApiRequest, res: NextApiResponse, userId: string) => {
+ // GET /api/usage – get a user's usage over all the projects they're an owner of
+ if (req.method === "GET") {
+ const { settingsPage } = req.query as {
+ settingsPage: string;
+ };
+ const response = await prisma.user.findUnique({
+ where: {
+ id: userId,
+ },
+ select: {
+ usage: true,
+ usageLimit: true,
+ ...(settingsPage === "1" && {
+ lastBilled: true,
+ projects: {
+ where: {
+ role: "owner",
+ },
+ },
+ }),
+ },
+ });
+ return res.status(200).json({
+ ...response,
+ ...(settingsPage === "1" && {
+ projects: undefined,
+ projectCount: response.projects.length || "0",
+ }),
+ });
+ } else {
+ res.setHeader("Allow", ["GET"]);
+ return res
+ .status(405)
+ .json({ error: `Method ${req.method} Not Allowed` });
+ }
+ }
+);
diff --git a/pages/app/[slug]/settings.tsx b/pages/app/[slug]/settings.tsx
index aaa1dcc88f..cb0650234e 100644
--- a/pages/app/[slug]/settings.tsx
+++ b/pages/app/[slug]/settings.tsx
@@ -3,7 +3,6 @@ import useProject from "@/lib/swr/use-project";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
import CustomDomain from "@/components/app/settings/custom-domain";
import DefaultPage from "@/components/app/settings/landing-page";
-import PlanUsage from "@/components/app/settings/plan-usage";
import ErrorPage from "next/error";
import DeleteProject from "@/components/app/settings/delete-project";
@@ -26,7 +25,6 @@ export default function ProjectLinks() {
</div>
<MaxWidthWrapper>
<div className="py-10 grid gap-5">
- <PlanUsage />
<CustomDomain />
<DefaultPage />
<DeleteProject />
diff --git a/pages/app/index.tsx b/pages/app/index.tsx
index 793df4db13..cb314939ae 100644
--- a/pages/app/index.tsx
+++ b/pages/app/index.tsx
@@ -7,10 +7,13 @@ import ProjectCard from "@/components/app/project-card";
import { useAddProjectModal } from "@/components/app/modals/add-project-modal";
import NoProjectsPlaceholder from "@/components/app/no-projects-placeholder";
import ProjectCardPlaceholder from "@/components/app/project-card-placeholder";
+import useUsage from "@/lib/swr/use-usage";
+import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
export default function App() {
const { data } = useSWR<ProjectProps[]>(`/api/projects`, fetcher);
const { setShowAddProjectModal, AddProjectModal } = useAddProjectModal({});
+ const { plan } = useUsage();
return (
<AppLayout>
@@ -19,12 +22,28 @@ export default function App() {
<MaxWidthWrapper>
<div className="flex justify-between items-center">
<h1 className="text-2xl text-gray-600">My Projects</h1>
- <button
- onClick={() => setShowAddProjectModal(true)}
- className="text-white hover:text-black bg-black hover:bg-white active:scale-95 font-medium text-sm px-5 py-2 border rounded-md border-black transition-all duration-75"
- >
- Add
- </button>
+ {plan === "Free" && data.length >= 1 ? (
+ <Tooltip
+ content={
+ <TooltipContent
+ title="You can only have 1 project on the Free plan. Upgrade to the Pro plan create more."
+ cta="Upgrade"
+ ctaLink={`/settings`}
+ />
+ }
+ >
+ <div className="text-gray-300 cursor-not-allowed font-medium text-sm px-5 py-2 border rounded-md border-gray-200 transition-all duration-75">
+ Add
+ </div>
+ </Tooltip>
+ ) : (
+ <button
+ onClick={() => setShowAddProjectModal(true)}
+ className="text-white hover:text-black bg-black hover:bg-white active:scale-95 font-medium text-sm px-5 py-2 border rounded-md border-black transition-all duration-75"
+ >
+ Add
+ </button>
+ )}
</div>
</MaxWidthWrapper>
</div>
diff --git a/pages/app/settings.tsx b/pages/app/settings.tsx
index a4f1d200cd..518b6d8d89 100644
--- a/pages/app/settings.tsx
+++ b/pages/app/settings.tsx
@@ -1,9 +1,22 @@
import AppLayout from "components/layout/app";
+import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
+import PlanUsage from "@/components/app/settings/plan-usage";
export default function Settings() {
return (
<AppLayout>
- <h1>Settings</h1>
+ <div className="h-36 flex items-center bg-white border-b border-gray-200">
+ <MaxWidthWrapper>
+ <div className="flex justify-between items-center">
+ <h1 className="text-2xl text-gray-600">Settings</h1>
+ </div>
+ </MaxWidthWrapper>
+ </div>
+ <MaxWidthWrapper>
+ <div className="py-10 grid gap-5">
+ <PlanUsage />
+ </div>
+ </MaxWidthWrapper>
</AppLayout>
);
}
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 7a6e574c6e..136f9843aa 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -18,7 +18,9 @@ model User {
email String? @unique
emailVerified DateTime?
image String?
- stripeId String? @unique // Stripe customer ID
+ stripeId String? @unique // Stripe customer ID
+ usage Int @default(0)
+ usageLimit Int @default(1000)
lastBilled DateTime?
accounts Account[]
sessions Session[]