Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat(ee): add dataroom invites

Marc Seitzb5fd6f4ac130
diff --git a/components/datarooms/groups/group-member-table.tsx b/components/datarooms/groups/group-member-table.tsx
index daafb10d..992c39e9 100644
--- a/components/datarooms/groups/group-member-table.tsx
+++ b/components/datarooms/groups/group-member-table.tsx
@@ -4,14 +4,19 @@ import { useTeam } from "@/context/team-context";
import {
MoreHorizontalIcon,
PlusCircleIcon,
+ SendIcon,
UserXIcon,
XIcon,
} from "lucide-react";
import { toast } from "sonner";
import { mutate } from "swr";
+import { useDataroom } from "@/lib/swr/use-dataroom";
import { useDataroomGroup } from "@/lib/swr/use-dataroom-groups";
+import { useUninvitedMembers } from "@/ee/features/dataroom-invitations/lib/swr/use-dataroom-invitations";
+import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";
+import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@@ -33,6 +38,7 @@ import {
} from "@/components/ui/table";
import { VisitorAvatar } from "@/components/visitors/visitor-avatar";
+import { InviteViewersModal } from "../invite-viewers-modal";
import { AddGroupMemberModal } from "./add-member-modal";
export default function GroupMemberTable({
@@ -44,13 +50,27 @@ export default function GroupMemberTable({
}) {
const teamInfo = useTeam();
const teamId = teamInfo?.currentTeam?.id;
+ const { dataroom } = useDataroom();
const { viewerGroupMembers, viewerGroupDomains, viewerGroupAllowAll } =
useDataroomGroup();
+ const {
+ uninvitedCount,
+ uninvitedEmails,
+ mutate: mutateUninvited,
+ } = useUninvitedMembers(dataroomId, groupId);
+ const { isFeatureEnabled } = useFeatureFlags();
const [addMembersOpen, setAddMembersOpen] = useState<boolean>(false);
+ const [inviteOpen, setInviteOpen] = useState<boolean>(false);
+
+ const groupKey = teamId
+ ? `/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}`
+ : null;
const handleToggleAllowAll = async () => {
- const key = `/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}`;
+ const key =
+ groupKey ??
+ `/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}`;
const response = await fetch(
`/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}`,
{
@@ -78,7 +98,9 @@ export default function GroupMemberTable({
};
const handleRemoveDomain = async (domain: string) => {
- const key = `/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}`;
+ const key =
+ groupKey ??
+ `/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}`;
const response = await fetch(
`/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}`,
{
@@ -103,7 +125,9 @@ export default function GroupMemberTable({
const handleRemoveMember = async (id: string) => {
// mutate the data optimistically
- const key = `/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}`;
+ const key =
+ groupKey ??
+ `/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}`;
mutate(
key,
(currentData: { members: any[] } | undefined) => {
@@ -135,131 +159,146 @@ export default function GroupMemberTable({
};
return (
- <div className="l">
- <div className="mb-2 flex items-center justify-between md:mb-4">
- <h2>All members</h2>
- <div className="flex items-center gap-4">
- <div className="flex items-center gap-2">
- <Switch
- checked={viewerGroupAllowAll}
- onCheckedChange={handleToggleAllowAll}
- aria-label="Allow all emails"
- />
- <span className="text-sm text-muted-foreground">
- Allow all emails
- </span>
+ <>
+ <div className="l">
+ <div className="mb-2 flex items-center justify-between md:mb-4">
+ <h2>All members</h2>
+ <div className="flex items-center gap-4">
+ <div className="flex items-center gap-2">
+ <Switch
+ checked={viewerGroupAllowAll}
+ onCheckedChange={handleToggleAllowAll}
+ aria-label="Allow all emails"
+ />
+ <span className="text-sm text-muted-foreground">
+ Allow all emails
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <Button
+ size="sm"
+ onClick={() => setAddMembersOpen(true)}
+ className="h-8 gap-1"
+ disabled={viewerGroupAllowAll}
+ >
+ <PlusCircleIcon className="h-4 w-4" />
+ Add members
+ </Button>
+ {isFeatureEnabled("dataroomInvitations") && (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => setInviteOpen(true)}
+ className="relative h-8 gap-1"
+ >
+ <SendIcon className="h-4 w-4" />
+ Share invite
+ {uninvitedCount > 0 ? (
+ <Badge
+ variant="secondary"
+ className="ml-2 h-5 rounded-full px-2 text-xs font-medium"
+ >
+ {uninvitedCount}
+ </Badge>
+ ) : null}
+ </Button>
+ )}
+ </div>
</div>
- <Button
- size="sm"
- onClick={() => setAddMembersOpen(true)}
- className="h-8 gap-1"
- disabled={viewerGroupAllowAll}
- >
- <PlusCircleIcon className="h-4 w-4" />
- Add members
- </Button>
</div>
- </div>
- <AddGroupMemberModal
- dataroomId={dataroomId}
- groupId={groupId}
- open={addMembersOpen}
- setOpen={setAddMembersOpen}
- />
-
- <div className="rounded-md border">
- <Table>
- <TableHeader>
- <TableRow className="*:whitespace-nowrap *:font-medium hover:bg-transparent">
- <TableHead>Name</TableHead>
- {/* <TableHead>Visit Duration</TableHead> */}
- {/* <TableHead>Last Viewed Document</TableHead> */}
- {/* <TableHead>Last Viewed</TableHead> */}
- <TableHead className="text-center"></TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {viewerGroupAllowAll ? (
- <TableRow>
- <TableCell colSpan={2}>
- <div className="flex h-40 w-full items-center justify-center">
- <p className="text-sm text-muted-foreground">
- All email addresses are allowed to access this group
- </p>
- </div>
- </TableCell>
+ <div className="rounded-md border">
+ <Table>
+ <TableHeader>
+ <TableRow className="*:whitespace-nowrap *:font-medium hover:bg-transparent">
+ <TableHead>Name</TableHead>
+ {/* <TableHead>Visit Duration</TableHead> */}
+ {/* <TableHead>Last Viewed Document</TableHead> */}
+ {/* <TableHead>Last Viewed</TableHead> */}
+ <TableHead className="text-center"></TableHead>
</TableRow>
- ) : viewerGroupMembers.length === 0 &&
- viewerGroupDomains.length === 0 ? (
- <TableRow>
- <TableCell colSpan={2}>
- <div className="flex h-40 w-full items-center justify-center">
- <p>No views yet. Try sharing a link.</p>
- </div>
- </TableCell>
- </TableRow>
- ) : (
- <>
- {viewerGroupDomains.length > 0 &&
- viewerGroupDomains.map((domain) => (
- <TableRow key={domain} className="group/row">
- <TableCell className="">
- <div className="flex items-center overflow-visible sm:space-x-3">
- <VisitorAvatar viewerEmail={"@"} />
- <div className="min-w-0 flex-1">
- <div className="focus:outline-none">
- <p className="flex items-center gap-x-2 overflow-visible text-sm font-medium text-gray-800 dark:text-gray-200">
- {domain}
- </p>
+ </TableHeader>
+ <TableBody>
+ {viewerGroupAllowAll ? (
+ <TableRow>
+ <TableCell colSpan={2}>
+ <div className="flex h-40 w-full items-center justify-center">
+ <p className="text-sm text-muted-foreground">
+ All email addresses are allowed to access this group
+ </p>
+ </div>
+ </TableCell>
+ </TableRow>
+ ) : viewerGroupMembers.length === 0 &&
+ viewerGroupDomains.length === 0 ? (
+ <TableRow>
+ <TableCell colSpan={2}>
+ <div className="flex h-40 w-full items-center justify-center">
+ <p>No views yet. Try sharing a link.</p>
+ </div>
+ </TableCell>
+ </TableRow>
+ ) : (
+ <>
+ {viewerGroupDomains.length > 0 &&
+ viewerGroupDomains.map((domain) => (
+ <TableRow key={domain} className="group/row">
+ <TableCell className="">
+ <div className="flex items-center overflow-visible sm:space-x-3">
+ <VisitorAvatar viewerEmail={"@"} />
+ <div className="min-w-0 flex-1">
+ <div className="focus:outline-none">
+ <p className="flex items-center gap-x-2 overflow-visible text-sm font-medium text-gray-800 dark:text-gray-200">
+ {domain}
+ </p>
+ </div>
</div>
</div>
- </div>
- </TableCell>
- {/* Actions */}
- <TableCell className="p-0 text-center">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- className="h-8 w-8 p-0 group-hover/row:ring-1 group-hover/row:ring-gray-200 group-hover/row:dark:ring-gray-700"
- >
- <span className="sr-only">Open menu</span>
- <MoreHorizontalIcon className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuLabel>Actions</DropdownMenuLabel>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- className="gap-x-2 text-destructive focus:bg-destructive focus:text-destructive-foreground"
- onClick={() => handleRemoveDomain(domain)}
- >
- <XIcon className="h-4 w-4" />
- Remove Domain
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </TableCell>
- </TableRow>
- ))}
- {viewerGroupMembers ? (
- viewerGroupMembers.map((viewer) => (
- <TableRow key={viewer.id} className="group/row">
- {/* Name */}
- <TableCell className="">
- <div className="flex items-center overflow-visible sm:space-x-3">
- <VisitorAvatar viewerEmail={viewer.viewer.email} />
- <div className="min-w-0 flex-1">
- <div className="focus:outline-none">
- <p className="flex items-center gap-x-2 overflow-visible text-sm font-medium text-gray-800 dark:text-gray-200">
- {viewer.viewer.email}
- </p>
+ </TableCell>
+ {/* Actions */}
+ <TableCell className="p-0 text-center">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ className="h-8 w-8 p-0 group-hover/row:ring-1 group-hover/row:ring-gray-200 group-hover/row:dark:ring-gray-700"
+ >
+ <span className="sr-only">Open menu</span>
+ <MoreHorizontalIcon className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ className="gap-x-2 text-destructive focus:bg-destructive focus:text-destructive-foreground"
+ onClick={() => handleRemoveDomain(domain)}
+ >
+ <XIcon className="h-4 w-4" />
+ Remove Domain
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ ))}
+ {viewerGroupMembers ? (
+ viewerGroupMembers.map((viewer) => (
+ <TableRow key={viewer.id} className="group/row">
+ {/* Name */}
+ <TableCell className="">
+ <div className="flex items-center overflow-visible sm:space-x-3">
+ <VisitorAvatar viewerEmail={viewer.viewer.email} />
+ <div className="min-w-0 flex-1">
+ <div className="focus:outline-none">
+ <p className="flex items-center gap-x-2 overflow-visible text-sm font-medium text-gray-800 dark:text-gray-200">
+ {viewer.viewer.email}
+ </p>
+ </div>
</div>
</div>
- </div>
- </TableCell>
- {/* Last Viewed */}
- {/* <TableCell className="text-sm text-muted-foreground">
+ </TableCell>
+ {/* Last Viewed */}
+ {/* <TableCell className="text-sm text-muted-foreground">
<time
dateTime={new Date(viewer.viewer.updatedAt).toISOString()}
>
@@ -268,48 +307,76 @@ export default function GroupMemberTable({
: "-"}
</time>
</TableCell> */}
- {/* Actions */}
- <TableCell className="p-0 text-center">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- className="h-8 w-8 p-0 group-hover/row:ring-1 group-hover/row:ring-gray-200 group-hover/row:dark:ring-gray-700"
- >
- <span className="sr-only">Open menu</span>
- <MoreHorizontalIcon className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuLabel>Actions</DropdownMenuLabel>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- className="gap-x-2 text-destructive focus:bg-destructive focus:text-destructive-foreground"
- onClick={() => handleRemoveMember(viewer.id)}
- >
- <UserXIcon className="h-4 w-4" />
- Remove Member
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ {/* Actions */}
+ <TableCell className="p-0 text-center">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ className="h-8 w-8 p-0 group-hover/row:ring-1 group-hover/row:ring-gray-200 group-hover/row:dark:ring-gray-700"
+ >
+ <span className="sr-only">Open menu</span>
+ <MoreHorizontalIcon className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ className="gap-x-2 text-destructive focus:bg-destructive focus:text-destructive-foreground"
+ onClick={() => handleRemoveMember(viewer.id)}
+ >
+ <UserXIcon className="h-4 w-4" />
+ Remove Member
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell className="min-w-[100px]">
+ <Skeleton className="h-6 w-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-6 w-24" />
</TableCell>
</TableRow>
- ))
- ) : (
- <TableRow>
- <TableCell className="min-w-[100px]">
- <Skeleton className="h-6 w-full" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-6 w-24" />
- </TableCell>
- </TableRow>
- )}
- </>
- )}
- </TableBody>
- </Table>
+ )}
+ </>
+ )}
+ </TableBody>
+ </Table>
+ </div>
</div>
- </div>
+ <AddGroupMemberModal
+ dataroomId={dataroomId}
+ groupId={groupId}
+ open={addMembersOpen}
+ setOpen={setAddMembersOpen}
+ />
+ {isFeatureEnabled("dataroomInvitations") && (
+ <InviteViewersModal
+ open={inviteOpen}
+ setOpen={(next) => {
+ setInviteOpen(next);
+ if (!next) {
+ mutateUninvited();
+ }
+ }}
+ dataroomId={dataroomId}
+ dataroomName={dataroom?.name ?? "this dataroom"}
+ groupId={groupId}
+ defaultEmails={uninvitedEmails}
+ onSuccess={() => {
+ if (groupKey) {
+ mutate(groupKey);
+ }
+ mutateUninvited();
+ }}
+ />
+ )}
+ </>
);
}
diff --git a/components/datarooms/invite-viewers-modal.tsx b/components/datarooms/invite-viewers-modal.tsx
new file mode 100644
index 00000000..52967352
--- /dev/null
+++ b/components/datarooms/invite-viewers-modal.tsx
@@ -0,0 +1,428 @@
+import { useEffect, useMemo, useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { invitationEmailSchema } from "@/ee/features/dataroom-invitations/lib/schema/dataroom-invitations";
+import { useUninvitedMembers } from "@/ee/features/dataroom-invitations/lib/swr/use-dataroom-invitations";
+import { Link } from "@prisma/client";
+import { useSession } from "next-auth/react";
+import { toast } from "sonner";
+import useSWR from "swr";
+
+import { fetcher } from "@/lib/utils";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Separator } from "@/components/ui/separator";
+import { Textarea } from "@/components/ui/textarea";
+
+type InviteViewersModalProps = {
+ open: boolean;
+ setOpen: (open: boolean) => void;
+ dataroomId: string;
+ dataroomName: string;
+ groupId?: string;
+ linkId?: string;
+ defaultEmails?: string[];
+ onSuccess?: () => void;
+};
+
+type LinkOption = Pick<
+ Link,
+ "id" | "name" | "domainId" | "domainSlug" | "slug"
+>;
+
+function parseRecipientInput(value: string) {
+ return Array.from(
+ new Set(
+ value
+ .split(/[\s,]+/)
+ .map((email) => email.trim())
+ .filter((email) => email.length > 0),
+ ),
+ );
+}
+
+export function InviteViewersModal({
+ open,
+ setOpen,
+ dataroomId,
+ dataroomName,
+ groupId,
+ linkId,
+ defaultEmails = [],
+ onSuccess,
+}: InviteViewersModalProps) {
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+ const { data: session } = useSession();
+ const senderEmail = session?.user?.email ?? "you";
+
+ const { data: groupLinks } = useSWR<LinkOption[]>(
+ groupId && teamId
+ ? `/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}/links`
+ : null,
+ fetcher,
+ {
+ dedupingInterval: 10000,
+ },
+ );
+ const { uninvitedEmails, mutate: mutateUninvited } = useUninvitedMembers(
+ groupId ? dataroomId : undefined,
+ groupId,
+ );
+
+ const availableLinks: LinkOption[] = useMemo(() => {
+ if (groupId) {
+ return (
+ groupLinks?.map((link) => {
+ const identifier = link.slug || link.id;
+ const last5 = identifier.slice(-5);
+ return {
+ id: link.id,
+ name: link.name || `Link #${last5}`,
+ domainId: link.domainId,
+ domainSlug: link.domainSlug,
+ slug: link.slug,
+ };
+ }) ?? []
+ );
+ }
+
+ return linkId
+ ? [
+ {
+ id: linkId,
+ name: `Link #${linkId.slice(-5)}`,
+ domainId: null,
+ domainSlug: null,
+ slug: null,
+ },
+ ]
+ : [];
+ }, [groupId, groupLinks, linkId]);
+
+ const [selectedLinkId, setSelectedLinkId] = useState<string | undefined>(
+ () => linkId ?? availableLinks[0]?.id,
+ );
+ const [customMessage, setCustomMessage] = useState<string>("");
+ const [recipientInput, setRecipientInput] = useState<string>("");
+ const [hasEditedRecipients, setHasEditedRecipients] =
+ useState<boolean>(false);
+ const [loading, setLoading] = useState<boolean>(false);
+
+ useEffect(() => {
+ if (!open) {
+ setCustomMessage("");
+ setRecipientInput("");
+ setHasEditedRecipients(false);
+ setSelectedLinkId(linkId ?? availableLinks[0]?.id);
+ return;
+ }
+
+ if (!hasEditedRecipients) {
+ const initialRecipients =
+ defaultEmails.length > 0
+ ? defaultEmails
+ : groupId
+ ? uninvitedEmails
+ : [];
+
+ if (initialRecipients.length > 0) {
+ setRecipientInput(initialRecipients.join("\n"));
+ }
+ }
+ }, [
+ open,
+ linkId,
+ availableLinks,
+ groupId,
+ uninvitedEmails,
+ defaultEmails,
+ hasEditedRecipients,
+ ]);
+
+ useEffect(() => {
+ if (!open) {
+ setSelectedLinkId(linkId ?? availableLinks[0]?.id);
+ }
+ }, [open, linkId, availableLinks]);
+
+ const selectedLink = availableLinks.find(
+ (link) => link.id === selectedLinkId,
+ );
+
+ const defaultRecipients =
+ defaultEmails.length > 0 ? defaultEmails : groupId ? uninvitedEmails : [];
+
+ const fallbackSubject = `You are invited to view ${dataroomName}`;
+
+ const handleClose = () => {
+ setOpen(false);
+ setLoading(false);
+ };
+
+ const handleSend = async () => {
+ if (!teamId) {
+ toast.error("No active team selected");
+ return;
+ }
+
+ if (groupId && !selectedLinkId) {
+ toast.error("Select a link to include in the invitation");
+ return;
+ }
+
+ const parsedEmails = hasEditedRecipients
+ ? parseRecipientInput(recipientInput)
+ : [];
+
+ if (parsedEmails.length > 0) {
+ const invalidEmails = parsedEmails.filter(
+ (email) => !invitationEmailSchema.safeParse(email).success,
+ );
+
+ if (invalidEmails.length > 0) {
+ toast.error(
+ `Found invalid emails: ${invalidEmails
+ .slice(0, 3)
+ .join(", ")}${invalidEmails.length > 3 ? "..." : ""}`,
+ );
+ return;
+ }
+ }
+
+ const endpoint = groupId
+ ? `/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}/invite`
+ : linkId
+ ? `/api/teams/${teamId}/datarooms/${dataroomId}/links/${linkId}/invite`
+ : null;
+
+ if (!endpoint) {
+ toast.error("Unable to determine invitation endpoint");
+ return;
+ }
+
+ setLoading(true);
+
+ try {
+ const response = await fetch(endpoint, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ ...(groupId ? { linkId: selectedLinkId } : {}),
+ customMessage: customMessage.length > 0 ? customMessage : undefined,
+ emails: parsedEmails.length > 0 ? parsedEmails : undefined,
+ }),
+ });
+
+ if (!response.ok) {
+ const payload = await response.json().catch(() => null);
+ throw new Error(payload?.error ?? "Failed to send invitations");
+ }
+
+ const payload = await response.json();
+ const sentCount = payload?.success?.length ?? 0;
+ const failedCount = payload?.failed?.length ?? 0;
+
+ if (sentCount > 0) {
+ toast.success(
+ `Invitation${sentCount > 1 ? "s" : ""} sent to ${sentCount} recipient${
+ sentCount > 1 ? "s" : ""
+ }.`,
+ );
+ }
+
+ if (failedCount > 0) {
+ toast.error(
+ `Failed to send to ${failedCount} recipient${
+ failedCount > 1 ? "s" : ""
+ }.`,
+ );
+ }
+
+ onSuccess?.();
+ if (groupId) {
+ mutateUninvited();
+ }
+ handleClose();
+ } catch (error: any) {
+ toast.error(error?.message ?? "Failed to send invitations");
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-xl">
+ <DialogHeader className="text-left">
+ <DialogTitle>Share invitation</DialogTitle>
+ </DialogHeader>
+
+ <div className="space-y-4">
+ {groupId ? (
+ <div className="space-y-2">
+ <span className="text-sm font-medium text-muted-foreground">
+ Choose link
+ </span>
+ <Select
+ value={selectedLinkId}
+ onValueChange={setSelectedLinkId}
+ disabled={loading}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select a link" />
+ </SelectTrigger>
+ <SelectContent>
+ {availableLinks.map((link) => (
+ <SelectItem key={link.id} value={link.id}>
+ {link.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ ) : null}
+
+ <div className="space-y-2">
+ <span className="text-sm font-medium text-muted-foreground">
+ Custom message
+ </span>
+ <Textarea
+ value={customMessage}
+ onChange={(event) => setCustomMessage(event.target.value)}
+ rows={4}
+ maxLength={500}
+ placeholder="Add a short personal message (optional)"
+ className="bg-muted"
+ disabled={loading}
+ />
+ <p className="text-xs text-muted-foreground">
+ {customMessage.length}/500 characters
+ </p>
+ </div>
+
+ <div className="space-y-2">
+ <span className="text-sm font-medium text-muted-foreground">
+ Recipients
+ </span>
+ <Textarea
+ value={recipientInput}
+ onChange={(event) => {
+ setRecipientInput(event.target.value);
+ setHasEditedRecipients(true);
+ }}
+ placeholder={
+ defaultRecipients.length > 0
+ ? defaultRecipients.join("\n")
+ : "Enter email addresses separated by comma or new line (leave empty to use allowed visitors)"
+ }
+ className="bg-muted"
+ rows={4}
+ disabled={loading}
+ />
+ <p className="text-xs text-muted-foreground">
+ Leave blank to invite{" "}
+ {defaultRecipients.length > 0
+ ? `${defaultRecipients.length} uninvited member${
+ defaultRecipients.length !== 1 ? "s" : ""
+ }`
+ : "all allowed visitors"}
+ .
+ </p>
+ </div>
+
+ <Separator />
+
+ <div className="space-y-2 rounded-md border bg-muted/40 p-4 text-sm text-muted-foreground">
+ <div>
+ <p className="font-medium text-foreground">Email preview</p>
+ <p className="text-xs text-muted-foreground">
+ Sent from Papermark system email
+ </p>
+ </div>
+
+ <div className="space-y-1">
+ <p>
+ <span className="font-medium">Subject:</span> {fallbackSubject}
+ </p>
+ <p>
+ <span className="font-medium">From:</span> {senderEmail}
+ </p>
+ <p>
+ <span className="font-medium">To:</span>{" "}
+ {hasEditedRecipients && recipientInput.length > 0
+ ? parseRecipientInput(recipientInput).join(", ")
+ : defaultRecipients.join(", ") || "Selected visitors"}
+ </p>
+ </div>
+
+ <Separator />
+
+ <div className="space-y-2 text-muted-foreground">
+ <p>Hey!</p>
+ <p>
+ You have been invited to view the{" "}
+ <span className="font-semibold text-foreground">
+ {dataroomName}
+ </span>{" "}
+ dataroom on{" "}
+ <span className="font-semibold text-foreground">Papermark</span>
+ . The invitation was sent by{" "}
+ <span className="font-semibold text-foreground">
+ {senderEmail}
+ </span>
+ .
+ </p>
+ {customMessage.length > 0 ? (
+ <p className="whitespace-pre-wrap text-foreground">
+ {customMessage}
+ </p>
+ ) : null}
+ <p>
+ Click the button below to access the dataroom.
+ {selectedLink
+ ? ` Link ID: ${selectedLink.slug ?? selectedLink.id}`
+ : ""}
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <div className="flex w-full flex-col gap-2 sm:flex-row sm:justify-end">
+ <Button
+ variant="outline"
+ type="button"
+ onClick={handleClose}
+ disabled={loading}
+ >
+ Cancel
+ </Button>
+ <Button
+ onClick={handleSend}
+ loading={loading}
+ disabled={groupId ? !selectedLinkId || loading : loading}
+ >
+ {loading ? "Sending invitations..." : "Send invitations"}
+ </Button>
+ </div>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/links/links-table.tsx b/components/links/links-table.tsx
index 3ecdc749..a2dde438 100644
--- a/components/links/links-table.tsx
+++ b/components/links/links-table.tsx
@@ -13,6 +13,7 @@ import {
EyeIcon,
FileSlidersIcon,
LinkIcon,
+ SendIcon,
Settings2Icon,
Trash2Icon,
} from "lucide-react";
@@ -26,8 +27,11 @@ import useLimits from "@/lib/swr/use-limits";
import { LinkWithViews, WatermarkConfig } from "@/lib/types";
import { cn, copyToClipboard, nFormatter, timeAgo } from "@/lib/utils";
import { useMediaQuery } from "@/lib/utils/use-media-query";
+import { invitationEmailSchema } from "@/ee/features/dataroom-invitations/lib/schema/dataroom-invitations";
+import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";
import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";
+import { InviteViewersModal } from "@/components/datarooms/invite-viewers-modal";
import { Button } from "@/components/ui/button";
import {
Collapsible,
@@ -93,11 +97,13 @@ export default function LinksTable({
links,
primaryVersion,
mutateDocument,
+ dataroomName,
}: {
targetType: "DOCUMENT" | "DATAROOM";
links?: LinkWithViews[];
primaryVersion?: DocumentVersion;
mutateDocument?: () => void;
+ dataroomName?: string;
}) {
const [tags, _] = useQueryState<string[]>("tags", {
parse: (value: string) => value.split(",").filter(Boolean),
@@ -116,6 +122,7 @@ export default function LinksTable({
};
const { isMobile } = useMediaQuery();
+ const { isFeatureEnabled } = useFeatureFlags();
let processedLinks = useMemo(() => {
if (!links?.length) return [];
@@ -179,6 +186,18 @@ export default function LinksTable({
link: linkToDelete,
targetType,
});
+ const [isInviteModalOpen, setIsInviteModalOpen] = useState<boolean>(false);
+ const [inviteLink, setInviteLink] = useState<LinkWithViews | null>(null);
+ const [inviteDefaultEmails, setInviteDefaultEmails] = useState<string[]>([]);
+
+ const linksApiRoute =
+ currentTeamId && targetId
+ ? groupId
+ ? `/api/teams/${currentTeamId}/datarooms/${targetId}/groups/${groupId}/links`
+ : `/api/teams/${currentTeamId}/datarooms/${targetId}/links`
+ : null;
+
+ const dataroomDisplayName = dataroomName ?? "this dataroom";
const handleCopyToClipboard = (linkString: string) => {
copyToClipboard(`${linkString}`, "Link copied to clipboard.");
@@ -315,6 +334,24 @@ export default function LinksTable({
setIsLoading(false);
};
+ const handleSendInvitations = (link: LinkWithViews) => {
+ if (targetType !== "DATAROOM") {
+ return;
+ }
+
+ const sanitizedEmails = Array.from(
+ new Set(
+ (link.allowList ?? []).filter(
+ (value) => invitationEmailSchema.safeParse(value).success,
+ ),
+ ),
+ );
+
+ setInviteDefaultEmails(sanitizedEmails);
+ setInviteLink(link);
+ setIsInviteModalOpen(true);
+ };
+
const handleEditPermissions = (link: LinkWithViews) => {
setEditPermissionLink(link);
setShowPermissionsSheet(true);
@@ -902,6 +939,15 @@ export default function LinksTable({
<EyeIcon className="mr-2 h-4 w-4" />
Preview Link
</DropdownMenuItem>
+ {targetType === "DATAROOM" &&
+ isFeatureEnabled("dataroomInvitations") && (
+ <DropdownMenuItem
+ onClick={() => handleSendInvitations(link)}
+ >
+ <SendIcon className="mr-2 h-4 w-4" />
+ Send Invitations
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
disabled={!canAddLinks}
onClick={() => handleDuplicateLink(link)}
@@ -996,6 +1042,28 @@ export default function LinksTable({
permissionGroupId={editPermissionLink?.permissionGroupId}
onSave={handlePermissionsSave}
/>
+ {inviteLink && isFeatureEnabled("dataroomInvitations") ? (
+ <InviteViewersModal
+ open={isInviteModalOpen}
+ setOpen={(open) => {
+ setIsInviteModalOpen(open);
+ if (!open) {
+ setInviteLink(null);
+ }
+ }}
+ dataroomId={targetId}
+ dataroomName={dataroomDisplayName}
+ groupId={inviteLink.groupId ?? undefined}
+ linkId={inviteLink.id}
+ defaultEmails={inviteDefaultEmails}
+ onSuccess={() => {
+ if (linksApiRoute) {
+ mutate(linksApiRoute);
+ }
+ setInviteLink(null);
+ }}
+ />
+ ) : null}
</>
) : (
<LinkSheet
diff --git a/ee/features/dataroom-invitations/api/group-invite.ts b/ee/features/dataroom-invitations/api/group-invite.ts
new file mode 100644
index 00000000..b3a16fc4
--- /dev/null
+++ b/ee/features/dataroom-invitations/api/group-invite.ts
@@ -0,0 +1,242 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { SendGroupInvitationSchema } from "@/ee/features/dataroom-invitations/lib/schema/dataroom-invitations";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { LinkAudienceType, LinkType } from "@prisma/client";
+import { getServerSession } from "next-auth/next";
+
+import { getFeatureFlags } from "@/lib/featureFlags";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { constructLinkUrl } from "@/lib/utils/link-url";
+
+import { sendDataroomViewerInvite } from "../emails/lib/send-dataroom-viewer-invite";
+
+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`);
+ }
+
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const user = session.user as CustomUser;
+ const {
+ teamId,
+ id: dataroomId,
+ groupId,
+ } = req.query as {
+ teamId: string;
+ id: string;
+ groupId: string;
+ };
+
+ const parseResult = SendGroupInvitationSchema.safeParse(req.body);
+ if (!parseResult.success) {
+ return res.status(400).json({
+ error: "Invalid request body",
+ details: parseResult.error.flatten(),
+ });
+ }
+
+ const { linkId, customMessage, emails } = parseResult.data;
+
+ try {
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: user.id,
+ teamId,
+ },
+ },
+ });
+
+ if (!teamAccess) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ // Check if dataroomInvitations feature is enabled for this team
+ const featureFlags = await getFeatureFlags({ teamId });
+ if (!featureFlags.dataroomInvitations) {
+ return res.status(403).json({
+ error: "Dataroom invitations feature is not enabled for this team",
+ });
+ }
+
+ const group = await prisma.viewerGroup.findUnique({
+ where: {
+ id: groupId,
+ dataroomId,
+ teamId,
+ },
+ select: {
+ id: true,
+ dataroom: {
+ select: {
+ name: true,
+ },
+ },
+ members: {
+ select: {
+ viewer: {
+ select: {
+ id: true,
+ email: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!group) {
+ return res.status(404).json({ error: "Group not found" });
+ }
+
+ const link = await prisma.link.findUnique({
+ where: {
+ id: linkId,
+ dataroomId,
+ teamId,
+ linkType: LinkType.DATAROOM_LINK,
+ audienceType: LinkAudienceType.GROUP,
+ groupId,
+ isArchived: false,
+ },
+ select: {
+ id: true,
+ domainId: true,
+ domainSlug: true,
+ slug: true,
+ allowList: true,
+ },
+ });
+
+ if (!link) {
+ return res
+ .status(404)
+ .json({ error: "Link not found or not associated with this group" });
+ }
+
+ const teamMember = await prisma.user.findUnique({
+ where: { id: user.id },
+ select: { email: true },
+ });
+
+ if (!teamMember?.email) {
+ return res.status(400).json({ error: "Sender email not available" });
+ }
+
+ const availableEmails = group.members
+ .map((member) => member.viewer.email)
+ .filter(Boolean);
+
+ const targetEmails = Array.from(
+ new Set(
+ (emails ?? availableEmails).filter((email) =>
+ availableEmails.includes(email),
+ ),
+ ),
+ );
+
+ if (targetEmails.length === 0) {
+ return res
+ .status(400)
+ .json({ error: "No valid group member emails provided" });
+ }
+
+ const viewers = await prisma.viewer.findMany({
+ where: {
+ teamId,
+ email: {
+ in: targetEmails,
+ },
+ },
+ select: {
+ id: true,
+ email: true,
+ },
+ });
+
+ const viewerByEmail = viewers.reduce<Record<string, { id: string }>>(
+ (acc, viewer) => {
+ if (viewer.email) {
+ acc[viewer.email] = { id: viewer.id };
+ }
+ return acc;
+ },
+ {},
+ );
+
+ const linkUrl = constructLinkUrl(link);
+
+ const successes: string[] = [];
+ const failures: { email: string; error: string }[] = [];
+
+ for (const email of targetEmails) {
+ const viewer = viewerByEmail[email];
+ if (!viewer) {
+ failures.push({
+ email,
+ error: "Viewer not found",
+ });
+ continue;
+ }
+
+ try {
+ await sendDataroomViewerInvite({
+ dataroomName: group.dataroom.name,
+ senderEmail: teamMember.email,
+ to: email,
+ url: linkUrl,
+ customMessage,
+ });
+
+ await prisma.viewerInvitation.create({
+ data: {
+ viewerId: viewer.id,
+ linkId: link.id,
+ groupId,
+ invitedBy: user.id,
+ customMessage,
+ status: "SENT",
+ },
+ });
+
+ successes.push(email);
+ } catch (error: any) {
+ failures.push({
+ email,
+ error: error?.message ?? "Unknown error",
+ });
+
+ await prisma.viewerInvitation.create({
+ data: {
+ viewerId: viewer.id,
+ linkId: link.id,
+ groupId,
+ invitedBy: user.id,
+ customMessage,
+ status: "FAILED",
+ },
+ });
+ }
+ }
+
+ return res.status(200).json({
+ success: successes,
+ failed: failures,
+ });
+ } catch (error) {
+ console.error("Error sending viewer invitations", error);
+ return res.status(500).json({
+ error: "Failed to send invitations",
+ });
+ }
+}
diff --git a/ee/features/dataroom-invitations/api/link-invite.ts b/ee/features/dataroom-invitations/api/link-invite.ts
new file mode 100644
index 00000000..0e9b7eec
--- /dev/null
+++ b/ee/features/dataroom-invitations/api/link-invite.ts
@@ -0,0 +1,222 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import {
+ SendLinkInvitationSchema,
+ invitationEmailSchema,
+} from "@/ee/features/dataroom-invitations/lib/schema/dataroom-invitations";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { LinkType } from "@prisma/client";
+import { getServerSession } from "next-auth/next";
+
+import { getFeatureFlags } from "@/lib/featureFlags";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { constructLinkUrl } from "@/lib/utils/link-url";
+
+import { sendDataroomViewerInvite } from "../emails/lib/send-dataroom-viewer-invite";
+
+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`);
+ }
+
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const user = session.user as CustomUser;
+ const {
+ teamId,
+ id: dataroomId,
+ linkId,
+ } = req.query as {
+ teamId: string;
+ id: string;
+ linkId: string;
+ };
+
+ const parseResult = SendLinkInvitationSchema.safeParse(req.body);
+ if (!parseResult.success) {
+ return res.status(400).json({
+ error: "Invalid request body",
+ details: parseResult.error.flatten(),
+ });
+ }
+
+ const { customMessage, emails } = parseResult.data;
+
+ try {
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: user.id,
+ teamId,
+ },
+ },
+ });
+
+ if (!teamAccess) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ // Check if dataroomInvitations feature is enabled for this team
+ const featureFlags = await getFeatureFlags({ teamId });
+ if (!featureFlags.dataroomInvitations) {
+ return res.status(403).json({
+ error: "Dataroom invitations feature is not enabled for this team",
+ });
+ }
+
+ const link = await prisma.link.findFirst({
+ where: {
+ id: linkId,
+ dataroomId,
+ teamId,
+ linkType: LinkType.DATAROOM_LINK,
+ isArchived: false,
+ },
+ select: {
+ id: true,
+ domainId: true,
+ domainSlug: true,
+ slug: true,
+ allowList: true,
+ dataroom: {
+ select: {
+ name: true,
+ },
+ },
+ },
+ });
+
+ if (!link) {
+ return res.status(404).json({ error: "Link not found" });
+ }
+
+ const teamMember = await prisma.user.findUnique({
+ where: { id: user.id },
+ select: { email: true },
+ });
+
+ if (!teamMember?.email) {
+ return res.status(400).json({ error: "Sender email not available" });
+ }
+
+ const defaultEmails = (link.allowList ?? []).filter(
+ (value) => invitationEmailSchema.safeParse(value).success,
+ );
+
+ const targetEmails = Array.from(
+ new Set(
+ (emails ?? defaultEmails).filter(
+ (email) => invitationEmailSchema.safeParse(email).success,
+ ),
+ ),
+ );
+
+ if (targetEmails.length === 0) {
+ return res.status(400).json({
+ error: "No valid recipient emails provided",
+ });
+ }
+
+ await prisma.viewer.createMany({
+ data: targetEmails.map((email) => ({
+ email,
+ teamId,
+ })),
+ skipDuplicates: true,
+ });
+
+ const viewers = await prisma.viewer.findMany({
+ where: {
+ teamId,
+ email: {
+ in: targetEmails,
+ },
+ },
+ select: {
+ id: true,
+ email: true,
+ },
+ });
+
+ const viewerByEmail = viewers.reduce<Record<string, { id: string }>>(
+ (acc, viewer) => {
+ if (viewer.email) {
+ acc[viewer.email] = { id: viewer.id };
+ }
+ return acc;
+ },
+ {},
+ );
+
+ const linkUrl = constructLinkUrl(link);
+
+ const successes: string[] = [];
+ const failures: { email: string; error: string }[] = [];
+
+ for (const email of targetEmails) {
+ const viewer = viewerByEmail[email];
+ if (!viewer) {
+ failures.push({
+ email,
+ error: "Viewer not found",
+ });
+ continue;
+ }
+
+ try {
+ await sendDataroomViewerInvite({
+ dataroomName: link.dataroom?.name ?? "",
+ senderEmail: teamMember.email,
+ to: email,
+ url: linkUrl,
+ customMessage,
+ });
+
+ await prisma.viewerInvitation.create({
+ data: {
+ viewerId: viewer.id,
+ linkId: link.id,
+ invitedBy: user.id,
+ customMessage,
+ status: "SENT",
+ },
+ });
+
+ successes.push(email);
+ } catch (error: any) {
+ failures.push({
+ email,
+ error: error?.message ?? "Unknown error",
+ });
+
+ await prisma.viewerInvitation.create({
+ data: {
+ viewerId: viewer.id,
+ linkId: link.id,
+ invitedBy: user.id,
+ customMessage,
+ status: "FAILED",
+ },
+ });
+ }
+ }
+
+ return res.status(200).json({
+ success: successes,
+ failed: failures,
+ });
+ } catch (error) {
+ console.error("Error sending link invitations", error);
+ return res.status(500).json({
+ error: "Failed to send invitations",
+ });
+ }
+}
diff --git a/ee/features/dataroom-invitations/api/uninvited.ts b/ee/features/dataroom-invitations/api/uninvited.ts
new file mode 100644
index 00000000..09fdcc07
--- /dev/null
+++ b/ee/features/dataroom-invitations/api/uninvited.ts
@@ -0,0 +1,112 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "GET") {
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const user = session.user as CustomUser;
+ const {
+ teamId,
+ id: dataroomId,
+ groupId,
+ } = req.query as {
+ teamId: string;
+ id: string;
+ groupId: string;
+ };
+
+ try {
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: user.id,
+ teamId,
+ },
+ },
+ });
+
+ if (!teamAccess) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const group = await prisma.viewerGroup.findFirst({
+ where: {
+ id: groupId,
+ dataroomId,
+ teamId,
+ },
+ select: {
+ members: {
+ select: {
+ viewer: {
+ select: {
+ id: true,
+ email: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!group) {
+ return res.status(404).json({ error: "Group not found" });
+ }
+
+ const viewerIds = group.members.map((member) => member.viewer.id);
+
+ if (viewerIds.length === 0) {
+ return res.status(200).json({
+ count: 0,
+ emails: [],
+ });
+ }
+
+ const existingInvitations = await prisma.viewerInvitation.findMany({
+ where: {
+ groupId,
+ viewerId: {
+ in: viewerIds,
+ },
+ },
+ select: {
+ viewerId: true,
+ },
+ });
+
+ const invitedViewerIds = new Set(
+ existingInvitations.map((record) => record.viewerId),
+ );
+
+ const uninvitedEmails = group.members
+ .filter((member) => !invitedViewerIds.has(member.viewer.id))
+ .map((member) => member.viewer.email)
+ .filter((email): email is string => Boolean(email));
+
+ return res.status(200).json({
+ count: uninvitedEmails.length,
+ emails: uninvitedEmails,
+ });
+ } catch (error) {
+ console.error("Error fetching uninvited members", error);
+ return res.status(500).json({
+ error: "Failed to load uninvited members",
+ });
+ }
+}
diff --git a/components/emails/dataroom-viewer-invitation.tsx b/ee/features/dataroom-invitations/emails/components/dataroom-viewer-invitation.tsx
similarity index 65%
rename from components/emails/dataroom-viewer-invitation.tsx
rename to ee/features/dataroom-invitations/emails/components/dataroom-viewer-invitation.tsx
index a3997310..3d4120e3 100644
--- a/components/emails/dataroom-viewer-invitation.tsx
+++ b/ee/features/dataroom-invitations/emails/components/dataroom-viewer-invitation.tsx
@@ -13,16 +13,20 @@ import {
Text,
} from "@react-email/components";
-import { Footer } from "./shared/footer";
+import { Footer } from "../../../../../components/emails/shared/footer";
export default function DataroomViewerInvitation({
dataroomName = "Example Data Room",
senderEmail = "[email protected]",
url = "https://app.papermark.com/datarooms/123",
+ recipientEmail = "[email protected]",
+ customMessage,
}: {
dataroomName: string;
senderEmail: string;
url: string;
+ recipientEmail: string;
+ customMessage?: string | null;
}) {
return (
<Html>
@@ -46,6 +50,14 @@ export default function DataroomViewerInvitation({
The invitation was sent by{" "}
<span className="font-semibold">{senderEmail}</span>.
</Text>
+ {customMessage ? (
+ <Text
+ className="text-sm leading-6 text-black"
+ style={{ whiteSpace: "pre-wrap" }}
+ >
+ {customMessage}
+ </Text>
+ ) : null}
<Section className="mb-[32px] mt-[32px] text-center">
<Button
className="rounded bg-black text-center text-xs font-semibold text-white no-underline"
@@ -59,11 +71,20 @@ export default function DataroomViewerInvitation({
or copy and paste this URL into your browser: <br />
{`${url}`}
</Text>
- <Text className="text-sm text-gray-400">Papermark</Text>
- <Footer
- footerText="If you have any feedback or questions about this email, simply
- reply to it."
- />
+ <Hr />
+ <Section className="mt-8 text-gray-400">
+ <Text className="text-xs">
+ © {new Date().getFullYear()} Papermark, Inc. All rights
+ reserved.
+ </Text>
+ <Text className="text-xs">
+ This email was intended for{" "}
+ <span className="text-black">{recipientEmail}</span>. If you
+ were not expecting this email, you can ignore this email. If you
+ have any feedback or questions about this email, simply reply to
+ it.
+ </Text>
+ </Section>
</Container>
</Body>
</Tailwind>
diff --git a/lib/emails/send-dataroom-viewer-invite.ts b/ee/features/dataroom-invitations/emails/lib/send-dataroom-viewer-invite.ts
similarity index 72%
rename from lib/emails/send-dataroom-viewer-invite.ts
rename to ee/features/dataroom-invitations/emails/lib/send-dataroom-viewer-invite.ts
index d6dfd118..1cdc6529 100644
--- a/lib/emails/send-dataroom-viewer-invite.ts
+++ b/ee/features/dataroom-invitations/emails/lib/send-dataroom-viewer-invite.ts
@@ -1,17 +1,19 @@
-import DataroomViewerInvitation from "@/components/emails/dataroom-viewer-invitation";
-
import { sendEmail } from "@/lib/resend";
+import DataroomViewerInvitation from "@/ee/features/dataroom-invitations/emails/components/dataroom-viewer-invitation";
+
export const sendDataroomViewerInvite = async ({
dataroomName,
senderEmail,
to,
url,
+ customMessage,
}: {
dataroomName: string;
senderEmail: string;
to: string;
url: string;
+ customMessage?: string;
}) => {
try {
await sendEmail({
@@ -21,6 +23,8 @@ export const sendDataroomViewerInvite = async ({
senderEmail,
dataroomName,
url,
+ recipientEmail: to,
+ customMessage,
}),
test: process.env.NODE_ENV === "development",
system: true,
diff --git a/ee/features/dataroom-invitations/lib/schema/dataroom-invitations.ts b/ee/features/dataroom-invitations/lib/schema/dataroom-invitations.ts
new file mode 100644
index 00000000..22dc227d
--- /dev/null
+++ b/ee/features/dataroom-invitations/lib/schema/dataroom-invitations.ts
@@ -0,0 +1,38 @@
+import { z } from "zod";
+
+const MAX_CUSTOM_MESSAGE_LENGTH = 500;
+
+export const invitationEmailSchema = z.string().email();
+
+const trimmedCustomMessageSchema = z
+ .string()
+ .max(MAX_CUSTOM_MESSAGE_LENGTH)
+ .transform((value) => value.trim());
+
+export const optionalCustomMessageSchema = z
+ .union([trimmedCustomMessageSchema, z.literal(""), z.undefined(), z.null()])
+ .transform((value) => {
+ if (typeof value !== "string") {
+ return undefined;
+ }
+
+ return value.length > 0 ? value : undefined;
+ });
+
+export const sendGroupInvitationSchema = z.object({
+ linkId: z.string().min(1),
+ customMessage: optionalCustomMessageSchema,
+ emails: z.array(invitationEmailSchema).optional(),
+});
+
+export const sendLinkInvitationSchema = z.object({
+ customMessage: optionalCustomMessageSchema,
+ emails: z.array(invitationEmailSchema).optional(),
+});
+
+export const SendGroupInvitationSchema = sendGroupInvitationSchema;
+export const SendLinkInvitationSchema = sendLinkInvitationSchema;
+
+export type SendGroupInvitationInput = z.infer<typeof sendGroupInvitationSchema>;
+export type SendLinkInvitationInput = z.infer<typeof sendLinkInvitationSchema>;
+
diff --git a/ee/features/dataroom-invitations/lib/swr/use-dataroom-invitations.ts b/ee/features/dataroom-invitations/lib/swr/use-dataroom-invitations.ts
new file mode 100644
index 00000000..e86d6fd8
--- /dev/null
+++ b/ee/features/dataroom-invitations/lib/swr/use-dataroom-invitations.ts
@@ -0,0 +1,43 @@
+import useSWR from "swr";
+
+import { useTeam } from "@/context/team-context";
+
+import { fetcher } from "@/lib/utils";
+
+type UninvitedMembersResponse = {
+ count: number;
+ emails: string[];
+};
+
+export function useUninvitedMembers(
+ dataroomId?: string,
+ groupId?: string,
+) {
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const {
+ data,
+ error,
+ mutate,
+ } = useSWR<UninvitedMembersResponse>(
+ teamId && dataroomId && groupId
+ ? `/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}/uninvited`
+ : null,
+ fetcher,
+ {
+ revalidateOnFocus: false,
+ dedupingInterval: 15000,
+ },
+ );
+
+ return {
+ uninvitedCount: data?.count ?? 0,
+ uninvitedEmails: data?.emails ?? [],
+ loading: !data && !error,
+ error,
+ mutate,
+ };
+}
+
+
diff --git a/lib/featureFlags/index.ts b/lib/featureFlags/index.ts
index 47d50691..3bbde72c 100644
--- a/lib/featureFlags/index.ts
+++ b/lib/featureFlags/index.ts
@@ -11,7 +11,8 @@ export type BetaFeatures =
| "usStorage"
| "dataroomIndex"
| "slack"
- | "annotations";
+ | "annotations"
+ | "dataroomInvitations";
type BetaFeaturesRecord = Record<BetaFeatures, string[]>;
@@ -28,6 +29,7 @@ export const getFeatureFlags = async ({ teamId }: { teamId?: string }) => {
dataroomIndex: false,
slack: false,
annotations: false,
+ dataroomInvitations: false,
};
// Return all features as true if edge config is not available
diff --git a/lib/utils/link-url.ts b/lib/utils/link-url.ts
new file mode 100644
index 00000000..35e9e406
--- /dev/null
+++ b/lib/utils/link-url.ts
@@ -0,0 +1,14 @@
+export function constructLinkUrl(link: {
+ id: string;
+ domainId?: string | null;
+ domainSlug?: string | null;
+ slug?: string | null;
+}) {
+ if (link.domainId && link.domainSlug && link.slug) {
+ return `https://${link.domainSlug}/${link.slug}`;
+ }
+
+ return `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${link.id}`;
+}
+
+
diff --git a/pages/api/jobs/send-dataroom-view-invitation.ts b/pages/api/jobs/send-dataroom-view-invitation.ts
deleted file mode 100644
index 63bfc98f..00000000
--- a/pages/api/jobs/send-dataroom-view-invitation.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-
-import { sendDataroomViewerInvite } from "@/lib/emails/send-dataroom-viewer-invite";
-import prisma from "@/lib/prisma";
-import { log } from "@/lib/utils";
-
-export const config = {
- maxDuration: 120,
-};
-
-export default async function handle(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- // We only allow POST requests
- if (req.method !== "POST") {
- res.status(405).json({ message: "Method Not Allowed" });
- return;
- }
-
- // Extract the API Key from the Authorization header
- const authHeader = req.headers.authorization;
- const token = authHeader?.split(" ")[1]; // Assuming the format is "Bearer [token]"
-
- // Check if the API Key matches
- if (token !== process.env.INTERNAL_API_KEY) {
- res.status(401).json({ message: "Unauthorized" });
- return;
- }
-
- const { linkId, dataroomId, viewerId, senderUserId } = req.body as {
- linkId: string;
- dataroomId: string;
- viewerId: string;
- senderUserId: string;
- };
-
- let viewer: { email: string; dataroom: { name: string } | null } | null =
- null;
-
- try {
- // Fetch the link to verify the settings
- viewer = await prisma.viewer.findUnique({
- where: {
- id: viewerId,
- },
- select: {
- email: true,
- dataroom: {
- select: {
- name: true,
- },
- },
- },
- });
-
- if (!viewer) {
- res.status(404).json({ message: "Viewer not found." });
- return;
- }
- } catch (error) {
- log({
- message: `Failed to find viewer for viewerId: ${viewerId}. \n\n Error: ${error}`,
- type: "error",
- mention: true,
- });
- res.status(500).json({ message: (error as Error).message });
- return;
- }
-
- // POST /api/jobs/send-datarooom-view-invitation
- try {
- const user = await prisma.user.findUnique({
- where: { id: senderUserId },
- select: { email: true },
- });
-
- if (!user) {
- res.status(404).json({ message: "Sender not found." });
- return;
- }
-
- // send email to document owner that document
- await sendDataroomViewerInvite({
- dataroomName: viewer.dataroom?.name ?? "",
- senderEmail: user.email!,
- to: viewer.email,
- url: `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${linkId}?email=${encodeURIComponent(viewer.email)}`,
- });
-
- res
- .status(200)
- .json({ message: "Successfully sent view invitation", viewerId });
- return;
- } catch (error) {
- log({
- message: `Failed to send invite email for dataroom ${dataroomId} to viewer: ${viewerId}. \n\n Error: ${error} \n\n*Metadata*: \`{dataroomId: ${dataroomId}, viewerId: ${viewerId}}\``,
- type: "error",
- mention: true,
- });
- return res.status(500).json({ message: (error as Error).message });
- }
-}
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/invite.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/invite.ts
new file mode 100644
index 00000000..b72c9d67
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/invite.ts
@@ -0,0 +1,10 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import handleRoute from "@/ee/features/dataroom-invitations/api/group-invite";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ return handleRoute(req, res);
+}
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/uninvited.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/uninvited.ts
new file mode 100644
index 00000000..be1efae2
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/uninvited.ts
@@ -0,0 +1,10 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import handleRoute from "@/ee/features/dataroom-invitations/api/uninvited";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ return handleRoute(req, res);
+}
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/links/[linkId]/invite.ts b/pages/api/teams/[teamId]/datarooms/[id]/links/[linkId]/invite.ts
new file mode 100644
index 00000000..ba943e55
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/links/[linkId]/invite.ts
@@ -0,0 +1,10 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import handleRoute from "@/ee/features/dataroom-invitations/api/link-invite";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ return handleRoute(req, res);
+}
diff --git a/pages/datarooms/[id]/groups/[groupId]/links.tsx b/pages/datarooms/[id]/groups/[groupId]/links.tsx
index ae176ecc..1925ec3b 100644
--- a/pages/datarooms/[id]/groups/[groupId]/links.tsx
+++ b/pages/datarooms/[id]/groups/[groupId]/links.tsx
@@ -1,3 +1,9 @@
+import { useDataroom } from "@/lib/swr/use-dataroom";
+import {
+ useDataroomGroup,
+ useDataroomGroupLinks,
+} from "@/lib/swr/use-dataroom-groups";
+
import { DataroomHeader } from "@/components/datarooms/dataroom-header";
import { DataroomNavigation } from "@/components/datarooms/dataroom-navigation";
import { GroupHeader } from "@/components/datarooms/groups/group-header";
@@ -5,12 +11,6 @@ import { GroupNavigation } from "@/components/datarooms/groups/group-navigation"
import AppLayout from "@/components/layouts/app";
import LinksTable from "@/components/links/links-table";
-import { useDataroom } from "@/lib/swr/use-dataroom";
-import {
- useDataroomGroup,
- useDataroomGroupLinks,
-} from "@/lib/swr/use-dataroom-groups";
-
export default function DataroomGroupLinksPage() {
const { dataroom } = useDataroom();
const { viewerGroup } = useDataroomGroup();
@@ -43,7 +43,11 @@ export default function DataroomGroupLinksPage() {
{loading ? (
<div>Loading...</div>
) : (
- <LinksTable links={links} targetType={"DATAROOM"} />
+ <LinksTable
+ links={links}
+ targetType={"DATAROOM"}
+ dataroomName={dataroom.name}
+ />
)}
</div>
</div>
diff --git a/pages/datarooms/[id]/index.tsx b/pages/datarooms/[id]/index.tsx
index 5895a15e..fb670b70 100644
--- a/pages/datarooms/[id]/index.tsx
+++ b/pages/datarooms/[id]/index.tsx
@@ -1,5 +1,7 @@
import { useState } from "react";
+import { useDataroom, useDataroomLinks } from "@/lib/swr/use-dataroom";
+
import { DataroomHeader } from "@/components/datarooms/dataroom-header";
import { DataroomNavigation } from "@/components/datarooms/dataroom-navigation";
import StatsCard from "@/components/datarooms/stats-card";
@@ -9,8 +11,6 @@ import LinksTable from "@/components/links/links-table";
import { Button } from "@/components/ui/button";
import DataroomVisitorsTable from "@/components/visitors/dataroom-visitors-table";
-import { useDataroom, useDataroomLinks } from "@/lib/swr/use-dataroom";
-
export default function DataroomPage() {
const { dataroom } = useDataroom();
const { links } = useDataroomLinks();
@@ -43,7 +43,11 @@ export default function DataroomPage() {
<StatsCard />
{/* Links */}
- <LinksTable links={links} targetType={"DATAROOM"} />
+ <LinksTable
+ links={links}
+ targetType={"DATAROOM"}
+ dataroomName={dataroom.name}
+ />
{/* Visitors */}
<DataroomVisitorsTable dataroomId={dataroom.id} />
diff --git a/pages/datarooms/[id]/permissions/index.tsx b/pages/datarooms/[id]/permissions/index.tsx
index 16b476d4..c88f3155 100644
--- a/pages/datarooms/[id]/permissions/index.tsx
+++ b/pages/datarooms/[id]/permissions/index.tsx
@@ -4,6 +4,8 @@ import { useState } from "react";
import { CircleHelpIcon } from "lucide-react";
+import { useDataroom, useDataroomLinks } from "@/lib/swr/use-dataroom";
+
import { DataroomHeader } from "@/components/datarooms/dataroom-header";
import { DataroomNavigation } from "@/components/datarooms/dataroom-navigation";
import AppLayout from "@/components/layouts/app";
@@ -13,8 +15,6 @@ import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { BadgeTooltip } from "@/components/ui/tooltip";
-import { useDataroom, useDataroomLinks } from "@/lib/swr/use-dataroom";
-
export default function DataroomAnalyticsPage() {
const { dataroom } = useDataroom();
const { links } = useDataroomLinks();
@@ -68,7 +68,11 @@ export default function DataroomAnalyticsPage() {
</p>
</div>
</div>
- <LinksTable links={links} targetType={"DATAROOM"} />
+ <LinksTable
+ links={links}
+ targetType={"DATAROOM"}
+ dataroomName={dataroom.name}
+ />
<LinkSheet
linkType={"DATAROOM_LINK"}
isOpen={isLinkSheetOpen}
diff --git a/prisma/migrations/20251111000000_add_viewer_invitations/migration.sql b/prisma/migrations/20251111000000_add_viewer_invitations/migration.sql
new file mode 100644
index 00000000..1733b7be
--- /dev/null
+++ b/prisma/migrations/20251111000000_add_viewer_invitations/migration.sql
@@ -0,0 +1,37 @@
+-- CreateEnum
+CREATE TYPE "InvitationStatus" AS ENUM ('SENT', 'FAILED', 'BOUNCED');
+
+-- CreateTable
+CREATE TABLE "ViewerInvitation" (
+ "id" TEXT NOT NULL,
+ "viewerId" TEXT NOT NULL,
+ "linkId" TEXT NOT NULL,
+ "groupId" TEXT,
+ "invitedBy" TEXT NOT NULL,
+ "customMessage" TEXT,
+ "sentAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "status" "InvitationStatus" NOT NULL DEFAULT 'SENT',
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "ViewerInvitation_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "ViewerInvitation_viewerId_idx" ON "ViewerInvitation"("viewerId" ASC);
+
+-- CreateIndex
+CREATE INDEX "ViewerInvitation_linkId_idx" ON "ViewerInvitation"("linkId" ASC);
+
+-- CreateIndex
+CREATE INDEX "ViewerInvitation_groupId_idx" ON "ViewerInvitation"("groupId" ASC);
+
+-- AddForeignKey
+ALTER TABLE "ViewerInvitation" ADD CONSTRAINT "ViewerInvitation_viewerId_fkey" FOREIGN KEY ("viewerId") REFERENCES "Viewer"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "ViewerInvitation" ADD CONSTRAINT "ViewerInvitation_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "Link"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "ViewerInvitation" ADD CONSTRAINT "ViewerInvitation_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "ViewerGroup"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+
diff --git a/prisma/schema/dataroom.prisma b/prisma/schema/dataroom.prisma
index f65a5865..5a909828 100644
--- a/prisma/schema/dataroom.prisma
+++ b/prisma/schema/dataroom.prisma
@@ -124,6 +124,7 @@ model ViewerGroup {
views View[]
conversations Conversation[]
+ invitations ViewerInvitation[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
diff --git a/prisma/schema/link.prisma b/prisma/schema/link.prisma
index 0171260b..7d1ebc59 100644
--- a/prisma/schema/link.prisma
+++ b/prisma/schema/link.prisma
@@ -86,6 +86,7 @@ model Link {
customFields CustomField[]
tags TagItem[]
+ viewerInvitations ViewerInvitation[]
@@unique([domainSlug, slug])
@@index([documentId])
diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prisma
index 6e6f1715..21091ee3 100644
--- a/prisma/schema/schema.prisma
+++ b/prisma/schema/schema.prisma
@@ -187,6 +187,7 @@ model Viewer {
views View[]
groups ViewerGroupMembership[]
+ invitations ViewerInvitation[]
participatedConversations ConversationParticipant[]
messages Message[]
@@ -450,3 +451,29 @@ model TagItem {
@@index([tagId, documentId])
@@index([tagId, dataroomId])
}
+
+model ViewerInvitation {
+ id String @id @default(cuid())
+ viewerId String
+ viewer Viewer @relation(fields: [viewerId], references: [id], onDelete: Cascade)
+ linkId String
+ link Link @relation(fields: [linkId], references: [id], onDelete: Cascade)
+ groupId String?
+ group ViewerGroup? @relation(fields: [groupId], references: [id], onDelete: SetNull)
+ invitedBy String
+ customMessage String?
+ sentAt DateTime @default(now())
+ status InvitationStatus @default(SENT)
+
+ createdAt DateTime @default(now())
+
+ @@index([viewerId])
+ @@index([linkId])
+ @@index([groupId])
+}
+
+enum InvitationStatus {
+ SENT
+ FAILED
+ BOUNCED
+}