Skip to content

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

feat: add dataroom document notifications

Marc Seitzce5631df31ae
diff --git a/components/emails/dataroom-notification.tsx b/components/emails/dataroom-notification.tsx
new file mode 100644
index 00000000..25aca5a8
--- /dev/null
+++ b/components/emails/dataroom-notification.tsx
@@ -0,0 +1,82 @@
+import React from "react";
+import {
+ Body,
+ Container,
+ Head,
+ Heading,
+ Html,
+ Preview,
+ Text,
+ Tailwind,
+ Section,
+ Button,
+ Hr,
+} from "@react-email/components";
+export default function DataroomNotification({
+ dataroomName,
+ documentName,
+ senderEmail,
+ url,
+}: {
+ dataroomName: string;
+ documentName: string | undefined;
+ senderEmail: string;
+ url: string;
+}) {
+ return (
+ <Html>
+ <Head />
+ <Preview>View dataroom on Papermark</Preview>
+ <Tailwind>
+ <Body className="bg-white my-auto mx-auto font-sans">
+ <Container className="my-10 mx-auto p-5 w-[465px]">
+ <Heading className="text-2xl font-normal text-center p-0 mt-4 mb-8 mx-0">
+ <span className="font-bold tracking-tighter">Papermark</span>
+ </Heading>
+ <Heading className="text-xl font-seminbold text-center p-0 mt-4 mb-8 mx-0">
+ {`New document available for ${dataroomName}`}
+ </Heading>
+ <Text className="text-sm leading-6 text-black">Hey!</Text>
+ <Text className="text-sm leading-6 text-black">
+ A new document{" "}
+ <span className="font-semibold">{documentName}</span> has been
+ added to <span className="font-semibold">{dataroomName}</span>{" "}
+ dataroom on Papermark.
+ </Text>
+ <Section className="text-center mt-[32px] mb-[32px]">
+ <Button
+ className="bg-black rounded text-white text-xs font-semibold no-underline text-center"
+ href={`${url}`}
+ style={{ padding: "12px 20px" }}
+ >
+ View the dataroom
+ </Button>
+ </Section>
+ <Text className="text-sm text-black">
+ or copy and paste this URL into your browser: <br />
+ {`${url}`}
+ </Text>
+ <Text className="text-sm text-gray-400">Papermark</Text>
+ <Hr />
+ <Section className="mt-8 text-gray-400">
+ <Text className="text-xs">
+ © {new Date().getFullYear()}{" "}
+ <a
+ href="https://www.papermark.io"
+ className="no-underline text-gray-400 hover:text-gray-400 visited:text-gray-400"
+ target="_blank"
+ >
+ papermark.io
+ </a>
+ </Text>
+ <Text className="text-xs">
+ If you have any feedback or questions about this email, simply
+ reply to it.
+ </Text>
+ </Section>
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/jobs/index.ts b/jobs/index.ts
index 92b39b67..738f030c 100644
--- a/jobs/index.ts
+++ b/jobs/index.ts
@@ -3,3 +3,4 @@
export * from "./convert-pdf-to-image";
export * from "./send-notification";
export * from "./send-dataroom-invitations";
+export * from "./send-dataroom-notification";
diff --git a/jobs/send-dataroom-notification.ts b/jobs/send-dataroom-notification.ts
new file mode 100644
index 00000000..4f6293f7
--- /dev/null
+++ b/jobs/send-dataroom-notification.ts
@@ -0,0 +1,93 @@
+import { client } from "@/trigger";
+import { eventTrigger } from "@trigger.dev/sdk";
+import { z } from "zod";
+import prisma from "@/lib/prisma";
+
+client.defineJob({
+ id: "send-dataroom-notification",
+ name: "Send Dataroom Notification",
+ version: "0.0.1",
+ trigger: eventTrigger({
+ name: "dataroom.new_document",
+ schema: z.object({
+ dataroomId: z.string(),
+ dataroomDocumentId: z.string(),
+ linkId: z.string(),
+ senderUserId: z.string(),
+ }),
+ }),
+ run: async (payload, io, ctx) => {
+ const { dataroomId, dataroomDocumentId, linkId, senderUserId } = payload;
+
+ const viewerIds = await io.runTask("get-viewer-ids", async () => {
+ const viewerIds = await prisma.viewer.findMany({
+ where: {
+ dataroomId,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (!viewerIds) {
+ await io.logger.error("Failed to get viewer ids", { payload });
+ return [];
+ }
+
+ return viewerIds;
+ });
+
+ if (!viewerIds || viewerIds.length === 0) {
+ return {
+ success: false,
+ message: "No viewers found for this dataroom.",
+ };
+ }
+
+ for (var i = 0; i < viewerIds.length; ++i) {
+ // get file url from document version
+ await io.runTask(
+ `send-viewer-notification-${viewerIds[i].id}`,
+ async () => {
+ const response = await fetch(
+ `${process.env.NEXT_PUBLIC_BASE_URL}/api/jobs/send-dataroom-notifications`,
+ {
+ method: "POST",
+ body: JSON.stringify({
+ dataroomId,
+ linkId,
+ dataroomDocumentId,
+ viewerId: viewerIds[i].id,
+ senderUserId,
+ }),
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${process.env.INTERNAL_API_KEY}`,
+ },
+ },
+ );
+
+ if (!response.ok) {
+ await io.logger.error("Failed to send dataroom notification", {
+ payload,
+ viewerId: viewerIds[i],
+ });
+ return;
+ }
+
+ const { message } = (await response.json()) as {
+ message: string;
+ };
+
+ await io.logger.info("Invitation sent", { message, payload });
+ return { message };
+ },
+ );
+ }
+
+ return {
+ success: true,
+ message: "Successfully sent view invitations",
+ };
+ },
+});
diff --git a/lib/emails/send-dataroom-notification.ts b/lib/emails/send-dataroom-notification.ts
new file mode 100644
index 00000000..7fbf6865
--- /dev/null
+++ b/lib/emails/send-dataroom-notification.ts
@@ -0,0 +1,33 @@
+import DataroomNotification from "@/components/emails/dataroom-notification";
+import { sendEmail } from "@/lib/resend";
+
+export const sendDataroomNotification = async ({
+ dataroomName,
+ documentName,
+ senderEmail,
+ to,
+ url,
+}: {
+ dataroomName: string;
+ documentName: string | undefined;
+ senderEmail: string;
+ to: string;
+ url: string;
+}) => {
+ try {
+ await sendEmail({
+ to: to,
+ subject: `New document available in ${dataroomName}`,
+ react: DataroomNotification({
+ senderEmail,
+ dataroomName,
+ documentName,
+ url,
+ }),
+ test: process.env.NODE_ENV === "development",
+ system: true,
+ });
+ } catch (e) {
+ console.error(e);
+ }
+};
diff --git a/pages/api/jobs/send-dataroom-notifications.ts b/pages/api/jobs/send-dataroom-notifications.ts
new file mode 100644
index 00000000..02550336
--- /dev/null
+++ b/pages/api/jobs/send-dataroom-notifications.ts
@@ -0,0 +1,119 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import prisma from "@/lib/prisma";
+import { log } from "@/lib/utils";
+import { sendDataroomNotification } from "@/lib/emails/send-dataroom-notification";
+
+export const config = {
+ maxDuration: 120,
+};
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ // We only allow POST requests
+ if (req.method !== "POST") {
+ res.status(405).json({ message: "Method Not Allowed" });
+ return;
+ }
+
+ // Extract the API Key from the Authorization header
+ const authHeader = req.headers.authorization;
+ const token = authHeader?.split(" ")[1]; // Assuming the format is "Bearer [token]"
+
+ // Check if the API Key matches
+ if (token !== process.env.INTERNAL_API_KEY) {
+ res.status(401).json({ message: "Unauthorized" });
+ return;
+ }
+
+ const { linkId, dataroomId, dataroomDocumentId, viewerId, senderUserId } =
+ req.body as {
+ linkId: string;
+ dataroomId: string;
+ dataroomDocumentId: string;
+ viewerId: string;
+ senderUserId: string;
+ };
+
+ let viewer: { email: string; dataroom: { name: string } } | null = null;
+
+ try {
+ // Fetch the link to verify the settings
+ viewer = await prisma.viewer.findUnique({
+ where: {
+ id: viewerId,
+ dataroomId: dataroomId,
+ },
+ select: {
+ email: true,
+ dataroom: {
+ select: {
+ name: true,
+ },
+ },
+ },
+ });
+
+ if (!viewer) {
+ res.status(404).json({ message: "Viewer not found." });
+ return;
+ }
+ } catch (error) {
+ log({
+ message: `Failed to find viewer for viewerId: ${viewerId}. \n\n Error: ${error}`,
+ type: "error",
+ mention: true,
+ });
+ res.status(500).json({ message: (error as Error).message });
+ return;
+ }
+
+ // POST /api/jobs/send-datarooom-notification
+ try {
+ // Fetch the document to verify the settings
+ const document = await prisma.dataroomDocument.findUnique({
+ where: {
+ id: dataroomDocumentId,
+ dataroomId: dataroomId,
+ },
+ select: {
+ document: {
+ select: {
+ name: true,
+ },
+ },
+ },
+ });
+
+ const user = await prisma.user.findUnique({
+ where: { id: senderUserId },
+ select: { email: true },
+ });
+
+ if (!user) {
+ res.status(404).json({ message: "Sender not found." });
+ return;
+ }
+
+ await sendDataroomNotification({
+ dataroomName: viewer.dataroom.name,
+ senderEmail: user.email!,
+ documentName: document?.document.name,
+ to: viewer.email,
+ url: `${process.env.NEXTAUTH_URL}/view/d/${linkId}?email=${encodeURIComponent(viewer.email)}`,
+ });
+
+ res
+ .status(200)
+ .json({ message: "Successfully sent dataroom notification", viewerId });
+ return;
+ } catch (error) {
+ log({
+ message: `Failed to send invite email for dataroom ${dataroomId} to viewer: ${viewerId}. \n\n Error: ${error} \n\n*Metadata*: \`{dataroomId: ${dataroomId}, viewerId: ${viewerId}}\``,
+ type: "error",
+ mention: true,
+ });
+ return res.status(500).json({ message: (error as Error).message });
+ }
+}
diff --git a/pages/api/jobs/send-dataroom-view-invitation.ts b/pages/api/jobs/send-dataroom-view-invitation.ts
index 84769f3d..1d2ad354 100644
--- a/pages/api/jobs/send-dataroom-view-invitation.ts
+++ b/pages/api/jobs/send-dataroom-view-invitation.ts
@@ -1,12 +1,10 @@
import { NextApiRequest, NextApiResponse } from "next";
import prisma from "@/lib/prisma";
-import { sendViewedDocumentEmail } from "@/lib/emails/send-viewed-document";
import { log } from "@/lib/utils";
import { sendDataroomViewerInvite } from "@/lib/emails/send-dataroom-viewer-invite";
-import { Viewer } from "@prisma/client";
export const config = {
- maxDuration: 60,
+ maxDuration: 120,
};
export default async function handle(
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts
index 7c8cb417..0f1ba073 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts
@@ -7,6 +7,7 @@ import slugify from "@sindresorhus/slugify";
import { newId } from "@/lib/id-helper";
import { log } from "@/lib/utils";
import { errorhandler } from "@/lib/errorHandler";
+import { client } from "@/trigger";
export default async function handle(
req: NextApiRequest,
@@ -139,6 +140,28 @@ export default async function handle(
dataroomId,
folderId: folder?.id,
},
+ include: {
+ dataroom: {
+ select: {
+ links: {
+ select: { id: true },
+ orderBy: { createdAt: "desc" },
+ take: 1,
+ },
+ },
+ },
+ },
+ });
+
+ // trigger `dataroom.new_document` event to notify existing viewers
+ await client.sendEvent({
+ name: "dataroom.new_document",
+ payload: {
+ dataroomId: dataroomId,
+ dataroomDocumentId: document.id,
+ linkId: document.dataroom.links[0].id,
+ senderUserId: userId,
+ },
});
return res.status(201).json(document);