Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: add duplicate dataroom feature

Marc Seitz5e4a8f727492
diff --git a/components/datarooms/settings/duplicate-dataroom.tsx b/components/datarooms/settings/duplicate-dataroom.tsx
new file mode 100644
index 00000000..6f9c9490
--- /dev/null
+++ b/components/datarooms/settings/duplicate-dataroom.tsx
@@ -0,0 +1,73 @@
+import { useState } from "react";
+
+import { toast } from "sonner";
+import { mutate } from "swr";
+
+import { Button } from "@/components/ui/button";
+
+export default function DuplicateDataroom({
+ dataroomId,
+ teamId,
+}: {
+ dataroomId: string;
+ teamId?: string;
+}) {
+ const [loading, setLoading] = useState<boolean>(false);
+
+ const handleDuplicateDataroom = async (
+ e: React.MouseEvent<HTMLButtonElement>,
+ ) => {
+ e.preventDefault();
+ e.stopPropagation();
+
+ if (!teamId) {
+ return;
+ }
+
+ setLoading(true);
+
+ try {
+ toast.promise(
+ fetch(`/api/teams/${teamId}/datarooms/${dataroomId}/duplicate`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }),
+ {
+ loading: "Copying dataroom...",
+ success: () => {
+ mutate(`/api/teams/${teamId}/datarooms`);
+ return "Dataroom copied successfully.";
+ },
+ error: "Failed to copy dataroom.",
+ },
+ );
+ } catch (error) {
+ console.error(error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <div className="rounded-lg border border-gray-200 bg-white">
+ <div className="flex flex-col space-y-3 p-5 sm:p-10">
+ <h2 className="text-xl font-medium">Duplicate Dataroom</h2>
+ <p className="text-sm text-gray-500">
+ Create a new data room with the same content (folders and files) as
+ this data room.
+ </p>
+ </div>
+ <div className="border-b border-gray-200" />
+
+ <div className="flex items-center justify-end px-5 py-4 sm:px-10">
+ <div>
+ <Button onClick={(e) => handleDuplicateDataroom(e)} loading={loading}>
+ Duplicate Dataroom
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/duplicate.ts b/pages/api/teams/[teamId]/datarooms/[id]/duplicate.ts
new file mode 100644
index 00000000..04180591
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/duplicate.ts
@@ -0,0 +1,219 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { getLimits } from "@/ee/limits/server";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { Dataroom, DataroomDocument, DataroomFolder } from "@prisma/client";
+import { getServerSession } from "next-auth/next";
+
+import { newId } from "@/lib/id-helper";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+
+interface DataroomWithContents extends Dataroom {
+ documents: DataroomDocument[];
+ folders: DataroomFolderWithContents[];
+}
+
+interface DataroomFolderWithContents extends DataroomFolder {
+ documents: DataroomDocument[];
+ childFolders: DataroomFolderWithContents[];
+}
+
+// Function to fetch the existing data room structure
+async function fetchDataroomContents(
+ dataroomId: string,
+): Promise<DataroomWithContents> {
+ const dataroom = await prisma.dataroom.findUnique({
+ where: {
+ id: dataroomId,
+ },
+ include: {
+ documents: true,
+ folders: true,
+ },
+ });
+
+ if (!dataroom) {
+ throw new Error(`Dataroom with id ${dataroomId} not found`);
+ }
+
+ const transformFolders = (
+ documents: DataroomDocument[],
+ folders: DataroomFolder[],
+ ): DataroomFolderWithContents[] => {
+ return folders.map((folder) => ({
+ ...folder,
+ documents: documents.filter((doc) => doc.folderId === folder.id),
+ childFolders: transformFolders(
+ documents,
+ folders.filter((f) => f.parentId === folder.id),
+ ),
+ }));
+ };
+
+ return {
+ ...dataroom,
+ documents: dataroom.documents.filter((doc) => !doc.folderId), // only look at root documents
+ folders: transformFolders(dataroom.documents, dataroom.folders),
+ };
+}
+
+// Recursive function to duplicate folders and documents
+async function duplicateFolders(
+ dataroomId: string,
+ folder: DataroomFolderWithContents,
+ parentFolderId?: string,
+) {
+ const newFolder = await prisma.dataroomFolder.create({
+ data: {
+ name: folder.name,
+ path: folder.path,
+ parentId: parentFolderId,
+ dataroomId: dataroomId,
+ },
+ select: { id: true },
+ });
+
+ // Duplicate documents for the current folder
+ await Promise.allSettled(
+ folder.documents.map((doc) =>
+ prisma.dataroomDocument.create({
+ data: {
+ documentId: doc.documentId,
+ dataroomId: dataroomId,
+ folderId: newFolder.id,
+ },
+ }),
+ ),
+ );
+
+ // Duplicate child folders recursively
+ await Promise.allSettled(
+ folder.childFolders.map((childFolder) =>
+ duplicateFolders(dataroomId, childFolder, newFolder.id),
+ ),
+ );
+}
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "POST") {
+ // POST /api/teams/:teamId/datarooms/:id/duplicate
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).end("Unauthorized");
+ return;
+ }
+
+ const { teamId, id: dataroomId } = req.query as {
+ teamId: string;
+ id: string;
+ };
+ const userId = (session.user as CustomUser).id;
+
+ try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ include: {
+ _count: {
+ select: {
+ datarooms: true,
+ },
+ },
+ },
+ });
+
+ if (!team) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ if (team.plan.includes("drtrial")) {
+ return res.status(403).json({
+ message:
+ "You've reached the limit of datarooms. Consider upgrading your plan.",
+ });
+ }
+
+ const dataroom = await prisma.dataroom.findUnique({
+ where: {
+ id: dataroomId,
+ teamId: teamId,
+ },
+ select: { id: true },
+ });
+
+ if (!dataroom) {
+ return res.status(404).json({ message: "Dataroom not found" });
+ }
+
+ // Check if the team has reached the limit of datarooms
+ const limits = await getLimits({ teamId, userId });
+ if (limits && team._count.datarooms >= limits.datarooms) {
+ console.log(
+ "Dataroom limit reached",
+ limits.datarooms,
+ team._count.datarooms,
+ );
+ return res.status(400).json({
+ message:
+ "You've reached the limit of datarooms. Consider upgrading your plan.",
+ });
+ }
+
+ // Fetch the existing data room structure
+ const dataroomContents = await fetchDataroomContents(dataroomId);
+
+ // Create a new data room
+ const pId = newId("dataroom");
+ const newDataroom = await prisma.dataroom.create({
+ data: {
+ pId: pId,
+ name: dataroomContents.name + " (Copy)",
+ teamId: dataroomContents.teamId,
+ documents: {
+ create: dataroomContents.documents.map((doc) => ({
+ documentId: doc.documentId,
+ })),
+ },
+ folders: {
+ create: [],
+ },
+ },
+ });
+
+ // Start the recursive creation with the root folders
+ dataroomContents.folders
+ .filter((folder) => !folder.parentId) // only look at root folders
+ .map(async (folder) => {
+ await duplicateFolders(newDataroom.id, folder);
+ });
+
+ const dataroomWithCount = await prisma.dataroom.findUnique({
+ where: {
+ id: dataroom.id,
+ },
+ include: {
+ _count: { select: { documents: true } },
+ },
+ });
+
+ res.status(201).json(dataroomWithCount);
+ } catch (error) {
+ console.error("Request error", error);
+ res.status(500).json({ error: "Error copying dataroom" });
+ }
+ } else {
+ // We only allow POST requests
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/datarooms/[id]/settings/index.tsx b/pages/datarooms/[id]/settings/index.tsx
index e883c20c..0628a6d7 100644
--- a/pages/datarooms/[id]/settings/index.tsx
+++ b/pages/datarooms/[id]/settings/index.tsx
@@ -5,6 +5,7 @@ import { toast } from "sonner";
import { mutate } from "swr";
import { DataroomHeader } from "@/components/datarooms/dataroom-header";
+import DuplicateDataroom from "@/components/datarooms/settings/duplicate-dataroom";
import AppLayout from "@/components/layouts/app";
import { NavMenu } from "@/components/navigation-menu";
import { Form } from "@/components/ui/form";
@@ -68,7 +69,7 @@ export default function Settings() {
<div className="mx-auto grid w-full items-start gap-6 md:grid-cols-[180px_1fr] lg:grid-cols-[250px_1fr]">
<nav className="grid gap-4 text-sm text-muted-foreground">
<Link
- href={`/datarooms/${dataroom.id}/settings2`}
+ href={`/datarooms/${dataroom.id}/settings`}
className="font-semibold text-primary"
>
General
@@ -106,6 +107,7 @@ export default function Settings() {
})
}
/>
+ <DuplicateDataroom dataroomId={dataroom.id} teamId={teamId} />
{/* <Card>
<CardHeader className="relative">
<CardTitle>Feedback Question</CardTitle>