Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: set group permission for doc from dataroom setting
Ashish Viradiya6e60db6b9d99
diff --git a/components/datarooms/dataroom-items-list.tsx b/components/datarooms/dataroom-items-list.tsxindex ecd3354c..6b5d7f19 100644--- a/components/datarooms/dataroom-items-list.tsx+++ b/components/datarooms/dataroom-items-list.tsx@@ -27,9 +27,11 @@ import { toast } from "sonner";import { moveDataroomDocumentToFolder } from "@/lib/documents/move-dataroom-documents";import { moveDataroomFolderToFolder } from "@/lib/documents/move-dataroom-folders";+import { useDataroomPermissions } from "@/lib/hooks/use-dataroom-permissions";import {DataroomFolderDocument,DataroomFolderWithCount,+ useDataroom,} from "@/lib/swr/use-dataroom";import useDataroomGroups from "@/lib/swr/use-dataroom-groups";import { useMediaQuery } from "@/lib/utils/use-media-query";@@ -75,7 +77,10 @@ export function DataroomItemsList({documentCount: number;}) {const { viewerGroups } = useDataroomGroups();+ const { dataroom } = useDataroom();const { isMobile } = useMediaQuery();+ const { applyDefaultPermissions, inheritParentPermissions } =+ useDataroomPermissions();const [uploads, setUploads] = useState<UploadState[]>([]);const [rejectedFiles, setRejectedFiles] = useState<RejectedFile[]>([]);@@ -547,11 +552,48 @@ export function DataroomItemsList({dataroomDocumentId: string;}[],) => {- if (viewerGroups && viewerGroups.length > 0) {+ const hasGroups = viewerGroups && viewerGroups.length > 0;+ if (!hasGroups) return;++ const defaultPermission =+ dataroom?.defaultGroupPermission || "ask_every_time";+ if (defaultPermission === "ask_every_time" && files.length > 0) {setUploadedFiles(files);setShowGroupPermissions(true);+ return;+ }++ if (defaultPermission === "inherit_from_parent") {+ const isRootLevel = !folderPathName || folderPathName.length === 0;+ if (isRootLevel) {+ setUploadedFiles(files);+ setShowGroupPermissions(true);+ } else {+ const documentIds = files.map((file) => file.documentId);+ inheritParentPermissions(+ dataroomId,+ documentIds,+ folderPathName.join("/"),+ ).catch((error) => {+ console.error("Failed to inherit parent permissions:", error);+ toast.error("Failed to inherit parent permissions");+ });+ }+ return;+ }++ if (defaultPermission === "use_default_permissions") {+ const documentIds = files.map((file) => file.documentId);+ applyDefaultPermissions(dataroomId, documentIds).catch((error) => {+ console.error("Failed to apply default permissions:", error);+ toast.error("Failed to apply default permissions");+ });+ return;+ }++ if (defaultPermission === "no_permissions") {+ return;}- return;};return (diff --git a/components/datarooms/settings/permission-settings.tsx b/components/datarooms/settings/permission-settings.tsxnew file mode 100644index 00000000..842e130f--- /dev/null+++ b/components/datarooms/settings/permission-settings.tsx@@ -0,0 +1,342 @@+import { useState } from "react";++import { useTeam } from "@/context/team-context";+import { AnimatePresence, motion } from "motion/react";+import { toast } from "sonner";+import useSWR from "swr";++import useDataroomGroups from "@/lib/swr/use-dataroom-groups";+import { fetcher } from "@/lib/utils";++import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import { Label } from "@/components/ui/label";+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import { Switch } from "@/components/ui/switch";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";++type DefaultGroupPermissionStrategy =+ | "ask_every_time"+ | "inherit_from_parent"+ | "use_default_permissions"+ | "no_permissions";++interface PermissionSettingsProps {+ dataroomId: string;+}++export default function PermissionSettings({+ dataroomId,+}: PermissionSettingsProps) {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;+ const { viewerGroups, mutate: mutateGroups } = useDataroomGroups();++ const { data: dataroomData, mutate: mutateDataroom } = useSWR<{+ id: string;+ name: string;+ pId: string;+ defaultGroupPermission: DefaultGroupPermissionStrategy;+ }>(+ dataroomId ? `/api/teams/${teamId}/datarooms/${dataroomId}` : null,+ fetcher,+ );++ const [isUpdating, setIsUpdating] = useState(false);++ const handlePermissionChange = async (+ value: DefaultGroupPermissionStrategy,+ ) => {+ if (!dataroomId || !teamId || isUpdating || !dataroomData) return;+ setIsUpdating(true);++ const optimisticData = { ...dataroomData, defaultGroupPermission: value };++ const mutation = async () => {+ const res = await fetch(`/api/teams/${teamId}/datarooms/${dataroomId}`, {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ defaultGroupPermission: value,+ }),+ });++ if (!res.ok) {+ throw new Error("Failed to update permission settings");+ }++ return res.json();+ };++ try {+ await toast.promise(+ mutateDataroom(mutation(), {+ optimisticData,+ rollbackOnError: true,+ populateCache: true,+ revalidate: false,+ }),+ {+ loading: "Updating permission settings...",+ success: "Permission settings updated successfully",+ error: (err) => err.message,+ },+ );+ } catch (error) {+ console.error(error);+ } finally {+ setIsUpdating(false);+ }+ };++ const updateGroupPermissions = async (+ groupId: string,+ permissions: {+ defaultCanView?: boolean;+ defaultCanDownload?: boolean;+ },+ ) => {+ if (!teamId) return;++ toast.promise(+ fetch(`/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}`, {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(permissions),+ }).then(async (res) => {+ if (!res.ok) {+ throw new Error("Failed to update group permissions");+ }+ await mutateGroups();+ }),+ {+ loading: "Updating group permissions...",+ success: "Group permissions updated successfully",+ error: "Failed to update group permissions",+ },+ );+ };++ const handleViewPermissionChange = async (+ groupId: string,+ checked: boolean,+ ) => {+ const group = viewerGroups?.find((g) => g.id === groupId);+ if (!group) return;++ // If disabling view, also disable download in single API call+ if (!checked && (group.defaultCanDownload ?? false)) {+ await updateGroupPermissions(groupId, {+ defaultCanView: checked,+ defaultCanDownload: false,+ });+ } else {+ await updateGroupPermissions(groupId, {+ defaultCanView: checked,+ });+ }+ };++ const handleDownloadPermissionChange = async (+ groupId: string,+ checked: boolean,+ ) => {+ const group = viewerGroups?.find((g) => g.id === groupId);+ if (!group) return;++ // If enabling download, also enable view in single API call+ if (checked && !(group.defaultCanView ?? false)) {+ await updateGroupPermissions(groupId, {+ defaultCanView: true,+ defaultCanDownload: checked,+ });+ } else {+ await updateGroupPermissions(groupId, {+ defaultCanDownload: checked,+ });+ }+ };++ const currentStrategy =+ dataroomData?.defaultGroupPermission ?? "ask_every_time";+ const showGroupSettings = currentStrategy === "use_default_permissions";++ return (+ <Card>+ <CardHeader>+ <CardTitle>Permission Settings</CardTitle>+ <CardDescription>+ Configure how group permissions are handled for new documents.+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-6">+ <RadioGroup+ value={currentStrategy}+ onValueChange={handlePermissionChange}+ disabled={isUpdating || !dataroomData}+ className="space-y-3"+ >+ <div className="flex items-center space-x-3">+ <RadioGroupItem value="ask_every_time" id="ask_every_time" />+ <div>+ <Label htmlFor="ask_every_time" className="text-sm font-medium">+ Ask every time+ </Label>+ <p className="text-xs text-muted-foreground">+ Show permissions modal for each upload+ </p>+ </div>+ </div>++ <div className="flex items-center space-x-3">+ <RadioGroupItem+ value="inherit_from_parent"+ id="inherit_from_parent"+ />+ <div>+ <Label+ htmlFor="inherit_from_parent"+ className="text-sm font-medium"+ >+ Inherit from parent folder+ </Label>+ <p className="text-xs text-muted-foreground">+ New documents inherit permissions from their parent folder.+ </p>+ </div>+ </div>++ <div className="space-y-4">+ <div className="flex items-center space-x-3">+ <RadioGroupItem+ value="use_default_permissions"+ id="use_default_permissions"+ />+ <div>+ <Label+ htmlFor="use_default_permissions"+ className="text-sm font-medium"+ >+ Use default group permissions+ </Label>+ <p className="text-xs text-muted-foreground">+ Apply configured group defaults automatically+ </p>+ </div>+ </div>++ <AnimatePresence>+ {showGroupSettings && (+ <motion.div+ initial={{ opacity: 0, height: 0 }}+ animate={{ opacity: 1, height: "auto" }}+ exit={{ opacity: 0, height: 0 }}+ transition={{ duration: 0.3, ease: "easeInOut" }}+ className="ml-6 overflow-hidden"+ >+ <div className="space-y-2">+ {viewerGroups === undefined ? (+ <div className="rounded-lg border bg-muted/20 p-6 text-center">+ <p className="text-xs text-muted-foreground">+ Loading groups...+ </p>+ </div>+ ) : viewerGroups.length > 0 ? (+ <div className="rounded-lg border bg-muted/30">+ <Table>+ <TableHeader>+ <TableRow className="border-b">+ <TableHead className="h-9 w-[60%] text-xs font-medium">+ Group+ </TableHead>+ <TableHead className="h-9 w-[20%] text-center text-xs font-medium">+ Can View+ </TableHead>+ <TableHead className="h-9 w-[20%] text-center text-xs font-medium">+ Can Download+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {viewerGroups.map((group) => (+ <TableRow+ key={group.id}+ className="border-b last:border-b-0"+ >+ <TableCell className="py-2 text-sm">+ {group.name}+ </TableCell>+ <TableCell className="py-2 text-center">+ <Switch+ checked={group.defaultCanView ?? false}+ onCheckedChange={(checked) =>+ handleViewPermissionChange(+ group.id,+ checked,+ )+ }+ />+ </TableCell>+ <TableCell className="py-2 text-center">+ <Switch+ checked={group.defaultCanDownload ?? false}+ onCheckedChange={(checked) =>+ handleDownloadPermissionChange(+ group.id,+ checked,+ )+ }+ />+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ ) : (+ <div className="rounded-lg border border-dashed bg-muted/20 p-6 text-center">+ <p className="text-xs text-muted-foreground">+ No groups found. Create groups to configure+ permissions.+ </p>+ </div>+ )}+ </div>+ </motion.div>+ )}+ </AnimatePresence>+ </div>++ <div className="flex items-center space-x-3">+ <RadioGroupItem value="no_permissions" id="no_permissions" />+ <div>+ <Label htmlFor="no_permissions" className="text-sm font-medium">+ No permissions by default+ </Label>+ <p className="text-xs text-muted-foreground">+ No group permissions applied automatically. Permissions modal+ will not open.+ </p>+ </div>+ </div>+ </RadioGroup>+ </CardContent>+ </Card>+ );+}diff --git a/components/datarooms/settings/settings-tabs.tsx b/components/datarooms/settings/settings-tabs.tsxindex 7b9be690..3a6cc954 100644--- a/components/datarooms/settings/settings-tabs.tsx+++ b/components/datarooms/settings/settings-tabs.tsx@@ -1,8 +1,7 @@import Link from "next/link";import { useRouter } from "next/router";-import { BellIcon, CogIcon } from "lucide-react";-+import { BellIcon, CogIcon, ShieldIcon } from "lucide-react";import { cn } from "@/lib/utils";interface SettingsTabsProps {@@ -39,6 +38,18 @@ export default function SettingsTabs({ dataroomId }: SettingsTabsProps) {<BellIcon className="h-4 w-4" />Notifications</Link>+ <Link+ href={`/datarooms/${dataroomId}/settings/permissions`}+ className={cn(+ "flex items-center gap-x-2 rounded-md p-2 text-primary hover:bg-muted",+ {+ "bg-muted font-medium": router.pathname.includes("permissions"),+ },+ )}+ >+ <ShieldIcon className="h-4 w-4" />+ Permissions+ </Link></nav>);}diff --git a/components/document-upload.tsx b/components/document-upload.tsxindex cde5765e..d68aa951 100644--- a/components/document-upload.tsx+++ b/components/document-upload.tsx@@ -91,6 +91,9 @@ export default function DocumentUpload({},multiple: false,onDropAccepted: (acceptedFiles) => {+ if (acceptedFiles.length === 0) {+ return;+ }const file = acceptedFiles[0];const fileType = file.type;const fileSizeLimitMB = getFileSizeLimit(fileType, fileSizeLimits); // in MBdiff --git a/components/documents/add-document-modal.tsx b/components/documents/add-document-modal.tsxindex 13ef50ac..d4f6e9f1 100644--- a/components/documents/add-document-modal.tsx+++ b/components/documents/add-document-modal.tsx@@ -16,7 +16,9 @@ import {createNewDocumentVersion,} from "@/lib/documents/create-document";import { putFile } from "@/lib/files/put-file";+import { useDataroomPermissions } from "@/lib/hooks/use-dataroom-permissions";import { usePlan } from "@/lib/swr/use-billing";+import { useDataroom } from "@/lib/swr/use-dataroom";import useLimits from "@/lib/swr/use-limits";import { getSupportedContentType } from "@/lib/utils/get-content-type";@@ -80,9 +82,12 @@ export function AddDocumentModal({const teamInfo = useTeam();const { canAddDocuments } = useLimits();const { plan, isFree, isTrial } = usePlan();-+ const { dataroom } = useDataroom();const teamId = teamInfo?.currentTeam?.id as string;+ const { applyDefaultPermissions, inheritParentPermissions } =+ useDataroomPermissions();+useEffect(() => {if (openModal) setIsOpen(openModal);}, [openModal]);@@ -137,6 +142,11 @@ export function AddDocumentModal({}};+ const toastErrorMessage = () =>+ toast.error(+ "Failed to apply default permissions. Update the group permissions in the group settings.",+ );+const handleFileUpload = async (event: FormEvent<HTMLFormElement>,): Promise<void> => {@@ -230,14 +240,69 @@ export function AddDocumentModal({};if (dataroomDocument.dataroom._count.viewerGroups > 0) {- setShowGroupPermissions(true);- setUploadedFiles([- {- documentId: document.id,- dataroomDocumentId: dataroomDocument.id,- fileName: document.name,- },- ]);+ const defaultPermission =+ dataroom?.defaultGroupPermission || "ask_every_time";++ if (defaultPermission === "ask_every_time") {+ setShowGroupPermissions(true);+ setUploadedFiles([+ {+ documentId: document.id,+ dataroomDocumentId: dataroomDocument.id,+ fileName: document.name,+ },+ ]);+ } else if (defaultPermission === "inherit_from_parent") {+ const isRootLevel =+ !currentFolderPath || currentFolderPath.length === 0;+ if (isRootLevel) {+ setShowGroupPermissions(true);+ setUploadedFiles([+ {+ documentId: document.id,+ dataroomDocumentId: dataroomDocument.id,+ fileName: document.name,+ },+ ]);+ } else {+ try {+ const result = await inheritParentPermissions(+ dataroomId,+ [document.id],+ currentFolderPath?.join("/"),+ );+ if (!result.success) {+ console.error(+ "Failed to inherit parent permissions:",+ result.error,+ );+ toastErrorMessage();+ }+ } catch (error) {+ console.error(+ "Failed to inherit parent permissions:",+ error,+ );+ toastErrorMessage();+ }+ }+ } else if (defaultPermission === "use_default_permissions") {+ try {+ const result = await applyDefaultPermissions(dataroomId, [+ document.id,+ ]);+ if (!result.success) {+ toastErrorMessage();+ console.error(+ "Failed to apply default permissions:",+ result.error,+ );+ }+ } catch (error) {+ console.error("Failed to apply default permissions:", error);+ toastErrorMessage();+ }+ }}}@@ -384,14 +449,67 @@ export function AddDocumentModal({};if (dataroomDocument.dataroom._count.viewerGroups > 0) {- setShowGroupPermissions(true);- setUploadedFiles([- {- documentId: document.id,- dataroomDocumentId: dataroomDocument.id,- fileName: document.name,- },- ]);+ const defaultPermission =+ dataroom?.defaultGroupPermission || "ask_every_time";++ if (defaultPermission === "ask_every_time") {+ setShowGroupPermissions(true);+ setUploadedFiles([+ {+ documentId: document.id,+ dataroomDocumentId: dataroomDocument.id,+ fileName: document.name,+ },+ ]);+ } else if (defaultPermission === "inherit_from_parent") {+ const isRootLevel =+ !currentFolderPath || currentFolderPath.length === 0;+ if (isRootLevel) {+ setShowGroupPermissions(true);+ setUploadedFiles([+ {+ documentId: document.id,+ dataroomDocumentId: dataroomDocument.id,+ fileName: document.name,+ },+ ]);+ } else {+ // For subfolder uploads, inherit permissions from parent folder automatically+ try {+ const result = await inheritParentPermissions(+ dataroomId,+ [document.id],+ currentFolderPath?.join("/"),+ );+ if (!result.success) {+ toastErrorMessage();+ console.error(+ "Failed to inherit parent permissions:",+ result.error,+ );+ }+ } catch (error) {+ console.error("Failed to inherit parent permissions:", error);+ toastErrorMessage();+ }+ }+ } else if (defaultPermission === "use_default_permissions") {+ try {+ const result = await applyDefaultPermissions(dataroomId, [+ document.id,+ ]);+ if (!result.success) {+ console.error(+ "Failed to apply default permissions:",+ result.error,+ );+ toastErrorMessage();+ }+ } catch (error) {+ console.error("Failed to apply default permissions:", error);+ toastErrorMessage();+ }+ }}}@@ -642,4 +760,4 @@ export function AddDocumentModal({)}</>);-}+}\ No newline at end of filediff --git a/components/layouts/breadcrumb.tsx b/components/layouts/breadcrumb.tsxindex 25147c4b..352fa4b0 100644--- a/components/layouts/breadcrumb.tsx+++ b/components/layouts/breadcrumb.tsx@@ -129,6 +129,8 @@ const SingleDataroomBreadcrumb = ({ path }: { path: string }) => {return "Conversations";case "/datarooms/[id]/settings/notifications":return "Notifications";+ case "/datarooms/[id]/settings/permissions":+ return "Permissions";default:return dataroom?.name || "Loading...";}diff --git a/lib/hooks/use-dataroom-permissions.ts b/lib/hooks/use-dataroom-permissions.tsnew file mode 100644index 00000000..dae8a1c5--- /dev/null+++ b/lib/hooks/use-dataroom-permissions.ts@@ -0,0 +1,101 @@+import { useTeam } from "@/context/team-context";++export const useDataroomPermissions = () => {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const applyDefaultPermissions = async (+ dataroomId: string,+ documentIds: string[],+ ): Promise<{ success: boolean; error?: string }> => {+ if (!teamId) {+ return { success: false, error: "Team ID not available" };+ }++ if (!documentIds || documentIds.length === 0) {+ return { success: false, error: "No document IDs provided" };+ }++ try {+ const response = await fetch(+ `/api/teams/${teamId}/datarooms/${dataroomId}/groups/apply-default-permissions`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ documentIds,+ }),+ },+ );++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ return {+ success: false,+ error: errorData.message || `HTTP ${response.status}`+ };+ }++ return { success: true };+ } catch (error) {+ console.error("Failed to apply default permissions:", error);+ return {+ success: false,+ error: error instanceof Error ? error.message : "Unknown error"+ };+ }+ };++ const inheritParentPermissions = async (+ dataroomId: string,+ documentIds: string[],+ folderPath?: string,+ ): Promise<{ success: boolean; error?: string }> => {+ if (!teamId) {+ return { success: false, error: "Team ID not available" };+ }++ if (!documentIds || documentIds.length === 0) {+ return { success: false, error: "No document IDs provided" };+ }++ try {+ const response = await fetch(+ `/api/teams/${teamId}/datarooms/${dataroomId}/groups/inherit-parent-permissions`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ documentIds,+ folderPath,+ }),+ },+ );++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ return {+ success: false,+ error: errorData.message || `HTTP ${response.status}`+ };+ }++ return { success: true };+ } catch (error) {+ console.error("Failed to inherit parent permissions:", error);+ return {+ success: false,+ error: error instanceof Error ? error.message : "Unknown error"+ };+ }+ };++ return {+ applyDefaultPermissions,+ inheritParentPermissions+ };+};\ No newline at end of filediff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/index.tsindex 9035c969..6a354b17 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/index.ts@@ -89,14 +89,31 @@ export default async function handle(groupId: string;};- const { name, domains, allowAll } = req.body as {+ const { name, defaultCanView, defaultCanDownload, allowAll, domains } = req.body as {name?: string;- domains?: string[];+ defaultCanView?: boolean;+ defaultCanDownload?: boolean;allowAll?: boolean;+ domains?: 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 group = await prisma.viewerGroup.update({where: {id: groupId,@@ -112,6 +129,8 @@ export default async function handle(},data: {...(name && { name }),+ ...(typeof defaultCanView === "boolean" && { defaultCanView }),+ ...(typeof defaultCanDownload === "boolean" && { defaultCanDownload }),...(typeof allowAll === "boolean" && { allowAll }),...(domains && { domains }),},diff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/apply-default-permissions.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/apply-default-permissions.tsnew file mode 100644index 00000000..160f5e2a--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/apply-default-permissions.ts@@ -0,0 +1,178 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { DefaultGroupPermissionStrategy, ItemType } from "@prisma/client";+import { getServerSession } from "next-auth/next";++import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "POST") {+ return res.status(405).json({ message: "Method not allowed" });+ }++ // POST /api/teams/:teamId/datarooms/:id/groups/apply-default-permissions+ 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 };++ try {+ const { documentIds } = req.body as {+ documentIds: string[];+ };++ // Validate input+ if (!documentIds || !Array.isArray(documentIds) || documentIds.length === 0) {+ return res.status(400).json({ message: "Document IDs are required" });+ }++ // Check if the user is part of the team+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId,+ },+ },+ },+ });++ if (!team) {+ return res.status(403).json({ message: "Unauthorized" });+ }++ // Get dataroom and verify it exists and belongs to the team+ const dataroom = await prisma.dataroom.findUnique({+ where: {+ id: dataroomId,+ teamId,+ },+ select: {+ id: true,+ defaultGroupPermission: true,+ },+ });++ if (!dataroom) {+ return res.status(404).json({ message: "Dataroom not found" });+ }++ // Check if dataroom is set to use default permissions+ if (dataroom.defaultGroupPermission !== DefaultGroupPermissionStrategy.use_default_permissions) {+ return res.status(400).json({+ message: "Dataroom is not configured to use default permissions"+ });+ }++ // Get all viewer groups with their default permissions+ const viewerGroups = await prisma.viewerGroup.findMany({+ where: {+ dataroomId,+ },+ select: {+ id: true,+ defaultCanView: true,+ defaultCanDownload: true,+ },+ });++ if (viewerGroups.length === 0) {+ return res.status(200).json({+ message: "No viewer groups found, no permissions applied"+ });+ }++ // Get dataroom document IDs for the provided document IDs+ const dataroomDocuments = await prisma.dataroomDocument.findMany({+ where: {+ documentId: {+ in: documentIds,+ },+ dataroomId,+ },+ select: {+ id: true,+ documentId: true,+ },+ });++ if (dataroomDocuments.length === 0) {+ return res.status(404).json({+ message: "No documents found in this dataroom"+ });+ }++ // Build permissions to create+ const permissionsToCreate: {+ groupId: string;+ itemId: string;+ itemType: ItemType;+ canView: boolean;+ canDownload: boolean;+ }[] = [];++ viewerGroups.forEach((group) => {+ // Only create permissions if the group has view or download enabled+ if (group.defaultCanView || group.defaultCanDownload) {+ dataroomDocuments.forEach((doc) => {+ permissionsToCreate.push({+ groupId: group.id,+ itemId: doc.id,+ itemType: ItemType.DATAROOM_DOCUMENT,+ canView: group.defaultCanView ?? false,+ canDownload: group.defaultCanDownload ?? false,+ });+ });+ }+ });++ if (permissionsToCreate.length === 0) {+ return res.status(200).json({+ message: "No default permissions configured, no permissions applied"+ });+ }++ // Apply permissions in a transaction+ await prisma.$transaction(async (tx) => {+ // First, remove any existing permissions for these documents and groups+ await tx.viewerGroupAccessControls.deleteMany({+ where: {+ itemId: {+ in: dataroomDocuments.map(doc => doc.id),+ },+ itemType: ItemType.DATAROOM_DOCUMENT,+ groupId: {+ in: viewerGroups.map(group => group.id),+ },+ },+ });++ // Then create the new default permissions+ await tx.viewerGroupAccessControls.createMany({+ data: permissionsToCreate,+ skipDuplicates: true,+ });+ });++ res.status(200).json({+ message: "Default permissions applied successfully",+ appliedPermissions: permissionsToCreate.length,+ documentsProcessed: dataroomDocuments.length,+ groupsProcessed: viewerGroups.length,+ });++ } catch (error) {+ console.error("Error applying default permissions:", error);+ res.status(500).json({ message: "Internal server error" });+ }+}\ No newline at end of filediff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/inherit-parent-permissions.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/inherit-parent-permissions.tsnew file mode 100644index 00000000..a721863a--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/inherit-parent-permissions.ts@@ -0,0 +1,219 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { ItemType } from "@prisma/client";+import { getServerSession } from "next-auth/next";++import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "POST") {+ return res.status(405).json({ message: "Method not allowed" });+ }++ // POST /api/teams/:teamId/datarooms/:id/groups/inherit-parent-permissions+ 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 };++ try {+ const { documentIds, folderPath } = req.body as {+ documentIds: string[];+ folderPath?: string;+ };++ // Validate input+ if (!documentIds || !Array.isArray(documentIds) || documentIds.length === 0) {+ return res.status(400).json({ message: "Document IDs are required" });+ }++ // Check if the user is part of the team+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId,+ },+ },+ },+ });++ if (!team) {+ return res.status(403).json({ message: "Unauthorized" });+ }++ // Get dataroom and verify it exists and belongs to the team+ const dataroom = await prisma.dataroom.findUnique({+ where: {+ id: dataroomId,+ teamId,+ },+ select: {+ id: true,+ defaultGroupPermission: true,+ },+ });++ if (!dataroom) {+ return res.status(404).json({ message: "Dataroom not found" });+ }++ // Get all viewer groups+ const viewerGroups = await prisma.viewerGroup.findMany({+ where: {+ dataroomId,+ },+ select: {+ id: true,+ name: true,+ },+ });++ if (viewerGroups.length === 0) {+ return res.status(200).json({+ message: "No viewer groups found, no permissions applied"+ });+ }++ // Get dataroom document IDs for the new documents+ const newDataroomDocuments = await prisma.dataroomDocument.findMany({+ where: {+ documentId: {+ in: documentIds,+ },+ dataroomId,+ },+ select: {+ id: true,+ documentId: true,+ folderId: true,+ },+ });++ if (newDataroomDocuments.length === 0) {+ return res.status(404).json({+ message: "No documents found in this dataroom"+ });+ }++ // Determine the parent folder ID based on the folderPath or new documents' folderId+ let parentFolderId: string | null = null;++ if (folderPath) {+ // Find the folder by path+ const folder = await prisma.dataroomFolder.findUnique({+ where: {+ dataroomId_path: {+ dataroomId,+ path: `/${folderPath}`,+ },+ },+ select: {+ id: true,+ },+ });+ parentFolderId = folder?.id || null;+ } else {+ // Use the folderId from the first new document (they should all be in the same folder)+ parentFolderId = newDataroomDocuments[0]?.folderId || null;+ }++ if (!parentFolderId) {+ return res.status(200).json({+ message: "Root level upload: please set permissions manually."+ });+ }++ // Get all permissions for the parent folder+ const parentFolderPermissions = await prisma.viewerGroupAccessControls.findMany({+ where: {+ itemId: parentFolderId,+ itemType: ItemType.DATAROOM_FOLDER,+ groupId: {+ in: viewerGroups.map(group => group.id),+ },+ },+ select: {+ groupId: true,+ canView: true,+ canDownload: true,+ },+ });++ if (parentFolderPermissions.length === 0) {+ return res.status(200).json({+ message: "Parent folder has no permissions to inherit."+ });+ }++ // Build permissions to create for new documents+ const permissionsToCreate: {+ groupId: string;+ itemId: string;+ itemType: ItemType;+ canView: boolean;+ canDownload: boolean;+ }[] = [];++ parentFolderPermissions.forEach((permission) => {+ newDataroomDocuments.forEach((doc) => {+ permissionsToCreate.push({+ groupId: permission.groupId,+ itemId: doc.id,+ itemType: ItemType.DATAROOM_DOCUMENT,+ canView: permission.canView,+ canDownload: permission.canDownload,+ });+ });+ });++ if (permissionsToCreate.length === 0) {+ return res.status(200).json({+ message: "No consistent permissions found to inherit"+ });+ }++ // Apply inherited permissions in a transaction+ await prisma.$transaction(async (tx) => {+ // First, remove any existing permissions for these documents and groups+ await tx.viewerGroupAccessControls.deleteMany({+ where: {+ itemId: {+ in: newDataroomDocuments.map(doc => doc.id),+ },+ itemType: ItemType.DATAROOM_DOCUMENT,+ groupId: {+ in: viewerGroups.map(group => group.id),+ },+ },+ });++ // Then create the inherited permissions+ await tx.viewerGroupAccessControls.createMany({+ data: permissionsToCreate,+ skipDuplicates: true,+ });+ });++ res.status(200).json({+ message: "Parent folder permissions inherited successfully",+ appliedPermissions: permissionsToCreate.length,+ documentsProcessed: newDataroomDocuments.length,+ groupsProcessed: viewerGroups.length,+ });++ } catch (error) {+ console.error("Error inheriting parent permissions:", error);+ res.status(500).json({ message: "Internal server error" });+ }+}\ No newline at end of filediff --git a/pages/api/teams/[teamId]/datarooms/[id]/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/index.tsindex 62e0f2a8..bc2b7174 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/index.ts@@ -7,6 +7,7 @@ import { errorhandler } from "@/lib/errorHandler";import { getFeatureFlags } from "@/lib/featureFlags";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";+import { DefaultGroupPermissionStrategy } from "@prisma/client";export default async function handle(req: NextApiRequest,@@ -96,9 +97,10 @@ export default async function handle(return res.status(401).end("Unauthorized");}- const { name, enableChangeNotifications } = req.body as {+ const { name, enableChangeNotifications, defaultGroupPermission } = req.body as {name?: string;enableChangeNotifications?: boolean;+ defaultGroupPermission?: DefaultGroupPermissionStrategy;};const featureFlags = await getFeatureFlags({ teamId: team.id });@@ -123,6 +125,7 @@ export default async function handle(...(typeof enableChangeNotifications === "boolean" && {enableChangeNotifications,}),+ ...(defaultGroupPermission && { defaultGroupPermission }),},});diff --git a/pages/datarooms/[id]/settings/permissions.tsx b/pages/datarooms/[id]/settings/permissions.tsxnew file mode 100644index 00000000..6fced07a--- /dev/null+++ b/pages/datarooms/[id]/settings/permissions.tsx@@ -0,0 +1,40 @@+import { useDataroom } from "@/lib/swr/use-dataroom";++import { DataroomHeader } from "@/components/datarooms/dataroom-header";+import { DataroomNavigation } from "@/components/datarooms/dataroom-navigation";+import PermissionSettings from "@/components/datarooms/settings/permission-settings";+import SettingsTabs from "@/components/datarooms/settings/settings-tabs";+import AppLayout from "@/components/layouts/app";++export default function PermissionsSettings() {+ const { dataroom } = useDataroom();++ if (!dataroom) {+ return <div>Loading...</div>;+ }++ return (+ <AppLayout>+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">+ <header>+ <DataroomHeader+ title={dataroom.name}+ description={dataroom.pId}+ actions={[]}+ />++ <DataroomNavigation dataroomId={dataroom.id} />+ </header>+ <div className="mx-auto grid w-full gap-2">+ <h1 className="text-2xl font-semibold">Settings</h1>+ </div>+ <div className="mx-auto grid w-full items-start gap-6 md:grid-cols-[180px_1fr] lg:grid-cols-[250px_1fr]">+ <SettingsTabs dataroomId={dataroom.id} />+ <div className="grid gap-6">+ <PermissionSettings dataroomId={dataroom.id} />+ </div>+ </div>+ </main>+ </AppLayout>+ );+}diff --git a/prisma/migrations/20250616102233_group_permission/migration.sql b/prisma/migrations/20250616102233_group_permission/migration.sqlnew file mode 100644index 00000000..95e93f03--- /dev/null+++ b/prisma/migrations/20250616102233_group_permission/migration.sql@@ -0,0 +1,9 @@+-- CreateEnum+CREATE TYPE "DefaultGroupPermissionStrategy" AS ENUM ('ask_every_time', 'inherit_from_parent', 'use_default_permissions', 'no_permissions');++-- AlterTable+ALTER TABLE "Dataroom" ADD COLUMN "defaultGroupPermission" "DefaultGroupPermissionStrategy" NOT NULL DEFAULT 'ask_every_time';++-- AlterTable+ALTER TABLE "ViewerGroup" ADD COLUMN "defaultCanDownload" BOOLEAN DEFAULT false,+ADD COLUMN "defaultCanView" BOOLEAN DEFAULT false;diff --git a/prisma/schema/dataroom.prisma b/prisma/schema/dataroom.prismaindex f0dfa1b0..0cd8d3e4 100644--- a/prisma/schema/dataroom.prisma+++ b/prisma/schema/dataroom.prisma@@ -25,6 +25,9 @@ model Dataroom {// notification settingsenableChangeNotifications Boolean @default(false)++ // default group permission setting+ defaultGroupPermission DefaultGroupPermissionStrategy @default(ask_every_time)createdAt DateTime @default(now())updatedAt DateTime @updatedAt@@ -104,6 +107,10 @@ model ViewerGroup {views View[]conversations Conversation[]+ // default group permission setting+ defaultCanView Boolean? @default(false)+ defaultCanDownload Boolean? @default(false)+createdAt DateTime @default(now())updatedAt DateTime @updatedAt@@ -150,3 +157,10 @@ enum ItemType {DATAROOM_DOCUMENTDATAROOM_FOLDER}++enum DefaultGroupPermissionStrategy {+ ask_every_time+ inherit_from_parent+ use_default_permissions+ no_permissions+}\ No newline at end of file