Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add visitors overview and details
Marc Seitz832b432e234b
diff --git a/components/Sidebar.tsx b/components/Sidebar.tsxindex 59fe20a2..963179ee 100644--- a/components/Sidebar.tsx+++ b/components/Sidebar.tsx@@ -1,3 +1,4 @@+import Link from "next/link";import { useRouter } from "next/router";import { useEffect, useState } from "react";@@ -6,6 +7,7 @@ import { TeamContextType, initialState, useTeam } from "@/context/team-context";import Cookies from "js-cookie";import {CogIcon,+ ContactIcon,FolderIcon as FolderLucideIcon,FolderOpenIcon,PaletteIcon,@@ -29,7 +31,6 @@ import { AddTeamModal } from "./teams/add-team-modal";import SelectTeam from "./teams/select-team";import { Progress } from "./ui/progress";import { ScrollArea } from "./ui/scroll-area";-import Link from "next/link";export default function Sidebar() {return (@@ -123,6 +124,14 @@ export const SidebarComponent = ({ className }: { className?: string }) => {? false: true,},+ {+ name: "Visitors",+ href: "/visitors",+ icon: ContactIcon,+ current: router.pathname.includes("visitors"),+ active: false,+ disabled: userPlan === "free" ? true : false,+ },{name: "Branding",href: "/settings/branding",@@ -157,7 +166,7 @@ export const SidebarComponent = ({ className }: { className?: string }) => {<div className="flex h-16 shrink-0 items-center space-x-3"><p className="flex items-center text-2xl font-bold tracking-tighter text-black dark:text-white">- <Link href="/documents">Papermark{" "}</Link>+ <Link href="/documents">Papermark </Link>{userPlan && userPlan != "free" ? (<span className="ml-4 rounded-full bg-background px-2.5 py-1 text-xs tracking-normal text-foreground ring-1 ring-gray-800">{userPlan.charAt(0).toUpperCase() + userPlan.slice(1)}diff --git a/components/visitors/contacts-document-table.tsx b/components/visitors/contacts-document-table.tsxnew file mode 100644index 00000000..4773d32f--- /dev/null+++ b/components/visitors/contacts-document-table.tsx@@ -0,0 +1,363 @@+"use client";++import { useRouter } from "next/router";++import { useMemo, useState } from "react";+import React from "react";++import {+ ColumnDef,+ ExpandedState,+ SortingState,+ flexRender,+ getCoreRowModel,+ getExpandedRowModel,+ getPaginationRowModel,+ getSortedRowModel,+ useReactTable,+} from "@tanstack/react-table";+import {+ ChevronDownIcon,+ ChevronUpIcon,+ ChevronsUpDownIcon,+} from "lucide-react";++import { Button } from "@/components/ui/button";+import { Skeleton } from "@/components/ui/skeleton";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";++import { durationFormat, timeAgo } from "@/lib/utils";+import { fileIcon } from "@/lib/utils/get-file-icon";++import { DataTablePagination } from "./data-table-pagination";++type DocumentView = {+ documentId: string;+ document: {+ name: string;+ type: string;+ };+ lastViewed: Date;+ totalDuration: number;+ viewCount: number;+};++const columns: ColumnDef<DocumentView>[] = [+ {+ accessorKey: "document",+ header: "Document Name",+ cell: ({ row }) => {+ const view = row.original;+ return (+ <div className="flex items-center overflow-visible sm:space-x-3">+ {fileIcon({+ fileType: view.document.type ?? "",+ className: "h-7 w-7",+ isLight: true,+ })}+ <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">+ {view.document.name}+ </p>+ </div>+ </div>+ </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 }) => {+ const view = row.original;+ return (+ <time dateTime={new Date(view.lastViewed).toISOString()}>+ {timeAgo(view.lastViewed)}+ </time>+ );+ },+ sortingFn: (rowA, rowB) => {+ return (+ new Date(rowB.original.lastViewed).getTime() -+ new Date(rowA.original.lastViewed).getTime()+ );+ },+ },+ {+ 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"+ }+ >+ 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 }) => {+ const view = row.original;+ return (+ <div className="text-sm text-muted-foreground">+ {durationFormat(view.totalDuration)}+ </div>+ );+ },+ },+ {+ accessorKey: "viewCount",+ header: ({ column }) => {+ return (+ <Button+ variant="ghost"+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}+ className={+ column.getIsSorted()+ ? "text-nowrap font-medium"+ : "text-nowrap font-normal"+ }+ >+ Visits+ {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 }) => {+ const view = row.original;+ return (+ <div className="text-sm text-muted-foreground">{view.viewCount}</div>+ );+ },+ },+ // INFO: disable for now until we have more details+ // {+ // id: "expander",+ // header: () => null,+ // cell: ({ row }) => {+ // return (+ // <Button+ // variant="ghost"+ // onClick={() => {+ // row.toggleExpanded();+ // }}+ // className="p-0"+ // >+ // {row.getIsExpanded() ? (+ // <ChevronUpIcon className="h-4 w-4" />+ // ) : (+ // <ChevronDownIcon className="h-4 w-4" />+ // )}+ // </Button>+ // );+ // },+ // },+];++export function ContactsDocumentsTable({+ views,+}: {+ views: DocumentView[] | null | undefined;+}) {+ const router = useRouter();+ const [sorting, setSorting] = useState<SortingState>([+ { id: "lastViewed", desc: false },+ ]);+ const [expanded, setExpanded] = useState<ExpandedState>({});++ const data = useMemo(() => views || [], [views]);++ const table = useReactTable({+ data,+ columns,+ getCoreRowModel: getCoreRowModel(),+ getSortedRowModel: getSortedRowModel(),+ getPaginationRowModel: getPaginationRowModel(),+ getExpandedRowModel: getExpandedRowModel(),+ onSortingChange: (updater) => {+ setSorting((old) => {+ const newSorting =+ typeof updater === "function" ? updater(old) : updater;+ if (newSorting.length > 0) {+ const [{ id, desc }] = newSorting;+ const prevSorting = old.find((s) => s.id === id);+ if (prevSorting) {+ if (prevSorting.desc && !desc) {+ // If it was descending and now ascending, reset+ return [];+ }+ }+ }+ return newSorting;+ });+ },+ onExpandedChange: setExpanded,+ state: {+ sorting,+ expanded,+ },+ });++ if (!views) {+ return (+ <div className="rounded-md border">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Document Name</TableHead>+ <TableHead>Last Viewed</TableHead>+ <TableHead>Time Spent</TableHead>+ <TableHead>Visits</TableHead>+ <TableHead></TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {[...Array(5)].map((_, index) => (+ <TableRow key={index}>+ <TableCell>+ <div className="flex items-center space-x-3">+ <Skeleton className="h-7 w-7" />+ <Skeleton className="h-4 w-[200px]" />+ </div>+ </TableCell>+ <TableCell>+ <Skeleton className="h-4 w-[100px]" />+ </TableCell>+ <TableCell>+ <Skeleton className="h-4 w-[80px]" />+ </TableCell>+ <TableCell>+ <Skeleton className="h-4 w-[50px]" />+ </TableCell>+ <TableCell>+ <Skeleton className="h-4 w-4" />+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ );+ }++ const handleRowClick = (id: string) => {+ router.push(`/documents/${id}`);+ };++ return (+ <div className="space-y-4">+ <div className="rounded-md 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) => (+ <React.Fragment key={row.id}>+ <TableRow+ key={row.id}+ onClick={() => handleRowClick(row.original.documentId)}+ className="cursor-pointer"+ >+ {row.getVisibleCells().map((cell) => (+ <TableCell key={cell.id}>+ {flexRender(+ cell.column.columnDef.cell,+ cell.getContext(),+ )}+ </TableCell>+ ))}+ </TableRow>+ {row.getIsExpanded() && (+ <TableRow>+ <TableCell colSpan={columns.length}>+ {/* Placeholder for expanded content */}+ <div className="p-4">+ <h4 className="mb-2 font-semibold">+ Additional Details+ </h4>+ <p>Chart placeholder</p>+ <p>Rows of all visits placeholder</p>+ </div>+ </TableCell>+ </TableRow>+ )}+ </React.Fragment>+ ))+ ) : (+ <TableRow>+ <TableCell+ colSpan={columns.length}+ className="h-24 text-center"+ >+ No results.+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </Table>+ </div>+ <DataTablePagination table={table} name="document" />+ </div>+ );+}diff --git a/components/visitors/contacts-table.tsx b/components/visitors/contacts-table.tsxnew file mode 100644index 00000000..cdd6da66--- /dev/null+++ b/components/visitors/contacts-table.tsx@@ -0,0 +1,284 @@+"use client";++import { useRouter } from "next/router";++import { useMemo, useState } from "react";+import React from "react";++import {+ ColumnDef,+ SortingState,+ flexRender,+ getCoreRowModel,+ getPaginationRowModel,+ getSortedRowModel,+ useReactTable,+} from "@tanstack/react-table";+import {+ ArrowUpDown,+ ChevronDownIcon,+ ChevronUpIcon,+ ChevronsUpDownIcon,+} from "lucide-react";++import { Button } from "@/components/ui/button";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";+import { VisitorAvatar } from "@/components/visitors/visitor-avatar";++import { timeAgo } from "@/lib/utils";++import { Skeleton } from "../ui/skeleton";+import { DataTablePagination } from "./data-table-pagination";++type Viewer = {+ id: string;+ email: string;+ views: { viewedAt: Date }[];+};++const columns: ColumnDef<Viewer>[] = [+ {+ accessorKey: "email",+ header: "Contact",+ 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}+ </p>+ </div>+ </div>+ </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 }) => {+ const lastView = row.original.views[0];+ return lastView ? (+ <time+ dateTime={new Date(lastView.viewedAt).toISOString()}+ className="text-sm text-muted-foreground"+ >+ {timeAgo(lastView.viewedAt)}+ </time>+ ) : (+ <div className="text-sm text-muted-foreground">-</div>+ );+ },+ sortingFn: (rowA, rowB) => {+ const dateA = rowA.original.views[0]?.viewedAt;+ const dateB = rowB.original.views[0]?.viewedAt;++ if (!dateA && !dateB) return 0;+ if (!dateA) return 1;+ if (!dateB) return -1;++ const timeA =+ dateA instanceof Date ? dateA.getTime() : new Date(dateA).getTime();+ const timeB =+ dateB instanceof Date ? dateB.getTime() : new Date(dateB).getTime();++ return timeB - timeA; // Sort in descending order (most recent first)+ },+ },+ {+ accessorKey: "totalVisits",+ header: ({ column }) => {+ return (+ <Button+ variant="ghost"+ onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}+ className={+ column.getIsSorted()+ ? "text-nowrap font-medium"+ : "text-nowrap font-normal"+ }+ >+ Total Visits+ {column.getIsSorted() === "asc" ? (+ <ChevronDownIcon className="ml-2 h-4 w-4" />+ ) : column.getIsSorted() === "desc" ? (+ <ChevronUpIcon 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.length}+ </div>+ ),+ sortingFn: (rowA, rowB) =>+ rowA.original.views.length - rowB.original.views.length,+ },+];++export function ContactsTable({+ viewers,+}: {+ viewers: Viewer[] | null | undefined;+}) {+ const router = useRouter();+ const [sorting, setSorting] = useState<SortingState>([+ { id: "lastViewed", desc: false },+ ]);++ const data = useMemo(() => viewers || [], [viewers]);++ const table = useReactTable({+ data,+ columns,+ getCoreRowModel: getCoreRowModel(),+ getSortedRowModel: getSortedRowModel(),+ getPaginationRowModel: getPaginationRowModel(),+ onSortingChange: (updater) => {+ setSorting((old) => {+ const newSorting =+ typeof updater === "function" ? updater(old) : updater;+ if (newSorting.length > 0) {+ const [{ id, desc }] = newSorting;+ const prevSorting = old.find((s) => s.id === id);+ if (prevSorting) {+ if (prevSorting.desc && !desc) {+ // If it was descending and now ascending, reset+ return [];+ }+ }+ }+ return newSorting;+ });+ },+ state: {+ sorting,+ },+ });++ if (!viewers) {+ return (+ <div className="rounded-md border">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Name</TableHead>+ <TableHead>Last Viewed</TableHead>+ <TableHead>Total Visits</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {[...Array(5)].map((_, index) => (+ <TableRow key={index}>+ <TableCell>+ <div className="flex items-center space-x-3">+ <Skeleton className="h-10 w-10 rounded-full" />+ <Skeleton className="h-4 w-[200px]" />+ </div>+ </TableCell>+ <TableCell>+ <Skeleton className="h-4 w-[100px]" />+ </TableCell>+ <TableCell>+ <Skeleton className="h-4 w-[50px]" />+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ );+ }++ const handleRowClick = (id: string) => {+ router.push(`/visitors/${id}`);+ };++ return (+ <div className="space-y-4">+ <div className="rounded-md 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}+ onClick={() => handleRowClick(row.original.id)}+ className="cursor-pointer"+ >+ {row.getVisibleCells().map((cell) => {+ return (+ <TableCell key={cell.id}>+ {flexRender(+ cell.column.columnDef.cell,+ cell.getContext(),+ )}+ </TableCell>+ );+ })}+ </TableRow>+ ))+ ) : (+ <TableRow>+ <TableCell+ colSpan={columns.length}+ className="h-24 text-center"+ >+ No results.+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </Table>+ </div>+ <DataTablePagination table={table} name="visitor" />+ </div>+ );+}diff --git a/components/visitors/data-table-pagination.tsx b/components/visitors/data-table-pagination.tsxnew file mode 100644index 00000000..0c8ab99a--- /dev/null+++ b/components/visitors/data-table-pagination.tsx@@ -0,0 +1,103 @@+import { Table } from "@tanstack/react-table";+import {+ ChevronLeftIcon,+ ChevronRightIcon,+ ChevronsLeftIcon,+ ChevronsRightIcon,+} from "lucide-react";++import { Button } from "@/components/ui/button";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";++interface DataTablePaginationProps<TData> {+ table: Table<TData>;+ name: string;+}++export function DataTablePagination<TData>({+ table,+ name,+}: DataTablePaginationProps<TData>) {+ const { pageSize, pageIndex } = table.getState().pagination;+ const totalRows = table.getFilteredRowModel().rows.length;+ const visibleRows = table.getRowModel().rows.length;++ return (+ <div className="flex items-center justify-between">+ <div className="flex-1 text-sm text-muted-foreground">+ {visibleRows} of {totalRows} {name}s shown+ </div>+ <div className="flex items-center space-x-6 lg:space-x-8">+ <div className="hidden items-center space-x-2 sm:flex">+ <p className="text-sm font-medium">+ {name.charAt(0).toUpperCase() + name.slice(1)}s per page+ </p>+ <Select+ value={`${pageSize}`}+ onValueChange={(value) => {+ table.setPageSize(Number(value));+ }}+ >+ <SelectTrigger className="h-8 w-[70px]">+ <SelectValue placeholder={pageSize} />+ </SelectTrigger>+ <SelectContent side="top">+ {[10, 20, 30, 40, 50].map((size) => (+ <SelectItem key={size} value={`${size}`}>+ {size}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="flex w-[100px] items-center justify-end text-sm font-medium">+ Page {pageIndex + 1} of {table.getPageCount()}+ </div>+ <div className="flex items-center space-x-2">+ <Button+ variant="outline"+ className="hidden h-8 w-8 p-0 lg:flex"+ onClick={() => table.setPageIndex(0)}+ disabled={!table.getCanPreviousPage()}+ >+ <span className="sr-only">Go to first page</span>+ <ChevronsLeftIcon className="h-4 w-4" />+ </Button>+ <Button+ variant="outline"+ className="h-8 w-8 p-0"+ onClick={() => table.previousPage()}+ disabled={!table.getCanPreviousPage()}+ >+ <span className="sr-only">Go to previous page</span>+ <ChevronLeftIcon className="h-4 w-4" />+ </Button>+ <Button+ variant="outline"+ className="h-8 w-8 p-0"+ onClick={() => table.nextPage()}+ disabled={!table.getCanNextPage()}+ >+ <span className="sr-only">Go to next page</span>+ <ChevronRightIcon className="h-4 w-4" />+ </Button>+ <Button+ variant="outline"+ className="hidden h-8 w-8 p-0 lg:flex"+ onClick={() => table.setPageIndex(table.getPageCount() - 1)}+ disabled={!table.getCanNextPage()}+ >+ <span className="sr-only">Go to last page</span>+ <ChevronsRightIcon className="h-4 w-4" />+ </Button>+ </div>+ </div>+ </div>+ );+}diff --git a/lib/swr/use-viewer.ts b/lib/swr/use-viewer.tsnew file mode 100644index 00000000..008e2744--- /dev/null+++ b/lib/swr/use-viewer.ts@@ -0,0 +1,35 @@+import { useRouter } from "next/router";++import { useTeam } from "@/context/team-context";+import { View, Viewer } from "@prisma/client";+import useSWR from "swr";++import { fetcher } from "@/lib/utils";++type ViewerWithViews = Viewer & {+ views: {+ documentId: string;+ viewCount: number;+ viewIds: string[];+ lastViewed: Date;+ }[];+};++export default function useViewer() {+ const router = useRouter();+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const { id } = router.query;++ const { data: viewer, error } = useSWR<ViewerWithViews>(+ teamId && id && `/api/teams/${teamId}/viewers/${id}`,+ fetcher,+ );++ return {+ viewer,+ loading: !viewer && !error,+ error,+ };+}diff --git a/lib/swr/use-viewers.ts b/lib/swr/use-viewers.tsnew file mode 100644index 00000000..4537c6f1--- /dev/null+++ b/lib/swr/use-viewers.ts@@ -0,0 +1,21 @@+import { useTeam } from "@/context/team-context";+import { Viewer } from "@prisma/client";+import useSWR from "swr";++import { fetcher } from "@/lib/utils";++export default function useViewers() {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const { data: viewers, error } = useSWR<Viewer[]>(+ teamId && `/api/teams/${teamId}/viewers`,+ fetcher,+ );++ return {+ viewers,+ loading: !viewers && !error,+ error,+ };+}diff --git a/lib/tinybird/endpoints/get_document_duration_per_viewer.pipe b/lib/tinybird/endpoints/get_document_duration_per_viewer.pipenew file mode 100644index 00000000..4a269543--- /dev/null+++ b/lib/tinybird/endpoints/get_document_duration_per_viewer.pipe@@ -0,0 +1,12 @@+VERSION 1++NODE endpoint+SQL >+ %+ SELECT+ SUM(duration) AS sum_duration+ FROM+ page_views__v3+ WHERE+ documentId = {{ String(documentId, required=True)}}+ AND viewId IN splitByChar(',', {{ String(viewIds, required=True) }})diff --git a/lib/tinybird/pipes.ts b/lib/tinybird/pipes.tsindex 41fa5eae..f2c46053 100644--- a/lib/tinybird/pipes.ts+++ b/lib/tinybird/pipes.ts@@ -60,3 +60,14 @@ export const getTotalDataroomDuration = tb.buildPipe({sum_duration: z.number(),}),});++export const getDocumentDurationPerViewer = tb.buildPipe({+ pipe: "get_document_duration_per_viewer__v1",+ parameters: z.object({+ documentId: z.string(),+ viewIds: z.string().describe("Comma separated viewIds"),+ }),+ data: z.object({+ sum_duration: z.number(),+ }),+});diff --git a/pages/api/teams/[teamId]/viewers/[id]/index.ts b/pages/api/teams/[teamId]/viewers/[id]/index.tsnew file mode 100644index 00000000..7c42a4d5--- /dev/null+++ b/pages/api/teams/[teamId]/viewers/[id]/index.ts@@ -0,0 +1,161 @@+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 { getDocumentDurationPerViewer } from "@/lib/tinybird";+import { CustomUser } from "@/lib/types";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ // GET /api/teams/:teamId/viewers/:id+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const { teamId, id } = req.query as { teamId: string; id: string };++ const userId = (session.user as CustomUser).id;++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId,+ },+ },+ },+ });++ if (!team) {+ return res.status(404).json({ error: "Team not found" });+ }++ const viewer = await prisma.viewer.findUnique({+ where: { id },+ include: {+ views: {+ where: {+ documentId: {+ not: null,+ },+ },+ },+ },+ });++ // same but for documentId+ const groupedViewsByDocumentId = viewer?.views.reduce(+ (+ acc: Record<+ string,+ {+ documentId: string;+ viewCount: number;+ viewIds: string[];+ lastViewed: Date;+ }+ >,+ view,+ ) => {+ const key = view.documentId!;+ if (!acc[key]) {+ acc[key] = {+ documentId: view.documentId ?? "",+ viewCount: 0,+ viewIds: [],+ lastViewed: new Date(0),+ };+ }+ acc[key].viewCount++;+ acc[key].viewIds.push(view.id);+ if (view.viewedAt > acc[key].lastViewed) {+ acc[key].lastViewed = view.viewedAt;+ }+ return acc;+ },+ {},+ );++ // get the document details for each documentId+ let documentDetails: {+ id: string;+ name: string | null;+ type: string | null;+ contentType: string | null;+ }[] = [];+ if (groupedViewsByDocumentId) {+ documentDetails = await prisma.document.findMany({+ where: {+ id: {+ in: Object.keys(groupedViewsByDocumentId),+ },+ },+ select: {+ id: true,+ name: true,+ type: true,+ contentType: true,+ },+ });+ }++ // Calculate sum_duration for each document+ const documentDurations = await Promise.all(+ Object.entries(groupedViewsByDocumentId ?? {}).map(+ async ([documentId, view]) => {+ const durationResult = await getDocumentDurationPerViewer({+ documentId,+ viewIds: view.viewIds.join(","),+ });+ return {+ documentId,+ sum_duration: durationResult.data[0].sum_duration,+ };+ },+ ),+ );++ // Create a map for quick lookup+ const durationMap = new Map(+ documentDurations.map((d) => [d.documentId, d.sum_duration]),+ );++ // create a new array with the grouped views and merge with document details+ const groupedViews = groupedViewsByDocumentId+ ? Object.values(groupedViewsByDocumentId).map((view) => {+ const document = documentDetails?.find(+ (doc) => doc.id === view.documentId,+ );++ return {+ ...view,+ document,+ totalDuration: durationMap.get(view.documentId) || 0,+ };+ })+ : [];++ const newViewer = {+ ...viewer,+ views: groupedViews,+ };++ return res.status(200).json(newViewer);+ } catch (error) {+ errorhandler(error, res);+ }+ } else {+ // We only allow GET requests+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/api/teams/[teamId]/viewers/index.ts b/pages/api/teams/[teamId]/viewers/index.tsnew file mode 100644index 00000000..fe1ff26a--- /dev/null+++ b/pages/api/teams/[teamId]/viewers/index.ts@@ -0,0 +1,66 @@+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 { CustomUser } from "@/lib/types";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ // GET /api/teams/:teamId/viewers+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const { teamId } = req.query as { teamId: string };++ const userId = (session.user as CustomUser).id;++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId,+ },+ },+ },+ });++ if (!team) {+ return res.status(404).json({ error: "Team not found" });+ }++ const viewers = await prisma.viewer.findMany({+ where: { teamId },+ include: {+ views: {+ orderBy: {+ viewedAt: "desc",+ },+ where: {+ documentId: {+ not: null,+ },+ },+ },+ },+ });++ return res.status(200).json(viewers);+ } catch (error) {+ errorhandler(error, res);+ }+ } else {+ // We only allow GET requests+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/api/views-dataroom.ts b/pages/api/views-dataroom.tsindex 372f5abf..96e2698f 100644--- a/pages/api/views-dataroom.ts+++ b/pages/api/views-dataroom.ts@@ -8,7 +8,6 @@ import { parsePageId } from "notion-utils";import { hashToken } from "@/lib/api/auth/token";import sendNotification from "@/lib/api/notification-helper";import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verification";-import { sendVerificationEmail } from "@/lib/emails/send-email-verification";import { getFile } from "@/lib/files/get-file";import { newId } from "@/lib/id-helper";import notion from "@/lib/notion";diff --git a/pages/datarooms/index.tsx b/pages/datarooms/index.tsxindex 7f918f26..40fb82da 100644--- a/pages/datarooms/index.tsx+++ b/pages/datarooms/index.tsx@@ -1,4 +1,7 @@import Link from "next/link";+import { useRouter } from "next/router";++import { useEffect } from "react";import { PlusIcon } from "lucide-react";@@ -21,27 +24,25 @@ import { usePlan } from "@/lib/swr/use-billing";import useDatarooms from "@/lib/swr/use-datarooms";import useLimits from "@/lib/swr/use-limits";import { daysLeft } from "@/lib/utils";-import { useEffect } from "react";-import { useRouter } from "next/navigation";export default function DataroomsPage() {const { datarooms } = useDatarooms();const { plan, trial } = usePlan();const { limits } = useLimits();- const router = useRouter()+ const router = useRouter();const numDatarooms = datarooms?.length ?? 0;const limitDatarooms = limits?.datarooms ?? 1;+ const isTrial = !!trial;const isBusiness = plan === "business";const isDatarooms = plan === "datarooms";- const isTrialDatarooms = trial === "drtrial";const canCreateUnlimitedDatarooms =isDatarooms || (isBusiness && numDatarooms < limitDatarooms);- useEffect(()=>{- if(trial == null && plan == 'free') router.push('/documents')- },[trial,plan])+ useEffect(() => {+ if (plan == "free" && !isTrial) router.push("/documents");+ }, [isTrial, plan]);return (<AppLayout>@@ -65,7 +66,7 @@ export default function DataroomsPage() {<span>Upgrade to Add Data Room</span></Button></UpgradePlanModal>- ) : isTrialDatarooms && datarooms && !isBusiness && !isDatarooms ? (+ ) : isTrial && datarooms && !isBusiness && !isDatarooms ? (<div className="flex items-center gap-x-4"><div className="text-sm text-destructive"><span>Dataroom Trial: </span>diff --git a/pages/visitors/[id]/index.tsx b/pages/visitors/[id]/index.tsxnew file mode 100644index 00000000..e855bb5e--- /dev/null+++ b/pages/visitors/[id]/index.tsx@@ -0,0 +1,56 @@+import Link from "next/link";++import { useState } from "react";++import AppLayout from "@/components/layouts/app";+import {+ Breadcrumb,+ BreadcrumbItem,+ BreadcrumbLink,+ BreadcrumbList,+ BreadcrumbPage,+ BreadcrumbSeparator,+} from "@/components/ui/breadcrumb";+import { Separator } from "@/components/ui/separator";+import { ContactsDocumentsTable } from "@/components/visitors/contacts-document-table";++import useViewer from "@/lib/swr/use-viewer";++export default function VisitorDetailPage() {+ const { viewer } = useViewer();+ const views = viewer?.views;++ return (+ <AppLayout>+ <div className="p-4 pb-0 sm:m-4 sm:py-4">+ <section className="mb-4 flex flex-col justify-between md:mb-8 lg:mb-12">+ <Breadcrumb className="hidden md:flex">+ <BreadcrumbList>+ <BreadcrumbItem>+ <BreadcrumbLink asChild>+ <Link href="/visitors">All Visitors</Link>+ </BreadcrumbLink>+ </BreadcrumbItem>+ <BreadcrumbSeparator />+ <BreadcrumbItem>+ <BreadcrumbPage>{viewer?.email}</BreadcrumbPage>+ </BreadcrumbItem>+ </BreadcrumbList>+ </Breadcrumb>+ <div className="mt-2">+ <h2 className="text-xl font-semibold tracking-tight text-foreground sm:text-2xl">+ {viewer?.email}+ </h2>+ </div>+ </section>++ <Separator className="mb-2 bg-gray-200 dark:bg-gray-800" />+ </div>++ <div className="relative p-4 pt-0 sm:mx-4 sm:mt-4">+ {/* @ts-ignore */}+ <ContactsDocumentsTable views={views} />+ </div>+ </AppLayout>+ );+}diff --git a/pages/visitors/index.tsx b/pages/visitors/index.tsxnew file mode 100644index 00000000..6e77a2a8--- /dev/null+++ b/pages/visitors/index.tsx@@ -0,0 +1,46 @@+import { useRouter } from "next/router";++import { useEffect, useState } from "react";++import AppLayout from "@/components/layouts/app";+import { Separator } from "@/components/ui/separator";+import { ContactsTable } from "@/components/visitors/contacts-table";++import { usePlan } from "@/lib/swr/use-billing";+import useViewers from "@/lib/swr/use-viewers";++export default function Visitors() {+ const router = useRouter();+ const { plan, trial } = usePlan();+ const { viewers } = useViewers();++ const isTrial = !!trial;+ const isFree = plan == "free";++ useEffect(() => {+ if (isFree && !isTrial) router.push("/documents");+ }, [isTrial, isFree]);++ return (+ <AppLayout>+ <div className="p-4 pb-0 sm:m-4 sm:py-4">+ <section className="mb-4 flex items-center justify-between md:mb-8 lg:mb-12">+ <div className="space-y-1">+ <h2 className="text-xl font-semibold tracking-tight text-foreground sm:text-2xl">+ All visitors+ </h2>+ <p className="text-xs text-muted-foreground sm:text-sm">+ Manage all your visitors in one place.+ </p>+ </div>+ </section>+ <Separator className="mb-2 bg-gray-200 dark:bg-gray-800" />+ </div>++ <div className="relative p-4 pt-0 sm:mx-4 sm:mt-4">+ {/* @ts-ignore */}+ <ContactsTable viewers={viewers} />+ </div>+ </AppLayout>+ );+}