Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
Merge branch 'main' of https://github.com/papermark/papermark-ee into preview-2026-07-29
Iuliia Shnai765efe4e15c2
diff --git a/components/datarooms/dataroom-navigation.tsx b/components/datarooms/dataroom-navigation.tsxindex 46cfc65e..01fb7aea 100644--- a/components/datarooms/dataroom-navigation.tsx+++ b/components/datarooms/dataroom-navigation.tsx@@ -20,6 +20,11 @@ export const DataroomNavigation = ({ dataroomId }: { dataroomId?: string }) => {href: `/datarooms/${dataroomId}/permissions`,segment: "permissions",},+ {+ label: "Participants",+ href: `/datarooms/${dataroomId}/participants`,+ segment: "participants",+ },{label: "Analytics",href: `/datarooms/${dataroomId}/analytics`,diff --git a/components/layouts/breadcrumb.tsx b/components/layouts/breadcrumb.tsxindex 02a85927..24589d3f 100644--- a/components/layouts/breadcrumb.tsx+++ b/components/layouts/breadcrumb.tsx@@ -164,6 +164,8 @@ const SingleDataroomBreadcrumb = ({ path }: { path: string }) => {case "/datarooms/[id]/groups/[groupId]/members":case "/datarooms/[id]/groups/[groupId]/links":return "Permissions";+ case "/datarooms/[id]/participants":+ return "Participants";case "/datarooms/[id]/analytics":return "Analytics";case "/datarooms/[id]/conversations/faqs":diff --git a/components/links/links-table.tsx b/components/links/links-table.tsxindex 23a83cb4..f998390b 100644--- a/components/links/links-table.tsx+++ b/components/links/links-table.tsx@@ -39,6 +39,7 @@ import { mutate } from "swr";import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";import { usePlan } from "@/lib/swr/use-billing";import useLimits from "@/lib/swr/use-limits";+import { buildLinkFormData } from "@/lib/links/build-link-form-data";import { LinkWithViews, WatermarkConfig } from "@/lib/types";import { cn, copyToClipboard, nFormatter, timeAgo } from "@/lib/utils";import { useMediaQuery } from "@/lib/utils/use-media-query";@@ -416,66 +417,6 @@ export default function LinksTable({copyToClipboard(`${linkString}`, "Link copied to clipboard.");};- const buildLinkFormData = (link: LinkWithViews): DEFAULT_LINK_TYPE => ({- id: link.id,- name: link.name || `Link #${link.id.slice(-5)}`,- domain: link.domainSlug,- slug: link.slug,- expiresAt: link.expiresAt,- password: link.password,- emailProtected: link.emailProtected,- emailAuthenticated: link.emailAuthenticated,- allowDownload: link.allowDownload ? link.allowDownload : false,- allowList: link.allowList,- denyList: link.denyList,- visitorGroupIds:- link.visitorGroups?.map(- (vg: { visitorGroupId: string }) => vg.visitorGroupId,- ) || [],- enableNotification: link.enableNotification- ? link.enableNotification- : false,- enableFeedback: link.enableFeedback ? link.enableFeedback : false,- enableScreenshotProtection: link.enableScreenshotProtection- ? link.enableScreenshotProtection- : false,- enableConfidentialView: link.enableConfidentialView- ? link.enableConfidentialView- : false,- enableCustomMetatag: link.enableCustomMetatag- ? link.enableCustomMetatag- : false,- enableQuestion: link.enableQuestion ? link.enableQuestion : false,- questionText: link.feedback ? link.feedback.data?.question : "",- questionType: link.feedback ? link.feedback.data?.type : "",- metaTitle: link.metaTitle,- metaDescription: link.metaDescription,- metaImage: link.metaImage,- metaFavicon: link.metaFavicon,- enableAgreement: link.enableAgreement ? link.enableAgreement : false,- agreementId: link.agreementId,- showBanner: link.showBanner ?? false,- enableWatermark: link.enableWatermark ?? false,- watermarkConfig: link.watermarkConfig as WatermarkConfig | null,- audienceType: link.audienceType,- groupId: link.groupId,- customFields: link.customFields || [],- tags: link.tags.map((tag) => tag.id) || [],- enableConversation: link.enableConversation ?? false,- enableUpload: link.enableUpload ?? false,- isFileRequestOnly: link.isFileRequestOnly ?? false,- uploadFolderIds: Array.isArray(link.uploadFolderIds)- ? link.uploadFolderIds- : [],- uploadFolders: Array.isArray(link.uploadFolders)- ? link.uploadFolders- : [],- enableIndexFile: link.enableIndexFile ?? false,- permissionGroupId: link.permissionGroupId ?? null,- welcomeMessage: link.welcomeMessage ?? null,- enableAIAgents: link.enableAIAgents ?? false,- });-const handleEditLink = (link: LinkWithViews) => {setOpenLinkSheetToFiles(false);setSelectedLink(buildLinkFormData(link));@@ -1235,6 +1176,19 @@ export default function LinksTable({mutate(linksApiRoute);}setInviteLink(null);+ // Invitees land on the room's participant list, where their+ // invited status and access now show up. The list is cached,+ // so drop it first or the fresh invite would not be there.+ if (targetType === "DATAROOM" && targetId) {+ mutate(+ (key) =>+ typeof key === "string" &&+ key.includes(`/datarooms/${targetId}/visitors`),+ undefined,+ { revalidate: true },+ );+ router.push(`/datarooms/${targetId}/participants`);+ }}}/>) : null}diff --git a/components/sidebar/dataroom-sidebar.tsx b/components/sidebar/dataroom-sidebar.tsxindex a24a0727..dcb09825 100644--- a/components/sidebar/dataroom-sidebar.tsx+++ b/components/sidebar/dataroom-sidebar.tsx@@ -26,6 +26,7 @@ import {SnowflakeIcon,TableIcon,TriangleAlertIcon,+ UserRoundIcon,UsersIcon,} from "lucide-react";@@ -197,6 +198,12 @@ export function DataroomSidebarContent() {},],},+ {+ title: "Participants",+ href: `/datarooms/${dataroomId}/participants`,+ icon: UserRoundIcon,+ segment: "participants",+ },{title: "Analytics",href: `/datarooms/${dataroomId}/analytics`,diff --git a/components/visitors/contacts-table.tsx b/components/visitors/contacts-table.tsxindex bf980c6e..e6ae1726 100644--- a/components/visitors/contacts-table.tsx+++ b/components/visitors/contacts-table.tsx@@ -10,9 +10,15 @@ import {useReactTable,} from "@tanstack/react-table";import {+ BadgeCheckIcon,+ BadgeInfoIcon,ChevronDownIcon,ChevronUpIcon,ChevronsUpDownIcon,+ FileBadgeIcon,+ FileSignatureIcon,+ GlobeIcon,+ UserRoundXIcon,} from "lucide-react";import { timeAgo } from "@/lib/utils";@@ -28,29 +34,46 @@ import {TableRow,} from "@/components/ui/table";import { TimestampTooltip } from "@/components/ui/timestamp-tooltip";+import { BadgeTooltip } from "@/components/ui/tooltip";import { VisitorAvatar } from "@/components/visitors/visitor-avatar";+import {+ VisitorAccessSource,+ VisitorStatus,+ VisitorStatusBadge,+} from "@/components/visitors/visitor-status-badge";import { Skeleton } from "../ui/skeleton";type Viewer = {- id: string;+ id: string | null;email: string;- createdAt: Date;- updatedAt: Date;+ createdAt: Date | null;+ updatedAt: Date | null;totalVisits: number;lastViewed: Date | null;viewerName?: string | null;+ isDomain?: boolean;+ verified?: boolean;+ internal?: boolean;+ agreement?: { name: string; signed: boolean } | null;+ status?: VisitorStatus;+ invitedAt?: Date | null;+ invitationStatus?: string | null;+ accessSources?: VisitorAccessSource[];};export function ContactsTable({viewers,+ anonymous,pagination,sorting,+ isFiltered,onPageChange,onPageSizeChange,onSortChange,}: {viewers: Viewer[] | null | undefined;+ anonymous?: { visits: number; lastViewed: Date | null };pagination?: {currentPage: number;pageSize: number;@@ -63,6 +86,7 @@ export function ContactsTable({sortBy: string;sortOrder: string;};+ isFiltered?: boolean;onPageChange?: (page: number) => void;onPageSizeChange?: (size: number) => void;onSortChange?: (sortBy: string, sortOrder: string) => void;@@ -146,11 +170,51 @@ export function ContactsTable({header: "Contact",cell: ({ row }) => (<div className="flex items-center overflow-visible sm:space-x-3">- <VisitorAvatar viewerEmail={row.original.email} />+ {row.original.isDomain ? (+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full border border-gray-200 bg-gray-50 dark:border-gray-700 dark:bg-gray-800">+ <GlobeIcon className="h-4 w-4 text-muted-foreground" />+ </div>+ ) : (+ <VisitorAvatar viewerEmail={row.original.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">- {row.original.viewerName || row.original.email}+ <span className="truncate">+ {row.original.viewerName || row.original.email}+ </span>+ {row.original.verified && (+ <BadgeTooltip+ content="Verified email"+ key={`verified-${row.original.email}`}+ >+ <BadgeCheckIcon className="h-4 w-4 shrink-0 text-emerald-500 hover:text-emerald-600" />+ </BadgeTooltip>+ )}+ {row.original.internal && (+ <BadgeTooltip+ content="Internal visitor"+ key={`internal-${row.original.email}`}+ >+ <BadgeInfoIcon className="h-4 w-4 shrink-0 text-blue-500 hover:text-blue-600" />+ </BadgeTooltip>+ )}+ {row.original.agreement && (+ <BadgeTooltip+ content={+ row.original.agreement.signed+ ? `Signed ${row.original.agreement.name}`+ : `Agreed to ${row.original.agreement.name}`+ }+ key={`agreement-${row.original.email}`}+ >+ {row.original.agreement.signed ? (+ <FileSignatureIcon className="h-4 w-4 shrink-0 text-emerald-500 hover:text-emerald-600" />+ ) : (+ <FileBadgeIcon className="h-4 w-4 shrink-0 text-emerald-500 hover:text-emerald-600" />+ )}+ </BadgeTooltip>+ )}</p>{row.original.viewerName && row.original.email && (<p className="text-xs text-muted-foreground/60">@@ -162,6 +226,19 @@ export function ContactsTable({</div>),},+ {+ id: "status",+ header: "Status",+ cell: ({ row }) =>+ row.original.status ? (+ <VisitorStatusBadge+ status={row.original.status}+ invitedAt={row.original.invitedAt}+ invitationStatus={row.original.invitationStatus}+ accessSources={row.original.accessSources}+ />+ ) : null,+ },{accessorKey: "lastViewed",header: ({ column }) => {@@ -212,7 +289,9 @@ export function ContactsTable({},cell: ({ row }) => (<div className="text-sm text-muted-foreground">- {row.original.totalVisits}+ {row.original.totalVisits > 0 || row.original.lastViewed+ ? row.original.totalVisits+ : "-"}</div>),},@@ -234,6 +313,7 @@ export function ContactsTable({<TableHeader><TableRow><TableHead>Name</TableHead>+ <TableHead>Status</TableHead><TableHead>Last Viewed</TableHead><TableHead>Total Views</TableHead></TableRow>@@ -247,6 +327,9 @@ export function ContactsTable({<Skeleton className="h-4 w-[200px]" /></div></TableCell>+ <TableCell>+ <Skeleton className="h-4 w-[80px]" />+ </TableCell><TableCell><Skeleton className="h-4 w-[100px]" /></TableCell>@@ -261,7 +344,9 @@ export function ContactsTable({);}- const handleRowClick = (id: string) => {+ const handleRowClick = (id: string | null) => {+ // Allow-list entries and domains have no viewer profile to open.+ if (!id) return;router.push(`/visitors/${id}`);};@@ -291,7 +376,7 @@ export function ContactsTable({<TableRowkey={row.id}onClick={() => handleRowClick(row.original.id)}- className="cursor-pointer"+ className={row.original.id ? "cursor-pointer" : undefined}>{row.getVisibleCells().map((cell) => {return (@@ -315,6 +400,51 @@ export function ContactsTable({</TableCell></TableRow>)}++ {anonymous &&+ anonymous.visits > 0 &&+ !isFiltered &&+ (!pagination || !pagination.hasNext) ? (+ <TableRow className="bg-gray-50/60 hover:bg-gray-50/60 dark:bg-gray-900/40 dark:hover:bg-gray-900/40">+ <TableCell>+ <div className="flex items-center overflow-visible sm:space-x-3">+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full border border-dashed border-gray-300 dark:border-gray-700">+ <UserRoundXIcon className="h-4 w-4 text-muted-foreground" />+ </div>+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium text-gray-800 dark:text-gray-200">+ Anonymous visitors+ </p>+ <p className="text-xs text-muted-foreground/60">+ Visits from links that do not ask for an email+ </p>+ </div>+ </div>+ </TableCell>+ <TableCell />+ <TableCell className="text-sm text-muted-foreground">+ {anonymous.lastViewed ? (+ <TimestampTooltip+ timestamp={anonymous.lastViewed}+ side="right"+ rows={["local", "utc", "unix"]}+ >+ <time+ className="select-none"+ dateTime={new Date(anonymous.lastViewed).toISOString()}+ >+ {timeAgo(anonymous.lastViewed)}+ </time>+ </TimestampTooltip>+ ) : (+ "-"+ )}+ </TableCell>+ <TableCell className="text-sm text-muted-foreground">+ {anonymous.visits}+ </TableCell>+ </TableRow>+ ) : null}</TableBody></Table></div>diff --git a/components/visitors/dataroom-participants-table.tsx b/components/visitors/dataroom-participants-table.tsxnew file mode 100644index 00000000..9ee38440--- /dev/null+++ b/components/visitors/dataroom-participants-table.tsx@@ -0,0 +1,367 @@+import { useRouter } from "next/router";++import {+ BadgeCheckIcon,+ BadgeInfoIcon,+ ChevronDownIcon,+ ChevronUpIcon,+ ChevronsUpDownIcon,+ DownloadCloudIcon,+ FileBadgeIcon,+ FileSignatureIcon,+ GlobeIcon,+ UserRoundXIcon,+ UsersIcon,+} from "lucide-react";++import {+ AnonymousVisitorStats,+ DataroomVisitor,+} from "@/lib/swr/use-dataroom-visitors";+import { timeAgo } from "@/lib/utils";++import { Pagination } from "@/components/documents/pagination";+import { Button } from "@/components/ui/button";+import { Skeleton } from "@/components/ui/skeleton";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";+import { TimestampTooltip } from "@/components/ui/timestamp-tooltip";+import { BadgeTooltip } from "@/components/ui/tooltip";++import { VisitorAvatar } from "./visitor-avatar";+import { VisitorStatusBadge } from "./visitor-status-badge";++export function DataroomParticipantsTable({+ visitors,+ anonymous,+ pagination,+ sorting,+ isFiltered,+ onPageChange,+ onPageSizeChange,+ onSortChange,+}: {+ visitors: DataroomVisitor[] | null | undefined;+ anonymous?: AnonymousVisitorStats;+ pagination?: {+ currentPage: number;+ pageSize: number;+ totalItems: number;+ totalPages: number;+ hasNext: boolean;+ hasPrev: boolean;+ };+ sorting?: {+ sortBy: string;+ sortOrder: string;+ };+ isFiltered?: boolean;+ onPageChange?: (page: number) => void;+ onPageSizeChange?: (size: number) => void;+ onSortChange?: (sortBy: string, sortOrder: string) => void;+}) {+ const router = useRouter();++ const handleSort = (columnId: string) => {+ if (!onSortChange) return;++ if (sorting?.sortBy === columnId) {+ onSortChange(columnId, sorting.sortOrder === "asc" ? "desc" : "asc");+ } else {+ onSortChange(columnId, "desc");+ }+ };++ const getSortIcon = (columnId: string) => {+ if (sorting?.sortBy !== columnId) {+ return <ChevronsUpDownIcon className="ml-2 h-4 w-4" />;+ }+ return sorting.sortOrder === "asc" ? (+ <ChevronUpIcon className="ml-2 h-4 w-4" />+ ) : (+ <ChevronDownIcon className="ml-2 h-4 w-4" />+ );+ };++ const sortButton = (columnId: string, label: string) => (+ <Button+ variant="ghost"+ onClick={() => handleSort(columnId)}+ className={+ sorting?.sortBy === columnId+ ? "text-nowrap px-2 font-medium"+ : "text-nowrap px-2 font-normal"+ }+ >+ {label}+ {getSortIcon(columnId)}+ </Button>+ );++ return (+ <div className="space-y-4">+ <div className="overflow-x-auto rounded-md border">+ <Table className="min-w-[760px]">+ <TableHeader>+ <TableRow className="*:whitespace-nowrap *:font-medium hover:bg-transparent">+ <TableHead>Participant</TableHead>+ <TableHead className="w-[170px]">Status</TableHead>+ <TableHead className="w-[130px]">+ {sortButton("totalVisits", "Visits")}+ </TableHead>+ <TableHead className="w-[150px]">+ {sortButton("lastViewed", "Last Viewed")}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {!visitors ? (+ [...Array(5)].map((_, index) => (+ <TableRow key={index}>+ <TableCell>+ <div className="flex items-center space-x-3">+ <Skeleton className="h-10 w-10 rounded-full" />+ <Skeleton className="h-4 w-[200px]" />+ </div>+ </TableCell>+ <TableCell>+ <Skeleton className="h-4 w-20" />+ </TableCell>+ <TableCell>+ <Skeleton className="h-4 w-10" />+ </TableCell>+ <TableCell>+ <Skeleton className="h-4 w-[100px]" />+ </TableCell>+ </TableRow>+ ))+ ) : visitors.length === 0 ? (+ <TableRow>+ <TableCell colSpan={4} className="h-24 text-center">+ {isFiltered+ ? "No participants match your search."+ : "No participants yet."}+ </TableCell>+ </TableRow>+ ) : (+ visitors.map((visitor) => {+ const rowKey = visitor.id ?? visitor.email;+ // Blocked people may still have visited before being blocked.+ const hasActivity =+ visitor.totalVisits > 0 ||+ visitor.documentViews > 0 ||+ !!visitor.lastViewed;+ // Both dataroom groups (permissions) and team visitor groups.+ const groupNames = Array.from(+ new Set(+ visitor.accessSources+ .filter(+ (source) =>+ source.type === "GROUP" ||+ source.type === "VISITOR_GROUP",+ )+ .map((source) => source.name),+ ),+ );+ return (+ <TableRow+ key={rowKey}+ onClick={() =>+ visitor.id && router.push(`/visitors/${visitor.id}`)+ }+ className={visitor.id ? "cursor-pointer" : undefined}+ >+ {/* Participant */}+ <TableCell>+ <div className="flex items-center overflow-visible sm:space-x-3">+ {visitor.isDomain ? (+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full border border-gray-200 bg-gray-50 dark:border-gray-700 dark:bg-gray-800">+ <GlobeIcon className="h-4 w-4 text-muted-foreground" />+ </div>+ ) : (+ <VisitorAvatar viewerEmail={visitor.email} />+ )}+ <div className="min-w-0 flex-1">+ <p className="flex items-center gap-x-2 overflow-visible text-sm font-medium text-gray-800 dark:text-gray-200">+ <span className="truncate">+ {visitor.viewerName || visitor.email}+ </span>+ {visitor.verified && (+ <BadgeTooltip+ content="Verified email"+ key={`verified-${rowKey}`}+ >+ <BadgeCheckIcon className="h-4 w-4 shrink-0 text-emerald-500 hover:text-emerald-600" />+ </BadgeTooltip>+ )}+ {visitor.internal && (+ <BadgeTooltip+ content="Internal visitor"+ key={`internal-${rowKey}`}+ >+ <BadgeInfoIcon className="h-4 w-4 shrink-0 text-blue-500 hover:text-blue-600" />+ </BadgeTooltip>+ )}+ {visitor.agreement && (+ <BadgeTooltip+ content={+ visitor.agreement.signed+ ? `Signed ${visitor.agreement.name}`+ : `Agreed to ${visitor.agreement.name}`+ }+ key={`agreement-${rowKey}`}+ >+ {visitor.agreement.signed ? (+ <FileSignatureIcon className="h-4 w-4 shrink-0 text-emerald-500 hover:text-emerald-600" />+ ) : (+ <FileBadgeIcon className="h-4 w-4 shrink-0 text-emerald-500 hover:text-emerald-600" />+ )}+ </BadgeTooltip>+ )}+ {visitor.downloads > 0 && (+ <BadgeTooltip+ content={`${visitor.downloads} download${visitor.downloads === 1 ? "" : "s"}`}+ key={`downloads-${rowKey}`}+ >+ <DownloadCloudIcon className="h-4 w-4 shrink-0 text-cyan-500 hover:text-cyan-600" />+ </BadgeTooltip>+ )}+ {groupNames.map((group) => (+ <span+ key={`${rowKey}-group-${group}`}+ className="inline-flex max-w-[150px] shrink-0 items-center gap-1 rounded-full border border-gray-200 px-2 py-0.5 text-xs font-normal text-muted-foreground dark:border-gray-700"+ >+ <UsersIcon className="h-3 w-3 shrink-0" />+ <span className="truncate">{group}</span>+ </span>+ ))}+ </p>+ {visitor.viewerName && visitor.email && (+ <p className="truncate text-xs text-muted-foreground/60">+ {visitor.email}+ </p>+ )}+ </div>+ </div>+ </TableCell>+ {/* Status */}+ <TableCell>+ <VisitorStatusBadge+ status={visitor.status}+ invitedAt={visitor.invitedAt}+ invitationStatus={visitor.invitationStatus}+ accessSources={visitor.accessSources}+ visitedLinks={+ visitor.hasVisitedLinks ? visitor.linkNames : undefined+ }+ />+ </TableCell>+ {/* Visits */}+ <TableCell className="text-sm text-muted-foreground">+ {hasActivity ? (+ <>+ {visitor.totalVisits}+ {visitor.documentViews > 0 ? (+ <span className="ml-1 text-xs text-muted-foreground/60">+ ({visitor.documentViews} doc+ {visitor.documentViews === 1 ? "" : "s"})+ </span>+ ) : null}+ </>+ ) : (+ "-"+ )}+ </TableCell>+ {/* Last Viewed */}+ <TableCell className="text-sm text-muted-foreground">+ {visitor.lastViewed ? (+ <TimestampTooltip+ timestamp={visitor.lastViewed}+ side="right"+ rows={["local", "utc", "unix"]}+ >+ <time+ className="select-none"+ dateTime={new Date(visitor.lastViewed).toISOString()}+ >+ {timeAgo(visitor.lastViewed)}+ </time>+ </TimestampTooltip>+ ) : (+ "-"+ )}+ </TableCell>+ </TableRow>+ );+ })+ )}++ {anonymous &&+ anonymous.visits > 0 &&+ !isFiltered &&+ (!pagination || !pagination.hasNext) ? (+ <TableRow className="bg-gray-50/60 hover:bg-gray-50/60 dark:bg-gray-900/40 dark:hover:bg-gray-900/40">+ <TableCell>+ <div className="flex items-center overflow-visible sm:space-x-3">+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full border border-dashed border-gray-300 dark:border-gray-700">+ <UserRoundXIcon className="h-4 w-4 text-muted-foreground" />+ </div>+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium text-gray-800 dark:text-gray-200">+ Anonymous participants+ </p>+ <p className="text-xs text-muted-foreground/60">+ Visits from links that do not ask for an email+ </p>+ </div>+ </div>+ </TableCell>+ <TableCell />+ <TableCell className="text-sm text-muted-foreground">+ {anonymous.visits}+ </TableCell>+ <TableCell className="text-sm text-muted-foreground">+ {anonymous.lastViewed ? (+ <TimestampTooltip+ timestamp={anonymous.lastViewed}+ side="right"+ rows={["local", "utc", "unix"]}+ >+ <time+ className="select-none"+ dateTime={new Date(anonymous.lastViewed).toISOString()}+ >+ {timeAgo(anonymous.lastViewed)}+ </time>+ </TimestampTooltip>+ ) : (+ "-"+ )}+ </TableCell>+ </TableRow>+ ) : null}+ </TableBody>+ </Table>+ </div>++ {pagination && pagination.totalItems > 0 && (+ <Pagination+ currentPage={pagination.currentPage}+ pageSize={pagination.pageSize}+ totalItems={pagination.totalItems}+ totalPages={pagination.totalPages}+ onPageChange={(page) => onPageChange?.(page)}+ onPageSizeChange={(size) => onPageSizeChange?.(size)}+ totalShownItems={visitors?.length ?? 0}+ itemName="participants"+ />+ )}+ </div>+ );+}diff --git a/components/visitors/visitor-access-card.tsx b/components/visitors/visitor-access-card.tsxnew file mode 100644index 00000000..bf18fc65--- /dev/null+++ b/components/visitors/visitor-access-card.tsx@@ -0,0 +1,195 @@+import { useState } from "react";++import { useTeam } from "@/context/team-context";+import { LinkIcon, PencilIcon, UsersIcon } from "lucide-react";+import { toast } from "sonner";+import useSWR from "swr";++import {+ VisitorAccessSource,+ VisitorRecord,+} from "@/lib/api/visitors/get-visitors";+import { buildLinkFormData } from "@/lib/links/build-link-form-data";+import { LinkWithViews } from "@/lib/types";+import { fetcher } from "@/lib/utils";++import { DataroomLinkSheet } from "@/components/links/link-sheet/dataroom-link-sheet";+import { DEFAULT_LINK_TYPE } from "@/components/links/link-sheet";++import { VisitorStatusBadge } from "./visitor-status-badge";++const LINK_SOURCES = ["ALLOW_LIST", "INVITATION", "DENY_LIST"] as const;+const GROUP_SOURCES = ["GROUP", "VISITOR_GROUP"] as const;++const SOURCE_PREFIX: Record<string, string> = {+ ALLOW_LIST: "Allow list of",+ INVITATION: "Invited on",+ DENY_LIST: "Denied on",+};++/**+ * Where a visitor's access comes from — the detail the participants table only+ * hints at on the status tooltip. Data room links open for editing in place.+ */+export function VisitorAccessCard({ access }: { access: VisitorRecord }) {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const [editing, setEditing] = useState<{+ dataroomId: string;+ link: DEFAULT_LINK_TYPE;+ } | null>(null);+ // Only fetch a room's links once someone asks to edit one of them.+ const [pendingDataroomId, setPendingDataroomId] = useState<string | null>(+ null,+ );+ const [pendingLinkId, setPendingLinkId] = useState<string | null>(null);++ const { isLoading } = useSWR<LinkWithViews[]>(+ teamId && pendingDataroomId+ ? `/api/teams/${teamId}/datarooms/${pendingDataroomId}/links`+ : null,+ fetcher,+ {+ onSuccess: (links) => {+ const link = links?.find((item) => item.id === pendingLinkId);+ if (!link || !pendingDataroomId) {+ toast.error("That link is no longer available.");+ } else {+ setEditing({+ dataroomId: pendingDataroomId,+ link: buildLinkFormData(link),+ });+ }+ setPendingDataroomId(null);+ setPendingLinkId(null);+ },+ onError: () => {+ toast.error("Could not load the link. Please try again.");+ setPendingDataroomId(null);+ setPendingLinkId(null);+ },+ },+ );++ const groups = Array.from(+ new Set(+ access.accessSources+ .filter((source) =>+ GROUP_SOURCES.includes(source.type as (typeof GROUP_SOURCES)[number]),+ )+ .map((source) => source.name),+ ),+ );++ const links = access.accessSources.filter((source) =>+ LINK_SOURCES.includes(source.type as (typeof LINK_SOURCES)[number]),+ );++ const assignments = access.accessSources.filter(+ (source) => source.type === "ASSIGNMENT",+ );++ const openLink = (source: VisitorAccessSource) => {+ if (!source.id || !source.dataroomId) return;+ setPendingDataroomId(source.dataroomId);+ setPendingLinkId(source.id);+ };++ return (+ <>+ <div className="mt-4 rounded-lg border border-gray-200 p-4 dark:border-gray-800">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-xs font-medium uppercase tracking-wide text-muted-foreground">+ Access+ </span>+ <VisitorStatusBadge+ status={access.status}+ invitedAt={access.invitedAt}+ invitationStatus={access.invitationStatus}+ accessSources={access.accessSources}+ />+ {access.agreement ? (+ <span className="text-xs text-muted-foreground">+ {access.agreement.signed ? "Signed" : "Agreed to"}{" "}+ {access.agreement.name}+ </span>+ ) : null}+ </div>++ {groups.length > 0 && (+ <div className="mt-3 flex flex-wrap items-center gap-1.5">+ {groups.map((group) => (+ <span+ key={`access-group-${group}`}+ className="inline-flex items-center gap-1 rounded-full border border-gray-200 px-2 py-0.5 text-xs text-muted-foreground dark:border-gray-700"+ >+ <UsersIcon className="h-3 w-3 shrink-0" />+ {group}+ </span>+ ))}+ </div>+ )}++ {links.length > 0 && (+ <ul className="mt-3 space-y-1">+ {links.map((source) => {+ const editable = !!source.id && !!source.dataroomId;+ const busy = pendingLinkId === source.id && isLoading;++ return (+ <li+ key={`access-link-${source.type}-${source.id ?? source.name}`}+ className="flex items-center gap-2 text-xs text-muted-foreground"+ >+ <LinkIcon className="h-3 w-3 shrink-0" />+ <span>+ {SOURCE_PREFIX[source.type] ?? "Via"} {source.name}+ </span>+ {editable ? (+ <button+ type="button"+ onClick={() => openLink(source)}+ disabled={busy}+ className="inline-flex items-center gap-1 rounded px-1 py-0.5 text-xs font-medium text-foreground underline-offset-2 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50"+ >+ <PencilIcon className="h-3 w-3" />+ {busy ? "Opening..." : "Edit link"}+ </button>+ ) : null}+ </li>+ );+ })}+ </ul>+ )}++ {assignments.length > 0 && (+ <p className="mt-3 text-xs text-muted-foreground">+ Assigned in {assignments.map((source) => source.name).join(", ")}+ </p>+ )}++ {groups.length === 0 &&+ links.length === 0 &&+ assignments.length === 0 && (+ <p className="mt-3 text-xs text-muted-foreground">+ No group or allow-list grant recorded — access came from an open+ link.+ </p>+ )}+ </div>++ {editing ? (+ <DataroomLinkSheet+ isOpen+ setIsOpen={(open: boolean) => {+ if (!open) setEditing(null);+ }}+ linkType="DATAROOM_LINK"+ currentLink={editing.link}+ linkTargetId={editing.dataroomId}+ />+ ) : null}+ </>+ );+}diff --git a/components/visitors/visitor-status-badge.tsx b/components/visitors/visitor-status-badge.tsxnew file mode 100644index 00000000..de21fb19--- /dev/null+++ b/components/visitors/visitor-status-badge.tsx@@ -0,0 +1,216 @@+import { UsersIcon } from "lucide-react";++import { cn, timeAgo } from "@/lib/utils";++import { BadgeTooltip } from "@/components/ui/tooltip";++export type VisitorStatus =+ | "BLOCKED"+ | "VISITED"+ | "INVITED"+ | "ALLOWED"+ | "ASSIGNED"+ | "NONE";++export type VisitorAccessSource = {+ type:+ | "ALLOW_LIST"+ | "VISITOR_GROUP"+ | "GROUP"+ | "DENY_LIST"+ | "ASSIGNMENT"+ | "BLOCK_LIST"+ | "INVITATION";+ name: string;+ id?: string | null;+ dataroomId?: string | null;+};++const SOURCE_LABEL: Record<VisitorAccessSource["type"], string> = {+ ALLOW_LIST: "Allow list of",+ VISITOR_GROUP: "Visitor group",+ GROUP: "Group",+ DENY_LIST: "Deny list of",+ ASSIGNMENT: "Assigned in",+ BLOCK_LIST: "On",+ INVITATION: "Invited on",+};++const describeSources = (sources: VisitorAccessSource[]) =>+ sources.map((source) => `${SOURCE_LABEL[source.type]} ${source.name}`);++export function VisitorStatusBadge({+ status,+ invitedAt,+ invitationStatus,+ accessSources,+ visitedLinks,+}: {+ status: VisitorStatus;+ invitedAt?: Date | string | null;+ invitationStatus?: string | null;+ accessSources?: VisitorAccessSource[];+ /** Links this person actually came through, named on the tooltip. */+ visitedLinks?: string[];+}) {+ const sources = accessSources ?? [];++ if (status === "BLOCKED") {+ const blockSources = describeSources(+ sources.filter(+ (source) => source.type === "DENY_LIST" || source.type === "BLOCK_LIST",+ ),+ );+ return (+ <BadgeTooltip+ content={+ blockSources.length+ ? blockSources.join(" · ")+ : "Blocked from accessing"+ }+ key="blocked"+ >+ <span className="inline-flex items-center rounded-md bg-red-50 px-2 py-0.5 text-xs font-medium text-red-700 dark:bg-red-900/30 dark:text-red-300">+ Blocked+ </span>+ </BadgeTooltip>+ );+ }++ if (status === "VISITED") {+ const badge = (+ <span className="inline-flex items-center rounded-md bg-emerald-50 px-2 py-0.5 text-xs font-medium text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300">+ Visited+ </span>+ );++ if (!visitedLinks?.length) {+ return badge;+ }++ return (+ <BadgeTooltip content={`Visited via ${visitedLinks.join(", ")}`} key="visited">+ {badge}+ </BadgeTooltip>+ );+ }++ if (status === "INVITED") {+ const failed =+ invitationStatus === "BOUNCED" || invitationStatus === "FAILED";+ const label = failed+ ? invitationStatus === "BOUNCED"+ ? "Invite bounced"+ : "Invite failed"+ : "Invited";+ const inviteLinks = describeSources(+ sources.filter((source) => source.type === "INVITATION"),+ );+ const tooltip = [+ invitedAt ? `Invited ${timeAgo(invitedAt)}` : "Invited",+ ...inviteLinks,+ "Has not accessed yet",+ ].join(" · ");++ return (+ <BadgeTooltip content={tooltip} key={`invited-${label}`}>+ <span+ className={cn(+ "inline-flex items-center rounded-md px-2 py-0.5 text-xs font-medium",+ failed+ ? "bg-red-50 text-red-700 dark:bg-red-900/30 dark:text-red-300"+ : "bg-amber-50 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300",+ )}+ >+ {label}+ </span>+ </BadgeTooltip>+ );+ }++ if (status === "ASSIGNED") {+ const assignmentSources = describeSources(+ sources.filter((source) => source.type === "ASSIGNMENT"),+ );+ return (+ <BadgeTooltip+ content={+ assignmentSources.length+ ? `${assignmentSources.join(" · ")} · Has not accessed yet`+ : "Assigned work · Has not accessed yet"+ }+ key="assigned"+ >+ <span className="inline-flex items-center rounded-md bg-sky-50 px-2 py-0.5 text-xs font-medium text-sky-700 dark:bg-sky-900/30 dark:text-sky-300">+ Assigned+ </span>+ </BadgeTooltip>+ );+ }++ if (status === "NONE") {+ return (+ <BadgeTooltip+ content="Known contact with no access grant and no activity"+ key="none"+ >+ <span className="inline-flex items-center rounded-md bg-gray-100 px-2 py-0.5 text-xs font-medium text-muted-foreground/70 dark:bg-gray-800">+ No activity+ </span>+ </BadgeTooltip>+ );+ }++ const accessDescriptions = describeSources(+ sources.filter((source) => source.type !== "BLOCK_LIST"),+ );++ // Access granted through a group is labelled with the group itself rather+ // than the generic allow-list wording.+ const groupNames = Array.from(+ new Set(+ sources+ .filter(+ (source) =>+ source.type === "GROUP" || source.type === "VISITOR_GROUP",+ )+ .map((source) => source.name),+ ),+ );++ if (groupNames.length > 0) {+ return (+ <BadgeTooltip+ content={+ accessDescriptions.length+ ? accessDescriptions.join(" · ")+ : "Has access through a group"+ }+ key="group-access"+ >+ <span className="inline-flex max-w-[180px] items-center gap-1 rounded-md bg-gray-100 px-2 py-0.5 text-xs font-medium text-muted-foreground dark:bg-gray-800">+ <UsersIcon className="h-3 w-3 shrink-0" />+ <span className="truncate">{groupNames[0]}</span>+ {groupNames.length > 1 ? (+ <span className="shrink-0">+{groupNames.length - 1}</span>+ ) : null}+ </span>+ </BadgeTooltip>+ );+ }++ return (+ <BadgeTooltip+ content={+ accessDescriptions.length+ ? accessDescriptions.join(" · ")+ : "Has access but has not visited yet"+ }+ key="allowed"+ >+ <span className="inline-flex items-center rounded-md bg-gray-100 px-2 py-0.5 text-xs font-medium text-muted-foreground dark:bg-gray-800">+ On allow list+ </span>+ </BadgeTooltip>+ );+}diff --git a/components/visitors/visitor-status-filter.tsx b/components/visitors/visitor-status-filter.tsxnew file mode 100644index 00000000..1fec755a--- /dev/null+++ b/components/visitors/visitor-status-filter.tsx@@ -0,0 +1,42 @@+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";++export const VISITOR_STATUS_OPTIONS = [+ { value: "all", label: "All statuses" },+ { value: "visited", label: "Visited" },+ { value: "invited", label: "Invited" },+ { value: "allowed", label: "On allow list" },+ { value: "assigned", label: "Assigned" },+ { value: "blocked", label: "Blocked" },+ { value: "none", label: "No activity" },+];++export function VisitorStatusFilter({+ value,+ onChange,+ className,+}: {+ value: string;+ onChange: (value: string) => void;+ className?: string;+}) {+ return (+ <Select value={value} onValueChange={onChange}>+ <SelectTrigger className={className ?? "h-10 w-[160px]"}>+ <SelectValue placeholder="All statuses" />+ </SelectTrigger>+ <SelectContent>+ {VISITOR_STATUS_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}diff --git a/lib/api/visitors/get-visitors.ts b/lib/api/visitors/get-visitors.tsnew file mode 100644index 00000000..af3cb2c8--- /dev/null+++ b/lib/api/visitors/get-visitors.ts@@ -0,0 +1,643 @@+import { Prisma } from "@prisma/client";++import prisma from "@/lib/prisma";++export type VisitorStatus =+ | "BLOCKED"+ | "VISITED"+ | "INVITED"+ | "ALLOWED"+ | "ASSIGNED"+ | "NONE";++export type VisitorAccessSource = {+ type:+ | "ALLOW_LIST"+ | "VISITOR_GROUP"+ | "GROUP"+ | "DENY_LIST"+ | "ASSIGNMENT"+ | "BLOCK_LIST"+ | "INVITATION";+ name: string;+ /** Link id for link-backed sources, group id for group sources. */+ id?: string | null;+ /** Set when the source belongs to a data room, so the UI can open it. */+ dataroomId?: string | null;+};++export type VisitorAgreement = {+ name: string;+ signed: boolean;+ signedAt: Date | null;+};++export type VisitorRecord = {+ id: string | null;+ email: string;+ viewerName: string | null;+ verified: boolean;+ internal: boolean;+ agreement: VisitorAgreement | null;+ isDomain: boolean;+ status: VisitorStatus;+ totalVisits: number;+ documentViews: number;+ downloads: number;+ lastViewed: Date | null;+ invitedAt: Date | null;+ invitationStatus: string | null;+ accessSources: VisitorAccessSource[];+ createdAt: Date | null;+ updatedAt: Date | null;+};++type RawVisitorRow = {+ id: string | null;+ email: string;+ viewerName: string | null;+ verified: boolean | null;+ verifiedViews: number | null;+ status: VisitorStatus;+ totalVisits: number | null;+ documentViews: number | null;+ downloads: number | null;+ lastViewed: Date | null;+ invitedAt: Date | null;+ invitationStatus: string | null;+ accessSources: VisitorAccessSource[] | null;+ globallyBlocked: boolean | null;+ createdAt: Date | null;+ updatedAt: Date | null;+ totalCount: number;+};++const VALID_SORT_FIELDS = ["lastViewed", "totalVisits", "downloads"];+const VALID_SORT_ORDERS = ["asc", "desc"];+const VALID_STATUSES: VisitorStatus[] = [+ "BLOCKED",+ "VISITED",+ "INVITED",+ "ALLOWED",+ "ASSIGNED",+ "NONE",+];++/**+ * Emails assigned work inside the scope: request-list tasks and Q&A questions.+ * Both live behind optional feature sets, so a missing table (an install that+ * has not run those migrations) yields an empty list instead of an error.+ */+async function getAssignmentEntries({+ teamId,+ dataroomId,+}: {+ teamId: string;+ dataroomId?: string;+}): Promise<{ email: string; source: string }[]> {+ const collect = async (sql: Prisma.Sql, source: string) => {+ try {+ const rows = (await prisma.$queryRaw(sql)) as { email: string | null }[];+ return rows+ .map((row) => row.email?.trim().toLowerCase())+ .filter((email): email is string => !!email)+ .map((email) => ({ email, source }));+ } catch (error) {+ return [];+ }+ };++ const [tasks, questions] = await Promise.all([+ collect(+ Prisma.sql`+ SELECT LOWER(COALESCE(av.email, ta.email)) AS email+ FROM "TaskAssignment" ta+ JOIN "Task" tk ON tk.id = ta."taskId"+ LEFT JOIN "Viewer" av ON av.id = ta."viewerId"+ WHERE ${+ dataroomId+ ? Prisma.sql`tk."dataroomId" = ${dataroomId}`+ : Prisma.sql`tk."teamId" = ${teamId}`+ }+ AND COALESCE(av.email, ta.email) IS NOT NULL`,+ "Request list",+ ),+ collect(+ Prisma.sql`+ SELECT LOWER(COALESCE(qv.email, qa.email)) AS email+ FROM "DataroomQuestionAssignment" qa+ JOIN "DataroomQuestion" q ON q.id = qa."questionId"+ LEFT JOIN "Viewer" qv ON qv.id = qa."viewerId"+ WHERE ${+ dataroomId+ ? Prisma.sql`q."dataroomId" = ${dataroomId}`+ : Prisma.sql`EXISTS (SELECT 1 FROM "Dataroom" d WHERE d.id = q."dataroomId" AND d."teamId" = ${teamId})`+ }+ AND COALESCE(qv.email, qa.email) IS NOT NULL`,+ "Q&A",+ ),+ ]);++ // De-duplicate so one person assigned many tasks contributes a single entry.+ const seen = new Set<string>();+ return [...tasks, ...questions].filter((entry) => {+ const key = `${entry.email}::${entry.source}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}++/**+ * Returns the people who can reach a team (or a single dataroom), not just the+ * ones who already showed up: viewers with views, viewers who were invited by+ * email, and the emails/domains sitting on a link allow list — either directly,+ * through a visitor group applied to a link, or through a dataroom group.+ */+export async function getVisitors({+ teamId,+ dataroomId,+ page = 1,+ pageSize = 10,+ sortBy = "lastViewed",+ sortOrder = "desc",+ query,+ email,+ status,+ pauseStartsAt,+ globalBlockList,+}: {+ teamId: string;+ dataroomId?: string;+ page?: number;+ pageSize?: number;+ sortBy?: string;+ sortOrder?: string;+ query?: string;+ /** Exact-match lookup for a single person, far cheaper than `query`. */+ email?: string;+ status?: string;+ pauseStartsAt?: Date | null;+ globalBlockList?: string[];+}) {+ const currentPage = Math.max(page, 1);+ const limit = Math.min(Math.max(pageSize, 1), 100);+ const offset = (currentPage - 1) * limit;++ const sort = VALID_SORT_FIELDS.includes(sortBy) ? sortBy : "lastViewed";+ const order = VALID_SORT_ORDERS.includes(sortOrder) ? sortOrder : "desc";++ const statusFilterValue = status?.toUpperCase();+ const statusFilter = VALID_STATUSES.includes(statusFilterValue as VisitorStatus)+ ? Prisma.sql`WHERE t.status = ${statusFilterValue}`+ : Prisma.empty;++ // Links that grant access within the requested scope.+ // teamId is indexed on Link while dataroomId is not, so lead with it — this+ // matches how the dataroom links endpoint already filters.+ const linkScope = dataroomId+ ? Prisma.sql`l."teamId" = ${teamId} AND l."dataroomId" = ${dataroomId}`+ : Prisma.sql`(+ l."teamId" = ${teamId}+ OR EXISTS (SELECT 1 FROM "Dataroom" d WHERE d.id = l."dataroomId" AND d."teamId" = ${teamId})+ OR EXISTS (SELECT 1 FROM "Document" doc WHERE doc.id = l."documentId" AND doc."teamId" = ${teamId})+ )`;++ const viewerGroupScope = dataroomId+ ? Prisma.sql`g."dataroomId" = ${dataroomId}`+ : Prisma.sql`g."teamId" = ${teamId}`;++ // Assignment tables belong to optional feature sets and may be absent on+ // installations that have not run every migration, so they are looked up+ // separately and skipped when unavailable rather than breaking the list.+ const assignmentEntries = await getAssignmentEntries({ teamId, dataroomId });+ const assignmentEntriesSelect = assignmentEntries.length+ ? Prisma.sql`+ SELECT a.email_key, 'ASSIGNMENT' AS source_type, a.source_name,+ NULL::text AS source_id, NULL::text AS source_dataroom_id+ FROM UNNEST(+ ARRAY[${Prisma.join(assignmentEntries.map((entry) => entry.email))}]::text[],+ ARRAY[${Prisma.join(assignmentEntries.map((entry) => entry.source))}]::text[]+ ) AS a(email_key, source_name)`+ : Prisma.sql`+ SELECT NULL::text AS email_key, NULL::text AS source_type, NULL::text AS source_name,+ NULL::text AS source_id, NULL::text AS source_dataroom_id+ WHERE FALSE`;++ // The team-wide block list applies everywhere, so it only ever flags people+ // who already surfaced through another source — it never adds rows of its own.+ const blockEntries = Array.from(+ new Set(+ (globalBlockList ?? [])+ .map((entry) => entry.trim().toLowerCase())+ .filter(Boolean),+ ),+ );+ const globalBlockFilter = blockEntries.length+ ? Prisma.sql`EXISTS (+ SELECT 1 FROM UNNEST(ARRAY[${Prisma.join(blockEntries)}]::text[]) AS b+ WHERE p.email_key = b OR (b LIKE '@%' AND p.email_key LIKE '%' || b)+ )`+ : Prisma.sql`FALSE`;++ // Views the stats are built from. Dataroom scope counts room sessions and+ // in-room document views; team scope keeps the historical document-view+ // definition of "total views" so existing numbers do not shift.+ const viewScope = dataroomId+ ? Prisma.sql`+ FROM "View" vw+ WHERE vw."dataroomId" = ${dataroomId}+ AND vw."viewerId" IS NOT NULL+ AND vw."isArchived" = false+ ${pauseStartsAt ? Prisma.sql`AND vw."viewedAt" < ${pauseStartsAt}` : Prisma.empty}`+ : Prisma.sql`+ FROM "View" vw+ JOIN "Viewer" vr ON vr.id = vw."viewerId" AND vr."teamId" = ${teamId}+ WHERE vw."viewerId" IS NOT NULL`;++ const visitsFilter = dataroomId+ ? Prisma.sql`vw."viewType" = 'DATAROOM_VIEW'`+ : Prisma.sql`vw."documentId" IS NOT NULL`;++ const lastViewedExpression = dataroomId+ ? Prisma.sql`MAX(vw."viewedAt")`+ : Prisma.sql`MAX(vw."viewedAt") FILTER (WHERE vw."documentId" IS NOT NULL)`;++ // Team scope lists every viewer of the team (historical behaviour); dataroom+ // scope only lists viewers with activity in that room.+ const basePeople = dataroomId+ ? Prisma.sql`+ SELECT DISTINCT LOWER(v.email) AS email_key+ FROM "Viewer" v+ JOIN view_stats vs ON vs."viewerId" = v.id+ WHERE v."teamId" = ${teamId} AND vs."allViews" > 0`+ : Prisma.sql`+ SELECT DISTINCT LOWER(v.email) AS email_key+ FROM "Viewer" v+ WHERE v."teamId" = ${teamId}`;++ // A viewer-level invite flag only makes sense when not scoped to one room.+ const invitedFallback = dataroomId+ ? Prisma.empty+ : Prisma.sql`OR v."invitedAt" IS NOT NULL`;++ const searchCondition = email+ ? Prisma.sql`AND p.email_key = ${email.trim().toLowerCase()}`+ : query+ ? Prisma.sql`AND (+ p.email_key LIKE LOWER(${`%${query}%`})+ OR LOWER(ln."viewerName") LIKE LOWER(${`%${query}%`})+ )`+ : Prisma.empty;++ let orderByClause: Prisma.Sql;+ if (sort === "totalVisits") {+ orderByClause =+ order === "desc"+ ? Prisma.sql`t."totalVisits" DESC, t."lastViewed" DESC NULLS LAST`+ : Prisma.sql`t."totalVisits" ASC, t."lastViewed" DESC NULLS LAST`;+ } else if (sort === "downloads") {+ orderByClause =+ order === "desc"+ ? Prisma.sql`t."downloads" DESC, t."lastViewed" DESC NULLS LAST`+ : Prisma.sql`t."downloads" ASC, t."lastViewed" DESC NULLS LAST`;+ } else {+ orderByClause =+ order === "desc"+ ? Prisma.sql`t."lastViewed" DESC NULLS LAST, t."createdAt" DESC NULLS LAST, t.email ASC`+ : Prisma.sql`t."lastViewed" ASC NULLS LAST, t."createdAt" DESC NULLS LAST, t.email ASC`;+ }++ const rows = (await prisma.$queryRaw`+ WITH scoped_links AS (+ SELECT l.id, l.name, l."allowList", l."denyList", l."groupId", l."dataroomId"+ FROM "Link" l+ WHERE ${linkScope}+ AND l."isArchived" = false+ AND l."deletedAt" IS NULL+ ),+ allow_list_entries AS (+ SELECT+ LOWER(TRIM(entry)) AS email_key,+ 'ALLOW_LIST' AS source_type,+ COALESCE(NULLIF(sl.name, ''), 'Link #' || RIGHT(sl.id, 5)) AS source_name,+ sl.id AS source_id,+ sl."dataroomId" AS source_dataroom_id+ FROM scoped_links sl, UNNEST(sl."allowList") AS entry+ WHERE TRIM(entry) <> ''+ ),+ visitor_group_entries AS (+ SELECT+ LOWER(TRIM(entry)) AS email_key,+ 'VISITOR_GROUP' AS source_type,+ vg.name AS source_name,+ vg.id AS source_id,+ sl."dataroomId" AS source_dataroom_id+ FROM "LinkVisitorGroup" lvg+ JOIN scoped_links sl ON sl.id = lvg."linkId"+ JOIN "VisitorGroup" vg ON vg.id = lvg."visitorGroupId",+ UNNEST(vg.emails) AS entry+ WHERE TRIM(entry) <> ''+ ),+ viewer_group_domain_entries AS (+ SELECT+ LOWER(TRIM(entry)) AS email_key,+ 'GROUP' AS source_type,+ g.name AS source_name,+ g.id AS source_id,+ g."dataroomId" AS source_dataroom_id+ FROM "ViewerGroup" g, UNNEST(g.domains) AS entry+ WHERE ${viewerGroupScope}+ AND TRIM(entry) <> ''+ ),+ viewer_group_member_entries AS (+ SELECT+ LOWER(mv.email) AS email_key,+ 'GROUP' AS source_type,+ g.name AS source_name,+ g.id AS source_id,+ g."dataroomId" AS source_dataroom_id+ FROM "ViewerGroupMembership" m+ JOIN "ViewerGroup" g ON g.id = m."groupId"+ JOIN "Viewer" mv ON mv.id = m."viewerId"+ WHERE ${viewerGroupScope}+ ),+ deny_list_entries AS (+ SELECT+ LOWER(TRIM(entry)) AS email_key,+ 'DENY_LIST' AS source_type,+ COALESCE(NULLIF(sl.name, ''), 'Link #' || RIGHT(sl.id, 5)) AS source_name,+ sl.id AS source_id,+ sl."dataroomId" AS source_dataroom_id+ FROM scoped_links sl, UNNEST(sl."denyList") AS entry+ WHERE TRIM(entry) <> ''+ ),+ invitation_link_entries AS (+ SELECT+ LOWER(iv.email) AS email_key,+ 'INVITATION' AS source_type,+ COALESCE(NULLIF(sl.name, ''), 'Link #' || RIGHT(sl.id, 5)) AS source_name,+ sl.id AS source_id,+ sl."dataroomId" AS source_dataroom_id+ FROM "ViewerInvitation" vi+ JOIN scoped_links sl ON sl.id = vi."linkId"+ JOIN "Viewer" iv ON iv.id = vi."viewerId"+ ),+ invitation_group_entries AS (+ SELECT+ LOWER(iv.email) AS email_key,+ 'GROUP' AS source_type,+ g.name AS source_name,+ g.id AS source_id,+ g."dataroomId" AS source_dataroom_id+ FROM "ViewerInvitation" vi+ JOIN scoped_links sl ON sl.id = vi."linkId"+ JOIN "Viewer" iv ON iv.id = vi."viewerId"+ JOIN "ViewerGroup" g ON g.id = COALESCE(vi."groupId", sl."groupId")+ ),+ assignment_entries AS (+ ${assignmentEntriesSelect}+ ),+ access_entries AS (+ SELECT * FROM allow_list_entries+ UNION ALL SELECT * FROM visitor_group_entries+ UNION ALL SELECT * FROM viewer_group_domain_entries+ UNION ALL SELECT * FROM viewer_group_member_entries+ UNION ALL SELECT * FROM deny_list_entries+ UNION ALL SELECT * FROM invitation_link_entries+ UNION ALL SELECT * FROM invitation_group_entries+ UNION ALL SELECT * FROM assignment_entries+ ),+ access_agg AS (+ SELECT+ email_key,+ JSONB_AGG(DISTINCT JSONB_BUILD_OBJECT(+ 'type', source_type,+ 'name', source_name,+ 'id', source_id,+ 'dataroomId', source_dataroom_id+ )) AS sources,+ BOOL_OR(source_type IN ('ALLOW_LIST', 'VISITOR_GROUP', 'GROUP')) AS has_access,+ BOOL_OR(source_type = 'ASSIGNMENT') AS has_assignment,+ BOOL_OR(source_type = 'DENY_LIST') AS has_deny+ FROM access_entries+ GROUP BY email_key+ ),+ invite_agg AS (+ SELECT+ LOWER(iv.email) AS email_key,+ MAX(vi."sentAt") AS invited_at,+ (ARRAY_AGG(vi.status::text ORDER BY vi."sentAt" DESC))[1] AS invitation_status+ FROM "ViewerInvitation" vi+ JOIN scoped_links sl ON sl.id = vi."linkId"+ JOIN "Viewer" iv ON iv.id = vi."viewerId"+ GROUP BY LOWER(iv.email)+ ),+ view_stats AS (+ SELECT+ vw."viewerId",+ COUNT(*)::int AS "allViews",+ COUNT(*) FILTER (WHERE ${visitsFilter})::int AS "totalVisits",+ COUNT(DISTINCT vw."documentId")::int AS "documentViews",+ COUNT(*) FILTER (WHERE vw."downloadedAt" IS NOT NULL)::int AS "downloads",+ COUNT(*) FILTER (WHERE vw.verified)::int AS "verifiedViews",+ ${lastViewedExpression} AS "lastViewed"+ ${viewScope}+ GROUP BY vw."viewerId"+ ),+ latest_viewer_names AS (+ SELECT DISTINCT ON (vw."viewerId")+ vw."viewerId",+ vw."viewerName"+ ${viewScope}+ AND vw."viewerName" IS NOT NULL+ ORDER BY vw."viewerId", vw."viewedAt" DESC+ ),+ people AS (+ ${basePeople}+ UNION+ SELECT email_key FROM access_agg+ UNION+ SELECT email_key FROM invite_agg+ ),+ joined AS (+ SELECT+ v.id,+ COALESCE(v.email, p.email_key) AS email,+ ln."viewerName" AS "viewerName",+ COALESCE(v.verified, false) AS verified,+ CASE+ WHEN COALESCE(aa.has_deny, false) OR ${globalBlockFilter} THEN 'BLOCKED'+ WHEN COALESCE(vs."allViews", 0) > 0 THEN 'VISITED'+ WHEN ia.email_key IS NOT NULL ${invitedFallback} THEN 'INVITED'+ WHEN COALESCE(aa.has_access, false) THEN 'ALLOWED'+ WHEN COALESCE(aa.has_assignment, false) THEN 'ASSIGNED'+ ELSE 'NONE'+ END AS status,+ ${globalBlockFilter} AS "globallyBlocked",+ COALESCE(vs."totalVisits", 0) AS "totalVisits",+ COALESCE(vs."documentViews", 0) AS "documentViews",+ COALESCE(vs."downloads", 0) AS "downloads",+ COALESCE(vs."verifiedViews", 0) AS "verifiedViews",+ vs."lastViewed" AS "lastViewed",+ COALESCE(ia.invited_at, v."invitedAt") AS "invitedAt",+ ia.invitation_status AS "invitationStatus",+ aa.sources AS "accessSources",+ v."createdAt" AS "createdAt",+ v."updatedAt" AS "updatedAt"+ FROM people p+ LEFT JOIN "Viewer" v ON LOWER(v.email) = p.email_key AND v."teamId" = ${teamId}+ LEFT JOIN view_stats vs ON vs."viewerId" = v.id+ LEFT JOIN latest_viewer_names ln ON ln."viewerId" = v.id+ LEFT JOIN access_agg aa ON aa.email_key = p.email_key+ LEFT JOIN invite_agg ia ON ia.email_key = p.email_key+ WHERE TRUE+ ${searchCondition}+ )+ SELECT t.*, (COUNT(*) OVER())::int AS "totalCount"+ FROM joined t+ ${statusFilter}+ ORDER BY ${orderByClause}+ LIMIT ${limit}+ OFFSET ${offset}+ `) as RawVisitorRow[];++ const viewerIds = rows+ .map((row) => row.id)+ .filter((id): id is string => !!id);++ // Agreements (NDAs) are answered per view, so the newest response in scope+ // stands for the person.+ const agreementResponses = viewerIds.length+ ? await prisma.agreementResponse.findMany({+ where: {+ view: {+ viewerId: { in: viewerIds },+ ...(dataroomId ? { dataroomId } : { teamId }),+ },+ },+ orderBy: { id: "desc" },+ select: {+ signingStatus: true,+ signedAt: true,+ completedAt: true,+ view: { select: { viewerId: true } },+ agreement: {+ select: {+ name: true,+ contentType: true,+ signingProvider: true,+ },+ },+ },+ })+ : [];++ const agreementByViewer = new Map<string, VisitorAgreement>();+ agreementResponses.forEach((response) => {+ const viewerId = response.view?.viewerId;+ if (!viewerId || agreementByViewer.has(viewerId)) return;++ // Signing agreements are only "signed" once the provider says so; plain+ // agreements count as accepted the moment the response exists.+ const isSigningAgreement =+ response.agreement.signingProvider === "DOCUMENSO" ||+ response.agreement.contentType === "SIGNING";+ const signed = isSigningAgreement+ ? response.signingStatus === "SIGNED" ||+ response.signingStatus === "COMPLETED"+ : true;++ agreementByViewer.set(viewerId, {+ name: response.agreement.name,+ signed,+ signedAt: response.signedAt ?? response.completedAt,+ });+ });++ // Teammates who opened the link show up as visitors too; flag them so the+ // table can mark them as internal.+ const teamUsers = await prisma.user.findMany({+ where: { teams: { some: { teamId } } },+ select: { email: true },+ });+ const teamEmails = new Set(+ teamUsers+ .map((user) => user.email?.toLowerCase())+ .filter((email): email is string => !!email),+ );++ // Views from links that do not ask for an email have no viewer to attach to,+ // so they are reported as one aggregate row instead of being dropped.+ const anonymousStats = await prisma.view.aggregate({+ where: dataroomId+ ? {+ dataroomId,+ viewerId: null,+ isArchived: false,+ ...(pauseStartsAt && { viewedAt: { lt: pauseStartsAt } }),+ }+ : { teamId, viewerId: null },+ _count: { _all: true },+ _max: { viewedAt: true },+ });++ const totalCount = rows[0]?.totalCount ?? 0;+ const totalPages = Math.ceil(totalCount / limit);++ const visitors: VisitorRecord[] = rows.map((row) => ({+ id: row.id,+ email: row.email,+ viewerName: row.viewerName,+ // A viewer counts as verified once any of their views was email-verified.+ verified: (row.verified ?? false) || (row.verifiedViews ?? 0) > 0,+ internal: teamEmails.has(row.email.toLowerCase()),+ agreement: row.id ? (agreementByViewer.get(row.id) ?? null) : null,+ isDomain: row.email.startsWith("@"),+ status: row.status,+ totalVisits: row.totalVisits ?? 0,+ documentViews: row.documentViews ?? 0,+ downloads: row.downloads ?? 0,+ lastViewed: row.lastViewed,+ invitedAt: row.invitedAt,+ invitationStatus: row.invitationStatus,+ accessSources: [+ ...(row.accessSources ?? []).map((source) => ({+ type: source.type as VisitorAccessSource["type"],+ name: source.name,+ id: source.id ?? null,+ dataroomId: source.dataroomId ?? null,+ })),+ ...(row.globallyBlocked+ ? [+ {+ type: "BLOCK_LIST" as const,+ name: "Team block list",+ },+ ]+ : []),+ ],+ createdAt: row.createdAt,+ updatedAt: row.updatedAt,+ }));++ return {+ visitors,+ anonymous: {+ visits: anonymousStats._count._all,+ lastViewed: anonymousStats._max.viewedAt,+ },+ pagination: {+ currentPage,+ pageSize: limit,+ totalItems: totalCount,+ totalPages,+ hasNext: currentPage < totalPages,+ hasPrev: currentPage > 1,+ },+ sorting: {+ sortBy: sort,+ sortOrder: order,+ },+ };+}diff --git a/lib/links/build-link-form-data.ts b/lib/links/build-link-form-data.tsnew file mode 100644index 00000000..56c00bc2--- /dev/null+++ b/lib/links/build-link-form-data.ts@@ -0,0 +1,69 @@+import { DEFAULT_LINK_TYPE } from "@/components/links/link-sheet";++import { LinkWithViews, WatermarkConfig } from "@/lib/types";++/**+ * Maps a saved link onto the shape the link sheet edits, so any surface that+ * can name a link can also open it for editing.+ */+export const buildLinkFormData = (+ link: LinkWithViews,+): DEFAULT_LINK_TYPE => ({+ id: link.id,+ name: link.name || `Link #${link.id.slice(-5)}`,+ domain: link.domainSlug,+ slug: link.slug,+ expiresAt: link.expiresAt,+ password: link.password,+ emailProtected: link.emailProtected,+ emailAuthenticated: link.emailAuthenticated,+ allowDownload: link.allowDownload ? link.allowDownload : false,+ allowList: link.allowList,+ denyList: link.denyList,+ visitorGroupIds:+ link.visitorGroups?.map(+ (vg: { visitorGroupId: string }) => vg.visitorGroupId,+ ) || [],+ enableNotification: link.enableNotification+ ? link.enableNotification+ : false,+ enableFeedback: link.enableFeedback ? link.enableFeedback : false,+ enableScreenshotProtection: link.enableScreenshotProtection+ ? link.enableScreenshotProtection+ : false,+ enableConfidentialView: link.enableConfidentialView+ ? link.enableConfidentialView+ : false,+ enableCustomMetatag: link.enableCustomMetatag+ ? link.enableCustomMetatag+ : false,+ enableQuestion: link.enableQuestion ? link.enableQuestion : false,+ questionText: link.feedback ? link.feedback.data?.question : "",+ questionType: link.feedback ? link.feedback.data?.type : "",+ metaTitle: link.metaTitle,+ metaDescription: link.metaDescription,+ metaImage: link.metaImage,+ metaFavicon: link.metaFavicon,+ enableAgreement: link.enableAgreement ? link.enableAgreement : false,+ agreementId: link.agreementId,+ showBanner: link.showBanner ?? false,+ enableWatermark: link.enableWatermark ?? false,+ watermarkConfig: link.watermarkConfig as WatermarkConfig | null,+ audienceType: link.audienceType,+ groupId: link.groupId,+ customFields: link.customFields || [],+ tags: link.tags.map((tag) => tag.id) || [],+ enableConversation: link.enableConversation ?? false,+ enableUpload: link.enableUpload ?? false,+ isFileRequestOnly: link.isFileRequestOnly ?? false,+ uploadFolderIds: Array.isArray(link.uploadFolderIds)+ ? link.uploadFolderIds+ : [],+ uploadFolders: Array.isArray(link.uploadFolders)+ ? link.uploadFolders+ : [],+ enableIndexFile: link.enableIndexFile ?? false,+ permissionGroupId: link.permissionGroupId ?? null,+ welcomeMessage: link.welcomeMessage ?? null,+ enableAIAgents: link.enableAIAgents ?? false,+});diff --git a/lib/swr/use-dataroom-visitors.ts b/lib/swr/use-dataroom-visitors.tsnew file mode 100644index 00000000..f879e672--- /dev/null+++ b/lib/swr/use-dataroom-visitors.ts@@ -0,0 +1,125 @@+import { useRouter } from "next/router";++import { useTeam } from "@/context/team-context";+import useSWR from "swr";++import { fetcher } from "@/lib/utils";++import type {+ VisitorAccessSource,+ VisitorStatus,+} from "@/components/visitors/visitor-status-badge";++export type DataroomVisitor = {+ id: string | null;+ email: string;+ viewerName: string | null;+ verified: boolean;+ agreement: { name: string; signed: boolean; signedAt: Date | null } | null;+ isDomain: boolean;+ status: VisitorStatus;+ invitedAt: Date | null;+ invitationStatus: string | null;+ accessSources: VisitorAccessSource[];+ createdAt: Date | null;+ updatedAt: Date | null;+ totalVisits: number;+ documentViews: number;+ downloads: number;+ lastViewed: Date | null;+ internal: boolean;+ dataroomName: string;+ linkNames: string[];+ hasVisitedLinks: boolean;+};++export type AnonymousVisitorStats = {+ visits: number;+ lastViewed: Date | null;+};++type DataroomVisitorsResponse = {+ visitors: DataroomVisitor[];+ anonymous: AnonymousVisitorStats;+ pagination: {+ currentPage: number;+ pageSize: number;+ totalItems: number;+ totalPages: number;+ hasNext: boolean;+ hasPrev: boolean;+ };+ sorting: {+ sortBy: string;+ sortOrder: string;+ };+};++export function useDataroomVisitors({+ dataroomId,+ page = 1,+ pageSize = 10,+ sortBy = "lastViewed",+ sortOrder = "desc",+ status,+}: {+ dataroomId?: string;+ page?: number;+ pageSize?: number;+ sortBy?: string;+ sortOrder?: string;+ status?: string;+}) {+ const router = useRouter();+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const searchQuery = router.query["search"];++ const queryParams = new URLSearchParams();+ queryParams.append("page", page.toString());+ queryParams.append("pageSize", pageSize.toString());+ queryParams.append("sortBy", sortBy);+ queryParams.append("sortOrder", sortOrder);++ if (searchQuery && typeof searchQuery === "string") {+ queryParams.append("query", searchQuery);+ }++ if (status && status !== "all") {+ queryParams.append("status", status);+ }++ const {+ data: response,+ isValidating,+ error,+ mutate,+ } = useSWR<DataroomVisitorsResponse>(+ teamId && dataroomId+ ? `/api/teams/${teamId}/datarooms/${dataroomId}/visitors?${queryParams.toString()}`+ : null,+ fetcher,+ {+ revalidateOnFocus: false,+ revalidateIfStale: false,+ revalidateOnReconnect: false,+ dedupingInterval: 30000,+ keepPreviousData: true,+ errorRetryCount: 2,+ errorRetryInterval: 5000,+ },+ );++ return {+ visitors: response?.visitors,+ anonymous: response?.anonymous,+ pagination: response?.pagination,+ sorting: response?.sorting,+ isValidating,+ loading: !response && !error,+ isFiltered: !!searchQuery || (!!status && status !== "all"),+ error,+ mutate,+ };+}diff --git a/lib/swr/use-viewer.ts b/lib/swr/use-viewer.tsindex 891ed287..c47d88a0 100644--- a/lib/swr/use-viewer.ts+++ b/lib/swr/use-viewer.ts@@ -6,11 +6,14 @@ import { useMemo } from "react";import { fetcher } from "@/lib/utils";+import type { VisitorRecord } from "@/lib/api/visitors/get-visitors";+type ViewerWithViews = {id: string;email: string;createdAt: Date;updatedAt: Date;+ access?: VisitorRecord | null;views: {documentId: string;viewCount: number;diff --git a/lib/swr/use-viewers.ts b/lib/swr/use-viewers.tsindex 1e4ca450..2ebf7078 100644--- a/lib/swr/use-viewers.ts+++ b/lib/swr/use-viewers.ts@@ -6,17 +6,34 @@ import useSWR from "swr";import { fetcher } from "@/lib/utils";+import type {+ VisitorAccessSource,+ VisitorStatus,+} from "@/components/visitors/visitor-status-badge";+type ViewerWithStats = {- id: string;+ id: string | null;email: string;- createdAt: Date;- updatedAt: Date;+ viewerName: string | null;+ verified: boolean;+ internal: boolean;+ agreement: { name: string; signed: boolean; signedAt: Date | null } | null;+ isDomain: boolean;+ status: VisitorStatus;+ createdAt: Date | null;+ updatedAt: Date | null;totalVisits: number;+ documentViews: number;+ downloads: number;lastViewed: Date | null;+ invitedAt: Date | null;+ invitationStatus: string | null;+ accessSources: VisitorAccessSource[];};type ViewersResponse = {viewers: ViewerWithStats[];+ anonymous: { visits: number; lastViewed: Date | null };pagination: {currentPage: number;pageSize: number;@@ -35,7 +52,8 @@ export default function useViewers(page: number = 1,pageSize: number = 10,sortBy: string = "lastViewed",- sortOrder: string = "desc"+ sortOrder: string = "desc",+ status?: string) {const router = useRouter();const teamInfo = useTeam();@@ -54,6 +72,10 @@ export default function useViewers(queryParams.append('query', searchQuery);}+ if (status && status !== 'all') {+ queryParams.append('status', status);+ }+const queryString = queryParams.toString();const {@@ -80,6 +102,7 @@ export default function useViewers(return {viewers: response?.viewers,+ anonymous: response?.anonymous,pagination: response?.pagination,sorting: response?.sorting,isValidating,diff --git a/pages/api/teams/[teamId]/datarooms/[id]/visitors/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/visitors/index.tsnew file mode 100644index 00000000..47a4751b--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/visitors/index.ts@@ -0,0 +1,186 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth/next";++import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";+import { getVisitors } from "@/lib/api/visitors/get-visitors";+import { errorhandler } from "@/lib/errorHandler";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";+import { log } from "@/lib/utils";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ // GET /api/teams/:teamId/datarooms/:id/visitors+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const {+ teamId,+ id: dataroomId,+ query,+ page,+ pageSize,+ sortBy,+ sortOrder,+ status,+ } = req.query as {+ teamId: string;+ id: string;+ query?: string;+ page?: string;+ pageSize?: string;+ sortBy?: string;+ sortOrder?: string;+ status?: string;+ };+ const userId = (session.user as CustomUser).id;++ // Scoped members may only read visitors for their assigned rooms.+ if (await enforceDataroomMemberScope({ userId, teamId, dataroomId, res })) {+ return;+ }++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: { userId },+ },+ },+ select: { id: true, pauseStartsAt: true, globalBlockList: true },+ });++ if (!team) {+ return res.status(403).end("Unauthorized to access this team");+ }++ const dataroom = await prisma.dataroom.findUnique({+ where: { id: dataroomId, teamId: teamId },+ select: { id: true, name: true },+ });++ if (!dataroom) {+ return res.status(404).json({ error: "Dataroom not found" });+ }++ const { visitors, anonymous, pagination, sorting } = await getVisitors({+ teamId,+ dataroomId,+ page: parseInt(page || "1", 10),+ pageSize: parseInt(pageSize || "10", 10),+ sortBy,+ sortOrder,+ query,+ status,+ pauseStartsAt: team.pauseStartsAt,+ globalBlockList: team.globalBlockList,+ });++ const viewerIds = visitors+ .map((visitor) => visitor.id)+ .filter((id): id is string => !!id);++ // Dataroom sessions for the current page of visitors, used only to name+ // the links each person actually came through.+ const views = viewerIds.length+ ? await prisma.view.findMany({+ where: {+ dataroomId: dataroomId,+ viewerId: { in: viewerIds },+ viewType: "DATAROOM_VIEW",+ isArchived: false,+ ...(team.pauseStartsAt && {+ viewedAt: { lt: team.pauseStartsAt },+ }),+ },+ orderBy: { viewedAt: "desc" },+ select: {+ viewerId: true,+ viewedAt: true,+ link: { select: { id: true, name: true } },+ },+ })+ : [];++ const viewsByViewer = new Map<string, typeof views>();+ views.forEach((view) => {+ if (!view.viewerId) return;+ const existing = viewsByViewer.get(view.viewerId);+ if (existing) {+ existing.push(view);+ } else {+ viewsByViewer.set(view.viewerId, [view]);+ }+ });++ const formattedVisitors = visitors.map((visitor) => {+ const visitorViews = visitor.id+ ? (viewsByViewer.get(visitor.id) ?? [])+ : [];++ // Links the person actually came through, most recent first; people who+ // have not visited fall back to the link that granted or invited them.+ const accessedLinks = Array.from(+ new Set(+ visitorViews.map(+ (view) =>+ view.link?.name ||+ (view.link?.id ? `Link #${view.link.id.slice(-5)}` : "a link"),+ ),+ ),+ );+ const namesFor = (types: string[]) =>+ Array.from(+ new Set(+ visitor.accessSources+ .filter((source) => types.includes(source.type))+ .map((source) => source.name),+ ),+ );++ const blockedLinks = namesFor(["DENY_LIST"]);+ const grantedLinks = namesFor(["ALLOW_LIST", "INVITATION"]);++ // People who have not visited fall back to the link that granted,+ // invited, or blocked them.+ let linkNames = accessedLinks;+ if (!linkNames.length) {+ linkNames =+ visitor.status === "BLOCKED" ? blockedLinks : grantedLinks;+ }++ return {+ ...visitor,+ dataroomName: dataroom.name,+ linkNames,+ hasVisitedLinks: accessedLinks.length > 0,+ };+ });++ return res.status(200).json({+ visitors: formattedVisitors,+ anonymous,+ pagination,+ sorting,+ });+ } catch (error) {+ log({+ message: `Failed to get visitors for dataroom: _${dataroomId}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``,+ type: "error",+ });+ errorhandler(error, res);+ }+ } else {+ // We only allow GET requests+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/api/teams/[teamId]/viewers/[id]/index.ts b/pages/api/teams/[teamId]/viewers/[id]/index.tsindex a316681e..362908b7 100644--- a/pages/api/teams/[teamId]/viewers/[id]/index.ts+++ b/pages/api/teams/[teamId]/viewers/[id]/index.ts@@ -4,6 +4,7 @@ import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";import { errorhandler } from "@/lib/errorHandler";+import { getVisitors } from "@/lib/api/visitors/get-visitors";import prisma from "@/lib/prisma";import { redis } from "@/lib/redis";import { getDocumentDurationPerViewer } from "@/lib/tinybird";@@ -246,8 +247,8 @@ export default async function handle(const durationCacheKey = `durations:${teamId}:${id}:${currentPage}:${limit}:${sort}:${order}`;const durationsMap = await fetchAndCacheDurations(groupedViews, teamId, id, durationCacheKey);- // Add cache headers- res.setHeader('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=300');+ // Per-viewer data behind auth: keep it out of shared/CDN caches.+ res.setHeader("Cache-Control", "private, no-store");return res.status(200).json({ durations: durationsMap });} catch (error) {@@ -274,8 +275,24 @@ export default async function handle(totalDuration: view.totalDuration || 0,}));+ // How this person can reach the team's content: groups, allow lists,+ // invitations, blocks. Never fatal — the profile still renders without it.+ let access: Awaited<ReturnType<typeof getVisitors>>["visitors"][number] | null =+ null;+ try {+ const { visitors } = await getVisitors({+ teamId,+ email: viewer.email ?? undefined,+ pageSize: 1,+ });+ access = visitors[0] ?? null;+ } catch (accessError) {+ access = null;+ }+const newViewer = {...viewer,+ access,views: formattedViews,pagination: {currentPage,@@ -294,7 +311,8 @@ export default async function handle(if (withDuration !== "true") {await redis.set(cacheKey, JSON.stringify(formattedViews), { ex: 600 }); // 10 min cache}- res.setHeader('Cache-Control', 'public, s-maxage=30, stale-while-revalidate=300');+ // Per-viewer data behind auth: keep it out of shared/CDN caches.+ res.setHeader("Cache-Control", "private, no-store");return res.status(200).json(newViewer);} catch (error) {diff --git a/pages/api/teams/[teamId]/viewers/index.ts b/pages/api/teams/[teamId]/viewers/index.tsindex ab1c06bd..93f26b72 100644--- a/pages/api/teams/[teamId]/viewers/index.ts+++ b/pages/api/teams/[teamId]/viewers/index.ts@@ -1,9 +1,9 @@import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";-import { Prisma } from "@prisma/client";import { getServerSession } from "next-auth/next";+import { getVisitors } from "@/lib/api/visitors/get-visitors";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -19,27 +19,18 @@ export default async function handle(return res.status(401).end("Unauthorized");}- const { query, page, pageSize, sortBy, sortOrder } = req.query as {- query?: string;- page?: string;- pageSize?: string;- sortBy?: string;- sortOrder?: string;- };+ const { query, page, pageSize, sortBy, sortOrder, status } =+ req.query as {+ query?: string;+ page?: string;+ pageSize?: string;+ sortBy?: string;+ sortOrder?: string;+ status?: string;+ };const { teamId } = req.query as { teamId: string };- const currentPage = parseInt(page || "1", 10);- const limit = Math.min(parseInt(pageSize || "10", 10), 100);- const offset = (currentPage - 1) * limit;-- const validSortFields = ["lastViewed", "totalVisits"];- const validSortOrders = ["asc", "desc"];- const sort = validSortFields.includes(sortBy || "") ? sortBy : "lastViewed";- const order = validSortOrders.includes(sortOrder || "")- ? sortOrder- : "desc";-const userId = (session.user as CustomUser).id;try {@@ -52,126 +43,35 @@ export default async function handle(},},},- select: { id: true, plan: true },+ select: { id: true, plan: true, globalBlockList: true },});if (!team || team.plan === "free") {return res.status(404).json({ error: "Team not found" });}- const searchCondition = query- ? Prisma.sql`AND LOWER(v.email) LIKE LOWER(${`${query}%`})`- : Prisma.empty;-- let orderByClause: Prisma.Sql;- if (sort === "totalVisits") {- orderByClause =- order === "desc"- ? Prisma.sql`"totalVisits" DESC, "createdAt" DESC`- : Prisma.sql`"totalVisits" ASC, "createdAt" DESC`;- } else if (sort === "lastViewed") {- orderByClause =- order === "desc"- ? Prisma.sql`"lastViewed" DESC NULLS LAST, "createdAt" DESC`- : Prisma.sql`"lastViewed" ASC NULLS LAST, "createdAt" DESC`;- } else {- orderByClause =- order === "desc"- ? Prisma.sql`"createdAt" DESC`- : Prisma.sql`"createdAt" ASC`;- }-- const viewersWithStats = (await prisma.$queryRaw`- WITH view_stats AS (- SELECT- vw."viewerId",- COUNT(*)::int as total_visits,- MAX(vw."viewedAt") as last_viewed- FROM "View" vw- JOIN "Viewer" vr ON vr.id = vw."viewerId" AND vr."teamId" = ${teamId}- WHERE vw."documentId" IS NOT NULL- GROUP BY vw."viewerId"- ),- latest_viewer_names AS (- SELECT DISTINCT ON (vw."viewerId")- vw."viewerId",- vw."viewerName"- FROM "View" vw- JOIN "Viewer" vr ON vr.id = vw."viewerId" AND vr."teamId" = ${teamId}- WHERE vw."viewerName" IS NOT NULL- ORDER BY vw."viewerId", vw."viewedAt" DESC- ),- viewer_stats AS (- SELECT- v.id,- v.email,- v."createdAt",- v."updatedAt",- COALESCE(vs.total_visits, 0)::int as "totalVisits",- vs.last_viewed as "lastViewed",- lvn."viewerName" as "viewerName"- FROM "Viewer" v- LEFT JOIN view_stats vs ON v.id = vs."viewerId"- LEFT JOIN latest_viewer_names lvn ON v.id = lvn."viewerId"- WHERE v."teamId" = ${teamId}- ${searchCondition}- )- SELECT * FROM viewer_stats- ORDER BY ${orderByClause}- LIMIT ${limit}- OFFSET ${offset}- `) as Array<{- id: string;- email: string;- createdAt: Date;- updatedAt: Date;- totalVisits: number;- lastViewed: Date | null;- viewerName: string | null;- }>;-- const totalCountResult = (await prisma.$queryRaw`- SELECT COUNT(*)::int as count- FROM "Viewer" v- WHERE v."teamId" = ${teamId}- ${searchCondition}- `) as Array<{ count: number }>;-- const totalCount = totalCountResult[0]?.count || 0;- const totalPages = Math.ceil(totalCount / limit);-- const formattedViewers = viewersWithStats.map((viewer) => ({- id: viewer.id,- email: viewer.email,- createdAt: viewer.createdAt,- updatedAt: viewer.updatedAt,- totalVisits: viewer.totalVisits,- lastViewed: viewer.lastViewed,- viewerName: viewer.viewerName,- }));-- const response = {- viewers: formattedViewers,- pagination: {- currentPage,- pageSize: limit,- totalItems: totalCount,- totalPages,- hasNext: currentPage < totalPages,- hasPrev: currentPage > 1,- },- sorting: {- sortBy: sort,- sortOrder: order,- },- };+ const { visitors, anonymous, pagination, sorting } = await getVisitors({+ teamId,+ page: parseInt(page || "1", 10),+ pageSize: parseInt(pageSize || "10", 10),+ sortBy,+ sortOrder,+ query,+ status,+ globalBlockList: team.globalBlockList,+ });- res.setHeader(- "Cache-Control",- "public, s-maxage=30, stale-while-revalidate=300",- );+ // Per-team data behind auth: never let shared/CDN caches store it, or a+ // cache hit could serve one team's list to another user before the auth+ // check runs. Client-side SWR still handles perceived speed.+ res.setHeader("Cache-Control", "private, no-store");- return res.status(200).json(response);+ return res.status(200).json({+ viewers: visitors,+ anonymous,+ pagination,+ sorting,+ });} catch (error) {errorhandler(error, res);}diff --git a/pages/datarooms/[id]/participants/index.tsx b/pages/datarooms/[id]/participants/index.tsxnew file mode 100644index 00000000..3dcbb098--- /dev/null+++ b/pages/datarooms/[id]/participants/index.tsx@@ -0,0 +1,177 @@+import { useRouter } from "next/router";++import { useEffect, useState } from "react";++import { InviteViewersModal } from "@/ee/features/dataroom-invitations/components/invite-viewers-modal";+import { CircleHelpIcon, SendIcon } from "lucide-react";++import { usePlan } from "@/lib/swr/use-billing";+import { useDataroom } from "@/lib/swr/use-dataroom";+import { useDataroomVisitors } from "@/lib/swr/use-dataroom-visitors";++import DataroomTeamMembers from "@/components/datarooms/settings/dataroom-team-members";+import AppLayout from "@/components/layouts/app";+import { SearchBoxPersisted } from "@/components/search-box";+import { Button } from "@/components/ui/button";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { BadgeTooltip, ButtonTooltip } from "@/components/ui/tooltip";+import { DataroomParticipantsTable } from "@/components/visitors/dataroom-participants-table";+import { VisitorStatusFilter } from "@/components/visitors/visitor-status-filter";++export default function DataroomParticipantsPage() {+ const router = useRouter();+ const { dataroom } = useDataroom();+ // Email invitations stay a Data Rooms Plus (and higher) capability for now.+ const { isDataroomsPlus } = usePlan();++ const [currentPage, setCurrentPage] = useState(1);+ const [pageSize, setPageSize] = useState(10);+ const [sortBy, setSortBy] = useState("lastViewed");+ const [sortOrder, setSortOrder] = useState("desc");+ const [activeTab, setActiveTab] = useState(+ (router.query.tab as string) || "participants",+ );+ const [status, setStatus] = useState("all");+ const [isInviteModalOpen, setIsInviteModalOpen] = useState(false);++ const {+ visitors,+ anonymous,+ pagination,+ sorting,+ isValidating,+ isFiltered,+ mutate: mutateParticipants,+ } = useDataroomVisitors({+ dataroomId: dataroom?.id,+ page: currentPage,+ pageSize,+ sortBy,+ sortOrder,+ status,+ });++ useEffect(() => {+ setCurrentPage(1);+ }, [router.query.search, status]);++ useEffect(() => {+ if (router.query.tab) {+ setActiveTab(router.query.tab as string);+ }+ }, [router.query.tab]);++ const handleTabChange = (value: string) => {+ setActiveTab(value);+ router.push(+ { pathname: router.pathname, query: { ...router.query, tab: value } },+ undefined,+ { shallow: true },+ );+ };++ const handleSortChange = (newSortBy: string, newSortOrder: string) => {+ setSortBy(newSortBy);+ setSortOrder(newSortOrder);+ setCurrentPage(1);+ };++ if (!dataroom) {+ return <div>Loading...</div>;+ }++ return (+ <AppLayout>+ <div className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">+ <div className="space-y-1">+ <h1 className="text-2xl font-semibold tracking-tight text-foreground">+ Participants+ </h1>+ <p className="flex flex-row items-center gap-2 text-sm text-muted-foreground">+ Everyone who visited this data room, was invited, or is on one of+ its link allow lists.+ <BadgeTooltip+ linkText="Learn more"+ content="Track who has accessed your data room."+ key="participants"+ link="https://www.papermark.com/help/article/viewer-analytics"+ >+ <CircleHelpIcon className="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" />+ </BadgeTooltip>+ </p>+ </div>++ <Tabs value={activeTab} onValueChange={handleTabChange}>+ <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">+ <TabsList>+ <TabsTrigger value="participants">Participants</TabsTrigger>+ <TabsTrigger value="team">Team Members</TabsTrigger>+ </TabsList>++ {activeTab === "participants" ? (+ <div className="flex items-center gap-x-2">+ <VisitorStatusFilter value={status} onChange={setStatus} />+ <div className="relative w-full sm:max-w-xs">+ <SearchBoxPersisted+ loading={isValidating}+ placeholder="Search participants..."+ inputClassName="h-10"+ />+ </div>+ {isDataroomsPlus ? (+ <ButtonTooltip content="Invite via email">+ <Button+ variant="outline"+ size="icon"+ className="h-10 w-10 shrink-0"+ onClick={() => setIsInviteModalOpen(true)}+ >+ <SendIcon className="h-4 w-4" />+ <span className="sr-only">Invite via email</span>+ </Button>+ </ButtonTooltip>+ ) : null}+ </div>+ ) : null}+ </div>++ <TabsContent value="participants">+ <div className="relative">+ <DataroomParticipantsTable+ visitors={visitors}+ anonymous={anonymous}+ pagination={pagination}+ sorting={sorting ?? { sortBy, sortOrder }}+ isFiltered={isFiltered}+ onPageChange={setCurrentPage}+ onPageSizeChange={(size) => {+ setPageSize(size);+ setCurrentPage(1);+ }}+ onSortChange={handleSortChange}+ />+ </div>+ </TabsContent>++ <TabsContent value="team">+ <DataroomTeamMembers+ dataroomId={dataroom.id}+ dataroomName={dataroom.name}+ />+ </TabsContent>+ </Tabs>+ </div>++ {isDataroomsPlus ? (+ <InviteViewersModal+ open={isInviteModalOpen}+ setOpen={setIsInviteModalOpen}+ dataroomId={dataroom.id}+ dataroomName={dataroom.name}+ canSend+ onSuccess={() => mutateParticipants()}+ />+ ) : null}+ </AppLayout>+ );+}diff --git a/pages/datarooms/[id]/permissions/index.tsx b/pages/datarooms/[id]/permissions/index.tsxindex 291de405..3bca4cc7 100644--- a/pages/datarooms/[id]/permissions/index.tsx+++ b/pages/datarooms/[id]/permissions/index.tsx@@ -1,3 +1,5 @@+import { useRouter } from "next/router";+import dynamic from "next/dynamic";import { useEffect, useRef, useState } from "react";@@ -37,6 +39,7 @@ const BulkImportLinksModal = dynamic();export default function DataroomLinksPage() {+ const router = useRouter();const { dataroom } = useDataroom();const { links, loading: linksLoading } = useDataroomLinks();const { isDatarooms, isDataroomsPlus, isTrial } = usePlan();@@ -91,15 +94,13 @@ export default function DataroomLinksPage() {</p></div><div className="flex items-center gap-2">- {!canInviteViewers && (- <Button- variant="outline"- onClick={() => setIsInviteModalOpen(true)}- >- <SendIcon className="h-4 w-4" />- Invite via email- </Button>- )}+ <Button+ variant="outline"+ onClick={() => setIsInviteModalOpen(true)}+ >+ <SendIcon className="h-4 w-4" />+ Invite via email+ </Button><Button onClick={() => setIsLinkSheetOpen(true)}><PlusIcon className="h-4 w-4" />Create link@@ -165,15 +166,14 @@ export default function DataroomLinksPage() {targetId={dataroom.id}/>- {!canInviteViewers && (- <InviteViewersModal- open={isInviteModalOpen}- setOpen={setIsInviteModalOpen}- dataroomId={dataroom.id}- dataroomName={dataroom.name}- canSend={false}- />- )}+ <InviteViewersModal+ open={isInviteModalOpen}+ setOpen={setIsInviteModalOpen}+ dataroomId={dataroom.id}+ dataroomName={dataroom.name}+ canSend={canInviteViewers}+ onSuccess={() => router.push(`/datarooms/${dataroom.id}/participants`)}+ /></AppLayout>);}diff --git a/pages/visitors/[id]/index.tsx b/pages/visitors/[id]/index.tsxindex 48cda6a3..d72d10de 100644--- a/pages/visitors/[id]/index.tsx+++ b/pages/visitors/[id]/index.tsx@@ -19,6 +19,7 @@ import {import { Separator } from "@/components/ui/separator";import { Skeleton } from "@/components/ui/skeleton";import { ContactsDocumentsTable } from "@/components/visitors/contacts-document-table";+import { VisitorAccessCard } from "@/components/visitors/visitor-access-card";import { VisitorAvatar } from "@/components/visitors/visitor-avatar";export default function VisitorDetailPage() {@@ -74,6 +75,10 @@ export default function VisitorDetailPage() {{viewer.email}</h2></div>++ {viewer.access ? (+ <VisitorAccessCard access={viewer.access} />+ ) : null}</section>) : (<VisitorDetailHeaderSkeleton />diff --git a/pages/visitors/index.tsx b/pages/visitors/index.tsxindex 2e143b53..96782d43 100644--- a/pages/visitors/index.tsx+++ b/pages/visitors/index.tsx@@ -7,10 +7,10 @@ import useViewers from "@/lib/swr/use-viewers";import AppLayout from "@/components/layouts/app";import { SearchBoxPersisted } from "@/components/search-box";-import { Separator } from "@/components/ui/separator";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { ContactsTable } from "@/components/visitors/contacts-table";import { VisitorGroupsSection } from "@/components/visitors/visitor-groups-section";+import { VisitorStatusFilter } from "@/components/visitors/visitor-status-filter";export default function Visitors() {const router = useRouter();@@ -22,12 +22,14 @@ export default function Visitors() {const [activeTab, setActiveTab] = useState((router.query.tab as string) || "visitors",);+ const [status, setStatus] = useState("all");- const { viewers, pagination, isValidating } = useViewers(+ const { viewers, anonymous, pagination, isValidating } = useViewers(currentPage,pageSize,sortBy,sortOrder,+ status,);const handlePageChange = (page: number) => {@@ -47,7 +49,7 @@ export default function Visitors() {useEffect(() => {setCurrentPage(1);- }, [router.query.search]);+ }, [router.query.search, status]);useEffect(() => {if (isFree && !isTrial) router.push("/documents");@@ -77,35 +79,41 @@ export default function Visitors() {All visitors</h2><p className="text-xs text-muted-foreground sm:text-sm">- See all your visitors and manage visitor groups.+ See everyone who visited, was invited, or is on a link allow list,+ and manage visitor groups.</p></div></section><Tabs value={activeTab} onValueChange={handleTabChange}>- <TabsList className="mb-4">- <TabsTrigger value="visitors">Visitors</TabsTrigger>- <TabsTrigger value="groups">Visitor Groups</TabsTrigger>- </TabsList>-- <TabsContent value="visitors">- <div className="mb-2 flex justify-end gap-x-2">- <div className="relative w-full sm:max-w-xs">- <SearchBoxPersisted- loading={isValidating}- placeholder="Search visitors..."- inputClassName="h-10"- />+ <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">+ <TabsList>+ <TabsTrigger value="visitors">Visitors</TabsTrigger>+ <TabsTrigger value="groups">Visitor Groups</TabsTrigger>+ </TabsList>++ {activeTab === "visitors" ? (+ <div className="flex items-center gap-x-2">+ <VisitorStatusFilter value={status} onChange={setStatus} />+ <div className="relative w-full sm:max-w-xs">+ <SearchBoxPersisted+ loading={isValidating}+ placeholder="Search visitors..."+ inputClassName="h-10"+ />+ </div></div>- </div>-- <Separator className="bg-gray-200 dark:bg-gray-800" />+ ) : null}+ </div>- <div className="relative pt-4">+ <TabsContent value="visitors">+ <div className="relative"><ContactsTableviewers={viewers}+ anonymous={anonymous}pagination={pagination}sorting={{ sortBy, sortOrder }}+ isFiltered={!!router.query.search || status !== "all"}onPageChange={handlePageChange}onPageSizeChange={handlePageSizeChange}onSortChange={handleSortChange}