Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add dataroom visitors
Marc Seitzec72cd840515
diff --git a/components/visitors/dataroom-visitors-history.tsx b/components/visitors/dataroom-visitors-history.tsxnew file mode 100644index 00000000..bc67bc00--- /dev/null+++ b/components/visitors/dataroom-visitors-history.tsx@@ -0,0 +1,64 @@+import { timeAgo } from "@/lib/utils";+import { TableCell, TableRow } from "@/components/ui/table";+import { Skeleton } from "@/components/ui/skeleton";+import { useDataroomVisitHistory } from "@/lib/swr/use-dataroom";+import Link from "next/link";+import { FileCheckIcon } from "lucide-react";+import { Button } from "@/components/ui/button";++export default function DataroomVisitHistory({+ viewId,+ dataroomId,+}: {+ viewId: string;+ dataroomId: string;+}) {+ const { documentViews } = useDataroomVisitHistory({ viewId, dataroomId });++ return (+ <>+ {documentViews ? (+ documentViews.map((view) => (+ <TableRow key={view.id}>+ <TableCell>+ <div className="flex items-center gap-x-4 overflow-visible">+ <FileCheckIcon className="h-5 w-5 text-[#fb7a00]" />+ Viewed {view.document.name}+ </div>+ </TableCell>++ <TableCell>+ <div>+ <time+ className="truncate text-sm text-muted-foreground"+ dateTime={new Date(view.viewedAt).toISOString()}+ title={new Date(view.viewedAt).toLocaleString()}+ >+ {timeAgo(view.viewedAt)}+ </time>+ </div>+ </TableCell>+ <TableCell className="table-cell">+ <div className="flex items-center justify-end space-x-4">+ <Button size={"sm"} variant={"link"} className="">+ <Link href={`/documents/${view.document.id}`}>+ See document+ </Link>+ </Button>+ </div>+ </TableCell>+ </TableRow>+ ))+ ) : (+ <TableRow>+ <TableCell>+ <Skeleton className="h-6 w-24" />+ </TableCell>+ <TableCell>+ <Skeleton className="h-6 w-16" />+ </TableCell>+ </TableRow>+ )}+ </>+ );+}diff --git a/components/visitors/dataroom-visitors-table.tsx b/components/visitors/dataroom-visitors-table.tsxnew file mode 100644index 00000000..b9bd2844--- /dev/null+++ b/components/visitors/dataroom-visitors-table.tsx@@ -0,0 +1,188 @@+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@/components/ui/table";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@/components/ui/collapsible";+import { Skeleton } from "@/components/ui/skeleton";++import { durationFormat, timeAgo } from "@/lib/utils";+import ChevronDown from "@/components/shared/icons/chevron-down";+import { VisitorAvatar } from "./visitor-avatar";+import { BadgeCheckIcon, BadgeInfoIcon, MailOpenIcon } from "lucide-react";+import { BadgeTooltip } from "@/components/ui/tooltip";+import { useDataroomVisits } from "@/lib/swr/use-dataroom";+import DataroomVisitHistory from "./dataroom-visitors-history";++export default function DataroomVisitorsTable({+ dataroomId,+}: {+ dataroomId: string;+}) {+ const { views } = useDataroomVisits({ dataroomId });++ return (+ <div className="w-full">+ <div>+ <h2 className="mb-2 md:mb-4">All visitors</h2>+ </div>+ <div className="rounded-md border">+ <Table>+ <TableHeader>+ <TableRow className="hover:bg-transparent *:font-medium *:whitespace-nowrap">+ <TableHead>Name</TableHead>+ {/* <TableHead>Visit Duration</TableHead> */}+ {/* <TableHead>Last Viewed Document</TableHead> */}+ <TableHead>Last Viewed</TableHead>+ <TableHead className="text-center sm:text-right"></TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {views?.length === 0 && (+ <TableRow>+ <TableCell colSpan={5}>+ <div className="w-full h-40 flex items-center justify-center">+ <p>No Data Available</p>+ </div>+ </TableCell>+ </TableRow>+ )}+ {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">+ <VisitorAvatar viewerEmail={view.viewerEmail} />+ <div className="min-w-0 flex-1">+ <div className="focus:outline-none">+ <p className="text-sm font-medium text-gray-800 dark:text-gray-200 overflow-visible flex items-center gap-x-2">+ {view.viewerEmail ? (+ <>+ {view.viewerEmail}{" "}+ {view.verified && (+ <BadgeTooltip+ content="Verified visitor"+ key="verified"+ >+ <BadgeCheckIcon className="h-4 w-4 text-emerald-500 hover:text-emerald-600" />+ </BadgeTooltip>+ )}+ {view.internal && (+ <BadgeTooltip+ content="Internal visitor"+ key="internal"+ >+ <BadgeInfoIcon className="h-4 w-4 text-blue-500 hover:text-blue-600" />+ </BadgeTooltip>+ )}+ </>+ ) : (+ "Anonymous"+ )}+ </p>+ <p className="text-xs sm:text-sm text-muted-foreground/60">+ {view.link.name ? view.link.name : view.linkId}+ </p>+ </div>+ </div>+ </div>+ </TableCell>+ {/* Duration */}+ {/* <TableCell className="">+ <div className="text-sm text-muted-foreground">+ {durationFormat(view.totalDuration)}+ </div>+ </TableCell> */}+ {/* Completion */}+ {/* <TableCell className="flex justify-start">+ <div className="text-sm text-muted-foreground">+ <Gauge+ value={view.completionRate}+ size={"small"}+ showValue={true}+ />+ </div>+ </TableCell> */}+ {/* Last Viewed */}+ <TableCell className="text-sm text-muted-foreground">+ <time dateTime={new Date(view.viewedAt).toISOString()}>+ {timeAgo(view.viewedAt)}+ </time>+ </TableCell>+ {/* Actions */}+ <TableCell className="text-center sm:text-right cursor-pointer p-0">+ <CollapsibleTrigger asChild>+ <div className="flex justify-end p-5 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 key={view.id}>+ <TableCell>+ <div className="flex items-center gap-x-4 overflow-visible">+ <MailOpenIcon className="h-5 w-5 text-[#fb7a00]" />+ Accessed {view.dataroomName} dataroom+ </div>+ </TableCell>++ <TableCell>+ <div>+ <time+ className="truncate text-sm text-muted-foreground"+ dateTime={new Date(+ view.viewedAt,+ ).toLocaleString()}+ title={new Date(view.viewedAt).toLocaleString()}+ >+ {timeAgo(view.viewedAt)}+ </time>+ </div>+ </TableCell>+ <TableCell className="table-cell"></TableCell>+ </TableRow>++ <DataroomVisitHistory+ viewId={view.id}+ dataroomId={dataroomId}+ />+ </>+ </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-dataroom.ts b/lib/swr/use-dataroom.tsindex 42ea76f7..ace9985e 100644--- a/lib/swr/use-dataroom.ts+++ b/lib/swr/use-dataroom.ts@@ -219,3 +219,51 @@ export function useDataroomFolderDocuments({ name }: { name: string[] }) {error,};}++export function useDataroomVisits({ dataroomId }: { dataroomId: string }) {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const { data: views, error } = useSWR<any[]>(+ teamId &&+ dataroomId &&+ `/api/teams/${teamId}/datarooms/${dataroomId}/views`,+ fetcher,+ {+ dedupingInterval: 10000,+ },+ );++ return {+ views,+ loading: !error && !views,+ error,+ };+}++export function useDataroomVisitHistory({+ viewId,+ dataroomId,+}: {+ viewId: string;+ dataroomId: string;+}) {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const { data: documentViews, error } = useSWR<any[]>(+ teamId &&+ dataroomId &&+ `/api/teams/${teamId}/datarooms/${dataroomId}/views/${viewId}/history`,+ fetcher,+ {+ dedupingInterval: 10000,+ },+ );++ return {+ documentViews,+ loading: !error && !documentViews,+ error,+ };+}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/views/[viewId]/history.ts b/pages/api/teams/[teamId]/datarooms/[id]/views/[viewId]/history.tsnew file mode 100644index 00000000..7a74b906--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/views/[viewId]/history.ts@@ -0,0 +1,80 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { CustomUser } from "@/lib/types";+import prisma from "@/lib/prisma";+import { errorhandler } from "@/lib/errorHandler";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ // GET /api/teams/:teamId/datarooms/:id/views/:viewId/history+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const {+ teamId,+ id: dataroomId,+ viewId,+ } = req.query as {+ teamId: string;+ id: string;+ viewId: string;+ };++ const userId = (session.user as CustomUser).id;++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId: (session.user as CustomUser).id,+ },+ },+ },+ select: {+ id: true,+ },+ });++ if (!team) {+ return res.status(403).end("Unauthorized to access this team");+ }++ const documentViews = await prisma.view.findMany({+ where: {+ dataroomViewId: viewId,+ dataroomId: dataroomId,+ viewType: "DOCUMENT_VIEW",+ },+ orderBy: {+ viewedAt: "asc",+ },+ select: {+ id: true,+ viewedAt: true,+ document: {+ select: {+ id: true,+ name: true,+ },+ },+ },+ });++ return res.status(200).json(documentViews);+ } catch (error) {+ errorhandler(error, res);+ }+ } else {+ // We only allow GET and POST requests+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/views/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/views/index.tsnew file mode 100644index 00000000..2c8cde81--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/views/index.ts@@ -0,0 +1,108 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import { log } from "@/lib/utils";+import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { CustomUser } from "@/lib/types";+import { errorhandler } from "@/lib/errorHandler";+import prisma from "@/lib/prisma";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ // GET /api/teams/:teamId/datarooms/:id/views+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const { teamId, id: dataroomId } = 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: (session.user as CustomUser).id,+ },+ },+ },+ select: {+ id: true,+ },+ });++ if (!team) {+ return res.status(403).end("Unauthorized to access this team");+ }++ const dataroom = await prisma.dataroom.findUnique({+ where: {+ id: dataroomId,+ teamId: teamId,+ },+ select: {+ id: true,+ teamId: true,+ name: true,+ views: {+ where: {+ viewType: "DATAROOM_VIEW",+ },+ orderBy: {+ viewedAt: "desc",+ },+ include: {+ link: {+ select: {+ name: true,+ },+ },+ },+ },+ },+ });++ const users = await prisma.user.findMany({+ where: {+ teams: {+ some: {+ teamId: teamId,+ },+ },+ },+ select: {+ email: true,+ },+ });++ const views = dataroom?.views || [];++ const returnViews = views.map((view) => {+ return {+ ...view,+ dataroomName: dataroom?.name,+ internal: users.some((user) => user.email === view.viewerEmail), // set internal to true if view.viewerEmail is in the users list+ };+ });++ return res.status(200).json(returnViews);+ } catch (error) {+ log({+ message: `Failed to get views for dataroom: _${dataroomId}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``,+ type: "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/datarooms/[id]/index.tsx b/pages/datarooms/[id]/index.tsxindex 8de0c750..36216389 100644--- a/pages/datarooms/[id]/index.tsx+++ b/pages/datarooms/[id]/index.tsx@@ -5,6 +5,7 @@ import LinkSheet from "@/components/links/link-sheet";import LinksTable from "@/components/links/links-table";import { NavMenu } from "@/components/navigation-menu";import { Button } from "@/components/ui/button";+import DataroomVisitorsTable from "@/components/visitors/dataroom-visitors-table";import { useDataroom, useDataroomLinks } from "@/lib/swr/use-dataroom";import { useState } from "react";@@ -66,7 +67,7 @@ export default function DataroomPage() {<LinksTable links={links} targetType={"DATAROOM"} />{/* Visitors */}- {/* <VisitorsTable numPages={primaryVersion.numPages!} /> */}+ <DataroomVisitorsTable dataroomId={dataroom.id} /><LinkSheetlinkType={"DATAROOM_LINK"}