Skip to content

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

feat: add upload notifications for dataroom file requests

Cursor Agent048b7f0dcf8b
diff --git a/app/(ee)/api/links/[id]/upload/route.ts b/app/(ee)/api/links/[id]/upload/route.ts
index 46a97670..da89e83a 100644
--- a/app/(ee)/api/links/[id]/upload/route.ts
+++ b/app/(ee)/api/links/[id]/upload/route.ts
@@ -4,7 +4,10 @@ import { processDocument } from "@/lib/api/documents/process-document";
import { verifyDataroomSession } from "@/lib/auth/dataroom-auth";
import { DocumentData } from "@/lib/documents/create-document";
import prisma from "@/lib/prisma";
+import { sendDataroomUploadNotificationTask } from "@/lib/trigger/dataroom-upload-notification";
import { supportsAdvancedExcelMode } from "@/lib/utils/get-content-type";
+import { runs } from "@trigger.dev/sdk/v3";
+import { waitUntil } from "@vercel/functions";
export async function POST(
request: NextRequest,
@@ -45,7 +48,9 @@ export async function POST(
where: { id: linkId, dataroomId },
select: {
id: true,
+ name: true,
enableUpload: true,
+ enableNotification: true,
uploadFolderId: true,
dataroomId: true,
teamId: true,
@@ -148,6 +153,43 @@ export async function POST(
},
});
+ // 4. Send upload notification to team if enabled
+ if (link.enableNotification) {
+ try {
+ // Cancel any existing pending notification runs for this dataroom+link
+ const allRuns = await runs.list({
+ taskIdentifier: ["send-dataroom-upload-notification"],
+ tag: [`dataroom_${dataroomId}`, `link_${linkId}`],
+ status: ["DELAYED", "QUEUED"],
+ period: "10m",
+ });
+
+ await Promise.all(allRuns.data.map((run) => runs.cancel(run.id)));
+
+ // Trigger a new notification with 5-minute delay to batch uploads
+ waitUntil(
+ sendDataroomUploadNotificationTask.trigger(
+ {
+ dataroomId,
+ linkId,
+ teamId: link.teamId,
+ },
+ {
+ idempotencyKey: `upload-notification-${link.teamId}-${dataroomId}-${linkId}-${newDataroomDocument.id}`,
+ tags: [
+ `team_${link.teamId}`,
+ `dataroom_${dataroomId}`,
+ `link_${linkId}`,
+ ],
+ delay: new Date(Date.now() + 5 * 60 * 1000), // 5 minute delay
+ },
+ ),
+ );
+ } catch (error) {
+ console.error("Error triggering upload notification:", error);
+ }
+ }
+
return NextResponse.json({ success: true });
} catch (error) {
console.error("Error uploading document:", error);
diff --git a/components/emails/dataroom-upload-notification.tsx b/components/emails/dataroom-upload-notification.tsx
new file mode 100644
index 00000000..84327722
--- /dev/null
+++ b/components/emails/dataroom-upload-notification.tsx
@@ -0,0 +1,103 @@
+import React from "react";
+
+import {
+ Body,
+ Button,
+ Container,
+ Head,
+ Html,
+ Preview,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+
+import { Footer } from "./shared/footer";
+
+export default function DataroomUploadNotification({
+ dataroomId = "123",
+ dataroomName = "Example Dataroom",
+ uploaderEmail = "[email protected]",
+ documentNames = ["Document 1.pdf", "Document 2.pdf"],
+ linkName = "Link #abc12",
+}: {
+ dataroomId: string;
+ dataroomName: string;
+ uploaderEmail: string | null;
+ documentNames: string[];
+ linkName: string;
+}) {
+ const documentCount = documentNames.length;
+ const documentLabel = documentCount === 1 ? "document" : "documents";
+
+ return (
+ <Html>
+ <Head />
+ <Preview>
+ {`${documentCount} new ${documentLabel} uploaded to ${dataroomName}`}
+ </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="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">
+ New File Upload
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ {uploaderEmail ? (
+ <>
+ <span className="font-semibold">{uploaderEmail}</span> has
+ uploaded{" "}
+ </>
+ ) : (
+ <>A visitor has uploaded </>
+ )}
+ <span className="font-semibold">
+ {documentCount} {documentLabel}
+ </span>{" "}
+ to your dataroom{" "}
+ <span className="font-semibold">{dataroomName}</span> via the link{" "}
+ <span className="font-semibold">{linkName}</span>.
+ </Text>
+ {documentNames.length <= 10 && (
+ <Section className="my-4">
+ {documentNames.map((name, index) => (
+ <Text
+ key={index}
+ className="my-1 text-sm leading-6 text-black"
+ >
+ {"\u2022"} {name}
+ </Text>
+ ))}
+ </Section>
+ )}
+ <Section className="my-8 text-center">
+ <Button
+ className="rounded bg-black text-center text-xs font-semibold text-white no-underline"
+ href={`https://app.papermark.com/datarooms/${dataroomId}`}
+ style={{ padding: "12px 20px" }}
+ >
+ View the dataroom
+ </Button>
+ </Section>
+
+ <Footer
+ footerText={
+ <>
+ If you have any feedback or questions about this email, simply
+ reply to it. I&apos;d love to hear from you!
+ <br />
+ <br />
+ To stop email notifications for this link, edit the link and
+ uncheck &quot;Receive email notification&quot;.
+ </>
+ }
+ />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/lib/emails/send-dataroom-upload-notification.ts b/lib/emails/send-dataroom-upload-notification.ts
new file mode 100644
index 00000000..02eaf88c
--- /dev/null
+++ b/lib/emails/send-dataroom-upload-notification.ts
@@ -0,0 +1,52 @@
+import DataroomUploadNotification from "@/components/emails/dataroom-upload-notification";
+
+import { sendEmail } from "@/lib/resend";
+
+export const sendDataroomUploadNotification = async ({
+ ownerEmail,
+ dataroomId,
+ dataroomName,
+ uploaderEmail,
+ documentNames,
+ linkName,
+ teamMembers,
+}: {
+ ownerEmail: string;
+ dataroomId: string;
+ dataroomName: string;
+ uploaderEmail: string | null;
+ documentNames: string[];
+ linkName: string;
+ teamMembers?: string[];
+}) => {
+ const documentCount = documentNames.length;
+ const documentLabel = documentCount === 1 ? "document" : "documents";
+
+ let subjectLine = `${documentCount} new ${documentLabel} uploaded to ${dataroomName}`;
+ if (uploaderEmail) {
+ subjectLine = `${uploaderEmail} uploaded ${documentCount} ${documentLabel} to ${dataroomName}`;
+ }
+
+ const emailTemplate = DataroomUploadNotification({
+ dataroomId,
+ dataroomName,
+ uploaderEmail,
+ documentNames,
+ linkName,
+ });
+
+ try {
+ const data = await sendEmail({
+ to: ownerEmail,
+ cc: teamMembers,
+ subject: subjectLine,
+ react: emailTemplate,
+ test: process.env.NODE_ENV === "development",
+ system: true,
+ });
+
+ return { success: true, data };
+ } catch (error) {
+ return { success: false, error };
+ }
+};
diff --git a/lib/trigger/dataroom-upload-notification.ts b/lib/trigger/dataroom-upload-notification.ts
new file mode 100644
index 00000000..69580232
--- /dev/null
+++ b/lib/trigger/dataroom-upload-notification.ts
@@ -0,0 +1,181 @@
+import { logger, task } from "@trigger.dev/sdk/v3";
+
+import prisma from "@/lib/prisma";
+
+type UploadNotificationPayload = {
+ dataroomId: string;
+ linkId: string;
+ teamId: string;
+};
+
+export const sendDataroomUploadNotificationTask = task({
+ id: "send-dataroom-upload-notification",
+ retry: { maxAttempts: 3 },
+ run: async (payload: UploadNotificationPayload) => {
+ const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
+
+ // Get all recent uploads for this dataroom via this link
+ const recentUploads = await prisma.documentUpload.findMany({
+ where: {
+ dataroomId: payload.dataroomId,
+ linkId: payload.linkId,
+ uploadedAt: {
+ gte: fiveMinutesAgo,
+ },
+ },
+ select: {
+ originalFilename: true,
+ viewer: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ orderBy: {
+ uploadedAt: "desc",
+ },
+ });
+
+ if (!recentUploads || recentUploads.length === 0) {
+ logger.info("No recent uploads found for this dataroom link", {
+ dataroomId: payload.dataroomId,
+ linkId: payload.linkId,
+ });
+ return;
+ }
+
+ // Get dataroom and link info
+ const [dataroom, link] = await Promise.all([
+ prisma.dataroom.findUnique({
+ where: { id: payload.dataroomId },
+ select: { name: true, teamId: true },
+ }),
+ prisma.link.findUnique({
+ where: { id: payload.linkId },
+ select: { name: true, ownerId: true },
+ }),
+ ]);
+
+ if (!dataroom) {
+ logger.error("Dataroom not found", {
+ dataroomId: payload.dataroomId,
+ });
+ return;
+ }
+
+ // Get all active team members who are admins or managers
+ const users = await prisma.userTeam.findMany({
+ where: {
+ role: { in: ["ADMIN", "MANAGER"] },
+ status: "ACTIVE",
+ teamId: payload.teamId,
+ },
+ select: {
+ role: true,
+ user: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ });
+
+ const adminEmail = users.find((user) => user.role === "ADMIN")?.user.email;
+
+ if (!adminEmail) {
+ logger.error("No admin email found for team", {
+ teamId: payload.teamId,
+ });
+ return;
+ }
+
+ // Build team members list (excluding admin to avoid duplicate)
+ const teamMembers = users
+ .map((user) => user.user.email!)
+ .filter((email) => email !== adminEmail);
+
+ // Add link owner to team members if they exist and aren't already included
+ if (link?.ownerId) {
+ const linkOwner = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId: link.ownerId,
+ teamId: payload.teamId,
+ },
+ status: "ACTIVE",
+ },
+ select: {
+ user: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ });
+
+ if (
+ linkOwner?.user.email &&
+ linkOwner.user.email !== adminEmail &&
+ !teamMembers.includes(linkOwner.user.email)
+ ) {
+ teamMembers.push(linkOwner.user.email);
+ }
+ }
+
+ const documentNames = recentUploads.map(
+ (upload) => upload.originalFilename || "Untitled document",
+ );
+
+ // Use the first uploader's email (uploads in same batch might be from different visitors)
+ const uploaderEmail = recentUploads[0]?.viewer?.email || null;
+
+ const linkName =
+ link?.name || `Link #${payload.linkId.slice(-5)}`;
+
+ try {
+ const response = await fetch(
+ `${process.env.NEXT_PUBLIC_BASE_URL}/api/jobs/send-dataroom-upload-notification`,
+ {
+ method: "POST",
+ body: JSON.stringify({
+ dataroomId: payload.dataroomId,
+ dataroomName: dataroom.name,
+ uploaderEmail,
+ documentNames,
+ linkName,
+ ownerEmail: adminEmail,
+ teamMembers,
+ teamId: payload.teamId,
+ }),
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${process.env.INTERNAL_API_KEY}`,
+ },
+ },
+ );
+
+ if (!response.ok) {
+ logger.error("Failed to send dataroom upload notification", {
+ dataroomId: payload.dataroomId,
+ linkId: payload.linkId,
+ error: await response.text(),
+ });
+ return;
+ }
+
+ const { message } = (await response.json()) as { message: string };
+ logger.info("Upload notification sent successfully", {
+ dataroomId: payload.dataroomId,
+ linkId: payload.linkId,
+ message,
+ uploadCount: recentUploads.length,
+ });
+ } catch (error) {
+ logger.error("Error sending upload notification", {
+ dataroomId: payload.dataroomId,
+ linkId: payload.linkId,
+ error,
+ });
+ }
+ },
+});
diff --git a/pages/api/jobs/send-dataroom-upload-notification.ts b/pages/api/jobs/send-dataroom-upload-notification.ts
new file mode 100644
index 00000000..61241cc1
--- /dev/null
+++ b/pages/api/jobs/send-dataroom-upload-notification.ts
@@ -0,0 +1,69 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { sendDataroomUploadNotification } from "@/lib/emails/send-dataroom-upload-notification";
+import { log } from "@/lib/utils";
+
+export const config = {
+ maxDuration: 120,
+};
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "POST") {
+ res.status(405).json({ message: "Method Not Allowed" });
+ return;
+ }
+
+ const authHeader = req.headers.authorization;
+ const token = authHeader?.split(" ")[1];
+
+ if (token !== process.env.INTERNAL_API_KEY) {
+ res.status(401).json({ message: "Unauthorized" });
+ return;
+ }
+
+ const {
+ dataroomId,
+ dataroomName,
+ uploaderEmail,
+ documentNames,
+ linkName,
+ ownerEmail,
+ teamMembers,
+ } = req.body as {
+ dataroomId: string;
+ dataroomName: string;
+ uploaderEmail: string | null;
+ documentNames: string[];
+ linkName: string;
+ ownerEmail: string;
+ teamMembers: string[];
+ teamId: string;
+ };
+
+ try {
+ await sendDataroomUploadNotification({
+ ownerEmail,
+ dataroomId,
+ dataroomName,
+ uploaderEmail,
+ documentNames,
+ linkName,
+ teamMembers,
+ });
+
+ res.status(200).json({
+ message: "Successfully sent dataroom upload notification",
+ });
+ return;
+ } catch (error) {
+ log({
+ message: `Failed to send dataroom upload notification for dataroom ${dataroomId}. \n\n Error: ${error}`,
+ type: "error",
+ mention: true,
+ });
+ return res.status(500).json({ message: (error as Error).message });
+ }
+}