Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: update and improve group permissions
Marc Seitzcf0ad5961d1e
diff --git a/components/datarooms/groups/group-permissions.tsx b/components/datarooms/groups/group-permissions.tsxindex a3c487cc..e7bd9de0 100644--- a/components/datarooms/groups/group-permissions.tsx+++ b/components/datarooms/groups/group-permissions.tsx@@ -24,6 +24,15 @@ import {} from "lucide-react";import { toast } from "sonner";+import {+ VIRTUAL_ROOT_ID,+ aggregateFolderPermissions,+ collectChangesForItem,+ collectChangesForRoot,+ findItemAndParents,+ resolveToggleIntent,+ type PermissionChanges,+} from "@/lib/dataroom/permissions-tree";import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";import { useDataroomFoldersTree } from "@/lib/swr/use-dataroom";import { cn } from "@/lib/utils";@@ -54,7 +63,7 @@ const PermissionItemName = ({ item }: { item: FileOrFolder }) => {isDataroomIndexEnabled,);- const isRoot = item.id === "__dataroom_root__";+ const isRoot = item.id === VIRTUAL_ROOT_ID;return (<div className="flex items-center text-foreground">@@ -88,10 +97,7 @@ type FileOrFolder = {documentId?: string;};-type ItemPermission = Record<- string,- { view: boolean; download: boolean; itemType: ItemType }->;+type ItemPermission = PermissionChanges;type ColumnExtra = {updatePermissions: (id: string, newPermissions: string[]) => void;@@ -237,40 +243,25 @@ const buildTree = (const folderPermissions = getPermissions(folder.id);- // Calculate view and partialView for folders- let viewStatus = folderPermissions.view;- let partialView = false;- let downloadStatus = folderPermissions.download;- let partialDownload = false;-- if (allSubItems.length > 0) {- const viewableItems = allSubItems.filter(- (item) => item.permissions.view,- );- const downloadableItems = allSubItems.filter(- (item) => item.permissions.download,- );-- viewStatus = viewableItems.length > 0;- partialView =- viewableItems.length > 0 && viewableItems.length < allSubItems.length;- downloadStatus = downloadableItems.length > 0;- partialDownload =- downloadableItems.length > 0 &&- downloadableItems.length < allSubItems.length;- }+ // Aggregate from direct children so the partial (indeterminate) state+ // propagates up the tree — a folder whose only-hidden descendant is+ // several levels deep must still render as partial. Empty folders fall+ // back to their own persisted permission row.+ const aggregated = aggregateFolderPermissions(+ allSubItems.map((sub) => sub.permissions),+ ) ?? {+ view: folderPermissions.view,+ download: folderPermissions.download,+ partialView: false,+ partialDownload: false,+ };result.push({id: folder.id,name: folder.name,hierarchicalIndex: folder.hierarchicalIndex,subItems: allSubItems,- permissions: {- view: viewStatus,- download: downloadStatus,- partialView,- partialDownload,- },+ permissions: aggregated,itemType: ItemType.DATAROOM_FOLDER,});});@@ -378,346 +369,186 @@ export default function ExpandableTable({const updatePermissions = useCallback((id: string, newPermissions: string[]) => {- const isRoot = id === "__dataroom_root__";-- const findItemAndParents = (- items: FileOrFolder[],- targetId: string,- parents: FileOrFolder[] = [],- ): { item: FileOrFolder; parents: FileOrFolder[] } | null => {- for (const item of items) {- if (item.id === targetId) {- return { item, parents };- }- if (item.subItems) {- const result = findItemAndParents(item.subItems, targetId, [- ...parents,- item,- ]);- if (result) return result;- }- }- return null;- };+ const isRoot = id === VIRTUAL_ROOT_ID;- const result = findItemAndParents(dataRef.current, id);- if (!result) return;-- const { item, parents } = result;-- const updatedPermissions = {+ const rawPermissions = {view: newPermissions.includes("view"),download: newPermissions.includes("download"),};- // Enforce invariants:- // - download requires view (you can't download what you can't see)- // - turning view off implies turning download off- if (!updatedPermissions.view) {- updatedPermissions.download = false;- } else if (updatedPermissions.download && !updatedPermissions.view) {- updatedPermissions.view = true;+ // Resolve user intent against the previous state so clicking the+ // download icon on a not-yet-visible item also flips view on (instead+ // of being silently dropped by the "download requires view" rule).+ let foundResult: ReturnType<typeof findItemAndParents> = null;+ let previous: { view: boolean; download: boolean };+ if (isRoot) {+ const root = dataRef.current[0];+ if (!root) return;+ previous = {+ view: root.permissions.view,+ download: root.permissions.download,+ };+ } else {+ foundResult = findItemAndParents(dataRef.current, id);+ if (!foundResult) return;+ previous = {+ view: foundResult.item.permissions.view,+ download: foundResult.item.permissions.download,+ };}+ const resolved = resolveToggleIntent(previous, rawPermissions);+ const normalized = resolved.view+ ? resolved+ : { view: false, download: false };- // Handle root-level permissions (affects all items)if (isRoot) {setData((prevData) => {const updateAllItems = (items: FileOrFolder[]): FileOrFolder[] => {- return items.map((currentItem) => {- if (currentItem.id === "__dataroom_root__") {- return {- ...currentItem,- permissions: {- view: updatedPermissions.view,- download: updatedPermissions.download,- partialView: false,- partialDownload: false,- },- subItems: currentItem.subItems- ? updateAllItems(currentItem.subItems)- : undefined,- };- }-- const updatedItem = {- ...currentItem,- permissions: {- view: updatedPermissions.view,- download: updatedPermissions.download,- partialView: false,- partialDownload: false,- },- subItems: currentItem.subItems- ? updateAllItems(currentItem.subItems)- : undefined,- };-- return updatedItem;- });+ return items.map((currentItem) => ({+ ...currentItem,+ permissions: {+ view: normalized.view,+ download: normalized.download,+ partialView: false,+ partialDownload: false,+ },+ subItems: currentItem.subItems+ ? updateAllItems(currentItem.subItems)+ : undefined,+ }));};return updateAllItems(prevData);});- // Collect changes for all items- const collectAllChanges = (items: FileOrFolder[]): ItemPermission => {- let changes: ItemPermission = {};-- const processItems = (items: FileOrFolder[]) => {- items.forEach((item) => {- // Don't save the virtual __dataroom_root__ item to database- if (item.id !== "__dataroom_root__") {- changes[item.id] = {- view: updatedPermissions.view,- download: updatedPermissions.download,- itemType: item.itemType,- };- }-- if (item.subItems) {- processItems(item.subItems);- }- });- };-- processItems(items);- return changes;- };-- const rootChanges = collectAllChanges(dataRef.current);- setPendingChanges((prev) => ({- ...prev,- ...rootChanges,- }));-+ const rootChanges = collectChangesForRoot(dataRef.current, normalized);+ setPendingChanges((prev) => ({ ...prev, ...rootChanges }));return;}- setData((prevData) => {- const updateItemInTree = (items: FileOrFolder[]): FileOrFolder[] => {- return items.map((currentItem) => {- if (currentItem.id === id) {- const updatedItem = {- ...currentItem,- permissions: {- view: updatedPermissions.view,- download: updatedPermissions.download,- partialView: false,- partialDownload: false,- },- };-- // If it's a folder, update all subitems- if (updatedItem.itemType === ItemType.DATAROOM_FOLDER) {- updatedItem.subItems = updateSubItems(- updatedItem.subItems || [],- updatedPermissions.view,- updatedPermissions.download,- );- }-- return updatedItem;- }-- // if the current item is a parent of the updated item, update the parent's permissions- if (parents.some((parent) => parent.id === currentItem.id)) {- const updatedSubItems = currentItem.subItems- ? updateItemInTree(currentItem.subItems)- : [];- return updateParentPermissions(currentItem, updatedSubItems);- }-- // if the current item has subitems, update the subitems- if (currentItem.subItems) {- return {- ...currentItem,- subItems: updateItemInTree(currentItem.subItems),- };- }- return currentItem;- });- };+ const { item, parents } = foundResult!;+ setData((prevData) => {const updateSubItems = (items: FileOrFolder[],viewState: boolean,downloadState: boolean,): FileOrFolder[] => {- return items.map((item) => ({- ...item,+ return items.map((subItem) => ({+ ...subItem,permissions: {- ...item.permissions,+ ...subItem.permissions,view: viewState,partialView: false,partialDownload: false,download: downloadState,},- subItems: item.subItems- ? updateSubItems(item.subItems, viewState, downloadState)+ subItems: subItem.subItems+ ? updateSubItems(subItem.subItems, viewState, downloadState): undefined,}));};- const updateParentPermissions = (+ const recalculateParentPermissions = (parent: FileOrFolder,subItems: FileOrFolder[],): FileOrFolder => {- const isParentRoot = parent.id === "__dataroom_root__";-- // For root folder, calculate based on all descendants- const calculatePermissions = (items: FileOrFolder[]) => {- const flattenItems = (items: FileOrFolder[]): FileOrFolder[] => {- return items.reduce((acc, item) => {- if (item.id !== "__dataroom_root__") {- acc.push(item);- }- if (item.subItems) {- acc.push(...flattenItems(item.subItems));- }+ const isParentRoot = parent.id === VIRTUAL_ROOT_ID;++ if (isParentRoot) {+ const flattenItems = (items: FileOrFolder[]): FileOrFolder[] =>+ items.reduce((acc, current) => {+ if (current.id !== VIRTUAL_ROOT_ID) acc.push(current);+ if (current.subItems) acc.push(...flattenItems(current.subItems));return acc;}, [] as FileOrFolder[]);- };- const allItems = flattenItems(items);- const viewableItems = allItems.filter(- (item) => item.permissions.view,- );+ const allItems = flattenItems(subItems);+ const viewableItems = allItems.filter((i) => i.permissions.view);const downloadableItems = allItems.filter(- (item) => item.permissions.download,+ (i) => i.permissions.download,);-- return {- view: viewableItems.length > 0,- partialView:- viewableItems.length > 0 &&- viewableItems.length < allItems.length,- download: downloadableItems.length > 0,- partialDownload:- downloadableItems.length > 0 &&- downloadableItems.length < allItems.length,- };- };-- if (isParentRoot) {- const rootPermissions = calculatePermissions(subItems);return {...parent,- permissions: rootPermissions,+ permissions: {+ view: viewableItems.length > 0,+ partialView:+ viewableItems.length > 0 &&+ viewableItems.length < allItems.length,+ download: downloadableItems.length > 0,+ partialDownload:+ downloadableItems.length > 0 &&+ downloadableItems.length < allItems.length,+ },subItems,};}- // For regular folders- const someSubItemViewable = subItems.some(- (subItem) => subItem.permissions.view,- );- const allSubItemsViewable = subItems.every(- (subItem) => subItem.permissions.view,- );- const someSubItemDownloadable = subItems.some(- (subItem) => subItem.permissions.download,- );- const allSubItemsDownloadable = subItems.every(- (subItem) => subItem.permissions.download,- );+ // Same aggregation rule as `buildTree` — propagate `partialView`+ // and `partialDownload` so an ancestor stays partial when any+ // descendant (not just an immediate child) is hidden.+ const aggregated = aggregateFolderPermissions(+ subItems.map((sub) => sub.permissions),+ ) ?? {+ view: parent.permissions.view,+ download: parent.permissions.download,+ partialView: false,+ partialDownload: false,+ };return {...parent,- permissions: {- view: someSubItemViewable,- partialView: someSubItemViewable && !allSubItemsViewable,- download: someSubItemDownloadable,- partialDownload:- someSubItemDownloadable && !allSubItemsDownloadable,- },+ permissions: aggregated,subItems,};};- return updateItemInTree(prevData);- });+ const updateItemInTree = (items: FileOrFolder[]): FileOrFolder[] => {+ return items.map((currentItem) => {+ if (currentItem.id === id) {+ const updatedItem = {+ ...currentItem,+ permissions: {+ view: normalized.view,+ download: normalized.download,+ partialView: false,+ partialDownload: false,+ },+ };- // Collect changes for database update- const collectChanges = (- item: FileOrFolder,- parents: FileOrFolder[],- ): ItemPermission => {- let changes: ItemPermission = {};-- // Don't save the virtual __dataroom_root__ item to database- if (item.id !== "__dataroom_root__") {- changes[item.id] = {- view: updatedPermissions.view,- download: updatedPermissions.download,- itemType: item.itemType,- };- }+ if (updatedItem.itemType === ItemType.DATAROOM_FOLDER) {+ updatedItem.subItems = updateSubItems(+ updatedItem.subItems || [],+ normalized.view,+ normalized.download,+ );+ }- // Collect changes for all subitems- const collectSubItemChanges = (- subItems: FileOrFolder[] | undefined,- ) => {- if (!subItems) return;- subItems.forEach((subItem) => {- // Don't save the virtual __dataroom_root__ item to database- if (subItem.id !== "__dataroom_root__") {- changes[subItem.id] = {- view: updatedPermissions.view,- download: updatedPermissions.download,- itemType: subItem.itemType,- };+ return updatedItem;}- collectSubItemChanges(subItem.subItems);- });- };- collectSubItemChanges(item.subItems);-- // Ensure all parent folders are viewable if the item is being set to viewable- if (updatedPermissions.view || updatedPermissions.download) {- parents.forEach((parent) => {- // Don't save the virtual __dataroom_root__ item to database- if (parent.id !== "__dataroom_root__") {- changes[parent.id] = {- view: true,- download: updatedPermissions.download- ? true- : parent.permissions.download,- itemType: parent.itemType,- };+ if (parents.some((parent) => parent.id === currentItem.id)) {+ const updatedSubItems = currentItem.subItems+ ? updateItemInTree(currentItem.subItems)+ : [];+ return recalculateParentPermissions(currentItem, updatedSubItems);}- });- } else {- // If turning off view, recalculate parent permissions- [...parents].reverse().forEach((parent) => {- // Don't save the virtual __dataroom_root__ item to database- if (parent.id !== "__dataroom_root__") {- const otherChildren =- parent.subItems?.filter((subItem) => subItem.id !== item.id) ||- [];- const someSubItemViewable = otherChildren.some(- (subItem) => subItem.permissions.view,- );- const someSubItemDownloadable = otherChildren.some(- (subItem) => subItem.permissions.download,- );-- changes[parent.id] = {- view: someSubItemViewable,- download: someSubItemDownloadable,- itemType: parent.itemType,++ if (currentItem.subItems) {+ return {+ ...currentItem,+ subItems: updateItemInTree(currentItem.subItems),};}+ return currentItem;});- }+ };- return changes;- };+ return updateItemInTree(prevData);+ });- setPendingChanges((prev) => ({- ...prev,- ...collectChanges(item, parents),- }));+ const changes = collectChangesForItem(item, parents, normalized);+ setPendingChanges((prev) => ({ ...prev, ...changes }));},[],);diff --git a/components/view/viewer/dataroom-viewer.tsx b/components/view/viewer/dataroom-viewer.tsxindex 9612c75f..5901f35d 100644--- a/components/view/viewer/dataroom-viewer.tsx+++ b/components/view/viewer/dataroom-viewer.tsx@@ -204,18 +204,87 @@ export default function DataroomViewer({[folderId, folders],);+ // Index access controls by `itemId` once per change so the per-document+ // lookups below are O(1) instead of O(A). Without this, the descendant+ // walk and the per-render `mixedItems` build each do an N×M scan over+ // documents × accessControls, which becomes noticeable past a few+ // thousand items in the dataroom.+ const accessControlByItemId = useMemo(() => {+ const map = new Map<+ string,+ ViewerGroupAccessControls | PermissionGroupAccessControls+ >();+ for (const access of accessControls) {+ map.set(access.itemId, access);+ }+ return map;+ }, [accessControls]);+const allDocumentsCanDownload = useMemo(() => {if (!allowDownload) return false;if (!documents || documents.length === 0) return false;return documents.some((doc) => {if (doc.versions[0].type === "notion") return false;- const accessControl = accessControls.find(- (access) => access.itemId === doc.dataroomDocumentId,- );+ const accessControl = accessControlByItemId.get(doc.dataroomDocumentId);return accessControl?.canDownload ?? true;});- }, [documents, accessControls, allowDownload]);+ }, [documents, accessControlByItemId, allowDownload]);++ // For each folder, whether *any* descendant document is downloadable for+ // this viewer. The folder card's download menu is shown whenever this is+ // true, so a folder that's only "partially downloadable" (e.g. one nested+ // doc downloadable, others not) still surfaces the action — matching what+ // the bulk-download job actually produces (it permission-filters in+ // `lib/trigger/bulk-download.ts`).+ const folderHasDownloadableDescendant = useMemo(() => {+ const result = new Map<string, boolean>();++ // Resolve a single doc's downloadability against the viewer's access+ // controls. `canDownload` defaults to true when no explicit row exists,+ // matching the per-document logic elsewhere in this file.+ const isDocDownloadable = (doc: DataroomDocument): boolean => {+ if (doc.versions[0]?.type === "notion") return false;+ const accessControl = accessControlByItemId.get(doc.dataroomDocumentId);+ return accessControl?.canDownload ?? true;+ };++ const folderChildren = new Map<string, string[]>();+ const folderDocsMap = new Map<string, DataroomDocument[]>();++ folders.forEach((folder) => {+ const parentId = folder.parentId || "root";+ if (!folderChildren.has(parentId)) folderChildren.set(parentId, []);+ folderChildren.get(parentId)!.push(folder.id);+ });++ documents.forEach((doc) => {+ const fid = doc.folderId || "root";+ if (!folderDocsMap.has(fid)) folderDocsMap.set(fid, []);+ folderDocsMap.get(fid)!.push(doc);+ });++ const compute = (folderId: string): boolean => {+ const cached = result.get(folderId);+ if (cached !== undefined) return cached;++ const docs = folderDocsMap.get(folderId) || [];+ if (docs.some(isDocDownloadable)) {+ result.set(folderId, true);+ return true;+ }++ const children = folderChildren.get(folderId) || [];+ const hasDownloadableChild = children.some(compute);++ result.set(folderId, hasDownloadableChild);+ return hasDownloadableChild;+ };++ folders.forEach((folder) => compute(folder.id));++ return result;+ }, [folders, documents, accessControlByItemId]);// Efficiently calculate effective updatedAt for all folders in a single passconst folderEffectiveUpdatedAt = useMemo(() => {@@ -291,8 +360,8 @@ export default function DataroomViewer({return (documents || []).filter((doc) => doc.name.toLowerCase().includes(searchQuery)).map((doc) => {- const accessControl = accessControls.find(- (access) => access.itemId === doc.dataroomDocumentId,+ const accessControl = accessControlByItemId.get(+ doc.dataroomDocumentId,);return {@@ -310,39 +379,30 @@ export default function DataroomViewer({...(folders || []).filter((folder) => folder.parentId === folderId).map((folder) => {- const folderDocuments = documents.filter(- (doc) => doc.folderId === folder.id,- );-// Get pre-calculated effective updatedAtconst effectiveUpdatedAt =folderEffectiveUpdatedAt.get(folder.id) ||new Date(folder.updatedAt);- const allDocumentsCanDownload =- folderDocuments.length === 0 || // Allow download for empty folders- folderDocuments.every((doc) => {- const accessControl = accessControls.find(- (access) => access.itemId === doc.dataroomDocumentId,- );- return (- (accessControl?.canDownload ?? true) &&- doc.versions[0].type !== "notion"- );- });+ // Show the download action when any descendant doc is downloadable+ // — including the partial case where some are and some aren't, and+ // the deeply-nested case where the only downloadable doc lives+ // several levels below this folder.+ const hasDownloadableDescendant =+ folderHasDownloadableDescendant.get(folder.id) ?? false;return {...folder,updatedAt: effectiveUpdatedAt,itemType: "folder",- allowDownload: allowDownload && allDocumentsCanDownload,+ allowDownload: allowDownload && hasDownloadableDescendant,};}),...(documents || []).filter((doc) => doc.folderId === folderId).map((doc) => {- const accessControl = accessControls.find(- (access) => access.itemId === doc.dataroomDocumentId,+ const accessControl = accessControlByItemId.get(+ doc.dataroomDocumentId,);return {@@ -360,9 +420,10 @@ export default function DataroomViewer({folders,documents,folderId,- accessControls,+ accessControlByItemId,allowDownload,folderEffectiveUpdatedAt,+ folderHasDownloadableDescendant,searchQuery,]);diff --git a/lib/dataroom/permissions-sql.ts b/lib/dataroom/permissions-sql.tsnew file mode 100644index 00000000..b0db5c7d--- /dev/null+++ b/lib/dataroom/permissions-sql.ts@@ -0,0 +1,239 @@+import { ItemType, Prisma } from "@prisma/client";++/**+ * SQL builders for bulk-saving viewer-group permissions.+ *+ * Replaces the previous loop of per-row `prisma.viewerGroupAccessControls+ * .upsert(...)` calls inside `prisma.$transaction(async (tx) => …)`, which+ * needed thousands of round-trips on large datarooms and reliably timed out+ * Prisma's interactive-transaction window for big "Save changes" payloads.+ *+ * The handler combines three statements inside a single transaction:+ * 1. `buildBulkUpsertPermissionsSql` — single `INSERT … ON CONFLICT DO+ * UPDATE` for every entry in the user-supplied payload.+ * 2. `buildFindAncestorFolderIdsSql` — single recursive-CTE walk of+ * `DataroomFolder.parentId` returning the distinct ancestor folder ids+ * of every item the payload is making visible.+ * 3. `buildUpsertAncestorVisibilitySql` — single bulk upsert that forces+ * `canView=true` on those ancestor folders while preserving any+ * existing `canDownload`. This is the server-side safety net for+ * callers (e.g. the post-upload modal in+ * `set-unified-permissions-modal.tsx`) that submit only a single+ * document and don't compute parent chains client-side.+ *+ * `id` values are generated client-side as cuids — same convention as the+ * rest of the schema's `@id @default(cuid())` columns — and passed in as+ * normal bound parameters. We deliberately avoid `gen_random_uuid()::text`+ * here so every row in `ViewerGroupAccessControls` keeps a consistent id+ * format.+ *+ * All builders are pure functions over their inputs so we can assert their+ * shape in unit tests without spinning up Postgres.+ */++export type PermissionUpsertRow = {+ /** Pre-generated cuid (same format as `@id @default(cuid())`). */+ id: string;+ itemId: string;+ itemType: ItemType;+ canView: boolean;+ canDownload: boolean;+};++export type AncestorUpsertRow = {+ /** Pre-generated cuid for the new `ViewerGroupAccessControls` row. */+ id: string;+ folderId: string;+};++/**+ * Build the bulk upsert SQL for the user-supplied payload.+ *+ * Returns `null` when `rows` is empty so the caller can skip the round-trip.+ */+export function buildBulkUpsertPermissionsSql(+ groupId: string,+ rows: PermissionUpsertRow[],+): Prisma.Sql | null {+ if (rows.length === 0) return null;++ // We sort by itemId so the row-lock order is stable across concurrent+ // saves for the same group — same property the previous loop relied on.+ const sortedRows = [...rows].sort((a, b) =>+ a.itemId.localeCompare(b.itemId),+ );++ const valueRows = sortedRows.map(+ (row) =>+ Prisma.sql`(${row.id}, ${row.itemId}, ${row.itemType}::"ItemType", ${row.canView}, ${row.canDownload})`,+ );++ return Prisma.sql`+ INSERT INTO "ViewerGroupAccessControls" (+ "id",+ "groupId",+ "itemId",+ "itemType",+ "canView",+ "canDownload",+ "createdAt",+ "updatedAt"+ )+ SELECT+ v."id",+ ${groupId},+ v."itemId",+ v."itemType",+ v."canView",+ v."canDownload",+ NOW(),+ NOW()+ FROM (VALUES ${Prisma.join(valueRows)})+ AS v("id", "itemId", "itemType", "canView", "canDownload")+ ON CONFLICT ("groupId", "itemId") DO UPDATE SET+ "itemType" = EXCLUDED."itemType",+ "canView" = EXCLUDED."canView",+ "canDownload" = EXCLUDED."canDownload",+ "updatedAt" = NOW();+ `;+}++/**+ * Build a single recursive-CTE statement that returns the distinct ancestor+ * folder ids of every item in the payload that is being made visible.+ *+ * Returns `null` when there's nothing visible (no walk needed).+ *+ * Notes:+ * - Constrained to `dataroomId` so a malicious or buggy caller can't trick+ * us into walking folders in a different dataroom.+ * - Folder→parent walking starts from each visible folder *and* from each+ * visible document's `folderId`. Root-level documents have no folder, so+ * they're filtered out (correct: they have no ancestor to make visible).+ */+export function buildFindAncestorFolderIdsSql(+ dataroomId: string,+ visibleDocumentIds: string[],+ visibleFolderIds: string[],+): Prisma.Sql | null {+ if (visibleDocumentIds.length === 0 && visibleFolderIds.length === 0) {+ return null;+ }++ // Empty arrays don't bind cleanly through `= ANY($1::text[])` in every+ // driver path, so substitute a no-match empty array literal when the+ // input is empty.+ const folderArray =+ visibleFolderIds.length > 0+ ? Prisma.sql`ARRAY[${Prisma.join(visibleFolderIds)}]::text[]`+ : Prisma.sql`ARRAY[]::text[]`;+ const documentArray =+ visibleDocumentIds.length > 0+ ? Prisma.sql`ARRAY[${Prisma.join(visibleDocumentIds)}]::text[]`+ : Prisma.sql`ARRAY[]::text[]`;++ return Prisma.sql`+ WITH RECURSIVE+ starting_folders AS (+ SELECT df."id" AS folder_id+ FROM "DataroomFolder" df+ WHERE df."id" = ANY(${folderArray})+ AND df."dataroomId" = ${dataroomId}++ UNION++ SELECT dd."folderId" AS folder_id+ FROM "DataroomDocument" dd+ WHERE dd."id" = ANY(${documentArray})+ AND dd."dataroomId" = ${dataroomId}+ AND dd."folderId" IS NOT NULL+ ),+ ancestor_folders AS (+ SELECT folder_id FROM starting_folders++ UNION++ SELECT df."parentId" AS folder_id+ FROM ancestor_folders af+ JOIN "DataroomFolder" df ON df."id" = af.folder_id+ WHERE df."parentId" IS NOT NULL+ )+ SELECT DISTINCT folder_id+ FROM ancestor_folders+ WHERE folder_id IS NOT NULL;+ `;+}++/**+ * Bulk-upsert the ancestor folder rows produced by+ * `buildFindAncestorFolderIdsSql`. Forces `canView=true` and never touches+ * `canDownload` so we don't clobber an ancestor's existing download grant.+ *+ * The `WHERE existing.canView = FALSE` guard skips no-op writes when the+ * ancestor is already visible — typical case in steady state.+ */+export function buildUpsertAncestorVisibilitySql(+ groupId: string,+ ancestors: AncestorUpsertRow[],+): Prisma.Sql | null {+ if (ancestors.length === 0) return null;++ // Stable lock order to match the main bulk-upsert path.+ const sorted = [...ancestors].sort((a, b) =>+ a.folderId.localeCompare(b.folderId),+ );++ const valueRows = sorted.map(+ (row) => Prisma.sql`(${row.id}, ${row.folderId})`,+ );++ return Prisma.sql`+ INSERT INTO "ViewerGroupAccessControls" (+ "id",+ "groupId",+ "itemId",+ "itemType",+ "canView",+ "canDownload",+ "createdAt",+ "updatedAt"+ )+ SELECT+ v."id",+ ${groupId},+ v."folderId",+ 'DATAROOM_FOLDER'::"ItemType",+ TRUE,+ FALSE,+ NOW(),+ NOW()+ FROM (VALUES ${Prisma.join(valueRows)}) AS v("id", "folderId")+ ON CONFLICT ("groupId", "itemId") DO UPDATE SET+ "canView" = TRUE,+ "updatedAt" = NOW()+ WHERE "ViewerGroupAccessControls"."canView" = FALSE;+ `;+}++/**+ * Convenience: split the payload (whatever the client posted) into the two+ * id arrays the recursive CTE needs.+ */+export function extractVisibleItemIds(+ permissions: Record<+ string,+ { itemType: ItemType; view: boolean; download: boolean }+ >,+): { visibleDocumentIds: string[]; visibleFolderIds: string[] } {+ const visibleDocumentIds: string[] = [];+ const visibleFolderIds: string[] = [];+ for (const [itemId, perm] of Object.entries(permissions)) {+ if (!perm.view) continue;+ if (perm.itemType === ItemType.DATAROOM_DOCUMENT) {+ visibleDocumentIds.push(itemId);+ } else if (perm.itemType === ItemType.DATAROOM_FOLDER) {+ visibleFolderIds.push(itemId);+ }+ }+ return { visibleDocumentIds, visibleFolderIds };+}diff --git a/lib/dataroom/permissions-tree.ts b/lib/dataroom/permissions-tree.tsnew file mode 100644index 00000000..4111c421--- /dev/null+++ b/lib/dataroom/permissions-tree.ts@@ -0,0 +1,345 @@+import { ItemType } from "@prisma/client";++/**+ * Pure helpers for computing dataroom permission diffs from the in-memory tree+ * shown in the group-permissions UI. Extracted from+ * `components/datarooms/groups/group-permissions.tsx` so the parent-cascade+ * behaviour can be unit tested without React.+ *+ * The server (`/api/.../permissions`) still re-derives ancestors via a+ * recursive CTE as a safety net, but these helpers are what produce the+ * payload from a user toggle and what backs the optimistic UI.+ */++export const VIRTUAL_ROOT_ID = "__dataroom_root__";++export type TreeNodePermissions = {+ view: boolean;+ download: boolean;+};++export type TreeNode = {+ id: string;+ itemType: ItemType;+ permissions: TreeNodePermissions;+ subItems?: TreeNode[];+};++export type PermissionChange = {+ view: boolean;+ download: boolean;+ itemType: ItemType;+};++export type PermissionChanges = Record<string, PermissionChange>;++/**+ * Enforce the "download requires view" invariant. Mirrors the behaviour the+ * UI relied on inline before extraction.+ */+export function normalizePermissions(input: {+ view: boolean;+ download: boolean;+}): TreeNodePermissions {+ if (!input.view) {+ return { view: false, download: false };+ }+ return { view: true, download: input.download };+}++export function findItemAndParents(+ items: TreeNode[],+ targetId: string,+ parents: TreeNode[] = [],+): { item: TreeNode; parents: TreeNode[] } | null {+ for (const item of items) {+ if (item.id === targetId) {+ return { item, parents };+ }+ if (item.subItems) {+ const result = findItemAndParents(item.subItems, targetId, [+ ...parents,+ item,+ ]);+ if (result) return result;+ }+ }+ return null;+}++/**+ * Build the change set produced when the user toggles permissions on a single+ * item (folder or document). Cascades:+ * - the item itself+ * - all descendants (set to the new permission)+ * - all ancestors:+ * - if turning view/download ON: ancestors are forced visible (download+ * only forced ON if the user explicitly turned download ON)+ * - if turning view OFF: ancestors are recomputed from their *remaining*+ * siblings (the toggled item is treated as if it already has the new+ * permission). View AND download both get recomputed from siblings.+ * - if turning download OFF while view stays on: ancestors keep their+ * view=true but their download is recomputed from remaining+ * siblings, so a folder whose only downloadable descendant just went+ * away no longer has a stale `canDownload=true` row.+ *+ * The virtual `__dataroom_root__` node is never written to the DB.+ */+export function collectChangesForItem(+ item: TreeNode,+ parents: TreeNode[],+ rawPermissions: { view: boolean; download: boolean },+): PermissionChanges {+ const updated = normalizePermissions(rawPermissions);+ const changes: PermissionChanges = {};++ if (item.id !== VIRTUAL_ROOT_ID) {+ changes[item.id] = {+ view: updated.view,+ download: updated.download,+ itemType: item.itemType,+ };+ }++ const cascadeDown = (subItems: TreeNode[] | undefined) => {+ if (!subItems) return;+ for (const subItem of subItems) {+ if (subItem.id !== VIRTUAL_ROOT_ID) {+ changes[subItem.id] = {+ view: updated.view,+ download: updated.download,+ itemType: subItem.itemType,+ };+ }+ cascadeDown(subItem.subItems);+ }+ };+ cascadeDown(item.subItems);++ // Diff against the pre-toggle snapshot (the tree we were handed reflects+ // state *before* the user's click) so we can tell apart the three+ // ancestor-update modes below.+ const previousDownload = item.permissions.download;+ const downloadTurnedOff =+ previousDownload && !updated.download && updated.view;++ if (!updated.view) {+ // Turning view (and therefore download) off. Walk parents bottom-up and+ // recompute view+download from the remaining siblings.+ //+ // We track ancestors that have already flipped to view=false in this+ // pass so higher-level parents don't *still* see them as viewable in the+ // pre-toggle snapshot — otherwise a chain like `f1 > f1a > doc1` where+ // doc1 is the only viewable item would correctly flip f1a to invisible+ // but leave f1 visible (because f1a still has view=true in the snapshot+ // we hold by reference).+ const flippedToInvisible = new Set<string>([item.id]);+ for (const parent of [...parents].reverse()) {+ if (parent.id === VIRTUAL_ROOT_ID) continue;+ const otherChildren =+ parent.subItems?.filter(+ (sub) => !flippedToInvisible.has(sub.id),+ ) ?? [];+ const someSubItemViewable = otherChildren.some(+ (sub) => sub.permissions.view,+ );+ const someSubItemDownloadable = otherChildren.some(+ (sub) => sub.permissions.download,+ );+ changes[parent.id] = {+ view: someSubItemViewable,+ download: someSubItemDownloadable,+ itemType: parent.itemType,+ };+ if (!someSubItemViewable) {+ flippedToInvisible.add(parent.id);+ }+ }+ } else if (downloadTurnedOff) {+ // View stays on, download was just turned off. Walk parents bottom-up+ // and recompute download from the remaining siblings — same shape as+ // the view-off branch but only for the download flag. Without this, a+ // folder whose *only* downloadable descendant just got turned off+ // would silently keep `canDownload=true` in the DB, even though the+ // optimistic UI correctly shows it as no-longer-downloadable.+ const flippedToNonDownloadable = new Set<string>([item.id]);+ for (const parent of [...parents].reverse()) {+ if (parent.id === VIRTUAL_ROOT_ID) continue;+ const otherChildren =+ parent.subItems?.filter(+ (sub) => !flippedToNonDownloadable.has(sub.id),+ ) ?? [];+ const someSubItemDownloadable = otherChildren.some(+ (sub) => sub.permissions.download,+ );+ changes[parent.id] = {+ // The toggled item kept view=true, so by the "download requires+ // view" invariant every ancestor must have view=true too. We don't+ // need to recompute view here.+ view: true,+ download: someSubItemDownloadable,+ itemType: parent.itemType,+ };+ if (!someSubItemDownloadable) {+ flippedToNonDownloadable.add(parent.id);+ }+ }+ } else {+ // Turning view and/or download ON (or a no-op toggle). Force ancestors+ // visible; bump their download to true only when the user explicitly+ // turned download on, otherwise preserve their existing download flag+ // so we don't clobber an ancestor's previously-granted download grant.+ for (const parent of parents) {+ if (parent.id === VIRTUAL_ROOT_ID) continue;+ changes[parent.id] = {+ view: true,+ download: updated.download ? true : parent.permissions.download,+ itemType: parent.itemType,+ };+ }+ }++ return changes;+}++/**+ * Build the change set for a "set permissions on the virtual root" toggle.+ * Every real item in the tree gets the new permission. The virtual root is+ * never written to the DB.+ */+export function collectChangesForRoot(+ treeRootedAtVirtualRoot: TreeNode[],+ rawPermissions: { view: boolean; download: boolean },+): PermissionChanges {+ const updated = normalizePermissions(rawPermissions);+ const changes: PermissionChanges = {};++ const walk = (items: TreeNode[]) => {+ for (const item of items) {+ if (item.id !== VIRTUAL_ROOT_ID) {+ changes[item.id] = {+ view: updated.view,+ download: updated.download,+ itemType: item.itemType,+ };+ }+ if (item.subItems) walk(item.subItems);+ }+ };+ walk(treeRootedAtVirtualRoot);++ return changes;+}++/**+ * Translate a fresh `(view, download)` pair coming out of the multi-select+ * ToggleGroup in the group-permissions UI into the user's actual intent,+ * using the previous state to disambiguate which button they pressed.+ *+ * The "download requires view" invariant goes in two directions:+ * - turning view OFF must also turn download OFF+ * - turning download ON must also turn view ON (otherwise clicking the+ * download icon on a hidden item is a no-op, which feels broken)+ *+ * Without comparing to the previous state we cannot tell a user *adding*+ * download from a user *removing* view: both can produce `["download"]`+ * from a multi-select toggle group.+ */+export function resolveToggleIntent(+ previous: { view: boolean; download: boolean },+ next: { view: boolean; download: boolean },+): { view: boolean; download: boolean } {+ const userTurnedViewOff = previous.view && !next.view;+ if (userTurnedViewOff) {+ return { view: false, download: false };+ }++ const userTurnedDownloadOn = !previous.download && next.download;+ if (userTurnedDownloadOn && !next.view) {+ return { view: true, download: true };+ }++ return next;+}++/**+ * Aggregate state for a folder row in the group-permissions UI: in addition+ * to the persisted `view`/`download` flags, the UI also renders an+ * "indeterminate" (gray) state when *some* but not *all* of the folder's+ * descendants are visible/downloadable.+ */+export type AggregatePermissions = {+ view: boolean;+ download: boolean;+ partialView: boolean;+ partialDownload: boolean;+};++/**+ * A child row's contribution to its parent folder's aggregate state. The+ * `partial*` flags are what let the indeterminate state propagate *up* the+ * tree: a folder is partial whenever any direct child is partial OR any+ * direct child is fully off, even if every direct child reports+ * `view=true` (because each of those children is itself partial).+ *+ * Without this, a folder like `Company Information` whose only-hidden item+ * is several levels deep would render as fully visible, because each of its+ * direct subfolders has `view=true` (they have *some* viewable descendant).+ */+export type AggregateChild = {+ view: boolean;+ download: boolean;+ partialView?: boolean;+ partialDownload?: boolean;+};++/**+ * Compute a folder's aggregate permission state from its direct children.+ * Returns `null` if there are no children (caller should fall back to the+ * folder's own persisted permissions).+ *+ * Rules:+ * - `view` is true iff at least one direct child contributes view=true.+ * - `partialView` is true iff `view` is true AND at least one direct child+ * is either view=false or itself partial. The same holds for download.+ */+export function aggregateFolderPermissions(+ children: AggregateChild[],+): AggregatePermissions | null {+ if (children.length === 0) return null;++ const someViewable = children.some((c) => c.view);+ const allViewable = children.every((c) => c.view);+ const someChildPartialView = children.some((c) => c.partialView === true);++ const someDownloadable = children.some((c) => c.download);+ const allDownloadable = children.every((c) => c.download);+ const someChildPartialDownload = children.some(+ (c) => c.partialDownload === true,+ );++ return {+ view: someViewable,+ partialView: someViewable && (!allViewable || someChildPartialView),+ download: someDownloadable,+ partialDownload:+ someDownloadable && (!allDownloadable || someChildPartialDownload),+ };+}++/**+ * Returns the ids of all real ancestor folders of `targetId` in `tree`,+ * skipping the virtual root. Used to assert (in tests) that+ * `collectChangesForItem` includes a complete ancestor chain when toggling+ * a permission on.+ */+export function ancestorFolderIdsOf(+ tree: TreeNode[],+ targetId: string,+): string[] {+ const found = findItemAndParents(tree, targetId);+ if (!found) return [];+ return found.parents+ .filter((p) => p.id !== VIRTUAL_ROOT_ID)+ .map((p) => p.id);+}diff --git a/package-lock.json b/package-lock.jsonindex e57a16bf..33466629 100644--- a/package-lock.json+++ b/package-lock.json@@ -89,6 +89,7 @@"class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",+ "cuid": "^3.0.0","date-fns": "^3.6.0","dub": "^0.71.7","embla-carousel-react": "^8.6.0",@@ -13631,6 +13632,13 @@"version": "3.2.3","license": "MIT"},+ "node_modules/cuid": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/cuid/-/cuid-3.0.0.tgz",+ "integrity": "sha512-WZYYkHdIDnaxdeP8Misq3Lah5vFjJwGuItJuV+tvMafosMzw0nF297T7mrm8IOWiPJkV6gc7sa8pzx27+w25Zg==",+ "deprecated": "Cuid and other k-sortable and non-cryptographic ids (Ulid, ObjectId, KSUID, all UUIDs) are all insecure. Use @paralleldrive/cuid2 instead.",+ "license": "MIT"+ },"node_modules/custom-error-instance": {"version": "2.1.1","license": "ISC"diff --git a/package.json b/package.jsonindex 1b73c8bc..880d7750 100644--- a/package.json+++ b/package.json@@ -101,6 +101,7 @@"class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",+ "cuid": "^3.0.0","date-fns": "^3.6.0","dub": "^0.71.7","embla-carousel-react": "^8.6.0",diff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/permissions.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/permissions.tsindex bc0f719c..92836f4c 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/permissions.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/permissions.ts@@ -2,124 +2,27 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { ItemType } from "@prisma/client";+import cuid from "cuid";import { getServerSession } from "next-auth/next";+import {+ buildBulkUpsertPermissionsSql,+ buildFindAncestorFolderIdsSql,+ buildUpsertAncestorVisibilitySql,+ extractVisibleItemIds,+ type AncestorUpsertRow,+ type PermissionUpsertRow,+} from "@/lib/dataroom/permissions-sql";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";-// Helper function to get parent folder IDs for a given document in a dataroom-async function getParentFolderIds(- dataroomId: string,- documentId: string,-): Promise<string[]> {- // Get the dataroom document to find which folder it's in- const dataroomDocument = await prisma.dataroomDocument.findUnique({- where: { id: documentId },- select: { folderId: true },- });-- if (!dataroomDocument?.folderId) {- return []; // Document is at root level- }-- // Get the folder and walk up the hierarchy- const parentFolders: string[] = [];- let currentFolderId: string | null = dataroomDocument.folderId;-- while (currentFolderId) {- parentFolders.push(currentFolderId);-- const folder: { parentId: string | null } | null =- await prisma.dataroomFolder.findUnique({- where: { id: currentFolderId },- select: { parentId: true },- });-- currentFolderId = folder?.parentId || null;- }-- return parentFolders;-}--// Helper function to ensure parent folders are visible when child documents are made visible-async function ensureParentFoldersVisible(- dataroomId: string,- groupId: string,- permissions: Record<- string,- { itemType: ItemType; view: boolean; download: boolean }- >,-): Promise<void> {- const foldersToMakeVisible = new Set<string>();-- // Find all documents that are being made visible- const visibleDocuments = Object.entries(permissions)- .filter(- ([_, perm]) => perm.itemType === ItemType.DATAROOM_DOCUMENT && perm.view,- )- .map(([itemId, _]) => itemId);-- // Get parent folder IDs for all visible documents- for (const documentId of visibleDocuments) {- const parentFolders = await getParentFolderIds(dataroomId, documentId);- parentFolders.forEach((folderId) => foldersToMakeVisible.add(folderId));- }-- // Also handle folders that are being made visible - ensure their parent folders are visible too- const visibleFolders = Object.entries(permissions)- .filter(- ([_, perm]) => perm.itemType === ItemType.DATAROOM_FOLDER && perm.view,- )- .map(([itemId, _]) => itemId);-- for (const folderId of visibleFolders) {- let currentFolderId: string | null = folderId;-- while (currentFolderId) {- const folder: { parentId: string | null } | null =- await prisma.dataroomFolder.findUnique({- where: { id: currentFolderId },- select: { parentId: true },- });-- if (folder?.parentId) {- foldersToMakeVisible.add(folder.parentId);- currentFolderId = folder.parentId;- } else {- break;- }- }- }-- // Update or create permissions for parent folders to make them visible- if (foldersToMakeVisible.size > 0) {- const foldersToUpdate = Array.from(foldersToMakeVisible);-- await prisma.$transaction(async (tx) => {- for (const folderId of foldersToUpdate) {- await tx.viewerGroupAccessControls.upsert({- where: {- groupId_itemId: {- groupId: groupId,- itemId: folderId,- },- },- create: {- groupId: groupId,- itemId: folderId,- itemType: ItemType.DATAROOM_FOLDER,- canView: true,- canDownload: false,- },- update: {- canView: true, // Always ensure parent folders are visible- // Don't change canDownload - preserve existing setting- },- });- }- });- }-}+// Saving thousands of permission rows in a single payload is a normal+// operation here (think "select all" on a large dataroom). With the bulk-SQL+// path below this is now ~3 round-trips total, but we still bump the+// platform timeout to be safe — same as the neighbouring `invite.ts`.+export const config = {+ maxDuration: 300,+};export default async function handler(req: NextApiRequest,@@ -155,12 +58,10 @@ export default async function handler(>;};- // Validate input- if (!permissions) {+ if (!permissions || typeof permissions !== "object") {return res.status(400).json({ message: "Missing required fields" });}- // Check if the user is part of the teamconst team = await prisma.team.findUnique({where: {id: teamId,@@ -176,7 +77,6 @@ export default async function handler(return res.status(403).json({ message: "Unauthorized" });}- // Verify the group belongs to this dataroom + team to avoid spoofingconst group = await prisma.viewerGroup.findFirst({where: { id: groupId, dataroomId, teamId },select: { id: true },@@ -186,51 +86,58 @@ export default async function handler(return res.status(404).json({ message: "Group not found" });}- // Build the deterministic upsert payload. We sort by itemId so the order- // of writes is stable across calls; combined with upsert this avoids the- // create/update race that previously caused intermittent failures and- // "random-feeling" persisted permissions when saves overlapped.- const upserts = Object.entries(permissions)- .map(([itemId, itemPermissions]) => ({+ const upsertRows: PermissionUpsertRow[] = Object.entries(permissions).map(+ ([itemId, itemPermissions]) => ({+ id: cuid(),itemId,itemType: itemPermissions.itemType,canView: Boolean(itemPermissions.view),canDownload: Boolean(itemPermissions.download),- }))- .sort((a, b) => a.itemId.localeCompare(b.itemId));-- // Perform operations sequentially inside a single transaction so that- // either every change lands or none do. We use upsert so we don't have to- // distinguish "create" vs "update" up front (the previous split caused- // unique-constraint failures when other in-flight saves had already- // created the row).+ }),+ );++ const bulkUpsertSql = buildBulkUpsertPermissionsSql(groupId, upsertRows);++ const { visibleDocumentIds, visibleFolderIds } =+ extractVisibleItemIds(permissions);++ const findAncestorsSql = buildFindAncestorFolderIdsSql(+ dataroomId,+ visibleDocumentIds,+ visibleFolderIds,+ );++ // Single interactive transaction so the invariant "every visible item+ // has visible ancestors" is never half-applied. Each step is a single+ // bulk SQL round-trip, so total wall-clock is well below Prisma's+ // 5s interactive-transaction window even for very large payloads.await prisma.$transaction(async (tx) => {- for (const item of upserts) {- await tx.viewerGroupAccessControls.upsert({- where: {- groupId_itemId: { groupId, itemId: item.itemId },- },- create: {+ if (bulkUpsertSql) {+ await tx.$executeRaw(bulkUpsertSql);+ }++ if (findAncestorsSql) {+ const ancestorRows = await tx.$queryRaw<{ folder_id: string }[]>(+ findAncestorsSql,+ );++ if (ancestorRows.length > 0) {+ const ancestors: AncestorUpsertRow[] = ancestorRows.map((r) => ({+ id: cuid(),+ folderId: r.folder_id,+ }));++ const ancestorUpsertSql = buildUpsertAncestorVisibilitySql(groupId,- itemId: item.itemId,- itemType: item.itemType,- canView: item.canView,- canDownload: item.canDownload,- },- update: {- // itemType is immutable for a given (groupId, itemId), but we set- // it explicitly to recover from any historical inconsistencies.- itemType: item.itemType,- canView: item.canView,- canDownload: item.canDownload,- },- });+ ancestors,+ );+ if (ancestorUpsertSql) {+ await tx.$executeRaw(ancestorUpsertSql);+ }+ }}});- // After saving permissions, ensure parent folders are visible for any items that were made visible- await ensureParentFoldersVisible(dataroomId, groupId, permissions);-res.status(200).json({ message: "Permissions updated successfully" });} catch (error) {console.error("Error updating permissions:", error);