Skip to content

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

feat: add folder to dataroom

Marc Seitz5863af5ade92
diff --git a/components/documents/add-folder-to-dataroom-modal.tsx b/components/documents/add-folder-to-dataroom-modal.tsx
new file mode 100644
index 00000000..96ddc141
--- /dev/null
+++ b/components/documents/add-folder-to-dataroom-modal.tsx
@@ -0,0 +1,138 @@
+import { useRouter } from "next/router";
+
+import { useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { toast } from "sonner";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+
+import useDatarooms from "@/lib/swr/use-datarooms";
+
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "../ui/select";
+
+export type TSelectedDataroom = { id: string; name: string } | null;
+
+export function AddFolderToDataroomModal({
+ open,
+ setOpen,
+ folderId,
+ folderName,
+}: {
+ open: boolean;
+ setOpen: React.Dispatch<React.SetStateAction<boolean>>;
+ folderId?: string;
+ folderName?: string;
+}) {
+ const router = useRouter();
+ const [selectedDataroom, setSelectedDataroom] = useState<string | null>(null);
+ const [loading, setLoading] = useState<boolean>(false);
+
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const { datarooms } = useDatarooms();
+
+ const handleSubmit = async (event: any) => {
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (!selectedDataroom) return;
+
+ setLoading(true);
+ try {
+ const response = await fetch(
+ `/api/teams/${teamId}/folders/manage/${folderId}/add-to-dataroom`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ dataroomId: selectedDataroom,
+ }),
+ },
+ );
+
+ if (!response.ok) {
+ const { message } = await response.json();
+ setLoading(false);
+ toast.error(message);
+ return;
+ }
+
+ toast.success("Folder added to dataroom successfully!");
+ } catch (error) {
+ console.error("Error adding folder to dataroom", error);
+ toast.error("Failed to add folder to dataroom. Try again.");
+ } finally {
+ setLoading(false);
+ setOpen(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader className="text-start">
+ <DialogTitle>
+ <span className="font-bold">{folderName}</span>
+ </DialogTitle>
+ <DialogDescription>Add your folder to a dataroom.</DialogDescription>
+ </DialogHeader>
+ <Select onValueChange={(value) => setSelectedDataroom(value)}>
+ <SelectTrigger className="min-w-fit">
+ <SelectValue placeholder="Select a dataroom" />
+ </SelectTrigger>
+ <SelectContent>
+ {datarooms?.map((dataroom) => (
+ <SelectItem key={dataroom.id} value={dataroom.id}>
+ {dataroom.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <form>
+ <div className="mb-2"></div>
+
+ <DialogFooter>
+ <Button
+ onClick={handleSubmit}
+ className="flex h-9 w-full gap-1"
+ loading={loading}
+ disabled={!selectedDataroom}
+ >
+ {!selectedDataroom ? (
+ "Select a dataroom"
+ ) : (
+ <>
+ Add to{" "}
+ <span className="font-medium">
+ {
+ datarooms?.filter((d) => d.id === selectedDataroom)[0]
+ .name
+ }
+ </span>
+ </>
+ )}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/documents/folder-card.tsx b/components/documents/folder-card.tsx
index 3bdf39ad..b180fdf1 100644
--- a/components/documents/folder-card.tsx
+++ b/components/documents/folder-card.tsx
@@ -3,7 +3,12 @@ import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { TeamContextType } from "@/context/team-context";
-import { FolderIcon, MoreVertical, TrashIcon } from "lucide-react";
+import {
+ BetweenHorizontalStartIcon,
+ FolderIcon,
+ MoreVertical,
+ TrashIcon,
+} from "lucide-react";
import { toast } from "sonner";
import { mutate } from "swr";
@@ -22,6 +27,7 @@ import { FolderWithCount } from "@/lib/swr/use-documents";
import { timeAgo } from "@/lib/utils";
import { EditFolderModal } from "../folders/edit-folder-modal";
+import { AddFolderToDataroomModal } from "./add-folder-to-dataroom-modal";
type FolderCardProps = {
folder: FolderWithCount | DataroomFolderWithCount;
@@ -38,6 +44,8 @@ export default function FolderCard({
const [openFolder, setOpenFolder] = useState<boolean>(false);
const [isFirstClick, setIsFirstClick] = useState<boolean>(false);
const [menuOpen, setMenuOpen] = useState<boolean>(false);
+ const [addDataroomOpen, setAddDataroomOpen] = useState<boolean>(false);
+
const dropdownRef = useRef<HTMLDivElement | null>(null);
const folderPath =
@@ -65,12 +73,12 @@ export default function FolderCard({
// https://github.com/radix-ui/primitives/issues/1241#issuecomment-1888232392
useEffect(() => {
- if (!openFolder) {
+ if (!openFolder || !addDataroomOpen) {
setTimeout(() => {
document.body.style.pointerEvents = "";
});
}
- }, [openFolder]);
+ }, [openFolder, addDataroomOpen]);
const handleButtonClick = (event: any, documentId: string) => {
event.stopPropagation();
@@ -233,11 +241,17 @@ export default function FolderCard({
Rename
</DropdownMenuItem>
{!isDataroom ? (
- <DropdownMenuItem
- onClick={(e) => handleCreateDataroom(e, folder.id)}
- >
- Create dataroom from folder
- </DropdownMenuItem>
+ <>
+ <DropdownMenuItem
+ onClick={(e) => handleCreateDataroom(e, folder.id)}
+ >
+ Create dataroom from folder
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setAddDataroomOpen(true)}>
+ <BetweenHorizontalStartIcon className="mr-2 h-4 w-4" />
+ Add folder to dataroom
+ </DropdownMenuItem>
+ </>
) : null}
<DropdownMenuSeparator />
@@ -268,6 +282,14 @@ export default function FolderCard({
dataroomId={dataroomId}
/>
) : null}
+ {addDataroomOpen ? (
+ <AddFolderToDataroomModal
+ open={addDataroomOpen}
+ setOpen={setAddDataroomOpen}
+ folderId={folder.id}
+ folderName={folder.name}
+ />
+ ) : null}
</>
);
}
diff --git a/pages/api/teams/[teamId]/folders/manage/[folderId]/add-to-dataroom.ts b/pages/api/teams/[teamId]/folders/manage/[folderId]/add-to-dataroom.ts
new file mode 100644
index 00000000..36671d7b
--- /dev/null
+++ b/pages/api/teams/[teamId]/folders/manage/[folderId]/add-to-dataroom.ts
@@ -0,0 +1,200 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { Document, Folder } from "@prisma/client";
+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: { id: string }[];
+ childFolders: FolderWithContents[];
+}
+
+async function fetchFolderContents(
+ folderId: string,
+): Promise<FolderWithContents> {
+ const folder = await prisma.folder.findUnique({
+ where: { id: folderId },
+ include: {
+ documents: { select: { id: 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.id,
+ dataroomId,
+ })),
+ },
+ },
+ });
+
+ console.log("Created dataroom folder", dataroomFolder);
+
+ 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/folders/manage/:folderId/add-to-dataroom
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const { teamId, folderId } = req.query as {
+ teamId: string;
+ folderId: 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: dataroomId,
+ },
+ },
+ 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);
+
+ // const folderWithDocuments = await prisma.folder.findUnique({
+ // where: {
+ // id: folderId,
+ // },
+ // include: {
+ // childFolders: true,
+ // documents: { select: { id: true } },
+ // },
+ // });
+
+ // if (!folderWithDocuments) {
+ // return res.status(404).json({
+ // message: "Folder not found.",
+ // });
+ // }
+
+ // const parentPath = "/" + slugify(folderWithDocuments.name);
+ // await prisma.dataroomFolder.create({
+ // data: {
+ // dataroomId: dataroomId,
+ // path: parentPath,
+ // name: folderWithDocuments.name,
+ // documents: {
+ // create: folderWithDocuments.documents.map((document) => ({
+ // documentId: document.id,
+ // dataroomId: dataroomId,
+ // })),
+ // },
+ // childFolders: {
+ // create: folderWithDocuments.childFolders.map((childFolder) => ({
+ // name: childFolder.name,
+ // dataroomId: dataroomId,
+ // path: parentPath + "/" + slugify(childFolder.name),
+ // documents:...
+ // })),
+ // },
+ // },
+ // });
+ } 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`);
+ }
+}