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.

New pricing (2024)

Steven Tey09d47460012b
diff --git a/apps/web/app/api/callback/stripe/route.ts b/apps/web/app/api/callback/stripe/route.ts
index aafaf2b8fd..89e037d047 100644
--- a/apps/web/app/api/callback/stripe/route.ts
+++ b/apps/web/app/api/callback/stripe/route.ts
@@ -1,7 +1,7 @@
import { limiter } from "@/lib/cron";
import prisma from "@/lib/prisma";
import { stripe } from "@/lib/stripe";
-import { getPlanFromPriceId, isUpgrade } from "@/lib/stripe/utils";
+import { PRO_PLAN } from "@/lib/stripe/utils";
import { redis } from "@/lib/upstash";
import { log } from "@dub/utils";
import { resend, sendEmail } from "emails";
@@ -47,12 +47,17 @@ export const POST = async (req: Request) => {
return;
}
- const stripeId = checkoutSession.customer.toString();
const subscription = await stripe.subscriptions.retrieve(
checkoutSession.subscription as string,
);
- const plan = getPlanFromPriceId(subscription.items.data[0].price.id);
- const usageLimit = plan.quota;
+ const priceId = subscription.items.data[0].price.id;
+
+ // we only process webhooks for pro plan
+ if (!PRO_PLAN.priceIds.includes(priceId)) {
+ return;
+ }
+
+ const stripeId = checkoutSession.customer.toString();
// when the project subscribes to a plan, set their stripe customer ID
// in the database for easy identification in future webhook events
@@ -65,8 +70,9 @@ export const POST = async (req: Request) => {
data: {
stripeId,
billingCycleStart: new Date().getDate(),
- usageLimit,
- plan: plan.slug,
+ usageLimit: PRO_PLAN.usageLimit,
+ linksLimit: PRO_PLAN.linksLimit,
+ plan: "pro",
},
select: {
users: {
@@ -92,11 +98,11 @@ export const POST = async (req: Request) => {
limiter.schedule(() =>
sendEmail({
email: user.email as string,
- subject: `Thank you for upgrading to Dub ${plan.name}!`,
+ subject: `Thank you for upgrading to Dub.co Pro!`,
react: UpgradeEmail({
name: user.name,
email: user.email as string,
- plan: plan.name,
+ plan: "pro",
}),
marketing: true,
}),
@@ -109,10 +115,12 @@ export const POST = async (req: Request) => {
if (event.type === "customer.subscription.updated") {
const subscriptionUpdated = event.data.object as Stripe.Subscription;
const priceId = subscriptionUpdated.items.data[0].price.id;
- const upgraded = isUpgrade(event.data.previous_attributes);
- const plan = getPlanFromPriceId(priceId);
- const usageLimit = plan.quota;
+ // we only process webhooks for pro plan
+ if (!PRO_PLAN.priceIds.includes(priceId)) {
+ return;
+ }
+
const stripeId = subscriptionUpdated.customer.toString();
const project = await prisma.project.findUnique({
@@ -133,13 +141,14 @@ export const POST = async (req: Request) => {
}
// If a project upgrades/downgrades their subscription, update their usage limit in the database.
- const updatedProject = await prisma.project.update({
+ await prisma.project.update({
where: {
stripeId,
},
data: {
- usageLimit,
- plan: plan.slug,
+ usageLimit: PRO_PLAN.usageLimit,
+ linksLimit: PRO_PLAN.linksLimit,
+ plan: "pro",
},
select: {
users: {
@@ -154,31 +163,6 @@ export const POST = async (req: Request) => {
},
},
});
-
- // if it's an upgrade from Pro to Enterprise
- if (upgraded) {
- const users = updatedProject.users.map(({ user }) => ({
- name: user.name,
- email: user.email,
- }));
-
- await Promise.allSettled(
- users.map((user) => {
- limiter.schedule(() =>
- sendEmail({
- email: user.email as string,
- subject: `Thank you for upgrading to Dub ${plan.name}!`,
- react: UpgradeEmail({
- name: user.name,
- email: user.email as string,
- plan: plan.name,
- }),
- marketing: true,
- }),
- );
- }),
- );
- }
}
// If project cancels their subscription
diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.ts
index 81380fcabf..c7519dd559 100644
--- a/apps/web/app/api/links/bulk/route.ts
+++ b/apps/web/app/api/links/bulk/route.ts
@@ -1,6 +1,8 @@
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";
// POST /api/links/bulk – bulk create up to 100 links
export const POST = withAuth(
@@ -29,6 +31,22 @@ 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) {
+ return new Response(
+ `You can only create ${
+ project.linksLimit
+ } short links on the ${project.plan.toUpperCase()} plan. Upgrade to create more links.`,
+ { status: 403, headers },
+ );
+ }
const processedLinks = await Promise.all(
links.map(async (link) =>
diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.ts
index 92526752a5..8cf4fac86c 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,
+ getBillingStartDate,
getDomainWithoutWWW,
getParamsFromURL,
getUrlFromString,
@@ -287,6 +288,23 @@ 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) {
+ return {
+ link: payload,
+ error: `You can only create ${
+ project.linksLimit
+ } short links on the ${project.plan.toUpperCase()} plan. Upgrade to create more links.`,
+ status: 403,
+ };
+ }
// internal Dub.co checks
} else if (process.env.NEXT_PUBLIC_IS_DUB) {
// if it's not a custom project, do some filtering
diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.ts
index cc97bd5d1f..873b01b7ae 100644
--- a/apps/web/lib/auth/index.ts
+++ b/apps/web/lib/auth/index.ts
@@ -209,6 +209,7 @@ export const withAuth =
logo: true,
usage: true,
usageLimit: true,
+ linksLimit: true,
plan: true,
stripeId: true,
billingCycleStart: true,
diff --git a/apps/web/lib/stripe/utils.ts b/apps/web/lib/stripe/utils.ts
index eeeaeefe6c..7a84399cb0 100644
--- a/apps/web/lib/stripe/utils.ts
+++ b/apps/web/lib/stripe/utils.ts
@@ -1,77 +1,24 @@
-export function getPlanFromPriceId(priceId: string) {
- const env =
- process.env.NEXT_PUBLIC_VERCEL_ENV === "production" ? "production" : "test";
- return PLANS.find(
- (plan) =>
- plan.price.monthly.priceIds[env] === priceId ||
- plan.price.yearly.priceIds[env] === priceId,
- )!;
-}
-
-// custom type coercion because Stripe's types are wrong
-export function isUpgrade(
- previousAttributes:
- | {
- default_payment_method?: string;
- items?: {
- data?: {
- price?: {
- id?: string;
- }[];
- };
- };
- }
- | undefined,
-) {
- const oldPriceId =
- previousAttributes?.items?.data &&
- previousAttributes?.items?.data[0].price.id;
-
- //
- return oldPriceId && getPlanFromPriceId(oldPriceId).slug === "pro";
-}
-
-export const PLANS = [
- {
- name: "Pro",
- slug: "pro",
- quota: 50000,
- price: {
- monthly: {
- amount: 9,
- priceIds: {
- test: "price_1LoytoAlJJEpqkPV2oPcQ63m",
- production: "price_1LodNLAlJJEpqkPVQSrt33Lc",
- },
- },
- yearly: {
- amount: 90,
- priceIds: {
- test: "price_1LoytoAlJJEpqkPVsWjM4tB9",
- production: "price_1LodNLAlJJEpqkPVRxUyCQgZ",
- },
- },
+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",
},
},
- {
- name: "Enterprise",
- slug: "enterprise",
- quota: 1000000000, // arbitrary large number to represent unlimited – might need to change this in the future
- price: {
- monthly: {
- amount: 49,
- priceIds: {
- test: "price_1LoyrCAlJJEpqkPVZ32BV3wm",
- production: "price_1LodLoAlJJEpqkPV9rD0rlNL",
- },
- },
- yearly: {
- amount: 490,
- priceIds: {
- test: "price_1LoyrCAlJJEpqkPVgIlNG23q",
- production: "price_1LodLoAlJJEpqkPVJdwv5zrG",
- },
- },
+ yearly: {
+ amount: 264,
+ priceIds: {
+ test: "price_1LoytoAlJJEpqkPVsWjM4tB9",
+ production: "price_1LodNLAlJJEpqkPVRxUyCQgZ",
},
},
-];
+};
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index ecf8664dfd..5e3e562bdf 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -43,9 +43,10 @@ export interface ProjectProps {
logo?: string;
usage: number;
usageLimit: number;
+ linksLimit: number;
plan: PlanProps;
stripeId?: string;
- billingCycleStart?: number;
+ billingCycleStart: number;
createdAt?: Date;
domains?: {
slug: string;
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index c7d205cd14..fd353f1887 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -90,10 +90,11 @@ model Project {
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
- monitoringId String? @unique // cron job ID for monitoring
+ billingCycleStart Int // day of the month when the billing cycle starts
+ monitoringId String? @unique // cron job ID for monitoring
sentEmails SentEmail[]
domains Domain[]
diff --git a/apps/web/ui/links/link-card.tsx b/apps/web/ui/links/link-card.tsx
index 4f83aad26b..41b4e08eb6 100644
--- a/apps/web/ui/links/link-card.tsx
+++ b/apps/web/ui/links/link-card.tsx
@@ -179,7 +179,6 @@ export default function LinkCard({
// - the key pressed is one of the shortcuts
// - there is no existing modal backdrop
if (
- !exceededUsage &&
(selected || openPopover) &&
["e", "d", "q", "a", "x"].includes(e.key)
) {
@@ -417,86 +416,33 @@ export default function LinkCard({
<Popover
content={
<div className="grid w-full gap-px p-2 sm:w-48">
- {slug && exceededUsage ? (
- <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 edit them."
- cta="Upgrade to Pro"
- onClick={() => {
- setOpenPopover(false);
- setShowUpgradePlanModal(true);
- }}
- />
- }
- >
- <div className="flex w-full cursor-not-allowed items-center justify-between p-2 text-left text-sm font-medium text-gray-300 transition-all duration-75">
- <IconMenu
- text="Edit"
- icon={<Edit3 className="h-4 w-4" />}
- />
- <kbd className="hidden rounded bg-gray-100 px-2 py-0.5 text-xs font-light text-gray-300 transition-all duration-75 sm:inline-block">
- E
- </kbd>
- </div>
- </Tooltip>
- ) : (
- <button
- onClick={() => {
- setOpenPopover(false);
- setShowAddEditLinkModal(true);
- }}
- className="group flex w-full items-center justify-between rounded-md p-2 text-left text-sm font-medium text-gray-500 transition-all duration-75 hover:bg-gray-100"
- >
- <IconMenu
- text="Edit"
- icon={<Edit3 className="h-4 w-4" />}
- />
- <kbd className="hidden rounded bg-gray-100 px-2 py-0.5 text-xs font-light text-gray-500 transition-all duration-75 group-hover:bg-gray-200 sm:inline-block">
- E
- </kbd>
- </button>
- )}
- {slug && exceededUsage ? (
- <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 create a new link."
- cta="Upgrade to Pro"
- onClick={() => {
- setOpenPopover(false);
- setShowUpgradePlanModal(true);
- }}
- />
- }
- >
- <div className="flex w-full cursor-not-allowed items-center justify-between p-2 text-left text-sm font-medium text-gray-300 transition-all duration-75">
- <IconMenu
- text="Duplicate"
- icon={<CopyPlus className="h-4 w-4" />}
- />
- <kbd className="hidden rounded bg-gray-100 px-2 py-0.5 text-xs font-light text-gray-300 transition-all duration-75 sm:inline-block">
- D
- </kbd>
- </div>
- </Tooltip>
- ) : (
- <button
- onClick={() => {
- setOpenPopover(false);
- setShowDuplicateLinkModal(true);
- }}
- className="group flex w-full items-center justify-between rounded-md p-2 text-left text-sm font-medium text-gray-500 transition-all duration-75 hover:bg-gray-100"
- >
- <IconMenu
- text="Duplicate"
- icon={<CopyPlus className="h-4 w-4" />}
- />
- <kbd className="hidden rounded bg-gray-100 px-2 py-0.5 text-xs font-light text-gray-500 transition-all duration-75 group-hover:bg-gray-200 sm:inline-block">
- D
- </kbd>
- </button>
- )}
+ <button
+ onClick={() => {
+ setOpenPopover(false);
+ setShowAddEditLinkModal(true);
+ }}
+ className="group flex w-full items-center justify-between rounded-md p-2 text-left text-sm font-medium text-gray-500 transition-all duration-75 hover:bg-gray-100"
+ >
+ <IconMenu text="Edit" icon={<Edit3 className="h-4 w-4" />} />
+ <kbd className="hidden rounded bg-gray-100 px-2 py-0.5 text-xs font-light text-gray-500 transition-all duration-75 group-hover:bg-gray-200 sm:inline-block">
+ E
+ </kbd>
+ </button>
+ <button
+ onClick={() => {
+ setOpenPopover(false);
+ setShowDuplicateLinkModal(true);
+ }}
+ className="group flex w-full items-center justify-between rounded-md p-2 text-left text-sm font-medium text-gray-500 transition-all duration-75 hover:bg-gray-100"
+ >
+ <IconMenu
+ text="Duplicate"
+ icon={<CopyPlus className="h-4 w-4" />}
+ />
+ <kbd className="hidden rounded bg-gray-100 px-2 py-0.5 text-xs font-light text-gray-500 transition-all duration-75 group-hover:bg-gray-200 sm:inline-block">
+ D
+ </kbd>
+ </button>
<button
onClick={() => {
setOpenPopover(false);
diff --git a/apps/web/ui/modals/add-edit-link-modal/index.tsx b/apps/web/ui/modals/add-edit-link-modal/index.tsx
index 3c31ad213f..ddab26ef8e 100644
--- a/apps/web/ui/modals/add-edit-link-modal/index.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal/index.tsx
@@ -612,11 +612,6 @@ function AddEditLinkButton({
}: {
setShowAddEditLinkModal: Dispatch<SetStateAction<boolean>>;
}) {
- const { slug } = useParams() as { slug?: string };
-
- const { exceededUsage } = useProject();
- const { setShowUpgradePlanModal } = useContext(ModalContext);
-
const onKeyDown = useCallback((e: KeyboardEvent) => {
const target = e.target as HTMLElement;
const existingModalBackdrop = document.getElementById("modal-backdrop");
@@ -627,7 +622,6 @@ function AddEditLinkButton({
// - user is not typing in an input or textarea
// - there is no existing modal backdrop (i.e. no other modal is open)
if (
- !exceededUsage &&
e.key === "c" &&
!e.metaKey &&
!e.ctrlKey &&
@@ -670,24 +664,7 @@ function AddEditLinkButton({
};
}, [onKeyDown]);
- return slug && exceededUsage ? ( // only show exceeded usage tooltip if user is on a project page
- <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."
- cta="Upgrade to Pro"
- onClick={() => setShowUpgradePlanModal(true)}
- />
- }
- >
- <div className="flex cursor-not-allowed items-center space-x-3 rounded-md border border-gray-200 px-3 py-2 text-sm font-medium text-gray-300">
- <p>Create link</p>
- <kbd className="hidden rounded bg-gray-100 px-2 py-0.5 text-xs font-light text-gray-300 md:inline-block">
- C
- </kbd>
- </div>
- </Tooltip>
- ) : (
+ return (
<button
onClick={() => setShowAddEditLinkModal(true)}
className="group flex items-center space-x-3 rounded-md border border-black bg-black px-3 py-2 text-sm font-medium text-white transition-all duration-75 hover:bg-white hover:text-black active:scale-95"
diff --git a/apps/web/ui/modals/upgrade-plan-modal.tsx b/apps/web/ui/modals/upgrade-plan-modal.tsx
index 5e4a3fe898..20648962e2 100644
--- a/apps/web/ui/modals/upgrade-plan-modal.tsx
+++ b/apps/web/ui/modals/upgrade-plan-modal.tsx
@@ -1,5 +1,5 @@
import { getStripe } from "@/lib/stripe/client";
-import { PLANS } from "@/lib/stripe/utils";
+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";
@@ -104,13 +104,14 @@ function UpgradePlanModal({
<h4 className="font-medium text-gray-900">
{plan} {capitalize(period)}
</h4>
- <Badge
- variant="neutral"
- className="text-sm font-normal normal-case"
- >
- ${PLANS.find((p) => p.name === plan)!.price[period].amount}/
- {period.replace("ly", "")}
- </Badge>
+ {plan === "Pro" && (
+ <Badge
+ variant="neutral"
+ className="text-sm font-normal normal-case"
+ >
+ ${PRO_PLAN[period].amount}/{period.replace("ly", "")}
+ </Badge>
+ )}
</div>
<Confetti
active={period === "yearly"}
@@ -158,7 +159,7 @@ function UpgradePlanModal({
setClicked(true);
fetch(
`/api/projects/${slug}/billing/upgrade?priceId=${
- PLANS.find((p) => p.name === plan)!.price[period].priceIds[
+ PRO_PLAN[period].priceIds[
process.env.NEXT_PUBLIC_VERCEL_ENV === "production"
? "production"
: "test"
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 7e677ac34a..e53d72985f 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -260,6 +260,23 @@ export const getAdjustedBillingCycleStart = (billingCycleStart: number) => {
}
};
+export const getBillingStartDate = (billingCycleStart: number) => {
+ const today = new Date();
+ const currentDay = today.getDate();
+ const currentMonth = today.getMonth();
+ const currentYear = today.getFullYear();
+ const adjustedBillingCycleStart =
+ getAdjustedBillingCycleStart(billingCycleStart);
+ if (currentDay <= adjustedBillingCycleStart) {
+ // if the current day is less than the billing cycle start, we need to go back a month
+ const lastMonth = currentMonth === 0 ? 11 : currentMonth - 1; // if the current month is January, we need to go back to December
+ const lastYear = currentMonth === 0 ? currentYear - 1 : currentYear; // if the current month is January, we need to go back a year
+ return new Date(lastYear, lastMonth, adjustedBillingCycleStart);
+ } else {
+ return new Date(currentYear, currentMonth, adjustedBillingCycleStart);
+ }
+};
+
export const generateDomainFromName = (name: string) => {
const normalizedName = slugify(name, { separator: "" });
if (normalizedName.length < 3) {