Skip to content

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

feat(ee): update conversation notifications for team members

Marc Seitz1caf722be83c
diff --git a/ee/features/conversations/api/conversations-route.ts b/ee/features/conversations/api/conversations-route.ts
index 4cf6a9e8..8b588ff8 100644
--- a/ee/features/conversations/api/conversations-route.ts
+++ b/ee/features/conversations/api/conversations-route.ts
@@ -1,5 +1,8 @@
import { NextApiRequest, NextApiResponse } from "next";
+import { runs } from "@trigger.dev/sdk/v3";
+import { waitUntil } from "@vercel/functions";
+
import prisma from "@/lib/prisma";
import {
@@ -8,6 +11,7 @@ import {
} from "../lib/api/conversations";
import { messageService } from "../lib/api/messages";
import { notificationService } from "../lib/api/notifications";
+import { sendConversationTeamMemberNotificationTask } from "../lib/trigger/conversation-message-notification";
// Route mapping object to handle different paths
const routeHandlers = {
@@ -117,6 +121,38 @@ const routeHandlers = {
data,
});
+ // Get all delayed and queued runs for this dataroom
+ const allRuns = await runs.list({
+ taskIdentifier: ["send-conversation-team-member-notification"],
+ tag: [`conversation_${conversation.id}`],
+ status: ["DELAYED", "QUEUED"],
+ period: "5m",
+ });
+
+ // Cancel any existing unsent notification runs for this dataroom
+ await Promise.all(allRuns.data.map((run) => runs.cancel(run.id)));
+
+ waitUntil(
+ sendConversationTeamMemberNotificationTask.trigger(
+ {
+ dataroomId,
+ messageId: conversation.messages[0].id,
+ conversationId: conversation.id,
+ senderUserId: viewerId,
+ teamId: team.id,
+ },
+ {
+ idempotencyKey: `conversation-notification-${team.id}-${dataroomId}-${conversation.id}-${conversation.messages[0].id}`,
+ tags: [
+ `team_${team.id}`,
+ `dataroom_${dataroomId}`,
+ `conversation_${conversation.id}`,
+ ],
+ delay: new Date(Date.now() + 5 * 60 * 1000), // 5 minute delay
+ },
+ ),
+ );
+
return res.status(201).json(conversation);
},
@@ -125,7 +161,7 @@ const routeHandlers = {
const { content, viewId, viewerId, conversationId } = req.body as {
content: string;
viewId: string;
- viewerId?: string;
+ viewerId: string;
conversationId: string;
};
@@ -141,6 +177,38 @@ const routeHandlers = {
viewerId,
});
+ // Get all delayed and queued runs for this dataroom
+ const allRuns = await runs.list({
+ taskIdentifier: ["send-conversation-team-member-notification"],
+ tag: [`conversation_${message.conversationId}`],
+ status: ["DELAYED", "QUEUED"],
+ period: "5m",
+ });
+
+ // Cancel any existing unsent notification runs for this dataroom
+ await Promise.all(allRuns.data.map((run) => runs.cancel(run.id)));
+
+ waitUntil(
+ sendConversationTeamMemberNotificationTask.trigger(
+ {
+ dataroomId: message.conversation.dataroomId,
+ messageId: message.id,
+ conversationId: message.conversationId,
+ senderUserId: viewerId,
+ teamId: message.conversation.teamId,
+ },
+ {
+ idempotencyKey: `conversation-notification-${message.conversation.teamId}-${message.conversation.dataroomId}-${message.conversationId}-${message.id}`,
+ tags: [
+ `team_${message.conversation.teamId}`,
+ `dataroom_${message.conversation.dataroomId}`,
+ `conversation_${message.conversationId}`,
+ ],
+ delay: new Date(Date.now() + 5 * 60 * 1000), // 5 minute delay
+ },
+ ),
+ );
+
return res.status(201).json(message);
},
diff --git a/ee/features/conversations/api/send-conversation-team-member-notification.ts b/ee/features/conversations/api/send-conversation-team-member-notification.ts
index e426f91e..7c00e576 100644
--- a/ee/features/conversations/api/send-conversation-team-member-notification.ts
+++ b/ee/features/conversations/api/send-conversation-team-member-notification.ts
@@ -1,6 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { sendConversationNotification } from "@/ee/features/conversations/emails/lib/send-conversation-notification";
+import { sendConversationTeamNotification } from "@/ee/features/conversations/emails/lib/send-conversation-team-notification";
import prisma from "@/lib/prisma";
import { log } from "@/lib/utils";
@@ -25,86 +25,67 @@ export default async function handle(
return;
}
- const {
- conversationId,
- dataroomId,
- userId,
- senderUserId,
- teamId,
- } = req.body as {
+ const { conversationId, dataroomId, senderUserId, teamId } = req.body as {
conversationId: string;
dataroomId: string;
- userId: string;
senderUserId: string;
teamId: string;
};
- let user: { email: string } | null = null;
-
try {
- // Find the team member
- user = await prisma.user.findUnique({
+ // Get all team members (ADMIN/MANAGER) for this team
+ const teamMembers = await prisma.userTeam.findMany({
where: {
- id: userId,
- },
- select: {
- email: true,
- },
- });
-
- if (!user) {
- res.status(404).json({ message: "Team member not found." });
- return;
- }
-
- // Verify the user is actually a team member with appropriate role
- const userTeam = await prisma.userTeam.findUnique({
- where: {
- userId_teamId: {
- userId,
- teamId,
+ teamId,
+ role: {
+ in: ["ADMIN", "MANAGER"],
},
+ // Only active team members (not blocked)
+ blockedAt: null,
},
select: {
- role: true,
- blockedAt: true,
+ userId: true,
notificationPreferences: true,
+ user: {
+ select: {
+ id: true,
+ email: true,
+ },
+ },
},
});
- if (!userTeam || userTeam.blockedAt || !["ADMIN", "MANAGER"].includes(userTeam.role)) {
- res.status(403).json({ message: "User is not an active team member with notification permissions." });
+ if (!teamMembers || teamMembers.length === 0) {
+ res.status(200).json({
+ message: "No team members found for notifications",
+ notified: 0,
+ });
return;
}
- // Check if team member has disabled conversation notifications
- // (This could be extended in the future to support more granular preferences)
- if (userTeam.notificationPreferences) {
- try {
- const preferences = userTeam.notificationPreferences as any;
- if (preferences.conversations === false) {
- res.status(200).json({
- message: "Team member has disabled conversation notifications",
- userId,
- });
- return;
+ // Filter out team members who have disabled conversation notifications
+ const eligibleTeamMembers = teamMembers.filter((teamMember) => {
+ if (teamMember.notificationPreferences) {
+ try {
+ const preferences = teamMember.notificationPreferences as any;
+ if (preferences.conversations === false) {
+ return false;
+ }
+ } catch (error) {
+ // If preferences parsing fails, include the team member
}
- } catch (error) {
- // If preferences parsing fails, continue with sending notification
}
- }
- } catch (error) {
- log({
- message: `Failed to find team member for userId: ${userId}. \n\n Error: ${error}`,
- type: "error",
- mention: true,
+ return teamMember.user.email; // Only include if they have an email
});
- res.status(500).json({ message: (error as Error).message });
- return;
- }
- // POST /api/jobs/send-conversation-team-member-notification
- try {
+ if (eligibleTeamMembers.length === 0) {
+ res.status(200).json({
+ message: "No eligible team members for notifications",
+ notified: 0,
+ });
+ return;
+ }
+
// Fetch the conversation and dataroom information
const conversation = await prisma.conversation.findUnique({
where: {
@@ -127,43 +108,50 @@ export default async function handle(
return;
}
- const sender = await prisma.user.findUnique({
+ // First try to find as a user
+ const userSender = await prisma.viewer.findUnique({
where: { id: senderUserId },
select: { email: true },
});
- if (!sender) {
- res.status(404).json({ message: "Sender not found." });
- return;
+ let senderEmail = "";
+ if (userSender) {
+ senderEmail = userSender.email;
+ } else {
+ senderEmail = "Unknown sender";
}
// Generate the URL for team members to access the conversation
const conversationUrl = `${process.env.NEXT_PUBLIC_BASE_URL}/datarooms/${dataroomId}/conversations/${conversationId}`;
// For team members, provide a generic unsubscribe URL to team settings
- // TODO: Implement team member specific unsubscribe functionality
- const unsubscribeUrl = `${process.env.NEXT_PUBLIC_BASE_URL}/settings/notifications`;
-
- await sendConversationNotification({
- conversationTitle: conversation.title || "",
- dataroomName: conversation.dataroom?.name || "",
- senderEmail: sender.email!,
- to: user.email!,
+
+ // Get all team member emails
+ const teamMemberEmails = eligibleTeamMembers
+ .map((tm) => tm.user.email)
+ .filter((email): email is string => !!email);
+
+ // Send email to all team members at once
+ await sendConversationTeamNotification({
+ conversationTitle: conversation.title || "Untitled Conversation",
+ dataroomName: conversation.dataroom?.name || "Untitled Dataroom",
+ senderEmail,
+ teamMemberEmails,
url: conversationUrl,
- unsubscribeUrl,
});
res.status(200).json({
- message: "Successfully sent conversation notification to team member",
- userId,
+ message: "Successfully sent conversation notification to team members",
+ notified: teamMemberEmails.length,
+ teamMemberEmails,
});
return;
} catch (error) {
log({
- message: `Failed to send conversation notification for dataroom ${dataroomId} to team member: ${userId}. \n\n Error: ${error} \n\n*Metadata*: \`{dataroomId: ${dataroomId}, userId: ${userId}}\``,
+ message: `Failed to send conversation notification for dataroom ${dataroomId} to team members. \n\n Error: ${error} \n\n*Metadata*: \`{dataroomId: ${dataroomId}, teamId: ${teamId}}\``,
type: "error",
mention: true,
});
return res.status(500).json({ message: (error as Error).message });
}
-}
\ No newline at end of file
+}
diff --git a/ee/features/conversations/components/conversation-view-sidebar.tsx b/ee/features/conversations/components/conversation-view-sidebar.tsx
index 29a45964..96b6a80f 100644
--- a/ee/features/conversations/components/conversation-view-sidebar.tsx
+++ b/ee/features/conversations/components/conversation-view-sidebar.tsx
@@ -8,17 +8,12 @@ import { ArrowLeftIcon, BellIcon, BellOffIcon, Plus } from "lucide-react";
import { toast } from "sonner";
import useSWR, { mutate } from "swr";
-import { cn, fetcher } from "@/lib/utils";
+import { fetcher } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
-import {
- Sheet,
- SheetContent,
- SheetHeader,
- SheetTitle,
-} from "@/components/ui/sheet";
+import { Sheet, SheetContent } from "@/components/ui/sheet";
// Type definitions
interface Message {
diff --git a/ee/features/conversations/emails/components/conversation-notification.tsx b/ee/features/conversations/emails/components/conversation-notification.tsx
index 59b3fce3..25bff0fc 100644
--- a/ee/features/conversations/emails/components/conversation-notification.tsx
+++ b/ee/features/conversations/emails/components/conversation-notification.tsx
@@ -62,14 +62,7 @@ export default function ConversationNotification({
<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.com
- </a>
+ © {new Date().getFullYear()} Papermark, Inc.
</Text>
<Text className="text-xs">
You received this email from{" "}
diff --git a/ee/features/conversations/emails/components/conversation-team-notification.tsx b/ee/features/conversations/emails/components/conversation-team-notification.tsx
new file mode 100644
index 00000000..28a9aa8a
--- /dev/null
+++ b/ee/features/conversations/emails/components/conversation-team-notification.tsx
@@ -0,0 +1,80 @@
+import React from "react";
+
+import {
+ Body,
+ Button,
+ Container,
+ Head,
+ Hr,
+ Html,
+ Preview,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+
+export default function ConversationTeamNotification({
+ conversationTitle,
+ dataroomName,
+ senderEmail,
+ url,
+}: {
+ conversationTitle: string;
+ dataroomName: string;
+ senderEmail: string;
+ url: string;
+}) {
+ return (
+ <Html>
+ <Head />
+ <Preview>New message from visitor in your dataroom</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="font-seminbold mx-0 mb-8 mt-4 p-0 text-center text-xl">
+ {`New message in ${dataroomName}`}
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ A visitor (<span className="font-semibold">{senderEmail}</span>)
+ has sent a new message in the conversation{" "}
+ <span className="font-semibold">{conversationTitle}</span> in your
+ dataroom <span className="font-semibold">{dataroomName}</span> on
+ Papermark.
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ As a manager, you&apos;re receiving this notification to stay
+ informed about visitor interactions in your dataroom.
+ </Text>
+ <Section className="mb-[32px] mt-[32px] text-center">
+ <Button
+ className="rounded bg-black text-center text-xs font-semibold text-white no-underline"
+ href={`${url}`}
+ style={{ padding: "12px 20px" }}
+ >
+ View the conversation
+ </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()} Papermark, Inc.
+ </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/ee/features/conversations/emails/lib/send-conversation-team-notification.ts b/ee/features/conversations/emails/lib/send-conversation-team-notification.ts
new file mode 100644
index 00000000..bf90e548
--- /dev/null
+++ b/ee/features/conversations/emails/lib/send-conversation-team-notification.ts
@@ -0,0 +1,40 @@
+import ConversationTeamNotification from "@/ee/features/conversations/emails/components/conversation-team-notification";
+
+import { sendEmail } from "@/lib/resend";
+
+export const sendConversationTeamNotification = async ({
+ dataroomName,
+ conversationTitle,
+ senderEmail,
+ teamMemberEmails,
+ url,
+}: {
+ dataroomName: string;
+ conversationTitle: string;
+ senderEmail: string;
+ teamMemberEmails: string[];
+ url: string;
+}) => {
+ try {
+ if (!teamMemberEmails || teamMemberEmails.length === 0) {
+ console.log("No team member emails provided");
+ return;
+ }
+
+ await sendEmail({
+ to: teamMemberEmails[0], // Send to first team member
+ cc: teamMemberEmails.slice(1).join(","), // Send to all other team members
+ subject: `New visitor message in ${dataroomName}`,
+ react: ConversationTeamNotification({
+ senderEmail,
+ conversationTitle,
+ dataroomName,
+ url,
+ }),
+ test: process.env.NODE_ENV === "development",
+ system: true,
+ });
+ } catch (e) {
+ console.error("Failed to send team member notification:", e);
+ }
+};
diff --git a/ee/features/conversations/lib/trigger/conversation-message-notification.ts b/ee/features/conversations/lib/trigger/conversation-message-notification.ts
index 68bcaa74..1e5acff8 100644
--- a/ee/features/conversations/lib/trigger/conversation-message-notification.ts
+++ b/ee/features/conversations/lib/trigger/conversation-message-notification.ts
@@ -57,35 +57,9 @@ export const sendConversationMessageNotificationTask = task({
},
});
- // Get team members (ADMIN/MANAGER) for this team
- const teamMembers = await prisma.userTeam.findMany({
- where: {
- teamId: payload.teamId,
- role: {
- in: ["ADMIN", "MANAGER"],
- },
- userId: {
- not: payload.senderUserId, // Don't notify the sender
- },
- // Only active team members (not blocked)
- blockedAt: null,
- },
- select: {
- userId: true,
- user: {
- select: {
- id: true,
- email: true,
- notificationPreferences: true,
- },
- },
- },
- });
-
- if ((!participants || participants.length === 0) && (!teamMembers || teamMembers.length === 0)) {
- logger.info("No participants or team members found for this conversation", {
+ if (!participants || participants.length === 0) {
+ logger.info("No participants found for this conversation", {
conversationId: payload.conversationId,
- teamId: payload.teamId,
});
return;
}
@@ -93,43 +67,66 @@ export const sendConversationMessageNotificationTask = task({
// Construct simplified viewer objects with link information
const viewersWithLinks = participants
.map((participant) => {
- const viewer = participant.viewer;
- if (!viewer || !viewer.views || viewer.views.length === 0) {
+ if (!participant.viewer) {
return null;
}
- const view = viewer.views[0];
- const link = view.link;
+ const viewer = participant.viewer;
- if (!link || link.isArchived || (link.expiresAt && link.expiresAt < new Date())) {
- return null; // Skip archived or expired links
+ // Skip if notifications are disabled for this dataroom
+ const parsedPreferences =
+ ZViewerNotificationPreferencesSchema.safeParse(
+ viewer.notificationPreferences,
+ );
+ if (
+ parsedPreferences.success &&
+ parsedPreferences.data.dataroom[payload.dataroomId]?.enabled === false
+ ) {
+ logger.info("Viewer notifications are disabled for this dataroom", {
+ viewerId: viewer.id,
+ conversationId: payload.conversationId,
+ dataroomId: payload.dataroomId,
+ });
+ return null;
}
- const baseUrl = link.domainSlug
- ? `https://${link.domainSlug}`
- : process.env.NEXT_PUBLIC_BASE_URL;
+ // Get the link from the conversationView
+ const link = viewer.views[0]?.link;
- const linkUrl = `${baseUrl}/view/${link.slug}`;
+ // Skip if link is expired or archived
+ if (
+ !link ||
+ link.isArchived ||
+ (link.expiresAt && new Date(link.expiresAt) < new Date())
+ ) {
+ logger.info("Link is expired or archived", {
+ conversationId: payload.conversationId,
+ link,
+ });
+ 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 !== null) as Array<{
- id: string;
- linkUrl: string;
- }>;
+ .filter(
+ (participant): participant is { id: string; linkUrl: string } =>
+ participant !== null,
+ );
logger.info("Processed viewer links", {
viewerCount: viewersWithLinks.length,
});
- logger.info("Found team members for notification", {
- teamMemberCount: teamMembers.length,
- teamId: payload.teamId,
- });
-
// Send notification to each viewer
for (const viewer of viewersWithLinks) {
try {
@@ -174,53 +171,106 @@ export const sendConversationMessageNotificationTask = task({
}
}
- // Send notification to each team member
- for (const teamMember of teamMembers) {
- try {
- const response = await fetch(
- `${process.env.NEXT_PUBLIC_BASE_URL}/api/jobs/send-conversation-team-member-notification`,
- {
- method: "POST",
- body: JSON.stringify({
- conversationId: payload.conversationId,
- dataroomId: payload.dataroomId,
- userId: teamMember.userId,
- senderUserId: payload.senderUserId,
- teamId: payload.teamId,
- }),
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${process.env.INTERNAL_API_KEY}`,
- },
+ logger.info("Completed sending notifications", {
+ dataroomId: payload.dataroomId,
+ conversationId: payload.conversationId,
+ viewerCount: viewersWithLinks.length,
+ });
+ return;
+ },
+});
+
+// New task specifically for notifying team members when viewers write messages
+export const sendConversationTeamMemberNotificationTask = task({
+ id: "send-conversation-team-member-notification",
+ retry: { maxAttempts: 3 },
+ run: async (payload: NotificationPayload) => {
+ logger.info("Starting team member notifications", {
+ conversationId: payload.conversationId,
+ teamId: payload.teamId,
+ });
+
+ // Get team members (ADMIN/MANAGER) for this team
+ const teamMembers = await prisma.userTeam.findMany({
+ where: {
+ teamId: payload.teamId,
+ role: {
+ in: ["ADMIN", "MANAGER"],
+ },
+ // Only active team members (not blocked)
+ blockedAt: null,
+ },
+ select: {
+ userId: true,
+ user: {
+ select: {
+ id: true,
+ email: true,
},
- );
+ },
+ },
+ });
- if (!response.ok) {
- logger.error("Failed to send team member notification", {
- userId: teamMember.userId,
+ if (!teamMembers || teamMembers.length === 0) {
+ logger.info("No team members found for this conversation", {
+ conversationId: payload.conversationId,
+ teamId: payload.teamId,
+ });
+ return;
+ }
+
+ logger.info("Found team members for notification", {
+ teamMemberCount: teamMembers.length,
+ teamId: payload.teamId,
+ conversationId: payload.conversationId,
+ });
+
+ // Send notification to all team members at once
+ try {
+ const response = await fetch(
+ `${process.env.NEXT_PUBLIC_BASE_URL}/api/jobs/send-conversation-team-member-notification`,
+ {
+ method: "POST",
+ body: JSON.stringify({
+ conversationId: payload.conversationId,
dataroomId: payload.dataroomId,
- error: await response.text(),
- });
- continue;
- }
+ senderUserId: payload.senderUserId,
+ teamId: payload.teamId,
+ }),
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${process.env.INTERNAL_API_KEY}`,
+ },
+ },
+ );
- const { message } = (await response.json()) as { message: string };
- logger.info("Team member notification sent successfully", {
- userId: teamMember.userId,
- message,
+ if (!response.ok) {
+ logger.error("Failed to send team member notifications", {
+ dataroomId: payload.dataroomId,
+ teamId: payload.teamId,
+ error: await response.text(),
});
- } catch (error) {
- logger.error("Error sending team member notification", {
- userId: teamMember.userId,
- error,
+ } else {
+ const result = (await response.json()) as {
+ message: string;
+ notified: number;
+ };
+ logger.info("Team member notifications sent successfully", {
+ teamId: payload.teamId,
+ notified: result.notified,
+ message: result.message,
});
}
+ } catch (error) {
+ logger.error("Error sending team member notifications", {
+ teamId: payload.teamId,
+ error,
+ });
}
- logger.info("Completed sending notifications", {
- dataroomId: payload.dataroomId,
+ logger.info("Completed team member notifications", {
conversationId: payload.conversationId,
- viewerCount: viewersWithLinks.length,
+ teamId: payload.teamId,
teamMemberCount: teamMembers.length,
});
return;
diff --git a/lib/trigger/conversation-message-notification.ts b/lib/trigger/conversation-message-notification.ts
index f7070196..d3789eff 100644
--- a/lib/trigger/conversation-message-notification.ts
+++ b/lib/trigger/conversation-message-notification.ts
@@ -1,3 +1,9 @@
-import { sendConversationMessageNotificationTask } from "@/ee/features/conversations/lib/trigger/conversation-message-notification";
+import {
+ sendConversationMessageNotificationTask,
+ sendConversationTeamMemberNotificationTask,
+} from "@/ee/features/conversations/lib/trigger/conversation-message-notification";
-export { sendConversationMessageNotificationTask };
+export {
+ sendConversationMessageNotificationTask,
+ sendConversationTeamMemberNotificationTask,
+};