Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat(datarooms): add option to remove the hierarchical index
Marc Seitze2fc1690eb35
diff --git a/components/datarooms/actions/rebuild-index-button.tsx b/components/datarooms/actions/rebuild-index-button.tsxindex 99056f70..04c260c2 100644--- a/components/datarooms/actions/rebuild-index-button.tsx+++ b/components/datarooms/actions/rebuild-index-button.tsx@@ -1,7 +1,7 @@import { useState } from "react";import { PlanEnum } from "@/ee/stripe/constants";-import { CrownIcon, ListOrderedIcon } from "lucide-react";+import { CrownIcon, ListOrderedIcon, Trash2Icon } from "lucide-react";import { toast } from "sonner";import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";@@ -34,7 +34,9 @@ export default function RebuildIndexButton({}: RebuildIndexButtonProps) {const { isFeatureEnabled } = useFeatureFlags();const { isDatarooms, isDataroomsPlus, isTrial } = usePlan();- const [isLoading, setIsLoading] = useState(false);+ const [loadingAction, setLoadingAction] = useState<+ "rebuild" | "clear" | null+ >(null);const [isOpen, setIsOpen] = useState(false);const isDataroomIndexEnabled = isFeatureEnabled("dataroomIndex");@@ -52,7 +54,7 @@ export default function RebuildIndexButton({return null;}- const handleRebuildIndex = async () => {+ const handleIndexAction = async (action: "rebuild" | "clear") => {if (!canUseFeature) {toast.error("Upgrade to Data Rooms Plus plan to use this feature.");return;@@ -63,8 +65,10 @@ export default function RebuildIndexButton({return;}+ const isClear = action === "clear";+try {- setIsLoading(true);+ setLoadingAction(action);const response = await fetch(`/api/teams/${teamId}/datarooms/${dataroomId}/calculate-indexes`,@@ -73,12 +77,15 @@ export default function RebuildIndexButton({headers: {"Content-Type": "application/json",},+ body: JSON.stringify({ action }),},);if (!response.ok) {const raw = await response.text();- let message = "Failed to rebuild indexes";+ let message = isClear+ ? "Failed to remove index"+ : "Failed to rebuild indexes";try {const parsed = JSON.parse(raw) as { message?: string };if (typeof parsed.message === "string") message = parsed.message;@@ -91,7 +98,9 @@ export default function RebuildIndexButton({const result = await response.json();toast.success(- `Hierarchical indexes rebuilt successfully! Updated ${result.totalUpdated} items (${result.foldersUpdated} folders, ${result.documentsUpdated} documents).`,+ isClear+ ? `Hierarchical index removed successfully! Cleared ${result.totalUpdated} items (${result.foldersUpdated} folders, ${result.documentsUpdated} documents).`+ : `Hierarchical indexes rebuilt successfully! Updated ${result.totalUpdated} items (${result.foldersUpdated} folders, ${result.documentsUpdated} documents).`,);setIsOpen(false);@@ -99,12 +108,19 @@ export default function RebuildIndexButton({// Trigger a page refresh to show updated indexeswindow.location.reload();} catch (error) {- console.error("Error rebuilding indexes:", error);+ console.error(+ isClear ? "Error removing index:" : "Error rebuilding indexes:",+ error,+ );toast.error(- error instanceof Error ? error.message : "Failed to rebuild indexes",+ error instanceof Error+ ? error.message+ : isClear+ ? "Failed to remove index"+ : "Failed to rebuild indexes",);} finally {- setIsLoading(false);+ setLoadingAction(null);}};@@ -119,7 +135,7 @@ export default function RebuildIndexButton({disabled={disabled || !teamId || !dataroomId}/></DialogTrigger>- <DialogContent className="sm:max-w-md">+ <DialogContent className="sm:max-w-lg"><DialogHeader><DialogTitle className="flex items-center">Rebuild Hierarchical Index@@ -146,21 +162,47 @@ export default function RebuildIndexButton({</li><li>Maintains the existing order and hierarchy</li></ul>+ <p className="mt-3">+ Prefer plain names? Use{" "}+ <span className="font-medium">Remove Index</span> to clear the+ hierarchical numbering from all folders and documents.+ </p></div></div></div></div>- <DialogFooter>+ <DialogFooter className="gap-2 sm:justify-between">{canUseFeature ? (<>- <Button variant="outline" onClick={() => setIsOpen(false)}>- Cancel- </Button>- <Button onClick={handleRebuildIndex} loading={isLoading}>- <ListOrderedIcon className="h-4 w-4" />- Rebuild Index+ <Button+ variant="ghost"+ className="whitespace-nowrap text-destructive hover:text-destructive"+ onClick={() => handleIndexAction("clear")}+ loading={loadingAction === "clear"}+ disabled={loadingAction !== null}+ >+ <Trash2Icon className="h-4 w-4" />+ Remove Index</Button>+ <div className="flex gap-2">+ <Button+ variant="outline"+ onClick={() => setIsOpen(false)}+ disabled={loadingAction !== null}+ >+ Cancel+ </Button>+ <Button+ className="whitespace-nowrap"+ onClick={() => handleIndexAction("rebuild")}+ loading={loadingAction === "rebuild"}+ disabled={loadingAction !== null}+ >+ <ListOrderedIcon className="h-4 w-4" />+ Rebuild Index+ </Button>+ </div></>) : (<UpgradePlanModaldiff --git a/lib/utils/calculate-hierarchical-indexes.ts b/lib/utils/calculate-hierarchical-indexes.tsindex a7e74c4b..947f788b 100644--- a/lib/utils/calculate-hierarchical-indexes.ts+++ b/lib/utils/calculate-hierarchical-indexes.ts@@ -218,3 +218,35 @@ export async function calculateAndUpdateHierarchicalIndexes(throw new Error("Failed to calculate and update hierarchical indexes");}}++/**+ * Clears (removes) hierarchical indexes for all folders and documents in a dataroom+ * by setting their `hierarchicalIndex` back to null.+ */+export async function clearHierarchicalIndexes(+ dataroomId: string,+): Promise<{ foldersUpdated: number; documentsUpdated: number }> {+ try {+ return await prisma.$transaction(+ async (tx) => {+ const foldersResult = await tx.dataroomFolder.updateMany({+ where: { dataroomId, hierarchicalIndex: { not: null } },+ data: { hierarchicalIndex: null },+ });+ const documentsResult = await tx.dataroomDocument.updateMany({+ where: { dataroomId, hierarchicalIndex: { not: null } },+ data: { hierarchicalIndex: null },+ });++ return {+ foldersUpdated: foldersResult.count,+ documentsUpdated: documentsResult.count,+ };+ },+ { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead },+ );+ } catch (error) {+ console.error("Error clearing hierarchical indexes for", dataroomId, error);+ throw new Error("Failed to clear hierarchical indexes");+ }+}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/calculate-indexes.ts b/pages/api/teams/[teamId]/datarooms/[id]/calculate-indexes.tsindex 3ce7ac62..74e7caf1 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/calculate-indexes.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/calculate-indexes.ts@@ -7,7 +7,10 @@ import { teamPlanIsDataroomPlusTier } from "@/lib/billing/team-plan-custom-messaimport { getFeatureFlags } from "@/lib/featureFlags";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";-import { calculateAndUpdateHierarchicalIndexes } from "@/lib/utils/calculate-hierarchical-indexes";+import {+ calculateAndUpdateHierarchicalIndexes,+ clearHierarchicalIndexes,+} from "@/lib/utils/calculate-hierarchical-indexes";export const config = {maxDuration: 300,@@ -32,6 +35,14 @@ export default async function handler(};const userId = (session.user as CustomUser).id;+ const action = (req.body as { action?: string } | undefined)?.action;+ if (action !== undefined && action !== "rebuild" && action !== "clear") {+ return res+ .status(400)+ .json({ message: "Invalid action. Use 'rebuild' or 'clear'." });+ }+ const shouldClear = action === "clear";+if (!dataroomId || typeof dataroomId !== "string") {return res.status(400).json({ message: "Invalid dataroom ID" });}@@ -81,19 +92,31 @@ export default async function handler(});}- // Calculate and update hierarchical indexes- const result = await calculateAndUpdateHierarchicalIndexes(dataroomId);+ // Calculate/update or clear hierarchical indexes+ const result = shouldClear+ ? await clearHierarchicalIndexes(dataroomId)+ : await calculateAndUpdateHierarchicalIndexes(dataroomId);res.status(200).json({- message: "Hierarchical indexes calculated successfully",+ message: shouldClear+ ? "Hierarchical indexes removed successfully"+ : "Hierarchical indexes calculated successfully",+ action: shouldClear ? "clear" : "rebuild",foldersUpdated: result.foldersUpdated,documentsUpdated: result.documentsUpdated,totalUpdated: result.foldersUpdated + result.documentsUpdated,});} catch (error) {- console.error("Error calculating hierarchical indexes:", error);+ console.error(+ shouldClear+ ? "Error removing hierarchical indexes:"+ : "Error calculating hierarchical indexes:",+ error,+ );res.status(500).json({- message: "Error calculating hierarchical indexes",+ message: shouldClear+ ? "Error removing hierarchical indexes"+ : "Error calculating hierarchical indexes",error: error instanceof Error ? error.message : "Unknown error",});}