Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add dataroom notifications
Marc Seitz7ff9fda67938
diff --git a/components/emails/dataroom-notification.tsx b/components/emails/dataroom-notification.tsxindex 1810644a..ffab49bd 100644--- a/components/emails/dataroom-notification.tsx+++ b/components/emails/dataroom-notification.tsx@@ -18,16 +18,18 @@ export default function DataroomNotification({documentName,senderEmail,url,+ unsubscribeUrl,}: {dataroomName: string;documentName: string | undefined;senderEmail: string;url: string;+ unsubscribeUrl: string;}) {return (<Html><Head />- <Preview>View dataroom on Papermark</Preview>+ <Preview>Dataroom update available</Preview><Tailwind><Body className="mx-auto my-auto bg-white font-sans"><Container className="mx-auto my-10 w-[465px] p-5">@@ -37,7 +39,6 @@ export default function DataroomNotification({<Text className="font-seminbold mx-0 mb-8 mt-4 p-0 text-center text-xl">{`New document available for ${dataroomName}`}</Text>- <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@@ -71,8 +72,20 @@ export default function DataroomNotification({</a></Text><Text className="text-xs">- If you have any feedback or questions about this email, simply- reply to it.+ You received this email from{" "}+ <span className="font-semibold">{senderEmail}</span> because you+ viewed the dataroom{" "}+ <span className="font-semibold">{dataroomName}</span> on+ Papermark. If you have any feedback or questions about this+ email, simply reply to it. To unsubscribe from updates about+ this dataroom,{" "}+ <a+ href={unsubscribeUrl}+ className="text-gray-400 underline underline-offset-2 visited:text-gray-400 hover:text-gray-400"+ >+ click here+ </a>+ .</Text></Section></Container>diff --git a/components/visitors/dataroom-viewers.tsx b/components/visitors/dataroom-viewers.tsxindex a912ab42..bea4f9e2 100644--- a/components/visitors/dataroom-viewers.tsx+++ b/components/visitors/dataroom-viewers.tsx@@ -39,7 +39,7 @@ export default function DataroomViewersTable({return (<div className="w-full"><div>- <h2 className="mb-2 md:mb-4">All dataroom viewers</h2>+ <h2 className="mb-2 md:mb-4">All dataroom visitors</h2></div><div className="rounded-md border"><Table>diff --git a/lib/constants.ts b/lib/constants.tsindex 69abc170..26566338 100644--- a/lib/constants.ts+++ b/lib/constants.ts@@ -53,23 +53,7 @@ export const BLOCKED_PATHNAMES = [];// list of paths that should be excluded from team checks-export const EXCLUDED_PATHS = [- "/",- "/register",- "/privacy",- "/oss-friends",- "/pricing",- "/docsend-alternatives",- "/launch-week",- "/open-source-investors",- "/investors",- "/ai",- "/share-notion-page",- "/alternatives",- "/investors",- "/blog",- "/view",-];+export const EXCLUDED_PATHS = ["/", "/register", "/privacy", "/view"];// free limitsexport const LIMITS = {diff --git a/lib/emails/send-dataroom-notification.ts b/lib/emails/send-dataroom-notification.tsindex 3dd61834..d30b276d 100644--- a/lib/emails/send-dataroom-notification.ts+++ b/lib/emails/send-dataroom-notification.ts@@ -8,12 +8,14 @@ export const sendDataroomNotification = async ({senderEmail,to,url,+ unsubscribeUrl,}: {dataroomName: string;documentName: string | undefined;senderEmail: string;to: string;url: string;+ unsubscribeUrl: string;}) => {try {await sendEmail({@@ -24,9 +26,11 @@ export const sendDataroomNotification = async ({dataroomName,documentName,url,+ unsubscribeUrl,}),test: process.env.NODE_ENV === "development",system: true,+ unsubscribeUrl,});} catch (e) {console.error(e);diff --git a/lib/resend.ts b/lib/resend.tsindex 78a0ff94..c144a643 100644--- a/lib/resend.ts+++ b/lib/resend.ts@@ -19,6 +19,7 @@ export const sendEmail = async ({test,cc,scheduledAt,+ unsubscribeUrl,}: {to: string;subject: string;@@ -29,6 +30,7 @@ export const sendEmail = async ({test?: boolean;cc?: string | string[];scheduledAt?: string;+ unsubscribeUrl?: string;}) => {if (!resend) {// Throw an error if resend is not initialized@@ -57,6 +59,7 @@ export const sendEmail = async ({text: plainText,headers: {"X-Entity-Ref-ID": nanoid(),+ ...(unsubscribeUrl ? { "List-Unsubscribe": unsubscribeUrl } : {}),},});diff --git a/lib/trigger/dataroom-change-notification.ts b/lib/trigger/dataroom-change-notification.tsnew file mode 100644index 00000000..e48f1ba4--- /dev/null+++ b/lib/trigger/dataroom-change-notification.ts@@ -0,0 +1,162 @@+import { logger, task } from "@trigger.dev/sdk/v3";++import prisma from "@/lib/prisma";++import { ZNotificationPreferencesSchema } from "../types";++type NotificationPayload = {+ dataroomId: string;+ dataroomDocumentId: string;+ senderUserId: string;+ teamId: string;+};++export const sendDataroomChangeNotificationTask = task({+ id: "send-dataroom-change-notification",+ retry: { maxAttempts: 3 },+ run: async (payload: NotificationPayload) => {+ // Get all verified viewers for this dataroom+ const viewers = await prisma.viewer.findMany({+ where: {+ teamId: payload.teamId,+ views: {+ some: {+ dataroomId: payload.dataroomId,+ viewType: "DATAROOM_VIEW",+ verified: true,+ },+ },+ },+ select: {+ id: true,+ notificationPreferences: true,+ views: {+ where: {+ dataroomId: payload.dataroomId,+ viewType: "DATAROOM_VIEW",+ verified: true,+ },+ orderBy: {+ viewedAt: "desc",+ },+ take: 1,+ include: {+ link: {+ select: {+ id: true,+ slug: true,+ domainSlug: true,+ domainId: true,+ isArchived: true,+ expiresAt: true,+ },+ },+ },+ },+ },+ });++ if (!viewers || viewers.length === 0) {+ logger.info("No verified viewers found for this dataroom", {+ dataroomId: payload.dataroomId,+ });+ return;+ }++ // Construct simplified viewer objects with email and link info, excluding expired/archived links+ const viewersWithLinks = viewers+ .map((viewer) => {+ const view = viewer.views[0];+ const link = view?.link;++ // Skip if link is expired or archived+ if (+ !link ||+ link.isArchived ||+ (link.expiresAt && new Date(link.expiresAt) < new Date())+ ) {+ return null;+ }++ // Skip if notifications are disabled for this dataroom+ const parsedPreferences = ZNotificationPreferencesSchema.safeParse(+ viewer.notificationPreferences,+ );+ if (+ parsedPreferences.success &&+ parsedPreferences.data.dataroom[payload.dataroomId]?.enabled === false+ ) {+ return null;+ }++ let linkUrl = "";+ if (link.domainId && link.domainSlug && link.slug) {+ linkUrl = `https://${link.domainSlug}/${link.slug}`;+ } else {+ linkUrl = `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${link.id}`;+ }++ return {+ id: viewer.id,+ linkUrl,+ };+ })+ .filter(+ (viewer): viewer is { id: string; linkUrl: string } => viewer !== null,+ );++ logger.info("Processed viewer links", {+ viewerCount: viewersWithLinks.length,+ });++ // Send notification to each viewer+ for (const viewer of viewersWithLinks) {+ try {+ const response = await fetch(+ `${process.env.NEXT_PUBLIC_BASE_URL}/api/jobs/send-dataroom-new-document-notification`,+ {+ method: "POST",+ body: JSON.stringify({+ dataroomId: payload.dataroomId,+ linkUrl: viewer.linkUrl,+ dataroomDocumentId: payload.dataroomDocumentId,+ viewerId: viewer.id,+ senderUserId: payload.senderUserId,+ teamId: payload.teamId,+ }),+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${process.env.INTERNAL_API_KEY}`,+ },+ },+ );++ if (!response.ok) {+ logger.error("Failed to send dataroom notification", {+ viewerId: viewer.id,+ dataroomId: payload.dataroomId,+ error: await response.text(),+ });+ continue;+ }++ const { message } = (await response.json()) as { message: string };+ logger.info("Notification sent successfully", {+ viewerId: viewer.id,+ message,+ });+ } catch (error) {+ logger.error("Error sending notification", {+ viewerId: viewer.id,+ error,+ });+ }+ }++ logger.info("Completed sending notifications", {+ dataroomId: payload.dataroomId,+ viewerCount: viewers.length,+ });+ return;+ },+});diff --git a/lib/types.ts b/lib/types.tsindex cab3e01f..ad16e41d 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -284,3 +284,14 @@ export const WatermarkConfigSchema = z.object({export type WatermarkConfig = z.infer<typeof WatermarkConfigSchema>;export type NotionTheme = "light" | "dark";++export const ZNotificationPreferencesSchema = z+ .object({+ dataroom: z.record(+ z.object({+ enabled: z.boolean(),+ }),+ ),+ })+ .optional()+ .default({ dataroom: {} });diff --git a/lib/utils/unsubscribe.ts b/lib/utils/unsubscribe.tsnew file mode 100644index 00000000..e8259ddd--- /dev/null+++ b/lib/utils/unsubscribe.ts@@ -0,0 +1,32 @@+import jwt from "jsonwebtoken";++const JWT_SECRET = process.env.NEXT_PRIVATE_UNSUBSCRIBE_JWT_SECRET as string;+const UNSUBSCRIBE_BASE_URL = process.env.NEXT_PUBLIC_BASE_URL as string;++type UnsubscribePayload = {+ viewerId: string;+ dataroomId: string;+ teamId: string;+ exp?: number; // Expiration timestamp+};++export function generateUnsubscribeUrl(payload: UnsubscribePayload): string {+ // Add expiration of 3 months+ const tokenPayload = {+ ...payload,+ exp: Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 90,+ };++ const token = jwt.sign(tokenPayload, JWT_SECRET);+ return `${UNSUBSCRIBE_BASE_URL}/api/unsubscribe/dataroom?token=${token}`;+}++export function verifyUnsubscribeToken(+ token: string,+): UnsubscribePayload | null {+ try {+ return jwt.verify(token, JWT_SECRET) as UnsubscribePayload;+ } catch (error) {+ return null;+ }+}diff --git a/middleware.ts b/middleware.tsindex c1616b09..107f21e1 100644--- a/middleware.ts+++ b/middleware.ts@@ -58,7 +58,11 @@ export default async function middleware(req: NextRequest, ev: NextFetchEvent) {return DomainMiddleware(req);}- if (!path.startsWith("/view/") && !path.startsWith("/verify")) {+ if (+ !path.startsWith("/view/") &&+ !path.startsWith("/verify") &&+ !path.startsWith("/unsubscribe")+ ) {return AppMiddleware(req);}diff --git a/next.config.mjs b/next.config.mjsindex 42d4e441..5625d216 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -79,6 +79,15 @@ const nextConfig = {},],},+ {+ source: "/unsubscribe",+ headers: [+ {+ key: "X-Robots-Tag",+ value: "noindex",+ },+ ],+ },];},experimental: {diff --git a/package-lock.json b/package-lock.jsonindex 9325de19..ed910a41 100644--- a/package-lock.json+++ b/package-lock.json@@ -76,6 +76,7 @@"handlebars": "^4.7.8","input-otp": "^1.4.1","js-cookie": "^3.0.5",+ "jsonwebtoken": "^9.0.2","lucide-react": "^0.460.0","mime-types": "^2.1.35","ms": "^2.1.3",@@ -128,6 +129,7 @@"@trivago/prettier-plugin-sort-imports": "^4.3.0","@types/bcryptjs": "^2.4.6","@types/js-cookie": "^3.0.6",+ "@types/jsonwebtoken": "^9.0.7","@types/mime-types": "^2.1.4","@types/ms": "^0.7.34","@types/node": "^20",@@ -6562,6 +6564,15 @@"resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz","integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ=="},+ "node_modules/@types/jsonwebtoken": {+ "version": "9.0.7",+ "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.7.tgz",+ "integrity": "sha512-ugo316mmTYBl2g81zDFnZ7cfxlut3o+/EQdaP7J8QN2kY6lJ22hmQYCK5EHcJHbrW+dkCGSCPgbG8JtYj6qSrg==",+ "dev": true,+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@types/mime-types": {"version": "2.1.4","resolved": "https://registry.npmjs.org/@types/mime-types/-/mime-types-2.1.4.tgz",@@ -7718,6 +7729,11 @@"ieee754": "^1.1.13"}},+ "node_modules/buffer-equal-constant-time": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",+ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="+ },"node_modules/buffer-from": {"version": "1.1.2","resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",@@ -8662,6 +8678,14 @@"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz","integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA=="},+ "node_modules/ecdsa-sig-formatter": {+ "version": "1.0.11",+ "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",+ "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",+ "dependencies": {+ "safe-buffer": "^5.0.1"+ }+ },"node_modules/editorconfig": {"version": "1.0.4","resolved": "https://registry.npmjs.org/editorconfig/-/editorconfig-1.0.4.tgz",@@ -11048,6 +11072,27 @@"node": ">=6"}},+ "node_modules/jsonwebtoken": {+ "version": "9.0.2",+ "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz",+ "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==",+ "dependencies": {+ "jws": "^3.2.2",+ "lodash.includes": "^4.3.0",+ "lodash.isboolean": "^3.0.3",+ "lodash.isinteger": "^4.0.4",+ "lodash.isnumber": "^3.0.3",+ "lodash.isplainobject": "^4.0.6",+ "lodash.isstring": "^4.0.1",+ "lodash.once": "^4.0.0",+ "ms": "^2.1.1",+ "semver": "^7.5.4"+ },+ "engines": {+ "node": ">=12",+ "npm": ">=6"+ }+ },"node_modules/jsx-ast-utils": {"version": "3.3.5","resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz",@@ -11062,6 +11107,25 @@"node": ">=4.0"}},+ "node_modules/jwa": {+ "version": "1.4.1",+ "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz",+ "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==",+ "dependencies": {+ "buffer-equal-constant-time": "1.0.1",+ "ecdsa-sig-formatter": "1.0.11",+ "safe-buffer": "^5.0.1"+ }+ },+ "node_modules/jws": {+ "version": "3.2.2",+ "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz",+ "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==",+ "dependencies": {+ "jwa": "^1.4.1",+ "safe-buffer": "^5.0.1"+ }+ },"node_modules/katex": {"version": "0.16.11","resolved": "https://registry.npmjs.org/katex/-/katex-0.16.11.tgz",@@ -11233,16 +11297,46 @@"resolved": "https://registry.npmjs.org/lodash.castarray/-/lodash.castarray-4.4.0.tgz","integrity": "sha512-aVx8ztPv7/2ULbArGJ2Y42bG1mEQ5mGjpdvrbJcJFU3TbYybe+QlLS4pst9zV52ymy2in1KpFPiZnAOATxD4+Q=="},+ "node_modules/lodash.includes": {+ "version": "4.3.0",+ "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",+ "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w=="+ },+ "node_modules/lodash.isboolean": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",+ "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg=="+ },+ "node_modules/lodash.isinteger": {+ "version": "4.0.4",+ "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",+ "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA=="+ },+ "node_modules/lodash.isnumber": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",+ "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw=="+ },"node_modules/lodash.isplainobject": {"version": "4.0.6","resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz","integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA=="},+ "node_modules/lodash.isstring": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",+ "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw=="+ },"node_modules/lodash.merge": {"version": "4.6.2","resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz","integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ=="},+ "node_modules/lodash.once": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",+ "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg=="+ },"node_modules/lodash.throttle": {"version": "4.1.1","resolved": "https://registry.npmjs.org/lodash.throttle/-/lodash.throttle-4.1.1.tgz",diff --git a/package.json b/package.jsonindex d0810bc1..0b2e35e5 100644--- a/package.json+++ b/package.json@@ -87,6 +87,7 @@"handlebars": "^4.7.8","input-otp": "^1.4.1","js-cookie": "^3.0.5",+ "jsonwebtoken": "^9.0.2","lucide-react": "^0.460.0","mime-types": "^2.1.35","ms": "^2.1.3",@@ -139,6 +140,7 @@"@trivago/prettier-plugin-sort-imports": "^4.3.0","@types/bcryptjs": "^2.4.6","@types/js-cookie": "^3.0.6",+ "@types/jsonwebtoken": "^9.0.7","@types/mime-types": "^2.1.4","@types/ms": "^0.7.34","@types/node": "^20",@@ -158,4 +160,4 @@"react-pdf": "8.0.2"}}-}+}\ No newline at end of filediff --git a/pages/api/jobs/send-dataroom-new-document-notification.ts b/pages/api/jobs/send-dataroom-new-document-notification.tsindex 3f5228e8..d752e8ab 100644--- a/pages/api/jobs/send-dataroom-new-document-notification.ts+++ b/pages/api/jobs/send-dataroom-new-document-notification.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { sendDataroomNotification } from "@/lib/emails/send-dataroom-notification";import prisma from "@/lib/prisma";import { log } from "@/lib/utils";+import { generateUnsubscribeUrl } from "@/lib/utils/unsubscribe";export const config = {maxDuration: 120,@@ -28,31 +29,33 @@ export default async function handle(return;}- const { linkId, dataroomId, dataroomDocumentId, viewerId, senderUserId } =- req.body as {- linkId: string;- dataroomId: string;- dataroomDocumentId: string;- viewerId: string;- senderUserId: string;- };+ const {+ linkUrl,+ dataroomId,+ dataroomDocumentId,+ viewerId,+ senderUserId,+ teamId,+ } = req.body as {+ linkUrl: string;+ dataroomId: string;+ dataroomDocumentId: string;+ viewerId: string;+ senderUserId: string;+ teamId: string;+ };- let viewer: { email: string; dataroom: { name: string } | null } | null =- null;+ let viewer: { email: string } | null = null;try {// Fetch the link to verify the settingsviewer = await prisma.viewer.findUnique({where: {id: viewerId,+ teamId,},select: {email: true,- dataroom: {- select: {- name: true,- },- },},});@@ -84,6 +87,11 @@ export default async function handle(name: true,},},+ dataroom: {+ select: {+ name: true,+ },+ },},});@@ -97,17 +105,25 @@ export default async function handle(return;}+ const unsubscribeUrl = generateUnsubscribeUrl({+ viewerId,+ dataroomId,+ teamId,+ });+await sendDataroomNotification({- dataroomName: viewer.dataroom?.name ?? "",+ dataroomName: document?.dataroom.name ?? "",senderEmail: user.email!,documentName: document?.document.name,to: viewer.email,- url: `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${linkId}?email=${encodeURIComponent(viewer.email)}`,+ url: `${linkUrl}?email=${encodeURIComponent(viewer.email)}`,+ unsubscribeUrl,});- res- .status(200)- .json({ message: "Successfully sent dataroom notification", viewerId });+ res.status(200).json({+ message: "Successfully sent dataroom change notification",+ viewerId,+ });return;} catch (error) {log({diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/index.tsindex 627c82fa..2657c52b 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts@@ -1,14 +1,21 @@import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { waitUntil } from "@vercel/functions";import { getServerSession } from "next-auth/next";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";+import { sendDataroomChangeNotificationTask } from "@/lib/trigger/dataroom-change-notification";import { CustomUser } from "@/lib/types";import { log } from "@/lib/utils";import { sortItemsByIndexAndName } from "@/lib/utils/sort-items-by-index-name";+export const config = {+ // in order to enable `waitUntil` function+ supportsResponseStreaming: true,+};+export default async function handle(req: NextApiRequest,res: NextApiResponse,@@ -151,16 +158,32 @@ export default async function handle(},});- // 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,- // },- // });+ // Check if the team has the change notification feature flag enabled+ const featureFlags = await fetch(+ `${process.env.NEXTAUTH_URL}/api/feature-flags?teamId=${teamId}`,+ ).then((res) => res.json());++ if (featureFlags.roomChangeNotifications) {+ waitUntil(+ sendDataroomChangeNotificationTask.trigger(+ {+ dataroomId,+ dataroomDocumentId: document.id,+ senderUserId: userId,+ teamId,+ },+ {+ idempotencyKey: `dataroom-notification-${teamId}-${dataroomId}-${document.id}`,+ tags: [+ `team_${teamId}`,+ `dataroom_${dataroomId}`,+ `document_${document.id}`,+ ],+ delay: new Date(Date.now() + 10 * 60 * 1000), // 10 minute delay+ },+ ),+ );+ }return res.status(201).json(document);} catch (error) {@@ -172,7 +195,7 @@ export default async function handle(}} else {// We only allow GET requests- res.setHeader("Allow", ["GET"]);+ res.setHeader("Allow", ["GET", "POST"]);return res.status(405).end(`Method ${req.method} Not Allowed`);}}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/viewers/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/viewers/index.tsindex c8d2404d..bd9f9fa2 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/viewers/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/viewers/index.ts@@ -30,9 +30,7 @@ export default async function handle(where: {id: teamId,users: {- some: {- userId: (session.user as CustomUser).id,- },+ some: { userId },},},select: {@@ -46,6 +44,7 @@ export default async function handle(const viewers = await prisma.viewer.findMany({where: {+ teamId: teamId,views: {some: {dataroomId: dataroomId,@@ -57,6 +56,7 @@ export default async function handle(id: true,teamId: true,email: true,+ verified: true,views: {where: {dataroomId: dataroomId,@@ -65,13 +65,6 @@ export default async function handle(orderBy: {viewedAt: "desc",},- include: {- link: {- select: {- name: true,- },- },- },},},});diff --git a/pages/api/teams/[teamId]/datarooms/trial.ts b/pages/api/teams/[teamId]/datarooms/trial.tsindex 505d07cd..2756867e 100644--- a/pages/api/teams/[teamId]/datarooms/trial.ts+++ b/pages/api/teams/[teamId]/datarooms/trial.ts@@ -14,6 +14,11 @@ import {import { CustomUser } from "@/lib/types";import { log } from "@/lib/utils";+export const config = {+ // in order to enable `waitUntil` function+ supportsResponseStreaming: true,+};+export default async function handle(req: NextApiRequest,res: NextApiResponse,diff --git a/pages/api/unsubscribe/dataroom/index.ts b/pages/api/unsubscribe/dataroom/index.tsnew file mode 100644index 00000000..c96a0da5--- /dev/null+++ b/pages/api/unsubscribe/dataroom/index.ts@@ -0,0 +1,119 @@+import { NextApiRequest, NextApiResponse } from "next";++import prisma from "@/lib/prisma";+import { ratelimit } from "@/lib/redis";+import { ZNotificationPreferencesSchema } from "@/lib/types";+import { verifyUnsubscribeToken } from "@/lib/utils/unsubscribe";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "POST" && req.method !== "GET") {+ res.status(405).json({ message: "Method Not Allowed" });+ return;+ }++ const { token } = req.query as { token: string };++ try {+ if (!token) {+ res.status(400).json({ message: "Token is required" });+ return;+ }++ if (req.method === "GET") {+ // For GET requests, redirect to the unsubscribe page+ return res.redirect(`/unsubscribe?token=${token}`);+ }++ // Rate limit the unsubscribe request+ const ipAddress =+ req.headers["x-forwarded-for"] || req.socket.remoteAddress || "127.0.0.1";+ const { success, limit, reset, remaining } = await ratelimit(+ 5,+ "1 m",+ ).limit(`unsubscribe_${ipAddress}`);++ // Set rate limit headers+ res.setHeader("Retry-After", reset.toString());+ res.setHeader("X-RateLimit-Limit", limit.toString());+ res.setHeader("X-RateLimit-Remaining", remaining.toString());+ res.setHeader("X-RateLimit-Reset", reset.toString());++ if (!success) {+ return res.status(429).json({ error: "Too many requests" });+ }++ const payload = verifyUnsubscribeToken(token);++ if (!payload) {+ res.status(404).json({ message: "Invalid token" });+ return;+ }++ if (payload.exp && payload.exp < new Date().getTime() / 1000) {+ res.status(404).json({ message: "Token expired" });+ return;+ }++ const { viewerId, dataroomId, teamId } = payload;++ // Fetch the current notification preferences+ const viewer = await prisma.viewer.findUnique({+ where: { id: viewerId, teamId },+ select: { notificationPreferences: true },+ });++ if (!viewer) {+ res.status(404).json({ message: "Viewer not found" });+ return;+ }++ // Parse the existing preferences or initialize an empty object+ // Example preferences object:+ // {+ // "dataroom": {+ // "123": { enabled: true, frequency: "instant" },+ // "456": { enabled: false, frequency: "daily" }+ // },+ // "document": {+ // "789": { enabled: true, frequency: "weekly" }+ // }+ // }+ let updatedPreferences;++ if (viewer.notificationPreferences) {+ // Parse the existing preferences+ const defaultPreferences = ZNotificationPreferencesSchema.safeParse(+ viewer.notificationPreferences,+ );++ // Update the preferences for the specific dataroom+ updatedPreferences = {+ ...defaultPreferences.data,+ dataroom: {+ ...defaultPreferences.data?.dataroom,+ [dataroomId]: { enabled: false },+ },+ };+ } else {+ // If no preferences exist, initialize with the dataroom preference+ updatedPreferences = {+ dataroom: { [dataroomId]: { enabled: false } },+ };+ }++ // Update the viewer's notification preferences in the database+ await prisma.viewer.update({+ where: { id: viewerId, teamId },+ data: { notificationPreferences: updatedPreferences },+ });++ res+ .status(200)+ .json({ message: "Successfully unsubscribed from notifications." });+ } catch (error) {+ res.status(500).json({ message: (error as Error).message });+ }+}diff --git a/pages/datarooms/[id]/users/index.tsx b/pages/datarooms/[id]/users/index.tsxindex 9876c80d..cfc67214 100644--- a/pages/datarooms/[id]/users/index.tsx+++ b/pages/datarooms/[id]/users/index.tsx@@ -1,18 +1,25 @@-import { useState } from "react";+import { useTeam } from "@/context/team-context";+import { AlertCircleIcon } from "lucide-react";+import useSWR from "swr";-import { AddViewerModal } from "@/components/datarooms/add-viewer-modal";import { DataroomHeader } from "@/components/datarooms/dataroom-header";import { DataroomNavigation } from "@/components/datarooms/dataroom-navigation";import AppLayout from "@/components/layouts/app";-import { Button } from "@/components/ui/button";+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";import DataroomViewersTable from "@/components/visitors/dataroom-viewers";import { useDataroom } from "@/lib/swr/use-dataroom";+import { fetcher } from "@/lib/utils";-export default function DataroomPage() {+export default function DataroomUsersPage() {+ const teamInfo = useTeam();const { dataroom } = useDataroom();-- const [modalOpen, setModalOpen] = useState<boolean>(false);+ const { data: features } = useSWR<{ roomChangeNotifications: boolean }>(+ teamInfo?.currentTeam?.id+ ? `/api/feature-flags?teamId=${teamInfo.currentTeam.id}`+ : null,+ fetcher,+ );if (!dataroom) {return <div>Loading...</div>;@@ -22,32 +29,25 @@ export default function DataroomPage() {<AppLayout><div className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10"><header>- <DataroomHeader- title={dataroom.name}- description={dataroom.pId}- // actions={[- // <Button- // disabled={true}- // onClick={() => setModalOpen(true)}- // key={1}- // >- // Invite users- // </Button>,- // ]}- />+ <DataroomHeader title={dataroom.name} description={dataroom.pId} /><DataroomNavigation dataroomId={dataroom.id} /></header>+ {features?.roomChangeNotifications && (+ <Alert>+ <AlertCircleIcon className="h-4 w-4" />+ <AlertTitle>Dataroom Change Notifications</AlertTitle>+ <AlertDescription>+ Verified visitors will be automatically notified by email when new+ documents are added to this dataroom.+ </AlertDescription>+ </Alert>+ )}+<div className="space-y-4">{/* Visitors */}<DataroomViewersTable dataroomId={dataroom.id} />-- {/* <AddViewerModal- dataroomId={dataroom.id}- open={modalOpen}- setOpen={setModalOpen}- /> */}</div></div></AppLayout>diff --git a/pages/unsubscribe.tsx b/pages/unsubscribe.tsxnew file mode 100644index 00000000..91eb3738--- /dev/null+++ b/pages/unsubscribe.tsx@@ -0,0 +1,78 @@+import { useRouter } from "next/router";++import { useState } from "react";++import { Button } from "@/components/ui/button";++export default function UnsubscribePage() {+ const router = useRouter();+ const { token } = router.query as { token: string };+ const [status, setStatus] = useState<"idle" | "success" | "error">("idle");+ const [loading, setLoading] = useState(false);+ const [message, setMessage] = useState("");++ const handleUnsubscribe = async () => {+ try {+ if (!token) {+ setStatus("error");+ setMessage("Token is required");+ return;+ }+ setLoading(true);+ const response = await fetch(`/api/unsubscribe/dataroom?token=${token}`, {+ method: "POST",+ });+ const data = await response.json();++ if (!response.ok) {+ throw new Error(data.message || "Failed to unsubscribe");+ }++ setStatus("success");+ setMessage(data.message);+ } catch (error) {+ setStatus("error");+ setMessage((error as Error).message);+ } finally {+ setLoading(false);+ }+ };++ return (+ <div className="flex min-h-screen flex-col items-center justify-center bg-gray-50 p-4">+ <div className="w-full max-w-md rounded-lg bg-white p-8 shadow-md">+ <h1 className="mb-6 text-center text-2xl font-bold">+ Unsubscribe from Notifications+ </h1>++ {status === "error" ? (+ <div className="mb-4 text-center text-red-500">{message}</div>+ ) : status === "success" ? (+ <div className="mb-4 text-center text-green-500">{message}</div>+ ) : (+ <p className="mb-6 text-center text-gray-600">+ Click the button below to unsubscribe from notifications for this+ dataroom.+ </p>+ )}++ {status === "idle" && (+ <Button+ onClick={handleUnsubscribe}+ variant="destructive"+ className="w-full"+ loading={loading}+ >+ {loading ? "Unsubscribing..." : "Unsubscribe"}+ </Button>+ )}++ {status === "success" && (+ <p className="mt-4 text-center text-sm text-gray-500">+ You can close this window now.+ </p>+ )}+ </div>+ </div>+ );+}diff --git a/prisma/migrations/20241123000000_add_viewer_notification_preferences/migration.sql b/prisma/migrations/20241123000000_add_viewer_notification_preferences/migration.sqlnew file mode 100644index 00000000..e43dcc35--- /dev/null+++ b/prisma/migrations/20241123000000_add_viewer_notification_preferences/migration.sql@@ -0,0 +1,3 @@+-- AlterTable+ALTER TABLE "Viewer" ADD COLUMN "notificationPreferences" JSONB;+diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex c36f8cf5..6ae2fcc4 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -356,10 +356,11 @@ enum ViewType {}model Viewer {- id String @id @default(cuid())- email String- verified Boolean @default(false) // Whether the viewer email has been verified- invitedAt DateTime? // This is the time the viewer was invited+ id String @id @default(cuid())+ email String+ verified Boolean @default(false) // Whether the viewer email has been verified+ invitedAt DateTime? // This is the time the viewer was invited+ notificationPreferences Json? // Format: { dataroom: {"dr_123": { "enabled": false }, "dr_456": { "enabled": true } } }dataroomId String?dataroom Dataroom? @relation(fields: [dataroomId], references: [id], onDelete: SetNull)