Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
Add dataroom folder to other dataroom (#1267)
Ashish Viradiyafc960770e3fe
diff --git a/components/documents/add-folder-to-dataroom-modal.tsx b/components/documents/add-folder-to-dataroom-modal.tsxindex 96ddc141..ba36b51f 100644--- a/components/documents/add-folder-to-dataroom-modal.tsx+++ b/components/documents/add-folder-to-dataroom-modal.tsx@@ -1,9 +1,8 @@-import { useRouter } from "next/router";-import { useState } from "react";import { useTeam } from "@/context/team-context";import { toast } from "sonner";+import { mutate } from "swr";import { Button } from "@/components/ui/button";import {@@ -32,13 +31,14 @@ export function AddFolderToDataroomModal({setOpen,folderId,folderName,+ dataroomId,}: {open: boolean;setOpen: React.Dispatch<React.SetStateAction<boolean>>;folderId?: string;folderName?: string;+ dataroomId?: string;}) {- const router = useRouter();const [selectedDataroom, setSelectedDataroom] = useState<string | null>(null);const [loading, setLoading] = useState<boolean>(false);@@ -56,7 +56,9 @@ export function AddFolderToDataroomModal({setLoading(true);try {const response = await fetch(- `/api/teams/${teamId}/folders/manage/${folderId}/add-to-dataroom`,+ !!dataroomId+ ? `/api/teams/${teamId}/datarooms/${dataroomId}/folders/manage/${folderId}/dataroom-to-dataroom`+ : `/api/teams/${teamId}/folders/manage/${folderId}/add-to-dataroom`,{method: "POST",headers: {@@ -74,6 +76,8 @@ export function AddFolderToDataroomModal({toast.error(message);return;}+ dataroomId &&+ mutate(`/api/teams/${teamId}/datarooms/${dataroomId}/folders`);toast.success("Folder added to dataroom successfully!");} catch (error) {@@ -100,8 +104,13 @@ export function AddFolderToDataroomModal({</SelectTrigger><SelectContent>{datarooms?.map((dataroom) => (- <SelectItem key={dataroom.id} value={dataroom.id}>+ <SelectItem+ key={dataroom.id}+ value={dataroom.id}+ disabled={dataroom.id === dataroomId}+ >{dataroom.name}+ {dataroom.id === dataroomId ? " (current)" : ""}</SelectItem>))}</SelectContent>diff --git a/components/documents/folder-card.tsx b/components/documents/folder-card.tsxindex 548b7a27..2816fabf 100644--- a/components/documents/folder-card.tsx+++ b/components/documents/folder-card.tsx@@ -261,24 +261,24 @@ export default function FolderCard({Rename</DropdownMenuItem>{!isDataroom ? (- <>- <DropdownMenuItem- onClick={(e) => handleCreateDataroom(e, folder.id)}- >- Create dataroom from folder- </DropdownMenuItem>- <DropdownMenuItem- onClick={(e) => {- e.preventDefault();- e.stopPropagation();- setAddDataroomOpen(true);- }}- >- <BetweenHorizontalStartIcon className="mr-2 h-4 w-4" />- Add folder to dataroom- </DropdownMenuItem>- </>+ <DropdownMenuItem+ onClick={(e) => handleCreateDataroom(e, folder.id)}+ >+ Create dataroom from folder+ </DropdownMenuItem>) : null}+ <DropdownMenuItem+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setAddDataroomOpen(true);+ }}+ >+ <BetweenHorizontalStartIcon className="mr-2 h-4 w-4" />+ {isDataroom+ ? "Copy folder to other dataroom"+ : "Add folder to dataroom"}+ </DropdownMenuItem><DropdownMenuSeparator /><DropdownMenuItem@@ -323,6 +323,7 @@ export default function FolderCard({setOpen={setAddDataroomOpen}folderId={folder.id}folderName={folder.name}+ dataroomId={dataroomId}/>) : null}</>diff --git a/pages/api/teams/[teamId]/datarooms/[id]/folders/manage/[folderId]/dataroom-to-dataroom.ts b/pages/api/teams/[teamId]/datarooms/[id]/folders/manage/[folderId]/dataroom-to-dataroom.tsnew file mode 100644index 00000000..daa81a1a--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/folders/manage/[folderId]/dataroom-to-dataroom.ts@@ -0,0 +1,163 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import slugify from "@sindresorhus/slugify";+import { getServerSession } from "next-auth/next";++import { errorhandler } from "@/lib/errorHandler";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++interface FolderWithContents {+ id: string;+ name: string;+ documents: { documentId: string }[];+ childFolders: FolderWithContents[];+}++async function fetchFolderContents(+ folderId: string,+): Promise<FolderWithContents> {+ const folder = await prisma.dataroomFolder.findUnique({+ where: { id: folderId },+ include: {+ documents: { select: { documentId: true } },+ childFolders: true,+ },+ });++ if (!folder) {+ throw new Error(`Folder with id ${folderId} not found`);+ }++ const childFolders = await Promise.all(+ folder.childFolders.map((childFolder) =>+ fetchFolderContents(childFolder.id),+ ),+ );++ return {+ id: folder.id,+ name: folder.name,+ documents: folder.documents,+ childFolders: childFolders,+ };+}++async function createDataroomStructure(+ dataroomId: string,+ folder: FolderWithContents,+ parentPath: string = "",+ parentFolderId?: string,+): Promise<void> {+ const currentPath = `${parentPath}/${slugify(folder.name)}`;++ const dataroomFolder = await prisma.dataroomFolder.create({+ data: {+ dataroomId,+ path: currentPath,+ name: folder.name,+ parentId: parentFolderId,+ documents: {+ create: folder.documents.map((doc) => ({+ documentId: doc.documentId,+ dataroomId: dataroomId,+ })),+ },+ },+ });++ await Promise.all(+ folder.childFolders.map((childFolder) =>+ createDataroomStructure(+ dataroomId,+ childFolder,+ currentPath,+ dataroomFolder.id,+ ),+ ),+ );+}++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "POST") {+ // POST /api/teams/:teamId/dataroomId/:id/folders/manage/:folderId/dataroom-to-dataroom+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const {+ teamId,+ folderId,+ id: roomId,+ } = req.query as {+ teamId: string;+ folderId: string;+ id: string;+ };+ const { dataroomId } = req.body as { dataroomId: string };+ const userId = (session.user as CustomUser).id;++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId,+ },+ },+ datarooms: {+ some: {+ id: roomId,+ folders: {+ some: {+ id: {+ equals: folderId,+ },+ },+ },+ },+ },+ },+ select: {+ id: true,+ plan: true,+ },+ });++ if (!team) {+ return res.status(401).end("Unauthorized");+ }++ if (team.plan === "free" || team.plan === "pro") {+ return res.status(403).json({+ message: "Upgrade your plan to use datarooms.",+ });+ }++ try {+ const folderContents = await fetchFolderContents(folderId);+ await createDataroomStructure(dataroomId, folderContents);+ } catch (error) {+ return res.status(500).json({+ message: "Document already exists in dataroom!",+ });+ }++ return res.status(200).json({+ message: "Folder added to dataroom!",+ });+ } catch (error) {+ errorhandler(error, res);+ }+ } else {+ // We only allow POST requests+ res.setHeader("Allow", ["POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}