The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
added Stripe price IDs, fix delete projects
Steven Tey7c2ab072690b
diff --git a/apps/web/app/admin.dub.co/actions.ts b/apps/web/app/admin.dub.co/actions.tsindex 7ef8737515..d25b05eb41 100644--- a/apps/web/app/admin.dub.co/actions.ts+++ b/apps/web/app/admin.dub.co/actions.ts@@ -1,6 +1,6 @@"use server";-import { reassignUserLinks } from "@/lib/api/links";-import { deleteProject } from "@/lib/api/project";++import { deleteProject } from "@/lib/api/projects";import { getSession, hashToken } from "@/lib/auth";import prisma from "@/lib/prisma";import { redis } from "@/lib/upstash";@@ -10,6 +10,7 @@ import {SHORT_DOMAIN,getDomainWithoutWWW,} from "@dub/utils";+import { LEGAL_PROJECT_ID } from "@dub/utils/dist/constants";import { get } from "@vercel/edge-config";import { randomBytes } from "crypto";@@ -244,7 +245,16 @@ export async function banUser(data: FormData) {const blacklistedEmails = (await get("emails")) as string[];const ban = await Promise.allSettled([- reassignUserLinks(user.id),+ prisma.link.updateMany({+ where: {+ userId: user.id,+ domain: SHORT_DOMAIN,+ },+ data: {+ userId: LEGAL_USER_ID,+ projectId: LEGAL_PROJECT_ID,+ },+ }),fetch(`https://api.vercel.com/v1/edge-config/${process.env.EDGE_CONFIG_ID}/items?teamId=${process.env.TEAM_ID_VERCEL}`,{diff --git a/apps/web/app/api/callback/stripe/route.ts b/apps/web/app/api/callback/stripe/route.tsindex fb011a1f21..1357f06ffb 100644--- a/apps/web/app/api/callback/stripe/route.ts+++ b/apps/web/app/api/callback/stripe/route.ts@@ -50,11 +50,12 @@ export const POST = async (req: Request) => {checkoutSession.subscription as string,);const priceId = subscription.items.data[0].price.id;+const plan = getPlanFromPriceId(priceId);if (!plan) {await log({- message: "Invalid price ID",+ message: "Invalid price ID in checkout.session.completed event",type: "cron",mention: true,});@@ -109,7 +110,7 @@ export const POST = async (req: Request) => {react: UpgradeEmail({name: user.name,email: user.email as string,- plan: plan.name.toLowerCase(),+ plan: plan.name,}),marketing: true,}),@@ -127,7 +128,7 @@ export const POST = async (req: Request) => {if (!plan) {await log({- message: "Invalid price ID",+ message: "Invalid price ID in customer.subscription.updated event",type: "cron",mention: true,});diff --git a/apps/web/app/api/projects/[slug]/route.ts b/apps/web/app/api/projects/[slug]/route.tsindex a421b23e1d..4a7a0d3fb3 100644--- a/apps/web/app/api/projects/[slug]/route.ts+++ b/apps/web/app/api/projects/[slug]/route.ts@@ -1,7 +1,7 @@import { withAuth } from "@/lib/auth";import { NextResponse } from "next/server";import prisma from "@/lib/prisma";-import { deleteProject } from "@/lib/api/project";+import { deleteProject } from "@/lib/api/projects";import { DEFAULT_REDIRECTS, validSlugRegex } from "@dub/utils";import { isReservedKey } from "@/lib/edge-config";diff --git a/apps/web/app/api/user/route.ts b/apps/web/app/api/user/route.tsindex 27062dac84..71001fc077 100644--- a/apps/web/app/api/user/route.ts+++ b/apps/web/app/api/user/route.ts@@ -1,4 +1,3 @@-import { deleteUserLinks } from "@/lib/api/links";import { withSession } from "@/lib/auth";import prisma from "@/lib/prisma";import cloudinary from "cloudinary";@@ -51,28 +50,26 @@ export const DELETE = withSession(async ({ session }) => {{ status: 422 },);} else {- const [deleteLinks, _] = await Promise.allSettled([- deleteUserLinks(session.user.id),+ const response = await Promise.allSettled([+ prisma.user.delete({+ where: {+ id: session.user.id,+ },+ }),cloudinary.v2.uploader.destroy(`avatars/${session?.user?.id}`, {invalidate: true,}),- // Disabling this until there's a way to delete audience by email using Resend API- // fetch(- // `https://api.resend.com/audiences/${process.env.RESEND_AUDIENCE_ID}/contacts`,- // {- // method: "DELETE",- // headers: {- // Authorization: `Bearer ${process.env.RESEND_API_KEY}`,- // "Content-Type": "application/json",- // },- // },- // )+ fetch(+ `https://api.resend.com/audiences/${process.env.RESEND_AUDIENCE_ID}/contacts/${session?.user?.email}`,+ {+ method: "DELETE",+ headers: {+ Authorization: `Bearer ${process.env.RESEND_API_KEY}`,+ "Content-Type": "application/json",+ },+ },+ ),]);- const response = await prisma.user.delete({- where: {- id: session.user.id,- },- });- return NextResponse.json({ deleteLinks, response });+ return NextResponse.json(response);}});diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsxindex b9a86bbd06..c6a1fecd29 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsx@@ -11,6 +11,7 @@ import { HOME_DOMAIN, getFirstAndLastDay, nFormatter } from "@dub/utils";import va from "@vercel/analytics";import { useRouter, useSearchParams } from "next/navigation";import { useEffect, useMemo, useState } from "react";+import Confetti from "react-dom-confetti";import { toast } from "sonner";import { mutate } from "swr";@@ -54,22 +55,26 @@ export default function ProjectBillingClient() {}, [billingCycleStart]);const { queryParams } = useRouterStuff();+ const [confetti, setConfetti] = useState(false);useEffect(() => {if (searchParams?.get("success")) {toast.success("Upgrade success!");+ setConfetti(true);setTimeout(() => {mutate(`/api/projects/${slug}`);- // track upgrade to pro event- va.track("Upgraded Plan", {- plan: "pro",- });+ // track upgrade event+ plan &&+ va.track("Upgraded Plan", {+ plan,+ });}, 1000);}- }, [searchParams]);+ }, [searchParams, plan]);return (<>+ <Confetti active={confetti} config={{ elementCount: 200, spread: 90 }} /><div className="rounded-lg border border-gray-200 bg-white"><div className="flex flex-col space-y-3 p-10"><h2 className="text-xl font-medium">Plan & Usage</h2>diff --git a/apps/web/lib/api/domains.ts b/apps/web/lib/api/domains.tsindex f34d2e91c2..ba2f0b14da 100644--- a/apps/web/lib/api/domains.ts+++ b/apps/web/lib/api/domains.ts@@ -237,7 +237,7 @@ export async function changeDomainForImages(domain: string, newDomain: string) {}}-/* Delete a domain and all links & images associated with with */+/* Delete a domain and all links & images associated with it */export async function deleteDomainAndLinks(domain: string,{diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.tsindex 046099d193..6804e31ed5 100644--- a/apps/web/lib/api/links.ts+++ b/apps/web/lib/api/links.ts@@ -691,84 +691,3 @@ export async function archiveLink(},});}--/* Delete all dub.sh links associated with a user when it's deleted */-export async function deleteUserLinks(userId: string) {- const links = await prisma.link.findMany({- where: {- userId,- domain: SHORT_DOMAIN,- },- select: {- key: true,- proxy: true,- },- });- const pipeline = redis.pipeline();- links.forEach(({ key }) => {- pipeline.del(`dub.sh:${key}`);- });- const [deleteRedis, deleteCloudinary, deletePrisma] =- await Promise.allSettled([- pipeline.exec(), // delete all links from redis- // remove all images from cloudinary- ...links.map(({ key, proxy }) =>- proxy- ? cloudinary.v2.uploader.destroy(`dub.sh/${key}`, {- invalidate: true,- })- : Promise.resolve(),- ),- prisma.link.deleteMany({- where: {- userId,- domain: SHORT_DOMAIN,- },- }),- ]);- return {- deleteRedis,- deleteCloudinary,- deletePrisma,- };-}--/* Reassign user links to another user when a user is deleted */-export async function reassignUserLinks(userId: string) {- const links = await prisma.link.findMany({- where: {- userId,- domain: SHORT_DOMAIN,- },- select: {- domain: true,- key: true,- },- });-- const redisLinks = await redis.mget<SimpleLinkProps[]>(- ...links.map(({ domain, key }) => `${domain}:${key}`),- );-- const pipeline = redis.pipeline();- redisLinks.forEach((link, index) => {- const { domain, key } = links[index];- pipeline.set(`${domain}:${key}`, {- ...link,- banned: true,- });- });-- await Promise.all([- pipeline.exec(),- prisma.link.updateMany({- where: {- userId,- domain: SHORT_DOMAIN,- },- data: {- userId: LEGAL_USER_ID,- },- }),- ]);-}diff --git a/apps/web/lib/api/project.ts b/apps/web/lib/api/projects.tssimilarity index 52%rename from apps/web/lib/api/project.tsrename to apps/web/lib/api/projects.tsindex d52478ca97..3131745cf9 100644--- a/apps/web/lib/api/project.ts+++ b/apps/web/lib/api/projects.ts@@ -3,30 +3,59 @@ import prisma from "@/lib/prisma";import { cancelSubscription } from "@/lib/stripe";import cloudinary from "cloudinary";import { ProjectProps } from "../types";+import { DUB_DOMAINS } from "@dub/utils";+import { redis } from "../upstash";export async function deleteProject(project: Pick<ProjectProps, "id" | "slug" | "stripeId" | "logo">,) {- const domains = (- await prisma.domain.findMany({+ const [customDomains, defaultDomainLinks] = await Promise.all([+ prisma.domain.findMany({where: {projectId: project.id,},select: {slug: true,},- })- ).map((domain) => domain.slug);+ }),+ prisma.link.findMany({+ where: {+ projectId: project.id,+ domain: {+ in: DUB_DOMAINS.map((domain) => domain.slug),+ },+ },+ select: {+ domain: true,+ key: true,+ proxy: true,+ },+ }),+ ]);++ const pipeline = redis.pipeline();+ defaultDomainLinks.forEach(({ domain, key }) => {+ pipeline.del(`${domain}:${key}`);+ });// delete all domains, links, and uploaded images associated with the project- const deleteDomainsResponse = await Promise.allSettled(- domains.map((domain) =>- deleteDomainAndLinks(domain, {+ const deleteDomainsLinksResponse = await Promise.allSettled([+ ...customDomains.map(({ slug }) =>+ deleteDomainAndLinks(slug, {// here, we don't need to delete in prisma because we're deleting the project later and have onDelete: CASCADE setskipPrismaDelete: true,}),),- );+ pipeline.exec(), // delete all default domain links from redis+ // remove all images from cloudinary+ ...defaultDomainLinks.map(({ domain, key, proxy }) =>+ proxy+ ? cloudinary.v2.uploader.destroy(`${domain}/${key}`, {+ invalidate: true,+ })+ : Promise.resolve(),+ ),+ ]);const deleteProjectResponse = await Promise.all([// delete project logo from Cloudinary@@ -45,7 +74,7 @@ export async function deleteProject(]);return {+ deleteDomainsLinksResponse,deleteProjectResponse,- deleteDomainsResponse,};}diff --git a/apps/web/ui/modals/add-edit-domain-modal/domain-input.tsx b/apps/web/ui/modals/add-edit-domain-modal/domain-input.tsxindex ef3a44e101..8e782539aa 100644--- a/apps/web/ui/modals/add-edit-domain-modal/domain-input.tsx+++ b/apps/web/ui/modals/add-edit-domain-modal/domain-input.tsx@@ -151,7 +151,7 @@ export default function DomainInput({className="flex flex-1 cursor-pointer items-center justify-between space-x-1 p-3 pl-0"><p className="text-gray-600">This is our website's domain</p>- <InfoTooltip content="If you're using this domain for your main website or app, you should add a subdomain for your short links instead (e.g. go.acme.com)." />+ <InfoTooltip content="If you're using this domain for your main website or app, you should be using a subdomain for your short links instead (e.g. go.acme.com)." /></Label></div></RadioGroup>diff --git a/packages/utils/src/constants/index.ts b/packages/utils/src/constants/index.tsindex ecbfdcee68..2eb1edca84 100644--- a/packages/utils/src/constants/index.ts+++ b/packages/utils/src/constants/index.ts@@ -217,6 +217,7 @@ export const DEFAULT_LINK_PROPS = {};export const DUB_PROJECT_ID = "cl7pj5kq4006835rbjlt2ofka";+export const LEGAL_PROJECT_ID = "xxx";export const LEGAL_USER_ID = "clqei1lgc0000vsnzi01pbf47";export const SAML_PROVIDERS = [diff --git a/packages/utils/src/constants/pricing.tsx b/packages/utils/src/constants/pricing.tsxindex 6114802655..a4b55571ed 100644--- a/packages/utils/src/constants/pricing.tsx+++ b/packages/utils/src/constants/pricing.tsx@@ -24,9 +24,9 @@ export const PLANS = [},featureTitle: "What's included:",features: [- { text: " 25 links/mo" },+ { text: "25 links/mo" },{- text: " 1K tracked clicks/mo",+ text: "1K tracked clicks/mo",},{ text: "30-day analytics retention" },{ text: "1 custom domain" },@@ -54,6 +54,10 @@ export const PLANS = [ids: ["price_1LodNLAlJJEpqkPVQSrt33Lc", // old monthly"price_1LodNLAlJJEpqkPVRxUyCQgZ", // old yearly+ "price_1OTcQBAlJJEpqkPViGtGEsbb", // new monthly (test)+ "price_1OYJeBAlJJEpqkPVLjTsjX0E", // new monthly (prod)+ "price_1OTcQBAlJJEpqkPVYlCMqdLL", // new yearly (test)+ "price_1OYJeBAlJJEpqkPVnPGEZeb0", // new yearly],},limits: {@@ -75,7 +79,7 @@ export const PLANS = [},featureTitle: "Everything in Free, plus:",features: [- { text: " 250 links/mo" },+ { text: "250 links/mo" },{text: "50K tracked clicks/mo",},@@ -105,7 +109,13 @@ export const PLANS = [price: {monthly: 49,yearly: 39,- ids: [],+ ids: [+ "price_1LodLoAlJJEpqkPVJdwv5zrG", // old yearly+ "price_1LoyrCAlJJEpqkPVZ32BV3wm", // new monthly (test)+ "price_1LodLoAlJJEpqkPV9rD0rlNL", // old (no change) & new monthly (prod)+ "price_1OTcRzAlJJEpqkPV6G9iP0Tb", // new yearly (test)+ "price_xxx", // new yearly (prod)+ ],},limits: {links: 1000,@@ -126,7 +136,7 @@ export const PLANS = [},featureTitle: "Everything in Pro, plus:",features: [- { text: " 1,000 links/mo" },+ { text: "1,000 links/mo" },{text: "250K tracked clicks/mo",},