Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: track folder download documents
Marc Seitzbad344f52e41
diff --git a/components/visitors/dataroom-visitors-history.tsx b/components/visitors/dataroom-visitors-history.tsxindex 7424551f..a37f3eb2 100644--- a/components/visitors/dataroom-visitors-history.tsx+++ b/components/visitors/dataroom-visitors-history.tsx@@ -3,6 +3,7 @@ import Link from "next/link";import {DownloadCloudIcon,FileCheckIcon,+ FileIcon,UploadCloudIcon,} from "lucide-react";@@ -10,6 +11,12 @@ import { useDataroomVisitHistory } from "@/lib/swr/use-dataroom";import { timeAgo } from "@/lib/utils";import { Button } from "@/components/ui/button";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import { ScrollArea } from "@/components/ui/scroll-area";import { Skeleton } from "@/components/ui/skeleton";import { TableCell, TableRow } from "@/components/ui/table";@@ -25,99 +32,294 @@ export default function DataroomVisitHistory({dataroomId,});+ // Group bulk and folder downloads together+ const groupedViews = documentViews+ ? documentViews.reduce(+ (acc, view) => {+ if (view.downloadType === "BULK" || view.downloadType === "FOLDER") {+ // Group bulk/folder downloads by type and timestamp+ const key = `${view.downloadType}-${new Date(view.viewedAt).toISOString()}`;+ if (!acc.bulkDownloads[key]) {+ acc.bulkDownloads[key] = {+ type: view.downloadType,+ viewedAt: view.viewedAt,+ downloadedAt: view.downloadedAt,+ metadata: view.downloadMetadata,+ documents: [],+ };+ }+ acc.bulkDownloads[key].documents.push(view);+ } else {+ // Keep individual views+ acc.individualViews.push(view);+ }+ return acc;+ },+ {+ individualViews: [] as typeof documentViews,+ bulkDownloads: {} as Record<+ string,+ {+ type: string;+ viewedAt: string;+ downloadedAt: string;+ metadata?: {+ folderName?: string;+ folderPath?: string;+ dataroomName?: string;+ documentCount?: number;+ documents?: {+ id: string;+ name: string;+ }[];+ };+ documents: typeof documentViews;+ }+ >,+ },+ )+ : { individualViews: [], bulkDownloads: {} };++ // Combine and sort all events chronologically (oldest to newest)+ const allEvents: Array<{+ type: "upload" | "view" | "download" | "bulk-download";+ timestamp: Date;+ data: any;+ }> = [];++ // Add uploads+ uploadedDocumentViews?.forEach((upload) => {+ allEvents.push({+ type: "upload",+ timestamp: new Date(upload.uploadedAt),+ data: upload,+ });+ });++ // Add bulk/folder downloads+ Object.entries(groupedViews.bulkDownloads).forEach(([key, bulkGroup]) => {+ allEvents.push({+ type: "bulk-download",+ timestamp: new Date(bulkGroup.downloadedAt),+ data: bulkGroup,+ });+ });++ // Add individual views+ groupedViews.individualViews.forEach((view) => {+ const viewedAtTime = new Date(view.viewedAt).getTime();+ const downloadedAtTime = view.downloadedAt+ ? new Date(view.downloadedAt).getTime()+ : null;+ const isDownloadOnly =+ downloadedAtTime && Math.abs(viewedAtTime - downloadedAtTime) < 1000;++ // Add view event (if not download-only)+ if (!isDownloadOnly) {+ allEvents.push({+ type: "view",+ timestamp: new Date(view.viewedAt),+ data: view,+ });+ }++ // Add download event (if exists)+ if (view.downloadedAt) {+ allEvents.push({+ type: "download",+ timestamp: new Date(view.downloadedAt),+ data: view,+ });+ }+ });++ // Sort chronologically (oldest to newest)+ allEvents.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());+return (<>- {uploadedDocumentViews &&- uploadedDocumentViews.length > 0 &&- uploadedDocumentViews.map((upload) => (- <TableRow key={`${upload.documentId}-upload`}>- <TableCell>- <div className="flex items-center gap-x-4 overflow-visible">- <UploadCloudIcon className="h-5 w-5 text-[#fb7a00]" />- Uploaded {upload.originalFilename}- </div>- </TableCell>-- <TableCell>- <div>- <time- className="truncate text-sm text-muted-foreground"- dateTime={new Date(upload.uploadedAt).toISOString()}- title={new Date(upload.uploadedAt).toLocaleString()}- >- {timeAgo(new Date(upload.uploadedAt))}- </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/${upload.documentId}`}>- See document- </Link>- </Button>- </div>- </TableCell>- </TableRow>- ))}- {documentViews ? (- documentViews.map((view) => (- <>- {/* Show viewed row */}- <TableRow key={`${view.id}-viewed`}>- <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>+ {allEvents.length > 0 ? (+ allEvents.map((event, index) => {+ if (event.type === "upload") {+ const upload = event.data;+ return (+ <TableRow key={`upload-${upload.documentId}-${index}`}>+ <TableCell>+ <div className="flex items-center gap-x-4 overflow-visible">+ <UploadCloudIcon className="h-5 w-5 text-[#fb7a00]" />+ Uploaded {upload.originalFilename}+ </div>+ </TableCell>+ <TableCell><timeclassName="truncate text-sm text-muted-foreground"- dateTime={new Date(view.viewedAt).toISOString()}- title={new Date(view.viewedAt).toLocaleString()}+ dateTime={event.timestamp.toISOString()}+ title={event.timestamp.toLocaleString()}>- {timeAgo(new Date(view.viewedAt))}+ {timeAgo(event.timestamp)}</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>-- {/* Show downloaded row if downloadedAt exists */}- {view.downloadedAt && (- <TableRow key={`${view.id}-downloaded`}>+ </TableCell>+ <TableCell className="table-cell">+ <div className="flex items-center justify-end space-x-4">+ <Button size={"sm"} variant={"link"}>+ <Link href={`/documents/${upload.documentId}`}>+ See document+ </Link>+ </Button>+ </div>+ </TableCell>+ </TableRow>+ );+ }++ if (event.type === "bulk-download") {+ const bulkGroup = event.data;+ const documentCount =+ bulkGroup.metadata?.documentCount || bulkGroup.documents.length;+ const hasDocumentList =+ bulkGroup.metadata?.documents &&+ bulkGroup.metadata.documents.length > 0;++ return (+ <TableRow key={`bulk-${index}`}><TableCell><div className="flex items-center gap-x-4 overflow-visible"><DownloadCloudIcon className="h-5 w-5 text-[#fb7a00]" />- Downloaded {view.document.name}+ <span>+ Downloaded{" "}+ {hasDocumentList ? (+ <Popover>+ <PopoverTrigger asChild>+ <button className="underline decoration-dotted hover:text-primary">+ {documentCount} document+ {documentCount !== 1 ? "s" : ""}+ </button>+ </PopoverTrigger>+ <PopoverContent className="w-80">+ <div className="space-y-2">+ <h4 className="font-medium leading-none">+ {bulkGroup.type === "FOLDER" &&+ bulkGroup.metadata?.folderName+ ? `Files in ${bulkGroup.metadata.folderName}`+ : `Files in ${bulkGroup.metadata?.dataroomName || "dataroom"}`}+ </h4>+ <ScrollArea className="h-[200px] w-full rounded-md border p-2">+ <div className="space-y-1">+ {bulkGroup.metadata.documents!.map(+ (doc: { id: string; name: string }) => (+ <div+ key={doc.id}+ className="flex items-center gap-2 text-sm"+ >+ <FileIcon className="h-4 w-4 text-muted-foreground" />+ <span className="truncate">+ {doc.name}+ </span>+ </div>+ ),+ )}+ </div>+ </ScrollArea>+ </div>+ </PopoverContent>+ </Popover>+ ) : (+ <>+ {documentCount} document+ {documentCount !== 1 ? "s" : ""}+ </>+ )}{" "}+ {bulkGroup.type === "FOLDER" &&+ bulkGroup.metadata?.folderName ? (+ <>+ from folder{" "}+ <span className="font-medium">+ {bulkGroup.metadata.folderName}+ </span>+ </>+ ) : bulkGroup.type === "BULK" &&+ bulkGroup.metadata?.dataroomName ? (+ <>+ from{" "}+ <span className="font-medium">+ {bulkGroup.metadata.dataroomName}+ </span>{" "}+ dataroom+ </>+ ) : (+ "via bulk download"+ )}+ </span>+ </div>+ </TableCell>+ <TableCell>+ <time+ className="truncate text-sm text-muted-foreground"+ dateTime={event.timestamp.toISOString()}+ title={event.timestamp.toLocaleString()}+ >+ {timeAgo(event.timestamp)}+ </time>+ </TableCell>+ <TableCell className="table-cell"></TableCell>+ </TableRow>+ );+ }++ if (event.type === "view") {+ const view = event.data;+ return (+ <TableRow key={`view-${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>+ <time+ className="truncate text-sm text-muted-foreground"+ dateTime={event.timestamp.toISOString()}+ title={event.timestamp.toLocaleString()}+ >+ {timeAgo(event.timestamp)}+ </time>+ </TableCell>+ <TableCell className="table-cell">+ <div className="flex items-center justify-end space-x-4">+ <Button size={"sm"} variant={"link"}>+ <Link href={`/documents/${view.document.id}`}>+ See document+ </Link>+ </Button>+ </div>+ </TableCell>+ </TableRow>+ );+ }+ if (event.type === "download") {+ const view = event.data;+ return (+ <TableRow key={`download-${view.id}`}><TableCell>- <div>- <time- className="truncate text-sm text-muted-foreground"- dateTime={new Date(view.downloadedAt).toISOString()}- title={new Date(view.downloadedAt).toLocaleString()}- >- {timeAgo(new Date(view.downloadedAt))}- </time>+ <div className="flex items-center gap-x-4 overflow-visible">+ <DownloadCloudIcon className="h-5 w-5 text-[#fb7a00]" />+ Downloaded {view.document.name}</div></TableCell>+ <TableCell>+ <time+ className="truncate text-sm text-muted-foreground"+ dateTime={event.timestamp.toISOString()}+ title={event.timestamp.toLocaleString()}+ >+ {timeAgo(event.timestamp)}+ </time>+ </TableCell><TableCell className="table-cell"><div className="flex items-center justify-end space-x-4">- <Button size={"sm"} variant={"link"} className="">+ <Button size={"sm"} variant={"link"}><Link href={`/documents/${view.document.id}`}>See document</Link>@@ -125,10 +327,12 @@ export default function DataroomVisitHistory({</div></TableCell></TableRow>- )}- </>- ))- ) : (+ );+ }++ return null;+ })+ ) : documentViews === undefined ? (<TableRow><TableCell><Skeleton className="h-6 w-24" />@@ -137,7 +341,7 @@ export default function DataroomVisitHistory({<Skeleton className="h-6 w-16" /></TableCell></TableRow>- )}+ ) : null}</>);}diff --git a/components/visitors/visitor-chart.tsx b/components/visitors/visitor-chart.tsxindex 4aaaca59..303bb75b 100644--- a/components/visitors/visitor-chart.tsx+++ b/components/visitors/visitor-chart.tsx@@ -1,5 +1,7 @@import ErrorPage from "next/error";+import { DownloadCloudIcon } from "lucide-react";+import BarChartComponent from "@/components/charts/bar-chart";import { useVisitorStats } from "@/lib/swr/use-stats";@@ -11,11 +13,24 @@ export default function VisitorChart({viewId,totalPages = 0,versionNumber,+ downloadType,+ downloadMetadata,}: {documentId: string;viewId: string;totalPages?: number;versionNumber?: number;+ downloadType?: "SINGLE" | "BULK" | "FOLDER" | null;+ downloadMetadata?: {+ folderName?: string;+ folderPath?: string;+ dataroomName?: string;+ documentCount?: number;+ documents?: {+ id: string;+ name: string;+ }[];+ } | null;}) {const { stats, error } = useVisitorStats(viewId);@@ -27,6 +42,35 @@ export default function VisitorChart({return <StatsChartSkeleton />;}+ // Check if this is a download-only view (no pages viewed)+ const hasViewData = stats.duration.data.some(+ (item) => item.sum_duration > 0,+ );++ // If no view data and it's a download (any type), show a message instead of the graph+ if (!hasViewData && downloadType) {+ let downloadMessage = "";++ if (downloadType === "FOLDER" && downloadMetadata?.folderName) {+ downloadMessage = `Downloaded without viewing via dataroom folder "${downloadMetadata.folderName}"`;+ } else if (downloadType === "BULK" && downloadMetadata?.dataroomName) {+ downloadMessage = `Downloaded without viewing via bulk download from "${downloadMetadata.dataroomName}" dataroom`;+ } else if (downloadType === "BULK") {+ downloadMessage = "Downloaded without viewing via bulk dataroom download";+ } else if (downloadType === "SINGLE") {+ downloadMessage = "Downloaded without viewing";+ }++ return (+ <div className="rounded-bl-lg border-b border-l p-4">+ <div className="flex items-center gap-2 text-sm text-muted-foreground">+ <DownloadCloudIcon className="h-4 w-4" />+ <span>{downloadMessage}</span>+ </div>+ </div>+ );+ }+let durationData = Array.from({ length: totalPages }, (_, i) => ({pageNumber: (i + 1).toString(),sum_duration: 0,diff --git a/components/visitors/visitors-table.tsx b/components/visitors/visitors-table.tsxindex a49b2d23..b00d3169 100644--- a/components/visitors/visitors-table.tsx+++ b/components/visitors/visitors-table.tsx@@ -438,6 +438,8 @@ export default function VisitorsTable({viewId={view.id}totalPages={view.versionNumPages}versionNumber={view.versionNumber}+ downloadType={view.downloadType}+ downloadMetadata={view.downloadMetadata as any}/>)}{!isFreePlan && primaryVersion.type === "pdf" ? (diff --git a/lib/swr/use-dataroom.ts b/lib/swr/use-dataroom.tsindex fc7e2576..cfb5a533 100644--- a/lib/swr/use-dataroom.ts+++ b/lib/swr/use-dataroom.ts@@ -373,6 +373,17 @@ type DataroomDocumentViewHistory = {id: string;downloadedAt: string;viewedAt: string;+ downloadType?: "SINGLE" | "BULK" | "FOLDER";+ downloadMetadata?: {+ folderName?: string;+ folderPath?: string;+ dataroomName?: string;+ documentCount?: number;+ documents?: {+ id: string;+ name: string;+ }[];+ };document: {id: string;name: string;diff --git a/pages/api/links/download/bulk.ts b/pages/api/links/download/bulk.tsindex dc3362a4..0f8f2651 100644--- a/pages/api/links/download/bulk.ts+++ b/pages/api/links/download/bulk.ts@@ -33,6 +33,8 @@ export default async function handle(id: true,viewedAt: true,viewerEmail: true,+ viewerId: true,+ verified: true,link: {select: {allowDownload: true,@@ -49,6 +51,7 @@ export default async function handle(dataroom: {select: {id: true,+ name: true,teamId: true,allowBulkDownload: true,folders: {@@ -64,6 +67,7 @@ export default async function handle(folderId: true,document: {select: {+ id: true,name: true,versions: {where: { isPrimary: true },@@ -174,10 +178,49 @@ export default async function handle();}- // update the view with the downloadedAt timestamp- await prisma.view.update({- where: { id: viewId },- data: { downloadedAt: new Date() },+ // Don't update DATAROOM_VIEW downloadedAt - we'll show the grouped bulk download entry instead++ // Create individual document views for each document being downloaded+ const downloadableDocuments = downloadDocuments.filter(+ (doc) =>+ doc.document.versions[0] &&+ doc.document.versions[0].type !== "notion" &&+ doc.document.versions[0].storageType !== "VERCEL_BLOB",+ );++ // For bulk downloads, only store metadata if there are less than 100 documents+ // to avoid storing huge JSON objects+ const downloadMetadata =+ downloadableDocuments.length < 100+ ? {+ dataroomName: view.dataroom!.name,+ documentCount: downloadableDocuments.length,+ documents: downloadableDocuments.map((doc) => ({+ id: doc.document.id,+ name: doc.document.name,+ })),+ }+ : {+ dataroomName: view.dataroom!.name,+ documentCount: downloadableDocuments.length,+ };++ await prisma.view.createMany({+ data: downloadableDocuments.map((doc) => ({+ viewType: "DOCUMENT_VIEW",+ documentId: doc.document.id,+ linkId: linkId,+ dataroomId: view.dataroom!.id,+ groupId: view.groupId,+ dataroomViewId: view.id,+ viewerEmail: view.viewerEmail,+ downloadedAt: new Date(),+ downloadType: "BULK",+ downloadMetadata: downloadMetadata,+ viewerId: view.viewerId,+ verified: view.verified,+ })),+ skipDuplicates: true,});// Construct folderStructure and fileKeys@@ -318,7 +361,7 @@ export default async function handle(dataroomId: view.dataroom.id,linkId,viewerEmail: view.viewerEmail ?? undefined,- viewerId: undefined,+ viewerId: view.viewerId ?? undefined,metadata: {documentCount: downloadDocuments.length,isBulkDownload: true,diff --git a/pages/api/links/download/dataroom-document.ts b/pages/api/links/download/dataroom-document.tsindex 774d9f89..f9771609 100644--- a/pages/api/links/download/dataroom-document.ts+++ b/pages/api/links/download/dataroom-document.ts@@ -169,6 +169,7 @@ export default async function handle(dataroomViewId: view.id,viewerEmail: view.viewerEmail,downloadedAt: new Date(),+ downloadType: "SINGLE",viewerId: view.viewerId,verified: view.verified,},diff --git a/pages/api/links/download/dataroom-folder.ts b/pages/api/links/download/dataroom-folder.tsindex abc15c03..a0a7f04a 100644--- a/pages/api/links/download/dataroom-folder.ts+++ b/pages/api/links/download/dataroom-folder.ts@@ -46,6 +46,8 @@ export default async function handler(id: true,viewedAt: true,viewerEmail: true,+ viewerId: true,+ verified: true,link: {select: {teamId: true,@@ -129,6 +131,7 @@ export default async function handler(folderId: true,document: {select: {+ id: true,name: true,versions: {where: { isPrimary: true },@@ -302,6 +305,45 @@ export default async function handler(};}+ // Don't update the DATAROOM_VIEW with downloadedAt for folder downloads+ // Only bulk downloads should update the DATAROOM_VIEW++ // Create individual document views for each document in the folder+ const downloadableDocuments = allDocuments.filter(+ (doc) =>+ doc.document.versions[0] &&+ doc.document.versions[0].type !== "notion" &&+ doc.document.versions[0].storageType !== "VERCEL_BLOB",+ );++ // Prepare metadata with folder name and document list+ const downloadMetadata = {+ folderName: rootFolder.name,+ folderPath: rootFolder.path,+ documents: downloadableDocuments.map((doc) => ({+ id: doc.document.id,+ name: doc.document.name,+ })),+ };++ await prisma.view.createMany({+ data: downloadableDocuments.map((doc) => ({+ viewType: "DOCUMENT_VIEW",+ documentId: doc.document.id,+ linkId: linkId,+ dataroomId: dataroomId,+ groupId: view.groupId,+ dataroomViewId: view.id,+ viewerEmail: view.viewerEmail,+ downloadedAt: new Date(),+ downloadType: "FOLDER",+ downloadMetadata: downloadMetadata,+ viewerId: view.viewerId,+ verified: view.verified,+ })),+ skipDuplicates: true,+ });+if (view.link.teamId) {void notifyDocumentDownload({teamId: view.link.teamId,@@ -309,7 +351,7 @@ export default async function handler(dataroomId,linkId,viewerEmail: view.viewerEmail ?? undefined,- viewerId: undefined,+ viewerId: view.viewerId ?? undefined,metadata: {folderName: rootFolder.name,documentCount: allDocuments.length,diff --git a/pages/api/teams/[teamId]/datarooms/[id]/views/[viewId]/history.ts b/pages/api/teams/[teamId]/datarooms/[id]/views/[viewId]/history.tsindex f471e6b0..b26399d4 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/views/[viewId]/history.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/views/[viewId]/history.ts@@ -63,6 +63,8 @@ export default async function handle(id: true,viewedAt: true,downloadedAt: true,+ downloadType: true,+ downloadMetadata: true,document: {select: {id: true,diff --git a/prisma/migrations/20250106000000_add_download_type/migration.sql b/prisma/migrations/20250106000000_add_download_type/migration.sqlnew file mode 100644index 00000000..68542bfb--- /dev/null+++ b/prisma/migrations/20250106000000_add_download_type/migration.sql@@ -0,0 +1,7 @@+-- CreateEnum+CREATE TYPE "DownloadType" AS ENUM ('SINGLE', 'BULK', 'FOLDER');++-- AlterTable+ALTER TABLE "View" ADD COLUMN "downloadType" "DownloadType";+ALTER TABLE "View" ADD COLUMN "downloadMetadata" JSONB;+diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prismaindex 309074fc..6e6f1715 100644--- a/prisma/schema/schema.prisma+++ b/prisma/schema/schema.prisma@@ -124,6 +124,8 @@ model View {verified Boolean @default(false) // Whether the viewer email has been verifiedviewedAt DateTime @default(now())downloadedAt DateTime? // This is the time the document was downloaded+ downloadType DownloadType? // Type of download: SINGLE, BULK, or FOLDER+ downloadMetadata Json? // Metadata about the download (folder name, document list, etc.)reactions Reaction[]viewType ViewType @default(DOCUMENT_VIEW)viewerId String? // This is the viewer ID from the dataroom@@ -165,6 +167,12 @@ enum ViewType {DATAROOM_VIEW}+enum DownloadType {+ SINGLE // Individual document download+ BULK // Full dataroom bulk download+ FOLDER // Folder download+}+model Viewer {id String @id @default(cuid())email String