Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
fix: use parentId hierarchy for download folder structure instead of stale path field
Cursor Agent5f65a4510d67
diff --git a/lib/dataroom/build-folder-hierarchy.ts b/lib/dataroom/build-folder-hierarchy.tsnew file mode 100644index 00000000..57411da0--- /dev/null+++ b/lib/dataroom/build-folder-hierarchy.ts@@ -0,0 +1,73 @@+import slugify from "@sindresorhus/slugify";++export interface FolderInput {+ id: string;+ name: string;+ parentId: string | null;+}++/**+ * Builds a map of folder ID -> computed path based on the parentId hierarchy.+ *+ * This ensures the download folder structure matches what the UI shows+ * (which uses parentId to build the tree), rather than relying on the+ * materialized `path` field which can become stale after renames/moves.+ *+ * @param folders - Array of folders with id, name, and parentId+ * @returns Map of folderId -> computed slugified path (e.g., "/02-company-background/docs")+ */+export function buildFolderPathsFromHierarchy(+ folders: FolderInput[],+): Map<string, string> {+ const folderById = new Map(folders.map((f) => [f.id, f]));+ const pathCache = new Map<string, string>();++ function computePath(folderId: string, visited: Set<string>): string {+ if (pathCache.has(folderId)) return pathCache.get(folderId)!;++ // Prevent infinite loops from circular parentId references+ if (visited.has(folderId)) {+ const folder = folderById.get(folderId);+ const fallbackPath = `/${slugify(folder?.name ?? folderId)}`;+ pathCache.set(folderId, fallbackPath);+ return fallbackPath;+ }+ visited.add(folderId);++ const folder = folderById.get(folderId);+ if (!folder) return "";++ let parentPath = "";+ if (folder.parentId && folderById.has(folder.parentId)) {+ parentPath = computePath(folder.parentId, visited);+ }++ const path = `${parentPath}/${slugify(folder.name)}`;+ pathCache.set(folderId, path);+ return path;+ }++ for (const folder of folders) {+ computePath(folder.id, new Set());+ }++ return pathCache;+}++/**+ * Builds a folder name map from computed paths.+ * Maps computedPath -> { name, id } for looking up display names.+ */+export function buildFolderNameMap(+ folders: FolderInput[],+ pathMap: Map<string, string>,+): Map<string, { name: string; id: string }> {+ const nameMap = new Map<string, { name: string; id: string }>();+ for (const folder of folders) {+ const computedPath = pathMap.get(folder.id);+ if (computedPath) {+ nameMap.set(computedPath, { name: folder.name, id: folder.id });+ }+ }+ return nameMap;+}diff --git a/pages/api/links/download/bulk.ts b/pages/api/links/download/bulk.tsindex 72130ada..fc367b0a 100644--- a/pages/api/links/download/bulk.ts+++ b/pages/api/links/download/bulk.ts@@ -4,6 +4,10 @@ import { getTeamStorageConfigById } from "@/ee/features/storage/config";import { ItemType, ViewType } from "@prisma/client";import { verifyDataroomSessionInPagesRouter } from "@/lib/auth/dataroom-auth";+import {+ buildFolderNameMap,+ buildFolderPathsFromHierarchy,+} from "@/lib/dataroom/build-folder-hierarchy";import { notifyDocumentDownload } from "@/lib/integrations/slack/events";import prisma from "@/lib/prisma";import { downloadJobStore } from "@/lib/redis-download-job-store";@@ -74,6 +78,7 @@ export default async function handle(id: true,name: true,path: true,+ parentId: true,},},documents: {@@ -258,6 +263,12 @@ export default async function handle(skipDuplicates: true,});+ // Build folder paths from the parentId hierarchy (source of truth)+ // instead of using the materialized `path` field which can become stale+ // after folder renames/moves+ const computedPathMap = buildFolderPathsFromHierarchy(downloadFolders);+ const folderMap = buildFolderNameMap(downloadFolders, computedPathMap);+// Construct folderStructure and fileKeysconst folderStructure: {[key: string]: {@@ -274,14 +285,6 @@ export default async function handle(} = {};const fileKeys: string[] = [];- // Create a map of folder IDs to folder names- const folderMap = new Map(- downloadFolders.map((folder) => [- folder.path,- { name: folder.name, id: folder.id },- ]),- );-const addFileToStructure = (path: string,fileName: string,@@ -352,6 +355,9 @@ export default async function handle(// Add documents in foldersdownloadFolders.forEach((folder) => {+ // Use the computed path from parentId hierarchy instead of the stored path+ const folderPath = computedPathMap.get(folder.id) ?? folder.path;+const folderDocs = downloadDocuments.filter((doc) => doc.folderId === folder.id).filter((doc) => doc.document.versions[0].type !== "notion")@@ -369,7 +375,7 @@ export default async function handle(doc.document.versions[0].file);addFileToStructure(- folder.path,+ folderPath,doc.document.name,fileKey,doc.document.versions[0].type ?? undefined,@@ -379,7 +385,7 @@ export default async function handle(// If the folder is empty, ensure it's still added to the structureif (folderDocs && folderDocs.length === 0) {- addFileToStructure(folder.path, "", "");+ addFileToStructure(folderPath, "", "");}});diff --git a/pages/api/links/download/dataroom-folder.ts b/pages/api/links/download/dataroom-folder.tsindex c4782e45..feaf5315 100644--- a/pages/api/links/download/dataroom-folder.ts+++ b/pages/api/links/download/dataroom-folder.ts@@ -5,6 +5,9 @@ import { ItemType, ViewType } from "@prisma/client";import slugify from "@sindresorhus/slugify";import { verifyDataroomSessionInPagesRouter } from "@/lib/auth/dataroom-auth";+import {+ buildFolderPathsFromHierarchy,+} from "@/lib/dataroom/build-folder-hierarchy";import { notifyDocumentDownload } from "@/lib/integrations/slack/events";import prisma from "@/lib/prisma";import { downloadJobStore } from "@/lib/redis-download-job-store";@@ -128,19 +131,20 @@ export default async function handler(id: folderId,dataroomId,},- select: { id: true, name: true, path: true },+ select: { id: true, name: true, path: true, parentId: true },});if (!rootFolder) {return res.status(404).json({ error: "Folder not found" });}+ // Find all subfolders using path prefix (to get the full subtree)const subfolders = await prisma.dataroomFolder.findMany({where: {dataroomId,path: { startsWith: rootFolder.path + "/" },},- select: { id: true, name: true, path: true },+ select: { id: true, name: true, path: true, parentId: true },});let allFolders = [rootFolder, ...subfolders];@@ -212,6 +216,13 @@ export default async function handler();}+ // Build folder paths from the parentId hierarchy (source of truth)+ // This ensures the download structure matches what the UI shows+ const computedPathMap = buildFolderPathsFromHierarchy(allFolders);++ // Compute the root folder's path from the hierarchy+ const computedRootPath = computedPathMap.get(rootFolder.id) ?? rootFolder.path;+const folderStructure: {[key: string]: {name: string;@@ -229,28 +240,27 @@ export default async function handler(const fileKeys: string[] = [];const addFileToStructure = (- fullPath: string,- rootFolder: { name: string; path: string },+ computedFolderPath: string,+ rootFolderInfo: { name: string; computedPath: string },fileName: string,fileKey: string,fileType?: string,numPages?: number,) => {let relativePath = "";- if (fullPath !== rootFolder.path) {- const pathRegex = new RegExp(`^${rootFolder.path}/(.*)$`);- const match = fullPath.match(pathRegex);+ if (computedFolderPath !== rootFolderInfo.computedPath) {+ const escapedRoot = rootFolderInfo.computedPath.replace(+ /[.*+?^${}()|[\]\\]/g,+ "\\$&",+ );+ const pathRegex = new RegExp(`^${escapedRoot}/(.*)$`);+ const match = computedFolderPath.match(pathRegex);relativePath = match ? match[1] : "";}- const pathParts = [slugify(rootFolder.name)];+ const pathParts = [slugify(rootFolderInfo.name)];if (relativePath) {- pathParts.push(- ...relativePath- .split("/")- .filter(Boolean)- .map((part) => slugify(part)),- );+ pathParts.push(...relativePath.split("/").filter(Boolean));}let currentPath = "";@@ -281,13 +291,16 @@ export default async function handler(}};+ const rootFolderInfo = { name: rootFolder.name, computedPath: computedRootPath };+for (const folder of allFolders) {+ const folderPath = computedPathMap.get(folder.id) ?? folder.path;const docs = allDocuments.filter((doc) => doc.folderId === folder.id);if (docs.length === 0) {addFileToStructure(- folder.path,- rootFolder,+ folderPath,+ rootFolderInfo,"","",undefined,@@ -311,8 +324,8 @@ export default async function handler(? version.file: (version.originalFile ?? version.file);addFileToStructure(- folder.path,- rootFolder,+ folderPath,+ rootFolderInfo,doc.document.name,fileKey,version.type ?? undefined,diff --git a/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.ts b/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.tsindex 0193620c..0c8c941b 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.ts@@ -4,6 +4,10 @@ import { getTeamStorageConfigById } from "@/ee/features/storage/config";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth";+import {+ buildFolderNameMap,+ buildFolderPathsFromHierarchy,+} from "@/lib/dataroom/build-folder-hierarchy";import prisma from "@/lib/prisma";import { downloadJobStore } from "@/lib/redis-download-job-store";import { bulkDownloadTask } from "@/lib/trigger/bulk-download";@@ -58,6 +62,7 @@ export default async function handler(id: true,name: true,path: true,+ parentId: true,},},documents: {@@ -93,6 +98,12 @@ export default async function handler(let downloadFolders = dataroom.folders;let downloadDocuments = dataroom.documents;+ // Build folder paths from the parentId hierarchy (source of truth)+ // instead of using the materialized `path` field which can become stale+ // after folder renames/moves+ const computedPathMap = buildFolderPathsFromHierarchy(downloadFolders);+ const folderMap = buildFolderNameMap(downloadFolders, computedPathMap);+// Construct folderStructure and fileKeysconst folderStructure: {[key: string]: {@@ -102,12 +113,6 @@ export default async function handler(};} = {};const fileKeys: string[] = [];- const folderMap = new Map(- downloadFolders.map((folder) => [- folder.path,- { name: folder.name, id: folder.id },- ]),- );const addFileToStructure = (path: string,@@ -168,6 +173,9 @@ export default async function handler();downloadFolders.forEach((folder) => {+ // Use the computed path from parentId hierarchy instead of the stored path+ const folderPath = computedPathMap.get(folder.id) ?? folder.path;+const folderDocs = downloadDocuments.filter((doc) => doc.folderId === folder.id).filter((doc) => doc.document.versions[0].type !== "notion")@@ -178,7 +186,7 @@ export default async function handler(folderDocs &&folderDocs.forEach((doc) =>addFileToStructure(- folder.path,+ folderPath,doc.document.name,doc.document.versions[0].originalFile ??doc.document.versions[0].file,@@ -190,7 +198,7 @@ export default async function handler(// If the folder is empty, ensure it's still added to the structureif (folderDocs && folderDocs.length === 0) {- addFileToStructure(folder.path, "", "");+ addFileToStructure(folderPath, "", "");}});