The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
final changes
Steven Tey9f3fc90ca09c
diff --git a/components/app/modals/upgrade-plan-modal.tsx b/components/app/modals/upgrade-plan-modal.tsxnew file mode 100644index 0000000000..274ea055bf--- /dev/null+++ b/components/app/modals/upgrade-plan-modal.tsx@@ -0,0 +1,152 @@+import Modal from "@/components/shared/modal";+import {+ useCallback,+ useMemo,+ useState,+ Dispatch,+ SetStateAction,+} from "react";+import BlurImage from "@/components/shared/blur-image";+import LoadingDots from "@/components/shared/icons/loading-dots";+import { getStripe } from "@/lib/stripe/client";+import { PRO_TIERS } from "@/lib/stripe/constants";+import { nFormatter } from "@/lib/utils";+import Slider from "@/components/shared/slider";+import Switch from "@/components/shared/switch";++function UpgradePlanModal({+ showUpgradePlanModal,+ setShowUpgradePlanModal,+}: {+ showUpgradePlanModal: boolean;+ setShowUpgradePlanModal: Dispatch<SetStateAction<boolean>>;+}) {+ const [clicked, setClicked] = useState(false);+ const [tier, setTier] = useState(0);+ const [annualBilling, setAnnualBilling] = useState(true);+ const period = useMemo(+ () => (annualBilling ? "yearly" : "monthly"),+ [annualBilling]+ );+ const env =+ process.env.NEXT_PUBLIC_VERCEL_ENV === "production" ? "production" : "test";++ return (+ <Modal+ showModal={showUpgradePlanModal}+ setShowModal={setShowUpgradePlanModal}+ >+ <div className="inline-block w-full sm:max-w-md overflow-hidden align-middle transition-all transform bg-white sm:border sm:border-gray-200 shadow-xl sm:rounded-2xl">+ <div className="flex flex-col justify-center items-center space-y-3 sm:px-16 px-4 pt-8 pb-24 border-b border-gray-200">+ <BlurImage+ src="/static/logo.png"+ alt="Dub logo"+ className="w-10 h-10 rounded-full border border-gray-200"+ width={20}+ height={20}+ />+ <h3 className="font-medium text-xl">Upgrade to Pro</h3>+ <div className="flex space-x-2 items-center">+ <p className="text-sm text-gray-600">Billed Monthly</p>+ <Switch setState={setAnnualBilling} />+ <p className="text-sm text-gray-600">Billed Annually</p>+ </div>+ </div>++ <div className="relative bg-white border border-gray-200 shadow-md rounded-lg max-w-sm mx-auto -mt-[5.1rem] -mb-[5.3rem]">+ {annualBilling && (+ <span className="bg-gradient-to-r from-blue-600 to-cyan-600 text-white px-2 py-0.5 absolute top-2 -right-0.5 text-xs rounded-l-md">+ 2 Free Months+ </span>+ )}+ <div className="max-w-md flex justify-between items-center w-full p-5 pt-7">+ <h3 className="text-2xl text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-cyan-600">+ {PRO_TIERS[tier].name}+ </h3>+ <div className="flex items-center">+ <p className="text-2xl font-semibold text-gray-700">+ ${PRO_TIERS[tier].price[period].amount}+ </p>+ <p className="text-sm text-gray-700">+ /{annualBilling ? "yr" : "mo"}+ </p>+ </div>+ </div>+ <div className="w-full flex flex-col items-center space-y-1 bg-gray-50 text-center p-5 border-t border-gray-200 rounded-b-lg">+ <Slider+ value={tier}+ setValue={setTier}+ maxValue={PRO_TIERS.length - 1}+ />+ <p className="text-sm text-gray-700">+ Up to {nFormatter(PRO_TIERS[tier].quota)} link clicks/mo+ </p>+ </div>+ </div>++ <div className="flex flex-col items-center text-left bg-gray-50 sm:px-16 px-4 pt-28 pb-8">+ <button+ disabled={clicked}+ onClick={() => {+ setClicked(true);+ fetch(+ `/api/stripe/upgrade?priceId=${PRO_TIERS[tier].price[period].priceIds[env]}&usageLimit=${PRO_TIERS[tier].quota}`,+ {+ 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);+ });+ }}+ className={`${+ clicked+ ? "cursor-not-allowed bg-gray-100 border-gray-200 text-gray-400"+ : "bg-blue-500 hover:bg-white hover:text-blue-500 border-blue-500 text-white"+ } flex justify-center items-center w-full text-sm h-10 mb-2 rounded-md border transition-all focus:outline-none`}+ >+ {clicked ? (+ <LoadingDots color="#808080" />+ ) : (+ <p>Upgrade to {PRO_TIERS[tier].name}</p>+ )}+ </button>+ <a+ href="mailto:[email protected]?subject=Upgrade%20to%20Enterprise%20Plan"+ className="text-gray-500 text-sm hover:text-gray-700 transition-all"+ >+ Or contact us for Enterprise+ </a>+ </div>+ </div>+ </Modal>+ );+}++export function useUpgradePlanModal() {+ const [showUpgradePlanModal, setShowUpgradePlanModal] = useState(false);++ const UpgradePlanModalCallback = useCallback(() => {+ return (+ <UpgradePlanModal+ showUpgradePlanModal={showUpgradePlanModal}+ setShowUpgradePlanModal={setShowUpgradePlanModal}+ />+ );+ }, [showUpgradePlanModal, setShowUpgradePlanModal]);++ return useMemo(+ () => ({+ setShowUpgradePlanModal,+ UpgradePlanModal: UpgradePlanModalCallback,+ }),+ [setShowUpgradePlanModal, UpgradePlanModalCallback]+ );+}diff --git a/components/app/settings/plan-usage.tsx b/components/app/settings/plan-usage.tsxindex 5ae88d7566..9987fa4c5c 100644--- a/components/app/settings/plan-usage.tsx+++ b/components/app/settings/plan-usage.tsx@@ -1,6 +1,5 @@-import useSWR from "swr";import { useMemo, useState } from "react";-import { nFormatter } from "@/lib/utils";+import { getFirstAndLastDay, nFormatter } from "@/lib/utils";import { useRouter } from "next/router";import Tooltip, { ProTiers } from "@/components/shared/tooltip";import {@@ -10,41 +9,43 @@ import {LoadingDots,} from "@/components/shared/icons";import { motion } from "framer-motion";-import { getStripe } from "@/lib/stripe/client";import useUsage from "@/lib/swr/use-usage";-import { PLAN_FROM_USAGE_LIMIT } from "@/lib/constants";+import { PRO_TIERS } from "@/lib/stripe/constants";+import { useUpgradePlanModal } from "@/components/app/modals/upgrade-plan-modal";export default function PlanUsage() {const router = useRouter();const {- data: { usage, usageLimit, lastBilled, projectCount } = {},+ data: { usage, usageLimit, billingCycleStart, projectCount } = {},loading,} = useUsage({ settingsPage: true });const [clicked, setClicked] = useState(false);const [billingStart, billingEnd] = useMemo(() => {- if (lastBilled) {- const lastBilledDate = new Date(lastBilled);- const start = lastBilledDate.toLocaleDateString("en-us", {+ if (billingCycleStart) {+ const { firstDay, lastDay } = getFirstAndLastDay(billingCycleStart);+ const start = firstDay.toLocaleDateString("en-us", {month: "short",day: "numeric",});- const end = new Date(- lastBilledDate.setDate(lastBilledDate.getDate() + 30)- ).toLocaleDateString("en-us", {+ const end = lastDay.toLocaleDateString("en-us", {month: "short",day: "numeric",});return [start, end];}return [];- }, [lastBilled]);+ }, [billingCycleStart]);- const plan = usageLimit && PLAN_FROM_USAGE_LIMIT[usageLimit];+ const plan =+ usageLimit && PRO_TIERS.find((tier) => tier.quota === usageLimit).name;++ const { UpgradePlanModal, setShowUpgradePlanModal } = useUpgradePlanModal();return (<div className="bg-white rounded-lg border border-gray-200">+ <UpgradePlanModal /><div className="flex flex-col space-y-3 p-10"><h2 className="text-xl font-medium">Plan & Usage</h2><p className="text-gray-500 text-sm">@@ -156,29 +157,11 @@ export default function PlanUsage() {plan === "Free" ? (<buttononClick={() => {- setClicked(true);- fetch(`/api/stripe/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);- });+ setShowUpgradePlanModal(true);}}- 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`}+ className="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"}+ Upgrade</button>) : (<div className="flex space-x-3">diff --git a/components/home/pricing.tsx b/components/home/pricing.tsxindex 1d6b90149b..6369409a5d 100644--- a/components/home/pricing.tsx+++ b/components/home/pricing.tsx@@ -9,7 +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";+import { PRO_TIERS } from "@/lib/stripe/constants";const pricingItems = [{@@ -23,7 +23,7 @@ const pricingItems = ["Just bring any domain you own and turn it into a custom domain link shortener for free.",},{ text: "Unlimited branded links" },- { text: "1 project" },+ { text: "5 project" },{text: "Root domain redirect",footnote:@@ -131,7 +131,10 @@ const Pricing = () => {) : (<div className="my-5 flex justify-center"><p className="text-6xl font-display font-semibold">- ${plan === "Pro" ? PRO_TIERS[tier].price : 0}+ $+ {plan === "Pro"+ ? PRO_TIERS[tier].price.monthly.amount+ : 0}</p></div>)}diff --git a/components/shared/switch.tsx b/components/shared/switch.tsxnew file mode 100644index 0000000000..cdf1304313--- /dev/null+++ b/components/shared/switch.tsx@@ -0,0 +1,32 @@+import * as SwitchPrimitive from "@radix-ui/react-switch";+import cx from "classnames";+import { Dispatch, SetStateAction } from "react";++const Switch = ({+ setState,+}: {+ setState: Dispatch<SetStateAction<boolean>>;+}) => {+ return (+ <SwitchPrimitive.Root+ defaultChecked={true}+ onCheckedChange={(checked) => setState(checked)}+ className={cx(+ "radix-state-checked:bg-blue-500",+ "radix-state-unchecked:bg-gray-200 dark:radix-state-unchecked:bg-gray-800",+ "relative inline-flex h-4 w-8 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out",+ "focus:outline-none focus-visible:ring focus-visible:ring-blue-500 focus-visible:ring-opacity-75"+ )}+ >+ <SwitchPrimitive.Thumb+ className={cx(+ "radix-state-checked:translate-x-4",+ "radix-state-unchecked:translate-x-0",+ "pointer-events-none inline-block h-3 w-3 transform rounded-full bg-white shadow-lg ring-0 transition duration-200 ease-in-out"+ )}+ />+ </SwitchPrimitive.Root>+ );+};++export default Switch;diff --git a/components/shared/tooltip.tsx b/components/shared/tooltip.tsxindex c436b6d8b2..5c4c6d3149 100644--- a/components/shared/tooltip.tsx+++ b/components/shared/tooltip.tsx@@ -1,7 +1,7 @@import * as TooltipPrimitive from "@radix-ui/react-tooltip";import { ReactNode, useEffect, useRef, useState } from "react";import { motion, AnimatePresence, useAnimation } from "framer-motion";-import { PLAN_FROM_USAGE_LIMIT, PRO_TIERS } from "@/lib/constants";+import { PRO_TIERS } from "@/lib/stripe/constants";import Slider from "@/components/shared/slider";export default function Tooltip({@@ -168,11 +168,11 @@ export function ProTiers({ usageLimit }: { usageLimit?: number }) {<div className="w-full rounded-md"><div className="max-w-md flex justify-between items-center w-full p-5"><h3 className="text-2xl text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-cyan-600">- {PLAN_FROM_USAGE_LIMIT[PRO_TIERS[tier].quota]}+ {PRO_TIERS[tier].name}</h3><div className="flex items-center"><p className="text-2xl font-semibold text-gray-700">- ${PRO_TIERS[tier].price}+ ${PRO_TIERS[tier].price.monthly.amount}</p><p className="text-sm text-gray-700">/mo</p></div>diff --git a/lib/auth.ts b/lib/auth.tsindex 7ac7ef47cc..d536ee2a07 100644--- a/lib/auth.ts+++ b/lib/auth.ts@@ -159,7 +159,7 @@ const withUserAuth =})) as UserProps;const freePlan = user.usageLimit === 1000;- if (needProSubscription && freePlan && user.projects.length === 1) {+ if (needProSubscription && freePlan && user.projects.length >= 5) {return res.status(403).end("Unauthorized: Can't add more projects, need pro subscription");diff --git a/lib/constants.ts b/lib/constants.tsindex 30e9e784b4..d49a6078b1 100644--- a/lib/constants.ts+++ b/lib/constants.ts@@ -13,44 +13,6 @@ 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",diff --git a/lib/cron.ts b/lib/cron.tsindex 051058b616..829c10a199 100644--- a/lib/cron.ts+++ b/lib/cron.ts@@ -45,45 +45,20 @@ 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,+ stripeId: true,+ billingCycleStart: true,projects: {select: {project: {select: {domain: true,+ domainVerified: true,},},},@@ -95,32 +70,36 @@ export const updateUsage = async () => {});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);+ users.map(+ async ({ id, email, usageLimit, billingCycleStart, projects }) => {+ // if user has no projects, don't update usage+ if (projects.length === 0) return;- if (totalUsage > usageLimit) {- await log(- `${email} is over usage limit. Usage: ${totalUsage}, Limit: ${usageLimit}`+ const usageArr = await Promise.all(+ projects.map(async ({ project: { domain, domainVerified } }) => {+ return domainVerified+ ? await getUsage(domain, billingCycleStart)+ : 0;+ }));- }+ let totalUsage = usageArr.reduce((a, b) => a + b, 0);- return await prisma.user.update({- where: {- id,- },- data: {- usage: totalUsage,- },- });- })+ 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;diff --git a/lib/stripe/constants.ts b/lib/stripe/constants.tsnew file mode 100644index 0000000000..118bcc6598--- /dev/null+++ b/lib/stripe/constants.ts@@ -0,0 +1,122 @@+export const PRO_TIERS = [+ {+ name: "Pro 10K",+ quota: 10000,+ price: {+ monthly: {+ amount: 9,+ priceIds: {+ test: "price_1LoytoAlJJEpqkPV2oPcQ63m",+ production: "price_1LodNLAlJJEpqkPVQSrt33Lc",+ },+ },+ yearly: {+ amount: 90,+ priceIds: {+ test: "price_1LoytoAlJJEpqkPVsWjM4tB9",+ production: "price_1LodNLAlJJEpqkPVRxUyCQgZ",+ },+ },+ },+ },+ {+ name: "Pro 25K",+ quota: 25000,+ price: {+ monthly: {+ amount: 19,+ priceIds: {+ test: "price_1LoytHAlJJEpqkPVonefD3RW",+ production: "price_1LodMrAlJJEpqkPVq3XV2Y3R",+ },+ },+ yearly: {+ amount: 190,+ priceIds: {+ test: "price_1LoytHAlJJEpqkPVP25C5yjd",+ production: "price_1LodMrAlJJEpqkPViKR29tq8",+ },+ },+ },+ },+ {+ name: "Pro 50K",+ quota: 50000,+ price: {+ monthly: {+ amount: 29,+ priceIds: {+ test: "price_1LoyrzAlJJEpqkPVVZfXIZE5",+ production: "price_1LodMEAlJJEpqkPVrMdRwaSk",+ },+ },+ yearly: {+ amount: 290,+ priceIds: {+ test: "price_1LoyrzAlJJEpqkPVtCBUz78P",+ production: "price_1LodMEAlJJEpqkPV5ztz7wyg",+ },+ },+ },+ },+ {+ name: "Pro 100K",+ quota: 100000,+ price: {+ monthly: {+ amount: 49,+ priceIds: {+ test: "price_1LoyrCAlJJEpqkPVZ32BV3wm",+ production: "price_1LodLoAlJJEpqkPV9rD0rlNL",+ },+ },+ yearly: {+ amount: 490,+ priceIds: {+ test: "price_1LoyrCAlJJEpqkPVgIlNG23q",+ production: "price_1LodLoAlJJEpqkPVJdwv5zrG",+ },+ },+ },+ },+ {+ name: "Pro 500K",+ quota: 500000,+ price: {+ monthly: {+ amount: 79,+ priceIds: {+ test: "price_1LoyqQAlJJEpqkPVGy7kyuxS",+ production: "price_1LodLIAlJJEpqkPVi7javvun",+ },+ },+ yearly: {+ amount: 790,+ priceIds: {+ test: "price_1LoyqQAlJJEpqkPVdWYVpS76",+ production: "price_1LodLIAlJJEpqkPValZ9TmgF",+ },+ },+ },+ },+ {+ name: "Pro 1M",+ quota: 1000000,+ price: {+ monthly: {+ amount: 99,+ priceIds: {+ test: "price_1Lis30AlJJEpqkPVAuSVxbT1",+ production: "price_1Lis1VAlJJEpqkPV7sUnggB3",+ },+ },+ yearly: {+ amount: 990,+ priceIds: {+ test: "price_1LoymUAlJJEpqkPVDX9fNCu7",+ production: "price_1LodJMAlJJEpqkPV2K0xX2kF",+ },+ },+ },+ },+];diff --git a/lib/swr/use-usage.ts b/lib/swr/use-usage.tsindex 18d120e135..b30dc85dd8 100644--- a/lib/swr/use-usage.ts+++ b/lib/swr/use-usage.ts@@ -2,7 +2,7 @@ import useSWR from "swr";import { useMemo } from "react";import { fetcher } from "@/lib/utils";import { UsageProps } from "@/lib/types";-import { PLAN_FROM_USAGE_LIMIT } from "../constants";+import { PRO_TIERS } from "@/lib/stripe/constants";export default function useUsage({ settingsPage } = { settingsPage: false }) {const { data, error } = useSWR<UsageProps>(@@ -18,7 +18,7 @@ export default function useUsage({ settingsPage } = { settingsPage: false }) {const plan = useMemo(() => {if (data) {- return PLAN_FROM_USAGE_LIMIT[data.usageLimit];+ return PRO_TIERS.find((tier) => tier.quota === data.usageLimit).name;}}, [data]);diff --git a/lib/types.ts b/lib/types.tsindex 8debb308e7..1fc65e78e1 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -23,7 +23,7 @@ export interface UsageProps {usage: number;usageLimit: number;projectCount?: number;- lastBilled?: number;+ billingCycleStart?: number;}export interface UserProps {diff --git a/lib/upstash.ts b/lib/upstash.tsindex b9719e6729..6517873468 100644--- a/lib/upstash.ts+++ b/lib/upstash.ts@@ -3,7 +3,11 @@ import { NextRequest, userAgent } from "next/server";import { LOCALHOST_GEO_DATA, RESERVED_KEYS } from "@/lib/constants";import { LinkProps, ProjectProps } from "@/lib/types";import { customAlphabet } from "nanoid";-import { getDescriptionFromUrl, getTitleFromUrl } from "@/lib/utils";+import {+ getDescriptionFromUrl,+ getFirstAndLastDay,+ getTitleFromUrl,+} from "@/lib/utils";// Initiate Redis instanceexport const redis = new Redis({@@ -251,25 +255,9 @@ export async function deleteLink(domain: string, key: string, userId?: string) {**/export async function getUsage(hostname: string,- billingCycleStart?: Date+ billingCycleStart: number): Promise<number> {- const cachedUsage = await redis.get<number>(`usage:${hostname}`);- if (cachedUsage) {- return cachedUsage;- }- console.log("no cached usage found. computing from scratch...");-- let firstDay;- let lastDay;-- if (billingCycleStart) {- firstDay = new Date(billingCycleStart).getTime();- lastDay = Date.now();- } else {- var date = new Date();- firstDay = new Date(date.getFullYear(), date.getMonth(), 1).getTime();- lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0).getTime();- }+ const { firstDay, lastDay } = getFirstAndLastDay(billingCycleStart);const links = await redis.zrange(`${hostname}:links:timestamps`, 0, -1);let results: number[] = [];@@ -277,7 +265,11 @@ export async function getUsage(if (links.length > 0) {const pipeline = redis.pipeline();links.forEach((link) => {- pipeline.zcount(`${hostname}:clicks:${link}`, firstDay, lastDay);+ pipeline.zcount(+ `${hostname}:clicks:${link}`,+ firstDay.getTime(),+ lastDay.getTime()+ );});results = await pipeline.exec();}diff --git a/lib/utils.ts b/lib/utils.tsindex f9763991a6..2ec652f376 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -146,3 +146,25 @@ export const generateSlugFromName = (name: string) => {export const validDomainRegex = new RegExp("^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$");++export const getFirstAndLastDay = (day: number) => {+ const today = new Date();+ const currentDay = today.getDate();+ const currentMonth = today.getMonth();+ const currentYear = today.getFullYear();+ if (currentDay >= day) {+ // if the current day is greater than target day, it means that we just passed it+ return {+ firstDay: new Date(currentYear, currentMonth, day),+ lastDay: new Date(currentYear, currentMonth + 1, day - 1),+ };+ } else {+ // if the current day is less than target day, it means that we haven't passed it yet+ const lastYear = currentMonth === 0 ? currentYear - 1 : currentYear; // if the current month is January, we need to go back a year+ const lastMonth = currentMonth === 0 ? 11 : currentMonth - 1; // if the current month is January, we need to go back to December+ return {+ firstDay: new Date(lastYear, lastMonth, day),+ lastDay: new Date(currentYear, currentMonth, day - 1),+ };+ }+};diff --git a/package.json b/package.jsonindex 1ce35bd69f..d201cafce4 100644--- a/package.json+++ b/package.json@@ -11,6 +11,7 @@"@next-auth/prisma-adapter": "^1.0.4","@prisma/client": "^4.3.1","@radix-ui/react-slider": "^1.0.0",+ "@radix-ui/react-switch": "^1.0.0","@radix-ui/react-tooltip": "^1.0.0","@stripe/stripe-js": "^1.36.0","@tailwindcss/forms": "^0.5.3",@@ -41,7 +42,7 @@"react-hot-toast": "^2.4.0","react-spring": "^9.5.4","react-textarea-autosize": "^8.3.4",- "stripe": "^10.7.0",+ "stripe": "^10.12.0","swr": "^2.0.0-beta.1","tailwind-scrollbar-hide": "^1.1.7","topojson-client": "^3.1.0",diff --git a/pages/api/stripe/manage-subscription.ts b/pages/api/stripe/manage-subscription.tsindex 106f500555..e92b0e5514 100644--- a/pages/api/stripe/manage-subscription.ts+++ b/pages/api/stripe/manage-subscription.ts@@ -4,22 +4,16 @@ import { stripe } from "@/lib/stripe";import { UserProps } from "@/lib/types";export default withUserAuth(- async (- req: NextApiRequest,- res: NextApiResponse,- userId: string,- user: UserProps- ) => {+ async (req: NextApiRequest, res: NextApiResponse, _, user: UserProps) => {// POST /api/stripe/manage-subscription – manage a user's subscriptionif (req.method === "POST") {- const { slug } = req.query as { slug: string };const { url } = await stripe.billingPortal.sessions.create({customer: user.stripeId,return_url: `${process.env.VERCEL === "1"? "https://app.dub.sh": "http://app.localhost:3000"- }/${slug}/settings`,+ }/settings`,});return res.status(200).json(url);} else {@@ -28,5 +22,6 @@ export default withUserAuth(.status(405).json({ error: `Method ${req.method} Not Allowed` });}- }+ },+ { needUserDetails: true });diff --git a/pages/api/stripe/upgrade.ts b/pages/api/stripe/upgrade.tsindex 2549e7ffee..56f43b530e 100644--- a/pages/api/stripe/upgrade.ts+++ b/pages/api/stripe/upgrade.ts@@ -1,11 +1,12 @@import { NextApiRequest, NextApiResponse } from "next";-import { withProjectAuth, withUserAuth } from "@/lib/auth";+import { withUserAuth } from "@/lib/auth";import { stripe } from "@/lib/stripe";export default withUserAuth(async (req: NextApiRequest, res: NextApiResponse, userId) => {// POST /api/stripe/upgrade – upgrade a user's account from free to proif (req.method === "POST") {+ const { priceId } = req.query as { priceId: string };const session = await stripe.checkout.sessions.create({payment_method_types: ["card"],billing_address_collection: "required",@@ -19,7 +20,7 @@ export default withUserAuth(? "https://app.dub.sh": "http://app.localhost:3000"}/settings`,- line_items: [{ price: process.env.STRIPE_PRO_PRICE_ID, quantity: 1 }],+ line_items: [{ price: priceId, quantity: 1 }],mode: "subscription",client_reference_id: userId,});diff --git a/pages/api/stripe/webhook.ts b/pages/api/stripe/webhook.tsindex 7751336bf0..a58e3ee86b 100644--- a/pages/api/stripe/webhook.ts+++ b/pages/api/stripe/webhook.ts@@ -3,6 +3,7 @@ import Stripe from "stripe";import { stripe } from "@/lib/stripe";import { Readable } from "node:stream";import prisma from "@/lib/prisma";+import { PRO_TIERS } from "@/lib/stripe/constants";// Stripe requires the raw body to construct the event.export const config = {@@ -21,8 +22,8 @@ async function buffer(readable: Readable) {const relevantEvents = new Set(["checkout.session.completed",- "invoice.paid","invoice.payment_failed",+ "customer.subscription.updated","customer.subscription.deleted",]);@@ -50,44 +51,54 @@ export default async function webhookHandler(const checkoutSession = event.data.object as Stripe.Checkout.Session;- await prisma.project.update({+ // when the user subscribes to a plan, set their stripe customer ID+ // in the database for easy identification in future webhook events+ await prisma.user.update({where: {- slug: checkoutSession.client_reference_id,+ id: checkoutSession.client_reference_id,},data: {- plan: "pro",- usageLimit: 1000000,stripeId: checkoutSession.customer.toString(),- lastBilled: new Date(),+ billingCycleStart: new Date().getDate(),},});break;- case "invoice.paid":- const invoicePaid = event.data.object as Stripe.Invoice;- console.log("invoice paid", invoicePaid);- await prisma.project.update({++ case "customer.subscription.updated":+ const subscriptionUpdated = event.data+ .object as Stripe.Subscription;+ const newPriceId = subscriptionUpdated.items.data[0].price.id;+ const env =+ process.env.NEXT_PUBLIC_VERCEL_ENV === "production"+ ? "production"+ : "test";+ const tier = PRO_TIERS.find(+ (tier) =>+ tier.price.monthly.priceIds[env] === newPriceId ||+ tier.price.yearly.priceIds[env] === newPriceId+ );+ const usageLimit = tier.quota;++ // If a user upgrades/downgrades their subscription,+ // update their usage limit in the database.+ await prisma.user.update({where: {- stripeId: invoicePaid.customer.toString(),+ stripeId: subscriptionUpdated.customer.toString(),},data: {- lastBilled: new Date(),+ usageLimit,},});break;- case "invoice.payment_failed":- const invoiceFailed = event.data.object as Stripe.Invoice;- console.log("invoice failed", invoiceFailed);- // TODO - send email to user- break;+case "customer.subscription.deleted":- const subscription = event.data.object as Stripe.Subscription;- console.log("subscription deleted", subscription);- await prisma.project.update({+ const subscriptionDeleted = event.data+ .object as Stripe.Subscription;+ await prisma.user.update({where: {- stripeId: subscription.customer.toString(),+ stripeId: subscriptionDeleted.customer.toString(),},data: {- plan: "free",usageLimit: 1000,},});diff --git a/pages/api/usage/index.ts b/pages/api/usage/index.tsindex 137574a16c..246ebc1b60 100644--- a/pages/api/usage/index.ts+++ b/pages/api/usage/index.ts@@ -16,7 +16,7 @@ export default withUserAuth(usage: true,usageLimit: true,...(settingsPage === "1" && {- lastBilled: true,+ billingCycleStart: true,projects: {where: {role: "owner",@@ -29,7 +29,7 @@ export default withUserAuth(...response,...(settingsPage === "1" && {projects: undefined,- projectCount: response.projects.length || "0",+ projectCount: response?.projects?.length || "0",}),});} else {diff --git a/pages/index.tsx b/pages/index.tsxindex 1f0d7eb94b..288dfc35fa 100644--- a/pages/index.tsx+++ b/pages/index.tsx@@ -60,7 +60,7 @@ export async function getStaticProps() {return {props: {- stars: stars || 0,+ stars,},revalidate: 10,};diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 136f9843aa..49cd1eacf0 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -13,18 +13,19 @@ generator client {}model User {- id String @id @default(cuid())- name String?- email String? @unique- emailVerified DateTime?- image String?- stripeId String? @unique // Stripe customer ID- usage Int @default(0)- usageLimit Int @default(1000)- lastBilled DateTime?- accounts Account[]- sessions Session[]- projects ProjectUsers[]+ id String @id @default(cuid())+ name String?+ email String? @unique+ emailVerified DateTime?+ image String?+ stripeId String? @unique // Stripe customer ID+ usage Int @default(0)+ usageLimit Int @default(1000)+ billingCycleStart Int? // day of the month when the billing cycle starts+ accounts Account[]+ sessions Session[]+ projects ProjectUsers[]+ createdAt DateTime @default(now())}model Account {@@ -66,6 +67,7 @@ model Project {id String @id @default(cuid())name Stringslug String @unique+ logo String?domain String @uniquedomainVerified Boolean @default(false)createdAt DateTime @default(now())diff --git a/tailwind.config.js b/tailwind.config.jsindex 9686cc394b..e20abf9413 100644--- a/tailwind.config.js+++ b/tailwind.config.js@@ -1,4 +1,6 @@/** @type {import('tailwindcss').Config} */+const plugin = require("tailwindcss/plugin");+module.exports = {content: ["./pages/**/*.{js,ts,jsx,tsx}",@@ -56,5 +58,9 @@ module.exports = {require("@tailwindcss/forms"),require("tailwind-scrollbar-hide"),require("@tailwindcss/line-clamp"),+ plugin(({ addVariant }) => {+ addVariant("radix-state-checked", '&[data-state="checked"]');+ addVariant("radix-state-unchecked", '&[data-state="unchecked"]');+ }),],};diff --git a/yarn.lock b/yarn.lockindex 45fb4afd90..e65b973aec 100644--- a/yarn.lock+++ b/yarn.lock@@ -487,6 +487,17 @@"@babel/runtime" "^7.13.10""@radix-ui/react-use-layout-effect" "1.0.0"+"@radix-ui/[email protected]":+ version "1.0.0"+ resolved "https://registry.yarnpkg.com/@radix-ui/react-label/-/react-label-1.0.0.tgz#c6691b0bec18958512a952c18732279285b61fef"+ integrity sha512-k+EbxeRaVbSJ4oaR9eUYuC0cDIGRB4TAPhilbFCIMpP9pXFNcyQPQUvRaVOQBrviuArYM80xh0BQR/0y3kjUdQ==+ dependencies:+ "@babel/runtime" "^7.13.10"+ "@radix-ui/react-compose-refs" "1.0.0"+ "@radix-ui/react-context" "1.0.0"+ "@radix-ui/react-id" "1.0.0"+ "@radix-ui/react-primitive" "1.0.0"+"@radix-ui/[email protected]":version "1.0.0"resolved "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.0.0.tgz"@@ -554,6 +565,21 @@"@babel/runtime" "^7.13.10""@radix-ui/react-compose-refs" "1.0.0"+"@radix-ui/react-switch@^1.0.0":+ version "1.0.0"+ resolved "https://registry.yarnpkg.com/@radix-ui/react-switch/-/react-switch-1.0.0.tgz#f714eb81da7b16dae7f5ab6e774e3194d8f009b6"+ integrity sha512-SydkCiuirxJfRG8259J0RIpOw1p6y4TgJdNYvDNXgkEjCjFzLCvBbgDNQn9SeYXk3mjO/ezMgMFsacnrp4eihw==+ dependencies:+ "@babel/runtime" "^7.13.10"+ "@radix-ui/primitive" "1.0.0"+ "@radix-ui/react-compose-refs" "1.0.0"+ "@radix-ui/react-context" "1.0.0"+ "@radix-ui/react-label" "1.0.0"+ "@radix-ui/react-primitive" "1.0.0"+ "@radix-ui/react-use-controllable-state" "1.0.0"+ "@radix-ui/react-use-previous" "1.0.0"+ "@radix-ui/react-use-size" "1.0.0"+"@radix-ui/react-tooltip@^1.0.0":version "1.0.0"resolved "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.0.0.tgz"@@ -3457,10 +3483,10 @@ strip-ansi@^6.0.1:dependencies:ansi-regex "^5.0.1"-stripe@^10.7.0:- version "10.7.0"- resolved "https://registry.npmjs.org/stripe/-/stripe-10.7.0.tgz"- integrity sha512-yCd8xTPaPLps7BYJL3FuBwza6A4TcYvE074bCEpN5xJUYBUYN4lly0F275HkUa7QODXn8UjO93oIanV/L6O14w==+stripe@^10.12.0:+ version "10.12.0"+ resolved "https://registry.yarnpkg.com/stripe/-/stripe-10.12.0.tgz#5312193d0651b27f0d1a7b6866e52a30915694ce"+ integrity sha512-4ijMsbTVSy6rzWIkal+/dFGeTXtjqLeZ/oo/jc2jhICbf3Dby0CBTPxAg6ZhBPXQL96TJxI613C/NhhE7LvrWw==dependencies:"@types/node" ">=8.1.0"qs "^6.10.3"