Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
Add team member notifications for conversations in datarooms
Cursor Agent0e89000f9e85
diff --git a/ee/features/conversations/api/send-conversation-team-member-notification.ts b/ee/features/conversations/api/send-conversation-team-member-notification.tsnew file mode 100644index 00000000..e426f91e--- /dev/null+++ b/ee/features/conversations/api/send-conversation-team-member-notification.ts@@ -0,0 +1,169 @@+import { NextApiRequest, NextApiResponse } from "next";++import { sendConversationNotification } from "@/ee/features/conversations/emails/lib/send-conversation-notification";++import prisma from "@/lib/prisma";+import { log } from "@/lib/utils";++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 {+ conversationId,+ dataroomId,+ userId,+ 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({+ 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,+ },+ },+ select: {+ role: true,+ blockedAt: true,+ notificationPreferences: 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." });+ 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;+ }+ } 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,+ });+ res.status(500).json({ message: (error as Error).message });+ return;+ }++ // POST /api/jobs/send-conversation-team-member-notification+ try {+ // Fetch the conversation and dataroom information+ const conversation = await prisma.conversation.findUnique({+ where: {+ id: conversationId,+ dataroomId: dataroomId,+ teamId: teamId,+ },+ select: {+ title: true,+ dataroom: {+ select: {+ name: true,+ },+ },+ },+ });++ if (!conversation) {+ res.status(404).json({ message: "Conversation not found." });+ return;+ }++ const sender = await prisma.user.findUnique({+ where: { id: senderUserId },+ select: { email: true },+ });++ if (!sender) {+ res.status(404).json({ message: "Sender not found." });+ return;+ }++ // 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!,+ url: conversationUrl,+ unsubscribeUrl,+ });++ res.status(200).json({+ message: "Successfully sent conversation notification to team member",+ userId,+ });+ 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}}\``,+ type: "error",+ mention: true,+ });+ return res.status(500).json({ message: (error as Error).message });+ }+}\ No newline at end of filediff --git a/ee/features/conversations/lib/trigger/conversation-message-notification.ts b/ee/features/conversations/lib/trigger/conversation-message-notification.tsindex 1cc0b78b..68bcaa74 100644--- a/ee/features/conversations/lib/trigger/conversation-message-notification.ts+++ b/ee/features/conversations/lib/trigger/conversation-message-notification.ts@@ -57,9 +57,35 @@ export const sendConversationMessageNotificationTask = task({},});- if (!participants || participants.length === 0) {- logger.info("No participants found for this conversation", {+ // 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", {conversationId: payload.conversationId,+ teamId: payload.teamId,});return;}@@ -67,66 +93,43 @@ export const sendConversationMessageNotificationTask = task({// Construct simplified viewer objects with link informationconst viewersWithLinks = participants.map((participant) => {- if (!participant.viewer) {+ const viewer = participant.viewer;+ if (!viewer || !viewer.views || viewer.views.length === 0) {return null;}- const viewer = participant.viewer;+ const view = viewer.views[0];+ const link = view.link;- // 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;+ if (!link || link.isArchived || (link.expiresAt && link.expiresAt < new Date())) {+ return null; // Skip archived or expired links}- // Get the link from the conversationView- const link = viewer.views[0]?.link;-- // 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;- }+ const baseUrl = link.domainSlug+ ? `https://${link.domainSlug}`+ : process.env.NEXT_PUBLIC_BASE_URL;- 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}`;- }+ const linkUrl = `${baseUrl}/view/${link.slug}`;return {id: viewer.id,linkUrl,};})- .filter(- (participant): participant is { id: string; linkUrl: string } =>- participant !== null,- );+ .filter((viewer) => viewer !== null) as Array<{+ id: string;+ linkUrl: string;+ }>;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 viewerfor (const viewer of viewersWithLinks) {try {@@ -171,10 +174,54 @@ 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}`,+ },+ },+ );++ if (!response.ok) {+ logger.error("Failed to send team member notification", {+ userId: teamMember.userId,+ dataroomId: payload.dataroomId,+ error: await response.text(),+ });+ continue;+ }++ const { message } = (await response.json()) as { message: string };+ logger.info("Team member notification sent successfully", {+ userId: teamMember.userId,+ message,+ });+ } catch (error) {+ logger.error("Error sending team member notification", {+ userId: teamMember.userId,+ error,+ });+ }+ }+logger.info("Completed sending notifications", {dataroomId: payload.dataroomId,conversationId: payload.conversationId,viewerCount: viewersWithLinks.length,+ teamMemberCount: teamMembers.length,});return;},diff --git a/pages/api/jobs/send-conversation-team-member-notification.ts b/pages/api/jobs/send-conversation-team-member-notification.tsnew file mode 100644index 00000000..211ea424--- /dev/null+++ b/pages/api/jobs/send-conversation-team-member-notification.ts@@ -0,0 +1,2 @@+// API route: /api/jobs/send-conversation-team-member-notification+export { default } from "@/ee/features/conversations/api/send-conversation-team-member-notification";\ No newline at end of file