Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add dataroom stats
Marc Seitzd523a45600fd
diff --git a/components/datarooms/stats-card.tsx b/components/datarooms/stats-card.tsxnew file mode 100644index 00000000..01aca310--- /dev/null+++ b/components/datarooms/stats-card.tsx@@ -0,0 +1,64 @@+import ErrorPage from "next/error";+import StatsElement from "@/components/documents/stats-element";+import { Skeleton } from "@/components/ui/skeleton";+import { useDataroomStats } from "@/lib/swr/use-dataroom-stats";++export default function StatsCard() {+ const { stats, loading, error } = useDataroomStats();++ if (error && error.status === 404) {+ return <ErrorPage statusCode={404} />;+ }++ if (loading) {+ return (+ <div className="grid grid-cols-1 sm:grid-cols-3 lg:grid-cols-3 border-foreground/5 space-y-2 sm:space-y-0 sm:space-x-2 lg:space-x-3">+ {Array.from({ length: 3 }).map((_, i) => (+ <div+ className="border border-foreground/5 py-6 px-4 sm:px-6 lg:px-8 rounded-lg"+ key={i}+ >+ <Skeleton className="h-6 w-[80%] rounded-sm" />+ <Skeleton className="mt-4 h-8 w-9" />+ </div>+ ))}+ </div>+ );+ }++ const statistics = [+ {+ name: "Number of visits",+ value: stats?.dataroomViews.length.toString() ?? "0",+ active: true,+ },+ {+ name: "Number of documents visits",+ value: stats?.documentViews.length.toString() ?? "0",+ active: true,+ },+ {+ name: "Total time spent",+ value:+ stats?.total_duration == null+ ? "46"+ : stats?.total_duration < 60000+ ? `${Math.round(stats?.total_duration / 1000)}`+ : `${Math.floor(stats?.total_duration / 60000)}:${+ Math.round((stats?.total_duration % 60000) / 1000) < 10+ ? `0${Math.round((stats?.total_duration % 60000) / 1000)}`+ : Math.round((stats?.total_duration % 60000) / 1000)+ }`,+ unit: stats?.total_duration! < 60000 ? "seconds" : "minutes",+ active: true,+ },+ ];++ return stats && stats.dataroomViews.length > 0 ? (+ <div className="grid grid-cols-1 sm:grid-cols-3 lg:grid-cols-3 border-foreground/5 space-y-2 sm:space-y-0 sm:space-x-2 lg:space-x-3">+ {statistics.map((stat, statIdx) => (+ <StatsElement key={statIdx} stat={stat} statIdx={statIdx} />+ ))}+ </div>+ ) : null;+}diff --git a/lib/swr/use-dataroom-stats.ts b/lib/swr/use-dataroom-stats.tsnew file mode 100644index 00000000..b89340d9--- /dev/null+++ b/lib/swr/use-dataroom-stats.ts@@ -0,0 +1,79 @@+import { useRouter } from "next/router";+import useSWR from "swr";+import { fetcher } from "@/lib/utils";+import { View } from "@prisma/client";+import { useTeam } from "@/context/team-context";++export type TDataroomStatsData = {+ dataroomViews: View[];+ documentViews: View[];+ duration: {+ viewId: string;+ sum_duration: number;+ }[];+ total_duration: number;+};++export function useDataroomStats({+ excludeTeamMembers,+}: { excludeTeamMembers?: boolean } = {}) {+ // this gets the data for a document's graph of all views+ const router = useRouter();+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const { id } = router.query as {+ id: string;+ };++ const { data: stats, error } = useSWR<TDataroomStatsData>(+ id &&+ teamId &&+ `/api/teams/${teamId}/datarooms/${id}/stats${excludeTeamMembers ? "?excludeTeamMembers=true" : ""}`,+ fetcher,+ {+ dedupingInterval: 10000,+ },+ );++ return {+ stats,+ loading: !error && !stats,+ error,+ };+}++// interface StatsViewData {+// views: View[];+// duration: {+// data: { pageNumber: string; sum_duration: number }[];+// };+// }++// export function useVisitorStats(viewId: string) {+// // this gets the data for a single visitor's graph+// const router = useRouter();+// const teamInfo = useTeam();++// const { id: documentId } = router.query as {+// id: string;+// };++// const { data: stats, error } = useSWR<StatsViewData>(+// documentId &&+// viewId &&+// `/api/teams/${teamInfo?.currentTeam?.id}/documents/${encodeURIComponent(+// documentId,+// )}/views/${encodeURIComponent(viewId)}/stats`,+// fetcher,+// {+// dedupingInterval: 10000,+// },+// );++// return {+// stats,+// loading: !error && !stats,+// error,+// };+// }diff --git a/pages/api/teams/[teamId]/datarooms/[id]/stats.ts b/pages/api/teams/[teamId]/datarooms/[id]/stats.tsnew file mode 100644index 00000000..8998c739--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/stats.ts@@ -0,0 +1,131 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import prisma from "@/lib/prisma";+import { authOptions } from "../../../../auth/[...nextauth]";+import { getTotalDataroomDuration } from "@/lib/tinybird";+import { CustomUser } from "@/lib/types";+import { errorhandler } from "@/lib/errorHandler";+import { View } from "@prisma/client";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ // GET /api/teams/:teamId/documents/:id/stats+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const {+ teamId,+ id: dataroomId,+ excludeTeamMembers,+ } = req.query as {+ teamId: string;+ id: string;+ excludeTeamMembers?: string;+ };++ const userId = (session.user as CustomUser).id;++ try {+ // Check if the user is part of the team+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId: userId,+ },+ },+ },+ });++ if (!team) {+ return res.status(401).end("Unauthorized");+ }++ const dataroom = await prisma.dataroom.findUnique({+ where: {+ id: dataroomId,+ },+ include: {+ views: true,+ },+ });++ const users = await prisma.user.findMany({+ where: {+ teams: {+ some: {+ teamId: teamId,+ },+ },+ },+ select: {+ email: true,+ },+ });++ const views = dataroom?.views;++ // if there are no views, return an empty array+ if (!views) {+ return res.status(200).json({+ views: [],+ duration: { data: [] },+ total_duration: 0,+ groupedReactions: [],+ });+ }++ const dataroomViews = views.filter(+ (view) => view.viewType === "DATAROOM_VIEW",+ );+ const documentViews = views.filter(+ (view) => view.viewType === "DOCUMENT_VIEW",+ );++ // exclude views from the team's members+ let excludedViews: View[] = [];+ if (excludeTeamMembers) {+ excludedViews = documentViews.filter((view) => {+ return users.some((user) => user.email === view.viewerEmail);+ });+ }++ const filteredViews = documentViews.filter(+ (view) => !excludedViews.map((view) => view.id).includes(view.id),+ );++ const duration = await getTotalDataroomDuration({+ dataroomId: dataroomId,+ excludedLinkIds: [],+ excludedViewIds: excludedViews.map((view) => view.id),+ since: 0,+ });++ const total_duration = duration.data.reduce(+ (totalDuration, data) => totalDuration + data.sum_duration,+ 0,+ );++ const stats = {+ dataroomViews: dataroomViews,+ documentViews: documentViews,+ duration: duration.data,+ total_duration,+ };++ return res.status(200).json(stats);+ } 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/datarooms/[id]/index.tsx b/pages/datarooms/[id]/index.tsxindex 9d4c106c..8de0c750 100644--- a/pages/datarooms/[id]/index.tsx+++ b/pages/datarooms/[id]/index.tsx@@ -1,4 +1,5 @@import { DataroomHeader } from "@/components/datarooms/dataroom-header";+import StatsCard from "@/components/datarooms/stats-card";import AppLayout from "@/components/layouts/app";import LinkSheet from "@/components/links/link-sheet";import LinksTable from "@/components/links/links-table";@@ -58,6 +59,9 @@ export default function DataroomPage() {</header><div className="space-y-4">+ {/* Stats */}+ <StatsCard />+{/* Links */}<LinksTable links={links} targetType={"DATAROOM"} />