Skip to content

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

Display visit state on dataroom group

Ashish Viradiyafd6d77c111cb
diff --git a/components/datarooms/groups/group-navigation.tsx b/components/datarooms/groups/group-navigation.tsx
index 815e8546..417820d7 100644
--- a/components/datarooms/groups/group-navigation.tsx
+++ b/components/datarooms/groups/group-navigation.tsx
@@ -53,6 +53,18 @@ export const GroupNavigation = ({
<FileSlidersIcon className="h-4 w-4" />
Permissions
</Link>
+ <Link
+ href={`/datarooms/${dataroomId}/groups/${viewerGroupId}/group-analytic`}
+ className={cn(
+ "flex items-center gap-x-2 rounded-md p-2 text-primary hover:bg-muted",
+ {
+ "bg-muted font-medium": router.pathname.includes("group-analytic"),
+ },
+ )}
+ >
+ <FileSlidersIcon className="h-4 w-4" />
+ Group analytics
+ </Link>
</nav>
);
};
diff --git a/components/visitors/dataroom-visitors-table.tsx b/components/visitors/dataroom-visitors-table.tsx
index aa9a77ac..3e633465 100644
--- a/components/visitors/dataroom-visitors-table.tsx
+++ b/components/visitors/dataroom-visitors-table.tsx
@@ -36,18 +36,22 @@ import { VisitorAvatar } from "./visitor-avatar";
export default function DataroomVisitorsTable({
dataroomId,
+ groupId,
+ name,
}: {
dataroomId: string;
+ groupId?: string;
+ name?: string;
}) {
const teamInfo = useTeam();
const teamId = teamInfo?.currentTeam?.id;
- const { views } = useDataroomVisits({ dataroomId });
+ const { views } = useDataroomVisits({ dataroomId, groupId });
const exportVisitCounts = async (dataroomId: string) => {
const formattedTime = new Date().toISOString().replace(/[-:Z]/g, "");
try {
const response = await fetch(
- `/api/teams/${teamId}/datarooms/${dataroomId}/export-visits`,
+ `/api/teams/${teamId}/datarooms/${dataroomId}${groupId ? `/groups/${groupId}` : ""}/export-visits`,
{ method: "GET" },
);
if (!response.ok) {
@@ -62,7 +66,7 @@ export default function DataroomVisitorsTable({
link.href = url;
link.setAttribute(
"download",
- `${data.dataroomName}_visits_${formattedTime}.csv`,
+ `${data.dataroomName}_${name ? `${name}_` : ""}visits_${formattedTime}.csv`,
);
document.body.appendChild(link);
link.click();
diff --git a/lib/swr/use-dataroom.ts b/lib/swr/use-dataroom.ts
index 7317858a..27ff95ac 100644
--- a/lib/swr/use-dataroom.ts
+++ b/lib/swr/use-dataroom.ts
@@ -324,14 +324,20 @@ export function useDataroomViewers({ dataroomId }: { dataroomId: string }) {
};
}
-export function useDataroomVisits({ dataroomId }: { dataroomId: string }) {
+export function useDataroomVisits({
+ dataroomId,
+ groupId,
+}: {
+ dataroomId: string;
+ groupId?: string;
+}) {
const teamInfo = useTeam();
const teamId = teamInfo?.currentTeam?.id;
const { data: views, error } = useSWR<any[]>(
teamId &&
dataroomId &&
- `/api/teams/${teamId}/datarooms/${dataroomId}/views`,
+ `/api/teams/${teamId}/datarooms/${dataroomId}${groupId ? `/groups/${groupId}` : ""}/views`,
fetcher,
{
dedupingInterval: 10000,
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/export-visits.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/export-visits.ts
new file mode 100644
index 00000000..7e16fb5c
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/export-visits.ts
@@ -0,0 +1,332 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import prisma from "@/lib/prisma";
+import { getViewPageDuration, getViewUserAgent } from "@/lib/tinybird";
+import { CustomUser } from "@/lib/types";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "GET") {
+ // GET /api/teams/:teamId/datarooms/:id/groups/:groupId/export-visits
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ // get dataroom id and teamId from query params
+ const {
+ teamId,
+ id: dataroomId,
+ groupId,
+ } = req.query as {
+ teamId: string;
+ id: string;
+ groupId: string;
+ };
+
+ const userId = (session.user as CustomUser).id;
+
+ try {
+ // Fetching Team based on team.id
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ select: { plan: true },
+ });
+
+ if (!team) {
+ return res.status(404).end("Team not found");
+ }
+
+ if (team.plan === "free") {
+ return res
+ .status(403)
+ .json({ message: "This feature is not available for your plan" });
+ }
+
+ // Fetching Dataroom based on dataroom.id
+ const dataroom = await prisma.dataroom.findUnique({
+ where: { id: dataroomId, teamId: teamId },
+ select: {
+ id: true,
+ name: true,
+ documents: {
+ select: {
+ id: true,
+ document: {
+ select: {
+ name: true,
+ numPages: true,
+ versions: {
+ orderBy: { createdAt: "desc" },
+ select: {
+ versionNumber: true,
+ createdAt: true,
+ numPages: true,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!dataroom) {
+ return res.status(404).end("Dataroom not found");
+ }
+
+ // First fetch the dataroom views
+ const views = await prisma.view.findMany({
+ where: {
+ dataroomId: dataroomId,
+ groupId: groupId,
+ },
+ include: {
+ link: { select: { name: true } },
+ agreementResponse: {
+ include: {
+ agreement: {
+ select: {
+ name: true,
+ content: true,
+ },
+ },
+ },
+ },
+ document: {
+ select: {
+ id: true,
+ name: true,
+ numPages: true,
+ versions: {
+ orderBy: { createdAt: "desc" },
+ select: {
+ versionNumber: true,
+ createdAt: true,
+ numPages: true,
+ },
+ },
+ },
+ },
+ customFieldResponse: {
+ select: {
+ data: true,
+ },
+ },
+ },
+ orderBy: {
+ viewedAt: "desc",
+ },
+ });
+
+ if (!views || views.length === 0) {
+ return res.status(404).end("Dataroom has no views");
+ }
+
+ // First get all dataroom views
+ const dataroomViews = views.filter(
+ (view) => view.viewType === "DATAROOM_VIEW",
+ );
+
+ // Get all document views for this dataroom
+ const documentViews = views.filter(
+ (view) => view.viewType === "DOCUMENT_VIEW",
+ );
+
+ // For each dataroom view, get its associated document views and build export data
+ const exportData = await Promise.all(
+ dataroomViews.map(async (dataroomView) => {
+ // Find all document views that belong to this dataroom view
+ const associatedDocViews = documentViews.filter(
+ (docView) => docView.dataroomViewId === dataroomView.id,
+ );
+
+ // Get document view details including durations from Tinybird
+ const documentViewDetails = await Promise.all(
+ associatedDocViews.map(async (docView) => {
+ const duration = await getViewPageDuration({
+ documentId: docView.document?.id || "null",
+ viewId: docView.id,
+ since: 0,
+ });
+
+ const relevantVersion = docView.document?.versions.find(
+ (version) => version.createdAt <= docView.viewedAt,
+ );
+
+ const numPages =
+ relevantVersion?.numPages || docView.document?.numPages || 0;
+ const completionRate = numPages
+ ? (duration.data.length / numPages) * 100
+ : 0;
+
+ return {
+ documentName: docView.document?.name || "NaN",
+ viewedAt: docView.viewedAt.toISOString(),
+ downloadedAt: docView.downloadedAt?.toISOString() || "NaN",
+ duration: duration.data.reduce(
+ (total, data) => total + data.sum_duration,
+ 0,
+ ),
+ completionRate: completionRate.toFixed(2) + "%",
+ documentVersion:
+ relevantVersion?.versionNumber ||
+ docView.document?.versions[0]?.versionNumber ||
+ "NaN",
+ };
+ }),
+ );
+
+ // Return the complete view data
+ return {
+ // Dataroom view details
+ dataroomViewedAt: dataroomView.viewedAt.toISOString(),
+ dataroomDownloadedAt:
+ dataroomView.downloadedAt?.toISOString() || "NaN",
+ viewerName: dataroomView.viewerName || "NaN",
+ viewerEmail: dataroomView.viewerEmail || "NaN",
+ linkName: dataroomView.link?.name || "NaN",
+ verified: dataroomView.verified ? "Yes" : "NaN",
+
+ // Agreement details
+ agreementStatus: dataroomView.agreementResponse ? "Yes" : "NaN",
+ agreementName:
+ dataroomView.agreementResponse?.agreement.name || "NaN",
+ agreementAcceptedAt:
+ dataroomView.agreementResponse?.createdAt.toISOString() || "NaN",
+ agreementContent:
+ dataroomView.agreementResponse?.agreement.content || "NaN",
+
+ // Document view details
+ documentViews: documentViewDetails,
+ };
+ }),
+ );
+
+ // Create CSV with nested document views
+ const csvRows: string[] = [];
+
+ // Add headers
+ csvRows.push(
+ [
+ "Dataroom Viewed At",
+ "Dataroom Downloaded At",
+ "Visitor Name",
+ "Visitor Email",
+ "Link Name",
+ "Verified",
+ "Agreement Accepted",
+ "Agreement Name",
+ "Agreement Content",
+ "Agreement Accepted At",
+ "Document Name",
+ "Document Viewed At",
+ "Document Downloaded At",
+ "Total Visit Duration (s)",
+ "Total Document Completion (%)",
+ "Document Version",
+ "Browser",
+ "OS",
+ "Device",
+ "Country",
+ "City",
+ ].join(","),
+ );
+
+ // Get user agent data for all views
+ const userAgentData = await Promise.all(
+ documentViews.map((view) =>
+ getViewUserAgent({
+ documentId: view.document?.id!,
+ viewId: view.id,
+ since: 0,
+ }),
+ ),
+ );
+
+ // Process each view and add to CSV rows
+ exportData.forEach((view) => {
+ if (view.documentViews.length === 0) {
+ // Add a row for dataroom view without document views
+ csvRows.push(
+ [
+ view.dataroomViewedAt,
+ view.dataroomDownloadedAt,
+ view.viewerName,
+ view.viewerEmail,
+ view.linkName,
+ view.verified,
+ view.agreementStatus,
+ view.agreementName,
+ view.agreementContent,
+ view.agreementAcceptedAt,
+ "No documents viewed",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "", // Browser
+ "", // OS
+ "", // Device
+ "", // Country
+ "", // City
+ ].join(","),
+ );
+ } else {
+ // Add a row for each document view
+ view.documentViews.forEach((docView, index) => {
+ csvRows.push(
+ [
+ view.dataroomViewedAt,
+ view.dataroomDownloadedAt,
+ view.viewerName,
+ view.viewerEmail,
+ view.linkName,
+ view.verified,
+ view.agreementStatus,
+ view.agreementName,
+ view.agreementContent,
+ view.agreementAcceptedAt,
+ docView.documentName,
+ docView.viewedAt,
+ docView.downloadedAt,
+ (docView.duration / 1000).toFixed(1),
+ docView.completionRate,
+ docView.documentVersion,
+ userAgentData[index]?.data[0]?.browser || "NaN",
+ userAgentData[index]?.data[0]?.os || "NaN",
+ userAgentData[index]?.data[0]?.device || "NaN",
+ userAgentData[index]?.data[0]?.country || "NaN",
+ userAgentData[index]?.data[0]?.city || "NaN",
+ ].join(","),
+ );
+ });
+ }
+ });
+
+ return res.status(200).json({
+ dataroomName: dataroom.name,
+ visits: csvRows.join("\n"),
+ });
+ } catch (error) {
+ console.error(error);
+ return res.status(500).json({ message: "Something went wrong" });
+ }
+}
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/views/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/views/index.ts
new file mode 100644
index 00000000..0d8caa74
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/views/index.ts
@@ -0,0 +1,127 @@
+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";
+import { log } from "@/lib/utils";
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "GET") {
+ // GET /api/teams/:teamId/datarooms/:id/groups/:groupId/views
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const {
+ teamId,
+ id: dataroomId,
+ groupId,
+ } = req.query as {
+ teamId: string;
+ id: string;
+ groupId: 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",
+ groupId: groupId,
+ },
+ orderBy: {
+ viewedAt: "desc",
+ },
+ include: {
+ link: {
+ select: {
+ name: true,
+ },
+ },
+ agreementResponse: {
+ select: {
+ id: true,
+ agreementId: true,
+ agreement: {
+ 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),
+ };
+ });
+
+ 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]/groups/[groupId]/group-analytic.tsx b/pages/datarooms/[id]/groups/[groupId]/group-analytic.tsx
new file mode 100644
index 00000000..9a6bdf0d
--- /dev/null
+++ b/pages/datarooms/[id]/groups/[groupId]/group-analytic.tsx
@@ -0,0 +1,49 @@
+import { DataroomHeader } from "@/components/datarooms/dataroom-header";
+import { DataroomNavigation } from "@/components/datarooms/dataroom-navigation";
+import { GroupHeader } from "@/components/datarooms/groups/group-header";
+import { GroupNavigation } from "@/components/datarooms/groups/group-navigation";
+import AppLayout from "@/components/layouts/app";
+import DataroomVisitorsTable from "@/components/visitors/dataroom-visitors-table";
+
+import { useDataroom } from "@/lib/swr/use-dataroom";
+import { useDataroomGroup } from "@/lib/swr/use-dataroom-groups";
+
+export default function DataroomGroupPage() {
+ const { dataroom } = useDataroom();
+ const { viewerGroup } = useDataroomGroup();
+
+ if (!dataroom || !viewerGroup) {
+ return <div>Loading...</div>;
+ }
+
+ return (
+ <AppLayout>
+ <div className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
+ <header>
+ <DataroomHeader
+ title={dataroom.name}
+ description={dataroom.pId}
+ actions={[]}
+ />
+
+ <DataroomNavigation dataroomId={dataroom.id} />
+ </header>
+
+ <GroupHeader dataroomId={dataroom.id} groupName={viewerGroup.name} />
+ <div className="mx-auto grid w-full items-start gap-6 md:grid-cols-[180px_1fr] lg:grid-cols-[250px_1fr]">
+ <GroupNavigation
+ dataroomId={dataroom.id}
+ viewerGroupId={viewerGroup?.id!}
+ />
+ <div className="grid gap-6">
+ <DataroomVisitorsTable
+ dataroomId={dataroom.id}
+ groupId={viewerGroup.id}
+ name={viewerGroup.name}
+ />
+ </div>
+ </div>
+ </div>
+ </AppLayout>
+ );
+}