Skip to content

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

feat: dataroom analytics overview redesign 1043

Marc Seitzf3ed99186c63
diff --git a/.gitignore b/.gitignore
index 629a7264..6ab1696b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -53,6 +53,8 @@ scripts/*
!scripts/mcp-smoke.mjs
!scripts/check-tool-contracts.sh
!scripts/extend-trial.ts
+!scripts/local/
+scripts/local/.tinybird-page-views.json
!.github/scripts/
# marketing emails
diff --git a/components/analytics/dashboard-views-chart.tsx b/components/analytics/dashboard-views-chart.tsx
index 973d4e6c..471e9afd 100644
--- a/components/analytics/dashboard-views-chart.tsx
+++ b/components/analytics/dashboard-views-chart.tsx
@@ -11,10 +11,10 @@ import {
YAxis,
} from "recharts";
-import { TimeRange } from "./time-range-select";
+import { DashboardTimeRange } from "./time-range-select";
interface DashboardViewsChartProps {
- timeRange: TimeRange;
+ timeRange: DashboardTimeRange;
data?: { date: string; views: number }[];
startDate?: Date;
endDate?: Date;
diff --git a/components/analytics/time-range-select.tsx b/components/analytics/time-range-select.tsx
index e8ccce33..58a19ae2 100644
--- a/components/analytics/time-range-select.tsx
+++ b/components/analytics/time-range-select.tsx
@@ -6,6 +6,9 @@ import { CalendarIcon, ChevronDown, CrownIcon } from "lucide-react";
import { DateRange } from "react-day-picker";
import { toast } from "sonner";
+import { cn } from "@/lib/utils";
+
+import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import {
@@ -14,42 +17,63 @@ import {
PopoverTrigger,
} from "@/components/ui/popover";
-import { cn } from "@/lib/utils";
-
-import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";
-
-const TIME_RANGES = [
+export const TIME_RANGES = [
{ value: "24h", label: "Last 24 hours", shortcut: "D" },
{ value: "7d", label: "Last 7 days", shortcut: "W" },
{ value: "30d", label: "Last 30 days", shortcut: "M" },
+ { value: "all", label: "All time", shortcut: "A" },
{ value: "custom", label: "Custom Date", shortcut: "C" },
] as const;
export type TimeRange = (typeof TIME_RANGES)[number]["value"];
+
+/** The dashboard's API only understands these; data rooms additionally offer "all". */
+export type DashboardTimeRange = Exclude<TimeRange, "all">;
+
+export const DASHBOARD_TIME_RANGES = TIME_RANGES.filter(
+ (
+ range,
+ ): range is Extract<
+ (typeof TIME_RANGES)[number],
+ { value: DashboardTimeRange }
+ > => range.value !== "all",
+);
+
+export function isDashboardTimeRange(
+ value: unknown,
+): value is DashboardTimeRange {
+ return DASHBOARD_TIME_RANGES.some((range) => range.value === value);
+}
+
interface CustomRange {
start: Date;
end: Date;
}
-interface TimeRangeSelectProps {
- value: TimeRange;
- onChange: (value: TimeRange) => void;
+interface TimeRangeSelectProps<T extends TimeRange> {
+ value: T;
+ /** The calendar commits a custom range regardless of which presets are offered. */
+ onChange: (value: NoInfer<T> | "custom") => void;
+ /** Pass the dashboard set to keep "All time" out of both the UI and the callback. */
+ ranges: readonly { value: T; label: string }[];
customRange: CustomRange;
setCustomRange: (range: CustomRange) => void;
onCustomRangeComplete?: (range: CustomRange) => void;
- slug: React.MutableRefObject<boolean>;
+ /** Dashboard-only latch recording that the user has picked a range. */
+ slug?: React.MutableRefObject<boolean>;
isPremium?: boolean;
}
-export function TimeRangeSelect({
+export function TimeRangeSelect<T extends TimeRange>({
value,
onChange,
+ ranges,
customRange,
setCustomRange,
onCustomRangeComplete,
slug,
isPremium = false,
-}: TimeRangeSelectProps) {
- const selectedRange = TIME_RANGES.find((range) => range.value === value);
+}: TimeRangeSelectProps<T>) {
+ const selectedRange = ranges.find((range) => range.value === value);
const [date, setDate] = useState<DateRange | undefined>({
from: customRange.start,
to: customRange.end,
@@ -63,21 +87,22 @@ export function TimeRangeSelect({
setDate({ from: customRange.start, to: customRange.end });
}, [customRange]);
- const handleSelectOption = (value: TimeRange) => {
+ const handleSelectOption = (selected: T) => {
// Prevent selecting custom range for non-premium users
- if (value === "custom" && !isPremium) {
+ if (selected === "custom" && !isPremium) {
toast.error("Upgrade to view data beyond 30 days");
return;
}
- onChange(value);
+ onChange(selected);
// Update date range based on selected preset
const now = new Date();
const end = startOfDay(now);
let start = startOfDay(now);
- switch (value) {
+ const preset: TimeRange = selected;
+ switch (preset) {
case "24h":
start = subDays(end, 1);
break;
@@ -87,17 +112,24 @@ export function TimeRangeSelect({
case "30d":
start = subDays(end, 30);
break;
+ case "all":
+ setDate(undefined);
+ if (slug) slug.current = false;
+ setOpen(false);
+ return;
case "custom":
// Reset the date range when switching to custom
setDate(undefined);
return;
- default:
- return;
+ default: {
+ const exhaustive: never = preset;
+ return exhaustive;
+ }
}
setCustomRange({ start, end });
setDate({ from: start, to: end });
- slug.current = false;
+ if (slug) slug.current = false;
setOpen(false);
};
@@ -117,13 +149,13 @@ export function TimeRangeSelect({
const newRange = { start: range.from, end: range.to };
setCustomRange(newRange);
onChange("custom");
- slug.current = false;
+ if (slug) slug.current = false;
setOpen(false);
onCustomRangeComplete?.(newRange);
} else if (range?.from) {
setCustomRange({ start: range.from, end: range.from });
onChange("custom");
- slug.current = false;
+ if (slug) slug.current = false;
}
};
@@ -175,7 +207,7 @@ export function TimeRangeSelect({
</div>
<div className="flex flex-col gap-2">
<div className="grid gap-1">
- {TIME_RANGES.map((range) => {
+ {ranges.map((range) => {
if (isPremium || range.value !== "custom") {
return (
<Button
diff --git a/components/charts/utils.ts b/components/charts/utils.ts
index aee6c1ee..54cd6e6b 100644
--- a/components/charts/utils.ts
+++ b/components/charts/utils.ts
@@ -11,6 +11,54 @@ export type SumData = {
sum_duration: number;
};
+export type PageDurationRow = {
+ versionNumber: number;
+ pageNumber: string;
+ avg_duration: number;
+};
+
+/** Lays averages over every page, so unopened pages still plot as empty bars. */
+export const buildPageDurationSeries = (
+ rows: PageDurationRow[],
+ totalPagesMax: number,
+): Data[] => {
+ const series: Data[] = Array.from({ length: totalPagesMax }, (_, index) => ({
+ pageNumber: (index + 1).toString(),
+ data: [{ versionNumber: 1, avg_duration: 0 }],
+ }));
+
+ const byPage = new Map(series.map((page) => [page.pageNumber, page]));
+
+ for (const row of rows) {
+ const page = byPage.get(row.pageNumber);
+ if (!page) {
+ const added: Data = {
+ pageNumber: row.pageNumber,
+ data: [
+ { versionNumber: row.versionNumber, avg_duration: row.avg_duration },
+ ],
+ };
+ series.push(added);
+ byPage.set(added.pageNumber, added);
+ continue;
+ }
+
+ const version = page.data.find(
+ (candidate) => candidate.versionNumber === row.versionNumber,
+ );
+ if (version) version.avg_duration = row.avg_duration;
+ else
+ page.data.push({
+ versionNumber: row.versionNumber,
+ avg_duration: row.avg_duration,
+ });
+ }
+
+ return series.sort(
+ (left, right) => parseInt(left.pageNumber) - parseInt(right.pageNumber),
+ );
+};
+
export type TransformedData = {
pageNumber: string;
[key: string]: number | string; // Adjusted type to accommodate version keys
diff --git a/components/datarooms/analytics/analytics-overview.tsx b/components/datarooms/analytics/analytics-overview.tsx
deleted file mode 100644
index 4190ea91..00000000
--- a/components/datarooms/analytics/analytics-overview.tsx
+++ /dev/null
@@ -1,166 +0,0 @@
-import { useRouter } from "next/router";
-
-import { useMemo } from "react";
-
-import { useDataroomFoldersTree } 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 router = useRouter();
- const { id: dataroomId } = router.query as { id: string };
-
- const {
- stats: dataroomStats,
- loading: dataroomLoading,
- error: dataroomError,
- } = useDataroomStats();
-
- const { folders, loading: foldersLoading } = useDataroomFoldersTree({
- dataroomId,
- include_documents: true,
- });
-
- const documentNamesById = useMemo(() => {
- const map = new Map<string, string>();
- folders?.forEach((item: any) => {
- if (item?.document?.id) {
- map.set(item.document.id, item.document.name);
- }
- item?.documents?.forEach((doc: any) => {
- if (doc?.document?.id) {
- map.set(doc.document.id, doc.document.name);
- }
- });
- });
- return map;
- }, [folders]);
-
- const mostViewedDocument = useMemo(() => {
- if (!dataroomStats || selectedDocument) return null;
- if (documentNamesById.size === 0) return null;
-
- // View records persist after a document is removed, so only count views for
- // documents still present in the dataroom to avoid selecting a stale one.
- const viewsByDocument = dataroomStats.documentViews.reduce(
- (acc, view) => {
- if (!view.documentId) return acc;
- if (!documentNamesById.has(view.documentId)) return acc;
-
- acc[view.documentId] = (acc[view.documentId] ?? 0) + 1;
- return acc;
- },
- {} as Record<string, number>,
- );
-
- let maxViews = 0;
- let mostViewedId = "";
- Object.entries(viewsByDocument).forEach(([docId, count]) => {
- if (count > maxViews) {
- maxViews = count;
- mostViewedId = docId;
- }
- });
-
- return mostViewedId
- ? {
- id: mostViewedId,
- name: documentNamesById.get(mostViewedId) ?? mostViewedId,
- }
- : null;
- }, [dataroomStats, selectedDocument, documentNamesById]);
-
- const documentId = selectedDocument?.id || mostViewedDocument?.id;
- const { stats: documentStats, loading: documentLoading } =
- useDataroomDocumentStats(documentId);
-
- // The per-document chart is supplementary, so a document stats failure (e.g. a
- // removed document) should not blank the overview; only dataroom stats are.
- const loading =
- documentLoading ||
- (dataroomLoading && !documentId) ||
- (foldersLoading && !selectedDocument);
- const error = dataroomError && !documentId;
-
- if (loading) {
- return <div>Loading analytics...</div>;
- }
-
- if (error) {
- return <div>Error loading analytics</div>;
- }
-
- const completionRate = 0;
-
- 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
deleted file mode 100644
index f587decf..00000000
--- a/components/datarooms/analytics/document-analytics-tree.tsx
+++ /dev/null
@@ -1,331 +0,0 @@
-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
deleted file mode 100644
index 53771849..00000000
--- a/components/datarooms/analytics/mock-analytics-table.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-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/documents/stats-chart.tsx b/components/documents/stats-chart.tsx
index e2fb626f..1635d273 100644
--- a/components/documents/stats-chart.tsx
+++ b/components/documents/stats-chart.tsx
@@ -3,6 +3,7 @@ import ErrorPage from "next/error";
import { TStatsData } from "@/lib/swr/use-stats";
import BarChartComponent from "../charts/bar-chart";
+import { buildPageDurationSeries } from "../charts/utils";
import StatsChartDummy from "./stats-chart-dummy";
import StatsChartSkeleton from "./stats-chart-skeleton";
@@ -25,67 +26,18 @@ export default function StatsChart({
return <StatsChartSkeleton className="my-8" />;
}
- let durationData = Array.from({ length: totalPagesMax }, (_, i) => ({
- pageNumber: (i + 1).toString(),
- data: [
- {
- versionNumber: 1,
- avg_duration: 0,
- },
- ],
- }));
-
- const swrData = stats?.duration;
-
- if (swrData) {
- swrData.data.forEach((dataItem) => {
- const pageIndex = durationData.findIndex(
- (item) => item.pageNumber === dataItem.pageNumber,
- );
-
- if (pageIndex !== -1) {
- // If page exists in the initialized array, update its data
- const versionIndex = durationData[pageIndex].data.findIndex(
- (v) => v.versionNumber === dataItem.versionNumber,
- );
- if (versionIndex === -1) {
- // If this version number doesn't exist, add it
- durationData[pageIndex].data.push({
- versionNumber: dataItem.versionNumber,
- avg_duration: dataItem.avg_duration,
- });
- } else {
- // Update existing data for this version
- durationData[pageIndex].data[versionIndex] = {
- ...durationData[pageIndex].data[versionIndex],
- avg_duration: dataItem.avg_duration,
- };
- }
- } else {
- // If this page number doesn't exist, add it with the version data
- durationData.push({
- pageNumber: dataItem.pageNumber,
- data: [
- {
- versionNumber: dataItem.versionNumber,
- avg_duration: dataItem.avg_duration,
- },
- ],
- });
- }
- });
-
- // Sort by page number
- durationData.sort(
- (a, b) => parseInt(a.pageNumber) - parseInt(b.pageNumber),
- );
+ if (!stats || stats.views.length === 0) {
+ return <StatsChartDummy totalPagesMax={totalPagesMax} />;
}
- return stats && stats.views.length > 0 ? (
+ return (
<div className="overflow-x-auto rounded-bl-lg border-b border-l pb-0.5 pl-0.5 md:pb-1 md:pl-1">
- <BarChartComponent data={durationData} />
+ <BarChartComponent
+ data={buildPageDurationSeries(
+ stats.duration?.data ?? [],
+ totalPagesMax,
+ )}
+ />
</div>
- ) : (
- <StatsChartDummy totalPagesMax={totalPagesMax} />
);
}
diff --git a/components/ui/fade-scroll-area.tsx b/components/ui/fade-scroll-area.tsx
index c8eaa918..8ca4496b 100644
--- a/components/ui/fade-scroll-area.tsx
+++ b/components/ui/fade-scroll-area.tsx
@@ -9,8 +9,9 @@ const FADE_THRESHOLD_PX = 10;
/**
* ScrollArea with top/bottom fade masks that appear when content overflows in
* that direction (same affordance as the viewer FAQ section), plus an optional
- * always-rendered scrollbar. Pair `showScrollbar` with a `pr-2.5`
- * `contentClassName` to keep content out of the scrollbar gutter.
+ * always-rendered scrollbar. Pair `showScrollbar` with a right-padded
+ * `contentClassName` (at least `pr-2.5`, the scrollbar width) to keep content
+ * out of the scrollbar gutter.
*/
export function FadeScrollArea({
className,
@@ -60,10 +61,13 @@ export function FadeScrollArea({
return (
<div className={cn("relative min-h-0", className)}>
+ {/* Radix wraps the viewport content in a `display: table`, which grows to the widest row
+ instead of clamping to the viewport, so `truncate` inside rows never engages. */}
<ScrollArea
ref={rootRef}
className="h-full"
showScrollbar={showScrollbar}
+ viewportClassName="[&>*]:!block"
>
<div className={contentClassName}>{children}</div>
</ScrollArea>
diff --git a/components/ui/nextra-filetree.tsx b/components/ui/nextra-filetree.tsx
index 792a6a84..feed5425 100644
--- a/components/ui/nextra-filetree.tsx
+++ b/components/ui/nextra-filetree.tsx
@@ -173,8 +173,13 @@ const Folder = memo<FolderProps>(
<FolderIcon className="h-5 w-5 shrink-0" aria-hidden="true" />
)}
<span
- className="ml-2 min-w-0 flex-1 truncate whitespace-nowrap"
- title={(label ?? name) as string}
+ className={cn(
+ "ml-2 min-w-0 flex-1",
+ // A label does its own truncation; clipping here would cut off whatever
+ // it places after the name.
+ label ? "flex items-center gap-2" : "truncate whitespace-nowrap",
+ )}
+ title={name}
>
{label ?? name}
</span>
@@ -207,7 +212,7 @@ const File = memo<FileProps>(({ label, name, active, onToggle }) => {
"px-3 py-1.5 leading-6",
active &&
(prefersLightText
- ? "bg-[var(--viewer-panel-active)] text-[var(--viewer-text)] font-semibold"
+ ? "bg-[var(--viewer-panel-active)] font-semibold text-[var(--viewer-text)]"
: "bg-gray-100 font-semibold dark:bg-muted"),
)}
>
@@ -218,8 +223,11 @@ const File = memo<FileProps>(({ label, name, active, onToggle }) => {
<Ident />
<FileIcon className="h-5 w-5 shrink-0" aria-hidden="true" />
<span
- className="ml-2 min-w-0 flex-1 truncate whitespace-nowrap"
- title={(label ?? name) as string}
+ className={cn(
+ "ml-2 min-w-0 flex-1",
+ label ? "flex items-center gap-2" : "truncate whitespace-nowrap",
+ )}
+ title={name}
>
{label ?? name}
</span>
diff --git a/components/ui/scroll-area.tsx b/components/ui/scroll-area.tsx
index 1aaa811c..ef64ea67 100644
--- a/components/ui/scroll-area.tsx
+++ b/components/ui/scroll-area.tsx
@@ -8,21 +8,29 @@ const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root> & {
showScrollbar?: boolean;
+ viewportClassName?: string;
}
->(({ className, children, showScrollbar, ...props }, ref) => (
- <ScrollAreaPrimitive.Root
- ref={ref}
- className={cn("relative overflow-hidden", className)}
- {...props}
- >
- <ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
- {children}
- </ScrollAreaPrimitive.Viewport>
+>(
+ (
+ { className, children, showScrollbar, viewportClassName, ...props },
+ ref,
+ ) => (
+ <ScrollAreaPrimitive.Root
+ ref={ref}
+ className={cn("relative overflow-hidden", className)}
+ {...props}
+ >
+ <ScrollAreaPrimitive.Viewport
+ className={cn("h-full w-full rounded-[inherit]", viewportClassName)}
+ >
+ {children}
+ </ScrollAreaPrimitive.Viewport>
- <ScrollAreaPrimitive.Corner />
- <ScrollBar className={showScrollbar ? "" : "hidden"} />
- </ScrollAreaPrimitive.Root>
-));
+ <ScrollAreaPrimitive.Corner />
+ <ScrollBar className={showScrollbar ? "" : "hidden"} />
+ </ScrollAreaPrimitive.Root>
+ ),
+);
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
const ScrollBar = React.forwardRef<
diff --git a/components/visitors/data-table-pagination.tsx b/components/visitors/data-table-pagination.tsx
index 0c8ab99a..e4b26d94 100644
--- a/components/visitors/data-table-pagination.tsx
+++ b/components/visitors/data-table-pagination.tsx
@@ -18,14 +18,18 @@ import {
interface DataTablePaginationProps<TData> {
table: Table<TData>;
name: string;
+ /** Required for server-paginated tables, where the row model only holds the current page. */
+ totalRows?: number;
}
export function DataTablePagination<TData>({
table,
name,
+ totalRows: totalRowsOverride,
}: DataTablePaginationProps<TData>) {
const { pageSize, pageIndex } = table.getState().pagination;
- const totalRows = table.getFilteredRowModel().rows.length;
+ const totalRows =
+ totalRowsOverride ?? table.getFilteredRowModel().rows.length;
const visibleRows = table.getRowModel().rows.length;
return (
diff --git a/lib/swr/use-dataroom-document-stats.ts b/lib/swr/use-dataroom-document-stats.ts
deleted file mode 100644
index 2e2ea12b..00000000
--- a/lib/swr/use-dataroom-document-stats.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-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/tinybird/pipes.ts b/lib/tinybird/pipes.ts
index 0fb928f6..e391fe16 100644
--- a/lib/tinybird/pipes.ts
+++ b/lib/tinybird/pipes.ts
@@ -4,7 +4,11 @@ import { z } from "zod";
import { VIDEO_EVENT_TYPES } from "../constants";
import { WEBHOOK_TRIGGERS } from "../webhook/constants";
-const tb = new Tinybird({ token: process.env.TINYBIRD_TOKEN! });
+const tb = new Tinybird({
+ token: process.env.TINYBIRD_TOKEN!,
+ // Tinybird is region-hosted; zod-bird defaults to the US API host.
+ baseUrl: process.env.TINYBIRD_BASE_URL,
+});
export const getTotalAvgPageDuration = tb.buildPipe({
pipe: "get_total_average_page_duration__v5",
diff --git a/lib/tinybird/publish.ts b/lib/tinybird/publish.ts
index 4ba04cd2..1a36df94 100644
--- a/lib/tinybird/publish.ts
+++ b/lib/tinybird/publish.ts
@@ -4,7 +4,11 @@ import { z } from "zod";
import { VIDEO_EVENT_TYPES } from "../constants";
import { WEBHOOK_TRIGGERS } from "../webhook/constants";
-const tb = new Tinybird({ token: process.env.TINYBIRD_TOKEN! });
+const tb = new Tinybird({
+ token: process.env.TINYBIRD_TOKEN!,
+ // Tinybird is region-hosted; zod-bird defaults to the US API host.
+ baseUrl: process.env.TINYBIRD_BASE_URL,
+});
export const publishPageView = tb.buildIngestEndpoint({
datasource: "page_views__v3",
diff --git a/lib/utils.ts b/lib/utils.ts
index d63d1be9..2f943b57 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -40,7 +40,7 @@ export function getFileNameWithPdfExtension(filename?: string): string {
return `${nameWithoutExt}.pdf`;
}
-interface SWRError extends Error {
+export interface SWRError extends Error {
status: number;
}
diff --git a/package-lock.json b/package-lock.json
index 479d4209..bde0e414 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -107,6 +107,7 @@
"js-cookie": "^3.0.7",
"jsonwebtoken": "^9.0.3",
"jszip": "^3.10.1",
+ "lru-cache": "^11.5.2",
"lucide-react": "^1.16.0",
"mime-types": "^3.0.2",
"motion": "^12.40.0",
@@ -17685,9 +17686,9 @@
}
},
"node_modules/lru-cache": {
- "version": "11.5.1",
- "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz",
- "integrity": "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==",
+ "version": "11.5.2",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz",
+ "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==",
"license": "BlueOak-1.0.0",
"engines": {
"node": "20 || >=22"
@@ -20300,9 +20301,9 @@
"license": "MIT-0"
},
"node_modules/postcss": {
- "version": "8.5.15",
- "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",
- "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",
+ "version": "8.5.25",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz",
+ "integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==",
"funding": [
{
"type": "opencollective",
@@ -20319,7 +20320,7 @@
],
"license": "MIT",
"dependencies": {
- "nanoid": "^3.3.12",
+ "nanoid": "^3.3.16",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
@@ -20455,9 +20456,9 @@
"license": "MIT"
},
"node_modules/postcss/node_modules/nanoid": {
- "version": "3.3.12",
- "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",
- "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",
+ "version": "3.3.17",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.17.tgz",
+ "integrity": "sha512-xQLf0A3HOMlgHq0n247/LRuAOYmB7dXJ/DvAxGvsSBij45XtBSmQycu+F8ODbHwns/XyFZagyL1+J0Offw1E0g==",
"funding": [
{
"type": "github",
@@ -24012,7 +24013,9 @@
"license": "MIT"
},
"node_modules/tinyglobby": {
- "version": "0.2.16",
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
"license": "MIT",
"dependencies": {
"fdir": "^6.5.0",
diff --git a/package.json b/package.json
index 24e96fa9..e02df7b1 100644
--- a/package.json
+++ b/package.json
@@ -120,6 +120,7 @@
"js-cookie": "^3.0.7",
"jsonwebtoken": "^9.0.3",
"jszip": "^3.10.1",
+ "lru-cache": "^11.5.2",
"lucide-react": "^1.16.0",
"mime-types": "^3.0.2",
"motion": "^12.40.0",
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/stats.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/stats.ts
deleted file mode 100644
index 9182d07f..00000000
--- a/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/stats.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-
-import { authOptions } from "@/pages/api/auth/[...nextauth]";
-import { View } from "@prisma/client";
-import { getServerSession } from "next-auth/next";
-
-import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";
-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;
-
- // Scoped members may only read stats within their assigned rooms.
- if (
- await enforceDataroomMemberScope({ userId, teamId, dataroomId, res })
- ) {
- return;
- }
-
- 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,
- avgCompletionRate: 0,
- 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
- avgCompletionRate: 0, // INFO: hiding this for now
- 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/dashboard.tsx b/pages/dashboard.tsx
index a7af7ec2..b4c4f81e 100644
--- a/pages/dashboard.tsx
+++ b/pages/dashboard.tsx
@@ -17,8 +17,10 @@ import DashboardViewsChart from "@/components/analytics/dashboard-views-chart";
import DocumentsTable from "@/components/analytics/documents-table";
import LinksTable from "@/components/analytics/links-table";
import {
- TimeRange,
+ DASHBOARD_TIME_RANGES,
+ DashboardTimeRange,
TimeRangeSelect,
+ isDashboardTimeRange,
} from "@/components/analytics/time-range-select";
import ViewsTable from "@/components/analytics/views-table";
import VisitorsTable from "@/components/analytics/visitors-table";
@@ -60,17 +62,22 @@ export default function DashboardPage() {
const isPremium = plan !== "free" || !!trial;
const {
- interval = "7d",
type = "links",
start,
end,
} = router.query as {
- interval: TimeRange;
type: string;
start: string;
end: string;
};
+ // A hand-edited "?interval=all" would 400 against /api/analytics, so fall back to the default.
+ const interval: DashboardTimeRange = isDashboardTimeRange(
+ router.query.interval,
+ )
+ ? router.query.interval
+ : "7d";
+
const {
data: overview,
isLoading,
@@ -95,7 +102,7 @@ export default function DashboardPage() {
}
// Update the URL when time range changes
- const handleTimeRangeChange = (newTimeRange: TimeRange) => {
+ const handleTimeRangeChange = (newTimeRange: DashboardTimeRange) => {
const params = new URLSearchParams(window.location.search);
params.set("interval", newTimeRange);
if (type) {
@@ -149,6 +156,7 @@ export default function DashboardPage() {
<TimeRangeSelect
value={interval}
onChange={handleTimeRangeChange}
+ ranges={DASHBOARD_TIME_RANGES}
customRange={customRange}
setCustomRange={setCustomRange}
onCustomRangeComplete={handleCustomRangeComplete}
diff --git a/pages/datarooms/[id]/analytics/index.tsx b/pages/datarooms/[id]/analytics/index.tsx
index e862e4e8..56fd703b 100644
--- a/pages/datarooms/[id]/analytics/index.tsx
+++ b/pages/datarooms/[id]/analytics/index.tsx
@@ -1,107 +1 @@
-import { useState } from "react";
-
-import { PlanEnum } from "@/ee/stripe/constants";
-import { CircleHelpIcon } 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 StatsCard from "@/components/datarooms/stats-card";
-import AppLayout from "@/components/layouts/app";
-import { TabMenu } from "@/components/tab-menu";
-import { FeaturePreview } from "@/components/ui/feature-preview";
-import { BadgeTooltip } from "@/components/ui/tooltip";
-
-export default function DataroomAnalyticsPage() {
- const { dataroom } = useDataroom();
- const { isDatarooms, isDataroomsPlus, isTrial } = usePlan();
-
- const [selectedDocument, setSelectedDocument] = useState<{
- id: string;
- name: string;
- } | null>(null);
-
- const hasAnalyticsAccess = isDatarooms || isDataroomsPlus || isTrial;
-
- 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">
- Data Room Analytics
- </h1>
- <p className="flex flex-row items-center gap-2 text-sm text-muted-foreground">
- Track document engagement and viewer behavior.
- <BadgeTooltip
- linkText="Learn more"
- content="Understand how viewers interact with your documents."
- key="analytics"
- 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>
-
- <TabMenu
- navigation={[
- {
- label: "Analytics",
- href: `/datarooms/${dataroom.id}/analytics`,
- value: "analytics",
- currentValue: "analytics",
- },
- {
- label: "Audit Log",
- href: `/datarooms/${dataroom.id}/analytics/audit-log`,
- value: "audit-log",
- currentValue: "analytics",
- },
- ]}
- className="md:hidden"
- />
-
- <StatsCard />
-
- {hasAnalyticsAccess ? (
- <div className="space-y-6">
- <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>
- </div>
- ) : (
- <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="Data Rooms"
- highlightItem={["analytics", "audit"]}
- >
- <MockAnalyticsTable />
- </FeaturePreview>
- )}
- </div>
- </AppLayout>
- );
-}
+export { default } from "@/ee/features/dataroom-analytics/pages/dataroom-analytics-page";