Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
fix: duplicate group and harden permissions cfc2
Marc Seitz970fb4cfb734
diff --git a/components/datarooms/groups/delete-group/delete-group-modal.tsx b/components/datarooms/groups/delete-group/delete-group-modal.tsxindex 092edeeb..8116a6d1 100644--- a/components/datarooms/groups/delete-group/delete-group-modal.tsx+++ b/components/datarooms/groups/delete-group/delete-group-modal.tsx@@ -18,7 +18,6 @@ import { Input } from "@/components/ui/input";import { Modal } from "@/components/ui/modal";import { useAnalytics } from "@/lib/analytics";-import { useMediaQuery } from "@/lib/utils/use-media-query";function DeleteGroupModal({dataroomId,@@ -65,15 +64,16 @@ function DeleteGroupModal({});}- const { isMobile } = useMediaQuery();-return (<ModalshowModal={showDeleteGroupModal}setShowModal={setShowDeleteGroupModal}><div className="flex flex-col items-center justify-center space-y-3 border-b border-border bg-white px-4 py-4 pt-8 dark:border-gray-900 dark:bg-gray-900 sm:px-8">- <CardTitle>Delete Group</CardTitle>+ <CardTitle>Delete Data Room Group</CardTitle>+ <CardDescription className="text-md font-semibold text-foreground">+ {groupName}+ </CardDescription><CardDescription>Warning: This will permanently delete your dataroom group, allassociated links and their respective views.@@ -93,22 +93,23 @@ function DeleteGroupModal({><div><label- htmlFor="group-name"- className="block text-sm font-medium text-muted-foreground"+ htmlFor="verification"+ className="block text-sm text-muted-foreground">- Enter the group name{" "}- <span className="font-semibold text-foreground">{groupName}</span>{" "}- to continue:+ To verify, type{" "}+ <span className="font-semibold text-foreground">+ confirm delete group+ </span>{" "}+ below</label><div className="relative mt-1 rounded-md shadow-sm"><Inputtype="text"- name="group-name"- id="group-name"- autoFocus={!isMobile}- autoComplete="off"+ name="verification"+ id="verification"+ pattern="confirm delete group"required- pattern={groupName}+ autoComplete="off"className="bg-white dark:border-gray-500 dark:bg-gray-800 focus:dark:bg-transparent"/></div>diff --git a/components/datarooms/groups/delete-group/index.tsx b/components/datarooms/groups/delete-group/index.tsxindex 19f177d3..7483aa42 100644--- a/components/datarooms/groups/delete-group/index.tsx+++ b/components/datarooms/groups/delete-group/index.tsx@@ -1,3 +1,5 @@+import { Trash2Icon } from "lucide-react";+import { Button } from "@/components/ui/button";import {Card,@@ -26,27 +28,49 @@ export default function DeleteGroup({});return (- <div className="rounded-lg">+ <div id="delete-group" className="scroll-mt-24 rounded-lg"><DeleteGroupModal />- <Card className="border-destructive bg-transparent">+ <Card className="border-destructive/50 bg-transparent"><CardHeader>- <CardTitle>Delete Group</CardTitle>+ <CardTitle className="flex items-center gap-2">+ <Trash2Icon className="h-5 w-5 text-destructive" />+ Delete Data Room Group+ </CardTitle><CardDescription>- Permanently delete your group. <br />- <span className="font-medium">This action cannot be undone</span> -- please proceed with caution.+ Permanently delete{" "}+ <span className="font-medium text-foreground">{groupName}</span>{" "}+ and everything associated with it.</CardDescription></CardHeader>- <CardContent></CardContent>- <CardFooter className="flex items-center justify-end rounded-b-lg border-t px-6 py-3">- <div className="shrink-0">- <Button- onClick={() => setShowDeleteGroupModal(true)}- variant="destructive"- >- Delete Group- </Button>+ <CardContent className="space-y-3">+ <div className="rounded-md border border-destructive/30 bg-destructive/5 p-4">+ <p className="text-sm font-medium text-destructive">+ This action cannot be undone.+ </p>+ <ul className="mt-2 space-y-1 text-sm text-muted-foreground">+ <li>- All links in this group will be permanently removed</li>+ <li>- All viewer access via this group will be revoked</li>+ <li>- All views and analytics for those links will be lost</li>+ <li>- Group permissions will be deleted</li>+ </ul></div>+ </CardContent>+ <CardFooter className="flex items-center justify-between rounded-b-lg border-t bg-muted px-6 py-6">+ <p className="text-sm text-muted-foreground">+ You will be asked to type{" "}+ <code className="rounded bg-background px-1 py-0.5 font-mono text-xs">+ confirm delete group+ </code>{" "}+ to continue.+ </p>+ <Button+ onClick={() => setShowDeleteGroupModal(true)}+ variant="destructive"+ className="gap-2"+ >+ <Trash2Icon className="h-4 w-4" />+ Delete Data Room Group+ </Button></CardFooter></Card></div>diff --git a/components/datarooms/groups/group-card.tsx b/components/datarooms/groups/group-card.tsxindex 68e871ce..01fc9d8f 100644--- a/components/datarooms/groups/group-card.tsx+++ b/components/datarooms/groups/group-card.tsx@@ -1,7 +1,11 @@+import { useRouter } from "next/router";+import { useState } from "react";+import { useTeam } from "@/context/team-context";import { ViewerGroup } from "@prisma/client";-import { BoxesIcon, Layers2Icon, PenIcon } from "lucide-react";+import { BoxesIcon, Layers2Icon, Loader2Icon, Trash2Icon } from "lucide-react";+import { toast } from "sonner";import BarChart from "@/components/shared/icons/bar-chart";import MoreVertical from "@/components/shared/icons/more-vertical";@@ -11,17 +15,82 @@ import {DropdownMenuContent,DropdownMenuItem,DropdownMenuLabel,+ DropdownMenuSeparator,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";+import { useAnalytics } from "@/lib/analytics";+import useDataroomGroups from "@/lib/swr/use-dataroom-groups";import { cn, nFormatter } from "@/lib/utils";export default function GroupCard({group,+ dataroomId,}: {group: ViewerGroup & { _count: { members: number; views: number } };+ dataroomId: string;}) {+ const router = useRouter();const [menuOpen, setMenuOpen] = useState(false);+ const [isDuplicating, setIsDuplicating] = useState(false);++ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;+ const analytics = useAnalytics();+ const { mutate: mutateGroups } = useDataroomGroups({ dataroomId });++ // Stop link navigation when interacting with the dropdown trigger or items.+ const stopNavigation = (event: React.SyntheticEvent) => {+ event.preventDefault();+ event.stopPropagation();+ };++ const handleDeleteNavigation = (event: React.MouseEvent) => {+ stopNavigation(event);+ setMenuOpen(false);+ router.push(`/datarooms/${dataroomId}/groups/${group.id}#delete-group`);+ };++ const handleDuplicate = async (event: React.MouseEvent) => {+ stopNavigation(event);+ if (isDuplicating || !teamId) return;++ setIsDuplicating(true);+ try {+ const response = await fetch(+ `/api/teams/${teamId}/datarooms/${dataroomId}/groups/${group.id}/duplicate`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ },+ );++ if (!response.ok) {+ let message = "Failed to duplicate group. Please try again.";+ try {+ const data = await response.json();+ message = data?.message || data?.error || message;+ } catch {+ // ignore body parse errors+ }+ toast.error(message);+ return;+ }++ analytics.capture("Group Duplicated", {+ groupId: group.id,+ dataroomId,+ });+ toast.success("Group duplicated successfully.");+ await mutateGroups();+ } catch (error) {+ console.error("Error duplicating group:", error);+ toast.error("Failed to duplicate group. Please try again.");+ } finally {+ setIsDuplicating(false);+ setMenuOpen(false);+ }+ };return (<>@@ -61,24 +130,44 @@ export default function GroupCard({<DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}><DropdownMenuTrigger asChild><Button- // size="icon"variant="outline"className="z-20 h-8 w-8 border-gray-200 bg-transparent p-0 hover:bg-gray-200 dark:border-gray-700 hover:dark:bg-gray-700 lg:h-9 lg:w-9"+ onClick={stopNavigation}><span className="sr-only">Open menu</span><MoreVertical className="h-4 w-4" /></Button></DropdownMenuTrigger>- <DropdownMenuContent align="end">+ <DropdownMenuContent+ align="end"+ onClick={(event) => event.stopPropagation()}+ ><DropdownMenuLabel>Actions</DropdownMenuLabel>- <DropdownMenuItem>- <PenIcon className="mr-2 h-4 w-4" />- Edit group- </DropdownMenuItem>- <DropdownMenuItem>- <Layers2Icon className="mr-2 h-4 w-4" />+ <DropdownMenuItem+ disabled={isDuplicating}+ onSelect={(event) => {+ event.preventDefault();+ }}+ onClick={handleDuplicate}+ >+ {isDuplicating ? (+ <Loader2Icon className="mr-2 h-4 w-4 animate-spin" />+ ) : (+ <Layers2Icon className="mr-2 h-4 w-4" />+ )}Duplicate</DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onSelect={(event) => {+ event.preventDefault();+ }}+ onClick={handleDeleteNavigation}+ className="text-destructive focus:bg-destructive focus:text-destructive-foreground"+ >+ <Trash2Icon className="mr-2 h-4 w-4" />+ Delete group+ </DropdownMenuItem></DropdownMenuContent></DropdownMenu></div>diff --git a/components/datarooms/groups/group-permissions.tsx b/components/datarooms/groups/group-permissions.tsxindex 5af59c29..a3c487cc 100644--- a/components/datarooms/groups/group-permissions.tsx+++ b/components/datarooms/groups/group-permissions.tsx@@ -20,9 +20,9 @@ import {File,Folder,HomeIcon,+ Loader2Icon,} from "lucide-react";import { toast } from "sonner";-import { useDebounce } from "use-debounce";import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";import { useDataroomFoldersTree } from "@/lib/swr/use-dataroom";@@ -34,7 +34,6 @@ import {import CloudDownloadOff from "@/components/shared/icons/cloud-download-off";import { Button } from "@/components/ui/button";-import { Switch } from "@/components/ui/switch";import {Table,TableBody,@@ -139,12 +138,14 @@ const createColumns = (extra: ColumnExtra): ColumnDef<FileOrFolder>[] => [extra.updatePermissions(item.id, value);};+ const toggleValue: string[] = [];+ if (item.permissions.view) toggleValue.push("view");+ if (item.permissions.download) toggleValue.push("download");+return (<ToggleGrouptype="multiple"- value={Object.entries(item.permissions)- .filter(([_, value]) => value)- .map(([key, _]) => key)}+ value={toggleValue}onValueChange={handleValueChange}><ToggleGroupItem@@ -202,11 +203,12 @@ const buildTree = (const getPermissions = (id: string) => {const permission = permissions.find((p) => p.itemId === id);- // If we have permission data loaded, use it. Otherwise default to true for consistency.- const hasPermissionData = permissions.length > 0;-+ // No row in viewerGroupAccessControls means the viewer cannot see the+ // item. Default to false so the UI faithfully reflects the persisted+ // server state (otherwise toggling one item silently changes the view of+ // unrelated items after refetch, which feels random to users).return {- view: permission ? permission.canView : hasPermissionData ? false : true,+ view: permission ? permission.canView : false,download: permission ? permission.canDownload : false,partialView: false,partialDownload: false,@@ -349,10 +351,12 @@ export default function ExpandableTable({dataroomId,groupId,permissions,+ onSaved,}: {dataroomId: string;groupId: string;permissions: ViewerGroupAccessControls[];+ onSaved?: () => void | Promise<unknown>;}) {const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;@@ -362,7 +366,8 @@ export default function ExpandableTable({});const [data, setData] = useState<FileOrFolder[]>([]);const [pendingChanges, setPendingChanges] = useState<ItemPermission>({});- const [debouncedPendingChanges] = useDebounce(pendingChanges, 2000);+ const [isSaving, setIsSaving] = useState(false);+ const hasPendingChanges = Object.keys(pendingChanges).length > 0;// Use ref to access current data without dependencyconst dataRef = useRef<FileOrFolder[]>([]);@@ -403,25 +408,17 @@ export default function ExpandableTable({const updatedPermissions = {view: newPermissions.includes("view"),download: newPermissions.includes("download"),- partialView: newPermissions.includes("partialView"),- partialDownload: newPermissions.includes("partialDownload"),};- // Special cases- if (!updatedPermissions.view && item.permissions.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;}- if (updatedPermissions.partialDownload) {- updatedPermissions.download = true;- }-- if (updatedPermissions.partialView) {- updatedPermissions.view = true;- }-// Handle root-level permissions (affects all items)if (isRoot) {setData((prevData) => {@@ -725,53 +722,78 @@ export default function ExpandableTable({[],);+ // Rebuild the tree from server state when the underlying permissions or+ // folder tree change. We intentionally only do this when there are no+ // pending edits so that an in-flight SWR refetch (e.g. from another tab)+ // never wipes out unsaved work in this view.useEffect(() => {- if (folders && !loading) {+ if (folders && !loading && !hasPendingChanges) {const treeData = buildTreeWithRoot(folders, permissions, "Dataroom Home");setData(treeData);}- }, [folders, loading, permissions]);-- const saveChanges = useCallback(- async (changes: typeof pendingChanges) => {- try {- const response = await fetch(- `/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}/permissions`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- dataroomId,- groupId,- permissions: changes,- }),+ }, [folders, loading, permissions, hasPendingChanges]);++ const handleDiscardChanges = useCallback(() => {+ if (!folders) return;+ setPendingChanges({});+ setData(buildTreeWithRoot(folders, permissions, "Dataroom Home"));+ }, [folders, permissions]);++ const handleSaveChanges = useCallback(async () => {+ if (!hasPendingChanges || isSaving) return;+ setIsSaving(true);+ const changesToSave = pendingChanges;+ try {+ const response = await fetch(+ `/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}/permissions`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",},- );-- if (!response.ok) {- throw new Error("Failed to save permissions");- }-- toast.success("Permissions updated successfully.");+ body: JSON.stringify({+ dataroomId,+ groupId,+ permissions: changesToSave,+ }),+ },+ );- setPendingChanges({});- } catch (error) {- console.error("Error saving permissions:", error);- toast.error("Failed to update permissions", {- description: "Please try again.",- });+ if (!response.ok) {+ throw new Error("Failed to save permissions");}- },- [dataroomId, groupId],- );- useEffect(() => {- if (Object.keys(debouncedPendingChanges).length > 0) {- saveChanges(debouncedPendingChanges);+ toast.success("Permissions updated successfully.");+ await onSaved?.();+ setPendingChanges({});+ } catch (error) {+ console.error("Error saving permissions:", error);+ toast.error("Failed to update permissions", {+ description: "Please try again.",+ });+ } finally {+ setIsSaving(false);}- }, [debouncedPendingChanges, saveChanges]);+ }, [+ hasPendingChanges,+ isSaving,+ pendingChanges,+ teamId,+ dataroomId,+ groupId,+ onSaved,+ ]);++ // Warn the user before they navigate away with unsaved permission changes.+ useEffect(() => {+ if (!hasPendingChanges) return;+ const handler = (event: BeforeUnloadEvent) => {+ event.preventDefault();+ event.returnValue = "";+ };+ window.addEventListener("beforeunload", handler);+ return () => window.removeEventListener("beforeunload", handler);+ }, [hasPendingChanges]);const columns = useMemo(() => createColumns({ updatePermissions }),@@ -800,68 +822,141 @@ export default function ExpandableTable({if (loading) return <div>Loading...</div>;+ const changedItemCount = Object.keys(pendingChanges).length;+return (- <div className="rounded-md border">- <Table>- <TableHeader>- {table.getHeaderGroups().map((headerGroup) => (- <TableRow key={headerGroup.id}>- {headerGroup.headers.map((header) => (- <TableHead- key={header.id}- className="py-2 first:w-12 last:text-right"- >- {header.isPlaceholder- ? null- : flexRender(- header.column.columnDef.header,- header.getContext(),- )}- </TableHead>- ))}- </TableRow>- ))}- </TableHeader>- <TableBody>- {table.getRowModel().rows?.length ? (- table.getRowModel().rows.map((row) => {- const isRoot = row.original.id === "__dataroom_root__";- return (- <TableRow- key={row.id}- data-state={row.getIsSelected() && "selected"}- className={cn(isRoot && "bg-blue-50/50 dark:bg-blue-950/50")}- >- {row.getVisibleCells().map((cell, index) => (- <TableCell- key={cell.id}- style={- index === 0- ? {- paddingLeft: `${row.depth * 1.25}rem`,- }- : undefined- }- className="py-2 last:flex last:justify-end"- >- {flexRender(- cell.column.columnDef.cell,- cell.getContext(),- )}- </TableCell>- ))}- </TableRow>- );- })+ <div className="space-y-3">+ <div+ role="status"+ aria-live="polite"+ className={cn(+ "flex flex-col gap-3 rounded-md border px-4 py-3 transition-colors sm:flex-row sm:items-center sm:justify-between",+ hasPendingChanges+ ? "border-amber-300 bg-amber-50 dark:border-amber-700/60 dark:bg-amber-950/40"+ : "border-border bg-muted/40",+ )}+ >+ <div className="flex items-center gap-2 text-sm">+ {hasPendingChanges ? (+ <>+ <span+ aria-hidden+ className="inline-block h-2 w-2 rounded-full bg-amber-500"+ />+ <span className="font-medium text-amber-900 dark:text-amber-100">+ {changedItemCount} unsaved{" "}+ {changedItemCount === 1 ? "change" : "changes"}+ </span>+ <span className="text-muted-foreground">+ Save to apply your updates to this group.+ </span>+ </>) : (- <TableRow>- <TableCell colSpan={columns.length} className="h-24 text-center">- No results.- </TableCell>- </TableRow>+ <span className="text-muted-foreground">+ All permission changes saved.+ </span>)}- </TableBody>- </Table>+ </div>+ <div className="flex items-center gap-2 sm:justify-end">+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={handleDiscardChanges}+ disabled={!hasPendingChanges || isSaving}+ >+ Discard+ </Button>+ <Button+ type="button"+ size="sm"+ onClick={handleSaveChanges}+ disabled={!hasPendingChanges || isSaving}+ >+ {isSaving ? (+ <>+ <Loader2Icon className="mr-2 h-4 w-4 animate-spin" />+ Saving…+ </>+ ) : (+ "Save changes"+ )}+ </Button>+ </div>+ </div>++ <div+ className={cn(+ "rounded-md border",+ isSaving && "pointer-events-none opacity-60",+ )}+ >+ <Table>+ <TableHeader>+ {table.getHeaderGroups().map((headerGroup) => (+ <TableRow key={headerGroup.id}>+ {headerGroup.headers.map((header) => (+ <TableHead+ key={header.id}+ className="py-2 first:w-12 last:text-right"+ >+ {header.isPlaceholder+ ? null+ : flexRender(+ header.column.columnDef.header,+ header.getContext(),+ )}+ </TableHead>+ ))}+ </TableRow>+ ))}+ </TableHeader>+ <TableBody>+ {table.getRowModel().rows?.length ? (+ table.getRowModel().rows.map((row) => {+ const isRoot = row.original.id === "__dataroom_root__";+ return (+ <TableRow+ key={row.id}+ data-state={row.getIsSelected() && "selected"}+ className={cn(+ isRoot && "bg-blue-50/50 dark:bg-blue-950/50",+ )}+ >+ {row.getVisibleCells().map((cell, index) => (+ <TableCell+ key={cell.id}+ style={+ index === 0+ ? {+ paddingLeft: `${row.depth * 1.25}rem`,+ }+ : undefined+ }+ className="py-2 last:flex last:justify-end"+ >+ {flexRender(+ cell.column.columnDef.cell,+ cell.getContext(),+ )}+ </TableCell>+ ))}+ </TableRow>+ );+ })+ ) : (+ <TableRow>+ <TableCell+ colSpan={columns.length}+ className="h-24 text-center"+ >+ No results.+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </Table>+ </div></div>);}diff --git a/lib/swr/use-dataroom-groups.ts b/lib/swr/use-dataroom-groups.tsindex 20e5f4c5..d1380221 100644--- a/lib/swr/use-dataroom-groups.ts+++ b/lib/swr/use-dataroom-groups.ts@@ -101,7 +101,11 @@ export function useDataroomGroup() {const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;- const { data: viewerGroup, error } = useSWR<ViewerGroupWithMembers>(+ const {+ data: viewerGroup,+ error,+ mutate,+ } = useSWR<ViewerGroupWithMembers>(teamId &&id &&groupId &&@@ -121,6 +125,7 @@ export function useDataroomGroup() {viewerGroupPermissions: viewerGroup?.accessControls ?? [],loading: !viewerGroup && !error,error,+ mutate,};}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/duplicate.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/duplicate.tsnew file mode 100644index 00000000..9ca6eaa2--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/duplicate.ts@@ -0,0 +1,151 @@+import { NextApiRequest, NextApiResponse } from "next";++import { isTeamPausedById } from "@/ee/features/billing/cancellation/lib/is-team-paused";+import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth/next";++import { errorhandler } from "@/lib/errorHandler";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";+import { log } from "@/lib/utils";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "POST") {+ res.setHeader("Allow", ["POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }++ // POST /api/teams/:teamId/datarooms/:id/groups/:groupId/duplicate+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const {+ teamId,+ id: dataroomId,+ groupId,+ } = req.query as {+ teamId: string;+ id: string;+ groupId: string;+ };+ const userId = (session.user as CustomUser).id;++ try {+ const teamAccess = await prisma.userTeam.findUnique({+ where: {+ userId_teamId: { userId, teamId },+ },+ });++ if (!teamAccess) {+ return res.status(403).end("Unauthorized to access this team");+ }++ const teamIsPaused = await isTeamPausedById(teamId);+ if (teamIsPaused) {+ return res.status(403).json({+ error: "Team is currently paused. Duplicating groups is not available.",+ });+ }++ const sourceGroup = await prisma.viewerGroup.findUnique({+ where: {+ id: groupId,+ dataroomId,+ teamId,+ },+ include: {+ accessControls: {+ select: {+ itemId: true,+ itemType: true,+ canView: true,+ canDownload: true,+ },+ },+ members: {+ select: {+ viewerId: true,+ },+ },+ },+ });++ if (!sourceGroup) {+ return res.status(404).json({ message: "Group not found" });+ }++ // Find a non-conflicting copy name+ const baseName = `${sourceGroup.name} (Copy)`;+ let candidateName = baseName;+ let counter = 1;+ const MAX_RETRIES = 50;++ while (counter <= MAX_RETRIES) {+ const existing = await prisma.viewerGroup.findFirst({+ where: { dataroomId, name: candidateName },+ select: { id: true },+ });+ if (!existing) break;+ counter += 1;+ candidateName = `${baseName} (${counter})`;+ }++ if (counter > MAX_RETRIES) {+ return res.status(400).json({+ message:+ "Could not duplicate group: too many duplicates with similar names.",+ });+ }++ const duplicatedGroup = await prisma.$transaction(async (tx) => {+ const newGroup = await tx.viewerGroup.create({+ data: {+ name: candidateName,+ dataroomId,+ teamId,+ allowAll: sourceGroup.allowAll,+ domains: sourceGroup.domains,+ },+ });++ if (sourceGroup.accessControls.length > 0) {+ await tx.viewerGroupAccessControls.createMany({+ data: sourceGroup.accessControls.map((ac) => ({+ groupId: newGroup.id,+ itemId: ac.itemId,+ itemType: ac.itemType,+ canView: ac.canView,+ canDownload: ac.canDownload,+ })),+ skipDuplicates: true,+ });+ }++ if (sourceGroup.members.length > 0) {+ await tx.viewerGroupMembership.createMany({+ data: sourceGroup.members.map((member) => ({+ groupId: newGroup.id,+ viewerId: member.viewerId,+ })),+ skipDuplicates: true,+ });+ }++ return newGroup;+ });++ return res.status(201).json(duplicatedGroup);+ } catch (error) {+ log({+ message: `Failed to duplicate group: _${groupId}_ in dataroom _${dataroomId}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``,+ type: "error",+ });+ errorhandler(error, res);+ }+}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/permissions.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/permissions.tsindex 46c0d2df..bc0f719c 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/permissions.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/permissions.ts@@ -176,79 +176,54 @@ export default async function handler(return res.status(403).json({ message: "Unauthorized" });}- const existingPermissions = await prisma.viewerGroupAccessControls.findMany(- {- where: {- groupId,- group: { dataroomId },- },- select: { itemId: true, itemType: true },- },- );-- const existingSet = new Set(- existingPermissions.map((p) => `${p.itemId}-${p.itemType}`),- );+ // Verify the group belongs to this dataroom + team to avoid spoofing+ const group = await prisma.viewerGroup.findFirst({+ where: { id: groupId, dataroomId, teamId },+ select: { id: true },+ });- const toUpdate: {- groupId: string;- itemId: string;- itemType: ItemType;- canView: boolean;- canDownload: boolean;- }[] = [];- const toCreate: {- groupId: string;- itemId: string;- itemType: ItemType;- canView: boolean;- canDownload: boolean;- }[] = [];+ if (!group) {+ return res.status(404).json({ message: "Group not found" });+ }- Object.entries(permissions).forEach(([itemId, itemPermissions]) => {- const key = `${itemId}-${itemPermissions.itemType}`;- const data = {- groupId,+ // 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]) => ({itemId,itemType: itemPermissions.itemType,- canView: itemPermissions.view,- canDownload: itemPermissions.download,- };-- if (existingSet.has(key)) {- toUpdate.push(data);- } else {- toCreate.push(data);- }- });-- console.log("toUpdate", toUpdate);- console.log("toCreate", toCreate);-- // Perform operations+ 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).await prisma.$transaction(async (tx) => {- if (toUpdate.length > 0) {- await Promise.all(- toUpdate.map((item) =>- tx.viewerGroupAccessControls.update({- where: {- groupId_itemId: {- groupId: item.groupId,- itemId: item.itemId,- },- },- data: {- canView: item.canView,- canDownload: item.canDownload,- },- }),- ),- );- }-- if (toCreate.length > 0) {- await tx.viewerGroupAccessControls.createMany({- data: toCreate,+ for (const item of upserts) {+ await tx.viewerGroupAccessControls.upsert({+ where: {+ groupId_itemId: { groupId, itemId: item.itemId },+ },+ create: {+ 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,+ },});}});diff --git a/pages/datarooms/[id]/groups/[groupId]/permissions.tsx b/pages/datarooms/[id]/groups/[groupId]/permissions.tsxindex b2d0bbb6..ebf19f8f 100644--- a/pages/datarooms/[id]/groups/[groupId]/permissions.tsx+++ b/pages/datarooms/[id]/groups/[groupId]/permissions.tsx@@ -8,7 +8,7 @@ import { useDataroomGroup } from "@/lib/swr/use-dataroom-groups";export default function DataroomGroupPage() {const { dataroom } = useDataroom();- const { viewerGroup } = useDataroomGroup();+ const { viewerGroup, mutate: mutateViewerGroup } = useDataroomGroup();if (!dataroom || !viewerGroup) {return <div>Loading...</div>;@@ -28,6 +28,7 @@ export default function DataroomGroupPage() {dataroomId={dataroom.id}permissions={viewerGroup.accessControls}groupId={viewerGroup.id}+ onSaved={mutateViewerGroup}/></div></div>diff --git a/pages/datarooms/[id]/groups/index.tsx b/pages/datarooms/[id]/groups/index.tsxindex 8c12f48b..43919697 100644--- a/pages/datarooms/[id]/groups/index.tsx+++ b/pages/datarooms/[id]/groups/index.tsx@@ -96,7 +96,7 @@ export default function DataroomGroupPage() {<Linkhref={`/datarooms/${dataroom.id}/groups/${group.id}`}>- <GroupCard group={group} />+ <GroupCard group={group} dataroomId={dataroom.id} /></Link></li>))}