Skip to content

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

feat: add dashboard with data for links, views, visitors, documents

Marc Seitza87c2411b17f
diff --git a/components/Sidebar.tsx b/components/Sidebar.tsx
index b1a31292..6d0bfa8b 100644
--- a/components/Sidebar.tsx
+++ b/components/Sidebar.tsx
@@ -10,6 +10,7 @@ import {
ContactIcon,
FolderIcon as FolderLucideIcon,
FolderOpenIcon,
+ LayoutDashboardIcon,
PaletteIcon,
ServerIcon,
} from "lucide-react";
@@ -84,13 +85,12 @@ export const SidebarComponent = ({ className }: { className?: string }) => {
}, []);
const navigation = [
- // {
- // name: "Overview",
- // href: "/overview",
- // icon: HomeIcon,
- // current: router.pathname.includes("overview"),
- // disabled: true,
- // },
+ {
+ name: "Dashboard",
+ href: "/dashboard",
+ icon: LayoutDashboardIcon,
+ current: router.pathname === "/dashboard",
+ },
{
name: "All Documents",
href: "/documents",
diff --git a/components/analytics/analytics-card.tsx b/components/analytics/analytics-card.tsx
new file mode 100644
index 00000000..5d629580
--- /dev/null
+++ b/components/analytics/analytics-card.tsx
@@ -0,0 +1,51 @@
+import { ReactNode } from "react";
+
+import { cn } from "@/lib/utils";
+
+interface AnalyticsCardProps {
+ title: string;
+ icon?: ReactNode;
+ columnHeaders?: {
+ label: string;
+ width?: string;
+ }[];
+ children: ReactNode;
+ className?: string;
+ contentClassName?: string;
+}
+
+export function AnalyticsCard({
+ title,
+ icon,
+ columnHeaders,
+ children,
+ className,
+ contentClassName,
+}: AnalyticsCardProps) {
+ return (
+ <div
+ className={cn(
+ "relative z-0 overflow-hidden border border-border bg-card sm:rounded-xl",
+ className,
+ )}
+ >
+ <div className="flex items-center justify-between border-b border-border py-4 pl-5 pr-4">
+ <h3 className="text-sm font-medium">{title}</h3>
+ {columnHeaders ? (
+ <div className="flex items-center justify-end space-x-1 text-sm text-muted-foreground">
+ {columnHeaders.map((header, index) => (
+ <div key={index} className={cn("text-xs", header.width)}>
+ {header.label}
+ </div>
+ ))}
+ </div>
+ ) : icon ? (
+ <div className="flex items-center gap-1 text-muted-foreground">
+ {icon}
+ </div>
+ ) : null}
+ </div>
+ <div className={cn("py-4", contentClassName)}>{children}</div>
+ </div>
+ );
+}
diff --git a/components/analytics/dashboard-views-chart.tsx b/components/analytics/dashboard-views-chart.tsx
new file mode 100644
index 00000000..5cd002a4
--- /dev/null
+++ b/components/analytics/dashboard-views-chart.tsx
@@ -0,0 +1,169 @@
+import { useMemo } from "react";
+
+import { format, subDays, subHours } from "date-fns";
+import {
+ Bar,
+ BarChart,
+ CartesianGrid,
+ ResponsiveContainer,
+ Tooltip,
+ XAxis,
+ YAxis,
+} from "recharts";
+
+import { TimeRange } from "./time-range-select";
+
+interface DashboardViewsChartProps {
+ timeRange: TimeRange;
+ data?: {
+ date: string;
+ views: number;
+ }[];
+}
+
+export default function DashboardViewsChart({
+ timeRange,
+ data = [],
+}: DashboardViewsChartProps) {
+ // Format the data for display
+ const formattedData = useMemo(() => {
+ // Generate all possible time slots
+ const now = new Date();
+ const slots: { date: Date; views: number }[] = [];
+
+ if (timeRange === "24h") {
+ // Generate 24 hourly slots
+ for (let i = 23; i >= 0; i--) {
+ const date = new Date(now);
+ date.setHours(date.getHours() - i);
+ date.setMinutes(0, 0, 0); // Reset minutes, seconds, milliseconds
+ slots.push({ date, views: 0 });
+ }
+ } else {
+ // Generate daily slots for 7d or 30d
+ const days = timeRange === "7d" ? 7 : 30;
+ for (let i = days - 1; i >= 0; i--) {
+ const date = new Date(now);
+ date.setDate(date.getDate() - i);
+ date.setHours(0, 0, 0, 0); // Reset hours, minutes, seconds, milliseconds
+ slots.push({ date, views: 0 });
+ }
+ }
+
+ // Fill in actual data points
+ if (data) {
+ data.forEach((point) => {
+ const pointDate = new Date(point.date);
+ const slotIndex = slots.findIndex((slot) => {
+ if (timeRange === "24h") {
+ return slot.date.getHours() === pointDate.getHours();
+ } else {
+ return slot.date.toDateString() === pointDate.toDateString();
+ }
+ });
+ if (slotIndex !== -1) {
+ slots[slotIndex].views = point.views;
+ }
+ });
+ }
+
+ // Format for display
+ return slots.map((slot) => ({
+ date: slot.date,
+ name: format(slot.date, timeRange === "24h" ? "h:mm aa" : "EEE, MMM d"),
+ views: slot.views,
+ }));
+ }, [data, timeRange]);
+
+ // Calculate tick values based on time range
+ const ticks = useMemo(() => {
+ if (!formattedData.length) return [];
+
+ if (timeRange === "24h") {
+ // Show current hour and every 5th hour working backwards
+ const tickIndices = [];
+ for (let i = formattedData.length - 1; i >= 0; i -= 5) {
+ tickIndices.unshift(i);
+ }
+ return tickIndices.map((i) => formattedData[i].name);
+ } else if (timeRange === "7d") {
+ // Show all days
+ return formattedData.map((d) => d.name);
+ } else if (timeRange === "30d") {
+ // Show current day and every 5th day working backwards
+ const tickIndices = [];
+ for (let i = formattedData.length - 1; i >= 0; i -= 5) {
+ tickIndices.unshift(i);
+ }
+ return tickIndices.map((i) => formattedData[i].name);
+ }
+ return formattedData.map((d) => d.name);
+ }, [timeRange, formattedData]);
+
+ return (
+ <div className="h-[300px] w-full">
+ <ResponsiveContainer width="100%" height="100%">
+ <BarChart
+ data={formattedData}
+ margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
+ barSize={timeRange === "24h" ? 8 : timeRange === "7d" ? 24 : 12}
+ >
+ <XAxis
+ dataKey="name"
+ stroke="#888888"
+ fontSize={12}
+ tickLine={false}
+ axisLine={false}
+ ticks={ticks}
+ interval="preserveStartEnd"
+ />
+ <YAxis
+ stroke="#888888"
+ fontSize={12}
+ tickLine={false}
+ axisLine={false}
+ tickFormatter={(value) => `${value}`}
+ />
+ <CartesianGrid vertical={false} strokeDasharray="3 3" />
+ <Tooltip
+ content={({ active, payload }) => {
+ if (active && payload && payload.length) {
+ const data = payload[0].payload;
+ return (
+ <div className="rounded-lg border bg-background p-2 shadow-sm">
+ <div className="grid grid-cols-2 gap-2">
+ <div className="flex flex-col">
+ <span className="text-[0.70rem] uppercase text-muted-foreground">
+ Time
+ </span>
+ <span className="font-bold text-muted-foreground">
+ {timeRange === "24h"
+ ? format(data.date, "h:mm a")
+ : format(data.date, "MMM d, yyyy")}
+ </span>
+ </div>
+ <div className="flex flex-col">
+ <span className="text-[0.70rem] uppercase text-muted-foreground">
+ Views
+ </span>
+ <span className="font-bold">{data.views}</span>
+ </div>
+ </div>
+ </div>
+ );
+ }
+ return null;
+ }}
+ />
+ <Bar
+ dataKey="views"
+ fill="rgb(16 185 129)"
+ stroke="rgb(16 185 129)"
+ strokeWidth={1}
+ radius={[2, 2, 0, 0]}
+ />
+ </BarChart>
+ </ResponsiveContainer>
+ </div>
+ );
+}
diff --git a/components/analytics/documents-table.tsx b/components/analytics/documents-table.tsx
new file mode 100644
index 00000000..c8add5a1
--- /dev/null
+++ b/components/analytics/documents-table.tsx
@@ -0,0 +1,276 @@
+import Link from "next/link";
+import { useRouter } from "next/router";
+
+import { useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import {
+ ColumnDef,
+ SortingState,
+ flexRender,
+ getCoreRowModel,
+ getPaginationRowModel,
+ getSortedRowModel,
+ useReactTable,
+} from "@tanstack/react-table";
+import {
+ ChevronDownIcon,
+ ChevronUpIcon,
+ ChevronsUpDownIcon,
+ Download,
+ FileIcon,
+} from "lucide-react";
+import { toast } from "sonner";
+import useSWR from "swr";
+
+import { Button } from "@/components/ui/button";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { DataTablePagination } from "@/components/visitors/data-table-pagination";
+
+import { fetcher, timeAgo } from "@/lib/utils";
+import { downloadCSV } from "@/lib/utils/csv";
+
+interface Document {
+ id: string;
+ name: string;
+ views: number;
+ avgDuration: string;
+ lastViewed: Date | null;
+}
+
+const columns: ColumnDef<Document>[] = [
+ {
+ accessorKey: "name",
+ header: "Documents",
+ cell: ({ row }) => (
+ <div className="flex items-center overflow-visible sm:space-x-3">
+ <div className="min-w-0 flex-1">
+ <div className="focus:outline-none">
+ <Link
+ href={`/documents/${row.original.id}`}
+ className="flex items-center gap-x-2 overflow-visible text-sm font-medium text-gray-800 hover:text-gray-600 dark:text-gray-200 dark:hover:text-gray-400"
+ >
+ {row.original.name}
+ </Link>
+ </div>
+ </div>
+ </div>
+ ),
+ },
+ {
+ accessorKey: "views",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className={
+ column.getIsSorted()
+ ? "text-nowrap font-medium"
+ : "text-nowrap font-normal"
+ }
+ >
+ Views
+ {column.getIsSorted() === "asc" ? (
+ <ChevronUpIcon className="ml-2 h-4 w-4" />
+ ) : column.getIsSorted() === "desc" ? (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ ) : (
+ <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ );
+ },
+ cell: ({ row }) => (
+ <div className="text-sm text-muted-foreground">{row.original.views}</div>
+ ),
+ },
+ {
+ accessorKey: "avgDuration",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className={
+ column.getIsSorted()
+ ? "text-nowrap font-medium"
+ : "text-nowrap font-normal"
+ }
+ >
+ Avg Duration
+ {column.getIsSorted() === "asc" ? (
+ <ChevronUpIcon className="ml-2 h-4 w-4" />
+ ) : column.getIsSorted() === "desc" ? (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ ) : (
+ <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ );
+ },
+ cell: ({ row }) => (
+ <div className="text-sm text-muted-foreground">
+ {row.original.avgDuration}
+ </div>
+ ),
+ },
+ {
+ accessorKey: "lastViewed",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className={
+ column.getIsSorted()
+ ? "text-nowrap font-medium"
+ : "text-nowrap font-normal"
+ }
+ >
+ Last Viewed
+ {column.getIsSorted() === "asc" ? (
+ <ChevronUpIcon className="ml-2 h-4 w-4" />
+ ) : column.getIsSorted() === "desc" ? (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ ) : (
+ <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ );
+ },
+ cell: ({ row }) => (
+ <div className="text-sm text-muted-foreground">
+ {row.original.lastViewed ? timeAgo(row.original.lastViewed) : "-"}
+ </div>
+ ),
+ },
+];
+
+export default function DocumentsTable() {
+ const router = useRouter();
+ const teamInfo = useTeam();
+ const [sorting, setSorting] = useState<SortingState>([
+ { id: "lastViewed", desc: true },
+ ]);
+
+ const interval = router.query.interval || "24h";
+ const { data: documents, isLoading } = useSWR<Document[]>(
+ `/api/analytics?type=documents&interval=${interval}&teamId=${teamInfo?.currentTeam?.id}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ revalidateOnFocus: false,
+ },
+ );
+
+ const table = useReactTable({
+ data: documents || [],
+ columns,
+ getCoreRowModel: getCoreRowModel(),
+ getPaginationRowModel: getPaginationRowModel(),
+ onSortingChange: setSorting,
+ getSortedRowModel: getSortedRowModel(),
+ state: {
+ sorting,
+ },
+ });
+
+ const handleExport = () => {
+ if (!documents?.length) {
+ toast.error("No data to export");
+ return;
+ }
+
+ const exportData = documents.map((doc) => ({
+ "Document Name": doc.name,
+ Views: doc.views,
+ "Average Duration": doc.avgDuration,
+ "Last Viewed": doc.lastViewed
+ ? new Date(doc.lastViewed).toISOString()
+ : "Never",
+ }));
+
+ downloadCSV(exportData, "documents");
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex justify-end">
+ <Button variant="outline" size="sm" onClick={handleExport}>
+ <Download className="!size-4" />
+ Export
+ </Button>
+ </div>
+ <div className="rounded-xl border">
+ <Table>
+ <TableHeader>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <TableRow key={headerGroup.id}>
+ {headerGroup.headers.map((header) => (
+ <TableHead key={header.id} className="px-0 first:px-4">
+ {header.isPlaceholder
+ ? null
+ : flexRender(
+ header.column.columnDef.header,
+ header.getContext(),
+ )}
+ </TableHead>
+ ))}
+ </TableRow>
+ ))}
+ </TableHeader>
+ <TableBody>
+ {isLoading ? (
+ <TableRow>
+ <TableCell
+ colSpan={columns.length}
+ className="h-24 text-center"
+ >
+ Loading...
+ </TableCell>
+ </TableRow>
+ ) : table.getRowModel().rows?.length ? (
+ table.getRowModel().rows.map((row) => (
+ <TableRow key={row.id}>
+ {row.getVisibleCells().map((cell) => (
+ <TableCell key={cell.id}>
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext(),
+ )}
+ </TableCell>
+ ))}
+ </TableRow>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell
+ colSpan={columns.length}
+ className="h-24 text-center"
+ >
+ <div className="flex w-full flex-col items-center justify-center gap-4 rounded-xl py-4">
+ <div className="hidden rounded-full sm:block">
+ <div className="rounded-full border border-white bg-gradient-to-t from-gray-100 p-1 md:p-3">
+ <FileIcon className="size-6" />
+ </div>
+ </div>
+ <p>No visited documents in the last {interval}</p>
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ <DataTablePagination table={table} name="document" />
+ </div>
+ );
+}
diff --git a/components/analytics/links-table.tsx b/components/analytics/links-table.tsx
new file mode 100644
index 00000000..f17d3a12
--- /dev/null
+++ b/components/analytics/links-table.tsx
@@ -0,0 +1,341 @@
+import Link from "next/link";
+import { useRouter } from "next/router";
+
+import { useEffect, useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import {
+ ColumnDef,
+ SortingState,
+ flexRender,
+ getCoreRowModel,
+ getPaginationRowModel,
+ getSortedRowModel,
+ useReactTable,
+} from "@tanstack/react-table";
+import {
+ Check,
+ ChevronDownIcon,
+ ChevronUpIcon,
+ ChevronsUpDownIcon,
+ Copy,
+ Download,
+ Link2Icon,
+} from "lucide-react";
+import { toast } from "sonner";
+import useSWR from "swr";
+
+import { Button } from "@/components/ui/button";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { DataTablePagination } from "@/components/visitors/data-table-pagination";
+
+import { cn, timeAgo } from "@/lib/utils";
+import { fetcher } from "@/lib/utils";
+import { downloadCSV } from "@/lib/utils/csv";
+
+interface Link {
+ id: string;
+ name: string;
+ url: string;
+ documentName: string;
+ documentId: string;
+ views: number;
+ avgDuration: string;
+ lastViewed: Date | null;
+}
+
+function CopyButton({ url }: { url: string }) {
+ const [copied, setCopied] = useState(false);
+
+ useEffect(() => {
+ if (copied) {
+ toast.success("Link copied to clipboard");
+ const timeout = setTimeout(() => setCopied(false), 2000);
+ return () => clearTimeout(timeout);
+ }
+ }, [copied]);
+
+ return (
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6 hover:bg-transparent"
+ onClick={() => {
+ navigator.clipboard.writeText(url);
+ setCopied(true);
+ }}
+ >
+ {copied ? (
+ <Check className="!size-4 text-emerald-500" />
+ ) : (
+ <Copy className="!size-4 text-muted-foreground" />
+ )}
+ </Button>
+ );
+}
+
+const columns: ColumnDef<Link>[] = [
+ {
+ accessorKey: "name",
+ header: "Links",
+ cell: ({ row }) => (
+ <div className="flex items-center overflow-visible sm:space-x-3">
+ <div className="min-w-0 flex-1">
+ <div className="focus:outline-none">
+ <p className="flex items-center gap-x-2 overflow-visible text-sm font-medium text-gray-800 dark:text-gray-200">
+ {row.original.name}
+ </p>
+ <div className="flex items-center gap-x-1">
+ <p className="text-sm text-muted-foreground">
+ {row.original.url}
+ </p>
+ <CopyButton url={row.original.url} />
+ </div>
+ </div>
+ </div>
+ </div>
+ ),
+ },
+ {
+ accessorKey: "documentName",
+ header: "Document",
+ cell: ({ row }) => (
+ <div className="text-sm">
+ {row.original.documentId ? (
+ <Link
+ href={`/documents/${row.original.documentId}`}
+ className="flex items-center gap-x-2 overflow-visible text-sm text-gray-800 hover:text-gray-600 dark:text-gray-200 dark:hover:text-gray-400"
+ >
+ {row.original.documentName}
+ </Link>
+ ) : (
+ <span className="text-muted-foreground">
+ {row.original.documentName}
+ </span>
+ )}
+ </div>
+ ),
+ },
+ {
+ accessorKey: "views",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className={cn(
+ column.getIsSorted()
+ ? "text-nowrap font-medium"
+ : "text-nowrap font-normal",
+ "px-0",
+ )}
+ >
+ Views
+ {column.getIsSorted() === "asc" ? (
+ <ChevronUpIcon className="ml-2 h-4 w-4" />
+ ) : column.getIsSorted() === "desc" ? (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ ) : (
+ <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ );
+ },
+ cell: ({ row }) => (
+ <div className="text-sm text-muted-foreground">{row.original.views}</div>
+ ),
+ },
+ {
+ accessorKey: "avgDuration",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className={cn(
+ column.getIsSorted()
+ ? "text-nowrap font-medium"
+ : "text-nowrap font-normal",
+ "px-0",
+ )}
+ >
+ Avg Duration
+ {column.getIsSorted() === "asc" ? (
+ <ChevronUpIcon className="ml-2 h-4 w-4" />
+ ) : column.getIsSorted() === "desc" ? (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ ) : (
+ <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ );
+ },
+ cell: ({ row }) => (
+ <div className="text-sm text-muted-foreground">
+ {row.original.avgDuration}
+ </div>
+ ),
+ },
+ {
+ accessorKey: "lastViewed",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className={cn(
+ column.getIsSorted()
+ ? "text-nowrap font-medium"
+ : "text-nowrap font-normal",
+ "px-0",
+ )}
+ >
+ Last Viewed
+ {column.getIsSorted() === "asc" ? (
+ <ChevronUpIcon className="ml-2 h-4 w-4" />
+ ) : column.getIsSorted() === "desc" ? (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ ) : (
+ <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ );
+ },
+ cell: ({ row }) => (
+ <div className="text-sm text-muted-foreground">
+ {row.original.lastViewed ? timeAgo(row.original.lastViewed) : "-"}
+ </div>
+ ),
+ },
+];
+
+export default function LinksTable() {
+ const router = useRouter();
+
+ const teamInfo = useTeam();
+ const [sorting, setSorting] = useState<SortingState>([
+ { id: "lastViewed", desc: true },
+ ]);
+
+ const interval = router.query.interval || "7d";
+ const { data: links, isLoading } = useSWR<Link[]>(
+ `/api/analytics?type=links&interval=${interval}&teamId=${teamInfo?.currentTeam?.id}`,
+ fetcher,
+ {
+ keepPreviousData: true,
+ revalidateOnFocus: false,
+ },
+ );
+
+ const table = useReactTable({
+ data: links || [],
+ columns,
+ getCoreRowModel: getCoreRowModel(),
+ getPaginationRowModel: getPaginationRowModel(),
+ onSortingChange: setSorting,
+ getSortedRowModel: getSortedRowModel(),
+ state: {
+ sorting,
+ },
+ });
+
+ const handleExport = () => {
+ if (!links?.length) {
+ toast.error("No data to export");
+ return;
+ }
+
+ const exportData = links.map((link) => ({
+ "Link Name": link.name,
+ URL: link.url,
+ Document: link.documentName,
+ Views: link.views,
+ "Average Duration": link.avgDuration,
+ "Last Viewed": link.lastViewed
+ ? new Date(link.lastViewed).toISOString()
+ : "Never",
+ }));
+
+ downloadCSV(exportData, "links");
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex justify-end">
+ <Button variant="outline" size="sm" onClick={handleExport}>
+ <Download className="!size-4" />
+ Export
+ </Button>
+ </div>
+ <div className="rounded-xl border">
+ <Table>
+ <TableHeader>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <TableRow key={headerGroup.id}>
+ {headerGroup.headers.map((header) => (
+ <TableHead key={header.id} className="px-4">
+ {header.isPlaceholder
+ ? null
+ : flexRender(
+ header.column.columnDef.header,
+ header.getContext(),
+ )}
+ </TableHead>
+ ))}
+ </TableRow>
+ ))}
+ </TableHeader>
+ <TableBody>
+ {isLoading ? (
+ <TableRow>
+ <TableCell
+ colSpan={columns.length}
+ className="h-24 text-center"
+ >
+ Loading...
+ </TableCell>
+ </TableRow>
+ ) : table.getRowModel().rows?.length ? (
+ table.getRowModel().rows.map((row) => (
+ <TableRow key={row.id}>
+ {row.getVisibleCells().map((cell) => (
+ <TableCell key={cell.id}>
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext(),
+ )}
+ </TableCell>
+ ))}
+ </TableRow>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell
+ colSpan={columns.length}
+ className="h-24 text-center"
+ >
+ <div className="flex w-full flex-col items-center justify-center gap-4 rounded-xl py-4">
+ <div className="hidden rounded-full sm:block">
+ <div className="rounded-full border border-white bg-gradient-to-t from-gray-100 p-1 md:p-3">
+ <Link2Icon className="size-6" />
+ </div>
+ </div>
+ <p>No visited links in the last {interval}</p>
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ <DataTablePagination table={table} name="link" />
+ </div>
+ );
+}
diff --git a/components/analytics/recent-views-table.tsx b/components/analytics/recent-views-table.tsx
new file mode 100644
index 00000000..cdd17135
--- /dev/null
+++ b/components/analytics/recent-views-table.tsx
@@ -0,0 +1,54 @@
+import { formatDistanceToNow } from "date-fns";
+import { FileText } from "lucide-react";
+
+import BarList from "@/components/ui/bar-list";
+
+export default function RecentViewsTable() {
+ // TODO: Replace with actual data fetching
+ const views = [
+ {
+ id: 1,
+ documentName: "Q4 2023 Report.pdf",
+ viewerName: "John Doe",
+ viewerEmail: "[email protected]",
+ duration: "2m 30s",
+ viewedAt: new Date(Date.now() - 1000 * 60 * 30), // 30 minutes ago
+ },
+ {
+ id: 2,
+ documentName: "Product Roadmap.pdf",
+ viewerName: "Jane Smith",
+ viewerEmail: "[email protected]",
+ duration: "4m 15s",
+ viewedAt: new Date(Date.now() - 1000 * 60 * 60), // 1 hour ago
+ },
+ ];
+
+ // For the bar visualization, we'll use the duration in seconds
+ const getDurationInSeconds = (duration: string) => {
+ const [minutes, seconds] = duration.split("m ");
+ return parseInt(minutes) * 60 + parseInt(seconds);
+ };
+
+ const maxDuration = Math.max(
+ ...views.map((view) => getDurationInSeconds(view.duration)),
+ );
+
+ const barListData = views.map((view) => ({
+ icon: <FileText className="h-4 w-4 text-muted-foreground" />,
+ title: view.documentName,
+ subtitle: `${view.viewerName} • ${formatDistanceToNow(view.viewedAt, { addSuffix: true })}`,
+ value: getDurationInSeconds(view.duration),
+ secondaryValue: view.duration,
+ }));
+
+ return (
+ <div className="space-y-4">
+ <BarList
+ data={barListData}
+ maxValue={maxDuration}
+ barBackground="bg-orange-100 dark:bg-orange-950/50"
+ />
+ </div>
+ );
+}
diff --git a/components/analytics/time-range-select.tsx b/components/analytics/time-range-select.tsx
new file mode 100644
index 00000000..979a2b9f
--- /dev/null
+++ b/components/analytics/time-range-select.tsx
@@ -0,0 +1,61 @@
+import { CalendarDays, CalendarIcon, ChevronDown } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+
+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: "90d", label: "Last 3 months", shortcut: "Q" },
+ // { value: "1y", label: "Last 12 months", shortcut: "Y" },
+] as const;
+
+export type TimeRange = (typeof TIME_RANGES)[number]["value"];
+
+interface TimeRangeSelectProps {
+ value: TimeRange;
+ onChange: (value: TimeRange) => void;
+}
+
+export function TimeRangeSelect({ value, onChange }: TimeRangeSelectProps) {
+ const selectedRange = TIME_RANGES.find((range) => range.value === value);
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ className="w-full justify-between text-left font-normal sm:inline-flex sm:min-w-[200px] md:w-fit"
+ >
+ <div className="flex items-center gap-2">
+ <CalendarIcon className="!size-4" />
+ <span>{selectedRange?.label}</span>
+ </div>
+ <ChevronDown className="!size-4 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[200px] p-1" align="end">
+ <div className="grid">
+ {TIME_RANGES.map((range) => (
+ <Button
+ key={range.value}
+ variant={range.value === value ? "secondary" : "ghost"}
+ className="justify-between"
+ onClick={() => onChange(range.value)}
+ >
+ <span>{range.label}</span>
+ <kbd className="pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100">
+ {range.shortcut}
+ </kbd>
+ </Button>
+ ))}
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/components/analytics/viewers-table.tsx b/components/analytics/viewers-table.tsx
new file mode 100644
index 00000000..828f6078
--- /dev/null
+++ b/components/analytics/viewers-table.tsx
@@ -0,0 +1,49 @@
+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
+import BarList from "@/components/ui/bar-list";
+
+export default function ViewersTable() {
+ // TODO: Replace with actual data fetching
+ const viewers = [
+ {
+ id: 1,
+ name: "John Doe",
+ email: "[email protected]",
+ viewCount: 15,
+ avgDuration: "3m 45s",
+ lastActive: new Date(Date.now() - 1000 * 60 * 5), // 5 minutes ago
+ },
+ {
+ id: 2,
+ name: "Jane Smith",
+ email: "[email protected]",
+ viewCount: 8,
+ avgDuration: "2m 30s",
+ lastActive: new Date(Date.now() - 1000 * 60 * 15), // 15 minutes ago
+ },
+ ];
+
+ const maxViews = Math.max(...viewers.map((viewer) => viewer.viewCount));
+
+ const barListData = viewers.map((viewer) => ({
+ icon: (
+ <Avatar className="h-6 w-6">
+ <AvatarImage src={`https://avatar.vercel.sh/${viewer.email}`} />
+ <AvatarFallback>{viewer.name.slice(0, 2).toUpperCase()}</AvatarFallback>
+ </Avatar>
+ ),
+ title: viewer.name,
+ subtitle: viewer.email,
+ value: viewer.viewCount,
+ secondaryValue: viewer.avgDuration,
+ }));
+
+ return (
+ <div className="space-y-4">
+ <BarList
+ data={barListData}
+ maxValue={maxViews}
+ barBackground="bg-green-100 dark:bg-green-950/50"
+ />
+ </div>
+ );
+}
diff --git a/components/analytics/views-table.tsx b/components/analytics/views-table.tsx
new file mode 100644
index 00000000..aa0626f3
--- /dev/null
+++ b/components/analytics/views-table.tsx
@@ -0,0 +1,411 @@
+import Link from "next/link";
+import { useRouter } from "next/router";
+
+import { useMemo, useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import {
+ ColumnDef,
+ SortingState,
+ flexRender,
+ getCoreRowModel,
+ getPaginationRowModel,
+ getSortedRowModel,
+ useReactTable,
+} from "@tanstack/react-table";
+import {
+ BadgeCheckIcon,
+ BadgeInfoIcon,
+ ChevronDownIcon,
+ ChevronUpIcon,
+ ChevronsUpDownIcon,
+ Download,
+ DownloadCloudIcon,
+ FileBadgeIcon,
+ FileDigitIcon,
+ MoreHorizontalIcon,
+ ServerIcon,
+ ThumbsDownIcon,
+ ThumbsUpIcon,
+} from "lucide-react";
+import { toast } from "sonner";
+import useSWR from "swr";
+
+import { Button } from "@/components/ui/button";
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from "@/components/ui/collapsible";
+import { Gauge } from "@/components/ui/gauge";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { BadgeTooltip } from "@/components/ui/tooltip";
+import { DataTablePagination } from "@/components/visitors/data-table-pagination";
+import { VisitorAvatar } from "@/components/visitors/visitor-avatar";
+import VisitorChart from "@/components/visitors/visitor-chart";
+import VisitorClicks from "@/components/visitors/visitor-clicks";
+import VisitorCustomFields from "@/components/visitors/visitor-custom-fields";
+import VisitorUserAgent from "@/components/visitors/visitor-useragent";
+import VisitorVideoChart from "@/components/visitors/visitor-video-chart";
+
+import { cn, durationFormat, fetcher, timeAgo } from "@/lib/utils";
+import { downloadCSV } from "@/lib/utils/csv";
+
+interface View {
+ id: string;
+ viewerEmail: string | null;
+ documentName: string;
+ linkName: string;
+ viewedAt: Date;
+ totalDuration: number;
+ completionRate: number;
+ verified?: boolean;
+ internal?: boolean;
+ agreementResponse?: any;
+ downloadedAt?: Date;
+ dataroomId?: string;
+ feedbackResponse?: any;
+ versionNumber?: number;
+ versionNumPages?: number;
+ documentId?: string;
+ teamId?: string;
+}
+
+const columns: ColumnDef<View>[] = [
+ {
+ accessorKey: "viewerEmail",
+ header: "Recent Visits",
+ cell: ({ row }) => (
+ <div className="flex items-center overflow-visible sm:space-x-3">
+ <VisitorAvatar viewerEmail={row.original.viewerEmail} />
+ <div className="min-w-0 flex-1">
+ <div className="focus:outline-none">
+ <p className="flex items-center gap-x-2 overflow-visible text-sm font-medium text-gray-800 dark:text-gray-200">
+ {row.original.viewerEmail ? (
+ <>
+ {row.original.viewerEmail}{" "}
+ {row.original.verified && (
+ <BadgeTooltip content="Verified visitor" key="verified">
+ <BadgeCheckIcon className="h-4 w-4 text-emerald-500 hover:text-emerald-600" />
+ </BadgeTooltip>
+ )}
+ {row.original.internal && (
+ <BadgeTooltip content="Internal visitor" key="internal">
+ <BadgeInfoIcon className="h-4 w-4 text-blue-500 hover:text-blue-600" />
+ </BadgeTooltip>
+ )}
+ {row.original.agreementResponse && (
+ <BadgeTooltip
+ content={`Agreed to ${row.original.agreementResponse.agreement.name}`}
+ key="nda-agreement"
+ >
+ <FileBadgeIcon className="h-4 w-4 text-emerald-500 hover:text-emerald-600" />
+ </BadgeTooltip>
+ )}
+ {row.original.downloadedAt && (
+ <BadgeTooltip
+ content={`Downloaded ${timeAgo(row.original.downloadedAt)}`}
+ key="download"
+ >
+ <DownloadCloudIcon className="h-4 w-4 text-cyan-500 hover:text-cyan-600" />
+ </BadgeTooltip>
+ )}
+ {row.original.dataroomId && (
+ <BadgeTooltip content={`Dataroom Visitor`} key="download">
+ <ServerIcon className="h-4 w-4 text-[#fb7a00] hover:text-[#fb7a00]/90" />
+ </BadgeTooltip>
+ )}
+ {row.original.feedbackResponse && (
+ <BadgeTooltip
+ content={`${row.original.feedbackResponse.data.question}: ${row.original.feedbackResponse.data.answer}`}
+ key="feedback"
+ >
+ {row.original.feedbackResponse.data.answer === "yes" ? (
+ <ThumbsUpIcon className="h-4 w-4 text-gray-500 hover:text-gray-600" />
+ ) : (
+ <ThumbsDownIcon className="h-4 w-4 text-gray-500 hover:text-gray-600" />
+ )}
+ </BadgeTooltip>
+ )}
+ </>
+ ) : (
+ "Anonymous"
+ )}
+ </p>
+ </div>
+ </div>
+ </div>
+ ),
+ },
+ {
+ accessorKey: "documentName",
+ header: "Document",
+ cell: ({ row }) => (
+ <div className="text-sm">
+ {row.original.documentId ? (
+ <Link
+ href={`/documents/${row.original.documentId}`}
+ className="flex items-center gap-x-2 overflow-visible text-sm text-gray-800 hover:text-gray-600 dark:text-gray-200 dark:hover:text-gray-400"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {row.original.documentName}
+ </Link>
+ ) : (
+ <span className="text-muted-foreground">
+ {row.original.documentName}
+ </span>
+ )}
+ </div>
+ ),
+ },
+ {
+ accessorKey: "linkName",
+ header: "Link",
+ cell: ({ row }) => (
+ <div className="text-sm text-muted-foreground">
+ {row.original.linkName}
+ </div>
+ ),
+ },
+ {
+ accessorKey: "totalDuration",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className={cn(
+ column.getIsSorted()
+ ? "text-nowrap font-medium"
+ : "text-nowrap font-normal",
+ "px-0",
+ )}
+ >
+ Time Spent
+ {column.getIsSorted() === "asc" ? (
+ <ChevronUpIcon className="ml-2 h-4 w-4" />
+ ) : column.getIsSorted() === "desc" ? (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ ) : (
+ <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ );
+ },
+ cell: ({ row }) => (
+ <div className="text-sm text-muted-foreground">
+ {durationFormat(row.original.totalDuration)}
+ </div>
+ ),
+ },
+ {
+ accessorKey: "completionRate",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className={cn(
+ column.getIsSorted()
+ ? "text-nowrap font-medium"
+ : "text-nowrap font-normal",
+ "px-0",
+ )}
+ >
+ Completion
+ {column.getIsSorted() === "asc" ? (
+ <ChevronUpIcon className="ml-2 h-4 w-4" />
+ ) : column.getIsSorted() === "desc" ? (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ ) : (
+ <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ );
+ },
+ cell: ({ row }) => (
+ <div className="flex justify-start text-sm text-muted-foreground">
+ <Gauge
+ value={row.original.completionRate}
+ size={"small"}
+ showValue={true}
+ />
+ </div>
+ ),
+ },
+ {
+ accessorKey: "viewedAt",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className={cn(
+ column.getIsSorted()
+ ? "text-nowrap font-medium"
+ : "text-nowrap font-normal",
+ "px-0",
+ )}
+ >
+ Last Visited
+ {column.getIsSorted() === "asc" ? (
+ <ChevronUpIcon className="ml-2 h-4 w-4" />
+ ) : column.getIsSorted() === "desc" ? (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ ) : (
+ <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ );
+ },
+ cell: ({ row }) => (
+ <div className="text-sm text-muted-foreground">
+ {timeAgo(row.original.viewedAt)}
+ </div>
+ ),
+ },
+];
+
+export default function ViewsTable() {
+ const router = useRouter();
+ const teamInfo = useTeam();
+ const { interval = "7d" } = router.query;
+ const [sorting, setSorting] = useState<SortingState>([
+ { id: "viewedAt", desc: true },
+ ]);
+
+ const { data: views } = useSWR<View[]>(
+ teamInfo?.currentTeam?.id
+ ? `/api/analytics?type=views&interval=${interval}&teamId=${teamInfo.currentTeam.id}`
+ : null,
+ fetcher,
+ {
+ keepPreviousData: true,
+ revalidateOnFocus: false,
+ },
+ );
+
+ const table = useReactTable({
+ data: views || [],
+ columns,
+ getCoreRowModel: getCoreRowModel(),
+ getPaginationRowModel: getPaginationRowModel(),
+ onSortingChange: setSorting,
+ getSortedRowModel: getSortedRowModel(),
+ state: {
+ sorting,
+ },
+ });
+
+ const handleExport = () => {
+ if (!views?.length) {
+ toast.error("No data to export");
+ return;
+ }
+
+ const exportData = views.map((view) => ({
+ "Visitor Email": view.viewerEmail || "Anonymous",
+ Document: view.documentName,
+ Link: view.linkName,
+ "Time Spent": durationFormat(view.totalDuration),
+ "Completion Rate": `${view.completionRate}%`,
+ "Viewed At": new Date(view.viewedAt).toISOString(),
+ Verified: view.verified ? "Yes" : "No",
+ }));
+
+ downloadCSV(exportData, "views");
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex justify-end">
+ <Button variant="outline" size="sm" onClick={handleExport}>
+ <Download className="!size-4" />
+ Export
+ </Button>
+ </div>
+ <div className="rounded-xl border">
+ <Table>
+ <TableHeader>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <TableRow key={headerGroup.id}>
+ {headerGroup.headers.map((header) => (
+ <TableHead key={header.id} className="px-4">
+ {header.isPlaceholder
+ ? null
+ : flexRender(
+ header.column.columnDef.header,
+ header.getContext(),
+ )}
+ </TableHead>
+ ))}
+ </TableRow>
+ ))}
+ </TableHeader>
+ <TableBody>
+ {table.getRowModel().rows?.length ? (
+ table.getRowModel().rows.map((row) => (
+ // <Collapsible key={row.id} asChild>
+ <>
+ {/* <CollapsibleTrigger asChild> */}
+ <TableRow>
+ {row.getVisibleCells().map((cell) => (
+ <TableCell key={cell.id}>
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext(),
+ )}
+ </TableCell>
+ ))}
+ </TableRow>
+ {/* </CollapsibleTrigger> */}
+ {/* <CollapsibleContent asChild>
+ <TableRow className="hover:bg-transparent">
+ <TableCell colSpan={columns.length}>
+ <div className="pb-0.5 pl-0.5 md:pb-1 md:pl-1">
+ <div className="flex items-center gap-x-1 px-1">
+ <FileDigitIcon className="size-4" /> Document
+ Version {row.original.versionNumber}
+ </div>
+ </div>
+ <VisitorChart
+ documentId={row.original.documentId!}
+ viewId={row.original.id}
+ totalPages={row.original.versionNumPages}
+ versionNumber={row.original.versionNumber}
+ />
+ <VisitorClicks
+ teamId={row.original.teamId!}
+ documentId={row.original.documentId!}
+ viewId={row.original.id}
+ />
+ </TableCell>
+ </TableRow>
+ </CollapsibleContent> */}
+ </>
+ // </Collapsible>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell
+ colSpan={columns.length}
+ className="h-24 text-center"
+ >
+ <p>No visits in the last {interval}</p>
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ <DataTablePagination table={table} name="view" />
+ </div>
+ );
+}
diff --git a/components/analytics/visitors-table.tsx b/components/analytics/visitors-table.tsx
new file mode 100644
index 00000000..061382a7
--- /dev/null
+++ b/components/analytics/visitors-table.tsx
@@ -0,0 +1,320 @@
+import { useRouter } from "next/router";
+
+import { useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import {
+ ColumnDef,
+ SortingState,
+ flexRender,
+ getCoreRowModel,
+ getPaginationRowModel,
+ getSortedRowModel,
+ useReactTable,
+} from "@tanstack/react-table";
+import {
+ BadgeCheckIcon,
+ ChevronDownIcon,
+ ChevronUpIcon,
+ ChevronsUpDownIcon,
+ Download,
+ UserIcon,
+} from "lucide-react";
+import { toast } from "sonner";
+import useSWR from "swr";
+
+import { Button } from "@/components/ui/button";
+import { Gauge } from "@/components/ui/gauge";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { BadgeTooltip } from "@/components/ui/tooltip";
+import { DataTablePagination } from "@/components/visitors/data-table-pagination";
+import { VisitorAvatar } from "@/components/visitors/visitor-avatar";
+
+import { durationFormat, fetcher, timeAgo } from "@/lib/utils";
+import { downloadCSV } from "@/lib/utils/csv";
+
+interface Visitor {
+ email: string;
+ viewerId: string | null;
+ totalViews: number;
+ lastActive: Date;
+ uniqueDocuments: number;
+ verified: boolean;
+ totalDuration: number;
+}
+
+const columns: ColumnDef<Visitor>[] = [
+ {
+ accessorKey: "email",
+ header: "Visitor",
+ cell: ({ row }) => (
+ <div className="flex items-center overflow-visible sm:space-x-3">
+ <VisitorAvatar viewerEmail={row.original.email} />
+ <div className="min-w-0 flex-1">
+ <div className="focus:outline-none">
+ <p className="flex items-center gap-x-2 overflow-visible text-sm font-medium text-gray-800 dark:text-gray-200">
+ {row.original.email}{" "}
+ {row.original.verified && (
+ <BadgeTooltip content="Verified visitor">
+ <BadgeCheckIcon className="h-4 w-4 text-emerald-500 hover:text-emerald-600" />
+ </BadgeTooltip>
+ )}
+ </p>
+ <p className="text-sm text-muted-foreground">
+ {row.original.uniqueDocuments} document
+ {row.original.uniqueDocuments !== 1 ? "s" : ""} viewed
+ </p>
+ </div>
+ </div>
+ </div>
+ ),
+ },
+ {
+ accessorKey: "totalViews",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className={
+ column.getIsSorted()
+ ? "text-nowrap font-medium"
+ : "text-nowrap font-normal"
+ }
+ >
+ Total Views
+ {column.getIsSorted() === "asc" ? (
+ <ChevronUpIcon className="ml-2 h-4 w-4" />
+ ) : column.getIsSorted() === "desc" ? (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ ) : (
+ <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ );
+ },
+ cell: ({ row }) => (
+ <div className="text-sm text-muted-foreground">
+ {row.original.totalViews}
+ </div>
+ ),
+ },
+ {
+ accessorKey: "totalDuration",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className={
+ column.getIsSorted()
+ ? "text-nowrap font-medium"
+ : "text-nowrap font-normal"
+ }
+ >
+ Total Time Spent
+ {column.getIsSorted() === "asc" ? (
+ <ChevronUpIcon className="ml-2 h-4 w-4" />
+ ) : column.getIsSorted() === "desc" ? (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ ) : (
+ <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ );
+ },
+ cell: ({ row }) => (
+ <div className="text-sm text-muted-foreground">
+ {durationFormat(row.original.totalDuration)}
+ </div>
+ ),
+ },
+ // {
+ // accessorKey: "avgCompletionRate",
+ // header: ({ column }) => {
+ // return (
+ // <Button
+ // variant="ghost"
+ // onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ // className={
+ // column.getIsSorted()
+ // ? "text-nowrap font-medium"
+ // : "text-nowrap font-normal"
+ // }
+ // >
+ // Avg. Completion
+ // {column.getIsSorted() === "asc" ? (
+ // <ChevronUpIcon className="ml-2 h-4 w-4" />
+ // ) : column.getIsSorted() === "desc" ? (
+ // <ChevronDownIcon className="ml-2 h-4 w-4" />
+ // ) : (
+ // <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
+ // )}
+ // </Button>
+ // );
+ // },
+ // cell: ({ row }) => (
+ // <div className="flex justify-start text-sm text-muted-foreground">
+ // <Gauge
+ // value={row.original.avgCompletionRate}
+ // size="small"
+ // showValue={true}
+ // />
+ // </div>
+ // ),
+ // },
+ {
+ accessorKey: "lastActive",
+ header: ({ column }) => {
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
+ className={
+ column.getIsSorted()
+ ? "text-nowrap font-medium"
+ : "text-nowrap font-normal"
+ }
+ >
+ Last Active
+ {column.getIsSorted() === "asc" ? (
+ <ChevronUpIcon className="ml-2 h-4 w-4" />
+ ) : column.getIsSorted() === "desc" ? (
+ <ChevronDownIcon className="ml-2 h-4 w-4" />
+ ) : (
+ <ChevronsUpDownIcon className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ );
+ },
+ cell: ({ row }) => (
+ <div className="text-sm text-muted-foreground">
+ {timeAgo(row.original.lastActive)}
+ </div>
+ ),
+ },
+];
+
+export default function VisitorsTable() {
+ const router = useRouter();
+ const teamInfo = useTeam();
+ const { interval = "7d" } = router.query;
+ const [sorting, setSorting] = useState<SortingState>([
+ { id: "lastActive", desc: true },
+ ]);
+
+ const { data: visitors } = useSWR<Visitor[]>(
+ teamInfo?.currentTeam?.id
+ ? `/api/analytics?type=visitors&interval=${interval}&teamId=${teamInfo.currentTeam.id}`
+ : null,
+ fetcher,
+ {
+ keepPreviousData: true,
+ revalidateOnFocus: false,
+ },
+ );
+
+ const table = useReactTable({
+ data: visitors || [],
+ columns,
+ getCoreRowModel: getCoreRowModel(),
+ getPaginationRowModel: getPaginationRowModel(),
+ onSortingChange: setSorting,
+ getSortedRowModel: getSortedRowModel(),
+ state: {
+ sorting,
+ },
+ });
+
+ const handleExport = () => {
+ if (!visitors?.length) {
+ toast.error("No data to export");
+ return;
+ }
+
+ const exportData = visitors.map((visitor) => ({
+ Email: visitor.email,
+ "Total Views": visitor.totalViews,
+ "Unique Documents": visitor.uniqueDocuments,
+ "Total Duration": durationFormat(visitor.totalDuration),
+ "Last Active": new Date(visitor.lastActive).toISOString(),
+ Verified: visitor.verified ? "Yes" : "No",
+ }));
+
+ downloadCSV(exportData, "visitors");
+ };
+
+ return (
+ <div className="space-y-4">
+ <div className="flex justify-end">
+ <Button variant="outline" size="sm" onClick={handleExport}>
+ <Download className="!size-4" />
+ Export
+ </Button>
+ </div>
+ <div className="rounded-xl border">
+ <Table>
+ <TableHeader>
+ {table.getHeaderGroups().map((headerGroup) => (
+ <TableRow key={headerGroup.id}>
+ {headerGroup.headers.map((header) => (
+ <TableHead key={header.id} className="px-0 first:px-4">
+ {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"}
+ >
+ {row.getVisibleCells().map((cell) => (
+ <TableCell key={cell.id}>
+ {flexRender(
+ cell.column.columnDef.cell,
+ cell.getContext(),
+ )}
+ </TableCell>
+ ))}
+ </TableRow>
+ ))
+ ) : (
+ <TableRow>
+ <TableCell
+ colSpan={columns.length}
+ className="h-24 text-center"
+ >
+ <div className="flex w-full flex-col items-center justify-center gap-4 rounded-xl py-4">
+ <div className="hidden rounded-full sm:block">
+ <div className="rounded-full border border-white bg-gradient-to-t from-gray-100 p-1 md:p-3">
+ <UserIcon className="size-6" />
+ </div>
+ </div>
+ <p>No visitors in the last {interval}</p>
+ </div>
+ </TableCell>
+ </TableRow>
+ )}
+ </TableBody>
+ </Table>
+ </div>
+ <DataTablePagination table={table} name="visitor" />
+ </div>
+ );
+}
diff --git a/components/layouts/breadcrumb.tsx b/components/layouts/breadcrumb.tsx
index 8433b48c..871bd74b 100644
--- a/components/layouts/breadcrumb.tsx
+++ b/components/layouts/breadcrumb.tsx
@@ -314,6 +314,42 @@ const SingleVisitorBreadcrumb = () => {
);
};
+const AnalyticsBreadcrumb = () => {
+ const router = useRouter();
+ const { type = "links" } = router.query;
+
+ const title = useMemo(() => {
+ switch (type) {
+ case "links":
+ return "Links";
+ case "documents":
+ return "Documents";
+ case "visitors":
+ return "Visitors";
+ case "views":
+ return "Recent Visits";
+ default:
+ return "Analytics";
+ }
+ }, [type]);
+
+ return (
+ <Breadcrumb>
+ <BreadcrumbList>
+ <BreadcrumbItem>
+ <BreadcrumbLink asChild>
+ <Link href="/dashboard?interval=7d&type=links">Dashboard</Link>
+ </BreadcrumbLink>
+ </BreadcrumbItem>
+ <BreadcrumbSeparator />
+ <BreadcrumbItem>
+ <BreadcrumbPage>{title}</BreadcrumbPage>
+ </BreadcrumbItem>
+ </BreadcrumbList>
+ </Breadcrumb>
+ );
+};
+
export const AppBreadcrumb = () => {
const router = useRouter();
const path = router.pathname;
@@ -322,6 +358,11 @@ export const AppBreadcrumb = () => {
};
const breadcrumb = useMemo(() => {
+ // Analytics routes
+ if (path === "/dashboard") {
+ return <AnalyticsBreadcrumb />;
+ }
+
// Settings routes
if (path.startsWith("/settings")) {
return <SettingsBreadcrumb />;
diff --git a/components/sidebar/app-sidebar.tsx b/components/sidebar/app-sidebar.tsx
index aaf118bf..1bb525d1 100644
--- a/components/sidebar/app-sidebar.tsx
+++ b/components/sidebar/app-sidebar.tsx
@@ -10,9 +10,12 @@ import { TeamContextType, initialState, useTeam } from "@/context/team-context";
import Cookies from "js-cookie";
import {
BrushIcon,
+ ChartNoAxesColumn,
+ ChartNoAxesColumnIcon,
CogIcon,
ContactIcon,
FolderIcon,
+ HouseIcon,
Loader,
ServerIcon,
} from "lucide-react";
@@ -56,6 +59,12 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
const data = {
navMain: [
+ {
+ title: "Dashboard",
+ url: "/dashboard",
+ icon: HouseIcon,
+ current: router.pathname.includes("dashboard"),
+ },
{
title: "All Documents",
url: "/documents",
diff --git a/components/tab-menu.tsx b/components/tab-menu.tsx
new file mode 100644
index 00000000..eb4fb25c
--- /dev/null
+++ b/components/tab-menu.tsx
@@ -0,0 +1,103 @@
+import Link from "next/link";
+
+import * as React from "react";
+
+import { Badge } from "@/components/ui/badge";
+import { Separator } from "@/components/ui/separator";
+
+import { cn } from "@/lib/utils";
+
+type Props = {
+ navigation: {
+ label: string;
+ href: string;
+ value: string;
+ currentValue: string;
+ count?: number;
+ tag?: string;
+ disabled?: boolean;
+ }[];
+ className?: string;
+};
+
+export const TabMenu: React.FC<React.PropsWithChildren<Props>> = ({
+ navigation,
+ className,
+}) => {
+ return (
+ <nav
+ className={cn("sticky top-0 bg-background dark:bg-gray-950", className)}
+ >
+ <div className="flex w-full items-center overflow-x-auto pl-1">
+ <ul className="flex flex-row gap-4">
+ {navigation.map(
+ ({ label, href, value, currentValue, count, tag, disabled }) => (
+ <TabItem
+ key={label}
+ label={label}
+ href={href}
+ value={value}
+ currentValue={currentValue}
+ count={count}
+ tag={tag}
+ disabled={disabled}
+ />
+ ),
+ )}
+ </ul>
+ </div>
+ <Separator />
+ </nav>
+ );
+};
+
+const TabItem: React.FC<Props["navigation"][0]> = ({
+ label,
+ href,
+ value,
+ currentValue,
+ count,
+ tag,
+ disabled,
+}) => {
+ const active = value === currentValue;
+
+ return (
+ <li
+ className={cn(
+ "flex shrink-0 list-none border-b-2 border-transparent p-2",
+ {
+ "border-primary": active,
+ hidden: disabled,
+ },
+ )}
+ >
+ <Link
+ href={href}
+ className={cn(
+ "-mx-3 flex items-center gap-2 rounded-lg px-3 py-2 text-sm hover:bg-muted hover:text-primary",
+ {
+ "font-medium": active,
+ },
+ )}
+ >
+ {label}
+ {count !== undefined && (
+ <Badge
+ variant="secondary"
+ className={cn("ml-auto", {
+ "bg-primary/10 hover:bg-primary/20": active,
+ })}
+ >
+ {count}
+ </Badge>
+ )}
+ {tag ? (
+ <div className="rounded border bg-background px-1 py-0.5 font-mono text-xs">
+ {tag}
+ </div>
+ ) : null}
+ </Link>
+ </li>
+ );
+};
diff --git a/components/ui/bar-list.tsx b/components/ui/bar-list.tsx
new file mode 100644
index 00000000..fd2a3f05
--- /dev/null
+++ b/components/ui/bar-list.tsx
@@ -0,0 +1,102 @@
+import { ReactNode } from "react";
+
+import { motion } from "framer-motion";
+
+import { cn } from "@/lib/utils";
+
+interface BarListProps {
+ data: {
+ icon: ReactNode;
+ title: string;
+ subtitle?: string;
+ value: number;
+ secondaryValue?: string;
+ }[];
+ maxValue: number;
+ barBackground?: string;
+ hoverBackground?: string;
+}
+
+export default function BarList({
+ data,
+ maxValue,
+ barBackground = "bg-indigo-100 dark:bg-indigo-950/50",
+ hoverBackground = "hover:bg-gray-100 dark:hover:bg-gray-800",
+}: BarListProps) {
+ return (
+ <div className="grid">
+ {data.map((item, idx) => (
+ <LineItem
+ key={idx}
+ {...item}
+ maxValue={maxValue}
+ barBackground={barBackground}
+ hoverBackground={hoverBackground}
+ />
+ ))}
+ </div>
+ );
+}
+
+function LineItem({
+ icon,
+ title,
+ subtitle,
+ value,
+ secondaryValue,
+ maxValue,
+ barBackground,
+ hoverBackground,
+}: {
+ icon: ReactNode;
+ title: string;
+ subtitle?: string;
+ value: number;
+ secondaryValue?: string;
+ maxValue: number;
+ barBackground: string;
+ hoverBackground: string;
+}) {
+ return (
+ <div
+ className={cn(
+ "min-w-0 border-l-2 border-transparent px-4 py-1",
+ hoverBackground,
+ )}
+ >
+ <div className="group flex items-center justify-between">
+ <div className="relative z-10 flex h-8 w-full min-w-0 max-w-[calc(100%-2rem)] items-center">
+ <div className="z-10 flex items-center space-x-3 overflow-hidden px-3">
+ {icon}
+ <div className="truncate">
+ <div className="truncate text-sm text-foreground">{title}</div>
+ {subtitle && (
+ <div className="truncate text-xs text-muted-foreground">
+ {subtitle}
+ </div>
+ )}
+ </div>
+ </div>
+ <motion.div
+ style={{
+ width: `${(value / maxValue) * 100}%`,
+ }}
+ className={cn(
+ "absolute h-full origin-left rounded-md",
+ barBackground,
+ )}
+ transition={{ ease: "easeOut", duration: 0.3 }}
+ initial={{ transform: "scaleX(0)" }}
+ animate={{ transform: "scaleX(1)" }}
+ />
+ {secondaryValue && (
+ <div className="absolute right-2 z-20 text-sm text-muted-foreground">
+ {secondaryValue}
+ </div>
+ )}
+ </div>
+ <div className="w-8 text-right text-sm text-foreground">{value}</div>
+ </div>
+ </div>
+ );
+}
diff --git a/lib/tinybird/endpoints/get_total_link_duration.pipe b/lib/tinybird/endpoints/get_total_link_duration.pipe
new file mode 100644
index 00000000..472e4a69
--- /dev/null
+++ b/lib/tinybird/endpoints/get_total_link_duration.pipe
@@ -0,0 +1,12 @@
+VERSION 1
+
+NODE endpoint
+SQL >
+ %
+ SELECT SUM(duration) AS sum_duration, COUNT(distinct viewId) as view_count
+ FROM page_views__v3
+ WHERE
+ linkId = {{ String(linkId, required=true) }}
+ AND time >= {{ Int64(since, required=true) }}
+ AND documentId = {{ String(documentId, required=true) }}
+ AND viewId NOT IN splitByChar(',', {{ String(excludedViewIds, required=true) }})
diff --git a/lib/tinybird/endpoints/get_total_viewer_duration.pipe b/lib/tinybird/endpoints/get_total_viewer_duration.pipe
new file mode 100644
index 00000000..b7faacff
--- /dev/null
+++ b/lib/tinybird/endpoints/get_total_viewer_duration.pipe
@@ -0,0 +1,12 @@
+VERSION 1
+
+NODE endpoint
+SQL >
+ %
+ SELECT
+ SUM(duration) AS sum_duration
+ FROM
+ page_views__v3
+ WHERE
+ viewId IN splitByChar(',', {{ String(viewIds, required=true) }})
+ AND time >= {{ Int64(since, required=true) }}
diff --git a/lib/tinybird/pipes.ts b/lib/tinybird/pipes.ts
index 7ce63449..d459054d 100644
--- a/lib/tinybird/pipes.ts
+++ b/lib/tinybird/pipes.ts
@@ -47,6 +47,31 @@ export const getTotalDocumentDuration = tb.buildPipe({
}),
});
+export const getTotalLinkDuration = tb.buildPipe({
+ pipe: "get_total_link_duration__v1",
+ parameters: z.object({
+ linkId: z.string(),
+ documentId: z.string(),
+ excludedViewIds: z.string().describe("Comma separated viewIds"),
+ since: z.number(),
+ }),
+ data: z.object({
+ sum_duration: z.number(),
+ view_count: z.number(),
+ }),
+});
+
+export const getTotalViewerDuration = tb.buildPipe({
+ pipe: "get_total_viewer_duration__v1",
+ parameters: z.object({
+ viewIds: z.string().describe("Comma separated viewIds"),
+ since: z.number(),
+ }),
+ data: z.object({
+ sum_duration: z.number(),
+ }),
+});
+
export const getViewUserAgent = tb.buildPipe({
pipe: "get_useragent_per_view__v2",
parameters: z.object({
diff --git a/lib/utils/csv.ts b/lib/utils/csv.ts
new file mode 100644
index 00000000..4ea915a3
--- /dev/null
+++ b/lib/utils/csv.ts
@@ -0,0 +1,54 @@
+import { toast } from "sonner";
+
+export function downloadCSV(data: any[], filename: string) {
+ try {
+ if (data.length === 0) {
+ toast.error("No data to export");
+ return;
+ }
+
+ // Get headers from the first object
+ const headers = Object.keys(data[0]);
+
+ // Convert data to CSV format
+ const csvContent = [
+ // Headers row
+ headers.join(","),
+ // Data rows
+ ...data.map((row) =>
+ headers
+ .map((header) => {
+ const value = row[header];
+ // Handle special cases
+ if (value instanceof Date) {
+ return value.toISOString();
+ }
+ if (typeof value === "string" && value.includes(",")) {
+ return `"${value}"`;
+ }
+ return value;
+ })
+ .join(","),
+ ),
+ ].join("\n");
+
+ // Create blob and download
+ const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ const formattedTime = new Date().toISOString().replace(/[-:Z]/g, "");
+ link.setAttribute("download", `${filename}_${formattedTime}.csv`);
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+
+ toast.success("CSV file downloaded successfully");
+ } catch (error) {
+ console.error("Error:", error);
+ toast.error(
+ "An error occurred while downloading the CSV. Please try again.",
+ );
+ }
+}
diff --git a/pages/api/analytics/index.ts b/pages/api/analytics/index.ts
new file mode 100644
index 00000000..acda5c9d
--- /dev/null
+++ b/pages/api/analytics/index.ts
@@ -0,0 +1,477 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { getServerSession } from "next-auth";
+import { z } from "zod";
+
+import prisma from "@/lib/prisma";
+import {
+ getTotalDocumentDuration,
+ getTotalLinkDuration,
+ getTotalViewerDuration,
+ getViewPageDuration,
+} from "@/lib/tinybird/pipes";
+import { durationFormat } from "@/lib/utils";
+
+import { authOptions } from "../auth/[...nextauth]";
+
+const analyticsQuerySchema = z.object({
+ interval: z.enum(["24h", "7d", "30d"]),
+ type: z.enum(["overview", "links", "documents", "visitors", "views"]),
+ teamId: z.string(),
+});
+
+const INTERVALS = {
+ "24h": 24 * 60 * 60 * 1000, // 24 hours in ms
+ "7d": 7 * 24 * 60 * 60 * 1000, // 7 days in ms
+ "30d": 30 * 24 * 60 * 60 * 1000, // 30 days in ms
+} as const;
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "GET") {
+ return res.status(405).json({ error: "Method not allowed" });
+ }
+
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).json({ error: "Unauthorized" });
+ }
+
+ try {
+ const result = analyticsQuerySchema.safeParse(req.query);
+
+ if (!result.success) {
+ return res
+ .status(400)
+ .json({ error: `Invalid body: ${result.error.message}` });
+ }
+
+ const { interval, type, teamId } = result.data;
+
+ const intervalFilter = {
+ gte: new Date(Date.now() - INTERVALS[interval]),
+ };
+
+ console.log(
+ "greater than or equal to",
+ new Date(Date.now() - INTERVALS[interval]),
+ );
+
+ switch (type) {
+ case "overview": {
+ const [viewStats, graphData] = await Promise.all([
+ // Get view stats with relational counts
+ prisma.view.findMany({
+ where: {
+ teamId,
+ viewedAt: intervalFilter,
+ isArchived: false,
+ },
+ select: {
+ id: true,
+ viewerEmail: true,
+ linkId: true,
+ documentId: true,
+ viewerId: true,
+ },
+ }),
+ // Get views data for graph grouped by day
+ interval === "24h"
+ ? prisma.$queryRaw`
+ SELECT
+ DATE_TRUNC('hour', "viewedAt") as date,
+ COUNT(*) as views
+ FROM "View"
+ WHERE
+ "teamId" = ${teamId}
+ AND "viewedAt" >= ${new Date(Date.now() - INTERVALS[interval])}
+ AND "isArchived" = false
+ GROUP BY DATE_TRUNC('hour', "viewedAt")
+ ORDER BY date ASC
+ `
+ : prisma.$queryRaw`
+ SELECT
+ DATE_TRUNC('day', "viewedAt") as date,
+ COUNT(*) as views
+ FROM "View"
+ WHERE
+ "teamId" = ${teamId}
+ AND "viewedAt" >= ${new Date(Date.now() - INTERVALS[interval])}
+ AND "isArchived" = false
+ GROUP BY DATE_TRUNC('day', "viewedAt")
+ ORDER BY date ASC
+ `,
+ ]);
+
+ // Calculate counts from viewStats
+ const uniqueLinks = new Set(viewStats.map((view) => view.linkId));
+ const uniqueDocuments = new Set(
+ viewStats.map((view) => view.documentId),
+ );
+ const uniqueVisitors = new Set(viewStats.map((view) => view.viewerId));
+
+ return res.status(200).json({
+ counts: {
+ links: uniqueLinks.size,
+ documents: uniqueDocuments.size,
+ visitors: uniqueVisitors.size,
+ views: viewStats.length,
+ },
+ graph: (graphData as { date: Date; views: bigint }[]).map(
+ (point) => ({
+ date: point.date,
+ views: Number(point.views),
+ }),
+ ),
+ });
+ }
+
+ case "links": {
+ const links = await prisma.link.findMany({
+ where: {
+ teamId,
+ isArchived: false,
+ views: {
+ some: {
+ viewedAt: intervalFilter,
+ },
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ slug: true,
+ domainSlug: true,
+ domainId: true,
+ documentId: true,
+ _count: {
+ select: {
+ views: {
+ where: {
+ viewedAt: intervalFilter,
+ },
+ },
+ },
+ },
+ views: {
+ orderBy: {
+ viewedAt: "desc",
+ },
+ take: 1,
+ select: {
+ viewedAt: true,
+ },
+ },
+ document: {
+ select: {
+ name: true,
+ versions: {
+ orderBy: {
+ createdAt: "desc",
+ },
+ take: 1,
+ select: {
+ numPages: true,
+ },
+ },
+ },
+ },
+ dataroom: {
+ select: {
+ name: true,
+ },
+ },
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ });
+
+ // Transform the data to match the table requirements
+ const transformedLinks = await Promise.all(
+ links.map(async (link) => {
+ let avgDuration = "0s";
+
+ if (link.documentId) {
+ try {
+ const since = Date.now() - INTERVALS[interval];
+ const durationData = await getTotalLinkDuration({
+ linkId: link.id,
+ documentId: link.documentId,
+ excludedViewIds: "", // Include all views
+ since,
+ });
+
+ if (durationData.data && durationData.data[0]) {
+ const totalDuration = durationData.data[0].sum_duration;
+ const viewCount = durationData.data[0].view_count;
+ const avgDurationMs = totalDuration / viewCount;
+ avgDuration = durationFormat(avgDurationMs);
+ }
+ } catch (error) {
+ console.error("Error fetching Tinybird data:", error);
+ }
+ }
+
+ return {
+ id: link.id,
+ name: link.name || `Link #${link.id.slice(-5)}`,
+ url: link.domainId
+ ? `https://${link.domainSlug}/${link.slug}`
+ : `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${link.id}`,
+ documentName:
+ link.document?.name || link.dataroom?.name || "Unknown",
+ documentId: link.documentId,
+ views: link._count.views,
+ avgDuration,
+ lastViewed: link.views[0]?.viewedAt || null,
+ };
+ }),
+ );
+
+ return res.status(200).json(transformedLinks);
+ }
+
+ case "documents": {
+ const documents = await prisma.document.findMany({
+ where: {
+ teamId,
+ views: {
+ some: {
+ viewedAt: intervalFilter,
+ },
+ },
+ },
+ select: {
+ id: true,
+ name: true,
+ _count: {
+ select: {
+ views: {
+ where: {
+ viewedAt: intervalFilter,
+ },
+ },
+ },
+ },
+ views: {
+ orderBy: {
+ viewedAt: "desc",
+ },
+ take: 1,
+ select: {
+ viewedAt: true,
+ },
+ },
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ });
+
+ // Transform the data to match the table requirements
+ const transformedDocuments = await Promise.all(
+ documents.map(async (doc) => {
+ let avgDuration = "0s";
+
+ try {
+ const since = Date.now() - INTERVALS[interval];
+ const durationData = await getTotalDocumentDuration({
+ documentId: doc.id,
+ excludedLinkIds: "", // Include all links
+ excludedViewIds: "", // Include all views
+ since,
+ });
+
+ if (durationData.data && durationData.data[0]) {
+ const totalDuration = durationData.data[0].sum_duration;
+ const avgDurationMs = totalDuration / doc._count.views;
+ avgDuration = durationFormat(avgDurationMs);
+ }
+ } catch (error) {
+ console.error("Error fetching Tinybird data:", error);
+ }
+
+ return {
+ id: doc.id,
+ name: doc.name,
+ views: doc._count.views,
+ avgDuration,
+ lastViewed: doc.views[0]?.viewedAt || null,
+ };
+ }),
+ );
+
+ return res.status(200).json(transformedDocuments);
+ }
+
+ case "visitors": {
+ const viewers = await prisma.viewer.findMany({
+ where: {
+ teamId,
+ views: {
+ some: {
+ viewedAt: intervalFilter,
+ isArchived: false,
+ viewType: "DOCUMENT_VIEW",
+ },
+ },
+ },
+ include: {
+ views: {
+ orderBy: {
+ viewedAt: "desc",
+ },
+ where: {
+ viewType: "DOCUMENT_VIEW",
+ viewedAt: intervalFilter,
+ isArchived: false,
+ },
+ },
+ },
+ });
+
+ // Transform the data to match the table requirements
+ const transformedVisitors = await Promise.all(
+ viewers.map(async (viewer) => {
+ // Get unique documents viewed
+ const uniqueDocuments = new Set(
+ viewer.views.map((view) => view.documentId),
+ );
+
+ let totalDuration = 0;
+
+ try {
+ const since = Date.now() - INTERVALS[interval];
+ const viewIds = viewer.views.map((view) => view.id).join(",");
+ const durationData = await getTotalViewerDuration({
+ viewIds,
+ since,
+ });
+
+ if (durationData.data && durationData.data[0]) {
+ totalDuration = durationData.data[0].sum_duration;
+ }
+ } catch (error) {
+ console.error("Error fetching Tinybird data:", error);
+ }
+
+ return {
+ email: viewer.email,
+ viewerId: viewer.id,
+ totalViews: viewer.views.length,
+ lastActive: viewer.views[0]?.viewedAt || new Date(),
+ uniqueDocuments: uniqueDocuments.size,
+ verified: viewer.verified,
+ totalDuration,
+ };
+ }),
+ );
+
+ return res.status(200).json(transformedVisitors);
+ }
+
+ case "views": {
+ const views = await prisma.view.findMany({
+ where: {
+ teamId,
+ viewedAt: intervalFilter,
+ isArchived: false,
+ viewType: "DOCUMENT_VIEW",
+ },
+ include: {
+ document: {
+ select: {
+ id: true,
+ name: true,
+ versions: {
+ orderBy: {
+ createdAt: "desc",
+ },
+ take: 1,
+ select: {
+ createdAt: true,
+ numPages: true,
+ },
+ },
+ },
+ },
+ link: {
+ select: {
+ id: true,
+ name: true,
+ },
+ },
+ },
+ orderBy: {
+ viewedAt: "desc",
+ },
+ });
+
+ // Transform the data to match the table requirements
+ const transformedViews = await Promise.all(
+ views.map(async (view) => {
+ let totalDuration = 0;
+ let completionRate = 0;
+
+ if (view.document?.id) {
+ try {
+ const since = Date.now() - INTERVALS[interval];
+ const pageData = await getViewPageDuration({
+ documentId: view.document.id,
+ viewId: view.id,
+ since,
+ });
+
+ if (pageData.data && pageData.data.length > 0) {
+ // Calculate total duration from all pages
+ totalDuration = pageData.data.reduce(
+ (sum, page) => sum + page.sum_duration,
+ 0,
+ );
+
+ // Calculate completion rate based on pages with any duration
+ const numPages = view.document.versions[0]?.numPages || 0;
+ completionRate = numPages
+ ? (pageData.data.length / numPages) * 100
+ : 0;
+ }
+ } catch (error) {
+ console.error("Error fetching Tinybird data:", error);
+ }
+ }
+
+ return {
+ id: view.id,
+ viewerEmail: view.viewerEmail,
+ documentName:
+ view.document?.name ||
+ `Document #${view.document?.id.slice(-5)}`,
+ linkName: view.link?.name || `Link #${view.link?.id.slice(-5)}`,
+ viewedAt: view.viewedAt,
+ totalDuration,
+ completionRate: Math.round(completionRate),
+ verified: view.verified || false,
+ documentId: view.document?.id,
+ teamId,
+ };
+ }),
+ );
+
+ return res.status(200).json(transformedViews);
+ }
+
+ default: {
+ return res.status(400).json({ error: "Invalid type" });
+ }
+ }
+ } catch (error) {
+ console.error(error);
+ if (error instanceof z.ZodError) {
+ return res.status(400).json({ error: error.issues });
+ }
+ return res.status(500).json({ error: "Internal server error" });
+ }
+}
diff --git a/pages/dashboard.tsx b/pages/dashboard.tsx
new file mode 100644
index 00000000..d2205465
--- /dev/null
+++ b/pages/dashboard.tsx
@@ -0,0 +1,124 @@
+import { useRouter } from "next/router";
+
+import { useEffect } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { BarChart3, Eye, FileText, Link, Users } from "lucide-react";
+import useSWR from "swr";
+
+import { AnalyticsCard } from "@/components/analytics/analytics-card";
+import DashboardViewsChart from "@/components/analytics/dashboard-views-chart";
+import DocumentsTable from "@/components/analytics/documents-table";
+import LinksTable from "@/components/analytics/links-table";
+import {
+ TimeRange,
+ TimeRangeSelect,
+} from "@/components/analytics/time-range-select";
+import ViewsTable from "@/components/analytics/views-table";
+import VisitorsTable from "@/components/analytics/visitors-table";
+import AppLayout from "@/components/layouts/app";
+import { TabMenu } from "@/components/tab-menu";
+
+import { fetcher } from "@/lib/utils";
+
+interface OverviewData {
+ counts: {
+ links: number;
+ documents: number;
+ visitors: number;
+ views: number;
+ };
+ graph: {
+ date: string;
+ views: number;
+ }[];
+}
+
+export default function DashboardPage() {
+ const router = useRouter();
+ const teamInfo = useTeam();
+ const { interval = "7d", type = "links" } = router.query as {
+ interval: TimeRange;
+ type: string;
+ };
+
+ // Fetch overview data
+ const { data: overview, isLoading } = useSWR<OverviewData>(
+ teamInfo?.currentTeam?.id
+ ? `/api/analytics?type=overview&interval=${interval}&teamId=${teamInfo.currentTeam.id}`
+ : null,
+ fetcher,
+ {
+ keepPreviousData: true,
+ revalidateOnFocus: false,
+ },
+ );
+
+ // Update the URL when time range changes
+ const handleTimeRangeChange = (newTimeRange: TimeRange) => {
+ const params = new URLSearchParams(window.location.search);
+ params.set("interval", newTimeRange);
+ router.push(`/dashboard?${params.toString()}`);
+ };
+
+ return (
+ <AppLayout>
+ <div className="flex-1 space-y-4 p-4 pt-6 md:p-8">
+ <div className="flex items-center justify-between">
+ <h2 className="text-3xl font-bold tracking-tight">Dashboard</h2>
+ <TimeRangeSelect value={interval} onChange={handleTimeRangeChange} />
+ </div>
+
+ <div className="space-y-4">
+ <AnalyticsCard
+ title="Views Overview"
+ icon={<BarChart3 className="h-4 w-4" />}
+ contentClassName="space-y-4"
+ >
+ <DashboardViewsChart timeRange={interval} data={overview?.graph} />
+ </AnalyticsCard>
+
+ <TabMenu
+ navigation={[
+ {
+ label: "Links",
+ href: `/dashboard?interval=${interval}&type=links`,
+ value: "links",
+ currentValue: type,
+ count: overview?.counts.links,
+ },
+ {
+ label: "Documents",
+ href: `/dashboard?interval=${interval}&type=documents`,
+ value: "documents",
+ currentValue: type,
+ count: overview?.counts.documents,
+ },
+ {
+ label: "Visitors",
+ href: `/dashboard?interval=${interval}&type=visitors`,
+ value: "visitors",
+ currentValue: type,
+ count: overview?.counts.visitors,
+ },
+ {
+ label: "Recent Visits",
+ href: `/dashboard?interval=${interval}&type=views`,
+ value: "views",
+ currentValue: type,
+ count: overview?.counts.views,
+ },
+ ]}
+ />
+
+ <div className="grid grid-cols-1">
+ {type === "links" && <LinksTable />}
+ {type === "documents" && <DocumentsTable />}
+ {type === "visitors" && <VisitorsTable />}
+ {type === "views" && <ViewsTable />}
+ </div>
+ </div>
+ </div>
+ </AppLayout>
+ );
+}