Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: edit name and path of folders
Marc Seitz50a1076b53c3
diff --git a/components/documents/folder-card.tsx b/components/documents/folder-card.tsxindex cb735beb..70257305 100644--- a/components/documents/folder-card.tsx+++ b/components/documents/folder-card.tsx@@ -11,9 +11,10 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { MoreVertical, FolderIcon } from "lucide-react";-import { useRef } from "react";+import { useRef, useState } from "react";import { FolderWithCount } from "@/lib/swr/use-documents";import { DataroomFolderWithCount } from "@/lib/swr/use-dataroom";+import { EditFolderModal } from "../folders/edit-folder-modal";type FolderCardProps = {folder: FolderWithCount | DataroomFolderWithCount;@@ -27,6 +28,7 @@ export default function FolderCard({isDataroom,dataroomId,}: FolderCardProps) {+ const [openFolder, setOpenFolder] = useState<boolean>(false);const dropdownRef = useRef<HTMLDivElement | null>(null);const folderPath =@@ -35,39 +37,40 @@ export default function FolderCard({: `/documents/tree${folder.path}`;return (- <li className="group/row relative rounded-lg p-3 border-0 dark:bg-secondary ring-1 ring-gray-400 dark:ring-gray-500 transition-all hover:ring-gray-500 hover:dark:ring-gray-400 hover:bg-secondary sm:p-4 flex justify-between items-center">- <div className="min-w-0 flex shrink items-center space-x-2 sm:space-x-4">- <div className="w-8 mx-0.5 sm:mx-1 text-center flex justify-center items-center">- <FolderIcon className="w-8 h-8 " strokeWidth={1} />- </div>-- <div className="flex-col">- <div className="flex items-center">- <h2 className="min-w-0 text-sm font-semibold leading-6 text-foreground truncate max-w-[150px] sm:max-w-md">- <Link href={`${folderPath}`} className="truncate w-full">- <span>{folder.name}</span>- <span className="absolute inset-0" />- </Link>- </h2>+ <>+ <li className="group/row relative rounded-lg p-3 border-0 dark:bg-secondary ring-1 ring-gray-400 dark:ring-gray-500 transition-all hover:ring-gray-500 hover:dark:ring-gray-400 hover:bg-secondary sm:p-4 flex justify-between items-center">+ <div className="min-w-0 flex shrink items-center space-x-2 sm:space-x-4">+ <div className="w-8 mx-0.5 sm:mx-1 text-center flex justify-center items-center">+ <FolderIcon className="w-8 h-8 " strokeWidth={1} /></div>- <div className="mt-1 flex items-center space-x-1 text-xs leading-5 text-muted-foreground">- <p className="truncate">{timeAgo(folder.createdAt)}</p>- <p>•</p>- <p className="truncate">- {folder._count.documents}{" "}- {folder._count.documents === 1 ? "Document" : "Documents"}- </p>- <p>•</p>- <p className="truncate">- {folder._count.childFolders}{" "}- {folder._count.childFolders === 1 ? "Folder" : "Folders"}- </p>++ <div className="flex-col">+ <div className="flex items-center">+ <h2 className="min-w-0 text-sm font-semibold leading-6 text-foreground truncate max-w-[150px] sm:max-w-md">+ <Link href={`${folderPath}`} className="truncate w-full">+ <span>{folder.name}</span>+ <span className="absolute inset-0" />+ </Link>+ </h2>+ </div>+ <div className="mt-1 flex items-center space-x-1 text-xs leading-5 text-muted-foreground">+ <p className="truncate">{timeAgo(folder.createdAt)}</p>+ <p>•</p>+ <p className="truncate">+ {folder._count.documents}{" "}+ {folder._count.documents === 1 ? "Document" : "Documents"}+ </p>+ <p>•</p>+ <p className="truncate">+ {folder._count.childFolders}{" "}+ {folder._count.childFolders === 1 ? "Folder" : "Folders"}+ </p>+ </div></div></div>- </div>- <div className="flex flex-row space-x-2">- {/* <Link+ <div className="flex flex-row space-x-2">+ {/* <LinkonClick={(e) => {e.stopPropagation();}}@@ -81,22 +84,25 @@ export default function FolderCard({</p></Link> */}- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- // size="icon"- variant="outline"- className="h-8 lg:h-9 w-8 lg:w-9 p-0 z-10 bg-transparent border-gray-200 dark:border-gray-700 hover:bg-gray-200 hover:dark:bg-gray-700"- >- <span className="sr-only">Open menu</span>- <MoreVertical className="w-4 h-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" ref={dropdownRef}>- <DropdownMenuLabel>Actions</DropdownMenuLabel>- <DropdownMenuSeparator />+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ // size="icon"+ variant="outline"+ className="h-8 lg:h-9 w-8 lg:w-9 p-0 z-10 bg-transparent border-gray-200 dark:border-gray-700 hover:bg-gray-200 hover:dark:bg-gray-700"+ >+ <span className="sr-only">Open menu</span>+ <MoreVertical className="w-4 h-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" ref={dropdownRef}>+ <DropdownMenuLabel>Actions</DropdownMenuLabel>+ <DropdownMenuItem onClick={() => setOpenFolder(true)}>+ Rename folder+ </DropdownMenuItem>+ <DropdownMenuSeparator />- {/* <DropdownMenuItem+ {/* <DropdownMenuItemonClick={(event) => handleButtonClick(event, prismaDocument.id)}className="text-destructive focus:bg-destructive focus:text-destructive-foreground duration-200">@@ -108,9 +114,20 @@ export default function FolderCard({</>)}</DropdownMenuItem> */}- </DropdownMenuContent>- </DropdownMenu>- </div>- </li>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </li>+ {openFolder ? (+ <EditFolderModal+ open={openFolder}+ setOpen={setOpenFolder}+ folderId={folder.id}+ name={folder.name}+ isDataroom={isDataroom}+ dataroomId={dataroomId}+ />+ ) : null}+ </>);}diff --git a/components/folders/edit-folder-modal.tsx b/components/folders/edit-folder-modal.tsxnew file mode 100644index 00000000..e45d8545--- /dev/null+++ b/components/folders/edit-folder-modal.tsx@@ -0,0 +1,125 @@+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { useTeam } from "@/context/team-context";+import { useState } from "react";+import { toast } from "sonner";+import { UpgradePlanModal } from "../billing/upgrade-plan-modal";+import { usePlan } from "@/lib/swr/use-billing";+import { useAnalytics } from "@/lib/analytics";+import { mutate } from "swr";+import { Folder } from "@prisma/client";+import { useRouter } from "next/router";++export function EditFolderModal({+ open,+ setOpen,+ name,+ folderId,+ onAddition,+ isDataroom,+ dataroomId,+ children,+}: {+ open?: boolean;+ setOpen?: React.Dispatch<React.SetStateAction<boolean>>;+ name: string;+ folderId: string;+ onAddition?: (folderName: string) => void;+ isDataroom?: boolean;+ dataroomId?: string;+ children?: React.ReactNode;+}) {+ const [folderName, setFolderName] = useState<string>(name);+ const [loading, setLoading] = useState<boolean>(false);++ const teamInfo = useTeam();++ const handleSubmit = async (event: any) => {+ event.preventDefault();+ event.stopPropagation();++ if (folderName == "") return;++ setLoading(true);+ const endpointTargetType =+ isDataroom && dataroomId ? `datarooms/${dataroomId}/folders` : "folders";++ try {+ const response = await fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/manage`,+ {+ method: "PUT",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ folderId: folderId,+ name: folderName,+ }),+ },+ );++ if (!response.ok) {+ const { message } = await response.json();+ setLoading(false);+ toast.error(message);+ return;+ }++ const { parentFolderPath } = await response.json();++ toast.success("Folder updated successfully! 🎉");++ mutate(`/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}`);+ mutate(+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}${parentFolderPath}`,+ );+ } catch (error) {+ setLoading(false);+ toast.error("Error updating folder. Please try again.");+ return;+ } finally {+ setLoading(false);+ setOpen(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger asChild>{children}</DialogTrigger>+ <DialogContent className="sm:max-w-[425px]">+ <DialogHeader className="text-start">+ <DialogTitle>Edit Folder</DialogTitle>+ <DialogDescription>Enter a new folder name.</DialogDescription>+ </DialogHeader>+ <form onSubmit={handleSubmit}>+ <Label htmlFor="folder-name-update" className="opacity-80">+ Folder Name+ </Label>+ <Input+ id="folder-name-update"+ value={folderName}+ placeholder="folder-123"+ className="w-full mt-1 mb-4"+ onChange={(e) => setFolderName(e.target.value)}+ />+ <DialogFooter>+ <Button type="submit" className="w-full h-9" loading={loading}>+ Update folder+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/folders/manage.ts b/pages/api/teams/[teamId]/datarooms/[id]/folders/manage.tsnew file mode 100644index 00000000..6e55a7a2--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/folders/manage.ts@@ -0,0 +1,143 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";+import { errorhandler } from "@/lib/errorHandler";+import slugify from "@sindresorhus/slugify";+import { authOptions } from "@/pages/api/auth/[...nextauth]";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "PUT") {+ // PUT /api/teams/:teamId/datarooms/:id/folders/manage+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ res.status(401).end("Unauthorized");+ return;+ }+ const userId = (session.user as CustomUser).id;+ const { teamId, id: dataroomId } = req.query as {+ teamId: string;+ id: string;+ };+ const { folderId, name } = req.body as { folderId: string; name: string };++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId: userId,+ },+ },+ },+ });++ if (!team) {+ return res.status(401).end("Unauthorized");+ }++ const folder = await prisma.dataroomFolder.findUnique({+ where: {+ id: folderId,+ dataroomId: dataroomId,+ },+ select: {+ name: true,+ path: true,+ },+ });++ if (!folder) {+ return res.status(404).json({ message: "Folder not found" });+ }++ console.log("Folder old path", folder.path);++ // take the old path and replace the last part with the new name+ const newPath = folder.path.split("/");+ newPath.pop();+ newPath.push(slugify(name));++ console.log("Folder new path", newPath.join("/"));++ await prisma.dataroomFolder.update({+ where: {+ id: folderId,+ },+ data: {+ name: name,+ path: newPath.join("/"),+ },+ });++ return res+ .status(200)+ .json({ message: "Folder name updated successfully" });+ } catch (error) {+ errorhandler(error, res);+ }+ } else if (req.method === "DELETE") {+ // DELETE /api/teams/:teamId/folders/manage+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ res.status(401).end("Unauthorized");+ return;+ }++ const { teamId } = req.query as { teamId: string };+ const { folderId } = req.body as { folderId: string };++ const userId = (session.user as CustomUser).id;++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId: userId,+ },+ },+ },+ });++ if (!team) {+ return res.status(401).end("Unauthorized");+ }++ const documents = await prisma.document.findMany({+ where: {+ folderId: folderId,+ teamId: teamId,+ },+ select: {+ id: true,+ },+ });++ if (documents.length > 0) {+ return res+ .status(400)+ .json({ message: "Folder contains documents. Move them first" });+ }++ await prisma.folder.delete({+ where: {+ id: folderId,+ },+ });++ return res.status(204).end(); // 204 No Content response for successful deletes+ } catch (error) {+ errorhandler(error, res);+ }+ } else {+ // We only allow GET, PUT and DELETE requests+ res.setHeader("Allow", ["PUT", "DELETE"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/api/teams/[teamId]/folders/manage.ts b/pages/api/teams/[teamId]/folders/manage.tsnew file mode 100644index 00000000..1019414a--- /dev/null+++ b/pages/api/teams/[teamId]/folders/manage.ts@@ -0,0 +1,139 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";+import { errorhandler } from "@/lib/errorHandler";+import slugify from "@sindresorhus/slugify";+import { authOptions } from "@/pages/api/auth/[...nextauth]";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "PUT") {+ // PUT /api/teams/:teamId/folders/manage+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ res.status(401).end("Unauthorized");+ return;+ }+ const userId = (session.user as CustomUser).id;+ const { teamId } = req.query as { teamId: string };+ const { folderId, name } = req.body as { folderId: string; name: string };++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId: userId,+ },+ },+ },+ });++ if (!team) {+ return res.status(401).end("Unauthorized");+ }++ const folder = await prisma.folder.findUnique({+ where: {+ id: folderId,+ },+ select: {+ name: true,+ path: true,+ },+ });++ if (!folder) {+ return res.status(404).json({ message: "Folder not found" });+ }++ console.log("Folder old path", folder.path);++ // take the old path and replace the last part with the new name+ const newPath = folder.path.split("/");+ newPath.pop();+ newPath.push(slugify(name));++ console.log("Folder new path", newPath.join("/"));++ await prisma.folder.update({+ where: {+ id: folderId,+ },+ data: {+ name: name,+ path: newPath.join("/"),+ },+ });++ return res+ .status(200)+ .json({ message: "Folder name updated successfully" });+ } catch (error) {+ errorhandler(error, res);+ }+ } else if (req.method === "DELETE") {+ // DELETE /api/teams/:teamId/folders/manage+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ res.status(401).end("Unauthorized");+ return;+ }++ const { teamId } = req.query as { teamId: string };+ const { folderId } = req.body as { folderId: string };++ const userId = (session.user as CustomUser).id;++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId: userId,+ },+ },+ },+ });++ if (!team) {+ return res.status(401).end("Unauthorized");+ }++ const documents = await prisma.document.findMany({+ where: {+ folderId: folderId,+ teamId: teamId,+ },+ select: {+ id: true,+ },+ });++ if (documents.length > 0) {+ return res+ .status(400)+ .json({ message: "Folder contains documents. Move them first" });+ }++ await prisma.folder.delete({+ where: {+ id: folderId,+ },+ });++ return res.status(204).end(); // 204 No Content response for successful deletes+ } catch (error) {+ errorhandler(error, res);+ }+ } else {+ // We only allow GET, PUT and DELETE requests+ res.setHeader("Allow", ["PUT", "DELETE"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}