Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add dataroom group default file permissions ac2b
Marc Seitz8ffa04af6465
diff --git a/components/datarooms/dataroom-items-list.tsx b/components/datarooms/dataroom-items-list.tsxindex 1e131053..25b14655 100644--- a/components/datarooms/dataroom-items-list.tsx+++ b/components/datarooms/dataroom-items-list.tsx@@ -40,7 +40,10 @@ import { useMediaQuery } from "@/lib/utils/use-media-query";import { useRemoveDataroomItemsModal } from "@/components/datarooms/actions/remove-document-modal";import DataroomDocumentCard from "@/components/datarooms/dataroom-document-card";-import { SetUnifiedPermissionsModal } from "@/components/datarooms/groups/set-unified-permissions-modal";+import {+ SetUnifiedPermissionsModal,+ type UnifiedPermissionItem,+} from "@/components/datarooms/groups/set-unified-permissions-modal";import { useDeleteFolderModal } from "@/components/documents/actions/delete-folder-modal";import { DraggableItem } from "@/components/documents/drag-and-drop/draggable-item";import { DroppableFolder } from "@/components/documents/drag-and-drop/droppable-folder";@@ -95,12 +98,8 @@ export function DataroomItemsList({} = useUploadCallbacks();const [showGroupPermissions, setShowGroupPermissions] = useState(false);- const [uploadedFiles, setUploadedFiles] = useState<- {- documentId: string;- dataroomDocumentId: string;- fileName: string;- }[]+ const [permissionItems, setPermissionItems] = useState<+ UnifiedPermissionItem[]>([]);const [moveFolderOpen, setMoveFolderOpen] = useState<boolean>(false);@@ -556,7 +555,9 @@ export function DataroomItemsList({fileName: string;documentId: string;dataroomDocumentId: string;+ topLevelDataroomFolderId?: string;}[],+ folders?: { dataroomFolderId: string; name: string }[],) => {// Check if there are any groups to apply permissions toconst hasAnyGroups =@@ -566,28 +567,67 @@ export function DataroomItemsList({if (!hasAnyGroups) return;const documentIds = files.map((file) => file.documentId);- const strategy =+ const groupStrategy =+ dataroom?.defaultGroupPermissionStrategy ||+ DefaultPermissionStrategy.INHERIT_FROM_PARENT;+ const linkStrategy =dataroom?.defaultPermissionStrategy ||DefaultPermissionStrategy.INHERIT_FROM_PARENT;- if (strategy === DefaultPermissionStrategy.ASK_EVERY_TIME) {+ // The unified modal handles both viewer-group and permission-group+ // configuration in one pass, so prompt if either side requests it.+ const shouldAsk =+ groupStrategy === DefaultPermissionStrategy.ASK_EVERY_TIME ||+ linkStrategy === DefaultPermissionStrategy.ASK_EVERY_TIME;++ if (shouldAsk) {+ // Build the list of items to configure. For folder uploads we show the+ // folder itself (which cascades to every file/sub-folder inside)+ // instead of every individual file — one decision instead of N.+ const folderItems: UnifiedPermissionItem[] = (folders ?? []).map(+ (folder) => ({+ fileName: folder.name,+ itemType: "folder" as const,+ dataroomFolderId: folder.dataroomFolderId,+ }),+ );+ // Standalone files (those NOT uploaded as part of a top-level folder)+ // still get their own row so users can configure them individually.+ const looseFileItems: UnifiedPermissionItem[] = files+ .filter((file) => !file.topLevelDataroomFolderId)+ .map((file) => ({+ fileName: file.fileName,+ itemType: "document" as const,+ documentId: file.documentId,+ dataroomDocumentId: file.dataroomDocumentId,+ }));++ const combined = [...folderItems, ...looseFileItems];+ if (combined.length === 0) return;setShowGroupPermissions(true);- setUploadedFiles(files);- } else if (strategy === DefaultPermissionStrategy.INHERIT_FROM_PARENT) {- const isRootLevel = !folderPathName || folderPathName.length === 0;-- applyPermissions(- dataroomId,- documentIds,- "INHERIT_FROM_PARENT",- isRootLevel ? undefined : folderPathName?.join("/"),- (message: string) => toast.error(message),- ).catch((error: any) => {- console.error("Failed to apply permissions:", error);- toast.error("Failed to apply permissions");- });+ setPermissionItems(combined);+ return;}- // strategy === DefaultPermissionStrategy.HIDDEN_BY_DEFAULT - do nothing++ if (+ groupStrategy === DefaultPermissionStrategy.HIDDEN_BY_DEFAULT &&+ linkStrategy === DefaultPermissionStrategy.HIDDEN_BY_DEFAULT+ ) {+ return;+ }++ const isRootLevel = !folderPathName || folderPathName.length === 0;++ // applyPermissions never rejects — it returns { success, error } and routes+ // failures through the onError callback below — so there's nothing to+ // .catch(). Errors surface as a toast via onError.+ void applyPermissions(+ dataroomId,+ documentIds,+ { groupStrategy, linkStrategy },+ isRootLevel ? undefined : folderPathName?.join("/"),+ (message: string) => toast.error(message),+ );};return (@@ -713,10 +753,10 @@ export function DataroomItemsList({open={showGroupPermissions}setOpen={setShowGroupPermissions}dataroomId={dataroomId}- uploadedFiles={uploadedFiles}+ uploadedFiles={permissionItems}onComplete={() => {setShowGroupPermissions(false);- setUploadedFiles([]);+ setPermissionItems([]);}}/>)}diff --git a/components/datarooms/groups/set-unified-permissions-modal.tsx b/components/datarooms/groups/set-unified-permissions-modal.tsxindex ee4d2c62..f28b6d31 100644--- a/components/datarooms/groups/set-unified-permissions-modal.tsx+++ b/components/datarooms/groups/set-unified-permissions-modal.tsx@@ -5,9 +5,11 @@ import { ItemType } from "@prisma/client";import {ArrowDownToLineIcon,ArrowLeftIcon,+ CheckIcon,EyeIcon,EyeOffIcon,FileTextIcon,+ FolderIcon,LinkIcon,Loader2,Users,@@ -15,7 +17,11 @@ import {import { toast } from "sonner";import { mutate } from "swr";-import { useDataroomLinks } from "@/lib/swr/use-dataroom";+import {+ DataroomFolderWithDocuments,+ useDataroomFoldersTree,+ useDataroomLinks,+} from "@/lib/swr/use-dataroom";import useDataroomGroups from "@/lib/swr/use-dataroom-groups";import useDataroomPermissionGroups from "@/lib/swr/use-dataroom-permission-groups";import { cn } from "@/lib/utils";@@ -30,19 +36,106 @@ import {DialogHeader,DialogTitle,} from "@/components/ui/dialog";-import {- Table,- TableBody,- TableCell,- TableHead,- TableHeader,- TableRow,-} from "@/components/ui/table";-import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";+import { Toggle } from "@/components/ui/toggle";type GroupPermissions = Record<string, { view: boolean; download: boolean }>;type LinkPermissions = Record<string, { view: boolean; download: boolean }>;+/**+ * An item the modal sets permissions for. Can be a single document or a+ * folder. When `itemType` is `folder`, the modal cascades the chosen view /+ * download permission to every descendant document and sub-folder so the+ * user can configure access for the whole tree with one click.+ */+export type UnifiedPermissionItem = {+ fileName: string;+ /** Defaults to "document" for backward compatibility with existing callers. */+ itemType?: "document" | "folder";+ // Document fields+ documentId?: string;+ dataroomDocumentId?: string;+ // Folder field+ dataroomFolderId?: string;+};++type InternalItem = {+ key: string;+ type: "document" | "folder";+ name: string;+ // Always present+ primaryId: string; // dataroomDocumentId or dataroomFolderId+ // For documents only — used to mutate the per-document groups SWR cache+ documentId?: string;+};++function normalizeItems(items: UnifiedPermissionItem[]): InternalItem[] {+ return items+ .map((item): InternalItem | null => {+ const type = item.itemType ?? "document";+ if (type === "folder") {+ if (!item.dataroomFolderId) return null;+ return {+ key: `folder:${item.dataroomFolderId}`,+ type: "folder",+ name: item.fileName,+ primaryId: item.dataroomFolderId,+ };+ }+ if (!item.dataroomDocumentId) return null;+ return {+ key: `document:${item.dataroomDocumentId}`,+ type: "document",+ name: item.fileName,+ primaryId: item.dataroomDocumentId,+ documentId: item.documentId,+ };+ })+ .filter((x): x is InternalItem => x !== null);+}++/**+ * Walk down the (flat) dataroom folder list starting from `rootFolderId` and+ * collect every descendant folder id and dataroom-document id. The list of+ * folders comes from `useDataroomFoldersTree({ include_documents: true })`+ * which already includes the documents directly inside each folder.+ */+function collectFolderDescendants(+ rootFolderId: string,+ folders: DataroomFolderWithDocuments[] | undefined,+): { folderIds: string[]; documentIds: string[] } {+ if (!folders) return { folderIds: [], documentIds: [] };++ const childrenByParent = new Map<string, DataroomFolderWithDocuments[]>();+ for (const folder of folders) {+ const parent = folder.parentId ?? "__root__";+ const arr = childrenByParent.get(parent) ?? [];+ arr.push(folder);+ childrenByParent.set(parent, arr);+ }++ const documentsByFolder = new Map<string, { id: string }[]>();+ for (const folder of folders) {+ documentsByFolder.set(folder.id, folder.documents ?? []);+ }++ const folderIds: string[] = [];+ const documentIds: string[] = [];++ const stack: string[] = [rootFolderId];+ while (stack.length) {+ const current = stack.pop()!;+ for (const doc of documentsByFolder.get(current) ?? []) {+ documentIds.push(doc.id);+ }+ for (const child of childrenByParent.get(current) ?? []) {+ folderIds.push(child.id);+ stack.push(child.id);+ }+ }++ return { folderIds, documentIds };+}+export function SetUnifiedPermissionsModal({open,setOpen,@@ -54,97 +147,86 @@ export function SetUnifiedPermissionsModal({setOpen: (open: boolean) => void;dataroomId: string;onComplete?: () => void;- uploadedFiles: {- documentId: string;- dataroomDocumentId: string;- fileName: string;- }[];+ uploadedFiles: UnifiedPermissionItem[];}) {const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;- const [selectedFile, setSelectedFile] = useState<{- documentId: string;- dataroomDocumentId: string;- fileName: string;- } | null>(null);-- // Computed values instead of useEffect + useState- const { showFileList, defaultSelectedFile } = useMemo(() => {- const shouldShowFileList = uploadedFiles.length > 1;- const defaultFile = uploadedFiles.length === 1 ? uploadedFiles[0] : null;- return {- showFileList: shouldShowFileList,- defaultSelectedFile: defaultFile,- };- }, [uploadedFiles]);-- const [showFileListState, setShowFileListState] = useState(showFileList);-- // Initialize selectedFile on mount or when uploadedFiles changes++ const items = useMemo(() => normalizeItems(uploadedFiles), [uploadedFiles]);++ const [selectedKey, setSelectedKey] = useState<string | null>(+ items.length === 1 ? items[0].key : null,+ );+ const [showFileListState, setShowFileListState] = useState(items.length > 1);++ // When the incoming items change (e.g. an upload completes), reset which+ // file is currently being edited so we don't get stuck pointing at a stale+ // selection.useEffect(() => {- if (defaultSelectedFile && !selectedFile) {- setSelectedFile(defaultSelectedFile);+ if (items.length === 1) {+ setSelectedKey(items[0].key);setShowFileListState(false);- } else if (!defaultSelectedFile) {+ } else if (items.length > 1) {+ setSelectedKey(null);setShowFileListState(true);}- }, [defaultSelectedFile, selectedFile]);+ }, [items]);++ const selectedItem = useMemo(+ () => items.find((item) => item.key === selectedKey) ?? null,+ [items, selectedKey],+ );- const currentDocumentId = useMemo(() => {- return selectedFile?.documentId || uploadedFiles[0]?.documentId;- }, [selectedFile, uploadedFiles]);+ // Folder tree — only fetched while the modal is open. We need it both to+ // count items inside a folder (so we can tell the user "this applies to N+ // items") and to cascade permission changes to every descendant.+ const { folders: folderTree, loading: folderTreeLoading } =+ useDataroomFoldersTree({+ dataroomId,+ include_documents: true,+ });- const currentDataroomDocumentId = useMemo(() => {- return (- selectedFile?.dataroomDocumentId || uploadedFiles[0]?.dataroomDocumentId+ // Right after a folder upload the cached tree won't yet include the new+ // folder or its children. Force a refresh whenever the modal opens with a+ // folder selection so we cascade to every freshly-created sub-item.+ useEffect(() => {+ if (!open || !teamId) return;+ const hasFolderItem = items.some((item) => item.type === "folder");+ if (!hasFolderItem) return;+ mutate(+ `/api/teams/${teamId}/datarooms/${dataroomId}/folders?include_documents=true`,);- }, [selectedFile, uploadedFiles]);+ }, [open, items, teamId, dataroomId]);++ const folderDescendants = useMemo(() => {+ if (!selectedItem || selectedItem.type !== "folder") return null;+ return collectFolderDescendants(selectedItem.primaryId, folderTree);+ }, [selectedItem, folderTree]);++ // Scope the groups query to the currently selected item so we get the+ // existing access controls (if any) for it. The server returns the same+ // group list either way; the access controls just get filtered.+ const documentIdForGroupsQuery =+ selectedItem?.type === "document" ? selectedItem.primaryId : undefined;+ const folderIdForGroupsQuery =+ selectedItem?.type === "folder" ? selectedItem.primaryId : undefined;- // Fetch viewer groupsconst {viewerGroups,loading: viewerGroupsLoading,mutate: mutateViewerGroups,} = useDataroomGroups({- documentId: currentDataroomDocumentId,+ documentId: documentIdForGroupsQuery,+ folderId: folderIdForGroupsQuery,+ dataroomId,});- // Fetch links and permission groupsconst { links, loading: linksLoading } = useDataroomLinks();const { permissionGroups, loading: permissionGroupsLoading } =useDataroomPermissionGroups();- const [loading, setLoading] = useState(false);- // Track permissions per file using dataroomDocumentId as key- const [filePermissions, setFilePermissions] = useState<- Record<- string,- {- groupPermissions: GroupPermissions;- linkPermissions: LinkPermissions;- }- >- >({});- // Track which files have been saved- const [savedFiles, setSavedFiles] = useState<Set<string>>(new Set());-- // Current file permissions (derived from filePermissions)- const selectedGroupPermissions = useMemo(() => {- return currentDataroomDocumentId- ? filePermissions[currentDataroomDocumentId]?.groupPermissions || {}- : {};- }, [filePermissions, currentDataroomDocumentId]);-- const selectedLinkPermissions = useMemo(() => {- return currentDataroomDocumentId- ? filePermissions[currentDataroomDocumentId]?.linkPermissions || {}- : {};- }, [filePermissions, currentDataroomDocumentId]);-- // Memoize links with permission groups to avoid recalculationconst linksWithPermissionGroups = useMemo(() => {if (!links || !permissionGroups) return [];-return links.filter((link) =>@@ -159,17 +241,33 @@ export function SetUnifiedPermissionsModal({}));}, [links, permissionGroups]);- // Refetch viewer groups when selectedFile changes+ // Per-item permission edits keyed by InternalItem.key. Allows quickly+ // switching between files when the user is processing a batch upload.+ const [filePermissions, setFilePermissions] = useState<+ Record<+ string,+ { groupPermissions: GroupPermissions; linkPermissions: LinkPermissions }+ >+ >({});+ const [savedKeys, setSavedKeys] = useState<Set<string>>(new Set());+ const [loading, setLoading] = useState(false);++ // Refresh viewer groups when switching items so the toggles reflect the+ // currently persisted state for that item.useEffect(() => {- if (selectedFile) {+ if (selectedItem) {mutateViewerGroups();}- }, [selectedFile, mutateViewerGroups]);+ }, [selectedItem, mutateViewerGroups]);- // Memoize initial group permissions instead of useEffect- const initialGroupPermissions = useMemo(() => {- if (!viewerGroups) return {};+ // Compute the initial "what is currently saved on the server" state for the+ // selected item, used both as the starting toggle values and to detect+ // what's changed when the user clicks save.+ const initialGroupPermissions = useMemo<GroupPermissions>(() => {+ if (!viewerGroups || !selectedItem) return {};+ // The groups endpoint already scopes accessControls to the current item+ // (document or folder) — there's at most one row per group.const permissions: GroupPermissions = {};viewerGroups.forEach((group) => {permissions[group.id] = {@@ -178,16 +276,14 @@ export function SetUnifiedPermissionsModal({};});return permissions;- }, [viewerGroups]);-- // Memoize initial link permissions instead of useEffect- const initialLinkPermissions = useMemo(() => {- if (!linksWithPermissionGroups || !currentDataroomDocumentId) return {};+ }, [viewerGroups, selectedItem]);+ const initialLinkPermissions = useMemo<LinkPermissions>(() => {+ if (!linksWithPermissionGroups || !selectedItem) return {};const permissions: LinkPermissions = {};linksWithPermissionGroups.forEach((link) => {const documentPermission = link.permissionGroup?.accessControls?.find(- (ac) => ac.itemId === currentDataroomDocumentId,+ (ac) => ac.itemId === selectedItem.primaryId,);permissions[link.id] = {view: documentPermission?.canView ?? false,@@ -195,127 +291,102 @@ export function SetUnifiedPermissionsModal({};});return permissions;- }, [linksWithPermissionGroups, currentDataroomDocumentId]);+ }, [linksWithPermissionGroups, selectedItem]);- // Update state when initial permissions changeuseEffect(() => {- if (currentDataroomDocumentId) {- setFilePermissions((prev) => ({- ...prev,- [currentDataroomDocumentId]: {- groupPermissions: initialGroupPermissions,- linkPermissions:- prev[currentDataroomDocumentId]?.linkPermissions || {},- },- }));- }- }, [initialGroupPermissions, currentDataroomDocumentId]);+ if (!selectedItem) return;+ setFilePermissions((prev) => ({+ ...prev,+ [selectedItem.key]: {+ groupPermissions: initialGroupPermissions,+ linkPermissions: prev[selectedItem.key]?.linkPermissions || {},+ },+ }));+ }, [initialGroupPermissions, selectedItem]);useEffect(() => {- if (currentDataroomDocumentId) {- setFilePermissions((prev) => ({- ...prev,- [currentDataroomDocumentId]: {- groupPermissions:- prev[currentDataroomDocumentId]?.groupPermissions || {},- linkPermissions: initialLinkPermissions,- },- }));- }- }, [initialLinkPermissions, currentDataroomDocumentId]);-- // Memoize permission update handlers to avoid recreation- const updateGroupPermissions = useCallback(- (groupId: string, newPermissions: string[]) => {- if (!currentDataroomDocumentId) return;-- const hasView = newPermissions.includes("view");- const hasDownload = newPermissions.includes("download");-- const prevPermissions = selectedGroupPermissions[groupId] || {- view: false,- download: false,- };+ if (!selectedItem) return;+ setFilePermissions((prev) => ({+ ...prev,+ [selectedItem.key]: {+ groupPermissions: prev[selectedItem.key]?.groupPermissions || {},+ linkPermissions: initialLinkPermissions,+ },+ }));+ }, [initialLinkPermissions, selectedItem]);- let finalPermissions = newPermissions;-- if (- hasDownload &&- !hasView &&- !prevPermissions.view &&- !prevPermissions.download- ) {- finalPermissions = ["view", "download"];- } else if (hasDownload && !hasView) {- finalPermissions = [];- }+ const selectedGroupPermissions = useMemo(() => {+ if (!selectedItem) return {};+ return filePermissions[selectedItem.key]?.groupPermissions || {};+ }, [filePermissions, selectedItem]);- setFilePermissions((prev) => ({- ...prev,- [currentDataroomDocumentId]: {- groupPermissions: {- ...prev[currentDataroomDocumentId]?.groupPermissions,- [groupId]: {- view: finalPermissions.includes("view"),- download: finalPermissions.includes("download"),+ const selectedLinkPermissions = useMemo(() => {+ if (!selectedItem) return {};+ return filePermissions[selectedItem.key]?.linkPermissions || {};+ }, [filePermissions, selectedItem]);++ const setGroupPerm = useCallback(+ (groupId: string, next: Partial<{ view: boolean; download: boolean }>) => {+ if (!selectedItem) return;++ setFilePermissions((prev) => {+ const current = prev[selectedItem.key]?.groupPermissions?.[groupId] || {+ view: false,+ download: false,+ };+ let view = next.view ?? current.view;+ let download = next.download ?? current.download;+ // Enforce invariants: download requires view; turning view off turns+ // download off too. Matches the server-side intent.+ if (download && !view) view = true;+ if (!view) download = false;++ return {+ ...prev,+ [selectedItem.key]: {+ groupPermissions: {+ ...prev[selectedItem.key]?.groupPermissions,+ [groupId]: { view, download },},+ linkPermissions: prev[selectedItem.key]?.linkPermissions || {},},- linkPermissions:- prev[currentDataroomDocumentId]?.linkPermissions || {},- },- }));+ };+ });},- [selectedGroupPermissions, currentDataroomDocumentId],+ [selectedItem],);- const updateLinkPermissions = useCallback(- (linkId: string, newPermissions: string[]) => {- if (!currentDataroomDocumentId) return;-- const hasView = newPermissions.includes("view");- const hasDownload = newPermissions.includes("download");-- const prevPermissions = selectedLinkPermissions[linkId] || {- view: false,- download: false,- };-- let finalPermissions = newPermissions;-- if (- hasDownload &&- !hasView &&- !prevPermissions.view &&- !prevPermissions.download- ) {- finalPermissions = ["view", "download"];- } else if (hasDownload && !hasView) {- finalPermissions = [];- }-- setFilePermissions((prev) => ({- ...prev,- [currentDataroomDocumentId]: {- groupPermissions:- prev[currentDataroomDocumentId]?.groupPermissions || {},- linkPermissions: {- ...prev[currentDataroomDocumentId]?.linkPermissions,- [linkId]: {- view: finalPermissions.includes("view"),- download: finalPermissions.includes("download"),+ const setLinkPerm = useCallback(+ (linkId: string, next: Partial<{ view: boolean; download: boolean }>) => {+ if (!selectedItem) return;++ setFilePermissions((prev) => {+ const current = prev[selectedItem.key]?.linkPermissions?.[linkId] || {+ view: false,+ download: false,+ };+ let view = next.view ?? current.view;+ let download = next.download ?? current.download;+ if (download && !view) view = true;+ if (!view) download = false;++ return {+ ...prev,+ [selectedItem.key]: {+ groupPermissions: prev[selectedItem.key]?.groupPermissions || {},+ linkPermissions: {+ ...prev[selectedItem.key]?.linkPermissions,+ [linkId]: { view, download },},},- },- }));+ };+ });},- [selectedLinkPermissions, currentDataroomDocumentId],+ [selectedItem],);- // Memoize bulk actions to avoid recreationconst enableViewForAll = useCallback(() => {- if (!currentDataroomDocumentId) return;-- // Enable view for all viewer groups+ if (!selectedItem) return;const newGroupPermissions = { ...selectedGroupPermissions };viewerGroups?.forEach((group) => {newGroupPermissions[group.id] = {@@ -323,8 +394,6 @@ export function SetUnifiedPermissionsModal({view: true,};});-- // Enable view for all linksconst newLinkPermissions = { ...selectedLinkPermissions };linksWithPermissionGroups?.forEach((link) => {newLinkPermissions[link.id] = {@@ -332,10 +401,9 @@ export function SetUnifiedPermissionsModal({view: true,};});-setFilePermissions((prev) => ({...prev,- [currentDataroomDocumentId]: {+ [selectedItem.key]: {groupPermissions: newGroupPermissions,linkPermissions: newLinkPermissions,},@@ -345,33 +413,22 @@ export function SetUnifiedPermissionsModal({selectedLinkPermissions,viewerGroups,linksWithPermissionGroups,- currentDataroomDocumentId,+ selectedItem,]);const enableDownloadForAll = useCallback(() => {- if (!currentDataroomDocumentId) return;-- // Enable view + download for all viewer groups+ if (!selectedItem) return;const newGroupPermissions = { ...selectedGroupPermissions };viewerGroups?.forEach((group) => {- newGroupPermissions[group.id] = {- view: true,- download: true,- };+ newGroupPermissions[group.id] = { view: true, download: true };});-- // Enable view + download for all linksconst newLinkPermissions = { ...selectedLinkPermissions };linksWithPermissionGroups?.forEach((link) => {- newLinkPermissions[link.id] = {- view: true,- download: true,- };+ newLinkPermissions[link.id] = { view: true, download: true };});-setFilePermissions((prev) => ({...prev,- [currentDataroomDocumentId]: {+ [selectedItem.key]: {groupPermissions: newGroupPermissions,linkPermissions: newLinkPermissions,},@@ -381,98 +438,117 @@ export function SetUnifiedPermissionsModal({selectedLinkPermissions,viewerGroups,linksWithPermissionGroups,- currentDataroomDocumentId,+ selectedItem,]);- const handleFileSelect = useCallback((file: (typeof uploadedFiles)[0]) => {- setSelectedFile(file);- setShowFileListState(false);- }, []);-- const handleBack = useCallback(() => {- setShowFileListState(true);- }, []);-const handleSubmit = useCallback(async (event: React.FormEvent) => {event.preventDefault();+ if (!selectedItem) return;setLoading(true);+ // Build the set of (id, itemType) pairs to write to. For a single+ // document this is just the document. For a folder we cascade to the+ // folder itself plus every descendant folder and document so a single+ // toggle gives the user access to (or hides) the whole tree.+ const targets: { itemId: string; itemType: ItemType }[] = [];+ if (selectedItem.type === "document") {+ targets.push({+ itemId: selectedItem.primaryId,+ itemType: ItemType.DATAROOM_DOCUMENT,+ });+ } else {+ targets.push({+ itemId: selectedItem.primaryId,+ itemType: ItemType.DATAROOM_FOLDER,+ });+ const descendants = folderDescendants ?? {+ folderIds: [],+ documentIds: [],+ };+ for (const folderId of descendants.folderIds) {+ targets.push({+ itemId: folderId,+ itemType: ItemType.DATAROOM_FOLDER,+ });+ }+ for (const documentId of descendants.documentIds) {+ targets.push({+ itemId: documentId,+ itemType: ItemType.DATAROOM_DOCUMENT,+ });+ }+ }+try {- // Save viewer group permissions (only if changed and at least one permission is true)const viewerGroupPromises = Object.entries(selectedGroupPermissions).filter(([groupId, permissions]) => {- // Only process groups that have actual permissions set OR have changed- const initialPermissions = initialGroupPermissions[groupId];- const hasChanged =- !initialPermissions ||- initialPermissions.view !== permissions.view ||- initialPermissions.download !== permissions.download;-- return hasChanged && (permissions.view || permissions.download);+ // Save whenever the user changed anything, including toggling+ // everything off. The server upserts to view=false,download=false+ // which effectively revokes access — required for the "remove+ // access" flow to actually persist.+ const initial = initialGroupPermissions[groupId];+ return (+ !initial ||+ initial.view !== permissions.view ||+ initial.download !== permissions.download+ );}).map(([groupId, permissions]) => {+ const payload: Record<+ string,+ { itemType: ItemType; view: boolean; download: boolean }+ > = {};+ for (const target of targets) {+ payload[target.itemId] = {+ itemType: target.itemType,+ view: permissions.view,+ download: permissions.download,+ };+ }return fetch(`/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}/permissions`,{method: "POST",- headers: {- "Content-Type": "application/json",- },+ headers: { "Content-Type": "application/json" },body: JSON.stringify({dataroomId,groupId,- permissions: {- [currentDataroomDocumentId]: {- itemType: ItemType.DATAROOM_DOCUMENT,- view: permissions.view,- download: permissions.download,- },- },+ permissions: payload,}),},);});- // Filter out link permissions that haven't changed or are both falseconst linksNeedingUpdate = Object.entries(selectedLinkPermissions).filter(([linkId, permissions]) => {- // Only process links that have actual permissions set OR need to be removed- const initialPermissions = initialLinkPermissions[linkId];- const hasChanged =- !initialPermissions ||- initialPermissions.view !== permissions.view ||- initialPermissions.download !== permissions.download;-- return hasChanged;+ const initial = initialLinkPermissions[linkId];+ return (+ !initial ||+ initial.view !== permissions.view ||+ initial.download !== permissions.download+ );}).map(([linkId, permissions]) => ({ linkId, permissions }));- // Save link permissions (only fetch and update what's needed)const linkPromises = linksNeedingUpdate.map(async ({ linkId, permissions }) => {const link = linksWithPermissionGroups.find((l) => l.id === linkId);if (!link?.permissionGroupId) return Promise.resolve();- // Fetch existing permissions for this permission groupconst existingPermissionsResponse = await fetch(`/api/teams/${teamId}/datarooms/${dataroomId}/permission-groups/${link.permissionGroupId}`,);-if (!existingPermissionsResponse.ok) {throw new Error("Failed to fetch existing permissions");}-const { permissionGroup } =await existingPermissionsResponse.json();- // Build the complete permissions object by merging existing with newconst allPermissions: Record<string,{ view: boolean; download: boolean; itemType: ItemType }> = {};-- // Add all existing permissionspermissionGroup.accessControls.forEach((control: any) => {allPermissions[control.itemId] = {view: control.canView,@@ -481,30 +557,24 @@ export function SetUnifiedPermissionsModal({};});- // Only add/update the permission if at least one is true- if (permissions.view || permissions.download) {- allPermissions[currentDataroomDocumentId] = {- itemType: ItemType.DATAROOM_DOCUMENT,- view: permissions.view,- download: permissions.download,- };- } else {- // If both are false, remove the permission entirely- delete allPermissions[currentDataroomDocumentId];+ for (const target of targets) {+ if (permissions.view || permissions.download) {+ allPermissions[target.itemId] = {+ itemType: target.itemType,+ view: permissions.view,+ download: permissions.download,+ };+ } else {+ delete allPermissions[target.itemId];+ }}- // Send the complete permissions setreturn fetch(`/api/teams/${teamId}/datarooms/${dataroomId}/permission-groups/${link.permissionGroupId}`,{method: "PUT",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- permissions: allPermissions,- linkId: linkId,- }),+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ permissions: allPermissions, linkId }),},);},@@ -516,32 +586,27 @@ export function SetUnifiedPermissionsModal({await Promise.all([mutateViewerGroups(),- mutate(- `/api/teams/${teamId}/datarooms/${dataroomId}/groups?documentId=${currentDocumentId}`,- ),+ selectedItem.type === "document" && selectedItem.documentId+ ? mutate(+ `/api/teams/${teamId}/datarooms/${dataroomId}/groups?documentId=${selectedItem.documentId}`,+ )+ : Promise.resolve(),mutate(`/api/teams/${teamId}/datarooms/${dataroomId}/permission-groups`,),mutate(`/api/teams/${teamId}/datarooms/${dataroomId}/links`),]);- // Mark current file as saved- setSavedFiles((prev) => new Set([...prev, currentDataroomDocumentId]));+ setSavedKeys((prev) => new Set([...prev, selectedItem.key]));- if (uploadedFiles.length > 1) {- // Find next unsaved file- const nextUnsavedFile = uploadedFiles.find(- (file) =>- !savedFiles.has(file.dataroomDocumentId) &&- file.dataroomDocumentId !== currentDataroomDocumentId,+ if (items.length > 1) {+ const next = items.find(+ (it) => it.key !== selectedItem.key && !savedKeys.has(it.key),);-- if (nextUnsavedFile) {- // Go to next unsaved file- setSelectedFile(nextUnsavedFile);+ if (next) {+ setSelectedKey(next.key);setShowFileListState(false);} else {- // All files are saved, complete the flowonComplete?.();setOpen(false);}@@ -557,540 +622,397 @@ export function SetUnifiedPermissionsModal({}},[+ selectedItem,selectedGroupPermissions,selectedLinkPermissions,initialGroupPermissions,initialLinkPermissions,teamId,dataroomId,- currentDataroomDocumentId,linksWithPermissionGroups,mutateViewerGroups,- currentDocumentId,- uploadedFiles,- savedFiles,+ items,+ savedKeys,onComplete,setOpen,+ folderDescendants,],);- // Memoize computed values for UI- const isLoading = useMemo(- () => viewerGroupsLoading || linksLoading || permissionGroupsLoading,- [viewerGroupsLoading, linksLoading, permissionGroupsLoading],- );+ const isLoading =+ viewerGroupsLoading ||+ linksLoading ||+ permissionGroupsLoading ||+ (selectedItem?.type === "folder" && folderTreeLoading);- const hasViewerGroups = useMemo(- () => viewerGroups && viewerGroups.length > 0,- [viewerGroups],- );-- const hasLinks = useMemo(- () => linksWithPermissionGroups && linksWithPermissionGroups.length > 0,- [linksWithPermissionGroups],- );+ const hasViewerGroups = !!viewerGroups && viewerGroups.length > 0;+ const hasLinks = linksWithPermissionGroups.length > 0;+ const hasAnyPermissions = hasViewerGroups || hasLinks;- const hasAnyPermissions = useMemo(- () => hasViewerGroups || hasLinks,- [hasViewerGroups, hasLinks],- );+ const folderDescendantCount = folderDescendants+ ? folderDescendants.folderIds.length + folderDescendants.documentIds.length+ : 0;return (<Dialog open={open} onOpenChange={setOpen}>- <DialogContent className="sm:max-w-[600px]">- <DialogHeader className="w-[90%]">- <div className="flex items-center gap-2">- {!showFileListState && uploadedFiles.length > 1 && (+ <DialogContent className="gap-0 p-0 sm:max-w-[560px] md:max-w-[640px]">+ <DialogHeader className="space-y-1 border-b px-6 py-5">+ <div className="flex items-start gap-2">+ {!showFileListState && items.length > 1 && (<Buttonvariant="ghost"size="icon"- onClick={handleBack}- className="h-8 w-8"+ onClick={() => setShowFileListState(true)}+ className="-ml-2 h-7 w-7"+ aria-label="Back to file list"><ArrowLeftIcon className="h-4 w-4" /></Button>)}- <div>- <DialogTitle>Set Permissions</DialogTitle>- <DialogDescription>+ <div className="flex-1">+ <DialogTitle className="text-base">{showFileListState- ? savedFiles.size === uploadedFiles.length- ? "All files have been processed successfully!"- : "Select a file to set permissions"- : "Update permissions for the selected file"}- {uploadedFiles.length > 1 && (- <div className="mt-2 text-sm text-muted-foreground">- Progress: {savedFiles.size} of {uploadedFiles.length} files- completed- </div>- )}+ ? "Set permissions"+ : selectedItem+ ? `Set permissions for ${selectedItem.name}`+ : "Set permissions"}+ </DialogTitle>+ <DialogDescription className="mt-1">+ {showFileListState+ ? savedKeys.size === items.length+ ? "All items have been updated."+ : `Choose an item to configure (${savedKeys.size}/${items.length} done)`+ : selectedItem?.type === "folder"+ ? folderTreeLoading+ ? "Loading folder contents…"+ : folderDescendantCount > 0+ ? `Applies to this folder and ${folderDescendantCount} ${+ folderDescendantCount === 1 ? "item" : "items"+ } inside`+ : "Applies to this folder"+ : "Choose who can view and download this file"}</DialogDescription></div></div></DialogHeader>{showFileListState ? (- <div className="space-y-2">- {uploadedFiles.map((file) => {- const isSaved = savedFiles.has(file.dataroomDocumentId);- const isSelected = selectedFile?.documentId === file.documentId;-+ <div className="max-h-[60vh] space-y-1.5 overflow-y-auto px-6 py-5">+ {items.map((item) => {+ const isSaved = savedKeys.has(item.key);return (- <div- key={file.documentId}+ <button+ key={item.key}+ type="button"+ onClick={() => {+ setSelectedKey(item.key);+ setShowFileListState(false);+ }}className={cn(- "flex cursor-pointer items-center justify-between rounded-lg border p-3",- isSelected- ? "border-primary bg-primary/5"- : isSaved- ? "border-green-200 bg-green-50"- : "hover:bg-muted/50",+ "flex w-full items-center justify-between rounded-md border bg-background px-3 py-2.5 text-left transition-colors hover:bg-muted/60",+ isSaved &&+ "border-emerald-200 bg-emerald-50/60 dark:border-emerald-900/60 dark:bg-emerald-950/30",)}- onClick={() => handleFileSelect(file)}>- <div className="flex items-center space-x-3">- <FileTextIcon className="h-5 w-5" />- <span>{file.fileName}</span>- </div>- <div className="flex items-center space-x-2">- {isSaved && (- <div className="text-sm text-green-600">✓ Saved</div>- )}- {isSelected && (- <div className="text-sm text-primary">Selected</div>+ <div className="flex min-w-0 items-center gap-3">+ {item.type === "folder" ? (+ <FolderIcon className="h-4 w-4 shrink-0 text-muted-foreground" />+ ) : (+ <FileTextIcon className="h-4 w-4 shrink-0 text-muted-foreground" />)}+ <span className="truncate text-sm">{item.name}</span></div>- </div>+ {isSaved ? (+ <span className="ml-3 flex items-center gap-1 text-xs text-emerald-700 dark:text-emerald-300">+ <CheckIcon className="h-3.5 w-3.5" />+ Saved+ </span>+ ) : (+ <span className="ml-3 text-xs text-muted-foreground">+ Configure+ </span>+ )}+ </button>);})}</div>) : (- <>- <div>- <p className="text-sm font-medium">Selected File</p>- <div className="mt-1 flex items-center space-x-2 rounded-lg border p-3">- <FileTextIcon className="h-5 w-5" />- <span>- {selectedFile?.fileName || uploadedFiles[0]?.fileName}- </span>- </div>- </div>-- {hasAnyPermissions && (- <div className="flex gap-2">- <Button- type="button"- variant="outline"- size="sm"- onClick={enableViewForAll}- className="flex items-center gap-2"- >- <EyeIcon className="h-4 w-4" />- Enable View for All- </Button>- <Button- type="button"- variant="outline"- size="sm"- onClick={enableDownloadForAll}- className="flex items-center gap-2"- >- <ArrowDownToLineIcon className="h-4 w-4" />- Enable Download for All- </Button>- </div>- )}+ <form onSubmit={handleSubmit} className="contents">+ <div className="space-y-5 px-6 py-5">+ {selectedItem ? (+ <div className="flex items-center gap-3 rounded-md border bg-muted/40 px-3 py-2.5">+ {selectedItem.type === "folder" ? (+ <FolderIcon className="h-4 w-4 shrink-0 text-muted-foreground" />+ ) : (+ <FileTextIcon className="h-4 w-4 shrink-0 text-muted-foreground" />+ )}+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm font-medium">+ {selectedItem.name}+ </p>+ <p className="text-xs text-muted-foreground">+ {selectedItem.type === "folder"+ ? folderTreeLoading+ ? "Folder · loading…"+ : `Folder · ${folderDescendantCount} ${+ folderDescendantCount === 1 ? "item" : "items"+ } inside`+ : "File"}+ </p>+ </div>+ </div>+ ) : null}++ {hasAnyPermissions ? (+ <div className="flex flex-wrap gap-2">+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={enableViewForAll}+ className="h-8"+ >+ <EyeIcon className="mr-1.5 h-3.5 w-3.5" />+ Enable view for all+ </Button>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={enableDownloadForAll}+ className="h-8"+ >+ <ArrowDownToLineIcon className="mr-1.5 h-3.5 w-3.5" />+ Enable download for all+ </Button>+ </div>+ ) : null}- <form onSubmit={handleSubmit}><div className="rounded-md border">- <div className="max-h-[400px] overflow-y-auto">+ <div className="max-h-[44vh] overflow-y-auto">{isLoading ? (- <div className="flex items-center justify-center py-8">- <Loader2 className="h-8 w-8 animate-spin" />+ <div className="flex items-center justify-center py-10">+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" /></div>) : !hasAnyPermissions ? (- <div className="py-8 text-center">- <p className="text-muted-foreground">- No groups or links found. Create groups or links to set- permissions.- </p>+ <div className="px-6 py-10 text-center text-sm text-muted-foreground">+ No groups or links yet. Create a viewer group or share+ link first to configure permissions.</div>) : (- <Table>- <TableHeader className="sticky top-0 z-10 bg-secondary">- <TableRow>- <TableHead className="w-[60%]">Name</TableHead>- <TableHead className="w-[20%] text-center">- View- </TableHead>- <TableHead className="w-[20%] text-center">- Download- </TableHead>- </TableRow>- </TableHeader>- <TableBody className="relative">- {hasViewerGroups && (- <>- <TableRow>- <TableCell- colSpan={3}- className="bg-muted/50 font-medium"- >- <div className="flex items-center gap-2">- <Users className="h-4 w-4" />- Viewer Groups- </div>- </TableCell>- </TableRow>- {viewerGroups?.map((group) => (- <TableRow key={group.id}>- <TableCell>- <div>- <p className="font-medium">{group.name}</p>- <p className="text-sm text-muted-foreground">- {group._count.members} members- </p>- </div>- </TableCell>- <TableCell className="text-center">- <ToggleGroup- type="multiple"- value={Object.entries(- selectedGroupPermissions[group.id] || {},- )- .filter(- ([key, value]) =>- key === "view" && value,- )- .map(([key, _]) => key)}- onValueChange={(value) => {- const currentPermissions = Object.entries(- selectedGroupPermissions[group.id] ||- {},- )- .filter(([_, val]) => val)- .map(([key, _]) => key);-- if (- currentPermissions.includes("view") &&- !value.includes("view")- ) {- const newPerms =- currentPermissions.filter(- (p) =>- p !== "view" && p !== "download",- );- updateGroupPermissions(- group.id,- newPerms,- );- } else if (- !currentPermissions.includes("view") &&- value.includes("view")- ) {- const newPerms = [- ...currentPermissions,- "view",- ];- updateGroupPermissions(- group.id,- newPerms,- );- }- }}- className="justify-center"- >- <ToggleGroupItem- value="view"- aria-label="Toggle view"- size="sm"- className={cn(- "px-3 py-1 text-muted-foreground hover:ring-1 hover:ring-gray-400 data-[state=on]:bg-foreground data-[state=on]:text-background",- selectedGroupPermissions[group.id]?.view- ? "data-[state=on]:bg-foreground data-[state=on]:text-background"- : "",- )}- >- {selectedGroupPermissions[group.id]- ?.view ? (- <EyeIcon className="h-5 w-5" />- ) : (- <EyeOffIcon className="h-5 w-5" />- )}- </ToggleGroupItem>- </ToggleGroup>- </TableCell>- <TableCell className="text-center">- <ToggleGroup- type="multiple"- value={Object.entries(- selectedGroupPermissions[group.id] || {},- )- .filter(- ([key, value]) =>- key === "download" && value,- )- .map(([key, _]) => key)}- onValueChange={(value) => {- const currentPermissions = Object.entries(- selectedGroupPermissions[group.id] ||- {},- )- .filter(([_, val]) => val)- .map(([key, _]) => key);-- if (- value.includes("download") &&- !currentPermissions.includes("view")- ) {- const newPerms = [- ...currentPermissions,- "view",- "download",- ];- updateGroupPermissions(- group.id,- newPerms,- );- } else {- const newPerms =- currentPermissions.filter(- (p) => p !== "download",- );- if (value.includes("download")) {- newPerms.push("download");- }- updateGroupPermissions(- group.id,- newPerms,- );- }- }}- className="justify-center"- >- <ToggleGroupItem- value="download"- aria-label="Toggle download"- size="sm"- className={cn(- "px-3 py-1 text-muted-foreground hover:ring-1 hover:ring-gray-400 data-[state=on]:bg-foreground data-[state=on]:text-background",- selectedGroupPermissions[group.id]- ?.download- ? "data-[state=on]:bg-foreground data-[state=on]:text-background"- : "",- )}- >- {selectedGroupPermissions[group.id]- ?.download ? (- <ArrowDownToLineIcon className="h-5 w-5" />- ) : (- <CloudDownloadOff className="h-5 w-5" />- )}- </ToggleGroupItem>- </ToggleGroup>- </TableCell>- </TableRow>- ))}- </>- )}-- {hasLinks && (- <>- <TableRow>- <TableCell- colSpan={3}- className="bg-muted/50 font-medium"- >- <div className="flex items-center gap-2">- <LinkIcon className="h-4 w-4" />- Links- </div>- </TableCell>- </TableRow>- {linksWithPermissionGroups?.map((link) => (- <TableRow key={link.id}>- <TableCell>- <div>- <p className="font-medium">- {link.name ||- `Link #${link.id.slice(-5)}`}- </p>- <p className="max-w-[300px] truncate text-sm text-muted-foreground">- {link.domainId && link.slug- ? `${link.domainSlug}/${link.slug}`- : `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${link.id}`}- </p>- </div>- </TableCell>- <TableCell className="text-center">- <ToggleGroup- type="multiple"- value={Object.entries(- selectedLinkPermissions[link.id] || {},- )- .filter(- ([key, value]) =>- key === "view" && value,- )- .map(([key, _]) => key)}- onValueChange={(value) => {- const currentPermissions = Object.entries(- selectedLinkPermissions[link.id] || {},- )- .filter(([_, val]) => val)- .map(([key, _]) => key);-- if (- currentPermissions.includes("view") &&- !value.includes("view")- ) {- const newPerms =- currentPermissions.filter(- (p) =>- p !== "view" && p !== "download",- );- updateLinkPermissions(- link.id,- newPerms,- );- } else if (- !currentPermissions.includes("view") &&- value.includes("view")- ) {- const newPerms = [- ...currentPermissions,- "view",- ];- updateLinkPermissions(- link.id,- newPerms,- );- }- }}- className="justify-center"- >- <ToggleGroupItem- value="view"- aria-label="Toggle view"- size="sm"- className={cn(- "px-3 py-1 text-muted-foreground hover:ring-1 hover:ring-gray-400 data-[state=on]:bg-foreground data-[state=on]:text-background",- selectedLinkPermissions[link.id]?.view- ? "data-[state=on]:bg-foreground data-[state=on]:text-background"- : "",- )}- >- {selectedLinkPermissions[link.id]- ?.view ? (- <EyeIcon className="h-5 w-5" />- ) : (- <EyeOffIcon className="h-5 w-5" />- )}- </ToggleGroupItem>- </ToggleGroup>- </TableCell>- <TableCell className="text-center">- <ToggleGroup- type="multiple"- value={Object.entries(- selectedLinkPermissions[link.id] || {},- )- .filter(- ([key, value]) =>- key === "download" && value,- )- .map(([key, _]) => key)}- onValueChange={(value) => {- const currentPermissions = Object.entries(- selectedLinkPermissions[link.id] || {},- )- .filter(([_, val]) => val)- .map(([key, _]) => key);-- if (- value.includes("download") &&- !currentPermissions.includes("view")- ) {- const newPerms = [- ...currentPermissions,- "view",- "download",- ];- updateLinkPermissions(- link.id,- newPerms,- );- } else {- const newPerms =- currentPermissions.filter(- (p) => p !== "download",- );- if (value.includes("download")) {- newPerms.push("download");- }- updateLinkPermissions(- link.id,- newPerms,- );- }- }}- className="justify-center"- >- <ToggleGroupItem- value="download"- aria-label="Toggle download"- size="sm"- className={cn(- "px-3 py-1 text-muted-foreground hover:ring-1 hover:ring-gray-400 data-[state=on]:bg-foreground data-[state=on]:text-background",- selectedLinkPermissions[link.id]- ?.download- ? "data-[state=on]:bg-foreground data-[state=on]:text-background"- : "",- )}- >- {selectedLinkPermissions[link.id]- ?.download ? (- <ArrowDownToLineIcon className="h-5 w-5" />- ) : (- <CloudDownloadOff className="h-5 w-5" />- )}- </ToggleGroupItem>- </ToggleGroup>- </TableCell>- </TableRow>- ))}- </>- )}- </TableBody>- </Table>+ <>+ {hasViewerGroups ? (+ <PermissionSection+ icon={<Users className="h-3.5 w-3.5" />}+ label="Viewer Groups"+ >+ {viewerGroups!.map((group) => {+ const perm = selectedGroupPermissions[group.id] || {+ view: false,+ download: false,+ };+ return (+ <PermissionRow+ key={group.id}+ primary={group.name}+ secondary={`${group._count.members} member${+ group._count.members === 1 ? "" : "s"+ }`}+ view={perm.view}+ download={perm.download}+ onView={(view) =>+ setGroupPerm(group.id, { view })+ }+ onDownload={(download) =>+ setGroupPerm(group.id, { download })+ }+ />+ );+ })}+ </PermissionSection>+ ) : null}++ {hasLinks ? (+ <PermissionSection+ icon={<LinkIcon className="h-3.5 w-3.5" />}+ label="Links"+ withTopBorder={hasViewerGroups}+ >+ {linksWithPermissionGroups.map((link) => {+ const perm = selectedLinkPermissions[link.id] || {+ view: false,+ download: false,+ };+ const primary =+ link.name || `Link #${link.id.slice(-5)}`;+ const secondary =+ link.domainId && link.slug+ ? `${link.domainSlug}/${link.slug}`+ : `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${link.id}`;+ return (+ <PermissionRow+ key={link.id}+ primary={primary}+ secondary={secondary}+ view={perm.view}+ download={perm.download}+ onView={(view) =>+ setLinkPerm(link.id, { view })+ }+ onDownload={(download) =>+ setLinkPerm(link.id, { download })+ }+ />+ );+ })}+ </PermissionSection>+ ) : null}+ </>)}</div></div>- <DialogFooter className="mt-6">- <Button- type="submit"- loading={loading}- disabled={!hasAnyPermissions}- >- {uploadedFiles.length > 1- ? (() => {- const remainingFiles = uploadedFiles.filter(- (file) =>- !savedFiles.has(file.dataroomDocumentId) &&- file.dataroomDocumentId !==- currentDataroomDocumentId,- );- return remainingFiles.length > 0- ? "Save & Next"- : "Save & Complete";- })()- : "Save permissions"}- </Button>- </DialogFooter>- </form>- </>+ </div>++ <DialogFooter className="border-t bg-muted/30 px-6 py-3">+ <Button+ type="submit"+ loading={loading}+ disabled={!hasAnyPermissions || !selectedItem}+ >+ {items.length > 1+ ? (() => {+ const remaining = items.filter(+ (it) =>+ it.key !== selectedItem?.key &&+ !savedKeys.has(it.key),+ );+ return remaining.length > 0+ ? "Save & next"+ : "Save & finish";+ })()+ : "Save permissions"}+ </Button>+ </DialogFooter>+ </form>)}</DialogContent></Dialog>);}++function PermissionSection({+ icon,+ label,+ withTopBorder,+ children,+}: {+ icon: React.ReactNode;+ label: string;+ withTopBorder?: boolean;+ children: React.ReactNode;+}) {+ return (+ <div className={cn(withTopBorder && "border-t")}>+ <div className="sticky top-0 z-10 flex items-center justify-between gap-2 border-b bg-muted/60 px-4 py-2 backdrop-blur supports-[backdrop-filter]:bg-muted/50">+ <div className="flex items-center gap-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground">+ {icon}+ {label}+ </div>+ <div className="flex shrink-0 items-center gap-1.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">+ <span className="w-16 text-center">View</span>+ <span className="w-16 text-center">Download</span>+ </div>+ </div>+ <div>{children}</div>+ </div>+ );+}++function PermissionRow({+ primary,+ secondary,+ view,+ download,+ onView,+ onDownload,+}: {+ primary: string;+ secondary?: string;+ view: boolean;+ download: boolean;+ onView: (next: boolean) => void;+ onDownload: (next: boolean) => void;+}) {+ return (+ <div className="flex items-center justify-between gap-3 border-b px-4 py-3 last:border-b-0">+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm font-medium">{primary}</p>+ {secondary ? (+ <p className="truncate text-xs text-muted-foreground">{secondary}</p>+ ) : null}+ </div>+ <div className="flex shrink-0 items-center gap-1.5">+ <div className="flex w-16 justify-center">+ <PermissionToggle+ pressed={view}+ onPressedChange={onView}+ aria-label="Toggle view"+ ariaLabelOn="View enabled"+ ariaLabelOff="View disabled"+ >+ {view ? (+ <EyeIcon className="h-4 w-4" />+ ) : (+ <EyeOffIcon className="h-4 w-4" />+ )}+ </PermissionToggle>+ </div>+ <div className="flex w-16 justify-center">+ <PermissionToggle+ pressed={download}+ onPressedChange={onDownload}+ aria-label="Toggle download"+ ariaLabelOn="Download enabled"+ ariaLabelOff="Download disabled"+ >+ {download ? (+ <ArrowDownToLineIcon className="h-4 w-4" />+ ) : (+ <CloudDownloadOff className="h-4 w-4" />+ )}+ </PermissionToggle>+ </div>+ </div>+ </div>+ );+}++function PermissionToggle({+ pressed,+ onPressedChange,+ ariaLabelOn,+ ariaLabelOff,+ children,+ ...rest+}: {+ pressed: boolean;+ onPressedChange: (next: boolean) => void;+ ariaLabelOn: string;+ ariaLabelOff: string;+ children: React.ReactNode;+} & React.HTMLAttributes<HTMLButtonElement>) {+ return (+ <Toggle+ size="sm"+ pressed={pressed}+ onPressedChange={onPressedChange}+ aria-label={pressed ? ariaLabelOn : ariaLabelOff}+ className={cn(+ "h-9 w-9 p-0 text-muted-foreground hover:bg-muted hover:text-foreground data-[state=on]:bg-foreground data-[state=on]:text-background",+ )}+ {...rest}+ >+ {children}+ </Toggle>+ );+}diff --git a/components/datarooms/settings/permission-settings.tsx b/components/datarooms/settings/permission-settings.tsxindex a3038e9a..d6292bf3 100644--- a/components/datarooms/settings/permission-settings.tsx+++ b/components/datarooms/settings/permission-settings.tsx@@ -1,10 +1,11 @@import { useState } from "react";import { useTeam } from "@/context/team-context";+import { LinkIcon, UsersIcon } from "lucide-react";import { toast } from "sonner";import useSWR from "swr";-import { fetcher } from "@/lib/utils";+import { cn, fetcher } from "@/lib/utils";import {Card,@@ -21,48 +22,99 @@ type DefaultPermissionStrategy =| "ASK_EVERY_TIME"| "HIDDEN_BY_DEFAULT";+type PermissionField =+ | "defaultPermissionStrategy"+ | "defaultGroupPermissionStrategy";++interface DataroomPermissionData {+ id: string;+ name: string;+ pId: string;+ defaultPermissionStrategy: DefaultPermissionStrategy;+ defaultGroupPermissionStrategy: DefaultPermissionStrategy;+}+interface PermissionSettingsProps {dataroomId: string;}+const STRATEGY_OPTIONS: {+ value: DefaultPermissionStrategy;+ label: string;+ description: string;+}[] = [+ {+ value: "INHERIT_FROM_PARENT",+ label: "Inherit from parent folder",+ description:+ "New documents and folders inherit permissions from their parent folder. Root-level items get view-only by default.",+ },+ {+ value: "ASK_EVERY_TIME",+ label: "Ask every time",+ description:+ "Show a permissions dialog after each upload to configure access manually.",+ },+ {+ value: "HIDDEN_BY_DEFAULT",+ label: "Hidden by default",+ description:+ "New documents and folders are hidden. Grant access manually before they become visible.",+ },+];++const SCOPES: {+ key: PermissionField;+ label: string;+ icon: React.ComponentType<{ className?: string }>;+}[] = [+ {+ key: "defaultGroupPermissionStrategy",+ label: "Groups",+ icon: UsersIcon,+ },+ {+ key: "defaultPermissionStrategy",+ label: "Links",+ icon: LinkIcon,+ },+];+export default function PermissionSettings({dataroomId,}: PermissionSettingsProps) {const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;- const { data: dataroomData, mutate: mutateDataroom } = useSWR<{- id: string;- name: string;- pId: string;- defaultPermissionStrategy: DefaultPermissionStrategy;- }>(- teamId && dataroomId- ? `/api/teams/${teamId}/datarooms/${dataroomId}`- : null,- fetcher,- );+ const { data: dataroomData, mutate: mutateDataroom } =+ useSWR<DataroomPermissionData>(+ teamId && dataroomId+ ? `/api/teams/${teamId}/datarooms/${dataroomId}`+ : null,+ fetcher,+ );- const [isUpdating, setIsUpdating] = useState(false);+ const [updatingField, setUpdatingField] = useState<PermissionField | null>(+ null,+ );- const handlePermissionChange = async (value: DefaultPermissionStrategy) => {- if (!dataroomId || !teamId || isUpdating || !dataroomData) return;- setIsUpdating(true);+ const handlePermissionChange = async (+ field: PermissionField,+ value: DefaultPermissionStrategy,+ ) => {+ if (!dataroomId || !teamId || updatingField || !dataroomData) return;+ setUpdatingField(field);- const optimisticData = {+ const optimisticData: DataroomPermissionData = {...dataroomData,- defaultPermissionStrategy: value,+ [field]: value,};const mutation = async () => {const res = await fetch(`/api/teams/${teamId}/datarooms/${dataroomId}`, {method: "PATCH",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- defaultPermissionStrategy: value,- }),+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ [field]: value }),});if (!res.ok) {@@ -82,77 +134,128 @@ export default function PermissionSettings({}),{loading: "Updating permission settings...",- success: "Permission settings updated successfully",+ success: "Permission settings updated",error: (err) => err.message,},);} catch (error) {console.error(error);} finally {- setIsUpdating(false);+ setUpdatingField(null);}};- const currentStrategy =- dataroomData?.defaultPermissionStrategy ?? "HIDDEN_BY_DEFAULT";+ const values: Record<PermissionField, DefaultPermissionStrategy> = {+ defaultGroupPermissionStrategy:+ dataroomData?.defaultGroupPermissionStrategy ?? "INHERIT_FROM_PARENT",+ defaultPermissionStrategy:+ dataroomData?.defaultPermissionStrategy ?? "INHERIT_FROM_PARENT",+ };++ const disabled = updatingField !== null || !dataroomData;return (<Card><CardHeader><CardTitle>Default File Permissions</CardTitle><CardDescription>- Configure how permissions are handled for new documents and folders- added to this dataroom.+ Configure how new documents and folders are exposed to groups and+ links. Each scope is set independently.</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="INHERIT_FROM_PARENT" id="inherit" />- <div>- <Label htmlFor="inherit" className="text-sm font-medium">- Inherit from parent folder- </Label>- <p className="text-xs text-muted-foreground">- New documents and folders automatically inherit permissions from- their parent folder. Root-level items get view-only permissions- by default.- </p>- </div>- </div>-- <div className="flex items-center space-x-3">- <RadioGroupItem value="ASK_EVERY_TIME" id="ask" />- <div>- <Label htmlFor="ask" className="text-sm font-medium">- Ask every time- </Label>- <p className="text-xs text-muted-foreground">- Show permissions modal for each document upload to manually- configure permissions.- </p>- </div>+ <CardContent>+ <div className="grid grid-cols-[1fr_auto] gap-x-8 gap-y-1">+ <div />+ <div className="flex items-center gap-1">+ {SCOPES.map((scope) => (+ <div+ key={scope.key}+ className="flex w-20 items-center justify-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground"+ >+ <scope.icon className="h-3 w-3" />+ {scope.label}+ </div>+ ))}</div>- <div className="flex items-center space-x-3">- <RadioGroupItem value="HIDDEN_BY_DEFAULT" id="hidden" />- <div>- <Label htmlFor="hidden" className="text-sm font-medium">- Hidden by default- </Label>- <p className="text-xs text-muted-foreground">- New documents and folders are hidden by default. Permissions- must be configured manually.- </p>- </div>- </div>- </RadioGroup>+ {STRATEGY_OPTIONS.map((option, index) => (+ <StrategyRow+ key={option.value}+ option={option}+ values={values}+ disabled={disabled}+ isFirst={index === 0}+ onChange={handlePermissionChange}+ />+ ))}+ </div></CardContent></Card>);}++function StrategyRow({+ option,+ values,+ disabled,+ isFirst,+ onChange,+}: {+ option: (typeof STRATEGY_OPTIONS)[number];+ values: Record<PermissionField, DefaultPermissionStrategy>;+ disabled: boolean;+ isFirst: boolean;+ onChange: (+ field: PermissionField,+ value: DefaultPermissionStrategy,+ ) => void;+}) {+ return (+ <>+ <div+ className={cn(+ "py-3",+ !isFirst && "border-t border-border/60",+ )}+ >+ <Label+ htmlFor={`group-${option.value}`}+ className="text-sm font-medium"+ >+ {option.label}+ </Label>+ <p className="mt-0.5 text-xs text-muted-foreground">+ {option.description}+ </p>+ </div>+ <div+ className={cn(+ "flex items-center gap-1 py-3",+ !isFirst && "border-t border-border/60",+ )}+ >+ {SCOPES.map((scope) => (+ <div+ key={scope.key}+ className="flex w-20 items-center justify-center"+ >+ <RadioGroup+ value={values[scope.key]}+ onValueChange={(value) =>+ onChange(scope.key, value as DefaultPermissionStrategy)+ }+ disabled={disabled}+ aria-label={`${scope.label} default`}+ >+ <RadioGroupItem+ value={option.value}+ id={`${scope.key}-${option.value}`}+ aria-label={`${option.label} for ${scope.label.toLowerCase()}`}+ />+ </RadioGroup>+ </div>+ ))}+ </div>+ </>+ );+}diff --git a/components/documents/add-document-modal.tsx b/components/documents/add-document-modal.tsxindex 9c52b396..410e687b 100644--- a/components/documents/add-document-modal.tsx+++ b/components/documents/add-document-modal.tsx@@ -166,11 +166,20 @@ export function AddDocumentModal({if (!hasAnyGroups) return;- const strategy =+ const groupStrategy =+ dataroom?.defaultGroupPermissionStrategy ||+ DefaultPermissionStrategy.INHERIT_FROM_PARENT;+ const linkStrategy =dataroom?.defaultPermissionStrategy ||DefaultPermissionStrategy.INHERIT_FROM_PARENT;- if (strategy === DefaultPermissionStrategy.ASK_EVERY_TIME) {+ // If either side wants to ask, surface the unified modal so the user can+ // configure group and/or link permissions in one place.+ const shouldAsk =+ groupStrategy === DefaultPermissionStrategy.ASK_EVERY_TIME ||+ linkStrategy === DefaultPermissionStrategy.ASK_EVERY_TIME;++ if (shouldAsk) {setShowGroupPermissions(true);setUploadedFiles([{@@ -179,28 +188,39 @@ export function AddDocumentModal({fileName: document.name,},]);- } else if (strategy === DefaultPermissionStrategy.INHERIT_FROM_PARENT) {- const isRootLevel = !currentFolderPath || currentFolderPath.length === 0;+ return;+ }- try {- const result = await applyPermissions(- dataroomId!,- [document.id],- "INHERIT_FROM_PARENT",- isRootLevel ? undefined : currentFolderPath?.join("/"),- toastErrorMessage,- );+ // No interactive prompt needed — defer to the server, which will apply+ // each strategy independently to viewer groups vs. permission groups.+ // HIDDEN_BY_DEFAULT for both sides becomes a no-op server-side, so we can+ // skip the round-trip entirely in that case.+ if (+ groupStrategy === DefaultPermissionStrategy.HIDDEN_BY_DEFAULT &&+ linkStrategy === DefaultPermissionStrategy.HIDDEN_BY_DEFAULT+ ) {+ return;+ }- if (!result.success) {- console.error("Failed to apply permissions:", result.error);- toastErrorMessage();- }- } catch (error) {- console.error("Failed to apply permissions:", error);+ const isRootLevel = !currentFolderPath || currentFolderPath.length === 0;++ try {+ const result = await applyPermissions(+ dataroomId!,+ [document.id],+ { groupStrategy, linkStrategy },+ isRootLevel ? undefined : currentFolderPath?.join("/"),+ toastErrorMessage,+ );++ if (!result.success) {+ console.error("Failed to apply permissions:", result.error);toastErrorMessage();}+ } catch (error) {+ console.error("Failed to apply permissions:", error);+ toastErrorMessage();}- // strategy === DefaultPermissionStrategy.HIDDEN_BY_DEFAULT - do nothing, documents remain hidden};const handleFileUpload = async (diff --git a/components/documents/folder-card.tsx b/components/documents/folder-card.tsxindex 98b76324..f679d53a 100644--- a/components/documents/folder-card.tsx+++ b/components/documents/folder-card.tsx@@ -10,6 +10,7 @@ import {ClipboardCopyIcon,CopyIcon,EyeOffIcon,+ FileSlidersIcon,FolderIcon,FolderInputIcon,FolderPenIcon,@@ -40,6 +41,7 @@ import {} from "@/components/ui/dropdown-menu";import { MoveToDataroomFolderModal } from "../datarooms/move-dataroom-folder-modal";+import { SetUnifiedPermissionsModal } from "../datarooms/groups/set-unified-permissions-modal";import { EditFolderModal } from "../folders/edit-folder-modal";import { AddFolderToDataroomModal } from "./add-folder-to-dataroom-modal";import { MoveToFolderModal } from "./move-folder-modal";@@ -76,6 +78,8 @@ export default function FolderCard({const [openFolder, setOpenFolder] = useState<boolean>(false);const [menuOpen, setMenuOpen] = useState<boolean>(false);const [addDataroomOpen, setAddDataroomOpen] = useState<boolean>(false);+ const [groupPermissionOpen, setGroupPermissionOpen] =+ useState<boolean>(false);const dropdownRef = useRef<HTMLDivElement | null>(null);// Get hierarchical display name for dataroom folders@@ -346,6 +350,18 @@ export default function FolderCard({? "Copy folder to other dataroom": "Add folder to dataroom"}</DropdownMenuItem>+ {isDataroom && dataroomId ? (+ <DropdownMenuItem+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setGroupPermissionOpen(true);+ }}+ >+ <FileSlidersIcon className="mr-2 h-4 w-4" />+ Set Group Permissions+ </DropdownMenuItem>+ ) : null}<DropdownMenuItemonClick={(e) => {e.preventDefault();@@ -438,6 +454,20 @@ export default function FolderCard({itemName={folder.name}/>) : null}+ {groupPermissionOpen && isDataroom && dataroomId ? (+ <SetUnifiedPermissionsModal+ open={groupPermissionOpen}+ setOpen={setGroupPermissionOpen}+ dataroomId={dataroomId}+ uploadedFiles={[+ {+ dataroomFolderId: folder.id,+ fileName: folder.name,+ itemType: "folder",+ },+ ]}+ />+ ) : null}</>);}diff --git a/components/upload-zone.tsx b/components/upload-zone.tsxindex 69f1b288..dc0d67b3 100644--- a/components/upload-zone.tsx+++ b/components/upload-zone.tsx@@ -53,6 +53,8 @@ interface FileWithPaths extends File {topLevelItemFolderCount?: number;/** Server-generated slug path for the top-level folder (e.g. "folder-with-100-subfolders") */topLevelItemFolderPath?: string;+ /** Database id of the top-level folder in the dataroom (only set in dataroom uploads) */+ topLevelDataroomFolderId?: string;}export interface RejectedFile {@@ -113,6 +115,13 @@ async function processWithConcurrency<T>(return results;}+export interface UploadedTopLevelFolder {+ /** Database id of the dataroom folder */+ dataroomFolderId: string;+ /** Folder name shown to the user */+ name: string;+}+interface UploadZoneProps extends React.PropsWithChildren {onUploadBatchStart: (batch: UploadBatchState, cancelFn: () => void) => void;onUploadBatchUpdate: (batchId: string, update: Partial<UploadBatchState>) => void;@@ -122,7 +131,10 @@ interface UploadZoneProps extends React.PropsWithChildren {fileName: string;documentId: string;dataroomDocumentId: string;+ /** Set when this file was uploaded as part of a top-level dataroom folder */+ topLevelDataroomFolderId?: string;}[],+ folders?: UploadedTopLevelFolder[],) => void;onTraversalStart?: (preliminaryItems?: { name: string; isFolder: boolean }[],@@ -433,6 +445,7 @@ export default function UploadZone({isFolder: boolean;folderCount: number;folderSlugPath?: string;+ dataroomFolderId?: string;files: FileWithPaths[];}>();@@ -447,6 +460,7 @@ export default function UploadZone({isFolder: file.topLevelItemIsFolder ?? false,folderCount: file.topLevelItemFolderCount ?? 0,folderSlugPath: file.topLevelItemFolderPath,+ dataroomFolderId: file.topLevelDataroomFolderId,files: [file],});}@@ -731,7 +745,12 @@ export default function UploadZone({? (await dataroomResponse.json()).id: null;- return { ...document, dataroomDocumentId: dataroomDocumentId };+ return {+ ...document,+ dataroomDocumentId: dataroomDocumentId,+ topLevelDataroomFolderId: file.topLevelDataroomFolderId,+ topLevelItemIsFolder: file.topLevelItemIsFolder,+ };} catch (error) {failedCount++;parentItem.failedEntries++;@@ -761,8 +780,25 @@ export default function UploadZone({documentId: document.id,dataroomDocumentId: document.dataroomDocumentId,fileName: document.name,+ topLevelDataroomFolderId: document.topLevelDataroomFolderId,}));- onUploadSuccess?.(dataroomDocuments);++ // Collect every top-level folder the user dropped so the caller can+ // offer one-shot folder-level permission configuration instead of+ // walking through every uploaded file individually.+ const uploadedFolders: UploadedTopLevelFolder[] = Array.from(+ itemGroups.values(),+ )+ .filter(+ (group) =>+ group.isFolder && !!group.dataroomFolderId,+ )+ .map((group) => ({+ dataroomFolderId: group.dataroomFolderId!,+ name: group.name,+ }));++ onUploadSuccess?.(dataroomDocuments, uploadedFolders);} catch (error) {console.error("Upload batch failed:", error);}@@ -868,6 +904,7 @@ export default function UploadZone({folderCounter?: { count: number },folderPathCapture?: { value?: string },topLevelName?: string,+ folderIdCapture?: { value?: string },): Promise<FileWithPaths[]> => {/*** Summary of this function:@@ -959,6 +996,7 @@ export default function UploadZone({folderCounter,folderPathCapture,topLevelName,+ folderIdCapture,)),);}@@ -981,16 +1019,17 @@ export default function UploadZone({await getOrCreateDataroomFolder();}- const { dataroomPath, mainDocsPath } = await createFolderInBoth({- teamId: teamInfo.currentTeam.id,- dataroomId,- name: entry.name,- parentMainDocsPath: targetParentMainDocsPath,- parentDataroomPath: targetParentDataroomPath,- setRejectedFiles,- analytics,- replicateDataroomFolders,- });+ const { dataroomPath, dataroomFolderId, mainDocsPath } =+ await createFolderInBoth({+ teamId: teamInfo.currentTeam.id,+ dataroomId,+ name: entry.name,+ parentMainDocsPath: targetParentMainDocsPath,+ parentDataroomPath: targetParentDataroomPath,+ setRejectedFiles,+ analytics,+ replicateDataroomFolders,+ });if (folderCounter) folderCounter.count++;if (folderPathCapture && folderPathCapture.value === undefined) {@@ -998,6 +1037,9 @@ export default function UploadZone({? dataroomPath.slice(1): dataroomPath;}+ if (folderIdCapture && folderIdCapture.value === undefined) {+ folderIdCapture.value = dataroomFolderId;+ }const dirReader = (entry as FileSystemDirectoryEntry@@ -1029,6 +1071,7 @@ export default function UploadZone({folderCounter,folderPathCapture,topLevelName,+ folderIdCapture,)),);}@@ -1135,6 +1178,7 @@ export default function UploadZone({if (!entry) return [];const counter = { count: 0 };const pathCapture: { value?: string } = {};+ const folderIdCapture: { value?: string } = {};return traverseFolder(entry,folderPathName,@@ -1142,12 +1186,14 @@ export default function UploadZone({counter,pathCapture,entry.name,+ folderIdCapture,).then((files) => {for (const f of files) {f.topLevelItemName = entry.name;f.topLevelItemIsFolder = entry.isDirectory;f.topLevelItemFolderCount = counter.count;f.topLevelItemFolderPath = pathCapture.value;+ f.topLevelDataroomFolderId = folderIdCapture.value;}return files;});diff --git a/lib/folders/create-folder.ts b/lib/folders/create-folder.tsindex 8dd4fb89..e7287d32 100644--- a/lib/folders/create-folder.ts+++ b/lib/folders/create-folder.ts@@ -10,6 +10,7 @@ export function isSystemFile(name: string): boolean {}interface CreateFolderResponse {+ id: string;path: string;parentFolderPath?: string;name: string;@@ -114,7 +115,11 @@ export async function createFolderInBoth({setRejectedFiles: (files: { fileName: string; message: string }[]) => void;analytics: any;replicateDataroomFolders?: boolean;-}): Promise<{ dataroomPath: string; mainDocsPath: string | undefined }> {+}): Promise<{+ dataroomPath: string;+ dataroomFolderId: string;+ mainDocsPath: string | undefined;+}> {try {// Always create folder in dataroomconst dataroomResponse = await createFolderInDataroom({@@ -165,6 +170,7 @@ export async function createFolderInBoth({return {dataroomPath: dataroomResponse.path,+ dataroomFolderId: dataroomResponse.id,mainDocsPath: mainDocsResponse?.path,};} catch (error) {diff --git a/lib/hooks/use-dataroom-permissions.ts b/lib/hooks/use-dataroom-permissions.tsindex f27cf621..526c0c1b 100644--- a/lib/hooks/use-dataroom-permissions.ts+++ b/lib/hooks/use-dataroom-permissions.ts@@ -1,5 +1,10 @@import { useTeam } from "@/context/team-context";+export type PermissionStrategy =+ | "INHERIT_FROM_PARENT"+ | "ASK_EVERY_TIME"+ | "HIDDEN_BY_DEFAULT";+export const useDataroomPermissions = () => {const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;@@ -7,7 +12,12 @@ export const useDataroomPermissions = () => {const applyPermissions = async (dataroomId: string,documentIds: string[],- strategy: "INHERIT_FROM_PARENT" | "ASK_EVERY_TIME" | "HIDDEN_BY_DEFAULT",+ strategies:+ | PermissionStrategy+ | {+ groupStrategy?: PermissionStrategy;+ linkStrategy?: PermissionStrategy;+ },folderPath?: string,onError?: (message: string) => void,): Promise<{ success: boolean; error?: string }> => {@@ -19,6 +29,22 @@ export const useDataroomPermissions = () => {return { success: false, error: "No document IDs provided" };}+ // Accept either a legacy single-strategy string (applied to both targets+ // server-side for backward compat) or per-target strategies.+ const body =+ typeof strategies === "string"+ ? {+ documentIds,+ strategy: strategies,+ folderPath,+ }+ : {+ documentIds,+ groupStrategy: strategies.groupStrategy,+ linkStrategy: strategies.linkStrategy,+ folderPath,+ };+try {const response = await fetch(`/api/teams/${encodeURIComponent(teamId)}/datarooms/${encodeURIComponent(dataroomId)}/apply-permissions`,@@ -27,11 +53,7 @@ export const useDataroomPermissions = () => {headers: {"Content-Type": "application/json",},- body: JSON.stringify({- documentIds,- strategy,- folderPath,- }),+ body: JSON.stringify(body),},);diff --git a/lib/swr/use-dataroom-groups.ts b/lib/swr/use-dataroom-groups.tsindex d1380221..41678cea 100644--- a/lib/swr/use-dataroom-groups.ts+++ b/lib/swr/use-dataroom-groups.ts@@ -17,8 +17,13 @@ import { LinkWithViews } from "../types";export default function useDataroomGroups({documentId,+ folderId,dataroomId: dataroomIdOverride,-}: { documentId?: string; dataroomId?: string } = {}) {+}: {+ documentId?: string;+ folderId?: string;+ dataroomId?: string;+} = {}) {const teamInfo = useTeam();const router = useRouter();@@ -37,6 +42,14 @@ export default function useDataroomGroups({};};+ // Build the optional scope query — at most one of documentId/folderId is+ // expected (the API picks the first one it sees).+ const scopeQuery = documentId+ ? `?documentId=${documentId}`+ : folderId+ ? `?folderId=${folderId}`+ : "";+const {data: viewerGroups,error,@@ -45,9 +58,7 @@ export default function useDataroomGroups({teamInfo?.currentTeam?.id &&id &&isDataroom &&- `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${id}/groups${- documentId ? `?documentId=${documentId}` : ""- }`,+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${id}/groups${scopeQuery}`,fetcher,{ dedupingInterval: 30000 },);diff --git a/pages/api/teams/[teamId]/datarooms/[id]/apply-permissions.ts b/pages/api/teams/[teamId]/datarooms/[id]/apply-permissions.tsindex e721d50d..a1f7db5e 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/apply-permissions.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/apply-permissions.ts@@ -1,13 +1,21 @@import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";-import { ItemType } from "@prisma/client";+import { DefaultPermissionStrategy, ItemType } from "@prisma/client";import { getServerSession } from "next-auth";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";+type GroupTarget = "VIEWER_GROUP" | "PERMISSION_GROUP";++const VALID_STRATEGIES = new Set<string>([+ "INHERIT_FROM_PARENT",+ "ASK_EVERY_TIME",+ "HIDDEN_BY_DEFAULT",+]);+async function revalidateLinksForDataroom(dataroomId: string): Promise<void> {try {const links = await prisma.link.findMany({@@ -67,9 +75,17 @@ export default async function handler(const userId = (session.user as CustomUser).id;try {- const { documentIds, strategy, folderPath } = req.body as {+ const {+ documentIds,+ strategy,+ groupStrategy,+ linkStrategy,+ folderPath,+ } = req.body as {documentIds: string[];- strategy: string;+ strategy?: string;+ groupStrategy?: string;+ linkStrategy?: string;folderPath?: string;};@@ -82,17 +98,11 @@ export default async function handler(return res.status(400).json({ message: "Document IDs are required" });}- if (!strategy) {- return res.status(400).json({ message: "Strategy is required" });- }-- // Validate strategy- if (- !["INHERIT_FROM_PARENT", "ASK_EVERY_TIME", "HIDDEN_BY_DEFAULT"].includes(- strategy,- )- ) {- return res.status(400).json({ message: "Invalid strategy" });+ // Validate all provided strategies+ for (const value of [strategy, groupStrategy, linkStrategy]) {+ if (value !== undefined && !VALID_STRATEGIES.has(value)) {+ return res.status(400).json({ message: "Invalid strategy" });+ }}// Check if the user is part of the team@@ -114,6 +124,7 @@ export default async function handler(id: true,teamId: true,defaultPermissionStrategy: true,+ defaultGroupPermissionStrategy: true,},});@@ -121,6 +132,20 @@ export default async function handler(return res.status(404).json({ message: "Dataroom not found" });}+ // Resolve effective strategies. Precedence:+ // 1. Explicit per-target strategy from the request body.+ // 2. Legacy `strategy` field (applied to both targets) for backward+ // compatibility with older clients that didn't know about the split.+ // 3. The dataroom's stored defaults.+ const effectiveGroupStrategy =+ (groupStrategy as DefaultPermissionStrategy | undefined) ??+ (strategy as DefaultPermissionStrategy | undefined) ??+ dataroom.defaultGroupPermissionStrategy;+ const effectiveLinkStrategy =+ (linkStrategy as DefaultPermissionStrategy | undefined) ??+ (strategy as DefaultPermissionStrategy | undefined) ??+ dataroom.defaultPermissionStrategy;+// Get dataroom documents for the provided document IDsconst dataroomDocuments = await prisma.dataroomDocument.findMany({where: {@@ -136,13 +161,23 @@ export default async function handler(.json({ message: "No documents found in this dataroom" });}- // Apply permissions based on strategy- await applyPermissionStrategy(- dataroomId,- dataroomDocuments,- strategy,- folderPath,- );+ // Apply each strategy independently to its target group type+ await Promise.all([+ applyPermissionStrategy({+ dataroomId,+ dataroomDocuments,+ strategy: effectiveGroupStrategy,+ folderPath,+ target: "VIEWER_GROUP",+ }),+ applyPermissionStrategy({+ dataroomId,+ dataroomDocuments,+ strategy: effectiveLinkStrategy,+ folderPath,+ target: "PERMISSION_GROUP",+ }),+ ]);// Revalidate ISR pages for links with permission restrictionsawait revalidateLinksForDataroom(dataroomId);@@ -150,38 +185,44 @@ export default async function handler(return res.status(200).json({message: "Permissions applied successfully",documentsProcessed: dataroomDocuments.length,+ groupStrategy: effectiveGroupStrategy,+ linkStrategy: effectiveLinkStrategy,});} catch (error) {errorhandler(error, res);}}-async function applyPermissionStrategy(- dataroomId: string,+async function applyPermissionStrategy(opts: {+ dataroomId: string;dataroomDocuments: {id: string;documentId: string;folderId: string | null;- }[],- strategy: string,- folderPath?: string,-) {- if (strategy === "INHERIT_FROM_PARENT") {- const isRootLevel = !folderPath || folderPath.length === 0;-- if (isRootLevel) {- // For root level, apply view-only permissions to all groups- await applyRootLevelPermissions(dataroomId, dataroomDocuments);- } else {- // For subfolders, inherit from parent folder- await inheritFromParentFolder(dataroomId, dataroomDocuments, folderPath);- }- } else if (strategy === "ASK_EVERY_TIME") {- // Do nothing here - the UI will handle showing the permission modal- return;- } else if (strategy === "HIDDEN_BY_DEFAULT") {- // Do nothing here - documents remain hidden with no permissions- return;+ }[];+ strategy: DefaultPermissionStrategy;+ folderPath?: string;+ target: GroupTarget;+}) {+ const { dataroomId, dataroomDocuments, strategy, folderPath, target } = opts;++ // ASK_EVERY_TIME and HIDDEN_BY_DEFAULT both intentionally leave the document+ // hidden until something else writes the access control rows (the unified+ // permissions modal for ASK_EVERY_TIME, manual configuration for+ // HIDDEN_BY_DEFAULT).+ if (strategy !== DefaultPermissionStrategy.INHERIT_FROM_PARENT) return;++ const isRootLevel = !folderPath || folderPath.length === 0;++ if (isRootLevel) {+ await applyRootLevelPermissions(dataroomId, dataroomDocuments, target);+ } else {+ await inheritFromParentFolder(+ dataroomId,+ dataroomDocuments,+ folderPath!,+ target,+ );}}@@ -192,66 +233,57 @@ async function applyRootLevelPermissions(documentId: string;folderId: string | null;}[],+ target: GroupTarget,) {- // Get both ViewerGroups and PermissionGroups- const [viewerGroups, permissionGroups] = await Promise.all([- prisma.viewerGroup.findMany({+ if (target === "VIEWER_GROUP") {+ const viewerGroups = await prisma.viewerGroup.findMany({where: { dataroomId },select: { id: true },- }),- prisma.permissionGroup.findMany({- where: { dataroomId },- select: { id: true },- }),- ]);-- const viewerGroupPermissionsToCreate: any[] = [];- const permissionGroupPermissionsToCreate: any[] = [];-- // ViewerGroup permissions - all get view-only access- viewerGroups.forEach((group) => {- dataroomDocuments.forEach((doc) => {- viewerGroupPermissionsToCreate.push({- groupId: group.id,- itemId: doc.id,- itemType: ItemType.DATAROOM_DOCUMENT,- canView: true,- canDownload: false,- });});- });+ if (viewerGroups.length === 0) return;- // PermissionGroup permissions - all get view-only access- permissionGroups.forEach((group) => {- dataroomDocuments.forEach((doc) => {- permissionGroupPermissionsToCreate.push({+ const data = viewerGroups.flatMap((group) =>+ dataroomDocuments.map((doc) => ({groupId: group.id,itemId: doc.id,itemType: ItemType.DATAROOM_DOCUMENT,canView: true,canDownload: false,- canDownloadOriginal: false,- });- });- });+ })),+ );- // Apply permissions in a transaction- await prisma.$transaction(async (tx) => {- // Create new permissions- if (viewerGroupPermissionsToCreate.length > 0) {- await tx.viewerGroupAccessControls.createMany({- data: viewerGroupPermissionsToCreate,+ if (data.length > 0) {+ await prisma.viewerGroupAccessControls.createMany({+ data,skipDuplicates: true,});}+ return;+ }- if (permissionGroupPermissionsToCreate.length > 0) {- await tx.permissionGroupAccessControls.createMany({- data: permissionGroupPermissionsToCreate,- skipDuplicates: true,- });- }+ const permissionGroups = await prisma.permissionGroup.findMany({+ where: { dataroomId },+ select: { id: true },});+ if (permissionGroups.length === 0) return;++ const data = permissionGroups.flatMap((group) =>+ dataroomDocuments.map((doc) => ({+ groupId: group.id,+ itemId: doc.id,+ itemType: ItemType.DATAROOM_DOCUMENT,+ canView: true,+ canDownload: false,+ canDownloadOriginal: false,+ })),+ );++ if (data.length > 0) {+ await prisma.permissionGroupAccessControls.createMany({+ data,+ skipDuplicates: true,+ });+ }}async function inheritFromParentFolder(@@ -262,8 +294,8 @@ async function inheritFromParentFolder(folderId: string | null;}[],folderPath: string,+ target: GroupTarget,) {- // Get parent folder permissions and apply them to new documentsconst pathSegments = folderPath.split("/").filter(Boolean);const parentPath = "/" + pathSegments.slice(0, -1).join("/");@@ -275,78 +307,72 @@ async function inheritFromParentFolder(});if (!parentFolder) {- // If no parent folder found, apply root level permissions- await applyRootLevelPermissions(dataroomId, dataroomDocuments);+ await applyRootLevelPermissions(dataroomId, dataroomDocuments, target);return;}- // Get existing permissions for the parent folder- const [parentViewerPermissions, parentPermissionGroupPermissions] =- await Promise.all([- prisma.viewerGroupAccessControls.findMany({+ if (target === "VIEWER_GROUP") {+ const parentViewerPermissions =+ await prisma.viewerGroupAccessControls.findMany({where: {itemId: parentFolder.id,itemType: ItemType.DATAROOM_FOLDER,},select: { groupId: true, canView: true, canDownload: true },- }),- prisma.permissionGroupAccessControls.findMany({- where: {- itemId: parentFolder.id,- itemType: ItemType.DATAROOM_FOLDER,- },- select: {- groupId: true,- canView: true,- canDownload: true,- canDownloadOriginal: true,- },- }),- ]);-- // Apply parent permissions to documents- await prisma.$transaction(async (tx) => {- // Create permissions based on parent folder permissions- const viewerGroupPermissionsToCreate: any[] = [];- const permissionGroupPermissionsToCreate: any[] = [];-- parentViewerPermissions.forEach((parentPerm) => {- dataroomDocuments.forEach((doc) => {- viewerGroupPermissionsToCreate.push({- groupId: parentPerm.groupId,- itemId: doc.id,- itemType: ItemType.DATAROOM_DOCUMENT,- canView: parentPerm.canView,- canDownload: parentPerm.canDownload,- });});- });- parentPermissionGroupPermissions.forEach((parentPerm) => {- dataroomDocuments.forEach((doc) => {- permissionGroupPermissionsToCreate.push({- groupId: parentPerm.groupId,- itemId: doc.id,- itemType: ItemType.DATAROOM_DOCUMENT,- canView: parentPerm.canView,- canDownload: parentPerm.canDownload,- canDownloadOriginal: parentPerm.canDownloadOriginal,- });- });- });+ if (parentViewerPermissions.length === 0) return;- if (viewerGroupPermissionsToCreate.length > 0) {- await tx.viewerGroupAccessControls.createMany({- data: viewerGroupPermissionsToCreate,- skipDuplicates: true,- });- }+ const data = parentViewerPermissions.flatMap((parentPerm) =>+ dataroomDocuments.map((doc) => ({+ groupId: parentPerm.groupId,+ itemId: doc.id,+ itemType: ItemType.DATAROOM_DOCUMENT,+ canView: parentPerm.canView,+ canDownload: parentPerm.canDownload,+ })),+ );- if (permissionGroupPermissionsToCreate.length > 0) {- await tx.permissionGroupAccessControls.createMany({- data: permissionGroupPermissionsToCreate,+ if (data.length > 0) {+ await prisma.viewerGroupAccessControls.createMany({+ data,skipDuplicates: true,});}- });+ return;+ }++ const parentPermissionGroupPermissions =+ await prisma.permissionGroupAccessControls.findMany({+ where: {+ itemId: parentFolder.id,+ itemType: ItemType.DATAROOM_FOLDER,+ },+ select: {+ groupId: true,+ canView: true,+ canDownload: true,+ canDownloadOriginal: true,+ },+ });++ if (parentPermissionGroupPermissions.length === 0) return;++ const data = parentPermissionGroupPermissions.flatMap((parentPerm) =>+ dataroomDocuments.map((doc) => ({+ groupId: parentPerm.groupId,+ itemId: doc.id,+ itemType: ItemType.DATAROOM_DOCUMENT,+ canView: parentPerm.canView,+ canDownload: parentPerm.canDownload,+ canDownloadOriginal: parentPerm.canDownloadOriginal,+ })),+ );++ if (data.length > 0) {+ await prisma.permissionGroupAccessControls.createMany({+ data,+ skipDuplicates: true,+ });+ }}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/folders/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/folders/index.tsindex a7612396..2feeaaa8 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/folders/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/folders/index.ts@@ -31,6 +31,7 @@ async function applyDefaultFolderPermissions(where: { id: dataroomId },select: {defaultPermissionStrategy: true,+ defaultGroupPermissionStrategy: true,teamId: true,},}),@@ -51,162 +52,147 @@ async function applyDefaultFolderPermissions(if (!dataroom) return;- if (+ // Resolve parent folder once if any side wants to inherit. We can't bail+ // out early for both sides anymore because the group strategy and the+ // link strategy can disagree.+ const groupInherits =+ dataroom.defaultGroupPermissionStrategy ===+ DefaultPermissionStrategy.INHERIT_FROM_PARENT;+ const linkInherits =dataroom.defaultPermissionStrategy ===- DefaultPermissionStrategy.INHERIT_FROM_PARENT &&- folderPath- ) {- // If we have a folder path, inherit from parent folder- await inheritFolderPermissionsFromParent(dataroomId, folderId, folderPath);- return;- }-- // Fallback to default behavior (for root folders or non-inherit strategies)- const allPermissionGroupData: {- groupId: string;- itemId: string;- itemType: ItemType;- canView: boolean;- canDownload: boolean;- canDownloadOriginal: boolean;- }[] = [];-- if (permissionGroups.length > 0) {- if (- dataroom.defaultPermissionStrategy ===- DefaultPermissionStrategy.INHERIT_FROM_PARENT- ) {- permissionGroups.forEach((group) => {- allPermissionGroupData.push({- groupId: group.id,- itemId: folderId,- itemType: ItemType.DATAROOM_FOLDER,- canView: true, // Root folders get view permissions by default- canDownload: false,- canDownloadOriginal: false,- });+ DefaultPermissionStrategy.INHERIT_FROM_PARENT;++ let parentFolderId: string | null = null;+ if ((groupInherits || linkInherits) && folderPath) {+ const pathSegments = folderPath.split("/").filter(Boolean);+ const parentPath = "/" + pathSegments.slice(0, -1).join("/");+ if (parentPath !== "/") {+ const parent = await prisma.dataroomFolder.findUnique({+ where: { dataroomId_path: { dataroomId, path: parentPath } },+ select: { id: true },});+ parentFolderId = parent?.id ?? null;}- // For other strategies (ASK_EVERY_TIME, HIDDEN_BY_DEFAULT), don't auto-create permissions}- const viewerGroupData = viewerGroups.map((group) => ({- groupId: group.id,- itemId: folderId,- itemType: ItemType.DATAROOM_FOLDER,- canView:- dataroom.defaultPermissionStrategy ===- DefaultPermissionStrategy.INHERIT_FROM_PARENT,- canDownload: false,- }));-await Promise.all([- viewerGroupData.length > 0 &&- dataroom.defaultPermissionStrategy ===- DefaultPermissionStrategy.INHERIT_FROM_PARENT &&- prisma.viewerGroupAccessControls.createMany({- data: viewerGroupData,- skipDuplicates: true,- }),- allPermissionGroupData.length > 0 &&- prisma.permissionGroupAccessControls.createMany({- data: allPermissionGroupData,- skipDuplicates: true,- }),+ applyForViewerGroups({+ dataroomId,+ folderId,+ viewerGroups,+ strategy: dataroom.defaultGroupPermissionStrategy,+ parentFolderId,+ }),+ applyForPermissionGroups({+ dataroomId,+ folderId,+ permissionGroups,+ strategy: dataroom.defaultPermissionStrategy,+ parentFolderId,+ }),]);}-async function inheritFolderPermissionsFromParent(- dataroomId: string,- folderId: string,- folderPath: string,-) {- // Get parent folder path- const pathSegments = folderPath.split("/").filter(Boolean);- const parentPath = "/" + pathSegments.slice(0, -1).join("/");-- // If this is a root folder, apply default permissions- if (parentPath === "/") {- await applyDefaultFolderPermissions(dataroomId, folderId);- return;- }+async function applyForViewerGroups(opts: {+ dataroomId: string;+ folderId: string;+ viewerGroups: { id: string }[];+ strategy: DefaultPermissionStrategy;+ parentFolderId: string | null;+}) {+ const { folderId, viewerGroups, strategy, parentFolderId } = opts;++ if (strategy !== DefaultPermissionStrategy.INHERIT_FROM_PARENT) return;+ if (viewerGroups.length === 0) return;++ if (parentFolderId) {+ const parentPerms = await prisma.viewerGroupAccessControls.findMany({+ where: {+ itemId: parentFolderId,+ itemType: ItemType.DATAROOM_FOLDER,+ },+ select: { groupId: true, canView: true, canDownload: true },+ });- const parentFolder = await prisma.dataroomFolder.findUnique({- where: {- dataroomId_path: { dataroomId, path: parentPath },- },- select: { id: true },- });+ if (parentPerms.length === 0) return;- if (!parentFolder) {- // If no parent folder found, apply default permissions- await applyDefaultFolderPermissions(dataroomId, folderId);+ await prisma.viewerGroupAccessControls.createMany({+ data: parentPerms.map((p) => ({+ groupId: p.groupId,+ itemId: folderId,+ itemType: ItemType.DATAROOM_FOLDER,+ canView: p.canView,+ canDownload: p.canDownload,+ })),+ skipDuplicates: true,+ });return;}- // Get existing permissions for the parent folder- const [parentViewerPermissions, parentPermissionGroupPermissions] =- await Promise.all([- prisma.viewerGroupAccessControls.findMany({- where: {- itemId: parentFolder.id,- itemType: ItemType.DATAROOM_FOLDER,- },- select: { groupId: true, canView: true, canDownload: true },- }),- prisma.permissionGroupAccessControls.findMany({- where: {- itemId: parentFolder.id,- itemType: ItemType.DATAROOM_FOLDER,- },- select: {- groupId: true,- canView: true,- canDownload: true,- canDownloadOriginal: true,- },- }),- ]);-- // Apply parent permissions to the new folder- await prisma.$transaction(async (tx) => {- const viewerGroupPermissionsToCreate: any[] = [];- const permissionGroupPermissionsToCreate: any[] = [];+ await prisma.viewerGroupAccessControls.createMany({+ data: viewerGroups.map((group) => ({+ groupId: group.id,+ itemId: folderId,+ itemType: ItemType.DATAROOM_FOLDER,+ canView: true,+ canDownload: false,+ })),+ skipDuplicates: true,+ });+}- parentViewerPermissions.forEach((parentPerm) => {- viewerGroupPermissionsToCreate.push({- groupId: parentPerm.groupId,- itemId: folderId,+async function applyForPermissionGroups(opts: {+ dataroomId: string;+ folderId: string;+ permissionGroups: { id: string }[];+ strategy: DefaultPermissionStrategy;+ parentFolderId: string | null;+}) {+ const { folderId, permissionGroups, strategy, parentFolderId } = opts;++ if (strategy !== DefaultPermissionStrategy.INHERIT_FROM_PARENT) return;+ if (permissionGroups.length === 0) return;++ if (parentFolderId) {+ const parentPerms = await prisma.permissionGroupAccessControls.findMany({+ where: {+ itemId: parentFolderId,itemType: ItemType.DATAROOM_FOLDER,- canView: parentPerm.canView,- canDownload: parentPerm.canDownload,- });+ },+ select: {+ groupId: true,+ canView: true,+ canDownload: true,+ canDownloadOriginal: true,+ },});- parentPermissionGroupPermissions.forEach((parentPerm) => {- permissionGroupPermissionsToCreate.push({- groupId: parentPerm.groupId,+ if (parentPerms.length === 0) return;++ await prisma.permissionGroupAccessControls.createMany({+ data: parentPerms.map((p) => ({+ groupId: p.groupId,itemId: folderId,itemType: ItemType.DATAROOM_FOLDER,- canView: parentPerm.canView,- canDownload: parentPerm.canDownload,- canDownloadOriginal: parentPerm.canDownloadOriginal,- });+ canView: p.canView,+ canDownload: p.canDownload,+ canDownloadOriginal: p.canDownloadOriginal,+ })),+ skipDuplicates: true,});+ return;+ }- if (viewerGroupPermissionsToCreate.length > 0) {- await tx.viewerGroupAccessControls.createMany({- data: viewerGroupPermissionsToCreate,- skipDuplicates: true,- });- }-- if (permissionGroupPermissionsToCreate.length > 0) {- await tx.permissionGroupAccessControls.createMany({- data: permissionGroupPermissionsToCreate,- skipDuplicates: true,- });- }+ await prisma.permissionGroupAccessControls.createMany({+ data: permissionGroups.map((group) => ({+ groupId: group.id,+ itemId: folderId,+ itemType: ItemType.DATAROOM_FOLDER,+ canView: true,+ canDownload: false,+ canDownloadOriginal: false,+ })),+ skipDuplicates: true,});}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/index.tsindex 4c875bd6..eed778e7 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/groups/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/index.ts@@ -26,6 +26,7 @@ export default async function handle(id: string;};const documentId = req.query?.documentId as string;+ const folderId = req.query?.folderId as string;const userId = (session.user as CustomUser).id;try {@@ -59,6 +60,14 @@ export default async function handle(return res.status(404).end("Dataroom not found");}+ // When the caller scopes the query to a specific item we return the+ // matching access controls so the UI can render existing toggle state.+ const accessControlFilter = documentId+ ? { itemId: documentId, itemType: ItemType.DATAROOM_DOCUMENT }+ : folderId+ ? { itemId: folderId, itemType: ItemType.DATAROOM_FOLDER }+ : null;+// Then, get viewer groups with optimized separate queriesconst viewerGroups = await prisma.viewerGroup.findMany({where: {@@ -68,13 +77,10 @@ export default async function handle(createdAt: "desc",},include: {- ...(documentId+ ...(accessControlFilter? {accessControls: {- where: {- itemId: documentId,- itemType: ItemType.DATAROOM_DOCUMENT,- },+ where: accessControlFilter,select: {id: true,canView: true,diff --git a/pages/api/teams/[teamId]/datarooms/[id]/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/index.tsindex a601af85..637efa19 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/index.ts@@ -120,6 +120,7 @@ export default async function handle(enableChangeNotifications,enableVisitorUploadChangeNotifications,defaultPermissionStrategy,+ defaultGroupPermissionStrategy,allowBulkDownload,showLastUpdated,tags,@@ -132,6 +133,7 @@ export default async function handle(enableChangeNotifications?: boolean;enableVisitorUploadChangeNotifications?: boolean;defaultPermissionStrategy?: DefaultPermissionStrategy;+ defaultGroupPermissionStrategy?: DefaultPermissionStrategy;allowBulkDownload?: boolean;showLastUpdated?: boolean;tags?: string[];@@ -180,6 +182,9 @@ export default async function handle(enableVisitorUploadChangeNotifications,}),...(defaultPermissionStrategy && { defaultPermissionStrategy }),+ ...(defaultGroupPermissionStrategy && {+ defaultGroupPermissionStrategy,+ }),...(typeof allowBulkDownload === "boolean" && {allowBulkDownload,}),diff --git a/pages/datarooms/[id]/settings/file-permissions.tsx b/pages/datarooms/[id]/settings/file-permissions.tsxindex 129df6d8..0219b217 100644--- a/pages/datarooms/[id]/settings/file-permissions.tsx+++ b/pages/datarooms/[id]/settings/file-permissions.tsx@@ -33,9 +33,7 @@ export default function PermissionsSettings() {</p></div>- <div className="grid gap-6">- <PermissionSettings dataroomId={dataroom.id} />- </div>+ <PermissionSettings dataroomId={dataroom.id} /></main></AppLayout>);diff --git a/prisma/migrations/20260511180000_add_default_group_permission_strategy/migration.sql b/prisma/migrations/20260511180000_add_default_group_permission_strategy/migration.sqlnew file mode 100644index 00000000..fec3eeb5--- /dev/null+++ b/prisma/migrations/20260511180000_add_default_group_permission_strategy/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "Dataroom" ADD COLUMN "defaultGroupPermissionStrategy" "DefaultPermissionStrategy" NOT NULL DEFAULT 'INHERIT_FROM_PARENT';\ No newline at end of filediff --git a/prisma/schema/dataroom.prisma b/prisma/schema/dataroom.prismaindex 0f7d7132..3076ac02 100644--- a/prisma/schema/dataroom.prisma+++ b/prisma/schema/dataroom.prisma@@ -38,9 +38,16 @@ model Dataroom {enableChangeNotifications Boolean @default(false)enableVisitorUploadChangeNotifications Boolean @default(false)- // unified permission strategy+ // Default strategy applied to permission groups (link-level file permissions)+ // when new documents/folders are added to this dataroom.defaultPermissionStrategy DefaultPermissionStrategy @default(INHERIT_FROM_PARENT)+ // Default strategy applied to viewer groups (group file permissions) when+ // new documents/folders are added. Kept separate from+ // `defaultPermissionStrategy` so admins can have, for example, links default+ // to inheriting permissions while groups default to hidden.+ defaultGroupPermissionStrategy DefaultPermissionStrategy @default(INHERIT_FROM_PARENT)+// bulk download settingallowBulkDownload Boolean @default(true) // Allow bulk download of entire dataroom