Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add visitor table to document page
Marc Seitz9cb5a7f69049
diff --git a/components/visitors/visitors-table.tsx b/components/visitors/visitors-table.tsxnew file mode 100644index 00000000..33d09d88--- /dev/null+++ b/components/visitors/visitors-table.tsx@@ -0,0 +1,138 @@+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@/components/ui/collapsible";+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";+import { Gauge } from "@/components/ui/gauge";++import { useDocumentVisits } from "@/lib/swr/use-document";+import { durationFormat, nFormatter, timeAgo } from "@/lib/utils";+import { Skeleton } from "../ui/skeleton";+import ChevronDown from "../shared/icons/chevron-down";++export default function VisitorsTable() {+ const { views } = useDocumentVisits();++ return (+ <div className="w-full sm:p-4">+ <div>+ <h2 className="p-4">All visitors</h2>+ </div>+ <div className="rounded-md sm:border">+ <Table>+ <TableHeader>+ <TableRow className="hover:bg-transparent">+ <TableHead className="font-medium">+ Name+ </TableHead>+ <TableHead className="font-medium">Visit Duration</TableHead>+ <TableHead className="font-medium">Visit Completion</TableHead>+ <TableHead className="font-medium">Last Viewed</TableHead>+ <TableHead className="font-medium text-center sm:text-right"></TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {views ? (+ views.map((view) => (+ <Collapsible key={view.id} asChild>+ <>+ <TableRow key={view.id} className="group/row">+ {/* Name */}+ <TableCell className="">+ <div className="flex items-center sm:space-x-3 overflow-visible">+ <Avatar className="flex-shrink-0 hidden sm:inline-flex">+ <AvatarFallback>+ {view.viewerEmail?.slice(0, 2).toUpperCase()}+ </AvatarFallback>+ </Avatar>+ <div className="min-w-0 flex-1">+ <div className="focus:outline-none">+ <p className="text-sm font-medium text-gray-200 overflow-visible">+ {view.viewerEmail}+ </p>+ <p className="text-sm text-gray-500">+ <span>Link Name</span>+ </p>+ </div>+ </div>+ </div>+ </TableCell>+ {/* Duration */}+ <TableCell className="">+ <div className="text-sm text-gray-400">+ {durationFormat(view.totalDuration)}+ </div>+ </TableCell>+ {/* Completion */}+ <TableCell className="flex justify-start">+ <div className="text-sm text-gray-400">+ <Gauge+ value={view.completionRate}+ size={"small"}+ showValue={true}+ />+ </div>+ </TableCell>+ {/* Last Viewed */}+ <TableCell className="text-sm text-gray-400">+ <time+ dateTime={new Date(+ view.viewedAt+ ).toISOString()}+ >+ {timeAgo(view.viewedAt)}+ </time>+ </TableCell>+ {/* Actions */}+ <TableCell className="text-center sm:text-right">+ <CollapsibleTrigger asChild>+ <div className="flex justify-end px-2 space-x-1 [&[data-state=open]>svg.chevron]:rotate-180">+ <ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200 chevron" />+ </div>+ </CollapsibleTrigger>+ </TableCell>+ </TableRow>+ <CollapsibleContent asChild>+ <>+ <TableRow className="hover:bg-transparent">+ <TableCell colSpan={5}>+ <div>+ </div>+ </TableCell>+ </TableRow>+ </>+ </CollapsibleContent>+ </>+ </Collapsible>+ ))+ ) : (+ <TableRow>+ <TableCell className="min-w-[100px]">+ <Skeleton className="h-6 w-full" />+ </TableCell>+ <TableCell className="min-w-[450px]">+ <Skeleton className="h-6 w-full" />+ </TableCell>+ <TableCell>+ <Skeleton className="h-6 w-24" />+ </TableCell>+ <TableCell>+ <Skeleton className="h-6 w-24" />+ </TableCell>+ </TableRow>+ )}+ </TableBody>+ </Table>+ </div>+ </div>+ );+}diff --git a/lib/swr/use-document.ts b/lib/swr/use-document.tsindex 32f3f717..1355b9d0 100644--- a/lib/swr/use-document.ts+++ b/lib/swr/use-document.ts@@ -2,7 +2,7 @@ import { useRouter } from "next/router";import useSWR from "swr";import { fetcher } from "@/lib/utils";import { LinkWithViews } from "@/lib/types";-import { Document } from "@prisma/client";+import { Document, View } from "@prisma/client";export function useDocument() {const router = useRouter();@@ -47,3 +47,33 @@ export function useDocumentLinks() {error,};}++interface ViewWithDuration extends View {+ duration: {+ data: { pageNumber: string; sum_duration: number }[];+ };+ totalDuration: number;+ completionRate: number;+}++export function useDocumentVisits() {+ const router = useRouter();++ const { id } = router.query as {+ id: string;+ };++ const { data: views, error } = useSWR<ViewWithDuration[]>(+ id && `/api/documents/${encodeURIComponent(id)}/views`,+ fetcher,+ {+ dedupingInterval: 10000,+ }+ );++ return {+ views,+ loading: !error && !views,+ error,+ };+}diff --git a/pages/api/documents/[id]/views/index.ts b/pages/api/documents/[id]/views/index.tsnew file mode 100644index 00000000..789ca79f--- /dev/null+++ b/pages/api/documents/[id]/views/index.ts@@ -0,0 +1,93 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import prisma from "@/lib/prisma";+import { log } from "@/lib/utils";+import { getViewPageDuration } from "@/lib/tinybird";+import { authOptions } from "@/pages/api/auth/[...nextauth]";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse+) {+ if (req.method === "GET") {+ // GET /api/documents/:id/visits+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ // get link id from query params+ const { id } = req.query as { id: string };++ try {+ // get the numPages from document+ const result = await prisma.document.findUnique({+ where: {+ id: id,+ },+ select: {+ numPages: true,+ },+ });+ const numPages = result?.numPages;++ const views = await prisma.view.findMany({+ where: {+ documentId: id,+ },+ orderBy: {+ viewedAt: "desc",+ },+ });++ const durationsPromises = views.map((view) => {+ return getViewPageDuration({+ documentId: id,+ viewId: view.id,+ since: 0,+ });+ });++ const durations = await Promise.all(durationsPromises);++ // Sum up durations for each view+ const summedDurations = durations.map((duration) => {+ return duration.data.reduce(+ (totalDuration, data) => totalDuration + data.sum_duration,+ 0+ );+ });++ // Construct the response combining views and their respective durations+ const viewsWithDuration = views.map((view, index) => {+ // calculate the completion rate+ const completionRate = numPages+ ? (durations[index].data.length / numPages) * 100+ : 0;++ return {+ ...view,+ duration: durations[index],+ totalDuration: summedDurations[index],+ completionRate: completionRate.toFixed(),+ };+ });++ // TODO: Check that the user is owner of the links, otherwise return 401++ // console.log("viewsWithDuration:", viewsWithDuration)++ res.status(200).json(viewsWithDuration);+ } catch (error) {+ log(`Failed to get views for link ${id}. Error: \n\n ${error}`);+ return res.status(500).json({+ message: "Internal Server Error",+ error: (error as Error).message,+ });+ }+ } else {+ // We only allow GET requests+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/documents/[id].tsx b/pages/documents/[id].tsxindex fecfb78a..ea5fb196 100644--- a/pages/documents/[id].tsx+++ b/pages/documents/[id].tsx@@ -7,6 +7,7 @@ import AppLayout from "@/components/layouts/app";import LinkSheet from "@/components/links/link-sheet";import Image from "next/image"import LinksTable from "@/components/links/links-table";+import VisitorsTable from "@/components/visitors/visitors-table";export default function DocumentPage() {const { document, error } = useDocument();@@ -55,6 +56,8 @@ export default function DocumentPage() {/>)}<StatsCard />+ {/* Visitors */}+ <VisitorsTable />{/* Links */}<LinksTable /></>