The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
add additional check while transfer
Kiran K5f8138e730af
diff --git a/apps/web/app/api/cron/domains/transfer/route.ts b/apps/web/app/api/cron/domains/transfer/route.tsindex fa64e72762..c6512e7ada 100644--- a/apps/web/app/api/cron/domains/transfer/route.ts+++ b/apps/web/app/api/cron/domains/transfer/route.ts@@ -1,5 +1,4 @@import { getAnalytics } from "@/lib/analytics";-import { setRootDomain } from "@/lib/api/domains";import { qstash, receiver } from "@/lib/cron";import prisma from "@/lib/prisma";import { formatRedisLink, redis } from "@/lib/upstash";@@ -8,6 +7,10 @@ import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";import { Link } from "@prisma/client";import { NextResponse } from "next/server";+// TODO:+// Update TB+// Send email+const schema = z.object({currentWorkspaceId: z.string(),newWorkspaceId: z.string(),@@ -30,24 +33,10 @@ export async function POST(req: Request) {const { currentWorkspaceId, newWorkspaceId, domain } = schema.parse(body);- const [newWorkspace, domainRecord, links] = await Promise.all([- prisma.project.findUniqueOrThrow({- where: { id: newWorkspaceId },- select: { plan: true },- }),- prisma.domain.findUniqueOrThrow({- where: { slug: domain },- select: {- id: true,- target: true,- type: true,- },- }),- prisma.link.findMany({- where: { domain, projectId: currentWorkspaceId },- take: 100,- }),- ]);+ const links = await prisma.link.findMany({+ where: { domain, projectId: currentWorkspaceId },+ take: 100,+ });if (!links || links.length === 0) {return NextResponse.json({@@ -55,79 +44,9 @@ export async function POST(req: Request) {});}- const linksCount = links.length;const linkIds = links.map((link) => link.id);try {- // Update links in the redis- const updateLinksInRedis = async (links: Link[]) => {- const pipeline = redis.pipeline();-- const formatedLinks = await Promise.all(- links.map(async (link) => {- return {- ...(await formatRedisLink(link)),- projectId: newWorkspaceId,- key: link.key.toLowerCase(),- };- }),- );-- formatedLinks.map((formatedLink) => {- const { key, ...rest } = formatedLink;-- pipeline.hset(domain, {- [formatedLink.key]: rest,- });- });-- await pipeline.exec();- };-- // Update analytics- const updateAnalytics = async (links: Link[]) => {- const linkClicks = (await Promise.all(- links.map((link) =>- getAnalytics({- linkId: link.id,- endpoint: "clicks",- interval: "30d",- }),- ),- )) as number[];-- const totalLinkClicks = linkClicks.reduce((acc, curr) => acc + curr, 0);-- await Promise.all([- prisma.project.update({- where: {- id: currentWorkspaceId,- },- data: {- usage: {- decrement: totalLinkClicks,- },- linksUsage: {- decrement: linksCount,- },- },- }),- prisma.project.update({- where: {- id: newWorkspaceId,- },- data: {- usage: {- increment: totalLinkClicks,- },- linksUsage: {- increment: linksCount,- },- },- }),- ]);- };-await Promise.all([prisma.link.updateMany({where: { domain, projectId: currentWorkspaceId, id: { in: linkIds } },@@ -136,18 +55,8 @@ export async function POST(req: Request) {prisma.linkTag.deleteMany({where: { linkId: { in: linkIds } },}),- updateLinksInRedis(links),- setRootDomain({- id: domainRecord.id,- domain,- projectId: newWorkspaceId,- ...(newWorkspace.plan !== "free" &&- domainRecord.target && {- url: domainRecord.target,- }),- rewrite: domainRecord.type === "rewrite",- }),- updateAnalytics(links),+ updateLinksInRedis({ links, newWorkspaceId, domain }),+ updateAnalytics({ links, newWorkspaceId, currentWorkspaceId }),]);// wait 500 ms before making another request@@ -173,8 +82,90 @@ export async function POST(req: Request) {return NextResponse.json({ error: error.message });}-- // TODO:- // Update TB- // Send email}++// Update links in the redis+const updateLinksInRedis = async ({+ newWorkspaceId,+ domain,+ links,+}: {+ newWorkspaceId: string;+ domain: string;+ links: Link[];+}) => {+ const pipeline = redis.pipeline();++ const formatedLinks = await Promise.all(+ links.map(async (link) => {+ return {+ ...(await formatRedisLink(link)),+ projectId: newWorkspaceId,+ key: link.key.toLowerCase(),+ };+ }),+ );++ formatedLinks.map((formatedLink) => {+ const { key, ...rest } = formatedLink;++ pipeline.hset(domain, {+ [formatedLink.key]: rest,+ });+ });++ await pipeline.exec();+};++// Update links & click usage+const updateAnalytics = async ({+ currentWorkspaceId,+ newWorkspaceId,+ links,+}: {+ currentWorkspaceId: string;+ newWorkspaceId: string;+ links: Link[];+}) => {+ const linkClicks: number[] = await Promise.all(+ links.map((link) =>+ getAnalytics({+ linkId: link.id,+ endpoint: "clicks",+ interval: "30d",+ }),+ ),+ );++ const totalClicks = linkClicks.reduce((acc, curr) => acc + curr, 0);+ const linksCount = links.length;++ await Promise.all([+ prisma.project.update({+ where: {+ id: currentWorkspaceId,+ },+ data: {+ usage: {+ decrement: totalClicks,+ },+ linksUsage: {+ decrement: linksCount,+ },+ },+ }),+ prisma.project.update({+ where: {+ id: newWorkspaceId,+ },+ data: {+ usage: {+ increment: totalClicks,+ },+ linksUsage: {+ increment: linksCount,+ },+ },+ }),+ ]);+};diff --git a/apps/web/app/api/domains/[domain]/transfer/route.ts b/apps/web/app/api/domains/[domain]/transfer/route.tsindex 77888699c9..decba159e8 100644--- a/apps/web/app/api/domains/[domain]/transfer/route.ts+++ b/apps/web/app/api/domains/[domain]/transfer/route.ts@@ -1,3 +1,4 @@+import { setRootDomain } from "@/lib/api/domains";import { DubApiError } from "@/lib/api/errors";import { withAuth } from "@/lib/auth";import { qstash } from "@/lib/cron";@@ -16,12 +17,24 @@ const transferDomainBodySchema = z.object({// POST /api/domains/[domain]/transfer – transfer a domain to another workspaceexport const POST = withAuth(async ({ req, headers, session, params, workspace }) => {- const { newWorkspaceId } = transferDomainBodySchema.parse(await req.json());const { domain } = params;+ const { newWorkspaceId } = transferDomainBodySchema.parse(await req.json());++ if (newWorkspaceId === workspace.id) {+ throw new DubApiError({+ code: "bad_request",+ message: "Please select another workspace to transfer the domain to.",+ });+ }const newWorkspace = await prisma.project.findUnique({where: { id: newWorkspaceId },select: {+ plan: true,+ linksUsage: true,+ linksLimit: true,+ domainsLimit: true,+ name: true,users: {where: {userId: session.user.id,@@ -30,42 +43,88 @@ export const POST = withAuth(role: true,},},+ domains: {+ select: {+ slug: true,+ },+ },},});if (!newWorkspace || newWorkspace.users.length === 0) {throw new DubApiError({code: "not_found",- message: "New workspace not found.",+ message: "New workspace not found. Make sure you have access to it.",});}- const domainFound = await prisma.domain.findUnique({+ const domainRecord = await prisma.domain.findUnique({where: { slug: domain, projectId: workspace.id },});- if (!domainFound) {+ if (!domainRecord) {throw new DubApiError({code: "not_found",- message: "Domain not found",+ message: "Domain not found. Make sure you spelled it correctly.",});}- const response = await prisma.domain.update({- where: { slug: domain, projectId: workspace.id },- data: { projectId: newWorkspaceId },+ if (newWorkspace.domains.length >= newWorkspace.domainsLimit) {+ throw new DubApiError({+ code: "exceeded_limit",+ message: `Workspace ${newWorkspace.name} has reached its domain limit (${newWorkspace.domainsLimit}). You need to upgrade it to accommodate more domains.`,+ });+ }++ if (newWorkspace.linksUsage >= newWorkspace.linksLimit) {+ throw new DubApiError({+ code: "exceeded_limit",+ message: `Workspace ${newWorkspace.name} has reached its link limit. You need to upgrade it to accommodate the links.`,+ });+ }++ const linksCount = await prisma.link.count({+ where: { domain, projectId: workspace.id },});- qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/domains/transfer`,- body: {- currentWorkspaceId: workspace.id,- newWorkspaceId,+ if (newWorkspace.linksUsage + linksCount > newWorkspace.linksLimit) {+ throw new DubApiError({+ code: "exceeded_limit",+ message: `Workspace ${newWorkspace.name} doesn't have enough space to accommodate the links from the current workspace. You need to upgrade it to accommodate the links.`,+ });+ }++ // Update the domain to use the new workspace+ const [domainResponse] = await Promise.all([+ prisma.domain.update({+ where: { slug: domain, projectId: workspace.id },+ data: { projectId: newWorkspaceId },+ }),+ setRootDomain({+ id: domainRecord.id,domain,- },- });+ projectId: newWorkspaceId,+ ...(newWorkspace.plan !== "free" &&+ domainRecord.target && {+ url: domainRecord.target,+ }),+ rewrite: domainRecord.type === "rewrite",+ }),+ ]);++ // If the domain has links, transfer them to the new workspace+ if (workspace.linksUsage > 0) {+ await qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/domains/transfer`,+ body: {+ currentWorkspaceId: workspace.id,+ newWorkspaceId,+ domain,+ },+ });+ }- return NextResponse.json(response, { headers });+ return NextResponse.json(domainResponse, { headers });},{ requiredRole: ["owner"] },);diff --git a/apps/web/ui/modals/transfer-domain-modal.tsx b/apps/web/ui/modals/transfer-domain-modal.tsxindex 941b657d09..1164c5dd59 100644--- a/apps/web/ui/modals/transfer-domain-modal.tsx+++ b/apps/web/ui/modals/transfer-domain-modal.tsx@@ -51,7 +51,8 @@ function TransferDomainModal({setShowTransferDomainModal(false);return true;} else {- const error = await res.json();+ setTransferring(false);+ const { error } = await res.json();throw new Error(error.message);}});@@ -72,7 +73,7 @@ function TransferDomainModal({loading: "Transferring domain...",success:"Domain transfer initiated. We'll send you an email once it's complete.",- error: "Failed to transfer domain.",+ error: (message) => message || "Failed to transfer domain.",});}}}@@ -87,20 +88,14 @@ function TransferDomainModal({</div><div className="flex flex-col space-y-28 bg-gray-50 px-4 py-8 text-left sm:space-y-3 sm:rounded-b-2xl sm:px-16"><InputSelect- items={- workspaces- ? workspaces.map((workspace) => ({- id: workspace.id,- value: workspace.name,- image:- workspace.logo ||- `${DICEBEAR_AVATAR_URL}${workspace.name}`,- disabled: workspace.id === currentWorkspace.id,- label:- workspace.id === currentWorkspace.id ? "Current" : "",- }))- : []- }+ items={(workspaces || []).map((workspace) => ({+ id: workspace.id,+ value: workspace.name,+ image:+ workspace.logo || `${DICEBEAR_AVATAR_URL}${workspace.name}`,+ disabled: workspace.id === currentWorkspace.id,+ label: workspace.id === currentWorkspace.id ? "Current" : "",+ }))}selectedItem={selectedWorkspace}setSelectedItem={setselectedWorkspace}inputAttrs={{