Skip to content

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

feat: add detailed analytics for data rooms plans

Marc Seitz4192d2e9398c
diff --git a/components/datarooms/analytics/analytics-overview.tsx b/components/datarooms/analytics/analytics-overview.tsx
new file mode 100644
index 00000000..ae50de25
--- /dev/null
+++ b/components/datarooms/analytics/analytics-overview.tsx
@@ -0,0 +1,145 @@
+import { useMemo } from "react";
+
+import { useDataroom } from "@/lib/swr/use-dataroom";
+import { useDataroomDocumentStats } from "@/lib/swr/use-dataroom-document-stats";
+import { useDataroomStats } from "@/lib/swr/use-dataroom-stats";
+
+import StatsChart from "@/components/documents/stats-chart";
+import { Gauge } from "@/components/ui/gauge";
+
+interface DataroomAnalyticsOverviewProps {
+ selectedDocument: {
+ id: string;
+ name: string;
+ } | null;
+ setSelectedDocument: React.Dispatch<
+ React.SetStateAction<{
+ id: string;
+ name: string;
+ } | null>
+ >;
+}
+
+export default function DataroomAnalyticsOverview({
+ selectedDocument,
+ setSelectedDocument,
+}: DataroomAnalyticsOverviewProps) {
+ const {
+ stats: dataroomStats,
+ loading: dataroomLoading,
+ error: dataroomError,
+ } = useDataroomStats();
+
+ // Memoize the most viewed document calculation
+ const mostViewedDocument = useMemo(() => {
+ if (!dataroomStats || selectedDocument) return null;
+
+ // Group views by document ID and count them
+ const viewsByDocument = dataroomStats.documentViews.reduce(
+ (acc, view) => {
+ if (!view.documentId) return acc;
+
+ if (!acc[view.documentId]) {
+ acc[view.documentId] = { count: 0, name: "" };
+ }
+ acc[view.documentId].count += 1;
+ return acc;
+ },
+ {} as Record<string, { count: number; name: string }>,
+ );
+
+ // Find document with most views
+ let maxViews = 0;
+ let mostViewedId = "";
+ Object.entries(viewsByDocument).forEach(([docId, data]) => {
+ if (data.count > maxViews) {
+ maxViews = data.count;
+ mostViewedId = docId;
+ }
+ });
+
+ // Return the most viewed document if found
+ return mostViewedId
+ ? {
+ id: mostViewedId,
+ name: mostViewedId, // We'll update the name once we have it
+ }
+ : null;
+ }, [dataroomStats, selectedDocument]);
+
+ // Get document stats for either selected document or most viewed document
+ const documentId = selectedDocument?.id || mostViewedDocument?.id;
+ const {
+ stats: documentStats,
+ loading: documentLoading,
+ error: documentError,
+ } = useDataroomDocumentStats(documentId);
+
+ // If neither is selected or we're still loading dataroom stats
+ const loading = documentLoading || (dataroomLoading && !documentId);
+ const error = documentError || (dataroomError && !documentId);
+
+ if (loading) {
+ return <div>Loading analytics...</div>;
+ }
+
+ if (error) {
+ return <div>Error loading analytics</div>;
+ }
+
+ const completionRate = 0;
+
+ // Get display name for the currently viewed document
+ const displayName =
+ selectedDocument?.name ||
+ (mostViewedDocument?.name !== mostViewedDocument?.id
+ ? mostViewedDocument?.name
+ : "Most viewed document");
+
+ return (
+ <div className="space-y-6">
+ <div className="grid grid-cols-1 gap-6">
+ <div>
+ <h3 className="mb-4 text-lg font-medium">
+ {displayName ? displayName : "Document Engagement"}
+ </h3>
+ {documentStats && (
+ <StatsChart
+ documentId={documentId || ""}
+ totalPagesMax={documentStats?.totalPagesMax || 0}
+ statsData={{
+ stats: documentStats,
+ loading: false,
+ error: null,
+ }}
+ />
+ )}
+ </div>
+
+ {/* INFO: hiding completion rate for now */}
+ {/* <div className="flex flex-col items-center justify-center rounded-lg border p-6">
+ <h3 className="mb-4 text-lg font-medium">
+ {displayName
+ ? `${displayName} - Completion Rate`
+ : "Completion Rate"}
+ </h3>
+ <div className="flex flex-col items-center">
+ <Gauge value={completionRate} size="large" showValue={true} />
+ <p className="mt-4 text-sm text-muted-foreground">
+ Document has {documentStats?.totalViews || 0} view
+ {documentStats?.totalViews !== 1 ? "s" : ""} in this dataroom
+ </p>
+ {!selectedDocument && mostViewedDocument && (
+ <button
+ onClick={() => setSelectedDocument(mostViewedDocument)}
+ className="mt-2 text-xs text-primary hover:underline"
+ >
+ View all documents
+ </button>
+ )}
+ </div>
+ </div> */}
+ </div>
+ </div>
+ );
+}
diff --git a/components/datarooms/analytics/document-analytics-tree.tsx b/components/datarooms/analytics/document-analytics-tree.tsx
new file mode 100644
index 00000000..f587decf
--- /dev/null
+++ b/components/datarooms/analytics/document-analytics-tree.tsx
@@ -0,0 +1,331 @@
+import { useCallback, useMemo } from "react";
+import { Dispatch, SetStateAction } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { ItemType } from "@prisma/client";
+import {
+ ColumnDef,
+ flexRender,
+ getCoreRowModel,
+ getExpandedRowModel,
+ useReactTable,
+} from "@tanstack/react-table";
+import {
+ ChevronDown,
+ ChevronRight,
+ Download,
+ Eye,
+ File,
+ Folder,
+} from "lucide-react";
+
+import { useDataroomFoldersTree } from "@/lib/swr/use-dataroom";
+import { useDataroomStats } from "@/lib/swr/use-dataroom-stats";
+import { cn } from "@/lib/utils";
+
+import { Button } from "@/components/ui/button";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+
+// Define types for the file/folder structure with analytics
+type FileOrFolder = {
+ id: string;
+ name: string;
+ subItems?: FileOrFolder[];
+ analytics: {
+ views: number;
+ downloads: number;
+ };
+ itemType: ItemType;
+ documentId?: string;
+};
+
+interface DocumentAnalyticsTreeProps {
+ dataroomId: string;
+ selectedDocument: {
+ id: string;
+ name: string;
+ } | null;
+ setSelectedDocument: Dispatch<
+ SetStateAction<{
+ id: string;
+ name: string;
+ } | null>
+ >;
+}
+
+export default function DocumentAnalyticsTree({
+ dataroomId,
+ selectedDocument,
+ setSelectedDocument,
+}: DocumentAnalyticsTreeProps) {
+ const { folders, loading: foldersLoading } = useDataroomFoldersTree({
+ dataroomId,
+ include_documents: true,
+ });
+ const { stats: dataroomStats, loading: statsLoading } = useDataroomStats();
+
+ // Memoize the tree data building
+ const data = useMemo(() => {
+ if (!folders || foldersLoading || !dataroomStats || statsLoading) {
+ return [];
+ }
+
+ return buildTree(folders, dataroomStats);
+ }, [folders, foldersLoading, dataroomStats, statsLoading]);
+
+ const handleRowClick = useCallback(
+ (row: FileOrFolder) => {
+ // Only select documents, not folders
+ if (row.itemType === ItemType.DATAROOM_DOCUMENT && row.documentId) {
+ if (selectedDocument && selectedDocument.id === row.documentId) {
+ // If clicking on the already selected document, deselect it
+ setSelectedDocument(null);
+ } else {
+ // Otherwise select the clicked document
+ setSelectedDocument({
+ id: row.documentId,
+ name: row.name,
+ });
+ }
+ }
+ },
+ [selectedDocument, setSelectedDocument],
+ );
+
+ const createColumns = useCallback(
+ (): ColumnDef<FileOrFolder>[] => [
+ {
+ id: "expander",
+ header: () => null,
+ cell: ({ row }) => {
+ return row.getCanExpand() ? (
+ <Button
+ variant="ghost"
+ onClick={(e) => {
+ e.stopPropagation();
+ row.getToggleExpandedHandler()();
+ }}
+ className="h-6 w-6 p-0"
+ >
+ {row.getIsExpanded() ? (
+ <ChevronDown className="h-4 w-4" />
+ ) : (
+ <ChevronRight className="h-4 w-4" />
+ )}
+ </Button>
+ ) : null;
+ },
+ },
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: ({ row }) => (
+ <div className="flex items-center text-foreground">
+ {row.original.itemType === ItemType.DATAROOM_FOLDER ? (
+ <Folder className="mr-2 h-5 w-5" />
+ ) : (
+ <File className="mr-2 h-5 w-5" />
+ )}
+ <span className="truncate">{row.original.name}</span>
+ </div>
+ ),
+ },
+ {
+ id: "views",
+ header: () => (
+ <div className="flex items-center justify-center">
+ <Eye className="mr-1 h-4 w-4" />
+ <span>Views</span>
+ </div>
+ ),
+ cell: ({ row }) => (
+ <div className="text-center">{row.original.analytics.views}</div>
+ ),
+ },
+ {
+ id: "downloads",
+ header: () => (
+ <div className="flex items-center justify-center">
+ <Download className="mr-1 h-4 w-4" />
+ <span>Downloads</span>
+ </div>
+ ),
+ cell: ({ row }) => (
+ <div className="text-center">{row.original.analytics.downloads}</div>
+ ),
+ },
+ ],
+ [],
+ );
+
+ const columns = useMemo(() => createColumns(), [createColumns]);
+
+ const table = useReactTable({
+ data,
+ columns,
+ getCoreRowModel: getCoreRowModel(),
+ getExpandedRowModel: getExpandedRowModel(),
+ getSubRows: (row) => row.subItems,
+ });
+
+ if (foldersLoading || statsLoading) {
+ return <div>Loading analytics data...</div>;
+ }
+
+ return (
+ <div className="rounded-md border">
+ <Table>
+ <TableHeader>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <TableRow key={headerGroup.id}>
+ {headerGroup.headers.map((header) => (
+ <TableHead key={header.id} className="py-2 first:w-12">
+ {header.isPlaceholder
+ ? null
+ : flexRender(
+ header.column.columnDef.header,
+ header.getContext(),
+ )}
+ </TableHead>
+ ))}
+ </TableRow>
+ ))}
+ </TableHeader>
+ <TableBody>
+ {table.getRowModel().rows?.length ? (
+ table.getRowModel().rows.map((row) => (
+ <TableRow
+ key={row.id}
+ data-state={row.getIsSelected() && "selected"}
+ className={cn(
+ "cursor-pointer hover:bg-muted/50",
+ // Highlight the selected document
+ selectedDocument &&
+ row.original.documentId === selectedDocument.id &&
+ "bg-muted",
+ )}
+ onClick={() => handleRowClick(row.original)}
+ >
+ {row.getVisibleCells().map((cell) => (
+ <TableCell
+ key={cell.id}
+ style={{
+ paddingLeft:
+ cell.column.id === "name"
+ ? `${row.depth * 1.25 + 1}rem`
+ : undefined,
+ }}
+ className="py-2"
+ >
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </TableCell>
+ ))}
+ </TableRow>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell colSpan={columns.length} className="h-24 text-center">
+ No analytics data available.
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
+
+// Build the tree structure with analytics data
+const buildTree = (
+ items: any[],
+ statsData: any,
+ parentId: string | null = null,
+): FileOrFolder[] => {
+ const getAnalytics = (id: string, documentId?: string) => {
+ // Count views for this specific item
+ const views =
+ statsData?.documentViews.filter(
+ (view: any) => view.itemId === id || view.documentId === documentId,
+ ).length || 0;
+
+ // Count downloads for this specific item (assuming downloads are tracked in views with a downloadedAt field)
+ const downloads =
+ statsData?.documentViews.filter(
+ (view: any) =>
+ (view.itemId === id || view.documentId === documentId) &&
+ view.downloadedAt,
+ ).length || 0;
+
+ return {
+ views,
+ downloads,
+ };
+ };
+
+ const result: FileOrFolder[] = [];
+
+ // Handle folders and their contents
+ items
+ .filter((item) => item.parentId === parentId && !item.document)
+ .forEach((folder) => {
+ const subItems = buildTree(items, statsData, folder.id);
+
+ // Add documents directly in this folder
+ const folderDocuments = (folder.documents || []).map((doc: any) => {
+ const analytics = getAnalytics(doc.id, doc.document.id);
+ return {
+ id: doc.id,
+ documentId: doc.document.id,
+ name: doc.document.name,
+ analytics,
+ itemType: ItemType.DATAROOM_DOCUMENT,
+ };
+ });
+
+ const allSubItems = [...subItems, ...folderDocuments];
+
+ // Calculate aggregated analytics for the folder
+ const folderAnalytics = {
+ views: allSubItems.reduce((sum, item) => sum + item.analytics.views, 0),
+ downloads: allSubItems.reduce(
+ (sum, item) => sum + item.analytics.downloads,
+ 0,
+ ),
+ };
+
+ result.push({
+ id: folder.id,
+ name: folder.name,
+ subItems: allSubItems,
+ analytics: folderAnalytics,
+ itemType: ItemType.DATAROOM_FOLDER,
+ });
+ });
+
+ // Handle documents at the current level
+ items
+ .filter(
+ (item) =>
+ (item.parentId === parentId && item.document) ||
+ (parentId === null && item.folderId === null && item.document),
+ )
+ .forEach((doc) => {
+ const analytics = getAnalytics(doc.id, doc.document.id);
+ result.push({
+ id: doc.id,
+ documentId: doc.document.id,
+ name: doc.document.name,
+ analytics,
+ itemType: ItemType.DATAROOM_DOCUMENT,
+ });
+ });
+
+ return result;
+};
diff --git a/components/datarooms/analytics/mock-analytics-table.tsx b/components/datarooms/analytics/mock-analytics-table.tsx
new file mode 100644
index 00000000..53771849
--- /dev/null
+++ b/components/datarooms/analytics/mock-analytics-table.tsx
@@ -0,0 +1,104 @@
+import { ChevronRight, Download, Eye, File, Folder } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+
+import { Button } from "@/components/ui/button";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+
+// Mock data for analytics preview
+const mockAnalyticsData = [
+ {
+ id: "2",
+ name: "Financial Reports",
+ type: "folder",
+ views: 38,
+ downloads: 8,
+ },
+ { id: "4", name: "Legal Documents", type: "folder", views: 22, downloads: 3 },
+ {
+ id: "1",
+ name: "Executive Summary",
+ type: "file",
+ views: 45,
+ downloads: 12,
+ },
+ {
+ id: "3",
+ name: "Market Analysis.pdf",
+ type: "file",
+ views: 29,
+ downloads: 15,
+ },
+ { id: "5", name: "Product Roadmap", type: "file", views: 18, downloads: 7 },
+ { id: "6", name: "Team Structure", type: "file", views: 14, downloads: 2 },
+ { id: "7", name: "Marketing Plan", type: "file", views: 14, downloads: 2 },
+];
+
+export default function MockAnalyticsTable() {
+ return (
+ <div className="space-y-6">
+ <h3 className="mb-4 text-lg font-medium">Dataroom Analytics</h3>
+ <div className="rounded-md border">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-12"></TableHead>
+ <TableHead>Name</TableHead>
+ <TableHead className="text-center">
+ <div className="flex items-center justify-center">
+ <Eye className="mr-1 h-4 w-4" />
+ <span>Views</span>
+ </div>
+ </TableHead>
+ <TableHead className="text-center">
+ <div className="flex items-center justify-center">
+ <Download className="mr-1 h-4 w-4" />
+ <span>Downloads</span>
+ </div>
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {mockAnalyticsData.map((row, index) => (
+ <TableRow
+ key={row.id}
+ className={cn(
+ "cursor-pointer transition-opacity hover:bg-muted/50",
+ // Fade out the last 2 rows
+ index >= 5 && "opacity-30",
+ )}
+ >
+ <TableCell>
+ {row.type === "folder" && (
+ <Button variant="ghost" className="h-6 w-6 p-0">
+ <ChevronRight className="h-4 w-4" />
+ </Button>
+ )}
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center text-foreground">
+ {row.type === "folder" ? (
+ <Folder className="mr-2 h-5 w-5" />
+ ) : (
+ <File className="mr-2 h-5 w-5" />
+ )}
+ <span className="truncate">{row.name}</span>
+ </div>
+ </TableCell>
+ <TableCell className="text-center">{row.views}</TableCell>
+ <TableCell className="text-center">{row.downloads}</TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ </div>
+ );
+}
diff --git a/components/ui/feature-preview.tsx b/components/ui/feature-preview.tsx
new file mode 100644
index 00000000..bf39ac73
--- /dev/null
+++ b/components/ui/feature-preview.tsx
@@ -0,0 +1,104 @@
+import React from "react";
+
+import { PlanEnum } from "@/ee/stripe/constants";
+import { LockIcon } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+
+import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+
+interface FeaturePreviewProps {
+ /**
+ * The title displayed in the preview card
+ */
+ title: string;
+ /**
+ * The description/subtitle displayed in the preview card
+ */
+ description: string;
+ /**
+ * The plan required to access this feature
+ */
+ requiredPlan: PlanEnum;
+ /**
+ * Analytics trigger identifier for tracking upgrade clicks
+ */
+ trigger: string;
+ /**
+ * The mock content to show as a preview (will be behind a gradient overlay)
+ */
+ children: React.ReactNode;
+ /**
+ * Additional CSS classes for the container
+ */
+ className?: string;
+ /**
+ * Custom upgrade button text
+ */
+ upgradeButtonText?: string;
+}
+
+/**
+ * A reusable component that shows a preview of premium features with an upgrade overlay
+ *
+ * @example
+ * ```tsx
+ * <FeaturePreview
+ * title="Advanced Analytics"
+ * description="Get detailed insights into document engagement and user behavior"
+ * requiredPlan={PlanEnum.DataRooms}
+ * trigger="analytics_preview"
+ * >
+ * <YourMockAnalyticsComponent />
+ * </FeaturePreview>
+ * ```
+ */
+export function FeaturePreview({
+ title,
+ description,
+ requiredPlan,
+ trigger,
+ children,
+ className,
+ upgradeButtonText = "Upgrade to unlock",
+}: FeaturePreviewProps) {
+ return (
+ <div className={cn("relative", className)}>
+ {/* Content with no interaction */}
+ <div className="pointer-events-none">{children}</div>
+
+ {/* Gradient overlay that fades the content into the upgrade section */}
+ <div className="absolute inset-0 bg-gradient-to-b from-transparent via-transparent to-background/90" />
+
+ {/* Upgrade prompt positioned at the bottom */}
+ <div className="absolute inset-x-0 bottom-0 flex items-end justify-center pb-8">
+ <Card className="max-w-md border-2 border-primary/20 bg-background/95 shadow-lg backdrop-blur-sm">
+ <CardHeader className="text-center">
+ <div className="mx-auto mb-2 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
+ <LockIcon className="h-6 w-6 text-primary" />
+ </div>
+ <CardTitle className="text-xl">{title}</CardTitle>
+ <CardDescription className="text-base">
+ {description}
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="text-center">
+ <UpgradePlanModal clickedPlan={requiredPlan} trigger={trigger}>
+ <Button size="lg" className="w-full">
+ {upgradeButtonText}
+ </Button>
+ </UpgradePlanModal>
+ </CardContent>
+ </Card>
+ </div>
+ </div>
+ );
+}
diff --git a/context/team-context.tsx b/context/team-context.tsx
index 39eff17f..01b7f11a 100644
--- a/context/team-context.tsx
+++ b/context/team-context.tsx
@@ -29,7 +29,7 @@ export const initialState = {
setCurrentTeam: (team: Team) => {},
};
-const TeamContext = createContext<TeamContextType | null>(initialState);
+const TeamContext = createContext<TeamContextType>(initialState);
export const TeamProvider = ({ children }: TeamContextProps): JSX.Element => {
const { teams, loading } = useTeams();
diff --git a/lib/swr/use-dataroom-document-stats.ts b/lib/swr/use-dataroom-document-stats.ts
new file mode 100644
index 00000000..2e2ea12b
--- /dev/null
+++ b/lib/swr/use-dataroom-document-stats.ts
@@ -0,0 +1,35 @@
+import { useRouter } from "next/router";
+
+import { useTeam } from "@/context/team-context";
+import useSWR from "swr";
+
+import { TStatsData } from "@/lib/swr/use-stats";
+import { fetcher } from "@/lib/utils";
+
+type TDataroomDocumentStats = TStatsData & {
+ totalPagesMax: number;
+};
+
+export function useDataroomDocumentStats(
+ documentId: string | null | undefined,
+) {
+ const { currentTeamId: teamId } = useTeam();
+ const router = useRouter();
+ const { id: dataroomId } = router.query as { id: string };
+
+ const { data: stats, error } = useSWR<TDataroomDocumentStats>(
+ documentId && teamId && dataroomId
+ ? `/api/teams/${teamId}/datarooms/${dataroomId}/documents/${encodeURIComponent(documentId)}/stats`
+ : null,
+ fetcher,
+ {
+ dedupingInterval: 10000,
+ },
+ );
+
+ return {
+ stats,
+ loading: documentId ? !error && !stats : false,
+ error,
+ };
+}
diff --git a/lib/swr/use-document-stats.ts b/lib/swr/use-document-stats.ts
new file mode 100644
index 00000000..5af76da5
--- /dev/null
+++ b/lib/swr/use-document-stats.ts
@@ -0,0 +1,26 @@
+import { useTeam } from "@/context/team-context";
+import { View } from "@prisma/client";
+import useSWR from "swr";
+
+import { TStatsData } from "@/lib/swr/use-stats";
+import { fetcher } from "@/lib/utils";
+
+export function useDocumentStats(documentId: string | null | undefined) {
+ const { currentTeamId: teamId } = useTeam();
+
+ const { data: stats, error } = useSWR<TStatsData>(
+ documentId && teamId
+ ? `/api/teams/${teamId}/documents/${encodeURIComponent(documentId)}/stats`
+ : null,
+ fetcher,
+ {
+ dedupingInterval: 10000,
+ },
+ );
+
+ return {
+ stats,
+ loading: documentId ? !error && !stats : false,
+ error,
+ };
+}
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/stats.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/stats.ts
new file mode 100644
index 00000000..e189324b
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/stats.ts
@@ -0,0 +1,163 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { View } from "@prisma/client";
+import { getServerSession } from "next-auth/next";
+
+import { errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+import {
+ getTotalAvgPageDuration,
+ getTotalDocumentDuration,
+} from "@/lib/tinybird";
+import { CustomUser } from "@/lib/types";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "GET") {
+ // GET /api/teams/:teamId/datarooms/:id/documents/:documentId/stats
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const {
+ teamId,
+ id: dataroomId,
+ documentId,
+ } = req.query as {
+ teamId: string;
+ id: string;
+ documentId: string;
+ };
+
+ const userId = (session.user as CustomUser).id;
+
+ try {
+ // Check if the user is part of the team
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ });
+
+ if (!team) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ // Verify the document exists in the dataroom
+ const dataroomDocument = await prisma.dataroomDocument.findFirst({
+ where: {
+ dataroomId,
+ document: {
+ id: documentId,
+ teamId,
+ },
+ },
+ include: {
+ document: {
+ include: {
+ versions: {
+ take: 1,
+ where: {
+ isPrimary: true,
+ },
+ select: {
+ versionNumber: true,
+ numPages: true,
+ },
+ },
+ team: {
+ select: {
+ plan: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!dataroomDocument) {
+ return res.status(404).json({
+ error: "Document not found in this dataroom",
+ });
+ }
+
+ // Get all views for this document that are specifically from the dataroom
+ const views = await prisma.view.findMany({
+ where: {
+ documentId: documentId,
+ },
+ });
+
+ // if there are no views, return an empty array
+ if (!views || views.length === 0) {
+ return res.status(200).json({
+ views: [],
+ duration: { data: [] },
+ total_duration: 0,
+ groupedReactions: [],
+ totalViews: 0,
+ totalPagesMax: 0,
+ });
+ }
+
+ const activeViews = views.filter((view) => !view.isArchived);
+ const archivedViews = views.filter((view) => view.isArchived);
+ const nonDataroomViews = activeViews.filter(
+ (view) => view.dataroomId !== dataroomId,
+ );
+
+ // exclude views from the team's members if requested
+ let internalViews: View[] = [];
+
+ // combined archived and internal and non-dataroom views
+ const allExcludedViews = [
+ ...internalViews,
+ ...archivedViews,
+ ...nonDataroomViews,
+ ];
+
+ // filter out the excluded views
+ const filteredViews = views
+ .filter(
+ (view) => !allExcludedViews.map((view) => view.id).includes(view.id),
+ )
+ .map((view) => ({
+ id: view.id,
+ }));
+
+ const duration = await getTotalAvgPageDuration({
+ documentId: documentId,
+ excludedLinkIds: "",
+ excludedViewIds: allExcludedViews.map((view) => view.id).join(","),
+ since: 0,
+ });
+
+ const stats = {
+ views: filteredViews,
+ duration,
+ total_duration: 0, // INFO: hiding this for now
+ groupedReactions: [], // INFO: hiding this as not relevant
+ totalViews: filteredViews.length,
+ completionRate: 0,
+ totalPagesMax: dataroomDocument.document.versions[0].numPages,
+ };
+
+ return res.status(200).json(stats);
+ } catch (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/datarooms/[id]/analytics/index.tsx b/pages/datarooms/[id]/analytics/index.tsx
index 202f7968..ac5b1aa8 100644
--- a/pages/datarooms/[id]/analytics/index.tsx
+++ b/pages/datarooms/[id]/analytics/index.tsx
@@ -1,18 +1,62 @@
+import { useState } from "react";
+
+import { PlanEnum } from "@/ee/stripe/constants";
+import { ChartNoAxesColumnIcon, LogsIcon } from "lucide-react";
+
+import { usePlan } from "@/lib/swr/use-billing";
import { useDataroom } from "@/lib/swr/use-dataroom";
+import DataroomAnalyticsOverview from "@/components/datarooms/analytics/analytics-overview";
+import DocumentAnalyticsTree from "@/components/datarooms/analytics/document-analytics-tree";
+import MockAnalyticsTable from "@/components/datarooms/analytics/mock-analytics-table";
import { DataroomHeader } from "@/components/datarooms/dataroom-header";
import { DataroomNavigation } from "@/components/datarooms/dataroom-navigation";
import StatsCard from "@/components/datarooms/stats-card";
import AppLayout from "@/components/layouts/app";
+import { FeaturePreview } from "@/components/ui/feature-preview";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import DataroomVisitorsTable from "@/components/visitors/dataroom-visitors-table";
export default function DataroomAnalyticsPage() {
const { dataroom } = useDataroom();
+ const { isDatarooms, isDataroomsPlus } = usePlan();
+
+ // State for the selected document
+ const [selectedDocument, setSelectedDocument] = useState<{
+ id: string;
+ name: string;
+ } | null>(null);
+
+ // Determine default tab based on plan
+ const defaultTab = isDatarooms || isDataroomsPlus ? "analytics" : "audit-log";
+ // Check if user has access to analytics features
+ const hasAnalyticsAccess = isDatarooms || isDataroomsPlus;
if (!dataroom) {
return <div>Loading...</div>;
}
+ const AnalyticsContent = () => (
+ <>
+ <DataroomAnalyticsOverview
+ selectedDocument={selectedDocument}
+ setSelectedDocument={setSelectedDocument}
+ />
+ <div>
+ <h3 className="mb-4 text-lg font-medium">
+ Dataroom Analytics{" "}
+ {selectedDocument &&
+ `- Showing detailed metrics for "${selectedDocument.name}"`}
+ </h3>
+ <DocumentAnalyticsTree
+ dataroomId={dataroom.id}
+ selectedDocument={selectedDocument}
+ setSelectedDocument={setSelectedDocument}
+ />
+ </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">
@@ -27,7 +71,45 @@ export default function DataroomAnalyticsPage() {
<div className="space-y-8">
<StatsCard />
- <DataroomVisitorsTable dataroomId={dataroom.id} />
+
+ <Tabs defaultValue={defaultTab} className="space-y-6">
+ <TabsList>
+ <TabsTrigger
+ value="analytics"
+ className="flex items-center gap-2"
+ >
+ <ChartNoAxesColumnIcon className="h-4 w-4" />
+ Analytics
+ </TabsTrigger>
+ <TabsTrigger
+ value="audit-log"
+ className="flex items-center gap-2"
+ >
+ <LogsIcon className="h-4 w-4" />
+ Audit Log
+ </TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="analytics" className="space-y-6">
+ {hasAnalyticsAccess ? (
+ <AnalyticsContent />
+ ) : (
+ <FeaturePreview
+ title="Advanced Dataroom Analytics"
+ description="Get detailed insights into document engagement, completion rates, and visitor behavior patterns across your dataroom."
+ requiredPlan={PlanEnum.DataRooms}
+ trigger="dataroom_analytics_tab"
+ upgradeButtonText="Upgrade to Data Rooms"
+ >
+ <MockAnalyticsTable />
+ </FeaturePreview>
+ )}
+ </TabsContent>
+
+ <TabsContent value="audit-log">
+ <DataroomVisitorsTable dataroomId={dataroom.id} />
+ </TabsContent>
+ </Tabs>
</div>
</div>
</AppLayout>