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.

transfer domain to another workspace

Kiran Kdf02e27ca464
diff --git a/apps/web/app/api/domains/[domain]/transfer/route.ts b/apps/web/app/api/domains/[domain]/transfer/route.ts
new file mode 100644
index 0000000000..4d8eabd18c
--- /dev/null
+++ b/apps/web/app/api/domains/[domain]/transfer/route.ts
@@ -0,0 +1,135 @@
+import { DubApiError } from "@/lib/api/errors";
+import { withAuth } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+import z from "@/lib/zod";
+import { NextResponse } from "next/server";
+
+const transferDomainBodySchema = z.object({
+ newWorkspaceId: z
+ .string()
+ .min(1, "Missing new workspace ID.")
+ .transform((v) => v.replace("ws_", "")),
+});
+
+// POST /api/domains/[domain]/transfer – transfer a domain to another workspace
+export const POST = withAuth(
+ async ({ req, headers, session, params, workspace }) => {
+ const { newWorkspaceId } = transferDomainBodySchema.parse(await req.json());
+
+ const newWorkspace = await prisma.project.findUnique({
+ where: { id: newWorkspaceId },
+ select: {
+ linksUsage: true,
+ linksLimit: true,
+ users: {
+ where: {
+ userId: session.user.id,
+ },
+ select: {
+ role: true,
+ },
+ },
+ },
+ });
+
+ if (!newWorkspace || newWorkspace.users.length === 0) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "New workspace not found.",
+ });
+ }
+
+ const domain = await prisma.domain.findUniqueOrThrow({
+ where: { slug: params.domain, projectId: workspace.id },
+ });
+
+ await prisma.domain.update({
+ where: { slug: domain.slug, projectId: workspace.id },
+ data: { projectId: newWorkspaceId },
+ });
+
+ // const link = await prisma.link.findUnique({
+ // where: {
+ // id: params.linkId,
+ // },
+ // include: {
+ // tags: true,
+ // },
+ // });
+
+ // if (newWorkspace.linksUsage >= newWorkspace.linksLimit) {
+ // throw new DubApiError({
+ // code: "forbidden",
+ // message: "New workspace has reached its link limit.",
+ // });
+ // }
+
+ // const linkClicks = await getAnalytics({
+ // linkId: link.id,
+ // endpoint: "clicks",
+ // interval: "30d",
+ // });
+
+ // const response = await Promise.all([
+ // prisma.link.update({
+ // where: {
+ // id: link.id,
+ // },
+ // data: {
+ // projectId: newWorkspaceId,
+ // // remove tags when transferring link
+ // tags: {
+ // deleteMany: {},
+ // },
+ // },
+ // }),
+ // redis.hset(link.domain, {
+ // [link.key.toLowerCase()]: await formatRedisLink({
+ // ...link,
+ // projectId: newWorkspaceId,
+ // }),
+ // }),
+ // recordLink({
+ // link: {
+ // ...link,
+ // projectId: newWorkspaceId,
+ // },
+ // }),
+ // // decrement old workspace usage
+ // prisma.project.update({
+ // where: {
+ // id: workspace.id,
+ // },
+ // data: {
+ // usage: {
+ // decrement: linkClicks,
+ // },
+ // linksUsage: {
+ // decrement: 1,
+ // },
+ // },
+ // }),
+ // // increment new workspace usage
+ // prisma.project.update({
+ // where: {
+ // id: newWorkspaceId,
+ // },
+ // data: {
+ // usage: {
+ // increment: linkClicks,
+ // },
+ // linksUsage: {
+ // increment: 1,
+ // },
+ // },
+ // }),
+ // ]);
+
+ return NextResponse.json(
+ {},
+ {
+ headers,
+ },
+ );
+ },
+);
diff --git a/apps/web/lib/api/domains.ts b/apps/web/lib/api/domains.ts
index 841d9d40a5..3e8ba6312e 100644
--- a/apps/web/lib/api/domains.ts
+++ b/apps/web/lib/api/domains.ts
@@ -272,3 +272,8 @@ export async function deleteDomainAndLinks(
}),
]);
}
+
+// Transfer domain
+const transferDomain = async () => {
+ //
+}
\ No newline at end of file
diff --git a/apps/web/ui/domains/domain-card.tsx b/apps/web/ui/domains/domain-card.tsx
index e3f250cc0a..3b22c96b7a 100644
--- a/apps/web/ui/domains/domain-card.tsx
+++ b/apps/web/ui/domains/domain-card.tsx
@@ -18,11 +18,12 @@ import { capitalize, fetcher, nFormatter, truncate } from "@dub/utils";
import { QrCode } from "lucide-react";
import Link from "next/link";
import punycode from "punycode/";
+import { useRef } from "react";
import useSWR, { mutate } from "swr";
import { useAddEditDomainModal } from "../modals/add-edit-domain-modal";
import { useLinkQRModal } from "../modals/link-qr-modal";
import DomainConfiguration from "./domain-configuration";
-import { useRef } from "react";
+import { useTransferDomainModal } from "../modals/transfer-domain-modal";
export default function DomainCard({ props }: { props: DomainProps }) {
const { id, slug } = useWorkspace();
@@ -73,10 +74,16 @@ export default function DomainCard({ props }: { props: DomainProps }) {
props,
});
+ const { setShowTransferDomainModal, TransferDomainModal } =
+ useTransferDomainModal({
+ props,
+ });
+
return (
<>
<AddEditDomainModal />
<LinkQRModal />
+ <TransferDomainModal />
<div
ref={domainRef}
className="flex flex-col space-y-3 rounded-lg border border-gray-200 bg-white px-5 py-8 sm:px-10"
@@ -132,6 +139,11 @@ export default function DomainCard({ props }: { props: DomainProps }) {
mutate(`/api/domains/${domain}/verify?workspaceId=${id}`);
}}
/>
+ <Button
+ text="Transfer"
+ variant="secondary"
+ onClick={() => setShowTransferDomainModal(true)}
+ />
<Button
text="Edit"
variant="secondary"
diff --git a/apps/web/ui/domains/transfer-domain.tsx b/apps/web/ui/domains/transfer-domain.tsx
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/apps/web/ui/modals/transfer-domain-modal.tsx b/apps/web/ui/modals/transfer-domain-modal.tsx
new file mode 100644
index 0000000000..e1d413321f
--- /dev/null
+++ b/apps/web/ui/modals/transfer-domain-modal.tsx
@@ -0,0 +1,157 @@
+import useWorkspace from "@/lib/swr/use-workspace";
+import useWorkspaces from "@/lib/swr/use-workspaces";
+import { DomainProps } from "@/lib/types";
+import {
+ BlurImage,
+ Button,
+ InputSelect,
+ InputSelectItemProps,
+ Logo,
+ Modal,
+} from "@dub/ui";
+import { APP_NAME, DICEBEAR_AVATAR_URL } from "@dub/utils";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
+import { toast } from "sonner";
+import { mutate } from "swr";
+
+function TransferDomainModal({
+ showTransferDomainModal,
+ setShowTransferDomainModal,
+ props,
+}: {
+ showTransferDomainModal: boolean;
+ setShowTransferDomainModal: Dispatch<SetStateAction<boolean>>;
+ props: DomainProps;
+}) {
+ const { slug: domain } = props;
+
+ const currentWorkspace = useWorkspace();
+ const { workspaces } = useWorkspaces();
+ const [transferring, setTransferring] = useState(false);
+ const [selectedWorkspace, setselectedWorkspace] =
+ useState<InputSelectItemProps | null>(null);
+
+ const transferDomain = async (linkId: string, newWorkspaceId: string) => {
+ return await fetch(
+ `/api/domains/${domain}/transfer?workspaceId=${currentWorkspace.id}`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ newWorkspaceId }),
+ },
+ ).then(async (res) => {
+ if (res.ok) {
+ mutate(
+ (key) => typeof key === "string" && key.startsWith("/api/domains"),
+ undefined,
+ { revalidate: true },
+ );
+ setShowTransferDomainModal(false);
+ return true;
+ } else {
+ const error = await res.json();
+ throw new Error(error.message);
+ }
+ });
+ };
+
+ return (
+ <Modal
+ showModal={showTransferDomainModal}
+ setShowModal={setShowTransferDomainModal}
+ className="overflow-visible"
+ >
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ if (selectedWorkspace) {
+ setTransferring(true);
+ toast.promise(transferDomain(props.id, selectedWorkspace.id), {
+ loading: "Transferring domain...",
+ success: "Successfully transferred domain.",
+ error: "Failed to transfer domain.",
+ });
+ }
+ }}
+ >
+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 text-center sm:px-16">
+ {currentWorkspace?.logo ? (
+ <BlurImage
+ src={currentWorkspace.logo}
+ alt={`Logo for ${currentWorkspace.slug}`}
+ className="h-10 w-10 rounded-full border border-gray-200"
+ width={20}
+ height={20}
+ />
+ ) : (
+ <Logo />
+ )}
+ <h3 className="text-lg font-medium">Transfer {domain}</h3>
+ <p className="text-sm text-gray-500">
+ Transfer this domain and its links to another {APP_NAME} workspace.
+ Link tags will not be transferred.
+ </p>
+ </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" : "",
+ }))
+ : []
+ }
+ selectedItem={selectedWorkspace}
+ setSelectedItem={setselectedWorkspace}
+ inputAttrs={{
+ placeholder: "Select a workspace",
+ }}
+ />
+ <Button
+ disabled={!selectedWorkspace}
+ loading={transferring}
+ text="Confirm transfer"
+ />
+ </div>
+ </form>
+ </Modal>
+ );
+}
+
+export function useTransferDomainModal({ props }: { props: DomainProps }) {
+ const [showTransferDomainModal, setShowTransferDomainModal] = useState(false);
+
+ const TransferDomainModalCallback = useCallback(() => {
+ return props ? (
+ <TransferDomainModal
+ showTransferDomainModal={showTransferDomainModal}
+ setShowTransferDomainModal={setShowTransferDomainModal}
+ props={props}
+ />
+ ) : null;
+ }, [showTransferDomainModal, setShowTransferDomainModal]);
+
+ return useMemo(
+ () => ({
+ setShowTransferDomainModal,
+ TransferDomainModal: TransferDomainModalCallback,
+ }),
+ [setShowTransferDomainModal, TransferDomainModalCallback],
+ );
+}