Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat(ee): add granular permissions
Marc Seitzb2904ece1925
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.tsindex 81ef4bf7..0e70d735 100644--- a/app/api/views-dataroom/route.ts+++ b/app/api/views-dataroom/route.ts@@ -115,6 +115,7 @@ export async function POST(request: NextRequest) {enableWatermark: true,watermarkConfig: true,groupId: true,+ permissionGroupId: true,audienceType: true,allowDownload: true,enableConversation: true,@@ -854,10 +855,13 @@ export async function POST(request: NextRequest) {// check if viewer can download the document based on group permissionslet canDownload: boolean = link.allowDownload ?? false;+ const effectiveGroupId = link.groupId || link.permissionGroupId;+if (link.allowDownload &&- link.audienceType === LinkAudienceType.GROUP &&- link.groupId &&+ (link.audienceType === LinkAudienceType.GROUP ||+ link.permissionGroupId) &&+ effectiveGroupId &&documentId &&dataroomId) {@@ -873,18 +877,36 @@ export async function POST(request: NextRequest) {if (!dataroomDocument) {canDownload = false;} else {- const groupDocumentPermission =- await prisma.viewerGroupAccessControls.findUnique({- where: {- groupId_itemId: {- groupId: link.groupId,- itemId: dataroomDocument.id,+ if (link.groupId) {+ // This is a ViewerGroup (legacy behavior)+ const groupDocumentPermission =+ await prisma.viewerGroupAccessControls.findUnique({+ where: {+ groupId_itemId: {+ groupId: link.groupId,+ itemId: dataroomDocument.id,+ },+ itemType: ItemType.DATAROOM_DOCUMENT,},- itemType: ItemType.DATAROOM_DOCUMENT,- },- select: { canDownload: true },- });- canDownload = groupDocumentPermission?.canDownload ?? false;+ select: { canDownload: true },+ });+ canDownload = groupDocumentPermission?.canDownload ?? false;+ } else if (link.permissionGroupId) {+ // This is a PermissionGroup (new behavior)+ const permissionGroupDocumentPermission =+ await prisma.permissionGroupAccessControls.findUnique({+ where: {+ groupId_itemId: {+ groupId: link.permissionGroupId,+ itemId: dataroomDocument.id,+ },+ itemType: ItemType.DATAROOM_DOCUMENT,+ },+ select: { canDownload: true },+ });+ canDownload =+ permissionGroupDocumentPermission?.canDownload ?? false;+ }}}diff --git a/components/datarooms/dataroom-header.tsx b/components/datarooms/dataroom-header.tsxindex 3ab9deae..5e83182f 100644--- a/components/datarooms/dataroom-header.tsx+++ b/components/datarooms/dataroom-header.tsx@@ -6,15 +6,14 @@ import { BellRingIcon } from "lucide-react";import { useDataroom, useDataroomLinks } from "@/lib/swr/use-dataroom";-import LinkSheet from "@/components/links/link-sheet";+import { DataroomLinkSheet } from "@/components/links/link-sheet/dataroom-link-sheet";import { Button } from "@/components/ui/button";-import {Tooltip,TooltipContent,TooltipPortal,TooltipTrigger,-} from "../ui/tooltip";+} from "@/components/ui/tooltip";export const DataroomHeader = ({title,@@ -70,7 +69,7 @@ export const DataroomHeader = ({Share</Button></div>- <LinkSheet+ <DataroomLinkSheetlinkType={"DATAROOM_LINK"}isOpen={isLinkSheetOpen}setIsOpen={setIsLinkSheetOpen}diff --git a/components/links/link-sheet/dataroom-link-sheet.tsx b/components/links/link-sheet/dataroom-link-sheet.tsxnew file mode 100644index 00000000..aa3f5e9d--- /dev/null+++ b/components/links/link-sheet/dataroom-link-sheet.tsx@@ -0,0 +1,7 @@+"use client";++import { DataroomLinkSheet as DataroomLinkSheetEE } from "@/ee/features/permissions/components/dataroom-link-sheet";++export function DataroomLinkSheet(props: any) {+ return <DataroomLinkSheetEE {...props} />;+}diff --git a/components/links/link-sheet/link-success-sheet.tsx b/components/links/link-sheet/link-success-sheet.tsxnew file mode 100644index 00000000..a61059db--- /dev/null+++ b/components/links/link-sheet/link-success-sheet.tsx@@ -0,0 +1,256 @@+"use client";++import { useState } from "react";++import {+ Check,+ ClockIcon,+ Copy,+ DownloadIcon,+ ExternalLink,+ FolderLockIcon,+ KeyRoundIcon,+ Mail,+ MailCheckIcon,+ MailIcon,+ ShieldIcon,+ Users,+} from "lucide-react";++import { LinkWithViews } from "@/lib/types";++import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { Separator } from "@/components/ui/separator";+import {+ Sheet,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from "@/components/ui/sheet";++interface LinkSuccessSheetProps {+ isOpen: boolean;+ setIsOpen: (open: boolean) => void;+ link: LinkWithViews;+ hasCustomPermissions: boolean;+ onCreateAnother: () => void;+}++export default function LinkSuccessSheet({+ isOpen,+ setIsOpen,+ link,+ hasCustomPermissions,+ onCreateAnother,+}: LinkSuccessSheetProps) {+ const [copied, setCopied] = useState(false);++ const copyToClipboard = async () => {+ try {+ const linkUrl =+ link.domainId && link.slug+ ? `https://${link.domainSlug}/${link.slug}`+ : `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${link.id}`;++ await navigator.clipboard.writeText(linkUrl);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ } catch (err) {+ console.error("Failed to copy: ", err);+ }+ };++ const openLink = () => {+ const linkUrl = link.domainSlug+ ? `https://${link.domainSlug}/${link.slug}`+ : `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${link.id}`;+ window.open(linkUrl, "_blank");+ };++ const linkUrl = link.domainSlug+ ? `https://${link.domainSlug}/${link.slug}`+ : `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${link.id}`;++ return (+ <Sheet open={isOpen} onOpenChange={setIsOpen}>+ <SheetContent className="flex w-[90%] flex-col justify-between border-l border-gray-200 bg-background px-4 text-foreground dark:border-gray-800 dark:bg-gray-900 sm:w-[600px] sm:max-w-2xl md:px-5">+ <SheetHeader className="text-start">+ <SheetTitle className="flex items-center gap-2">+ <Check className="h-5 w-5 text-green-600" />+ Link Created Successfully+ </SheetTitle>+ <p className="text-sm text-muted-foreground">+ Your dataroom link has been created and is ready to share.+ </p>+ </SheetHeader>++ <div className="flex-1 space-y-6 py-6">+ {/* Link Section */}+ <div className="space-y-3">+ <h3 className="text-sm font-medium">Share Link</h3>+ <div className="flex items-center gap-2 rounded-lg border bg-muted/30 p-3">+ <div className="flex-1 truncate font-mono text-sm">{linkUrl}</div>+ <Button+ variant="outline"+ size="sm"+ onClick={copyToClipboard}+ className="shrink-0"+ >+ {copied ? (+ <Check className="h-4 w-4" />+ ) : (+ <Copy className="h-4 w-4" />+ )}+ {copied ? "Copied" : "Copy"}+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={openLink}+ className="shrink-0"+ >+ <ExternalLink className="h-4 w-4" />+ Open+ </Button>+ </div>+ </div>++ <Separator />++ {/* Link Configuration Summary */}+ <div className="space-y-4">+ <h3 className="text-sm font-medium">Link Configuration</h3>++ <div className="grid gap-3">+ <div className="flex items-center justify-between text-sm">+ <span className="flex items-center gap-2 text-muted-foreground">+ <FolderLockIcon className="h-4 w-4" />+ File Permissions+ </span>+ <Badge variant={hasCustomPermissions ? "secondary" : "default"}>+ {hasCustomPermissions ? "Custom Permissions" : "Full Access"}+ </Badge>+ </div>++ <div className="flex items-center justify-between text-sm">+ <span className="flex items-center gap-2 text-muted-foreground">+ <Users className="h-4 w-4" />+ Viewer Access+ </span>+ <Badge+ variant={link.allowList.length > 0 ? "default" : "secondary"}+ >+ {link.allowList.length > 0+ ? "Specified viewers"+ : "Everyone with link"}+ </Badge>+ </div>++ {link.emailProtected && (+ <div className="flex items-center justify-between text-sm">+ <span className="flex items-center gap-2 text-muted-foreground">+ <MailIcon className="h-4 w-4" />+ Email Protection+ </span>+ <Badge variant="default">Enabled</Badge>+ </div>+ )}++ {link.emailProtected && (+ <div className="flex items-center justify-between text-sm">+ <span className="flex items-center gap-2 text-muted-foreground">+ <MailCheckIcon className="h-4 w-4" />+ Email Verification+ </span>+ <Badge+ variant={link.emailAuthenticated ? "default" : "secondary"}+ >+ {link.emailAuthenticated ? "Enabled" : "Disabled"}+ </Badge>+ </div>+ )}++ {link.password && (+ <div className="flex items-center justify-between text-sm">+ <span className="flex items-center gap-2 text-muted-foreground">+ <KeyRoundIcon className="h-4 w-4" />+ Password Protection+ </span>+ <Badge variant="secondary">Enabled</Badge>+ </div>+ )}++ {link.expiresAt && (+ <div className="flex items-center justify-between text-sm">+ <span className="flex items-center gap-2 text-muted-foreground">+ <ClockIcon className="h-4 w-4" />+ Expiration+ </span>+ <Badge variant="outline">+ {new Date(link.expiresAt).toLocaleDateString()}+ </Badge>+ </div>+ )}++ <div className="flex items-center justify-between text-sm">+ <span className="flex items-center gap-2 text-muted-foreground">+ <DownloadIcon className="h-4 w-4" />+ Downloads+ </span>+ <Badge variant={link.allowDownload ? "default" : "secondary"}>+ {link.allowDownload ? "Enabled" : "Disabled"}+ </Badge>+ </div>++ <div className="flex items-center justify-between text-sm">+ <span className="flex items-center gap-2 text-muted-foreground">+ <ShieldIcon className="h-4 w-4" />+ Additional Security+ </span>+ <Badge+ variant={+ link.enableAgreement || link.enableWatermark+ ? "default"+ : "secondary"+ }+ >+ {link.enableAgreement || link.enableWatermark+ ? "Enabled"+ : "Disabled"}+ </Badge>+ </div>+ </div>+ </div>++ <Separator />++ {/* Future: Invite Members Section */}+ <div className="space-y-3">+ <h3 className="text-sm font-medium text-muted-foreground">+ Invite Members (Coming Soon)+ </h3>+ <div className="rounded-lg border border-dashed border-muted-foreground/25 p-6 text-center">+ <Mail className="mx-auto h-8 w-8 text-muted-foreground/50" />+ <p className="mt-2 text-sm text-muted-foreground">+ Soon you'll be able to invite team members directly via email+ </p>+ </div>+ </div>+ </div>++ <SheetFooter>+ <div className="flex flex-row-reverse items-center gap-2 pt-2">+ <Button type="button" onClick={() => setIsOpen(false)}>+ Close+ </Button>+ <Button type="button" variant="outline" onClick={onCreateAnother}>+ Create Another Link+ </Button>+ </div>+ </SheetFooter>+ </SheetContent>+ </Sheet>+ );+}diff --git a/components/links/link-sheet/permissions-sheet.tsx b/components/links/link-sheet/permissions-sheet.tsxnew file mode 100644index 00000000..14ce3330--- /dev/null+++ b/components/links/link-sheet/permissions-sheet.tsx@@ -0,0 +1,7 @@+"use client";++import { PermissionsSheet as PermissionsSheetEE } from "@/ee/features/permissions/components/permissions-sheet";++export function PermissionsSheet(props: any) {+ return <PermissionsSheetEE {...props} />;+}diff --git a/ee/features/permissions/components/dataroom-link-sheet.tsx b/ee/features/permissions/components/dataroom-link-sheet.tsxnew file mode 100644index 00000000..4674dddc--- /dev/null+++ b/ee/features/permissions/components/dataroom-link-sheet.tsx@@ -0,0 +1,900 @@+import Link from "next/link";+import { useRouter } from "next/router";++import { Dispatch, SetStateAction, useEffect, useState } from "react";++import { useTeam } from "@/context/team-context";+import {+ ItemType,+ LinkAudienceType,+ LinkPreset,+ LinkType,+} from "@prisma/client";+import { RefreshCwIcon } from "lucide-react";+import { toast } from "sonner";+import { mutate } from "swr";+import useSWR from "swr";++import { useAnalytics } from "@/lib/analytics";+import { usePlan } from "@/lib/swr/use-billing";+import useDataroomGroups from "@/lib/swr/use-dataroom-groups";+import { useDomains } from "@/lib/swr/use-domains";+import useLimits from "@/lib/swr/use-limits";+import { LinkWithViews, WatermarkConfig } from "@/lib/types";+import { convertDataUrlToFile, fetcher, uploadImage } from "@/lib/utils";++import {+ DEFAULT_LINK_PROPS as BASE_DEFAULT_LINK_PROPS,+ DEFAULT_LINK_TYPE as BASE_DEFAULT_LINK_TYPE,+} from "@/components/links/link-sheet";+import DomainSection from "@/components/links/link-sheet/domain-section";+import { LinkOptions } from "@/components/links/link-sheet/link-options";+import LinkSuccessSheet from "@/components/links/link-sheet/link-success-sheet";+import TagSection from "@/components/links/link-sheet/tags/tag-section";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { ScrollArea } from "@/components/ui/scroll-area";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Separator } from "@/components/ui/separator";+import {+ Sheet,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from "@/components/ui/sheet";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { ButtonTooltip } from "@/components/ui/tooltip";++import { PermissionsSheet } from "./permissions-sheet";++export const DEFAULT_LINK_PROPS = (+ linkType: LinkType,+ groupId: string | null = null,+ showBanner: boolean = true,+) => ({+ ...BASE_DEFAULT_LINK_PROPS(linkType, groupId, showBanner),+ permissions: {},+});++type ItemPermission = Record<+ string,+ { view: boolean; download: boolean; itemType: ItemType }+>;++export type DEFAULT_LINK_TYPE = BASE_DEFAULT_LINK_TYPE & {+ permissions?: ItemPermission | null;+};++export function DataroomLinkSheet({+ isOpen,+ setIsOpen,+ linkType,+ currentLink,+ existingLinks,+}: {+ isOpen: boolean;+ setIsOpen: Dispatch<SetStateAction<boolean>>;+ linkType: LinkType;+ currentLink?: DEFAULT_LINK_TYPE;+ existingLinks?: LinkWithViews[];+}) {+ const router = useRouter();+ const { id: targetId, groupId } = router.query as {+ id: string;+ groupId?: string;+ };++ const { domains } = useDomains();++ const {+ viewerGroups,+ loading: isLoadingGroups,+ mutate: mutateGroups,+ } = useDataroomGroups();+ const teamInfo = useTeam();+ const { isFree, isPro, isBusiness, isDatarooms, isDataroomsPlus, isTrial } =+ usePlan();+ const { limits } = useLimits();+ const analytics = useAnalytics();+ const [data, setData] = useState<DEFAULT_LINK_TYPE>(+ DEFAULT_LINK_PROPS(linkType, groupId, !isDatarooms),+ );+ const [isLoading, setIsLoading] = useState<boolean>(false);+ const [isSaving, setIsSaving] = useState<boolean>(false);+ const [currentPreset, setCurrentPreset] = useState<LinkPreset | null>(null);+ const [showPermissionsSheet, setShowPermissionsSheet] =+ useState<boolean>(false);+ const [pendingLinkData, setPendingLinkData] =+ useState<DEFAULT_LINK_TYPE | null>(null);+ const [showSuccessSheet, setShowSuccessSheet] = useState<boolean>(false);+ const [createdLink, setCreatedLink] = useState<LinkWithViews | null>(null);+ const [hasCustomPermissions, setHasCustomPermissions] =+ useState<boolean>(false);++ const isPresetsAllowed =+ (isPro && limits?.advancedLinkControlsOnPro) ||+ isBusiness ||+ isDatarooms ||+ isDataroomsPlus;++ // Presets+ const { data: presets } = useSWR<LinkPreset[]>(+ teamInfo?.currentTeam?.id+ ? `/api/teams/${teamInfo.currentTeam.id}/presets`+ : null,+ fetcher,+ {+ dedupingInterval: 10000,+ },+ );++ useEffect(() => {+ setData(currentLink || DEFAULT_LINK_PROPS(linkType, groupId, !isDatarooms));+ }, [currentLink]);++ const handlePreviewLink = async (link: LinkWithViews) => {+ if (link.domainId && isFree) {+ toast.error("You need to upgrade to preview this link");+ return;+ }++ setIsLoading(true);+ const response = await fetch(`/api/links/${link.id}/preview`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ });++ if (!response.ok) {+ toast.error("Failed to generate preview link");+ setIsLoading(false);+ return;+ }++ const { previewToken } = await response.json();+ const previewLink = `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${link.id}?previewToken=${previewToken}`;+ setIsLoading(false);+ const linkElement = document.createElement("a");+ linkElement.href = previewLink;+ linkElement.target = "_blank";+ document.body.appendChild(linkElement);+ linkElement.click();++ setTimeout(() => {+ document.body.removeChild(linkElement);+ }, 100);+ };++ const applyPreset = (presetId: string) => {+ const preset = presets?.find((p) => p.id === presetId);+ if (!preset) return;++ setData((prev) => {+ return {+ ...prev,+ name: prev.name, // Keep existing name+ domain: prev.domain, // Keep existing domain+ slug: prev.slug, // Keep existing slug+ emailProtected: preset.emailProtected ?? prev.emailProtected,+ emailAuthenticated:+ preset.emailAuthenticated ?? prev.emailAuthenticated,+ allowList: preset.allowList || prev.allowList,+ denyList: preset.denyList || prev.denyList,+ password: preset.password || prev.password,+ enableCustomMetatag:+ preset.enableCustomMetaTag ?? prev.enableCustomMetatag,+ metaTitle: preset.metaTitle || prev.metaTitle,+ metaDescription: preset.metaDescription || prev.metaDescription,+ metaImage: preset.metaImage || prev.metaImage,+ metaFavicon: preset.metaFavicon || prev.metaFavicon,+ allowDownload: preset.allowDownload || prev.allowDownload,+ enableAgreement: preset.enableAgreement || prev.enableAgreement,+ agreementId: preset.agreementId || prev.agreementId,+ enableScreenshotProtection:+ preset.enableScreenshotProtection || prev.enableScreenshotProtection,+ enableNotification: !!preset.enableNotification,+ };+ });++ setCurrentPreset(preset);+ };++ const handlePermissionsSave = async (permissions: ItemPermission | null) => {+ if (!pendingLinkData) return;++ setIsSaving(true);++ try {+ // Use the unified function for both new and existing links+ await createOrUpdateLinkWithPermissions(+ pendingLinkData,+ permissions,+ false,+ true,+ );++ // Close the sheets and show success+ setIsOpen(false);+ setShowPermissionsSheet(false);+ setPendingLinkData(null);+ } catch (error) {+ console.error("Error creating/updating link with permissions:", error);+ setIsSaving(false);+ }+ };++ const createOrUpdateLinkWithPermissions = async (+ linkData: DEFAULT_LINK_TYPE,+ permissions: ItemPermission | null,+ shouldPreview: boolean = false,+ showSuccess: boolean = false,+ ) => {+ // Upload the image if it's a data URL+ let blobUrl: string | null =+ linkData.metaImage && linkData.metaImage.startsWith("data:")+ ? null+ : linkData.metaImage;+ if (linkData.metaImage && linkData.metaImage.startsWith("data:")) {+ // Convert the data URL to a blob+ const blob = convertDataUrlToFile({ dataUrl: linkData.metaImage });+ // Upload the blob to vercel storage+ blobUrl = await uploadImage(blob);+ }++ // Upload meta favicon if it's a data URL+ let blobUrlFavicon: string | null =+ linkData.metaFavicon && linkData.metaFavicon.startsWith("data:")+ ? null+ : linkData.metaFavicon;+ if (linkData.metaFavicon && linkData.metaFavicon.startsWith("data:")) {+ const blobFavicon = convertDataUrlToFile({+ dataUrl: linkData.metaFavicon,+ });+ blobUrlFavicon = await uploadImage(blobFavicon);+ }++ let endpoint = "/api/links";+ let method = "POST";+ const isUpdating = !!currentLink?.id;++ if (isUpdating) {+ endpoint = `/api/links/${currentLink.id}`;+ method = "PUT";+ }++ const response = await fetch(endpoint, {+ method: method,+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ ...linkData,+ metaImage: blobUrl,+ metaFavicon: blobUrlFavicon,+ targetId: targetId,+ linkType: linkType,+ teamId: teamInfo?.currentTeam?.id,+ }),+ });++ if (!response.ok) {+ // handle error with toast message+ const { error } = await response.json();+ toast.error(error);+ setIsSaving(false);+ return;+ }++ const returnedLink = await response.json();++ // Handle permissions+ await handlePermissionGroupOperations(+ returnedLink,+ permissions,+ isUpdating,+ );++ // Handle UI updates and notifications+ await handlePostSaveOperations(+ returnedLink,+ isUpdating,+ showSuccess,+ shouldPreview,+ permissions,+ );++ setData(DEFAULT_LINK_PROPS(linkType, groupId));+ setIsSaving(false);+ };++ const handlePermissionGroupOperations = async (+ link: any,+ permissions: ItemPermission | null,+ isUpdating: boolean,+ ) => {+ // If permissions are null, user wants full dataroom access - no permission group needed+ if (permissions === null) {+ // If updating and link had a permission group, we might want to remove it+ // For now, we'll leave existing permission groups as they are+ return;+ }++ // If permissions is an empty object, user wants no access - still create/update permission group+ // If permissions has items, create/update permission group with those permissions+ if (permissions && typeof permissions === "object") {+ if (isUpdating && currentLink?.permissionGroupId) {+ // Update existing permission group+ await fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${targetId}/permission-groups/${currentLink.permissionGroupId}`,+ {+ method: "PUT",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ permissions: permissions,+ }),+ },+ );+ } else {+ // Create new permission group+ await fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${targetId}/permission-groups`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ permissions: permissions,+ linkId: link.id,+ }),+ },+ );+ }+ }+ };++ const handlePostSaveOperations = async (+ returnedLink: any,+ isUpdating: boolean,+ showSuccess: boolean,+ shouldPreview: boolean,+ permissions: ItemPermission | null,+ ) => {+ const endpointTargetType = `${linkType.replace("_LINK", "").toLowerCase()}s`; // "documents" or "datarooms"++ if (isUpdating) {+ setIsOpen(false);+ // Update the link in the list of links+ mutate(+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/${encodeURIComponent(+ targetId,+ )}/links`,+ (existingLinks || []).map((link) =>+ link.id === currentLink!.id ? returnedLink : link,+ ),+ false,+ );++ // Handle group changes+ if (!!groupId && returnedLink.audienceType === LinkAudienceType.GROUP) {+ // If we're viewing a group page+ if (currentLink!.groupId !== returnedLink.groupId) {+ // If the link's group has changed+ if (currentLink!.groupId === groupId) {+ // If the link was in the current group but is now in a different group+ // Remove it from the current group's view+ const groupLinks =+ existingLinks?.filter(+ (link) =>+ link.id !== currentLink!.id && link.groupId === groupId,+ ) || [];++ mutate(+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/${encodeURIComponent(+ targetId,+ )}/groups/${groupId}/links`,+ groupLinks,+ false,+ );+ } else if (returnedLink.groupId === groupId) {+ // If the link was in a different group but is now in the current group+ // Add it to the current group's view+ const groupLinks =+ existingLinks?.filter((link) => link.groupId === groupId) || [];++ mutate(+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/${encodeURIComponent(+ targetId,+ )}/groups/${groupId}/links`,+ [returnedLink, ...groupLinks],+ false,+ );+ }+ } else if (returnedLink.groupId === groupId) {+ // If the link's group hasn't changed and it's in the current group+ // Update it in the current group's view+ const groupLinks =+ existingLinks?.filter((link) => link.groupId === groupId) || [];++ mutate(+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/${encodeURIComponent(+ targetId,+ )}/groups/${groupId}/links`,+ groupLinks.map((link) =>+ link.id === currentLink!.id ? returnedLink : link,+ ),+ false,+ );+ }+ }++ toast.success("Link updated successfully");+ } else {+ // Add the new link to the list of links+ mutate(+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/${encodeURIComponent(+ targetId,+ )}/links`,+ [returnedLink, ...(existingLinks || [])],+ false,+ );++ // Also update the group-specific links cache if this is a group link+ if (+ !!groupId &&+ returnedLink.audienceType === LinkAudienceType.GROUP &&+ returnedLink.groupId === groupId+ ) {+ const groupLinks =+ existingLinks?.filter((link) => link.groupId === groupId) || [];+ mutate(+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/${encodeURIComponent(+ targetId,+ )}/groups/${groupId}/links`,+ [returnedLink, ...groupLinks],+ false,+ );+ }++ analytics.capture("Link Added", {+ linkId: returnedLink.id,+ targetId,+ linkType,+ customDomain: returnedLink.domainSlug,+ });++ if (showSuccess) {+ // Show success sheet instead of closing+ setIsOpen(false);+ setShowPermissionsSheet(false);+ setPendingLinkData(null);+ setCreatedLink(returnedLink);+ setHasCustomPermissions(+ permissions !== null &&+ permissions &&+ Object.keys(permissions).length > 0,+ );+ setShowSuccessSheet(true);+ } else {+ setIsOpen(false);+ setShowPermissionsSheet(false);+ setPendingLinkData(null);+ toast.success("Link created successfully");+ }+ }++ if (shouldPreview) {+ await handlePreviewLink(returnedLink);+ }+ };++ // Remove the old createLinkWithPermissions function and replace it with a simple wrapper+ const createLinkWithPermissions = async (+ linkData: DEFAULT_LINK_TYPE,+ shouldPreview: boolean = false,+ showSuccess: boolean = false,+ ) => {+ // For backward compatibility, extract permissions from linkData+ const permissions = linkData.permissions || null;+ await createOrUpdateLinkWithPermissions(+ linkData,+ permissions,+ shouldPreview,+ showSuccess,+ );+ };++ const handleSubmit = async (+ event: any,+ shouldPreview: boolean = false,+ shouldManagePermissions: boolean = false,+ ) => {+ event.preventDefault();++ if (shouldManagePermissions && linkType === LinkType.DATAROOM_LINK) {+ // Store the link data and show permissions sheet+ setPendingLinkData(data);+ setShowPermissionsSheet(true);+ return;+ }++ // Use the refactored function+ await createLinkWithPermissions(data, shouldPreview);+ };++ const handleCreateAnother = () => {+ // Close success sheet and open new link sheet+ setShowSuccessSheet(false);+ setCreatedLink(null);+ setHasCustomPermissions(false);+ setData(DEFAULT_LINK_PROPS(linkType, groupId));+ setIsOpen(true);+ };++ return (+ <>+ <Sheet open={isOpen} onOpenChange={(open: boolean) => setIsOpen(open)}>+ <SheetContent className="flex w-[90%] flex-col justify-between border-l border-gray-200 bg-background px-4 text-foreground dark:border-gray-800 dark:bg-gray-900 sm:w-[800px] sm:max-w-4xl md:px-5">+ <SheetHeader className="text-start">+ <SheetTitle>+ {currentLink+ ? `Edit ${currentLink.audienceType === LinkAudienceType.GROUP ? "group" : ""} link`+ : "Create a new link"}+ </SheetTitle>+ </SheetHeader>++ <form+ className="flex grow flex-col"+ onSubmit={(e) => handleSubmit(e, false)}+ >+ <ScrollArea className="flex-grow">+ <div className="h-0 flex-1">+ <div className="flex flex-1 flex-col justify-between pb-6">+ <div className="divide-y divide-gray-200">+ <Tabs+ value={data.audienceType}+ onValueChange={(value) =>+ setData({+ ...data,+ audienceType: value as LinkAudienceType,+ })+ }+ >+ {/* {linkType === LinkType.DATAROOM_LINK && !!!currentLink ? (+ <TabsList className="grid w-full grid-cols-2">+ <TabsTrigger value={LinkAudienceType.GENERAL}>+ General+ </TabsTrigger>+ {isDatarooms || isDataroomsPlus || isTrial ? (+ <TabsTrigger value={LinkAudienceType.GROUP}>+ Group+ </TabsTrigger>+ ) : (+ <UpgradePlanModal+ clickedPlan={PlanEnum.DataRooms}+ trigger="add_group_link"+ >+ <div className="inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all">+ Group+ </div>+ </UpgradePlanModal>+ )}+ </TabsList>+ ) : null} */}++ {/* GENERAL LINK */}+ <TabsContent value={LinkAudienceType.GENERAL}>+ <div className="space-y-6 pt-2">+ <div className="space-y-2">+ <Label htmlFor="link-name">Link Name</Label>+ <Input+ type="text"+ name="link-name"+ id="link-name"+ placeholder="Recipient's Organization"+ value={data.name || ""}+ className="focus:ring-inset"+ onChange={(e) =>+ setData({ ...data, name: e.target.value })+ }+ />+ </div>++ <div className="space-y-2">+ <DomainSection+ {...{ data, setData, domains }}+ linkType={linkType}+ editLink={!!currentLink}+ />+ </div>++ {/* Preset Selector - only show when creating a new link */}+ {!currentLink &&+ isPresetsAllowed &&+ presets &&+ presets.length > 0 && (+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <Label htmlFor="preset">Link Preset</Label>+ <Link+ href="/settings/presets"+ className="text-xs text-muted-foreground hover:text-foreground hover:underline"+ >+ Manage+ </Link>+ </div>+ <Select onValueChange={applyPreset}>+ <SelectTrigger className="w-full">+ <SelectValue placeholder="Select a preset" />+ </SelectTrigger>+ <SelectContent>+ {presets.map((preset) => (+ <SelectItem+ key={preset.id}+ value={preset.id}+ >+ {preset.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <p className="text-xs text-muted-foreground">+ Apply a preset to quickly configure link+ settings+ </p>+ </div>+ )}++ <div className="relative flex items-center">+ <Separator className="absolute bg-muted-foreground" />+ <div className="relative mx-auto">+ <span className="bg-background px-2 text-sm text-muted-foreground dark:bg-gray-900">+ Link Options+ </span>+ </div>+ </div>++ <LinkOptions+ data={data}+ setData={setData}+ targetId={targetId}+ linkType={linkType}+ editLink={!!currentLink}+ currentPreset={currentPreset}+ />+ </div>+ </TabsContent>++ {/* GROUP LINK */}+ <TabsContent value={LinkAudienceType.GROUP}>+ <div className="space-y-6 pb-10 pt-2">+ <div className="space-y-2">+ <div className="flex w-full items-center justify-between">+ <Label htmlFor="group-id">Group </Label>+ <ButtonTooltip content="Refresh groups">+ <Button+ size="icon"+ variant="ghost"+ className="h-6"+ onClick={async (e) => {+ e.stopPropagation();+ e.preventDefault();+ await mutateGroups();+ }}+ >+ <RefreshCwIcon className="h-4 w-4" />+ </Button>+ </ButtonTooltip>+ </div>+ <Select+ onValueChange={(value) => {+ if (value === "add_group") {+ // Open the group sheet+ console.log("add_group redirect");+ return;+ }++ setData({ ...data, groupId: value });+ }}+ defaultValue={data.groupId ?? undefined}+ >+ <SelectTrigger className="focus:ring-offset-3 flex w-full rounded-md border-0 bg-background py-1.5 text-foreground shadow-sm ring-1 ring-inset ring-input placeholder:text-muted-foreground focus:ring-2 focus:ring-gray-400 sm:text-sm sm:leading-6">+ <SelectValue placeholder="Select an group" />+ </SelectTrigger>+ <SelectContent>+ {isLoadingGroups ? (+ <SelectItem value="loading" disabled>+ Loading groups...+ </SelectItem>+ ) : viewerGroups && viewerGroups.length > 0 ? (+ viewerGroups.map(({ id, name, _count }) => (+ <SelectItem key={id} value={id}>+ {name}{" "}+ <span className="text-muted-foreground">+ ({_count.members} members)+ </span>+ </SelectItem>+ ))+ ) : (+ <SelectItem value="no-groups" disabled>+ No groups available+ </SelectItem>+ )}+ </SelectContent>+ </Select>+ </div>++ <div className="space-y-2">+ <Label htmlFor="link-name">Link Name</Label>++ <Input+ type="text"+ name="link-name"+ id="link-name"+ placeholder={+ viewerGroups?.find(+ (group) => group.id === data.groupId,+ )?.name+ ? `${+ viewerGroups?.find(+ (group) => group.id === data.groupId,+ )?.name+ } Link`+ : "Group Link"+ }+ value={data.name || ""}+ className="focus:ring-inset"+ onChange={(e) =>+ setData({ ...data, name: e.target.value })+ }+ />+ </div>++ <div className="space-y-2">+ <DomainSection+ {...{ data, setData, domains }}+ linkType={linkType}+ editLink={!!currentLink}+ />+ </div>++ {/* Preset Selector for Group links - only show when creating a new link */}+ {!currentLink &&+ isPresetsAllowed &&+ presets &&+ presets.length > 0 && (+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <Label htmlFor="preset">Link Preset</Label>+ <Link+ href="/settings/presets"+ className="text-xs text-muted-foreground hover:text-foreground hover:underline"+ >+ Manage+ </Link>+ </div>+ <Select onValueChange={applyPreset}>+ <SelectTrigger className="w-full">+ <SelectValue placeholder="Select a preset" />+ </SelectTrigger>+ <SelectContent>+ {presets.map((preset) => (+ <SelectItem+ key={preset.id}+ value={preset.id}+ >+ {preset.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <p className="text-xs text-muted-foreground">+ Apply a preset to quickly configure link+ settings+ </p>+ </div>+ )}++ <div className="relative flex items-center">+ <Separator className="absolute bg-muted-foreground" />+ <div className="relative mx-auto">+ <span className="bg-background px-2 text-sm text-muted-foreground dark:bg-gray-900">+ Link Options+ </span>+ </div>+ </div>++ <LinkOptions+ data={data}+ setData={setData}+ targetId={targetId}+ linkType={linkType}+ editLink={!!currentLink}+ currentPreset={currentPreset}+ />+ </div>+ </TabsContent>+ </Tabs>+ </div>+ <Separator className="mb-6 mt-2" />++ <div className="space-y-2">+ <TagSection+ {...{ data, setData }}+ teamId={teamInfo?.currentTeam?.id as string}+ />+ </div>+ </div>+ </div>+ </ScrollArea>++ <SheetFooter>+ <div className="flex flex-row-reverse items-center gap-2 pt-2">+ <Button+ type="submit"+ loading={isSaving}+ onClick={(e) => handleSubmit(e, false)}+ >+ {currentLink ? "Update Link" : "Save Link"}+ </Button>+ <Button+ type="button"+ variant="outline"+ loading={isLoading}+ onClick={(e) => handleSubmit(e, true)}+ >+ {currentLink ? "Update & Preview" : "Save & Preview"}+ </Button>+ {linkType === LinkType.DATAROOM_LINK &&+ currentLink?.audienceType !== LinkAudienceType.GROUP && (+ <Button+ type="button"+ variant="secondary"+ onClick={(e) => handleSubmit(e, false, true)}+ >+ Manage Permissions+ </Button>+ )}+ </div>+ </SheetFooter>+ </form>+ </SheetContent>++ <PermissionsSheet+ isOpen={showPermissionsSheet}+ setIsOpen={(open) => {+ setShowPermissionsSheet(open);+ if (!open) {+ setShowSuccessSheet(true);+ }+ }}+ dataroomId={targetId}+ linkId={currentLink?.id ?? undefined}+ permissionGroupId={currentLink?.permissionGroupId ?? undefined}+ onSave={handlePermissionsSave}+ />+ </Sheet>++ {createdLink && (+ <LinkSuccessSheet+ isOpen={showSuccessSheet}+ setIsOpen={setShowSuccessSheet}+ link={createdLink}+ hasCustomPermissions={hasCustomPermissions}+ onCreateAnother={handleCreateAnother}+ />+ )}+ </>+ );+}diff --git a/ee/features/permissions/components/permissions-sheet.tsx b/ee/features/permissions/components/permissions-sheet.tsxnew file mode 100644index 00000000..d3a209f7--- /dev/null+++ b/ee/features/permissions/components/permissions-sheet.tsx@@ -0,0 +1,1027 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";++import { useTeam } from "@/context/team-context";+import { ItemType, PermissionGroupAccessControls } from "@prisma/client";+import {+ ColumnDef,+ flexRender,+ getCoreRowModel,+ getExpandedRowModel,+ useReactTable,+} from "@tanstack/react-table";+import {+ ArrowDownToLineIcon,+ ChevronDown,+ ChevronRight,+ EyeIcon,+ EyeOffIcon,+ File,+ Folder,+ HomeIcon,+} from "lucide-react";+import useSWR from "swr";++import { useDataroomFoldersTree } from "@/lib/swr/use-dataroom";+import { cn, fetcher } from "@/lib/utils";++import CloudDownloadOff from "@/components/shared/icons/cloud-download-off";+import { Button } from "@/components/ui/button";+import {+ Sheet,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from "@/components/ui/sheet";+import { Switch } from "@/components/ui/switch";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";+import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";++// FileOrFolder type for link permissions+type FileOrFolder = {+ id: string;+ name: string;+ subItems?: FileOrFolder[];+ permissions: {+ view: boolean;+ download: boolean;+ partialView?: boolean;+ partialDownload?: boolean;+ };+ itemType: ItemType;+ documentId?: string;+};++type ItemPermission = Record<+ string,+ { view: boolean; download: boolean; itemType: ItemType }+>;++type ColumnExtra = {+ updatePermissions: (id: string, newPermissions: string[]) => void;+};++const createColumns = (extra: ColumnExtra): ColumnDef<FileOrFolder>[] => [+ {+ accessorKey: "name",+ header: "Name",+ cell: ({ row }) => {+ const isRoot = row.original.id === "__dataroom_root__";+ return (+ <div className="flex items-center text-foreground">+ {isRoot ? (+ <div className="h-6 w-6 shrink-0" />+ ) : row.getCanExpand() ? (+ <Button+ variant="ghost"+ onClick={row.getToggleExpandedHandler()}+ className="mr-1 h-6 w-6 shrink-0 p-0"+ disabled={isRoot} // Root is always expanded+ >+ {row.getIsExpanded() ? (+ <ChevronDown className="h-4 w-4" />+ ) : (+ <ChevronRight className="h-4 w-4" />+ )}+ </Button>+ ) : (+ <div className="mr-1 h-6 w-6 shrink-0" /> // Placeholder to maintain alignment+ )}+ {isRoot ? (+ <HomeIcon className="mr-2 h-5 w-5 shrink-0" />+ ) : row.original.itemType === ItemType.DATAROOM_FOLDER ? (+ <Folder className="mr-2 h-5 w-5 shrink-0" />+ ) : (+ <File className="mr-2 h-5 w-5 shrink-0" />+ )}+ <span className={cn("truncate", isRoot && "font-semibold")}>+ {row.original.name}+ </span>+ </div>+ );+ },+ },+ {+ id: "actions",+ header: "Actions",+ cell: ({ row }) => {+ const item = row.original;++ const handleValueChange = (value: string[]) => {+ extra.updatePermissions(item.id, value);+ };++ return (+ <ToggleGroup+ type="multiple"+ value={Object.entries(item.permissions)+ .filter(([_, value]) => value)+ .map(([key, _]) => key)}+ onValueChange={handleValueChange}+ >+ <ToggleGroupItem+ value="view"+ aria-label="Toggle view"+ size="sm"+ className={cn(+ "px-2 text-muted-foreground hover:ring-1 hover:ring-gray-400 data-[state=on]:bg-foreground data-[state=on]:text-background",+ item.permissions.view+ ? item.permissions.partialView+ ? "data-[state=on]:bg-gray-400 data-[state=on]:text-background"+ : "data-[state=on]:bg-foreground data-[state=on]:text-background"+ : "",+ )}+ >+ {item.permissions.view ||+ (item.permissions.view && item.permissions.partialView) ? (+ <EyeIcon className="h-5 w-5" />+ ) : (+ <EyeOffIcon className="h-5 w-5" />+ )}+ </ToggleGroupItem>+ <ToggleGroupItem+ value="download"+ aria-label="Toggle download"+ size="sm"+ className={cn(+ "px-2 text-muted-foreground hover:ring-1 hover:ring-gray-400 data-[state=on]:bg-foreground data-[state=on]:text-background",+ item.permissions.download+ ? item.permissions.partialDownload+ ? "data-[state=on]:bg-gray-400 data-[state=on]:text-background"+ : "data-[state=on]:bg-foreground data-[state=on]:text-background"+ : "",+ )}+ >+ {item.permissions.download ||+ (item.permissions.download && item.permissions.partialDownload) ? (+ <ArrowDownToLineIcon className="h-5 w-5" />+ ) : (+ <CloudDownloadOff className="h-5 w-5" />+ )}+ </ToggleGroupItem>+ </ToggleGroup>+ );+ },+ },+];++// Build tree function adapted for link permissions with virtual root+const buildTree = (+ items: any[],+ permissions: PermissionGroupAccessControls[],+ parentId: string | null = null,+): FileOrFolder[] => {+ 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 new links.+ const hasPermissionData = permissions.length > 0;++ return {+ view: permission ? permission.canView : hasPermissionData ? false : true,+ download: permission ? permission.canDownload : false,+ partialView: false,+ partialDownload: false,+ };+ };++ const result: FileOrFolder[] = [];++ // Handle folders and their contents+ items+ .filter((item) => item.parentId === parentId && !item.document)+ .forEach((folder) => {+ const subItems = buildTree(items, permissions, folder.id);++ // Add documents directly in this folder+ const folderDocuments = (folder.documents || []).map((doc: any) => ({+ id: doc.id,+ documentId: doc.document.id,+ name: doc.document.name,+ permissions: getPermissions(doc.id),+ itemType: ItemType.DATAROOM_DOCUMENT,+ }));++ const allSubItems = [...subItems, ...folderDocuments];++ 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;+ }++ result.push({+ id: folder.id,+ name: folder.name,+ subItems: allSubItems,+ permissions: {+ view: viewStatus,+ download: downloadStatus,+ partialView,+ partialDownload,+ },+ itemType: ItemType.DATAROOM_FOLDER,+ });+ });++ // Handle documents that are direct children of the current parent (including root level)+ items+ .filter(+ (item) =>+ (item.parentId === parentId && item.document) ||+ (parentId === null && item.folderId === null && item.document),+ )+ .forEach((doc) => {+ result.push({+ id: doc.id,+ documentId: doc.document.id,+ name: doc.document.name,+ permissions: getPermissions(doc.id),+ itemType: ItemType.DATAROOM_DOCUMENT,+ });+ });++ return result;+};++// Build tree with virtual root folder+const buildTreeWithRoot = (+ items: any[],+ permissions: PermissionGroupAccessControls[],+ dataroomName: string = "Dataroom Home",+): FileOrFolder[] => {+ // Get all items (folders and root documents) - buildTree already handles root documents when parentId is null+ const allItems = buildTree(items, permissions, null);++ // Calculate overall permissions for the virtual root+ const calculateRootPermissions = (items: FileOrFolder[]) => {+ const flattenItems = (items: FileOrFolder[]): FileOrFolder[] => {+ return items.reduce((acc, item) => {+ acc.push(item);+ if (item.subItems) {+ acc.push(...flattenItems(item.subItems));+ }+ return acc;+ }, [] as FileOrFolder[]);+ };++ const allFlatItems = flattenItems(items);+ const viewableItems = allFlatItems.filter((item) => item.permissions.view);+ const downloadableItems = allFlatItems.filter(+ (item) => item.permissions.download,+ );++ return {+ view: viewableItems.length > 0,+ download: downloadableItems.length > 0,+ partialView:+ viewableItems.length > 0 && viewableItems.length < allFlatItems.length,+ partialDownload:+ downloadableItems.length > 0 &&+ downloadableItems.length < allFlatItems.length,+ };+ };++ const rootPermissions = calculateRootPermissions(allItems);++ return [+ {+ id: "__dataroom_root__",+ name: dataroomName,+ subItems: allItems,+ permissions: rootPermissions,+ itemType: ItemType.DATAROOM_FOLDER,+ },+ ];+};++interface PermissionsSheetProps {+ isOpen: boolean;+ setIsOpen: (open: boolean) => void;+ dataroomId: string;+ linkId?: string; // For editing existing links+ permissionGroupId?: string | null; // For loading existing permissions+ onSave: (permissions: ItemPermission | null) => void;+ // initialPermissions?: PermissionGroupAccessControls[]; // Keep for backward compatibility+}++export function PermissionsSheet({+ isOpen,+ setIsOpen,+ dataroomId,+ linkId,+ permissionGroupId,+ onSave,+ // initialPermissions = [],+}: PermissionsSheetProps) {+ const { currentTeamId } = useTeam();+ const { folders, loading } = useDataroomFoldersTree({+ dataroomId,+ include_documents: true,+ });++ // Fetch permission group data if permissionGroupId is provided+ const { data: permissionGroupData, isLoading: permissionGroupLoading } =+ useSWR<{+ permissionGroup: {+ id: string;+ name: string;+ description: string | null;+ accessControls: PermissionGroupAccessControls[];+ };+ }>(+ permissionGroupId && currentTeamId+ ? `/api/teams/${currentTeamId}/datarooms/${dataroomId}/permission-groups/${permissionGroupId}`+ : null,+ fetcher,+ );++ const [data, setData] = useState<FileOrFolder[]>([]);+ const [pendingChanges, setPendingChanges] = useState<ItemPermission>({});+ const [isSaving, setIsSaving] = useState<boolean>(false);++ // Determine the effective permissions to use+ const effectivePermissions = useMemo(() => {+ if (permissionGroupData?.permissionGroup?.accessControls) {+ return permissionGroupData.permissionGroup.accessControls;+ }+ return [];+ }, [permissionGroupData]);++ // Add state for the "share entire dataroom" toggle+ const [shareEntireDataroom, setShareEntireDataroom] = useState<boolean>(+ effectivePermissions.length === 0, // Default to true if no effective permissions+ );++ // Use ref to access current data without dependency+ const dataRef = useRef<FileOrFolder[]>([]);++ useEffect(() => {+ dataRef.current = data;+ }, [data]);++ const updatePermissions = useCallback(+ (id: string, newPermissions: string[]) => {+ // When any permission is changed, turn off the "share entire dataroom" toggle+ setShareEntireDataroom(false);++ 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 result = findItemAndParents(dataRef.current, id);+ if (!result) return;++ const { item, parents } = result;++ 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) {+ 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) => {+ 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 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,+ }));++ 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,+ },+ };++ // 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 updateSubItems = (+ items: FileOrFolder[],+ viewState: boolean,+ downloadState: boolean,+ ): FileOrFolder[] => {+ return items.map((item) => ({+ ...item,+ permissions: {+ ...item.permissions,+ view: viewState,+ partialView: false,+ partialDownload: false,+ download: downloadState,+ },+ subItems: item.subItems+ ? updateSubItems(item.subItems, viewState, downloadState)+ : undefined,+ }));+ };++ const updateParentPermissions = (+ 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));+ }+ return acc;+ }, [] as FileOrFolder[]);+ };++ const allItems = flattenItems(items);+ const viewableItems = allItems.filter(+ (item) => item.permissions.view,+ );+ const downloadableItems = allItems.filter(+ (item) => item.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,+ 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,+ );++ return {+ ...parent,+ permissions: {+ view: someSubItemViewable,+ partialView: someSubItemViewable && !allSubItemsViewable,+ download: someSubItemDownloadable,+ partialDownload:+ someSubItemDownloadable && !allSubItemsDownloadable,+ },+ subItems,+ };+ };++ return updateItemInTree(prevData);+ });++ // 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,+ };+ }++ // 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,+ };+ }+ 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,+ };+ }+ });+ } 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,+ };+ }+ });+ }++ return changes;+ };++ setPendingChanges((prev) => ({+ ...prev,+ ...collectChanges(item, parents),+ }));+ },+ [], // Remove data dependency to prevent excessive re-renders+ );++ useEffect(() => {+ if (folders && !loading) {+ const treeData = buildTreeWithRoot(+ folders,+ effectivePermissions,+ "Dataroom Home",+ );+ setData(treeData);+ }+ }, [folders, loading, effectivePermissions]); // Add effectivePermissions as dependency++ // Reset settings when sheet opens for a new link+ useEffect(() => {+ if (isOpen) {+ // Reset to default state for new links+ setShareEntireDataroom(effectivePermissions.length === 0);+ setPendingChanges({});++ // Reset the UI to show full access for new links (when no effective permissions)+ if (effectivePermissions.length === 0) {+ setData((prevData) => {+ const resetToFullAccess = (items: FileOrFolder[]): FileOrFolder[] => {+ return items.map((item) => ({+ ...item,+ permissions: {+ view: true,+ download: false,+ partialView: false,+ partialDownload: false,+ },+ subItems: item.subItems+ ? resetToFullAccess(item.subItems)+ : undefined,+ }));+ };++ return resetToFullAccess(prevData);+ });+ }+ }+ }, [isOpen, effectivePermissions.length]);++ // Handle the "share entire dataroom" toggle+ const handleShareEntireDataroomToggle = (checked: boolean) => {+ setShareEntireDataroom(checked);+ if (checked) {+ // Clear pending changes when sharing entire dataroom+ setPendingChanges({});+ // Reset UI to show full access (but don't save to database)+ setData((prevData) => {+ const updateAllItems = (items: FileOrFolder[]): FileOrFolder[] => {+ return items.map((item) => {+ return {+ ...item,+ permissions: {+ view: true,+ download: false,+ partialView: false,+ partialDownload: false,+ },+ subItems: item.subItems+ ? updateAllItems(item.subItems)+ : undefined,+ };+ });+ };++ return updateAllItems(prevData);+ });+ } else {+ // When turning off, don't automatically set all items to viewable+ // Let the user manually select what they want+ // Just ensure we have some changes to track+ setPendingChanges({});+ }+ };++ const handleSave = async () => {+ setIsSaving(true);+ try {+ // If sharing entire dataroom, pass null to indicate no specific permissions+ if (shareEntireDataroom) {+ await onSave(null);+ } else {+ // Merge existing permissions with pending changes+ const completePermissions: ItemPermission = {};++ // First, add all existing permissions+ effectivePermissions.forEach((permission) => {+ completePermissions[permission.itemId] = {+ view: permission.canView,+ download: permission.canDownload,+ itemType: permission.itemType,+ };+ });++ // Then, apply pending changes (this will override existing permissions for changed items)+ Object.keys(pendingChanges).forEach((itemId) => {+ completePermissions[itemId] = pendingChanges[itemId];+ });++ await onSave(completePermissions);+ }++ setIsOpen(false);+ // Clear pending changes after the sheet is closed to avoid UI flickering+ setPendingChanges({});+ } catch (error) {+ console.error("Error saving permissions:", error);+ } finally {+ setIsSaving(false);+ }+ };++ const columns = useMemo(+ () => createColumns({ updatePermissions }),+ [updatePermissions],+ );++ const table = useReactTable({+ data,+ columns,+ getCoreRowModel: getCoreRowModel(),+ getExpandedRowModel: getExpandedRowModel(),+ getSubRows: (row) => row.subItems,+ initialState: {+ expanded: {+ "0": true, // Always expand the root folder (first row)+ },+ },+ getRowCanExpand: (row) => {+ // Root folder is always expanded and cannot be collapsed+ if (row.original.id === "__dataroom_root__") {+ return true;+ }+ return (row.subRows?.length ?? 0) > 0;+ },+ });++ if (loading) return null;++ return (+ <Sheet open={isOpen} onOpenChange={setIsOpen}>+ <SheetContent className="flex w-[90%] flex-col justify-between border-l border-gray-200 bg-background px-4 text-foreground dark:border-gray-800 dark:bg-gray-900 sm:w-[780px] sm:max-w-3xl md:px-5">+ <SheetHeader className="text-start">+ <SheetTitle>Manage File Permissions</SheetTitle>+ <p className="text-sm text-muted-foreground">+ Configure which files can be viewed and downloaded through this+ link. Use the toggle below to share all dataroom contents or set+ specific permissions.+ </p>+ </SheetHeader>++ <div className="flex-1 overflow-auto py-4">+ {/* Share Entire Dataroom Toggle */}+ <div className="mb-6 rounded-lg border bg-card p-4">+ <div className="flex items-center justify-between">+ <div className="space-y-1">+ <h4 className="text-sm font-medium">Share Entire Dataroom</h4>+ <p className="text-sm text-muted-foreground">+ When enabled, all files and folders will be visible and+ accessible. Turn off to set specific permissions for+ individual items.+ </p>+ </div>+ <Switch+ checked={shareEntireDataroom}+ onCheckedChange={handleShareEntireDataroomToggle}+ />+ </div>+ </div>++ {/* Permissions Table */}+ <div+ className={cn(+ "rounded-md border",+ shareEntireDataroom && "opacity-50",+ )}+ >+ <Table>+ <TableHeader>+ {table.getHeaderGroups().map((headerGroup) => (+ <TableRow key={headerGroup.id}>+ {headerGroup.headers.map((header) => (+ <TableHead+ key={header.id}+ className="py-2 last:text-right"+ >+ {header.isPlaceholder+ ? null+ : flexRender(+ header.column.columnDef.header,+ header.getContext(),+ )}+ </TableHead>+ ))}+ </TableRow>+ ))}+ </TableHeader>+ <TableBody className="transition-all duration-200 ease-in-out">+ {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(+ "transition-all duration-200 ease-in-out",+ 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"+ >+ <div+ className={cn(+ shareEntireDataroom && "pointer-events-none",+ )}+ >+ {flexRender(+ cell.column.columnDef.cell,+ cell.getContext(),+ )}+ </div>+ </TableCell>+ ))}+ </TableRow>+ );+ })+ ) : (+ <TableRow>+ <TableCell+ colSpan={columns.length}+ className="h-24 text-center"+ >+ No files found.+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </Table>+ </div>+ </div>++ <SheetFooter>+ <div className="flex flex-row-reverse items-center gap-2 pt-2">+ <Button+ type="button"+ loading={isSaving}+ onClick={handleSave}+ disabled={+ shareEntireDataroom+ ? false+ : Object.keys(pendingChanges).length === 0+ }+ >+ Save Permissions+ </Button>+ <Button+ type="button"+ variant="outline"+ onClick={() => setIsOpen(false)}+ >+ Cancel+ </Button>+ </div>+ </SheetFooter>+ </SheetContent>+ </Sheet>+ );+}diff --git a/lib/api/links/link-data.ts b/lib/api/links/link-data.tsindex 769d0d1c..de2ee3f2 100644--- a/lib/api/links/link-data.ts+++ b/lib/api/links/link-data.ts@@ -1,4 +1,8 @@-import { ItemType, ViewerGroupAccessControls } from "@prisma/client";+import {+ ItemType,+ PermissionGroupAccessControls,+ ViewerGroupAccessControls,+} from "@prisma/client";import prisma from "@/lib/prisma";import { sortItemsByIndexAndName } from "@/lib/utils/sort-items-by-index-name";@@ -7,22 +11,41 @@ export async function fetchDataroomLinkData({linkId,teamId,groupId,+ permissionGroupId,}: {linkId: string;teamId: string;groupId?: string;+ permissionGroupId?: string;}) {- let groupPermissions: ViewerGroupAccessControls[] = [];+ let groupPermissions:+ | ViewerGroupAccessControls[]+ | PermissionGroupAccessControls[] = [];let documentIds: string[] = [];let folderIds: string[] = [];- if (groupId) {- groupPermissions = await prisma.viewerGroupAccessControls.findMany({- where: {- groupId,- OR: [{ canView: true }, { canDownload: true }],- },- });+ const effectiveGroupId = groupId || permissionGroupId;++ if (effectiveGroupId) {+ // Check if this is a ViewerGroup (legacy) or PermissionGroup+ // First try to find ViewerGroup permissions (for backwards compatibility)+ if (groupId) {+ // This is a ViewerGroup (legacy behavior)+ groupPermissions = await prisma.viewerGroupAccessControls.findMany({+ where: {+ groupId: groupId,+ OR: [{ canView: true }, { canDownload: true }],+ },+ });+ } else if (permissionGroupId) {+ // This is a PermissionGroup (new behavior)+ groupPermissions = await prisma.permissionGroupAccessControls.findMany({+ where: {+ groupId: permissionGroupId,+ OR: [{ canView: true }, { canDownload: true }],+ },+ });+ }documentIds = groupPermissions.filter(@@ -44,7 +67,7 @@ export async function fetchDataroomLinkData({teamId: true,documents: {where:- groupPermissions.length > 0 || groupId+ groupPermissions.length > 0 || effectiveGroupId? { id: { in: documentIds } }: undefined,select: {@@ -83,7 +106,7 @@ export async function fetchDataroomLinkData({},folders: {where:- groupPermissions.length > 0 || groupId+ groupPermissions.length > 0 || effectiveGroupId? { id: { in: folderIds } }: undefined,orderBy: [{ orderIndex: "asc" }, { name: "asc" }],@@ -145,24 +168,49 @@ export async function fetchDataroomDocumentLinkData({teamId,dataroomDocumentId,groupId,+ permissionGroupId,}: {linkId: string;teamId: string;dataroomDocumentId: string;groupId?: string;+ permissionGroupId?: string;}) {- if (groupId) {- const groupPermissions = await prisma.viewerGroupAccessControls.findMany({- where: {- groupId,- itemId: dataroomDocumentId,- itemType: ItemType.DATAROOM_DOCUMENT,- OR: [{ canView: true }, { canDownload: true }],- },- });+ let groupPermissions:+ | ViewerGroupAccessControls[]+ | PermissionGroupAccessControls[] = [];++ const effectiveGroupId = groupId || permissionGroupId;++ if (effectiveGroupId) {+ let hasAccess = false;++ if (groupId) {+ // This is a ViewerGroup (legacy behavior)+ groupPermissions = await prisma.viewerGroupAccessControls.findMany({+ where: {+ groupId: groupId,+ itemId: dataroomDocumentId,+ itemType: ItemType.DATAROOM_DOCUMENT,+ OR: [{ canView: true }, { canDownload: true }],+ },+ });+ hasAccess = groupPermissions.length > 0;+ } else if (permissionGroupId) {+ // This is a PermissionGroup (new behavior)+ groupPermissions = await prisma.permissionGroupAccessControls.findMany({+ where: {+ groupId: permissionGroupId,+ itemId: dataroomDocumentId,+ itemType: ItemType.DATAROOM_DOCUMENT,+ OR: [{ canView: true }, { canDownload: true }],+ },+ });+ hasAccess = groupPermissions.length > 0;+ }- // if it's a group link, we need to check if the document is in the group- if (!groupPermissions || groupPermissions.length === 0) {+ // if it's a group/permission link, we need to check if the document is accessible+ if (!hasAccess) {throw new Error("Document not found in group");}}diff --git a/lib/api/views/send-webhook-event.ts b/lib/api/views/send-webhook-event.tsindex e5c1f984..d68e59b2 100644--- a/lib/api/views/send-webhook-event.ts+++ b/lib/api/views/send-webhook-event.ts@@ -96,6 +96,7 @@ export async function sendLinkViewWebhook({documentId: link.documentId,dataroomId: link.dataroomId,groupId: link.groupId,+ permissionGroupId: link.permissionGroupId,linkType: link.linkType,teamId: teamId,createdAt: link.createdAt.toISOString(),diff --git a/lib/webhook/triggers/link-created.ts b/lib/webhook/triggers/link-created.tsindex 3f7c9de6..378778ed 100644--- a/lib/webhook/triggers/link-created.ts+++ b/lib/webhook/triggers/link-created.ts@@ -95,6 +95,7 @@ export async function sendLinkCreatedWebhook({documentId: link.documentId,dataroomId: link.dataroomId,groupId: link.groupId,+ permissionGroupId: link.permissionGroupId,linkType: link.linkType,teamId: teamId,createdAt: link.createdAt.toISOString(),diff --git a/pages/api/links/[id]/documents/[documentId].ts b/pages/api/links/[id]/documents/[documentId].tsindex ba95bf59..c7cafe09 100644--- a/pages/api/links/[id]/documents/[documentId].ts+++ b/pages/api/links/[id]/documents/[documentId].ts@@ -53,6 +53,7 @@ export default async function handle(enableWatermark: true,watermarkConfig: true,groupId: true,+ permissionGroupId: true,audienceType: true,dataroomId: true,teamId: true,@@ -94,6 +95,7 @@ export default async function handle(linkId: id,teamId: link.teamId!,dataroomDocumentId: dataroomDocumentId,+ permissionGroupId: link.permissionGroupId || undefined,...(link.audienceType === LinkAudienceType.GROUP &&link.groupId && {groupId: link.groupId,diff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.tsindex 69755543..b225e430 100644--- a/pages/api/links/[id]/index.ts+++ b/pages/api/links/[id]/index.ts@@ -61,6 +61,7 @@ export default async function handle(enableWatermark: true,watermarkConfig: true,groupId: true,+ permissionGroupId: true,audienceType: true,teamId: true,team: {@@ -115,6 +116,7 @@ export default async function handle(const data = await fetchDataroomLinkData({linkId: id,teamId: link.teamId!,+ permissionGroupId: link.permissionGroupId || undefined,...(link.audienceType === LinkAudienceType.GROUP &&link.groupId && {groupId: link.groupId,diff --git a/pages/api/links/domains/[...domainSlug].ts b/pages/api/links/domains/[...domainSlug].tsindex 55953a3e..8cd0ab22 100644--- a/pages/api/links/domains/[...domainSlug].ts+++ b/pages/api/links/domains/[...domainSlug].ts@@ -71,6 +71,7 @@ export default async function handle(enableWatermark: true,watermarkConfig: true,groupId: true,+ permissionGroupId: true,audienceType: true,teamId: true,team: {@@ -152,6 +153,7 @@ export default async function handle(linkId: link.id,teamId: link.teamId!,dataroomDocumentId: documentId,+ permissionGroupId: link.permissionGroupId || undefined,...(link.audienceType === LinkAudienceType.GROUP &&link.groupId && {groupId: link.groupId,@@ -163,6 +165,7 @@ export default async function handle(const data = await fetchDataroomLinkData({linkId: link.id,teamId: link.teamId!,+ permissionGroupId: link.permissionGroupId || undefined,...(link.audienceType === LinkAudienceType.GROUP &&link.groupId && {groupId: link.groupId,diff --git a/pages/api/links/download/bulk.ts b/pages/api/links/download/bulk.tsindex 7d4e1214..ddd1d14d 100644--- a/pages/api/links/download/bulk.ts+++ b/pages/api/links/download/bulk.ts@@ -39,6 +39,7 @@ export default async function handle(enableWatermark: true,watermarkConfig: true,name: true,+ permissionGroupId: true,},},groupId: true,@@ -115,14 +116,27 @@ export default async function handle(let downloadFolders = view.dataroom.folders;let downloadDocuments = view.dataroom.documents;- // if groupId is not null,- // we should find the group permissions- // and reduce the number of documents and folders to download- if (view.groupId) {- const groupPermissions =- await prisma.viewerGroupAccessControls.findMany({+ // Check permissions based on groupId (ViewerGroup) or permissionGroupId (PermissionGroup)+ const effectiveGroupId = view.groupId || view.link.permissionGroupId;++ if (effectiveGroupId) {+ let groupPermissions: any[] = [];++ if (view.groupId) {+ // This is a ViewerGroup (legacy behavior)+ groupPermissions = await prisma.viewerGroupAccessControls.findMany({where: { groupId: view.groupId, canDownload: true },});+ } else if (view.link.permissionGroupId) {+ // This is a PermissionGroup (new behavior)+ groupPermissions =+ await prisma.permissionGroupAccessControls.findMany({+ where: {+ groupId: view.link.permissionGroupId,+ canDownload: true,+ },+ });+ }const permittedFolderIds = groupPermissions.filter(diff --git a/pages/api/links/download/dataroom-document.ts b/pages/api/links/download/dataroom-document.tsindex 0b38fa4e..f37d85ed 100644--- a/pages/api/links/download/dataroom-document.ts+++ b/pages/api/links/download/dataroom-document.ts@@ -30,19 +30,20 @@ export default async function handle(viewType: { equals: ViewType.DATAROOM_VIEW },},select: {- viewerId: true,- verified: true,id: true,- viewerEmail: true,viewedAt: true,+ viewerEmail: true,+ viewerId: true,+ verified: true,link: {select: {- enableWatermark: true,allowDownload: true,expiresAt: true,+ isArchived: true,+ enableWatermark: true,watermarkConfig: true,name: true,- isArchived: true,+ permissionGroupId: true,},},groupId: true,@@ -50,17 +51,17 @@ export default async function handle(select: {id: true,documents: {- where: {- documentId: documentId,- },+ where: { document: { id: documentId } },select: {id: true,document: {select: {+ id: true,name: true,versions: {where: { isPrimary: true },select: {+ id: true,type: true,file: true,storageType: true,@@ -114,14 +115,27 @@ export default async function handle(let downloadDocuments = view.dataroom.documents;- // if groupId is not null,- // we should find the group permissions- // and reduce the number of documents and folders to download- if (view.groupId) {- const groupPermissions =- await prisma.viewerGroupAccessControls.findMany({+ // Check permissions based on groupId (ViewerGroup) or permissionGroupId (PermissionGroup)+ const effectiveGroupId = view.groupId || view.link.permissionGroupId;++ if (effectiveGroupId) {+ let groupPermissions: any[] = [];++ if (view.groupId) {+ // This is a ViewerGroup (legacy behavior)+ groupPermissions = await prisma.viewerGroupAccessControls.findMany({where: { groupId: view.groupId, canDownload: true },});+ } else if (view.link.permissionGroupId) {+ // This is a PermissionGroup (new behavior)+ groupPermissions =+ await prisma.permissionGroupAccessControls.findMany({+ where: {+ groupId: view.link.permissionGroupId,+ canDownload: true,+ },+ });+ }const permittedDocumentIds = groupPermissions.filter(diff --git a/pages/api/links/download/dataroom-folder.ts b/pages/api/links/download/dataroom-folder.tsindex 32a965ad..9745ab5c 100644--- a/pages/api/links/download/dataroom-folder.ts+++ b/pages/api/links/download/dataroom-folder.ts@@ -47,6 +47,7 @@ export default async function handler(allowDownload: true,expiresAt: true,isArchived: true,+ permissionGroupId: true,},},groupId: true,@@ -130,11 +131,23 @@ export default async function handler(},});- // Check group permissions if groupId is provided- if (view?.groupId) {- const groupPermissions = await prisma.viewerGroupAccessControls.findMany({- where: { groupId: view.groupId, canDownload: true },- });+ // Check permissions based on groupId (ViewerGroup) or permissionGroupId (PermissionGroup)+ const effectiveGroupId = view.groupId || view.link.permissionGroupId;++ if (effectiveGroupId) {+ let groupPermissions: any[] = [];++ if (view.groupId) {+ // This is a ViewerGroup (legacy behavior)+ groupPermissions = await prisma.viewerGroupAccessControls.findMany({+ where: { groupId: view.groupId, canDownload: true },+ });+ } else if (view.link.permissionGroupId) {+ // This is a PermissionGroup (new behavior)+ groupPermissions = await prisma.permissionGroupAccessControls.findMany({+ where: { groupId: view.link.permissionGroupId, canDownload: true },+ });+ }const permittedFolderIds = groupPermissions.filter(diff --git a/pages/api/teams/[teamId]/datarooms/[id]/permission-groups/[permissionGroupId].ts b/pages/api/teams/[teamId]/datarooms/[id]/permission-groups/[permissionGroupId].tsnew file mode 100644index 00000000..e4079258--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/permission-groups/[permissionGroupId].ts@@ -0,0 +1,293 @@+import { NextApiRequest, NextApiResponse } from "next";++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";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ // GET /api/teams/:teamId/datarooms/:id/permission-groups/:permissionGroupId+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const {+ teamId,+ id: dataroomId,+ permissionGroupId,+ } = req.query as {+ teamId: string;+ id: string;+ permissionGroupId: string;+ };++ const userId = (session.user as CustomUser).id;++ try {+ // Verify team membership+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: { userId },+ },+ },+ });++ if (!team) {+ return res.status(401).end("Unauthorized");+ }++ // Fetch permission group with access controls+ const permissionGroup = await prisma.permissionGroup.findUnique({+ where: {+ id: permissionGroupId,+ dataroomId: dataroomId,+ teamId: teamId,+ },+ include: {+ accessControls: {+ select: {+ id: true,+ itemId: true,+ itemType: true,+ canView: true,+ canDownload: true,+ canDownloadOriginal: true,+ },+ },+ },+ });++ if (!permissionGroup) {+ return res.status(404).json({ error: "Permission group not found" });+ }++ return res.status(200).json({ permissionGroup });+ } catch (error) {+ errorhandler(error, res);+ }+ } else if (req.method === "PUT") {+ // PUT /api/teams/:teamId/datarooms/:id/permission-groups/:permissionGroupId+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const {+ teamId,+ id: dataroomId,+ permissionGroupId,+ } = req.query as {+ teamId: string;+ id: string;+ permissionGroupId: string;+ };++ const { permissions } = req.body;++ const userId = (session.user as CustomUser).id;++ try {+ // Verify team membership+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: { userId },+ },+ },+ });++ if (!team) {+ return res.status(401).end("Unauthorized");+ }++ // Verify dataroom exists and belongs to team+ const dataroom = await prisma.dataroom.findUnique({+ where: {+ id: dataroomId,+ teamId: teamId,+ },+ });++ if (!dataroom) {+ return res.status(404).json({ error: "Dataroom not found" });+ }++ // Verify permission group exists and belongs to dataroom+ const permissionGroup = await prisma.permissionGroup.findUnique({+ where: {+ id: permissionGroupId,+ dataroomId: dataroomId,+ teamId: teamId,+ },+ });++ if (!permissionGroup) {+ return res.status(404).json({ error: "Permission group not found" });+ }++ // Update permission group access controls using a transaction+ const updatedPermissionGroup = await prisma.$transaction(async (tx) => {+ if (permissions && typeof permissions === "object") {+ // Get existing access controls to determine what needs to be updated vs created+ const existingControls =+ await tx.permissionGroupAccessControls.findMany({+ where: {+ groupId: permissionGroupId,+ },+ select: {+ itemId: true,+ itemType: true,+ canView: true,+ canDownload: true,+ canDownloadOriginal: true,+ },+ });++ const existingMap = new Map(+ existingControls.map((control) => [+ `${control.itemId}-${control.itemType}`,+ control,+ ]),+ );++ const toUpdate: Array<{+ itemId: string;+ itemType: any;+ canView: boolean;+ canDownload: boolean;+ canDownloadOriginal: boolean;+ }> = [];++ const toCreate: Array<{+ groupId: string;+ itemId: string;+ itemType: any;+ canView: boolean;+ canDownload: boolean;+ canDownloadOriginal: boolean;+ }> = [];++ // Categorize permissions into updates vs creates+ Object.entries(permissions).forEach(+ ([itemId, permission]: [string, any]) => {+ const key = `${itemId}-${permission.itemType}`;+ const existing = existingMap.get(key);++ const permissionData = {+ itemId,+ itemType: permission.itemType,+ canView: permission.view,+ canDownload: permission.download,+ canDownloadOriginal: permission.download,+ };++ if (existing) {+ // Check if anything actually changed+ if (+ existing.canView !== permission.view ||+ existing.canDownload !== permission.download+ ) {+ toUpdate.push(permissionData);+ }+ } else {+ toCreate.push({+ groupId: permissionGroupId,+ ...permissionData,+ });+ }+ },+ );++ // Perform updates+ if (toUpdate.length > 0) {+ await Promise.all(+ toUpdate.map((item) =>+ tx.permissionGroupAccessControls.updateMany({+ where: {+ groupId: permissionGroupId,+ itemId: item.itemId,+ itemType: item.itemType,+ },+ data: {+ canView: item.canView,+ canDownload: item.canDownload,+ canDownloadOriginal: item.canDownloadOriginal,+ },+ }),+ ),+ );+ }++ // Perform creates+ if (toCreate.length > 0) {+ await tx.permissionGroupAccessControls.createMany({+ data: toCreate,+ });+ }++ // Remove permissions that are no longer in the new set+ const newItemKeys = new Set(+ Object.entries(permissions).map(+ ([itemId, permission]: [string, any]) =>+ `${itemId}-${permission.itemType}`,+ ),+ );++ const toDelete = existingControls.filter(+ (control) =>+ !newItemKeys.has(`${control.itemId}-${control.itemType}`),+ );++ if (toDelete.length > 0) {+ await Promise.all(+ toDelete.map((item) =>+ tx.permissionGroupAccessControls.deleteMany({+ where: {+ groupId: permissionGroupId,+ itemId: item.itemId,+ itemType: item.itemType,+ },+ }),+ ),+ );+ }+ }++ // Return the updated permission group with access controls+ return await tx.permissionGroup.findUnique({+ where: { id: permissionGroupId },+ include: {+ accessControls: {+ select: {+ id: true,+ itemId: true,+ itemType: true,+ canView: true,+ canDownload: true,+ canDownloadOriginal: true,+ },+ },+ },+ });+ });++ return res.status(200).json({ permissionGroup: updatedPermissionGroup });+ } catch (error) {+ errorhandler(error, res);+ }+ }++ // We only allow GET requests+ res.setHeader("Allow", ["GET", "PUT"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/permission-groups/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/permission-groups/index.tsnew file mode 100644index 00000000..79f6adb2--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/permission-groups/index.ts@@ -0,0 +1,116 @@+import { NextApiRequest, NextApiResponse } from "next";++import { ItemType } from "@prisma/client";+import { getServerSession } from "next-auth/next";++import { errorhandler } from "@/lib/errorHandler";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++import { authOptions } from "../../../../../auth/[...nextauth]";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "POST") {+ // POST /api/teams/:teamId/datarooms/:id/permission-groups+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const { teamId, id: dataroomId } = req.query as {+ teamId: string;+ id: string;+ };+ const { permissions, linkId } = req.body;++ const userId = (session.user as CustomUser).id;++ try {+ // Verify team membership+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: { userId },+ },+ },+ });++ if (!team) {+ return res.status(401).end("Unauthorized");+ }++ // Verify dataroom exists and belongs to team+ const dataroom = await prisma.dataroom.findUnique({+ where: {+ id: dataroomId,+ teamId: teamId,+ },+ });++ if (!dataroom) {+ return res.status(404).json({ error: "Dataroom not found" });+ }++ // Create permission group and access controls in a transaction+ const result = await prisma.$transaction(async (tx) => {+ // Create the permission group+ const permissionGroup = await tx.permissionGroup.create({+ data: {+ name: `Link Permissions ${Date.now()}`,+ description: "Auto-generated permission group for link",+ dataroomId: dataroomId,+ teamId: teamId,+ },+ });++ // Create access controls for each permission+ const accessControls = [];+ for (const [itemId, permission] of Object.entries(permissions)) {+ const perm = permission as {+ view: boolean;+ download: boolean;+ itemType: ItemType;+ };+ const accessControl = await tx.permissionGroupAccessControls.create({+ data: {+ groupId: permissionGroup.id,+ itemId: itemId,+ itemType: perm.itemType,+ canView: perm.view,+ canDownload: perm.download,+ canDownloadOriginal: false,+ },+ });+ accessControls.push(accessControl);+ }++ // Update the link with the permission group+ if (linkId) {+ await tx.link.update({+ where: { id: linkId },+ data: {+ permissionGroupId: permissionGroup.id,+ },+ });+ }++ return {+ permissionGroup,+ accessControls,+ };+ });++ return res.status(200).json(result);+ } catch (error) {+ errorhandler(error, res);+ }+ }++ // We only allow POST requests+ res.setHeader("Allow", ["POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+}