Skip to content

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

feat: add export function and download option

Marc Seitz71fdf2e3bade
diff --git a/components/datarooms/export-visits-modal.tsx b/components/datarooms/export-visits-modal.tsx
new file mode 100644
index 00000000..1e9e8b3e
--- /dev/null
+++ b/components/datarooms/export-visits-modal.tsx
@@ -0,0 +1,289 @@
+import { useEffect, useRef, useState } from "react";
+
+import { useSession } from "next-auth/react";
+import { toast } from "sonner";
+
+interface ExportStatus {
+ status: string;
+ progress?: string;
+ exportId?: string;
+ startTime?: number;
+}
+
+interface ExportVisitsModalProps {
+ dataroomId: string;
+ dataroomName: string;
+ teamId: string;
+ groupId?: string;
+ groupName?: string;
+ isVisible: boolean;
+ onClose: () => void;
+}
+
+export function ExportVisitsModal({
+ dataroomId,
+ dataroomName,
+ teamId,
+ groupId,
+ groupName,
+ isVisible,
+ onClose,
+}: ExportVisitsModalProps) {
+ const { data: session } = useSession();
+ const [exportStatus, setExportStatus] = useState<ExportStatus | null>(null);
+ const [showModal, setShowModal] = useState(false);
+ const [viewCount, setViewCount] = useState<number | null>(null);
+ const pollIntervalRef = useRef<NodeJS.Timeout | null>(null);
+
+ // Cleanup interval on component unmount
+ useEffect(() => {
+ return () => {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ }
+ };
+ }, []);
+
+ // Start export when component becomes visible
+ useEffect(() => {
+ if (isVisible) {
+ startExport();
+ }
+ }, [isVisible]);
+
+ const startExport = async () => {
+ try {
+ // Show modal immediately
+ setShowModal(true);
+
+ // Get view count first
+ try {
+ const viewCountResponse = await fetch(
+ `/api/teams/${teamId}/datarooms/${dataroomId}/views-count${groupId ? `?groupId=${groupId}` : ""}`,
+ { method: "GET" },
+ );
+
+ if (viewCountResponse.ok) {
+ const viewData = await viewCountResponse.json();
+ setViewCount(viewData.count || 0);
+ }
+ } catch (error) {
+ console.error("Error fetching view count:", error);
+ // Continue with export even if view count fails
+ }
+
+ // Trigger the background export job
+ const response = await fetch(
+ `/api/teams/${teamId}/datarooms/${dataroomId}${groupId ? `/groups/${groupId}` : ""}/export-visits`,
+ { method: "POST" },
+ );
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+ const data = await response.json();
+
+ if (data.exportId) {
+ const startTime = Date.now();
+ setExportStatus({
+ status: "PROCESSING",
+ exportId: data.exportId,
+ startTime,
+ });
+
+ // Clear any existing interval
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ }
+
+ // Start polling
+ pollIntervalRef.current = setInterval(async () => {
+ try {
+ const statusResponse = await fetch(
+ `/api/teams/${teamId}/export-jobs/${data.exportId}`,
+ { method: "GET" },
+ );
+
+ if (statusResponse.ok) {
+ const statusData = await statusResponse.json();
+
+ // Update progress
+ setExportStatus((prev) => ({
+ ...prev!,
+ progress: "Preparing export...",
+ }));
+
+ if (statusData.status === "COMPLETED" && statusData.isReady) {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+
+ // Create a direct link to the API endpoint (it will redirect to blob)
+ const downloadUrl = `/api/teams/${teamId}/export-jobs/${data.exportId}?download=true`;
+ const link = window.document.createElement("a");
+ link.href = downloadUrl;
+ link.setAttribute(
+ "download",
+ `${statusData.resourceName || dataroomName}_${groupName ? `${groupName}_` : ""}visits_${new Date().toISOString().split("T")[0]}.csv`,
+ );
+ link.rel = "noopener noreferrer";
+ link.style.display = "none";
+
+ window.document.body.appendChild(link);
+ link.click();
+ window.document.body.removeChild(link);
+
+ handleClose();
+ toast.success("Export successfully downloaded");
+ } else if (statusData.status === "FAILED") {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+ handleClose();
+ toast.error(
+ `Export failed: ${statusData.error || "Unknown error"}`,
+ );
+ }
+ }
+ } catch (error) {
+ console.error("Error polling export status:", error);
+ }
+ }, 3000); // Poll every 3 seconds
+
+ // Clear interval after 10 minutes to prevent indefinite polling
+ setTimeout(() => {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+ handleClose();
+ }, 600000);
+ }
+ } catch (error) {
+ console.error("Error:", error);
+ toast.error(
+ "An error occurred while starting the export. Please try again.",
+ );
+ onClose();
+ }
+ };
+
+ // Send export via email
+ const sendExportEmail = async () => {
+ if (!exportStatus?.exportId || !session?.user?.email) return;
+
+ try {
+ const response = await fetch(
+ `/api/teams/${teamId}/export-jobs/${exportStatus.exportId}/send-email`,
+ { method: "POST" },
+ );
+
+ if (response.ok) {
+ toast.success("Export will be sent to your email when ready");
+ handleClose();
+ } else {
+ toast.error("Failed to setup email notification");
+ }
+ } catch (error) {
+ console.error("Error sending email:", error);
+ toast.error("Failed to setup email notification");
+ }
+ };
+
+ // Handle close - cleanup and call parent onClose
+ const handleClose = () => {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+ setShowModal(false);
+ setExportStatus(null);
+ onClose();
+ };
+
+ // Don't render anything if not visible and no modal to show
+ if (!isVisible && !showModal) {
+ return null;
+ }
+
+ // Only show modal if it should be visible
+ if (!showModal) {
+ return null;
+ }
+
+ const displayName = groupName
+ ? `${dataroomName} - ${groupName}`
+ : dataroomName;
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
+ <div className="mx-4 w-full max-w-md rounded-lg bg-white p-6">
+ <div className="mb-4 flex items-center justify-between">
+ <h3 className="text-lg font-semibold">Export Visits</h3>
+ <button
+ onClick={handleClose}
+ className="text-gray-400 hover:text-gray-600"
+ >
+ <svg
+ className="h-5 w-5"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M6 18L18 6M6 6l12 12"
+ />
+ </svg>
+ </button>
+ </div>
+
+ <div className="space-y-4">
+ <div className="flex items-center space-x-2">
+ <div className="h-4 w-4 animate-spin rounded-full border-b-2 border-muted-foreground"></div>
+ <span className="text-sm text-gray-600">
+ {exportStatus?.progress || "Processing export..."}
+ </span>
+ </div>
+
+ <div className="text-sm text-gray-600">
+ Exporting visits for: {displayName}
+ </div>
+
+ {viewCount !== null && (
+ <div className="text-sm text-gray-600">
+ Found {viewCount} visit{viewCount !== 1 ? "s" : ""} to export
+ </div>
+ )}
+
+ {viewCount !== null && viewCount > 10 && session?.user?.email && (
+ <div className="rounded-md bg-gray-50 p-3 text-sm dark:bg-gray-900">
+ <p className="mb-2 font-medium text-muted-foreground">
+ Large export detected ({viewCount} visits)
+ </p>
+ <p className="mb-3 text-muted-foreground">
+ This export may take several minutes. We recommend getting it
+ emailed to you when ready.
+ </p>
+ <button
+ onClick={sendExportEmail}
+ className="w-full rounded-md bg-primary px-4 py-2 text-primary-foreground transition-colors hover:bg-primary/80"
+ >
+ Email to {session.user.email}
+ </button>
+ </div>
+ )}
+
+ {(!viewCount || viewCount <= 10) && (
+ <div className="text-sm text-gray-500">
+ Your export will be ready shortly...
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/components/documents/document-header.tsx b/components/documents/document-header.tsx
index 000bb66b..62d4ae69 100644
--- a/components/documents/document-header.tsx
+++ b/components/documents/document-header.tsx
@@ -65,6 +65,7 @@ import { ButtonTooltip } from "../ui/tooltip";
import { AddDocumentModal } from "./add-document-modal";
import { AddToDataroomModal } from "./add-document-to-dataroom-modal";
import AlertBanner from "./alert";
+import { ExportVisitsModal } from "./export-visits-modal";
export default function DocumentHeader({
prismaDocument,
@@ -94,6 +95,7 @@ export default function DocumentHeader({
const [planModalOpen, setPlanModalOpen] = useState<boolean>(false);
const [planModalTrigger, setPlanModalTrigger] = useState<string>("");
const [selectedPlan, setSelectedPlan] = useState<PlanEnum>(PlanEnum.Pro);
+ const [exportModalOpen, setExportModalOpen] = useState<boolean>(false);
const nameRef = useRef<HTMLHeadingElement>(null);
const enterPressedRef = useRef<boolean>(false);
const dropdownRef = useRef<HTMLDivElement | null>(null);
@@ -315,89 +317,12 @@ export default function DocumentHeader({
};
// export method to fetch the visits data and convert to csv.
- const exportVisitCounts = async (document: Document) => {
+ const exportVisitCounts = (document: Document) => {
if (isFree) {
toast.error("This feature is not available for your plan");
return;
}
-
- try {
- // Trigger the background export job
- const response = await fetch(
- `/api/teams/${teamId}/documents/${document.id}/export-visits`,
- { method: "POST" },
- );
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
- const data = await response.json();
-
- if (data.exportId) {
- toast.success("Export job started. You'll be notified when it's ready.");
-
- // Poll for export completion
- const pollInterval = setInterval(async () => {
- try {
- const statusResponse = await fetch(
- `/api/teams/${teamId}/export-jobs/${data.exportId}`,
- { method: "GET" },
- );
-
- if (statusResponse.ok) {
- const statusData = await statusResponse.json();
-
- if (statusData.status === "COMPLETED" && statusData.isReady) {
- clearInterval(pollInterval);
-
- // Download the CSV file
- const downloadResponse = await fetch(
- `/api/teams/${teamId}/export-jobs/${data.exportId}?download=true`,
- { method: "GET" },
- );
-
- if (downloadResponse.ok) {
- const blob = await downloadResponse.blob();
- const url = window.URL.createObjectURL(blob);
- const link = window.document.createElement("a");
- link.href = url;
- link.setAttribute(
- "download",
- `${statusData.resourceName}_visits_${formattedTime}.csv`,
- );
- link.rel = "noopener noreferrer";
- window.document.body.appendChild(link);
- link.click();
-
- setTimeout(() => {
- window.URL.revokeObjectURL(url);
- window.document.body.removeChild(link);
- }, 100);
-
- toast.success("CSV file downloaded successfully");
- } else {
- toast.error("Failed to download the export file");
- }
- } else if (statusData.status === "FAILED") {
- clearInterval(pollInterval);
- toast.error(`Export failed: ${statusData.error || "Unknown error"}`);
- }
- }
- } catch (error) {
- console.error("Error polling export status:", error);
- }
- }, 3000); // Poll every 3 seconds
-
- // Clear interval after 5 minutes to prevent indefinite polling
- setTimeout(() => {
- clearInterval(pollInterval);
- }, 300000);
- }
- } catch (error) {
- console.error("Error:", error);
- toast.error(
- "An error occurred while starting the export. Please try again.",
- );
- }
+ setExportModalOpen(true);
};
// Make a document download only or viewable
@@ -1041,6 +966,13 @@ export default function DocumentHeader({
setOpen={setPlanModalOpen}
/>
) : null}
+
+ <ExportVisitsModal
+ document={prismaDocument}
+ teamId={teamId}
+ isVisible={exportModalOpen}
+ onClose={() => setExportModalOpen(false)}
+ />
</header>
);
}
diff --git a/components/documents/export-visits-modal.tsx b/components/documents/export-visits-modal.tsx
new file mode 100644
index 00000000..19710451
--- /dev/null
+++ b/components/documents/export-visits-modal.tsx
@@ -0,0 +1,276 @@
+import { useEffect, useRef, useState } from "react";
+
+import { Document } from "@prisma/client";
+import { useSession } from "next-auth/react";
+import { toast } from "sonner";
+
+interface ExportStatus {
+ status: string;
+ progress?: string;
+ exportId?: string;
+ startTime?: number;
+}
+
+interface ExportVisitsModalProps {
+ document: Document;
+ teamId: string;
+ isVisible: boolean;
+ onClose: () => void;
+}
+
+export function ExportVisitsModal({
+ document,
+ teamId,
+ isVisible,
+ onClose,
+}: ExportVisitsModalProps) {
+ const { data: session } = useSession();
+ const [exportStatus, setExportStatus] = useState<ExportStatus | null>(null);
+ const [showModal, setShowModal] = useState(false);
+ const [viewCount, setViewCount] = useState<number | null>(null);
+ const pollIntervalRef = useRef<NodeJS.Timeout | null>(null);
+
+ // Cleanup interval on component unmount
+ useEffect(() => {
+ return () => {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ }
+ };
+ }, []);
+
+ // Start export when component becomes visible
+ useEffect(() => {
+ if (isVisible) {
+ startExport();
+ }
+ }, [isVisible]);
+
+ const startExport = async () => {
+ try {
+ // Show modal immediately
+ setShowModal(true);
+
+ // Get view count first
+ try {
+ const viewCountResponse = await fetch(
+ `/api/teams/${teamId}/documents/${document.id}/views-count`,
+ { method: "GET" },
+ );
+
+ if (viewCountResponse.ok) {
+ const viewData = await viewCountResponse.json();
+ setViewCount(viewData.count || 0);
+ }
+ } catch (error) {
+ console.error("Error fetching view count:", error);
+ // Continue with export even if view count fails
+ }
+
+ // Trigger the background export job
+ const response = await fetch(
+ `/api/teams/${teamId}/documents/${document.id}/export-visits`,
+ { method: "POST" },
+ );
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+ const data = await response.json();
+
+ if (data.exportId) {
+ const startTime = Date.now();
+ setExportStatus({
+ status: "PROCESSING",
+ exportId: data.exportId,
+ startTime,
+ });
+
+ // Clear any existing interval
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ }
+
+ // Start polling
+ pollIntervalRef.current = setInterval(async () => {
+ try {
+ const statusResponse = await fetch(
+ `/api/teams/${teamId}/export-jobs/${data.exportId}`,
+ { method: "GET" },
+ );
+
+ if (statusResponse.ok) {
+ const statusData = await statusResponse.json();
+
+ // Update progress
+ setExportStatus((prev) => ({
+ ...prev!,
+ progress: "Preparing export...",
+ }));
+
+ if (statusData.status === "COMPLETED" && statusData.isReady) {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+
+ // Create a direct link to the API endpoint (it will redirect to blob)
+ const downloadUrl = `/api/teams/${teamId}/export-jobs/${data.exportId}?download=true`;
+ const link = window.document.createElement("a");
+ link.href = downloadUrl;
+ link.setAttribute(
+ "download",
+ `${statusData.resourceName || document.name}_visits_${new Date().toISOString().split("T")[0]}.csv`,
+ );
+ link.rel = "noopener noreferrer";
+ link.style.display = "none";
+
+ window.document.body.appendChild(link);
+ link.click();
+ window.document.body.removeChild(link);
+
+ handleClose();
+ toast.success("Export successfully downloaded");
+ } else if (statusData.status === "FAILED") {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+ handleClose();
+ toast.error(
+ `Export failed: ${statusData.error || "Unknown error"}`,
+ );
+ }
+ }
+ } catch (error) {
+ console.error("Error polling export status:", error);
+ }
+ }, 3000); // Poll every 3 seconds
+
+ // Clear interval after 10 minutes to prevent indefinite polling
+ setTimeout(() => {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+ handleClose();
+ }, 600000);
+ }
+ } catch (error) {
+ console.error("Error:", error);
+ toast.error(
+ "An error occurred while starting the export. Please try again.",
+ );
+ onClose();
+ }
+ };
+
+ // Send export via email
+ const sendExportEmail = async () => {
+ if (!exportStatus?.exportId || !session?.user?.email) return;
+
+ try {
+ const response = await fetch(
+ `/api/teams/${teamId}/export-jobs/${exportStatus.exportId}/send-email`,
+ { method: "POST" },
+ );
+
+ if (response.ok) {
+ toast.success("Export will be sent to your email when ready");
+ handleClose();
+ } else {
+ toast.error("Failed to setup email notification");
+ }
+ } catch (error) {
+ console.error("Error sending email:", error);
+ toast.error("Failed to setup email notification");
+ }
+ };
+
+ // Handle close - cleanup and call parent onClose
+ const handleClose = () => {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+ setShowModal(false);
+ setExportStatus(null);
+ onClose();
+ };
+
+ // Don't render anything if not visible and no modal to show
+ if (!isVisible && !showModal) {
+ return null;
+ }
+
+ // Only show modal if it should be visible
+ if (!showModal) {
+ return null;
+ }
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
+ <div className="mx-4 w-full max-w-md rounded-lg bg-white p-6">
+ <div className="mb-4 flex items-center justify-between">
+ <h3 className="text-lg font-semibold">Export Visits</h3>
+ <button
+ onClick={handleClose}
+ className="text-gray-400 hover:text-gray-600"
+ >
+ <svg
+ className="h-5 w-5"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M6 18L18 6M6 6l12 12"
+ />
+ </svg>
+ </button>
+ </div>
+
+ <div className="space-y-4">
+ <div className="flex items-center space-x-2">
+ <div className="h-4 w-4 animate-spin rounded-full border-b-2 border-muted-foreground"></div>
+ <span className="text-sm text-gray-600">
+ {exportStatus?.progress || "Processing export..."}
+ </span>
+ </div>
+
+ {viewCount !== null && (
+ <div className="text-sm text-gray-600">
+ Found {viewCount} view{viewCount !== 1 ? "s" : ""} to export
+ </div>
+ )}
+
+ {viewCount !== null && viewCount > 10 && session?.user?.email && (
+ <div className="rounded-md bg-gray-50 p-3 text-sm dark:bg-gray-900">
+ <p className="mb-2 font-medium text-muted-foreground">
+ Large export detected ({viewCount} views)
+ </p>
+ <p className="mb-3 text-muted-foreground">
+ This export may take several minutes. We recommend getting it
+ emailed to you when ready.
+ </p>
+ <button
+ onClick={sendExportEmail}
+ className="w-full rounded-md bg-primary px-4 py-2 text-primary-foreground transition-colors hover:bg-primary/80"
+ >
+ Email to {session.user.email}
+ </button>
+ </div>
+ )}
+
+ {(!viewCount || viewCount <= 10) && (
+ <div className="text-sm text-gray-500">
+ Your export will be ready shortly...
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/components/emails/export-ready.tsx b/components/emails/export-ready.tsx
new file mode 100644
index 00000000..68c958db
--- /dev/null
+++ b/components/emails/export-ready.tsx
@@ -0,0 +1,90 @@
+import {
+ Body,
+ Button,
+ Container,
+ Head,
+ Heading,
+ Hr,
+ Html,
+ Img,
+ Link,
+ Preview,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+
+export default function ExportReady({
+ resourceName = "Export",
+ downloadUrl,
+ email,
+}: {
+ resourceName?: string;
+ downloadUrl: string;
+ email: string;
+}) {
+ return (
+ <Html>
+ <Head />
+ <Preview>Your {resourceName} export is ready for download</Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-10 w-[465px] p-5">
+ <Text className="mx-0 mb-8 mt-4 p-0 text-center text-2xl font-normal">
+ <span className="font-bold tracking-tighter">Papermark</span>
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ The export you requested is ready to download for your Papermark
+ account. Make sure you're signed into this account, and click
+ below to download. The file will be available for the next three
+ days.
+ </Text>
+ <Section className="my-8 text-center">
+ <Button
+ className="rounded bg-black text-center text-xs font-semibold text-white no-underline"
+ href={downloadUrl}
+ style={{ padding: "12px 20px" }}
+ >
+ Download Export
+ </Button>
+ </Section>
+ <Text className="text-sm leading-6 text-black">
+ Export details:
+ </Text>
+ <Text className="break-all text-sm leading-6 text-black">
+ <ul>
+ <li className="text-sm leading-6 text-black">
+ Export type: {resourceName}
+ </li>
+ </ul>
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ Best,
+ <br />
+ The Papermark Team
+ </Text>
+ <Hr />
+ <Section className="mt-8 text-gray-400">
+ <Text className="text-xs">
+ © {new Date().getFullYear()}{" "}
+ <a
+ href="https://www.papermark.com"
+ className="text-gray-400 no-underline hover:text-gray-400"
+ target="_blank"
+ >
+ Papermark, Inc.
+ </a>
+ </Text>
+ <Text className="text-xs">
+ This email was intended for{" "}
+ <span className="text-black">{email}</span>. If you were not
+ expecting this email, you can ignore this email. If you have any
+ feedback or questions about this email, simply reply to it.
+ </Text>
+ </Section>
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/components/visitors/dataroom-visitors-table.tsx b/components/visitors/dataroom-visitors-table.tsx
index 7c7991ec..411f6d1d 100644
--- a/components/visitors/dataroom-visitors-table.tsx
+++ b/components/visitors/dataroom-visitors-table.tsx
@@ -1,3 +1,5 @@
+import { useState } from "react";
+
import { useTeam } from "@/context/team-context";
import {
BadgeCheckIcon,
@@ -9,6 +11,7 @@ import {
} from "lucide-react";
import { toast } from "sonner";
+import { useDataroom } from "@/lib/swr/use-dataroom";
import { useDataroomVisits } from "@/lib/swr/use-dataroom";
import { timeAgo } from "@/lib/utils";
@@ -30,6 +33,7 @@ import {
} from "@/components/ui/table";
import { BadgeTooltip } from "@/components/ui/tooltip";
+import { ExportVisitsModal } from "../datarooms/export-visits-modal";
import DataroomVisitorCustomFields from "./dataroom-visitor-custom-fields";
import { DataroomVisitorUserAgent } from "./dataroom-visitor-useragent";
import DataroomVisitHistory from "./dataroom-visitors-history";
@@ -47,93 +51,18 @@ export default function DataroomVisitorsTable({
const teamInfo = useTeam();
const teamId = teamInfo?.currentTeam?.id;
const { views } = useDataroomVisits({ dataroomId, groupId });
+ const { dataroom } = useDataroom();
+ const [exportModalOpen, setExportModalOpen] = useState(false);
- const exportVisitCounts = async (dataroomId: string) => {
- const formattedTime = new Date().toISOString().replace(/[-:Z]/g, "");
- try {
- // Trigger the background export job
- const response = await fetch(
- `/api/teams/${teamId}/datarooms/${dataroomId}${groupId ? `/groups/${groupId}` : ""}/export-visits`,
- { method: "POST" },
- );
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
- const data = await response.json();
-
- if (data.exportId) {
- toast.success("Export job started. You'll be notified when it's ready.");
-
- // Poll for export completion
- const pollInterval = setInterval(async () => {
- try {
- const statusResponse = await fetch(
- `/api/teams/${teamId}/export-jobs/${data.exportId}`,
- { method: "GET" },
- );
-
- if (statusResponse.ok) {
- const statusData = await statusResponse.json();
-
- if (statusData.status === "COMPLETED" && statusData.isReady) {
- clearInterval(pollInterval);
-
- // Download the CSV file
- const downloadResponse = await fetch(
- `/api/teams/${teamId}/export-jobs/${data.exportId}?download=true`,
- { method: "GET" },
- );
-
- if (downloadResponse.ok) {
- const blob = await downloadResponse.blob();
- const url = URL.createObjectURL(blob);
- const link = document.createElement("a");
- link.href = url;
- link.setAttribute(
- "download",
- `${statusData.resourceName}_${name ? `${name}_` : ""}visits_${formattedTime}.csv`,
- );
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- URL.revokeObjectURL(url);
-
- toast.success("CSV file downloaded successfully");
- } else {
- toast.error("Failed to download the export file");
- }
- } else if (statusData.status === "FAILED") {
- clearInterval(pollInterval);
- toast.error(`Export failed: ${statusData.error || "Unknown error"}`);
- }
- }
- } catch (error) {
- console.error("Error polling export status:", error);
- }
- }, 3000); // Poll every 3 seconds
-
- // Clear interval after 5 minutes to prevent indefinite polling
- setTimeout(() => {
- clearInterval(pollInterval);
- }, 300000);
- }
- } catch (error) {
- console.error("Error:", error);
- toast.error(
- "An error occurred while starting the export. Please try again.",
- );
- }
+ const exportVisitCounts = () => {
+ setExportModalOpen(true);
};
return (
<div className="w-full">
<div className="mb-2 flex items-center justify-between md:mb-4">
<h2>All visitors</h2>
- <Button
- variant="outline"
- size="sm"
- onClick={() => exportVisitCounts(dataroomId)}
- >
+ <Button variant="outline" size="sm" onClick={exportVisitCounts}>
<Download className="!size-4" />
Export visits
</Button>
@@ -342,6 +271,18 @@ export default function DataroomVisitorsTable({
</TableBody>
</Table>
</div>
+
+ {dataroom && teamId && (
+ <ExportVisitsModal
+ dataroomId={dataroomId}
+ dataroomName={dataroom.name}
+ teamId={teamId}
+ groupId={groupId}
+ groupName={name}
+ isVisible={exportModalOpen}
+ onClose={() => setExportModalOpen(false)}
+ />
+ )}
</div>
);
}
diff --git a/lib/emails/send-export-ready-email.ts b/lib/emails/send-export-ready-email.ts
new file mode 100644
index 00000000..ce402cf9
--- /dev/null
+++ b/lib/emails/send-export-ready-email.ts
@@ -0,0 +1,28 @@
+import { sendEmail } from "@/lib/resend";
+
+import ExportReady from "@/components/emails/export-ready";
+
+export const sendExportReadyEmail = async ({
+ to,
+ resourceName,
+ downloadUrl,
+}: {
+ to: string;
+ resourceName: string;
+ downloadUrl: string;
+}) => {
+ const emailTemplate = ExportReady({ resourceName, downloadUrl, email: to });
+
+ try {
+ await sendEmail({
+ to,
+ subject: `Your ${resourceName} export is ready`,
+ react: emailTemplate,
+ test: process.env.NODE_ENV === "development",
+ system: true,
+ });
+ } catch (e) {
+ console.error("Error sending export ready email:", e);
+ throw e;
+ }
+};
diff --git a/lib/redis-job-store.ts b/lib/redis-job-store.ts
index 236cae48..54ee9d37 100644
--- a/lib/redis-job-store.ts
+++ b/lib/redis-job-store.ts
@@ -1,4 +1,5 @@
-import { nanoid } from "nanoid";
+import { nanoid } from "@/lib/utils";
+
import { redis } from "./redis";
export type ExportJobStatus = "PENDING" | "PROCESSING" | "COMPLETED" | "FAILED";
@@ -10,19 +11,22 @@ export interface ExportJob {
resourceId: string;
resourceName?: string;
groupId?: string;
- result?: string; // CSV data
+ result?: string; // CSV data or blob URL
error?: string;
userId: string;
teamId: string;
createdAt: string;
updatedAt: string;
completedAt?: string;
+ emailNotification?: boolean;
+ emailAddress?: string;
}
const JOB_PREFIX = "export_job:";
const USER_JOBS_PREFIX = "user_jobs:";
const TEAM_JOBS_PREFIX = "team_jobs:";
-const JOB_TTL = 60 * 60 * 24 * 7; // 7 days
+const CLEANUP_QUEUE_PREFIX = "cleanup_blobs:";
+const JOB_TTL = 60 * 60 * 24 * 3; // 3 days
export class RedisJobStore {
private getJobKey(jobId: string): string {
@@ -37,10 +41,16 @@ export class RedisJobStore {
return `${TEAM_JOBS_PREFIX}${teamId}`;
}
- async createJob(jobData: Omit<ExportJob, "id" | "createdAt" | "updatedAt">): Promise<ExportJob> {
+ private getCleanupQueueKey(): string {
+ return `${CLEANUP_QUEUE_PREFIX}pending`;
+ }
+
+ async createJob(
+ jobData: Omit<ExportJob, "id" | "createdAt" | "updatedAt">,
+ ): Promise<ExportJob> {
const jobId = nanoid();
const now = new Date().toISOString();
-
+
const job: ExportJob = {
...jobData,
id: jobId,
@@ -54,13 +64,13 @@ export class RedisJobStore {
// Store job data with TTL
await redis.setex(jobKey, JOB_TTL, JSON.stringify(job));
-
+
// Add to user's job list (sorted by creation time)
- await redis.zadd(userJobsKey, Date.now(), jobId);
+ await redis.zadd(userJobsKey, { score: Date.now(), member: jobId });
await redis.expire(userJobsKey, JOB_TTL);
-
+
// Add to team's job list (sorted by creation time)
- await redis.zadd(teamJobsKey, Date.now(), jobId);
+ await redis.zadd(teamJobsKey, { score: Date.now(), member: jobId });
await redis.expire(teamJobsKey, JOB_TTL);
return job;
@@ -69,20 +79,28 @@ export class RedisJobStore {
async getJob(jobId: string): Promise<ExportJob | null> {
const jobKey = this.getJobKey(jobId);
const jobData = await redis.get(jobKey);
-
+
if (!jobData) {
return null;
}
try {
- return JSON.parse(jobData);
+ // Check if data is already an object (Redis client auto-parsed)
+ if (typeof jobData === "object") {
+ return jobData as ExportJob;
+ }
+ // Otherwise parse the JSON string
+ return JSON.parse(jobData as string);
} catch (error) {
console.error("Error parsing job data:", error);
return null;
}
}
- async updateJob(jobId: string, updates: Partial<ExportJob>): Promise<ExportJob | null> {
+ async updateJob(
+ jobId: string,
+ updates: Partial<ExportJob>,
+ ): Promise<ExportJob | null> {
const job = await this.getJob(jobId);
if (!job) {
return null;
@@ -97,9 +115,73 @@ export class RedisJobStore {
const jobKey = this.getJobKey(jobId);
await redis.setex(jobKey, JOB_TTL, JSON.stringify(updatedJob));
+ // If this update includes a blob URL, schedule it for cleanup
+ if (updates.result && updates.result.startsWith("https://")) {
+ await this.scheduleBlobForCleanup(updates.result, jobId);
+ }
+
return updatedJob;
}
+ async scheduleBlobForCleanup(blobUrl: string, jobId: string): Promise<void> {
+ const cleanupTime = Date.now() + JOB_TTL * 1000; // Convert to milliseconds
+ const cleanupQueueKey = this.getCleanupQueueKey();
+
+ // Store blob URL with cleanup timestamp
+ await redis.zadd(cleanupQueueKey, {
+ score: cleanupTime,
+ member: JSON.stringify({
+ blobUrl,
+ jobId,
+ scheduledAt: new Date().toISOString(),
+ }),
+ });
+ }
+
+ async getBlobsForCleanup(
+ beforeTimestamp?: number,
+ ): Promise<Array<{ blobUrl: string; jobId: string; scheduledAt: string }>> {
+ const cleanupQueueKey = this.getCleanupQueueKey();
+ const maxScore = beforeTimestamp || Date.now();
+
+ // Get all items scheduled for cleanup before the specified timestamp
+ const items = await redis.zrange(cleanupQueueKey, 0, maxScore, {
+ byScore: true,
+ });
+
+ const blobs: Array<{
+ blobUrl: string;
+ jobId: string;
+ scheduledAt: string;
+ }> = [];
+
+ for (const item of items) {
+ try {
+ const parsed = JSON.parse(item as string);
+ blobs.push(parsed);
+ } catch (error) {
+ console.error("Error parsing cleanup item:", error);
+ }
+ }
+
+ return blobs;
+ }
+
+ async removeBlobFromCleanupQueue(
+ blobUrl: string,
+ jobId: string,
+ ): Promise<void> {
+ const cleanupQueueKey = this.getCleanupQueueKey();
+ const itemToRemove = JSON.stringify({
+ blobUrl,
+ jobId,
+ scheduledAt: new Date().toISOString(),
+ });
+
+ // Remove the specific item from the cleanup queue
+ await redis.zrem(cleanupQueueKey, itemToRemove);
+ }
+
async deleteJob(jobId: string): Promise<boolean> {
const job = await this.getJob(jobId);
if (!job) {
@@ -122,49 +204,55 @@ export class RedisJobStore {
async getUserJobs(userId: string, limit: number = 20): Promise<ExportJob[]> {
const userJobsKey = this.getUserJobsKey(userId);
-
+
// Get job IDs sorted by creation time (newest first)
- const jobIds = await redis.zrevrange(userJobsKey, 0, limit - 1);
-
+ const jobIds = await redis.zrange(userJobsKey, 0, limit - 1, { rev: true });
+
if (!jobIds.length) {
return [];
}
// Get all job data
const jobs = await Promise.all(
- jobIds.map(jobId => this.getJob(jobId))
+ (jobIds as string[]).map((jobId: string) => this.getJob(jobId)),
);
// Filter out null values (deleted jobs)
- return jobs.filter((job): job is ExportJob => job !== null);
+ return jobs.filter(
+ (job: ExportJob | null): job is ExportJob => job !== null,
+ );
}
async getTeamJobs(teamId: string, limit: number = 20): Promise<ExportJob[]> {
const teamJobsKey = this.getTeamJobsKey(teamId);
-
+
// Get job IDs sorted by creation time (newest first)
- const jobIds = await redis.zrevrange(teamJobsKey, 0, limit - 1);
-
+ const jobIds = await redis.zrange(teamJobsKey, 0, limit - 1, { rev: true });
+
if (!jobIds.length) {
return [];
}
// Get all job data
const jobs = await Promise.all(
- jobIds.map(jobId => this.getJob(jobId))
+ (jobIds as string[]).map((jobId: string) => this.getJob(jobId)),
);
// Filter out null values (deleted jobs)
- return jobs.filter((job): job is ExportJob => job !== null);
+ return jobs.filter(
+ (job: ExportJob | null): job is ExportJob => job !== null,
+ );
}
- async getUserTeamJobs(userId: string, teamId: string, limit: number = 20): Promise<ExportJob[]> {
+ async getUserTeamJobs(
+ userId: string,
+ teamId: string,
+ limit: number = 20,
+ ): Promise<ExportJob[]> {
const userJobs = await this.getUserJobs(userId, limit * 2); // Get more to filter
-
+
// Filter jobs by team
- return userJobs
- .filter(job => job.teamId === teamId)
- .slice(0, limit);
+ return userJobs.filter((job) => job.teamId === teamId).slice(0, limit);
}
async cleanupExpiredJobs(): Promise<void> {
@@ -173,4 +261,4 @@ export class RedisJobStore {
}
}
-export const jobStore = new RedisJobStore();
\ No newline at end of file
+export const jobStore = new RedisJobStore();
diff --git a/lib/trigger/cleanup-expired-exports.ts b/lib/trigger/cleanup-expired-exports.ts
new file mode 100644
index 00000000..0493a748
--- /dev/null
+++ b/lib/trigger/cleanup-expired-exports.ts
@@ -0,0 +1,76 @@
+import { logger, schedules } from "@trigger.dev/sdk/v3";
+import { del } from "@vercel/blob";
+
+import { jobStore } from "@/lib/redis-job-store";
+
+export const cleanupExpiredExports = schedules.task({
+ id: "cleanup-expired-exports",
+ // Run daily at 2 AM UTC
+ cron: "0 2 * * *",
+ run: async (payload) => {
+ logger.info("Starting cleanup of expired export blobs", {
+ timestamp: payload.timestamp,
+ });
+
+ try {
+ // Get all blob URLs that are due for cleanup
+ const blobsToCleanup = await jobStore.getBlobsForCleanup();
+
+ if (blobsToCleanup.length === 0) {
+ logger.info("No blobs due for cleanup");
+ return { deletedCount: 0 };
+ }
+
+ logger.info(`Found ${blobsToCleanup.length} blobs to delete`);
+
+ // Delete blobs from Vercel Blob
+ const deletionResults = await Promise.allSettled(
+ blobsToCleanup.map(async (blob) => {
+ try {
+ await del(blob.blobUrl);
+
+ // Remove from cleanup queue after successful deletion
+ await jobStore.removeBlobFromCleanupQueue(blob.blobUrl, blob.jobId);
+
+ logger.info("Successfully deleted blob", {
+ blobUrl: blob.blobUrl,
+ jobId: blob.jobId,
+ });
+
+ return { blob, success: true };
+ } catch (error) {
+ logger.error("Failed to delete blob", {
+ blobUrl: blob.blobUrl,
+ jobId: blob.jobId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return { blob, success: false, error };
+ }
+ }),
+ );
+
+ const successCount = deletionResults.filter(
+ (result) => result.status === "fulfilled" && result.value.success,
+ ).length;
+
+ const failureCount = deletionResults.length - successCount;
+
+ logger.info("Cleanup completed", {
+ totalBlobs: blobsToCleanup.length,
+ successCount,
+ failureCount,
+ });
+
+ return {
+ deletedCount: successCount,
+ failureCount,
+ totalProcessed: blobsToCleanup.length,
+ };
+ } catch (error) {
+ logger.error("Cleanup task failed", {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throw error;
+ }
+ },
+});
diff --git a/lib/trigger/export-visits.ts b/lib/trigger/export-visits.ts
index cb2d6ce0..7606e6e8 100644
--- a/lib/trigger/export-visits.ts
+++ b/lib/trigger/export-visits.ts
@@ -1,6 +1,8 @@
import { logger, task } from "@trigger.dev/sdk/v3";
+import { put } from "@vercel/blob";
import Bottleneck from "bottleneck";
+import { sendExportReadyEmail } from "@/lib/emails/send-export-ready-email";
import prisma from "@/lib/prisma";
import { jobStore } from "@/lib/redis-job-store";
import {
@@ -28,9 +30,6 @@ export const exportVisitsTask = task({
id: "export-visits",
retry: { maxAttempts: 3 },
maxDuration: 900, // 15 minutes to handle large datasets
- machine: {
- preset: "medium-1x", // More resources for processing
- },
run: async (payload: ExportVisitsPayload) => {
const { type, teamId, resourceId, groupId, userId, exportId } = payload;
@@ -65,26 +64,71 @@ export const exportVisitsTask = task({
let resourceName: string;
if (type === "document") {
- ({ csvData, resourceName } = await exportDocumentVisits(resourceId, teamId));
+ ({ csvData, resourceName } = await exportDocumentVisits(
+ resourceId,
+ teamId,
+ ));
} else if (type === "dataroom") {
- ({ csvData, resourceName } = await exportDataroomVisits(resourceId, teamId, groupId));
+ ({ csvData, resourceName } = await exportDataroomVisits(
+ resourceId,
+ teamId,
+ groupId,
+ ));
} else {
throw new Error("Invalid export type");
}
- // Store the result in Redis
- await jobStore.updateJob(exportId, {
+ // Create timestamp for filename
+ const currentTime = new Date().toISOString().split("T")[0];
+
+ // Upload CSV to Vercel Blob
+ const filename = `visits-${resourceName.replace(/[^a-zA-Z0-9]/g, "_")}-${currentTime}.csv`;
+ const blob = await put(filename, csvData, {
+ access: "public",
+ addRandomSuffix: true,
+ contentType: "text/csv",
+ });
+
+ logger.info("CSV uploaded to Vercel Blob", {
+ filename,
+ url: blob.downloadUrl,
+ size: csvData.length,
+ });
+
+ // Store the blob URL in Redis
+ const updatedJob = await jobStore.updateJob(exportId, {
status: "COMPLETED",
- result: csvData,
+ result: blob.downloadUrl,
resourceName,
completedAt: new Date().toISOString(),
});
+ // Send email notification if requested
+ if (updatedJob?.emailNotification && updatedJob.emailAddress) {
+ try {
+ await sendExportReadyEmail({
+ to: updatedJob.emailAddress,
+ resourceName: resourceName,
+ downloadUrl: `${process.env.NEXTAUTH_URL}/api/teams/${teamId}/export-jobs/${exportId}?download=true`,
+ });
+ logger.info("Export ready email sent", {
+ exportId,
+ emailAddress: updatedJob.emailAddress,
+ });
+ } catch (error) {
+ logger.error("Failed to send export ready email", {
+ exportId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
logger.info("Export visits task completed successfully", {
exportId,
type,
resourceId,
csvSize: csvData.length,
+ blobUrl: blob.downloadUrl,
});
return {
@@ -92,6 +136,7 @@ export const exportVisitsTask = task({
exportId,
resourceName,
csvSize: csvData.length,
+ blobUrl: blob.downloadUrl,
};
} catch (error) {
logger.error("Export visits task failed", {
@@ -110,7 +155,10 @@ export const exportVisitsTask = task({
},
});
-async function exportDocumentVisits(docId: string, teamId: string): Promise<{
+async function exportDocumentVisits(
+ docId: string,
+ teamId: string,
+): Promise<{
csvData: string;
resourceName: string;
}> {
@@ -208,7 +256,7 @@ async function exportDocumentVisits(docId: string, teamId: string): Promise<{
for (let i = 0; i < views.length; i++) {
const view = views[i];
-
+
logger.info(`Processing view ${i + 1}/${views.length}`, {
viewId: view.id,
viewedAt: view.viewedAt,
@@ -299,7 +347,7 @@ async function exportDocumentVisits(docId: string, teamId: string): Promise<{
async function exportDataroomVisits(
dataroomId: string,
teamId: string,
- groupId?: string
+ groupId?: string,
): Promise<{
csvData: string;
resourceName: string;
@@ -385,8 +433,12 @@ async function exportDataroomVisits(
}
// First get all dataroom views
- const dataroomViews = views.filter((view) => view.viewType === "DATAROOM_VIEW");
- const documentViews = views.filter((view) => view.viewType === "DOCUMENT_VIEW");
+ const dataroomViews = views.filter(
+ (view) => view.viewType === "DATAROOM_VIEW",
+ );
+ const documentViews = views.filter(
+ (view) => view.viewType === "DOCUMENT_VIEW",
+ );
logger.info("Processing dataroom views with rate limiting", {
dataroomViewCount: dataroomViews.length,
@@ -397,35 +449,38 @@ async function exportDataroomVisits(
const exportData = [];
for (let i = 0; i < dataroomViews.length; i++) {
const dataroomView = dataroomViews[i];
-
+
logger.info(`Processing dataroom view ${i + 1}/${dataroomViews.length}`, {
viewId: dataroomView.id,
});
// Find associated document views
const associatedDocViews = documentViews.filter(
- (docView) => docView.dataroomViewId === dataroomView.id
+ (docView) => docView.dataroomViewId === dataroomView.id,
);
// Process document views with rate limiting
const documentViewDetails = [];
for (let j = 0; j < associatedDocViews.length; j++) {
const docView = associatedDocViews[j];
-
- logger.info(`Processing document view ${j + 1}/${associatedDocViews.length} for dataroom view ${i + 1}`, {
- docViewId: docView.id,
- });
+
+ logger.info(
+ `Processing document view ${j + 1}/${associatedDocViews.length} for dataroom view ${i + 1}`,
+ {
+ docViewId: docView.id,
+ },
+ );
const duration = await tinybirdLimiter.schedule(() =>
getViewPageDuration({
documentId: docView.document?.id || "null",
viewId: docView.id,
since: 0,
- })
+ }),
);
const relevantVersion = docView.document?.versions.find(
- (version) => version.createdAt <= docView.viewedAt
+ (version) => version.createdAt <= docView.viewedAt,
);
const numPages =
@@ -440,7 +495,7 @@ async function exportDataroomVisits(
downloadedAt: docView.downloadedAt?.toISOString() || "NaN",
duration: duration.data.reduce(
(total, data) => total + data.sum_duration,
- 0
+ 0,
),
completionRate: completionRate.toFixed(2) + "%",
documentVersion:
@@ -462,7 +517,8 @@ async function exportDataroomVisits(
agreementName: dataroomView.agreementResponse?.agreement.name || "NaN",
agreementAcceptedAt:
dataroomView.agreementResponse?.createdAt.toISOString() || "NaN",
- agreementContent: dataroomView.agreementResponse?.agreement.content || "NaN",
+ agreementContent:
+ dataroomView.agreementResponse?.agreement.content || "NaN",
documentViews: documentViewDetails,
});
}
@@ -491,60 +547,36 @@ async function exportDataroomVisits(
// Create CSV
const csvRows: string[] = [];
- 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(","));
+ 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(","),
+ );
exportData.forEach((view) => {
if (view.documentViews.length === 0) {
- csvRows.push([
- view.dataroomViewedAt,
- view.dataroomDownloadedAt,
- view.viewerName,
- view.viewerEmail,
- view.linkName,
- view.verified,
- view.agreementStatus,
- view.agreementName,
- view.agreementContent,
- view.agreementAcceptedAt,
- "NaN",
- "NaN",
- "NaN",
- "NaN",
- "NaN",
- "NaN",
- "NaN",
- "NaN",
- "NaN",
- "NaN",
- "NaN",
- ].join(","));
- } else {
- view.documentViews.forEach((docView) => {
- const userAgentData = userAgentDataMap.get(docView.viewId);
-
- csvRows.push([
+ csvRows.push(
+ [
view.dataroomViewedAt,
view.dataroomDownloadedAt,
view.viewerName,
@@ -555,18 +587,48 @@ async function exportDataroomVisits(
view.agreementName,
view.agreementContent,
view.agreementAcceptedAt,
- docView.documentName,
- docView.viewedAt,
- docView.downloadedAt,
- (docView.duration / 1000).toFixed(1),
- docView.completionRate,
- docView.documentVersion,
- userAgentData?.data[0]?.browser || "NaN",
- userAgentData?.data[0]?.os || "NaN",
- userAgentData?.data[0]?.device || "NaN",
- userAgentData?.data[0]?.country || "NaN",
- userAgentData?.data[0]?.city || "NaN",
- ].join(","));
+ "NaN",
+ "NaN",
+ "NaN",
+ "NaN",
+ "NaN",
+ "NaN",
+ "NaN",
+ "NaN",
+ "NaN",
+ "NaN",
+ "NaN",
+ ].join(","),
+ );
+ } else {
+ view.documentViews.forEach((docView) => {
+ const userAgentData = userAgentDataMap.get(docView.viewId);
+
+ 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?.data[0]?.browser || "NaN",
+ userAgentData?.data[0]?.os || "NaN",
+ userAgentData?.data[0]?.device || "NaN",
+ userAgentData?.data[0]?.country || "NaN",
+ userAgentData?.data[0]?.city || "NaN",
+ ].join(","),
+ );
});
}
});
@@ -575,4 +637,4 @@ async function exportDataroomVisits(
csvData: csvRows.join("\n"),
resourceName: dataroom.name,
};
-}
\ No newline at end of file
+}
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/views-count.ts b/pages/api/teams/[teamId]/datarooms/[id]/views-count.ts
new file mode 100644
index 00000000..4a2136d0
--- /dev/null
+++ b/pages/api/teams/[teamId]/datarooms/[id]/views-count.ts
@@ -0,0 +1,68 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const { teamId, id } = req.query as {
+ teamId: string;
+ id: string;
+ };
+ const groupId = req.query.groupId as string | undefined;
+ const userId = (session.user as CustomUser).id;
+
+ if (req.method === "GET") {
+ try {
+ // Verify user has access to the dataroom
+ const dataroom = await prisma.dataroom.findFirst({
+ where: {
+ id: id,
+ teamId: teamId,
+ team: {
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (!dataroom) {
+ return res.status(404).json({ error: "Dataroom not found" });
+ }
+
+ // Build the where clause for views
+ const whereClause = {
+ dataroomId: id,
+ ...(groupId && { groupId }),
+ };
+
+ const viewCount = await prisma.view.count({
+ where: whereClause,
+ });
+
+ return res.status(200).json({ count: viewCount });
+ } catch (error) {
+ console.error("Error fetching view count:", error);
+ return res.status(500).json({ error: "Failed to fetch view count" });
+ }
+ }
+
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+}
diff --git a/pages/api/teams/[teamId]/documents/[id]/views-count.ts b/pages/api/teams/[teamId]/documents/[id]/views-count.ts
new file mode 100644
index 00000000..c858af3a
--- /dev/null
+++ b/pages/api/teams/[teamId]/documents/[id]/views-count.ts
@@ -0,0 +1,62 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const { teamId, id } = req.query as {
+ teamId: string;
+ id: string;
+ };
+ const userId = (session.user as CustomUser).id;
+
+ if (req.method === "GET") {
+ try {
+ // Verify user has access to the document
+ const document = await prisma.document.findFirst({
+ where: {
+ id: id,
+ teamId: teamId,
+ team: {
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ },
+ select: {
+ id: true,
+ _count: {
+ select: {
+ views: true,
+ },
+ },
+ },
+ });
+
+ if (!document) {
+ return res.status(404).json({ error: "Document not found" });
+ }
+
+ return res.status(200).json({ count: document._count.views });
+ } catch (error) {
+ console.error("Error fetching view count:", error);
+ return res.status(500).json({ error: "Failed to fetch view count" });
+ }
+ }
+
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+}
diff --git a/pages/api/teams/[teamId]/export-jobs/[exportId].ts b/pages/api/teams/[teamId]/export-jobs/[exportId].ts
index 87a66033..1d9703c4 100644
--- a/pages/api/teams/[teamId]/export-jobs/[exportId].ts
+++ b/pages/api/teams/[teamId]/export-jobs/[exportId].ts
@@ -26,24 +26,23 @@ export default async function handler(
// Get export job details
const exportJob = await jobStore.getJob(exportId);
- if (!exportJob || exportJob.teamId !== teamId || exportJob.userId !== userId) {
+ if (
+ !exportJob ||
+ exportJob.teamId !== teamId ||
+ exportJob.userId !== userId
+ ) {
return res.status(404).json({ error: "Export job not found" });
}
// Check if client wants to download the CSV
const { download } = req.query;
- if (download === "true" && exportJob.status === "COMPLETED" && exportJob.result) {
- const timestamp = new Date().toISOString().replace(/[-:Z]/g, "");
- const filename = `${exportJob.resourceName || "export"}_visits_${timestamp}.csv`;
-
- res.setHeader("Content-Type", "text/csv");
- res.setHeader(
- "Content-Disposition",
- `attachment; filename="${filename}"`
- );
- res.setHeader("Content-Length", Buffer.byteLength(exportJob.result));
-
- return res.status(200).send(exportJob.result);
+ if (
+ download === "true" &&
+ exportJob.status === "COMPLETED" &&
+ exportJob.result
+ ) {
+ // Redirect directly to the blob URL
+ return res.redirect(302, exportJob.result);
}
// Return job status
@@ -70,15 +69,21 @@ export default async function handler(
try {
// Get the job first to verify ownership
const exportJob = await jobStore.getJob(exportId);
-
- if (!exportJob || exportJob.teamId !== teamId || exportJob.userId !== userId) {
+
+ if (
+ !exportJob ||
+ exportJob.teamId !== teamId ||
+ exportJob.userId !== userId
+ ) {
return res.status(404).json({ error: "Export job not found" });
}
// Delete export job
await jobStore.deleteJob(exportId);
- return res.status(200).json({ message: "Export job deleted successfully" });
+ return res
+ .status(200)
+ .json({ message: "Export job deleted successfully" });
} catch (error) {
console.error("Error deleting export job:", error);
return res.status(500).json({ error: "Failed to delete export job" });
@@ -87,4 +92,4 @@ export default async function handler(
res.setHeader("Allow", ["GET", "DELETE"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);
-}
\ No newline at end of file
+}
diff --git a/pages/api/teams/[teamId]/export-jobs/[exportId]/send-email.ts b/pages/api/teams/[teamId]/export-jobs/[exportId]/send-email.ts
new file mode 100644
index 00000000..fb3852a9
--- /dev/null
+++ b/pages/api/teams/[teamId]/export-jobs/[exportId]/send-email.ts
@@ -0,0 +1,69 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import { sendExportReadyEmail } from "@/lib/emails/send-export-ready-email";
+import { jobStore } from "@/lib/redis-job-store";
+import { CustomUser } from "@/lib/types";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const { teamId, exportId } = req.query as {
+ teamId: string;
+ exportId: string;
+ };
+ const userId = (session.user as CustomUser).id;
+
+ if (req.method === "POST") {
+ try {
+ // Get export job details
+ const exportJob = await jobStore.getJob(exportId);
+
+ if (
+ !exportJob ||
+ exportJob.teamId !== teamId ||
+ exportJob.userId !== userId
+ ) {
+ return res.status(404).json({ error: "Export job not found" });
+ }
+
+ // Check if user has email
+ if (!session.user?.email) {
+ return res.status(400).json({ error: "User email not found" });
+ }
+
+ // Store email notification flag
+ await jobStore.updateJob(exportId, {
+ emailNotification: true,
+ emailAddress: session.user.email,
+ });
+
+ // If job is already completed, send email immediately
+ if (exportJob.status === "COMPLETED" && exportJob.result) {
+ await sendExportReadyEmail({
+ to: session.user.email,
+ resourceName: exportJob.resourceName || "Export",
+ downloadUrl: `${process.env.NEXTAUTH_URL}/api/teams/${teamId}/export-jobs/${exportId}?download=true`,
+ });
+ }
+
+ return res.status(200).json({ success: true });
+ } catch (error) {
+ console.error("Error setting up email notification:", error);
+ return res
+ .status(500)
+ .json({ error: "Failed to setup email notification" });
+ }
+ }
+
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+}
diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prisma
index 843b94eb..ee594ee7 100644
--- a/prisma/schema/schema.prisma
+++ b/prisma/schema/schema.prisma
@@ -642,5 +642,3 @@ model TagItem {
@@index([tagId, documentId])
@@index([tagId, dataroomId])
}
-
-