Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add document stats (duration, completion, per-page chart) to dataroom visitor audit log
Cursor Agent925d71078293
diff --git a/components/visitors/dataroom-view-stats.tsx b/components/visitors/dataroom-view-stats.tsxnew file mode 100644index 00000000..75d13b1c--- /dev/null+++ b/components/visitors/dataroom-view-stats.tsx@@ -0,0 +1,482 @@+import Link from "next/link";++import { useState } from "react";++import {+ DownloadCloudIcon,+ FileCheckIcon,+ FileIcon,+ UploadCloudIcon,+} from "lucide-react";++import { useDataroomVisitHistory } from "@/lib/swr/use-dataroom";+import {+ DocumentViewStats,+ useDataroomViewDocumentStats,+} from "@/lib/swr/use-dataroom-view-document-stats";+import { durationFormat, timeAgo } from "@/lib/utils";++import { Button } from "@/components/ui/button";+import { Gauge } from "@/components/ui/gauge";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import { ScrollArea } from "@/components/ui/scroll-area";+import { Skeleton } from "@/components/ui/skeleton";+import { TableCell, TableRow } from "@/components/ui/table";+import { TimestampTooltip } from "@/components/ui/timestamp-tooltip";++import { DocumentPageChart } from "./document-view-stats";++export function DataroomViewStats({+ viewId,+ dataroomId,+ isExpanded,+}: {+ viewId: string;+ dataroomId: string;+ isExpanded: boolean;+}) {+ const { documentViews, uploadedDocumentViews } = useDataroomVisitHistory({+ viewId,+ dataroomId,+ });++ const { documentStats, loading: statsLoading } =+ useDataroomViewDocumentStats({+ dataroomId,+ dataroomViewId: viewId,+ enabled: isExpanded,+ });++ const statsMap = new Map<string, DocumentViewStats>();+ documentStats?.forEach((s) => {+ statsMap.set(s.viewId, s);+ });++ const groupedViews = documentViews+ ? documentViews.reduce(+ (acc, view) => {+ if (view.downloadType === "BULK" || view.downloadType === "FOLDER") {+ const key = `${view.downloadType}-${new Date(view.viewedAt).toISOString()}`;+ if (!acc.bulkDownloads[key]) {+ acc.bulkDownloads[key] = {+ type: view.downloadType,+ viewedAt: view.viewedAt,+ downloadedAt: view.downloadedAt,+ metadata: view.downloadMetadata,+ documents: [],+ };+ }+ acc.bulkDownloads[key].documents.push(view);+ } else {+ acc.individualViews.push(view);+ }+ return acc;+ },+ {+ individualViews: [] as typeof documentViews,+ bulkDownloads: {} as Record<+ string,+ {+ type: string;+ viewedAt: string;+ downloadedAt: string;+ metadata?: {+ folderName?: string;+ folderPath?: string;+ dataroomName?: string;+ documentCount?: number;+ documents?: {+ id: string;+ name: string;+ }[];+ };+ documents: typeof documentViews;+ }+ >,+ },+ )+ : { individualViews: [], bulkDownloads: {} };++ const allEvents: Array<{+ type: "upload" | "view" | "download" | "bulk-download";+ timestamp: Date;+ data: any;+ }> = [];++ uploadedDocumentViews?.forEach((upload) => {+ allEvents.push({+ type: "upload",+ timestamp: new Date(upload.uploadedAt),+ data: upload,+ });+ });++ Object.entries(groupedViews.bulkDownloads).forEach(([_key, bulkGroup]) => {+ allEvents.push({+ type: "bulk-download",+ timestamp: new Date(bulkGroup.downloadedAt),+ data: bulkGroup,+ });+ });++ groupedViews.individualViews.forEach((view) => {+ const viewedAtTime = new Date(view.viewedAt).getTime();+ const downloadedAtTime = view.downloadedAt+ ? new Date(view.downloadedAt).getTime()+ : null;+ const isDownloadOnly =+ downloadedAtTime && Math.abs(viewedAtTime - downloadedAtTime) < 1000;++ if (!isDownloadOnly) {+ allEvents.push({+ type: "view",+ timestamp: new Date(view.viewedAt),+ data: view,+ });+ }++ if (view.downloadedAt) {+ allEvents.push({+ type: "download",+ timestamp: new Date(view.downloadedAt),+ data: view,+ });+ }+ });++ allEvents.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());++ return (+ <>+ {allEvents.length > 0 ? (+ allEvents.map((event, index) => {+ if (event.type === "upload") {+ return (+ <UploadRow+ key={`upload-${event.data.documentId}-${index}`}+ upload={event.data}+ timestamp={event.timestamp}+ />+ );+ }++ if (event.type === "bulk-download") {+ return (+ <BulkDownloadRow+ key={`bulk-${index}`}+ bulkGroup={event.data}+ timestamp={event.timestamp}+ />+ );+ }++ if (event.type === "view") {+ const view = event.data;+ const stats = statsMap.get(view.id);+ return (+ <DocumentViewRow+ key={`view-${view.id}`}+ view={view}+ stats={stats}+ statsLoading={statsLoading}+ dataroomId={dataroomId}+ dataroomViewId={viewId}+ timestamp={event.timestamp}+ />+ );+ }++ if (event.type === "download") {+ const view = event.data;+ return (+ <DownloadRow+ key={`download-${view.id}`}+ view={view}+ timestamp={event.timestamp}+ />+ );+ }++ return null;+ })+ ) : documentViews === undefined ? (+ <TableRow>+ <TableCell>+ <Skeleton className="h-6 w-24" />+ </TableCell>+ <TableCell>+ <Skeleton className="h-6 w-16" />+ </TableCell>+ </TableRow>+ ) : null}+ </>+ );+}++function DocumentViewRow({+ view,+ stats,+ statsLoading,+ dataroomId,+ dataroomViewId,+ timestamp,+}: {+ view: any;+ stats: DocumentViewStats | undefined;+ statsLoading: boolean;+ dataroomId: string;+ dataroomViewId: string;+ timestamp: Date;+}) {+ return (+ <>+ <TableRow>+ <TableCell>+ <div className="flex items-center gap-x-4 overflow-visible">+ <FileCheckIcon className="h-5 w-5 shrink-0 text-[#fb7a00]" />+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-3">+ <span className="truncate">Viewed {view.document.name}</span>+ {statsLoading ? (+ <div className="flex items-center gap-2">+ <Skeleton className="h-4 w-14" />+ <Skeleton className="h-6 w-6 rounded-full" />+ </div>+ ) : stats ? (+ <div className="flex items-center gap-2">+ <span className="shrink-0 text-xs text-muted-foreground">+ {durationFormat(stats.totalDuration)}+ </span>+ <Gauge+ value={stats.completionRate}+ size={"xs"}+ showValue={true}+ />+ </div>+ ) : null}+ </div>+ {stats && stats.totalPages > 0 && (+ <div className="mt-1">+ <DocumentPageChart+ dataroomId={dataroomId}+ dataroomViewId={dataroomViewId}+ documentViewId={view.id}+ documentId={view.document.id}+ totalPages={stats.totalPages}+ downloadType={view.downloadType}+ downloadMetadata={view.downloadMetadata}+ />+ </div>+ )}+ </div>+ </div>+ </TableCell>+ <TableCell>+ <TimestampTooltip+ timestamp={timestamp}+ side="right"+ rows={["local", "utc", "unix"]}+ >+ <time+ className="select-none truncate text-sm text-muted-foreground"+ dateTime={timestamp.toISOString()}+ >+ {timeAgo(timestamp)}+ </time>+ </TimestampTooltip>+ </TableCell>+ <TableCell className="table-cell">+ <div className="flex items-center justify-end space-x-4">+ <Button size={"sm"} variant={"link"}>+ <Link href={`/documents/${view.document.id}`}>See document</Link>+ </Button>+ </div>+ </TableCell>+ </TableRow>+ </>+ );+}++function UploadRow({+ upload,+ timestamp,+}: {+ upload: any;+ timestamp: Date;+}) {+ return (+ <TableRow>+ <TableCell>+ <div className="flex items-center gap-x-4 overflow-visible">+ <UploadCloudIcon className="h-5 w-5 text-[#fb7a00]" />+ Uploaded {upload.originalFilename}+ </div>+ </TableCell>+ <TableCell>+ <TimestampTooltip+ timestamp={timestamp}+ side="right"+ rows={["local", "utc", "unix"]}+ >+ <time+ className="select-none truncate text-sm text-muted-foreground"+ dateTime={timestamp.toISOString()}+ >+ {timeAgo(timestamp)}+ </time>+ </TimestampTooltip>+ </TableCell>+ <TableCell className="table-cell">+ <div className="flex items-center justify-end space-x-4">+ <Button size={"sm"} variant={"link"}>+ <Link href={`/documents/${upload.documentId}`}>See document</Link>+ </Button>+ </div>+ </TableCell>+ </TableRow>+ );+}++function DownloadRow({+ view,+ timestamp,+}: {+ view: any;+ timestamp: Date;+}) {+ return (+ <TableRow>+ <TableCell>+ <div className="flex items-center gap-x-4 overflow-visible">+ <DownloadCloudIcon className="h-5 w-5 text-[#fb7a00]" />+ Downloaded {view.document.name}+ </div>+ </TableCell>+ <TableCell>+ <TimestampTooltip+ timestamp={timestamp}+ side="right"+ rows={["local", "utc", "unix"]}+ >+ <time+ className="select-none truncate text-sm text-muted-foreground"+ dateTime={timestamp.toISOString()}+ >+ {timeAgo(timestamp)}+ </time>+ </TimestampTooltip>+ </TableCell>+ <TableCell className="table-cell">+ <div className="flex items-center justify-end space-x-4">+ <Button size={"sm"} variant={"link"}>+ <Link href={`/documents/${view.document.id}`}>See document</Link>+ </Button>+ </div>+ </TableCell>+ </TableRow>+ );+}++function BulkDownloadRow({+ bulkGroup,+ timestamp,+}: {+ bulkGroup: any;+ timestamp: Date;+}) {+ const documentCount =+ bulkGroup.metadata?.documentCount || bulkGroup.documents.length;+ const hasDocumentList =+ bulkGroup.metadata?.documents && bulkGroup.metadata.documents.length > 0;++ return (+ <TableRow>+ <TableCell>+ <div className="flex items-center gap-x-4 overflow-visible">+ <DownloadCloudIcon className="h-5 w-5 text-[#fb7a00]" />+ <span>+ Downloaded{" "}+ {hasDocumentList ? (+ <Popover>+ <PopoverTrigger asChild>+ <button className="underline decoration-dotted hover:text-primary">+ {documentCount} document+ {documentCount !== 1 ? "s" : ""}+ </button>+ </PopoverTrigger>+ <PopoverContent className="w-80">+ <div className="space-y-2">+ <h4 className="font-medium leading-none">+ {bulkGroup.type === "FOLDER" &&+ bulkGroup.metadata?.folderName+ ? `Files in ${bulkGroup.metadata.folderName}`+ : `Files in ${bulkGroup.metadata?.dataroomName || "dataroom"}`}+ </h4>+ <ScrollArea className="h-[200px] w-full rounded-md border p-2">+ <div className="space-y-1">+ {bulkGroup.metadata.documents!.map(+ (doc: { id: string; name: string }) => (+ <div+ key={doc.id}+ className="flex items-center gap-2 text-sm"+ >+ <FileIcon className="h-4 w-4 text-muted-foreground" />+ <span className="truncate">{doc.name}</span>+ </div>+ ),+ )}+ </div>+ </ScrollArea>+ </div>+ </PopoverContent>+ </Popover>+ ) : (+ <>+ {documentCount} document+ {documentCount !== 1 ? "s" : ""}+ </>+ )}{" "}+ {bulkGroup.type === "FOLDER" && bulkGroup.metadata?.folderName ? (+ <>+ from folder{" "}+ <span className="font-medium">+ {bulkGroup.metadata.folderName}+ </span>+ </>+ ) : bulkGroup.type === "BULK" &&+ bulkGroup.metadata?.dataroomName ? (+ <>+ from{" "}+ <span className="font-medium">+ {bulkGroup.metadata.dataroomName}+ </span>{" "}+ dataroom+ </>+ ) : (+ "via bulk download"+ )}+ </span>+ </div>+ </TableCell>+ <TableCell>+ <TimestampTooltip+ timestamp={timestamp}+ side="right"+ rows={["local", "utc", "unix"]}+ >+ <time+ className="select-none truncate text-sm text-muted-foreground"+ dateTime={timestamp.toISOString()}+ >+ {timeAgo(timestamp)}+ </time>+ </TimestampTooltip>+ </TableCell>+ <TableCell className="table-cell"></TableCell>+ </TableRow>+ );+}diff --git a/components/visitors/dataroom-viewers.tsx b/components/visitors/dataroom-viewers.tsxindex 7f8ce2b3..b4838f4a 100644--- a/components/visitors/dataroom-viewers.tsx+++ b/components/visitors/dataroom-viewers.tsx@@ -1,3 +1,5 @@+import { useState } from "react";+import {BadgeCheckIcon,BadgeInfoIcon,@@ -27,7 +29,7 @@ import {import { TimestampTooltip } from "@/components/ui/timestamp-tooltip";import { BadgeTooltip } from "@/components/ui/tooltip";-import DataroomVisitHistory from "./dataroom-visitors-history";+import { DataroomViewStats } from "./dataroom-view-stats";import { VisitorAvatar } from "./visitor-avatar";export default function DataroomViewersTable({@@ -36,6 +38,21 @@ export default function DataroomViewersTable({dataroomId: string;}) {const { viewers } = useDataroomViewers({ dataroomId });+ const [expandedViewerIds, setExpandedViewerIds] = useState<Set<string>>(+ new Set(),+ );++ const handleOpenChange = (viewerId: string, open: boolean) => {+ setExpandedViewerIds((prev) => {+ const next = new Set(prev);+ if (open) {+ next.add(viewerId);+ } else {+ next.delete(viewerId);+ }+ return next;+ });+ };return (<div className="w-full">@@ -47,8 +64,6 @@ export default function DataroomViewersTable({<TableHeader><TableRow className="*:whitespace-nowrap *:font-medium hover:bg-transparent"><TableHead>Name</TableHead>- {/* <TableHead>Visit Duration</TableHead> */}- {/* <TableHead>Last Viewed Document</TableHead> */}<TableHead>Last Viewed</TableHead><TableHead className="text-center sm:text-right"></TableHead></TableRow>@@ -56,7 +71,7 @@ export default function DataroomViewersTable({<TableBody>{viewers?.length === 0 && (<TableRow>- <TableCell colSpan={5}>+ <TableCell colSpan={3}><div className="flex h-40 w-full items-center justify-center"><p>No Data Available</p></div>@@ -65,7 +80,11 @@ export default function DataroomViewersTable({)}{viewers ? (viewers.map((viewer) => (- <Collapsible key={viewer.id} asChild>+ <Collapsible+ key={viewer.id}+ asChild+ onOpenChange={(open) => handleOpenChange(viewer.id, open)}+ ><><TableRow key={viewer.id} className="group/row">{/* Name */}@@ -112,29 +131,10 @@ export default function DataroomViewersTable({{viewer.email}</p>)}- <p className="text-xs text-muted-foreground/60 sm:text-sm">- {/* {view.link.name ? view.link.name : view.linkId} */}- </p></div></div></div></TableCell>- {/* Duration */}- {/* <TableCell className="">- <div className="text-sm text-muted-foreground">- {durationFormat(view.totalDuration)}- </div>- </TableCell> */}- {/* Completion */}- {/* <TableCell className="flex justify-start">- <div className="text-sm text-muted-foreground">- <Gauge- value={view.completionRate}- size={"small"}- showValue={true}- />- </div>- </TableCell> */}{/* Last Viewed */}<TableCell className="text-sm text-muted-foreground">{viewer.lastViewedAt ? (@@ -228,9 +228,10 @@ export default function DataroomViewersTable({</TableRow>) : null}- <DataroomVisitHistory+ <DataroomViewStatsviewId={view.id}dataroomId={dataroomId}+ isExpanded={expandedViewerIds.has(viewer.id)}/></></CollapsibleContent>@@ -250,9 +251,6 @@ export default function DataroomViewersTable({<TableCell><Skeleton className="h-6 w-24" /></TableCell>- <TableCell>- <Skeleton className="h-6 w-24" />- </TableCell></TableRow>)}</TableBody>diff --git a/components/visitors/dataroom-visitors-table.tsx b/components/visitors/dataroom-visitors-table.tsxindex 2c0ef4ee..2e11a006 100644--- a/components/visitors/dataroom-visitors-table.tsx+++ b/components/visitors/dataroom-visitors-table.tsx@@ -16,7 +16,7 @@ import {import { usePlan } from "@/lib/swr/use-billing";import { useDataroom } from "@/lib/swr/use-dataroom";import { useDataroomVisits } from "@/lib/swr/use-dataroom";-import { timeAgo } from "@/lib/utils";+import { durationFormat, timeAgo } from "@/lib/utils";import ChevronDown from "@/components/shared/icons/chevron-down";import { Button } from "@/components/ui/button";@@ -42,6 +42,7 @@ import DataroomVisitorCustomFields from "./dataroom-visitor-custom-fields";import { DataroomVisitorUserAgent } from "./dataroom-visitor-useragent";import DataroomVisitHistory from "./dataroom-visitors-history";import { VisitorAvatar } from "./visitor-avatar";+import { DataroomViewStats } from "./dataroom-view-stats";export default function DataroomVisitorsTable({dataroomId,@@ -61,11 +62,26 @@ export default function DataroomVisitorsTable({const { dataroom } = useDataroom();const { isPaused } = usePlan();const [exportModalOpen, setExportModalOpen] = useState(false);+ const [expandedViewIds, setExpandedViewIds] = useState<Set<string>>(+ new Set(),+ );const exportVisitCounts = () => {setExportModalOpen(true);};+ const handleOpenChange = (viewId: string, open: boolean) => {+ setExpandedViewIds((prev) => {+ const next = new Set(prev);+ if (open) {+ next.add(viewId);+ } else {+ next.delete(viewId);+ }+ return next;+ });+ };+return (<div className="w-full"><div className="mb-2 flex items-center justify-between md:mb-4">@@ -80,8 +96,6 @@ export default function DataroomVisitorsTable({<TableHeader><TableRow className="*:whitespace-nowrap *:font-medium hover:bg-transparent"><TableHead>Name</TableHead>- {/* <TableHead>Visit Duration</TableHead> */}- {/* <TableHead>Last Viewed Document</TableHead> */}<TableHead>Last Viewed</TableHead><TableHead className="text-center sm:text-right"></TableHead></TableRow>@@ -89,7 +103,7 @@ export default function DataroomVisitorsTable({<TableBody>{views?.length === 0 && hiddenFromPause === 0 && (<TableRow>- <TableCell colSpan={5}>+ <TableCell colSpan={3}><div className="flex h-40 w-full items-center justify-center"><p>No views yet. Try sharing a link.</p></div>@@ -124,7 +138,11 @@ export default function DataroomVisitorsTable({)}{views ? (views.map((view) => (- <Collapsible key={view.id} asChild>+ <Collapsible+ key={view.id}+ asChild+ onOpenChange={(open) => handleOpenChange(view.id, open)}+ ><><TableRow key={view.id} className="group/row">{/* Name */}@@ -186,22 +204,6 @@ export default function DataroomVisitorsTable({</div></div></TableCell>- {/* Duration */}- {/* <TableCell className="">- <div className="text-sm text-muted-foreground">- {durationFormat(view.totalDuration)}- </div>- </TableCell> */}- {/* Completion */}- {/* <TableCell className="flex justify-start">- <div className="text-sm text-muted-foreground">- <Gauge- value={view.completionRate}- size={"small"}- showValue={true}- />- </div>- </TableCell> */}{/* Last Viewed */}<TableCell className="text-sm text-muted-foreground"><TimestampTooltip@@ -293,9 +295,10 @@ export default function DataroomVisitorsTable({</TableRow>) : null}- <DataroomVisitHistory+ <DataroomViewStatsviewId={view.id}dataroomId={dataroomId}+ isExpanded={expandedViewIds.has(view.id)}/></></CollapsibleContent>@@ -313,9 +316,6 @@ export default function DataroomVisitorsTable({<TableCell><Skeleton className="h-6 w-24" /></TableCell>- <TableCell>- <Skeleton className="h-6 w-24" />- </TableCell></TableRow>)}</TableBody>@@ -336,7 +336,6 @@ export default function DataroomVisitorsTable({);}-// create a component for a blurred view of the visitorconst VisitorBlurred = () => {return (<TableRow className="blur-sm">diff --git a/components/visitors/document-view-stats.tsx b/components/visitors/document-view-stats.tsxnew file mode 100644index 00000000..87510f69--- /dev/null+++ b/components/visitors/document-view-stats.tsx@@ -0,0 +1,165 @@+import { useState } from "react";++import { ChevronRight, DownloadCloudIcon } from "lucide-react";++import BarChartComponent from "@/components/charts/bar-chart";+import StatsChartSkeleton from "@/components/documents/stats-chart-skeleton";+import { Skeleton } from "@/components/ui/skeleton";++import { useDataroomDocumentPageStats } from "@/lib/swr/use-dataroom-view-document-stats";+import { durationFormat } from "@/lib/utils";++import { Gauge } from "@/components/ui/gauge";++export function DocumentViewDuration({+ duration,+ loading,+}: {+ duration: number;+ loading?: boolean;+}) {+ if (loading) {+ return <Skeleton className="h-4 w-16" />;+ }+ return (+ <span className="text-sm text-muted-foreground">+ {durationFormat(duration)}+ </span>+ );+}++export function DocumentViewCompletion({+ completionRate,+ loading,+}: {+ completionRate: number;+ loading?: boolean;+}) {+ if (loading) {+ return <Skeleton className="h-6 w-6 rounded-full" />;+ }+ return (+ <Gauge value={completionRate} size={"small"} showValue={true} />+ );+}++export function DocumentPageChart({+ dataroomId,+ dataroomViewId,+ documentViewId,+ documentId,+ totalPages,+ downloadType,+ downloadMetadata,+}: {+ dataroomId: string;+ dataroomViewId: string;+ documentViewId: string;+ documentId: string;+ totalPages: number;+ downloadType?: "SINGLE" | "BULK" | "FOLDER" | null;+ downloadMetadata?: {+ folderName?: string;+ folderPath?: string;+ dataroomName?: string;+ documentCount?: number;+ documents?: { id: string; name: string }[];+ } | null;+}) {+ const [isExpanded, setIsExpanded] = useState(false);++ const { duration, loading } = useDataroomDocumentPageStats({+ dataroomId,+ dataroomViewId,+ documentViewId,+ documentId,+ enabled: isExpanded,+ });++ const handleToggle = () => setIsExpanded((prev) => !prev);++ if (!isExpanded) {+ return (+ <button+ onClick={handleToggle}+ className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"+ >+ <ChevronRight className="h-3 w-3" />+ Show page-by-page+ </button>+ );+ }++ if (loading || !duration) {+ return (+ <div>+ <button+ onClick={handleToggle}+ className="mb-1 flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"+ >+ <ChevronRight className="h-3 w-3 rotate-90 transition-transform" />+ Hide page-by-page+ </button>+ <StatsChartSkeleton className="border-none px-0" />+ </div>+ );+ }++ const hasViewData = duration.data.some((item) => item.sum_duration > 0);++ if (!hasViewData && downloadType) {+ let downloadMessage = "";+ if (downloadType === "FOLDER" && downloadMetadata?.folderName) {+ downloadMessage = `Downloaded without viewing via folder "${downloadMetadata.folderName}"`;+ } else if (downloadType === "BULK" && downloadMetadata?.dataroomName) {+ downloadMessage = `Downloaded without viewing via bulk download`;+ } else if (downloadType === "SINGLE") {+ downloadMessage = "Downloaded without viewing";+ } else {+ downloadMessage = "Downloaded without viewing";+ }++ return (+ <div>+ <button+ onClick={handleToggle}+ className="mb-1 flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"+ >+ <ChevronRight className="h-3 w-3 rotate-90 transition-transform" />+ Hide page-by-page+ </button>+ <div className="flex items-center gap-2 py-2 text-sm text-muted-foreground">+ <DownloadCloudIcon className="h-4 w-4" />+ <span>{downloadMessage}</span>+ </div>+ </div>+ );+ }++ let durationData = Array.from({ length: totalPages }, (_, i) => ({+ pageNumber: (i + 1).toString(),+ sum_duration: 0,+ }));++ durationData = durationData.map((item) => {+ const match = duration.data.find(+ (d) => d.pageNumber === item.pageNumber,+ );+ return match || item;+ });++ return (+ <div>+ <button+ onClick={handleToggle}+ className="mb-1 flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"+ >+ <ChevronRight className="h-3 w-3 rotate-90 transition-transform" />+ Hide page-by-page+ </button>+ <div className="pb-0.5 pl-0.5 md:pb-1 md:pl-1">+ <BarChartComponent data={durationData} isSum={true} />+ </div>+ </div>+ );+}diff --git a/lib/swr/use-dataroom-view-document-stats.ts b/lib/swr/use-dataroom-view-document-stats.tsnew file mode 100644index 00000000..d486c789--- /dev/null+++ b/lib/swr/use-dataroom-view-document-stats.ts@@ -0,0 +1,82 @@+import { useTeam } from "@/context/team-context";+import useSWR from "swr";++import { fetcher } from "@/lib/utils";++export type DocumentViewStats = {+ viewId: string;+ documentId: string;+ totalDuration: number;+ pagesViewed: number;+ totalPages: number;+ completionRate: number;+};++export function useDataroomViewDocumentStats({+ dataroomId,+ dataroomViewId,+ enabled = false,+}: {+ dataroomId: string;+ dataroomViewId: string;+ enabled?: boolean;+}) {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const { data, error } = useSWR<{ documentStats: DocumentViewStats[] }>(+ enabled && teamId && dataroomId && dataroomViewId+ ? `/api/teams/${teamId}/datarooms/${dataroomId}/views/${dataroomViewId}/document-stats`+ : null,+ fetcher,+ {+ dedupingInterval: 30000,+ revalidateOnFocus: false,+ },+ );++ return {+ documentStats: data?.documentStats,+ loading: enabled ? !error && !data : false,+ error,+ };+}++type PageDurationData = {+ pageNumber: string;+ sum_duration: number;+};++export function useDataroomDocumentPageStats({+ dataroomId,+ dataroomViewId,+ documentViewId,+ documentId,+ enabled = false,+}: {+ dataroomId: string;+ dataroomViewId: string;+ documentViewId: string;+ documentId: string;+ enabled?: boolean;+}) {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const { data, error } = useSWR<{ duration: { data: PageDurationData[] } }>(+ enabled && teamId && dataroomId && dataroomViewId && documentViewId && documentId+ ? `/api/teams/${teamId}/datarooms/${dataroomId}/views/${dataroomViewId}/document-stats?documentViewId=${documentViewId}&documentId=${documentId}`+ : null,+ fetcher,+ {+ dedupingInterval: 30000,+ revalidateOnFocus: false,+ },+ );++ return {+ duration: data?.duration,+ loading: enabled ? !error && !data : false,+ error,+ };+}diff --git a/lib/tinybird/endpoints/get_dataroom_view_document_stats.pipe b/lib/tinybird/endpoints/get_dataroom_view_document_stats.pipenew file mode 100644index 00000000..53d2f838--- /dev/null+++ b/lib/tinybird/endpoints/get_dataroom_view_document_stats.pipe@@ -0,0 +1,16 @@+VERSION 1++NODE endpoint+SQL >+ %+ SELECT+ viewId,+ documentId,+ SUM(duration) AS sum_duration,+ COUNT(DISTINCT pageNumber) AS pages_viewed+ FROM+ page_views__v3+ WHERE+ viewId IN splitByChar(',', {{ String(viewIds, required=True) }})+ GROUP BY+ viewId, documentIddiff --git a/lib/tinybird/pipes.ts b/lib/tinybird/pipes.tsindex db937262..0fb928f6 100644--- a/lib/tinybird/pipes.ts+++ b/lib/tinybird/pipes.ts@@ -213,6 +213,19 @@ export const getClickEventsByView = tb.buildPipe({}),});+export const getDataroomViewDocumentStats = tb.buildPipe({+ pipe: "get_dataroom_view_document_stats__v1",+ parameters: z.object({+ viewIds: z.string().describe("Comma separated viewIds"),+ }),+ data: z.object({+ viewId: z.string(),+ documentId: z.string(),+ sum_duration: z.number(),+ pages_viewed: z.number(),+ }),+});+export const getTotalTeamDuration = tb.buildPipe({pipe: "get_total_team_duration__v1",parameters: z.object({diff --git a/pages/api/teams/[teamId]/datarooms/[id]/views/[viewId]/document-stats.ts b/pages/api/teams/[teamId]/datarooms/[id]/views/[viewId]/document-stats.tsnew file mode 100644index 00000000..a14f650f--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/views/[viewId]/document-stats.ts@@ -0,0 +1,125 @@+import { NextApiRequest, NextApiResponse } from "next";++import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { getServerSession } from "next-auth/next";++import { errorhandler } from "@/lib/errorHandler";+import prisma from "@/lib/prisma";+import { getDataroomViewDocumentStats, getViewPageDuration } from "@/lib/tinybird";+import { CustomUser } from "@/lib/types";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const {+ teamId,+ id: dataroomId,+ viewId,+ } = req.query as {+ teamId: string;+ id: string;+ viewId: string;+ };++ const documentViewId = req.query.documentViewId as string | undefined;+ const documentId = req.query.documentId as string | undefined;++ const userId = (session.user as CustomUser).id;++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId,+ },+ },+ },+ select: { id: true },+ });++ if (!team) {+ return res.status(403).end("Unauthorized to access this team");+ }++ // If documentViewId and documentId are provided, return per-page stats+ if (documentViewId && documentId) {+ const duration = await getViewPageDuration({+ documentId,+ viewId: documentViewId,+ since: 0,+ });++ return res.status(200).json({ duration });+ }++ // Otherwise return summary stats for all document views under this dataroom view+ const documentViews = await prisma.view.findMany({+ where: {+ dataroomViewId: viewId,+ dataroomId,+ viewType: "DOCUMENT_VIEW",+ },+ select: {+ id: true,+ documentId: true,+ document: {+ select: {+ id: true,+ name: true,+ versions: {+ where: { isPrimary: true },+ take: 1,+ select: { numPages: true },+ },+ },+ },+ },+ });++ if (!documentViews.length) {+ return res.status(200).json({ documentStats: [] });+ }++ const viewIds = documentViews.map((v) => v.id).join(",");++ const tinybirdStats = await getDataroomViewDocumentStats({ viewIds });++ const statsMap = new Map(+ tinybirdStats.data.map((s) => [`${s.viewId}:${s.documentId}`, s]),+ );++ const documentStats = documentViews.map((dv) => {+ const stats = statsMap.get(`${dv.id}:${dv.documentId}`);+ const totalPages = dv.document?.versions?.[0]?.numPages ?? 0;+ const pagesViewed = stats?.pages_viewed ?? 0;+ const completionRate =+ totalPages > 0 ? Math.round((pagesViewed / totalPages) * 100) : 0;++ return {+ viewId: dv.id,+ documentId: dv.documentId,+ totalDuration: stats?.sum_duration ?? 0,+ pagesViewed,+ totalPages,+ completionRate,+ };+ });++ return res.status(200).json({ documentStats });+ } catch (error) {+ errorhandler(error, res);+ }+ } else {+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}