Skip to content

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

feat: slack integration improvements and simplification

Marc Seitzff9a5505c002
diff --git a/app/api/integrations/slack/oauth/authorize/route.ts b/app/api/integrations/slack/oauth/authorize/route.ts
new file mode 100644
index 00000000..afea28e7
--- /dev/null
+++ b/app/api/integrations/slack/oauth/authorize/route.ts
@@ -0,0 +1,53 @@
+import { NextResponse } from "next/server";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+import { z } from "zod";
+
+import { getSlackInstallationUrl } from "@/lib/integrations/slack/install";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { getSearchParams } from "@/lib/utils/get-search-params";
+
+const oAuthAuthorizeSchema = z.object({
+ teamId: z.string().cuid(),
+});
+
+export async function GET(req: Request) {
+ try {
+ const session = await getServerSession(authOptions);
+ if (!session) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const { teamId } = oAuthAuthorizeSchema.parse(getSearchParams(req.url));
+ console.log("teamId", teamId);
+ const userId = (session.user as CustomUser).id;
+
+ const userTeam = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId,
+ teamId,
+ },
+ },
+ });
+
+ if (!userTeam) {
+ return NextResponse.json({ error: "Access denied" }, { status: 403 });
+ }
+
+ const oauthUrl = await getSlackInstallationUrl(teamId);
+ console.log("oauthUrl", oauthUrl);
+
+ return NextResponse.json({
+ oauthUrl,
+ });
+ } catch (error) {
+ console.error("Slack OAuth authorization error:", error);
+ return NextResponse.json(
+ { error: "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
diff --git a/app/api/integrations/slack/oauth/callback/route.ts b/app/api/integrations/slack/oauth/callback/route.ts
new file mode 100644
index 00000000..22f4076f
--- /dev/null
+++ b/app/api/integrations/slack/oauth/callback/route.ts
@@ -0,0 +1,95 @@
+import { redirect } from "next/navigation";
+import { NextResponse } from "next/server";
+
+import { Team } from "@prisma/client";
+import { getSession } from "next-auth/react";
+import z from "zod";
+
+import { installIntegration } from "@/lib/integrations/install";
+import { getSlackEnv } from "@/lib/integrations/slack/env";
+import { SlackCredential } from "@/lib/integrations/slack/types";
+import { encryptSlackToken } from "@/lib/integrations/slack/utils";
+import prisma from "@/lib/prisma";
+import { redis } from "@/lib/redis";
+import { CustomUser } from "@/lib/types";
+import { getSearchParams } from "@/lib/utils/get-search-params";
+
+export const dynamic = "force-dynamic";
+
+const oAuthCallbackSchema = z.object({
+ code: z.string(),
+ state: z.string(),
+});
+
+export const GET = async (req: Request) => {
+ const env = getSlackEnv();
+
+ let workspace: Pick<Team, "id" | "plan"> | null = null;
+
+ try {
+ const session = await getSession();
+ if (!session) {
+ throw new Error("Unauthorized");
+ }
+
+ const userId = (session.user as CustomUser).id;
+
+ const { code, state } = oAuthCallbackSchema.parse(getSearchParams(req.url));
+
+ // Find workspace that initiated the Stripe app install
+ const teamId = await redis.get<string>(`slack:install:state:${state}`);
+
+ if (!teamId) {
+ throw new Error("Unknown state");
+ }
+
+ workspace = await prisma.team.findUniqueOrThrow({
+ where: {
+ id: teamId,
+ },
+ select: {
+ id: true,
+ plan: true,
+ },
+ });
+
+ const formData = new FormData();
+ formData.append("code", code);
+ formData.append("client_id", env.SLACK_CLIENT_ID);
+ formData.append("client_secret", env.SLACK_CLIENT_SECRET);
+ formData.append(
+ "redirect_uri",
+ `${process.env.NEXT_PUBLIC_BASE_URL}/api/integrations/slack/oauth/callback`,
+ );
+
+ const response = await fetch("https://slack.com/api/oauth.v2.access", {
+ method: "POST",
+ body: formData,
+ });
+
+ const data = await response.json();
+
+ console.log("data", data);
+
+ const credentials: SlackCredential = {
+ appId: data.app_id,
+ botUserId: data.bot_user_id,
+ scope: data.scope,
+ accessToken: encryptSlackToken(data.access_token),
+ tokenType: data.token_type,
+ authUser: data.authed_user,
+ team: data.team,
+ };
+
+ await installIntegration({
+ integrationId: env.SLACK_INTEGRATION_ID,
+ userId,
+ teamId,
+ credentials,
+ });
+ } catch (e: any) {
+ return NextResponse.json({ error: e.message }, { status: 500 });
+ }
+
+ redirect(`/settings/integrations/slack`);
+};
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.ts
index d8128863..e1691ef9 100644
--- a/app/api/views-dataroom/route.ts
+++ b/app/api/views-dataroom/route.ts
@@ -17,6 +17,10 @@ import { PreviewSession, verifyPreviewSession } from "@/lib/auth/preview-auth";
import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verification";
import { getFile } from "@/lib/files/get-file";
import { newId } from "@/lib/id-helper";
+import {
+ notifyDataroomAccess,
+ notifyDocumentView,
+} from "@/lib/integrations/slack/events";
import prisma from "@/lib/prisma";
import { ratelimit } from "@/lib/redis";
import { parseSheet } from "@/lib/sheet";
@@ -28,7 +32,6 @@ import { generateOTP } from "@/lib/utils/generate-otp";
import { LOCALHOST_IP } from "@/lib/utils/geo";
import { checkGlobalBlockList } from "@/lib/utils/global-block-list";
import { validateEmail } from "@/lib/utils/validate-email";
-import { notifyDataroomAccess, notifyDocumentView } from "@/lib/slack/events";
export async function POST(request: NextRequest) {
try {
@@ -604,28 +607,28 @@ export async function POST(request: NextRequest) {
...(link.enableAgreement &&
link.agreementId &&
hasConfirmedAgreement && {
- agreementResponse: {
- create: {
- agreementId: link.agreementId,
+ agreementResponse: {
+ create: {
+ agreementId: link.agreementId,
+ },
},
- },
- }),
+ }),
...(link.audienceType === LinkAudienceType.GROUP &&
link.groupId && {
- groupId: link.groupId,
- }),
+ groupId: link.groupId,
+ }),
...(customFields &&
link.customFields.length > 0 && {
- customFieldResponse: {
- create: {
- data: link.customFields.map((field) => ({
- identifier: field.identifier,
- label: field.label,
- response: customFields[field.identifier] || "",
- })),
+ customFieldResponse: {
+ create: {
+ data: link.customFields.map((field) => ({
+ identifier: field.identifier,
+ label: field.label,
+ response: customFields[field.identifier] || "",
+ })),
+ },
},
- },
- }),
+ }),
};
// ** DATAROOM_VIEW **
@@ -673,7 +676,7 @@ export async function POST(request: NextRequest) {
} catch (error) {
console.error("Error sending Slack notification:", error);
}
- })()
+ })(),
);
}
}
@@ -803,7 +806,7 @@ export async function POST(request: NextRequest) {
} catch (error) {
console.error("Error sending Slack notification:", error);
}
- })()
+ })(),
);
}
}
diff --git a/app/api/views/route.ts b/app/api/views/route.ts
index c9611956..b9dcf210 100644
--- a/app/api/views/route.ts
+++ b/app/api/views/route.ts
@@ -14,11 +14,11 @@ import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verificati
import { getFeatureFlags } from "@/lib/featureFlags";
import { getFile } from "@/lib/files/get-file";
import { newId } from "@/lib/id-helper";
+import { notifyDocumentView } from "@/lib/integrations/slack/events";
import prisma from "@/lib/prisma";
import { ratelimit } from "@/lib/redis";
import { parseSheet } from "@/lib/sheet";
import { recordLinkView } from "@/lib/tracking/record-link-view";
-import { notifyDocumentView } from "@/lib/slack/events";
import { CustomUser, WatermarkConfigSchema } from "@/lib/types";
import { checkPassword, decryptEncrpytedPassword, log } from "@/lib/utils";
import { isEmailMatched } from "@/lib/utils/email-domain";
@@ -647,7 +647,7 @@ export async function POST(request: NextRequest) {
viewerId: viewer?.id ?? undefined,
}).catch((error) => {
console.error("Error sending Slack notification:", error);
- })
+ }),
);
}
}
diff --git a/components/emails/installed-integration-notification.tsx b/components/emails/installed-integration-notification.tsx
new file mode 100644
index 00000000..0fa85626
--- /dev/null
+++ b/components/emails/installed-integration-notification.tsx
@@ -0,0 +1,84 @@
+import React from "react";
+
+import {
+ Body,
+ Button,
+ Container,
+ Head,
+ Hr,
+ Html,
+ Preview,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+
+import { Footer } from "./shared/footer";
+
+export default function SlackIntegrationNotification({
+ email = "[email protected]",
+ team = {
+ name: "Acme, Inc",
+ },
+ integration = {
+ name: "Slack",
+ slug: "slack",
+ },
+}: {
+ email: string;
+ team: {
+ name: string;
+ };
+ integration: {
+ name: string;
+ slug: string;
+ };
+}) {
+ return (
+ <Html>
+ <Head />
+ <Preview>An integration has been added to your team</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">
+ An integration has been added to your team
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ The <strong>{integration.name}</strong> integration has been added
+ to your team {team.name} on Papermark.
+ </Text>
+ <Text className="text-sm leading-6 text-black">
+ You can now receive notifications about document views, dataroom
+ access and downloads directly in your Slack channels.
+ </Text>
+ <Section className="my-8 text-center">
+ <Button
+ className="rounded bg-black text-center text-xs font-semibold text-white no-underline"
+ href={`${process.env.NEXT_PUBLIC_BASE_URL}/settings/integrations/${integration.slug}`}
+ style={{ padding: "12px 20px" }}
+ >
+ View installed integration
+ </Button>
+ </Section>
+
+ <Footer
+ footerText={
+ <>
+ This email was intended for{" "}
+ <span className="text-black">{email}</span>. If you were not
+ expecting this email, you can ignore this email. If you have
+ any feedback or questions about this email, simply reply to
+ it.
+ </>
+ }
+ />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
diff --git a/components/emails/slack-integration-notification.tsx b/components/emails/slack-integration-notification.tsx
deleted file mode 100644
index cf0a07c1..00000000
--- a/components/emails/slack-integration-notification.tsx
+++ /dev/null
@@ -1,85 +0,0 @@
-import React from "react";
-
-import {
- Body,
- Button,
- Container,
- Head,
- Hr,
- Html,
- Preview,
- Section,
- Tailwind,
- Text,
-} from "@react-email/components";
-
-export default function SlackIntegrationNotification({
- teamName,
- userEmail,
- settingsUrl,
-}: {
- teamName: string;
- userEmail: string;
- settingsUrl: string;
-}) {
- return (
- <Html>
- <Head />
- <Preview>Slack integration has been added to your workspace</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">
- An integration has been added to your workspace
- </Text>
- <Text className="text-sm leading-6 text-black">
- The Slack integration has been added to your workspace{" "}
- <span className="font-semibold">{teamName}</span> on{" "}
- <span className="font-semibold">Papermark</span>.
- </Text>
- <Text className="text-sm leading-6 text-black">
- You can now receive notifications about document views, dataroom
- access and downloads directly in your Slack channels.
- </Text>
- <Section className="my-8 text-center">
- <Button
- className="rounded bg-black text-center text-xs font-semibold text-white no-underline"
- href={settingsUrl}
- style={{ padding: "12px 20px" }}
- >
- View installed integration
- </Button>
- </Section>
- <Text className="text-sm leading-6 text-black">
- or copy and paste this URL into your browser:
- </Text>
- <Text className="max-w-sm flex-wrap break-words font-medium text-purple-600 no-underline">
- {settingsUrl.replace(/^https?:\/\//, "")}
- </Text>
- <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"
- rel="noopener noreferrer"
- >
- papermark.com
- </a>
- </Text>
- <Text className="text-xs">
- If you have any feedback or questions about this email, simply
- reply to it. I&apos;d love to hear from you!
- </Text>
- </Section>
- </Container>
- </Body>
- </Tailwind>
- </Html>
- );
-}
diff --git a/lib/emails/send-slack-integration-notification.ts b/lib/emails/send-slack-integration-notification.ts
deleted file mode 100644
index dcb380cc..00000000
--- a/lib/emails/send-slack-integration-notification.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import SlackIntegrationNotification from "@/components/emails/slack-integration-notification";
-
-import { sendEmail } from "@/lib/resend";
-
-export const sendSlackIntegrationNotification = async ({
- userEmail,
- teamName,
- settingsUrl,
-}: {
- userEmail: string;
- teamName: string;
- settingsUrl: string;
-}) => {
- try {
- await sendEmail({
- to: userEmail,
- subject: `Slack integration added to ${teamName}`,
- react: SlackIntegrationNotification({
- userEmail,
- teamName,
- settingsUrl,
- }),
- test: process.env.NODE_ENV === "development",
- system: true,
- });
- } catch (e) {
- console.error("Failed to send Slack integration notification:", e);
- }
-};
\ No newline at end of file
diff --git a/lib/integrations/install.ts b/lib/integrations/install.ts
new file mode 100644
index 00000000..f1d4b8c0
--- /dev/null
+++ b/lib/integrations/install.ts
@@ -0,0 +1,98 @@
+import { waitUntil } from "@vercel/functions";
+
+import prisma from "@/lib/prisma";
+import { sendEmail } from "@/lib/resend";
+
+import IntegrationInstalled from "@/components/emails/installed-integration-notification";
+
+interface InstallIntegration {
+ userId: string;
+ teamId: string;
+ integrationId: string;
+ credentials?: Record<string, any>;
+}
+
+// Install an integration for a user in a workspace
+export const installIntegration = async ({
+ userId,
+ teamId,
+ integrationId,
+ credentials,
+}: InstallIntegration) => {
+ const installation = await prisma.installedIntegration.upsert({
+ create: {
+ userId,
+ teamId,
+ integrationId,
+ credentials,
+ },
+ update: {
+ credentials,
+ },
+ where: {
+ teamId_integrationId: {
+ teamId,
+ integrationId,
+ },
+ },
+ });
+
+ waitUntil(
+ (async () => {
+ const team = await prisma.team.findUniqueOrThrow({
+ where: {
+ id: teamId,
+ },
+ select: {
+ name: true,
+ users: {
+ where: { userId },
+ select: {
+ user: {
+ select: { email: true },
+ },
+ },
+ },
+ installedIntegrations: {
+ where: { integrationId },
+ select: {
+ integration: {
+ select: {
+ name: true,
+ slug: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ const email = team.users.length > 0 ? team.users[0].user.email : null;
+ const integration =
+ team.installedIntegrations.length > 0
+ ? team.installedIntegrations[0].integration
+ : null;
+
+ if (email && integration) {
+ await sendEmail({
+ to: email,
+ system: true,
+ test: process.env.NODE_ENV === "development",
+ subject: `The "${integration.name}" integration has been added to your team`,
+ react: IntegrationInstalled({
+ email: email!,
+ team: {
+ name: team.name,
+ },
+ integration: {
+ name: integration.name,
+ slug: integration.slug,
+ },
+ }),
+ });
+ }
+ })(),
+ );
+
+ return installation;
+};
diff --git a/lib/integrations/slack/client.ts b/lib/integrations/slack/client.ts
new file mode 100644
index 00000000..7e9b9631
--- /dev/null
+++ b/lib/integrations/slack/client.ts
@@ -0,0 +1,224 @@
+import {
+ SlackChannel,
+ SlackMessage,
+ // SlackOAuthResponse,
+ // SlackWorkspaceInfo,
+} from "@/lib/integrations/slack/types";
+import { decryptSlackToken } from "@/lib/integrations/slack/utils";
+
+export class SlackClient {
+ private clientId: string;
+ private clientSecret: string;
+ private baseUrl = "https://slack.com/api";
+ // private oauthUrl = "https://slack.com/oauth/v2/authorize";
+
+ constructor() {
+ this.clientId = process.env.SLACK_CLIENT_ID as string;
+ this.clientSecret = process.env.SLACK_CLIENT_SECRET as string;
+
+ if (!this.clientId || !this.clientSecret) {
+ throw new Error("SLACK_CLIENT_ID and SLACK_CLIENT_SECRET must be set");
+ }
+ }
+
+ // private decryptToken(accessToken: string): string {
+ // return decryptSlackToken(accessToken);
+ // }
+
+ /**
+ * Get OAuth URL for Slack app installation
+ */
+ // getOAuthUrl(state: string, redirectUri: string): string {
+ // const params = new URLSearchParams({
+ // client_id: this.clientId,
+ // scope:
+ // // "channels:read,groups:read,mpim:read,im:read,chat:write,chat:write.public,team:read,users:read,users:read.email",
+ // "channels:read,chat:write,chat:write.public,groups:read,team:read,users:read",
+ // redirect_uri: redirectUri,
+ // state: state,
+ // });
+
+ // const oauthUrl = `${this.oauthUrl}?${params.toString()}`;
+
+ // return oauthUrl;
+ // }
+
+ /**
+ * Exchange authorization code for access token
+ */
+ // async exchangeCodeForToken(
+ // code: string,
+ // redirectUri: string,
+ // ): Promise<SlackOAuthResponse> {
+ // const ac = new AbortController();
+ // const t = setTimeout(() => ac.abort(), 10000);
+ // const response = await fetch(`${this.baseUrl}/oauth.v2.access`, {
+ // method: "POST",
+ // headers: {
+ // "Content-Type": "application/x-www-form-urlencoded",
+ // },
+ // body: new URLSearchParams({
+ // client_id: this.clientId,
+ // client_secret: this.clientSecret,
+ // code: code,
+ // redirect_uri: redirectUri,
+ // }),
+ // signal: ac.signal,
+ // })
+ // .catch((e) => {
+ // throw new Error(`Slack OAuth network error: ${e}`);
+ // })
+ // .finally(() => clearTimeout(t));
+
+ // if (!response.ok) {
+ // throw new Error(`Slack OAuth failed: ${response.statusText}`);
+ // }
+
+ // const data = await response.json();
+
+ // if (!data.ok) {
+ // throw new Error(`Slack OAuth error: ${data.error}`);
+ // }
+
+ // return data;
+ // }
+
+ /**
+ * Get workspace information
+ */
+ // async getWorkspaceInfo(accessToken: string): Promise<SlackWorkspaceInfo> {
+ // const decryptedToken = this.decryptToken(accessToken);
+ // const response = await fetch(`${this.baseUrl}/team.info`, {
+ // headers: {
+ // Authorization: `Bearer ${decryptedToken}`,
+ // "Content-Type": "application/x-www-form-urlencoded",
+ // },
+ // });
+
+ // if (!response.ok) {
+ // throw new Error(`Failed to get workspace info: ${response.statusText}`);
+ // }
+
+ // const data = await response.json();
+
+ // if (!data.ok) {
+ // throw new Error(`Slack API error: ${data.error}`);
+ // }
+
+ // return {
+ // id: data.team.id,
+ // name: data.team.name,
+ // url: `https://${data.team.domain}.slack.com`, // not in use
+ // domain: data.team.domain,
+ // };
+ // }
+
+ /**
+ * Get bot information
+ */
+ // async getBotInfo(accessToken: string): Promise<{ id: string; name: string }> {
+ // const decryptedToken = this.decryptToken(accessToken);
+ // const response = await fetch(`${this.baseUrl}/auth.test`, {
+ // headers: {
+ // Authorization: `Bearer ${decryptedToken}`,
+ // "Content-Type": "application/json",
+ // },
+ // });
+
+ // if (!response.ok) {
+ // throw new Error(`Failed to get bot info: ${response.statusText}`);
+ // }
+
+ // const data = await response.json();
+
+ // if (!data.ok) {
+ // throw new Error(`Slack API error: ${data.error}`);
+ // }
+
+ // return {
+ // id: data.bot_id,
+ // name: data.user,
+ // };
+ // }
+
+ async getChannels(accessToken: string): Promise<SlackChannel[]> {
+ const decryptedToken = decryptSlackToken(accessToken);
+
+ const channels: SlackChannel[] = [];
+ let cursor: string | undefined = undefined;
+
+ do {
+ const url = new URL(`${this.baseUrl}/conversations.list`);
+ url.searchParams.set("types", "public_channel,private_channel");
+ url.searchParams.set("exclude_archived", "true");
+ if (cursor) url.searchParams.set("cursor", cursor);
+
+ const requestUrl = url.toString();
+ const resp = await fetch(requestUrl, {
+ headers: {
+ Authorization: `Bearer ${decryptedToken}`,
+ "Content-Type": "application/json",
+ },
+ });
+ if (!resp.ok)
+ throw new Error(
+ `Failed to get channels: ${resp.status} ${resp.statusText}`,
+ );
+ const data = await resp.json();
+ if (!data.ok) throw new Error(`Slack API error: ${data.error}`);
+ channels.push(
+ ...data.channels.map((channel: any) => ({
+ id: channel.id,
+ name: channel.name,
+ is_private: channel.is_private,
+ is_archived: channel.is_archived,
+ is_member: channel.is_member,
+ })),
+ );
+ cursor = data.response_metadata?.next_cursor || undefined;
+ } while (cursor);
+
+ return channels;
+ }
+
+ /**
+ * Send message to Slack channel
+ */
+ async sendMessage(
+ accessToken: string,
+ message: SlackMessage,
+ ): Promise<{ ok: boolean; ts?: string; error?: string }> {
+ const decryptedToken = decryptSlackToken(accessToken);
+
+ const requestUrl = `${this.baseUrl}/chat.postMessage`;
+ const response = await fetch(requestUrl, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${decryptedToken}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(message),
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to send message: ${response.statusText}`);
+ }
+
+ const data = await response.json();
+
+ if (!data.ok) {
+ return {
+ ok: false,
+ error: data.error,
+ };
+ }
+
+ return {
+ ok: true,
+ ts: data.ts,
+ };
+ }
+}
+
+// Export singleton instance
+export const slackClient = new SlackClient();
diff --git a/lib/integrations/slack/env.ts b/lib/integrations/slack/env.ts
new file mode 100644
index 00000000..2e00b82b
--- /dev/null
+++ b/lib/integrations/slack/env.ts
@@ -0,0 +1,30 @@
+import z from "zod";
+
+export const envSchema = z.object({
+ SLACK_APP_INSTALL_URL: z.string(),
+ SLACK_CLIENT_ID: z.string(),
+ SLACK_CLIENT_SECRET: z.string(),
+ SLACK_INTEGRATION_ID: z.string(),
+});
+
+type SlackEnv = z.infer<typeof envSchema>;
+
+let env: SlackEnv | undefined;
+
+export const getSlackEnv = () => {
+ if (env) {
+ return env;
+ }
+
+ const parsed = envSchema.safeParse(process.env);
+
+ if (!parsed.success) {
+ throw new Error(
+ "Slack app environment variables are not configured properly.",
+ );
+ }
+
+ env = parsed.data;
+
+ return env;
+};
diff --git a/lib/integrations/slack/events.ts b/lib/integrations/slack/events.ts
new file mode 100644
index 00000000..82cd0f1a
--- /dev/null
+++ b/lib/integrations/slack/events.ts
@@ -0,0 +1,143 @@
+import prisma from "@/lib/prisma";
+
+import { SlackClient } from "./client";
+import { getSlackEnv } from "./env";
+import { createSlackMessage } from "./templates";
+import { SlackEventData, SlackIntegration } from "./types";
+
+export class SlackEventManager {
+ private client: SlackClient;
+
+ constructor() {
+ this.client = new SlackClient();
+ }
+
+ async processEvent(eventData: SlackEventData): Promise<void> {
+ try {
+ const env = getSlackEnv();
+
+ const integration = await prisma.installedIntegration.findUnique({
+ where: {
+ teamId_integrationId: {
+ teamId: eventData.teamId,
+ integrationId: env.SLACK_INTEGRATION_ID,
+ },
+ },
+ select: {
+ enabled: true,
+ },
+ });
+
+ if (!integration || !integration.enabled) {
+ return;
+ }
+
+ await this.sendSlackNotification(
+ eventData,
+ integration as unknown as SlackIntegration,
+ );
+ } catch (error) {
+ console.error("Error processing Slack event:", error);
+ }
+ }
+
+ /**
+ * Send slack notification for an event
+ */
+ private async sendSlackNotification(
+ eventData: SlackEventData,
+ integration: SlackIntegration,
+ ): Promise<void> {
+ try {
+ const channels = await this.getNotificationChannels(
+ eventData,
+ integration,
+ );
+
+ if (channels.length === 0) {
+ return;
+ }
+
+ for (const channel of channels) {
+ try {
+ const message = await createSlackMessage(eventData);
+ if (message) {
+ const slackMessage = {
+ ...message,
+ channel: channel.id,
+ };
+ await this.client.sendMessage(
+ integration.credentials.accessToken,
+ slackMessage,
+ );
+ }
+ } catch (channelError) {
+ console.error(
+ `Error sending to channel ${channel.name || channel.id}:`,
+ channelError,
+ );
+ }
+ }
+ } catch (error) {
+ console.error("Error sending instant notification:", error);
+ }
+ }
+
+ // private async getSlackIntegration(teamId: string) {
+ // const env = getSlackEnv();
+ // return await prisma.installedIntegration.findUnique({
+ // where: {
+ // teamId_integrationId: {
+ // teamId,
+ // integrationId: env.SLACK_INTEGRATION_ID,
+ // },
+ // enabled: true,
+ // },
+ // });
+ // }
+
+ // private isEventTypeEnabled(eventType: string, integration: any): boolean {
+ // const notificationTypes = integration.notificationTypes || {};
+ // return notificationTypes[eventType] || false;
+ // }
+
+ private async getNotificationChannels(
+ eventData: SlackEventData,
+ integration: SlackIntegration,
+ ): Promise<any[]> {
+ const enabledChannels = integration.configuration.enabledChannels || {};
+ return Object.values(enabledChannels)
+ .filter((channel: any) => channel.enabled)
+ .filter(
+ (channel: any) =>
+ channel.notificationTypes &&
+ channel.notificationTypes.includes(eventData.eventType),
+ );
+ }
+}
+
+export const slackEventManager = new SlackEventManager();
+
+export async function notifyDocumentView(
+ data: Omit<SlackEventData, "eventType">,
+) {
+ await slackEventManager.processEvent({ ...data, eventType: "document_view" });
+}
+
+export async function notifyDataroomAccess(
+ data: Omit<SlackEventData, "eventType">,
+) {
+ await slackEventManager.processEvent({
+ ...data,
+ eventType: "dataroom_access",
+ });
+}
+
+export async function notifyDocumentDownload(
+ data: Omit<SlackEventData, "eventType">,
+) {
+ await slackEventManager.processEvent({
+ ...data,
+ eventType: "document_download",
+ });
+}
diff --git a/lib/integrations/slack/install.ts b/lib/integrations/slack/install.ts
new file mode 100644
index 00000000..fdd97878
--- /dev/null
+++ b/lib/integrations/slack/install.ts
@@ -0,0 +1,26 @@
+import { nanoid } from "nanoid";
+
+import { redis } from "@/lib/redis";
+
+import { getSlackEnv } from "./env";
+
+// Get the installation URL for Slack
+export const getSlackInstallationUrl = async (
+ teamId: string,
+): Promise<string> => {
+ const env = getSlackEnv();
+
+ const state = nanoid(16);
+ await redis.set(`slack:install:state:${state}`, teamId, {
+ ex: 30 * 60,
+ });
+
+ const url = new URL(env.SLACK_APP_INSTALL_URL);
+ url.searchParams.set(
+ "redirect_uri",
+ `${process.env.NEXT_PUBLIC_BASE_URL}/api/integrations/slack/oauth/callback`,
+ );
+ url.searchParams.set("state", state);
+
+ return url.toString();
+};
diff --git a/lib/integrations/slack/templates.ts b/lib/integrations/slack/templates.ts
new file mode 100644
index 00000000..e01c8430
--- /dev/null
+++ b/lib/integrations/slack/templates.ts
@@ -0,0 +1,433 @@
+import prisma from "@/lib/prisma";
+
+import { SlackEventData, SlackMessage } from "./types";
+
+export async function createSlackMessage(
+ eventData: SlackEventData,
+): Promise<SlackMessage | null> {
+ try {
+ switch (eventData.eventType) {
+ case "document_view":
+ return await createDocumentViewMessage(eventData);
+ case "dataroom_access":
+ return await createDataroomAccessMessage(eventData);
+ case "document_download":
+ return await createDocumentDownloadMessage(eventData);
+
+ default:
+ return null;
+ }
+ } catch (error) {
+ console.error("Error creating Slack message:", error);
+ return null;
+ }
+}
+
+/**
+ * Document View Message Template
+ */
+async function createDocumentViewMessage(
+ eventData: SlackEventData,
+): Promise<SlackMessage> {
+ const document = eventData.documentId
+ ? await getDocumentInfo(eventData.documentId)
+ : null;
+ const dataroom = eventData.dataroomId
+ ? await getDataroomInfo(eventData.dataroomId)
+ : null;
+ const link = eventData.linkId ? await getLinkInfo(eventData.linkId) : null;
+
+ const viewerDisplay = eventData.viewerEmail || "Anonymous";
+ const viewerMention = eventData.viewerEmail
+ ? `<mailto:${eventData.viewerEmail}|${viewerDisplay}>`
+ : viewerDisplay;
+
+ let accessContext = "";
+ if (eventData.dataroomId && dataroom) {
+ accessContext = `in dataroom "${dataroom.name}"`;
+ } else if (link?.name) {
+ accessContext = `via shared link "${link.name}"`;
+ } else {
+ accessContext = `via shared link "Link ${link?.id.slice(0, 5)}"`;
+ }
+
+ return {
+ text: `Your document has been viewed: ${document?.name || "Unknown document"} by ${viewerDisplay} ${accessContext}`,
+ blocks: [
+ {
+ type: "header",
+ text: {
+ type: "plain_text",
+ text: "Your document has been viewed",
+ emoji: false,
+ },
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Document:*\n${document?.name || "Unknown"}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Viewer:*\n${viewerMention}`,
+ },
+ ],
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: dataroom?.name
+ ? `*Dataroom:*\n${dataroom.name}`
+ : link?.name
+ ? `*Shared Link:*\n${link.name}`
+ : `*Access:*\nDirect access`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Time:*\n${new Date().toLocaleString()}`,
+ },
+ ],
+ },
+ {
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: eventData.dataroomId
+ ? `Viewed document in dataroom "${dataroom?.name || "Unknown"}"`
+ : link?.name
+ ? `Viewed document via shared link "${link.name}"`
+ : `Viewed document via shared link "Link ${link?.id.slice(0, 5)}"`,
+ },
+ ],
+ },
+ {
+ type: "actions",
+ elements: [
+ {
+ type: "button",
+ text: {
+ type: "plain_text",
+ text: "View document",
+ emoji: true,
+ },
+ style: "primary",
+ url: eventData.documentId
+ ? `${process.env.NEXTAUTH_URL}/documents/${eventData.documentId}`
+ : `${process.env.NEXTAUTH_URL}/dashboard`,
+ },
+ ],
+ },
+ ],
+ };
+}
+
+/**
+ * Dataroom Access Message Template
+ */
+async function createDataroomAccessMessage(
+ eventData: SlackEventData,
+): Promise<SlackMessage> {
+ const dataroom = eventData.dataroomId
+ ? await getDataroomInfo(eventData.dataroomId)
+ : null;
+ const link = eventData.linkId ? await getLinkInfo(eventData.linkId) : null;
+
+ const viewerDisplay = eventData.viewerEmail || "Anonymous";
+ const viewerMention = eventData.viewerEmail
+ ? `<mailto:${eventData.viewerEmail}|${viewerDisplay}>`
+ : viewerDisplay;
+
+ const accessContext = link?.name
+ ? `via shared link "${link.name}"`
+ : `via shared link "Link ${link?.id.slice(0, 5)}"`;
+
+ return {
+ text: `Your dataroom has been viewed: ${dataroom?.name || "Unknown dataroom"} by ${viewerDisplay} ${accessContext}`,
+ blocks: [
+ {
+ type: "header",
+ text: {
+ type: "plain_text",
+ text: "Your dataroom has been viewed",
+ emoji: false,
+ },
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Dataroom:*\n${dataroom?.name || "Unknown"}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Viewer:*\n${viewerMention}`,
+ },
+ ],
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: link?.name
+ ? `*Shared Link:*\n${link.name}`
+ : `*Access:*\nDirect access`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Time:*\n${new Date().toLocaleString()}`,
+ },
+ ],
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Documents:*\n${dataroom?.documentCount || 0} documents`,
+ },
+ ],
+ },
+ {
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: link?.name
+ ? `Dataroom accessed via shared link "${link.name}"`
+ : `Dataroom accessed via shared link "Link ${link?.id.slice(0, 5)}"`,
+ },
+ ],
+ },
+ {
+ type: "actions",
+ elements: [
+ {
+ type: "button",
+ text: {
+ type: "plain_text",
+ text: "View dataroom",
+ emoji: true,
+ },
+ style: "primary",
+ url: eventData.dataroomId
+ ? `${process.env.NEXTAUTH_URL}/datarooms/${eventData.dataroomId}`
+ : `${process.env.NEXTAUTH_URL}/dashboard`,
+ },
+ ],
+ },
+ ],
+ };
+}
+
+/**
+ * Document Download Message Template
+ */
+async function createDocumentDownloadMessage(
+ eventData: SlackEventData,
+): Promise<SlackMessage> {
+ const document = eventData.documentId
+ ? await getDocumentInfo(eventData.documentId)
+ : null;
+ const dataroom = eventData.dataroomId
+ ? await getDataroomInfo(eventData.dataroomId)
+ : null;
+ const link = eventData.linkId ? await getLinkInfo(eventData.linkId) : null;
+
+ const viewerDisplay = eventData.viewerEmail || "Anonymous";
+ const viewerMention = eventData.viewerEmail
+ ? `<mailto:${eventData.viewerEmail}|${viewerDisplay}>`
+ : viewerDisplay;
+
+ const isBulkDownload = eventData.metadata?.isBulkDownload;
+ const isFolderDownload = eventData.metadata?.isFolderDownload;
+ const folderName = eventData.metadata?.folderName;
+ const documentCount = eventData.metadata?.documentCount;
+
+ let downloadType = "Document";
+ let downloadContext = "";
+
+ if (isBulkDownload) {
+ downloadType = "Dataroom";
+ downloadContext = `(${documentCount} documents)`;
+ } else if (isFolderDownload) {
+ downloadType = "Folder";
+ downloadContext = `"${folderName}" (${documentCount} documents)`;
+ } else if (dataroom) {
+ downloadContext = `from dataroom "${dataroom.name}"`;
+ } else if (link?.name) {
+ downloadContext = `via shared link "${link.name}"`;
+ } else {
+ downloadContext = `via shared link "Link ${link?.id.slice(0, 5)}"`;
+ }
+
+ return {
+ text: `${downloadType} has been downloaded: ${document?.name || downloadContext} by ${viewerDisplay}`,
+ blocks: [
+ {
+ type: "header",
+ text: {
+ type: "plain_text",
+ text: `${downloadType} has been downloaded`,
+ emoji: false,
+ },
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: document?.name
+ ? `*${downloadType}:*\n${document.name}`
+ : `*${downloadType}:*\n${downloadContext}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Downloaded by:*\n${viewerMention}`,
+ },
+ ],
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: dataroom?.name
+ ? `*From Dataroom:*\n${dataroom.name}`
+ : link?.name
+ ? `*Shared Link:*\n${link.name}`
+ : `*Context:*\n${downloadContext}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Time:*\n${new Date().toLocaleString()}`,
+ },
+ ],
+ },
+ {
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: isBulkDownload
+ ? `Bulk dataroom download`
+ : isFolderDownload
+ ? `Folder download`
+ : link?.name
+ ? `Document download via shared link "${link.name}"`
+ : `Document download via shared link "Link ${link?.id.slice(0, 5)}"`,
+ },
+ ],
+ },
+ {
+ type: "actions",
+ elements: [
+ {
+ type: "button",
+ text: {
+ type: "plain_text",
+ text: "View activity",
+ emoji: true,
+ },
+ style: "primary",
+ url: eventData.dataroomId
+ ? `${process.env.NEXTAUTH_URL}/datarooms/${eventData.dataroomId}`
+ : eventData.documentId
+ ? `${process.env.NEXTAUTH_URL}/documents/${eventData.documentId}`
+ : `${process.env.NEXTAUTH_URL}/dashboard`,
+ },
+ ],
+ },
+ ],
+ };
+}
+
+// Helper functions
+async function getDocumentInfo(documentId: string) {
+ try {
+ return await prisma.document.findUnique({
+ where: { id: documentId },
+ select: {
+ id: true,
+ name: true,
+ description: true,
+ type: true,
+ },
+ });
+ } catch (error) {
+ console.error("Error fetching document info:", error);
+ return null;
+ }
+}
+
+async function getDataroomInfo(dataroomId: string) {
+ try {
+ return await prisma.dataroom
+ .findUnique({
+ where: { id: dataroomId },
+ select: {
+ id: true,
+ name: true,
+ description: true,
+ _count: {
+ select: {
+ documents: true,
+ },
+ },
+ },
+ })
+ .then((dataroom) =>
+ dataroom
+ ? {
+ ...dataroom,
+ documentCount: dataroom._count.documents,
+ }
+ : null,
+ );
+ } catch (error) {
+ console.error("Error fetching dataroom info:", error);
+ return null;
+ }
+}
+
+async function getLinkInfo(linkId: string) {
+ try {
+ return await prisma.link.findUnique({
+ where: { id: linkId },
+ select: {
+ id: true,
+ name: true,
+ linkType: true,
+ },
+ });
+ } catch (error) {
+ console.error("Error fetching link info:", error);
+ return null;
+ }
+}
+
+async function getViewInfo(viewId: string) {
+ try {
+ return await prisma.view.findUnique({
+ where: { id: viewId },
+ select: {
+ id: true,
+ viewerEmail: true,
+ viewerId: true,
+ viewedAt: true,
+ viewType: true,
+ documentId: true,
+ dataroomId: true,
+ },
+ });
+ } catch (error) {
+ console.error("Error fetching view info:", error);
+ return null;
+ }
+}
diff --git a/lib/integrations/slack/types.ts b/lib/integrations/slack/types.ts
new file mode 100644
index 00000000..73ac9029
--- /dev/null
+++ b/lib/integrations/slack/types.ts
@@ -0,0 +1,66 @@
+import { InstalledIntegration } from "@prisma/client";
+
+export type SlackCredential = {
+ appId: string;
+ botUserId: string;
+ scope: string;
+ accessToken: string;
+ tokenType: string;
+ authUser: { id: string };
+ team: { id: string; name: string };
+};
+
+export type SlackConfiguration = {
+ enabledChannels: Record<string, SlackChannelConfig>;
+};
+
+// from lib/types/slack.ts
+export interface SlackChannel {
+ id: string;
+ name: string;
+ is_archived: boolean;
+ is_private: boolean;
+ is_member?: boolean;
+}
+
+export type SlackIntegration = Omit<
+ InstalledIntegration,
+ "credentials" | "configuration"
+> & {
+ credentials: SlackCredential;
+ configuration: SlackConfiguration;
+};
+
+export interface SlackMessage {
+ channel?: string;
+ text?: string;
+ blocks?: any[];
+ thread_ts?: string;
+ unfurl_links?: boolean;
+ unfurl_media?: boolean;
+}
+
+export interface SlackEventData {
+ teamId: string;
+ eventType: string;
+ documentId?: string;
+ dataroomId?: string;
+ viewId?: string;
+ linkId?: string;
+ viewerEmail?: string;
+ viewerId?: string;
+ userId?: string;
+ metadata?: Record<string, any>;
+}
+
+export type SlackNotificationType =
+ | "document_view"
+ | "dataroom_access"
+ | "document_download";
+
+export interface SlackChannelConfig {
+ id: string;
+ name: string;
+ enabled: boolean;
+ notificationTypes: SlackNotificationType[];
+}
diff --git a/lib/integrations/slack/uninstall.ts b/lib/integrations/slack/uninstall.ts
new file mode 100644
index 00000000..b3ce6a21
--- /dev/null
+++ b/lib/integrations/slack/uninstall.ts
@@ -0,0 +1,32 @@
+import { InstalledIntegration } from "@prisma/client";
+
+import { getSlackEnv } from "./env";
+import { SlackCredential } from "./types";
+
+export const uninstallSlackIntegration = async ({
+ installation,
+}: {
+ installation: InstalledIntegration;
+}) => {
+ const env = getSlackEnv();
+ const credentials = installation.credentials as SlackCredential;
+
+ const response = await fetch("https://slack.com/api/apps.uninstall", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ body: new URLSearchParams({
+ token: credentials.accessToken,
+ client_id: env.SLACK_CLIENT_ID,
+ client_secret: env.SLACK_CLIENT_SECRET,
+ }),
+ });
+
+ const data = await response.json();
+
+ if (!data.ok) {
+ console.error("[Slack App]", data);
+ throw new Error("Failed to remove the app from the Slack workspace.");
+ }
+};
diff --git a/lib/integrations/slack/utils.ts b/lib/integrations/slack/utils.ts
new file mode 100644
index 00000000..6eda18dd
--- /dev/null
+++ b/lib/integrations/slack/utils.ts
@@ -0,0 +1,58 @@
+import crypto from "crypto";
+
+export function encryptSlackToken(token: string): string {
+ if (!token) return "";
+ const textParts: string[] = token.split(":");
+ if (textParts.length === 2) {
+ return token;
+ }
+ const encryptionKey = process.env.NEXT_PRIVATE_SLACK_ENCRYPTION_KEY;
+ if (!encryptionKey) {
+ throw new Error(
+ "NEXT_PRIVATE_SLACK_ENCRYPTION_KEY environment variable is required for token encryption",
+ );
+ }
+
+ const encryptedKey: string = crypto
+ .createHash("sha256")
+ .update(String(encryptionKey))
+ .digest("base64")
+ .substring(0, 32);
+
+ const IV: Buffer = crypto.randomBytes(16);
+ const cipher = crypto.createCipheriv("aes-256-ctr", encryptedKey, IV);
+ let encryptedText: string = cipher.update(token, "utf8", "hex");
+ encryptedText += cipher.final("hex");
+
+ return IV.toString("hex") + ":" + encryptedText;
+}
+
+export function decryptSlackToken(encryptedToken: string): string {
+ if (!encryptedToken) return "";
+
+ const encryptionKey = process.env.NEXT_PRIVATE_SLACK_ENCRYPTION_KEY;
+ if (!encryptionKey) {
+ throw new Error(
+ "NEXT_PRIVATE_SLACK_ENCRYPTION_KEY environment variable is required for token decryption",
+ );
+ }
+
+ const encryptedKey: string = crypto
+ .createHash("sha256")
+ .update(String(encryptionKey))
+ .digest("base64")
+ .substring(0, 32);
+
+ const textParts: string[] = encryptedToken.split(":");
+ if (!textParts || textParts.length !== 2) {
+ return encryptedToken;
+ }
+
+ const IV: Buffer = Buffer.from(textParts[0], "hex");
+ const encryptedText: string = textParts[1];
+ const decipher = crypto.createDecipheriv("aes-256-ctr", encryptedKey, IV);
+ let decrypted: string = decipher.update(encryptedText, "hex", "utf8");
+ decrypted += decipher.final("utf8");
+
+ return decrypted;
+}
diff --git a/lib/slack/client.ts b/lib/slack/client.ts
deleted file mode 100644
index 66c46c38..00000000
--- a/lib/slack/client.ts
+++ /dev/null
@@ -1,201 +0,0 @@
-import { SlackOAuthResponse, SlackChannel, SlackMessage, SlackWorkspaceInfo } from '@/lib/types/slack';
-import { decryptSlackToken } from '@/lib/utils';
-
-export class SlackClient {
- private clientId: string;
- private clientSecret: string;
- private baseUrl = 'https://slack.com/api';
- private oauthUrl = 'https://slack.com/oauth/v2/authorize';
-
- constructor() {
- this.clientId = process.env.SLACK_CLIENT_ID!;
- this.clientSecret = process.env.SLACK_CLIENT_SECRET!;
-
- if (!this.clientId || !this.clientSecret) {
- throw new Error('SLACK_CLIENT_ID and SLACK_CLIENT_SECRET must be set');
- }
- }
-
- private decryptToken(accessToken: string): string {
- return decryptSlackToken(accessToken);
- }
-
- /**
- * Get OAuth URL for Slack app installation
- */
- getOAuthUrl(state: string, redirectUri: string): string {
- const params = new URLSearchParams({
- client_id: this.clientId,
- scope: 'channels:read,groups:read,mpim:read,im:read,chat:write,chat:write.public,team:read,users:read,users:read.email',
- redirect_uri: redirectUri,
- state: state,
- });
-
- const oauthUrl = `${this.oauthUrl}?${params.toString()}`;
-
- return oauthUrl;
- }
-
- /**
- * Exchange authorization code for access token
- */
- async exchangeCodeForToken(code: string, redirectUri: string): Promise<SlackOAuthResponse> {
- const ac = new AbortController();
- const t = setTimeout(() => ac.abort(), 10000);
- const response = await fetch(`${this.baseUrl}/oauth.v2.access`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded',
- },
- body: new URLSearchParams({
- client_id: this.clientId,
- client_secret: this.clientSecret,
- code: code,
- redirect_uri: redirectUri,
- }),
- signal: ac.signal,
- }).catch((e) => {
- throw new Error(`Slack OAuth network error: ${e}`);
- }).finally(() => clearTimeout(t));
-
-
- if (!response.ok) {
- throw new Error(`Slack OAuth failed: ${response.statusText}`);
- }
-
- const data = await response.json();
-
- if (!data.ok) {
- throw new Error(`Slack OAuth error: ${data.error}`);
- }
-
- return data;
- }
-
- /**
- * Get workspace information
- */
- async getWorkspaceInfo(accessToken: string): Promise<SlackWorkspaceInfo> {
- const decryptedToken = this.decryptToken(accessToken);
- const response = await fetch(`${this.baseUrl}/team.info`, {
- headers: {
- 'Authorization': `Bearer ${decryptedToken}`,
- 'Content-Type': 'application/x-www-form-urlencoded',
- },
- });
-
- if (!response.ok) {
- throw new Error(`Failed to get workspace info: ${response.statusText}`);
- }
-
- const data = await response.json();
-
- if (!data.ok) {
- throw new Error(`Slack API error: ${data.error}`);
- }
-
- return {
- id: data.team.id,
- name: data.team.name,
- url: `https://${data.team.domain}.slack.com`, // not in use
- domain: data.team.domain,
- };
- }
-
- /**
- * Get bot information
- */
- async getBotInfo(accessToken: string): Promise<{ id: string; name: string }> {
- const decryptedToken = this.decryptToken(accessToken);
- const response = await fetch(`${this.baseUrl}/auth.test`, {
- headers: {
- 'Authorization': `Bearer ${decryptedToken}`,
- 'Content-Type': 'application/json',
- },
- });
-
- if (!response.ok) {
- throw new Error(`Failed to get bot info: ${response.statusText}`);
- }
-
- const data = await response.json();
-
- if (!data.ok) {
- throw new Error(`Slack API error: ${data.error}`);
- }
-
- return {
- id: data.bot_id,
- name: data.user,
- };
- }
-
- async getChannels(accessToken: string): Promise<SlackChannel[]> {
- const decryptedToken = this.decryptToken(accessToken);
- const channels: SlackChannel[] = [];
- let cursor: string | undefined = undefined;
- do {
- const url = new URL(`${this.baseUrl}/conversations.list`);
- url.searchParams.set('types', 'public_channel,private_channel');
- url.searchParams.set('exclude_archived', 'true');
- if (cursor) url.searchParams.set('cursor', cursor);
- const resp = await fetch(url.toString(), {
- headers: {
- 'Authorization': `Bearer ${decryptedToken}`,
- 'Content-Type': 'application/json',
- },
- });
- if (!resp.ok) throw new Error(`Failed to get channels: ${resp.status} ${resp.statusText}`);
- const data = await resp.json();
- if (!data.ok) throw new Error(`Slack API error: ${data.error}`);
- channels.push(
- ...data.channels.map((channel: any) => ({
- id: channel.id,
- name: channel.name,
- is_private: channel.is_private,
- is_archived: channel.is_archived,
- is_member: channel.is_member,
- }))
- );
- cursor = data.response_metadata?.next_cursor || undefined;
- } while (cursor);
- return channels;
- }
-
-
- /**
- * Send message to Slack channel
- */
- async sendMessage(accessToken: string, message: SlackMessage): Promise<{ ok: boolean; ts?: string; error?: string }> {
- const decryptedToken = this.decryptToken(accessToken);
- const response = await fetch(`${this.baseUrl}/chat.postMessage`, {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${decryptedToken}`,
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(message),
- });
-
- if (!response.ok) {
- throw new Error(`Failed to send message: ${response.statusText}`);
- }
-
- const data = await response.json();
-
- if (!data.ok) {
- return {
- ok: false,
- error: data.error,
- };
- }
-
- return {
- ok: true,
- ts: data.ts,
- };
- }
-}
-
-// Export singleton instance
-export const slackClient = new SlackClient();
\ No newline at end of file
diff --git a/lib/slack/events.ts b/lib/slack/events.ts
deleted file mode 100644
index 84da4f85..00000000
--- a/lib/slack/events.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-import { SlackIntegration } from "@prisma/client";
-import { SlackClient } from "./client";
-import { createSlackMessage } from "./templates";
-import prisma from "@/lib/prisma";
-
-export interface SlackEventData {
- teamId: string;
- eventType: string;
- documentId?: string;
- dataroomId?: string;
- linkId?: string;
- viewerEmail?: string;
- viewerId?: string;
- userId?: string;
- metadata?: Record<string, any>;
-}
-
-export class SlackEventManager {
- private client: SlackClient;
-
- constructor() {
- this.client = new SlackClient();
- }
-
-
- async processEvent(eventData: SlackEventData): Promise<void> {
- try {
-
- const integration = await this.getSlackIntegration(eventData.teamId);
- if (!integration || !integration.enabled) {
- return;
- }
-
-
- if (!this.isEventTypeEnabled(eventData.eventType, integration)) {
- return;
- }
-
- await this.sendInstantNotification(eventData, integration);
-
- } catch (error) {
- console.error('Error processing Slack event:', error);
- }
- }
-
- /**
- * Send instant notification for an event
- */
- private async sendInstantNotification(
- eventData: SlackEventData,
- integration: SlackIntegration
- ): Promise<void> {
- try {
- const channels = await this.getNotificationChannels(eventData, integration);
-
- if (channels.length === 0) {
- return;
- }
-
-
- for (const channel of channels) {
- try {
- const message = await createSlackMessage(eventData);
- if (message) {
- const slackMessage = {
- ...message,
- channel: channel.id
- };
- await this.client.sendMessage(integration.accessToken, slackMessage);
- }
- } catch (channelError) {
- console.error(`Error sending to channel ${channel.name || channel.id}:`, channelError);
- }
- }
- } catch (error) {
- console.error('Error sending instant notification:', error);
- }
- }
-
-
-
- private async getSlackIntegration(teamId: string): Promise<SlackIntegration | null> {
- return await prisma.slackIntegration.findFirst({
- where: { teamId, enabled: true },
- });
- }
-
-
- private isEventTypeEnabled(
- eventType: string,
- integration: any
- ): boolean {
- const notificationTypes = integration.notificationTypes || {};
- return notificationTypes[eventType] || false;
- }
-
- private async getNotificationChannels(
- eventData: SlackEventData,
- integration: SlackIntegration
- ): Promise<any[]> {
- const enabledChannels = integration.enabledChannels || {};
- return Object.values(enabledChannels)
- .filter((channel: any) => channel.enabled)
- .filter((channel: any) => channel.notificationTypes && channel.notificationTypes.includes(eventData.eventType));
- }
-}
-
-
-export const slackEventManager = new SlackEventManager();
-
-export async function notifyDocumentView(data: Omit<SlackEventData, 'eventType'>) {
- await slackEventManager.processEvent({ ...data, eventType: 'document_view' });
-}
-
-export async function notifyDataroomAccess(data: Omit<SlackEventData, 'eventType'>) {
- await slackEventManager.processEvent({ ...data, eventType: 'dataroom_access' });
-}
-
-
-export async function notifyDocumentDownload(data: Omit<SlackEventData, 'eventType'>) {
- await slackEventManager.processEvent({ ...data, eventType: 'document_download' });
-}
-
diff --git a/lib/slack/templates.ts b/lib/slack/templates.ts
deleted file mode 100644
index e3de0b15..00000000
--- a/lib/slack/templates.ts
+++ /dev/null
@@ -1,399 +0,0 @@
-import { SlackMessage } from "../types/slack";
-import { SlackEventData } from "./events";
-import prisma from "@/lib/prisma";
-
-export async function createSlackMessage(
- eventData: SlackEventData,
-): Promise<SlackMessage | null> {
- try {
- switch (eventData.eventType) {
- case 'document_view':
- return await createDocumentViewMessage(eventData);
- case 'dataroom_access':
- return await createDataroomAccessMessage(eventData);
- case 'document_download':
- return await createDocumentDownloadMessage(eventData);
-
- default:
- return null;
- }
- } catch (error) {
- console.error('Error creating Slack message:', error);
- return null;
- }
-}
-
-/**
- * Document View Message Template
- */
-async function createDocumentViewMessage(eventData: SlackEventData): Promise<SlackMessage> {
- const document = eventData.documentId ? await getDocumentInfo(eventData.documentId) : null;
- const dataroom = eventData.dataroomId ? await getDataroomInfo(eventData.dataroomId) : null;
- const link = eventData.linkId ? await getLinkInfo(eventData.linkId) : null;
-
- const viewerDisplay = eventData.viewerEmail || 'Anonymous';
- const viewerMention = eventData.viewerEmail ? `<mailto:${eventData.viewerEmail}|${viewerDisplay}>` : viewerDisplay;
-
- let accessContext = "";
- if (eventData.dataroomId && dataroom) {
- accessContext = `in dataroom "${dataroom.name}"`;
- } else if (link?.name) {
- accessContext = `via shared link "${link.name}"`;
- } else {
- accessContext = `via shared link "Link ${link?.id.slice(0, 5)}"`;
- }
-
- return {
- text: `Your document has been viewed: ${document?.name || 'Unknown document'} by ${viewerDisplay} ${accessContext}`,
- blocks: [
- {
- type: "header",
- text: {
- type: "plain_text",
- text: "Your document has been viewed",
- emoji: false
- }
- },
- {
- type: "section",
- fields: [
- {
- type: "mrkdwn",
- text: `*Document:*\n${document?.name || 'Unknown'}`
- },
- {
- type: "mrkdwn",
- text: `*Viewer:*\n${viewerMention}`
- }
- ]
- },
- {
- type: "section",
- fields: [
- {
- type: "mrkdwn",
- text: dataroom?.name
- ? `*Dataroom:*\n${dataroom.name}`
- : link?.name
- ? `*Shared Link:*\n${link.name}`
- : `*Access:*\nDirect access`
- },
- {
- type: "mrkdwn",
- text: `*Time:*\n${new Date().toLocaleString()}`
- }
- ]
- },
- {
- type: "context",
- elements: [
- {
- type: "mrkdwn",
- text: eventData.dataroomId
- ? `Viewed document in dataroom "${dataroom?.name || 'Unknown'}"`
- : link?.name
- ? `Viewed document via shared link "${link.name}"`
- : `Viewed document via shared link "Link ${link?.id.slice(0, 5)}"`
- }
- ]
- },
- {
- type: "actions",
- elements: [
- {
- type: "button",
- text: {
- type: "plain_text",
- text: "View document",
- emoji: true
- },
- style: "primary",
- url: eventData.documentId
- ? `${process.env.NEXTAUTH_URL}/documents/${eventData.documentId}`
- : `${process.env.NEXTAUTH_URL}/dashboard`
- }
- ]
- }
- ]
- };
-}
-
-/**
- * Dataroom Access Message Template
- */
-async function createDataroomAccessMessage(eventData: SlackEventData): Promise<SlackMessage> {
- const dataroom = eventData.dataroomId ? await getDataroomInfo(eventData.dataroomId) : null;
- const link = eventData.linkId ? await getLinkInfo(eventData.linkId) : null;
-
- const viewerDisplay = eventData.viewerEmail || 'Anonymous';
- const viewerMention = eventData.viewerEmail ? `<mailto:${eventData.viewerEmail}|${viewerDisplay}>` : viewerDisplay;
-
-
- const accessContext = link?.name ? `via shared link "${link.name}"` : `via shared link "Link ${link?.id.slice(0, 5)}"`;
-
- return {
- text: `Your dataroom has been viewed: ${dataroom?.name || 'Unknown dataroom'} by ${viewerDisplay} ${accessContext}`,
- blocks: [
- {
- type: "header",
- text: {
- type: "plain_text",
- text: "Your dataroom has been viewed",
- emoji: false
- }
- },
- {
- type: "section",
- fields: [
- {
- type: "mrkdwn",
- text: `*Dataroom:*\n${dataroom?.name || 'Unknown'}`
- },
- {
- type: "mrkdwn",
- text: `*Viewer:*\n${viewerMention}`
- }
- ]
- },
- {
- type: "section",
- fields: [
- {
- type: "mrkdwn",
- text: link?.name
- ? `*Shared Link:*\n${link.name}`
- : `*Access:*\nDirect access`
- },
- {
- type: "mrkdwn",
- text: `*Time:*\n${new Date().toLocaleString()}`
- }
- ]
- },
- {
- type: "section",
- fields: [
- {
- type: "mrkdwn",
- text: `*Documents:*\n${dataroom?.documentCount || 0} documents`
- }
- ]
- },
- {
- type: "context",
- elements: [
- {
- type: "mrkdwn",
- text: link?.name
- ? `Dataroom accessed via shared link "${link.name}"`
- : `Dataroom accessed via shared link "Link ${link?.id.slice(0, 5)}"`
- }
- ]
- },
- {
- type: "actions",
- elements: [
- {
- type: "button",
- text: {
- type: "plain_text",
- text: "View dataroom",
- emoji: true
- },
- style: "primary",
- url: eventData.dataroomId
- ? `${process.env.NEXTAUTH_URL}/datarooms/${eventData.dataroomId}`
- : `${process.env.NEXTAUTH_URL}/dashboard`
- }
- ]
- }
- ]
- };
-}
-
-
-
-/**
- * Document Download Message Template
- */
-async function createDocumentDownloadMessage(eventData: SlackEventData): Promise<SlackMessage> {
- const document = eventData.documentId ? await getDocumentInfo(eventData.documentId) : null;
- const dataroom = eventData.dataroomId ? await getDataroomInfo(eventData.dataroomId) : null;
- const link = eventData.linkId ? await getLinkInfo(eventData.linkId) : null;
-
- const viewerDisplay = eventData.viewerEmail || 'Anonymous';
- const viewerMention = eventData.viewerEmail ? `<mailto:${eventData.viewerEmail}|${viewerDisplay}>` : viewerDisplay;
-
-
- const isBulkDownload = eventData.metadata?.isBulkDownload;
- const isFolderDownload = eventData.metadata?.isFolderDownload;
- const folderName = eventData.metadata?.folderName;
- const documentCount = eventData.metadata?.documentCount;
-
- let downloadType = "Document";
- let downloadContext = "";
-
- if (isBulkDownload) {
- downloadType = "Dataroom";
- downloadContext = `(${documentCount} documents)`;
- } else if (isFolderDownload) {
- downloadType = "Folder";
- downloadContext = `"${folderName}" (${documentCount} documents)`;
- } else if (dataroom) {
- downloadContext = `from dataroom "${dataroom.name}"`;
- } else if (link?.name) {
- downloadContext = `via shared link "${link.name}"`;
- } else {
- downloadContext = `via shared link "Link ${link?.id.slice(0, 5)}"`;
- }
-
- return {
- text: `${downloadType} has been downloaded: ${document?.name || downloadContext} by ${viewerDisplay}`,
- blocks: [
- {
- type: "header",
- text: {
- type: "plain_text",
- text: `${downloadType} has been downloaded`,
- emoji: false
- }
- },
- {
- type: "section",
- fields: [
- {
- type: "mrkdwn",
- text: document?.name
- ? `*${downloadType}:*\n${document.name}`
- : `*${downloadType}:*\n${downloadContext}`
- },
- {
- type: "mrkdwn",
- text: `*Downloaded by:*\n${viewerMention}`
- }
- ]
- },
- {
- type: "section",
- fields: [
- {
- type: "mrkdwn",
- text: dataroom?.name
- ? `*From Dataroom:*\n${dataroom.name}`
- : link?.name
- ? `*Shared Link:*\n${link.name}`
- : `*Context:*\n${downloadContext}`
- },
- {
- type: "mrkdwn",
- text: `*Time:*\n${new Date().toLocaleString()}`
- }
- ]
- },
- {
- type: "context",
- elements: [
- {
- type: "mrkdwn",
- text: isBulkDownload
- ? `Bulk dataroom download`
- : isFolderDownload
- ? `Folder download`
- : link?.name
- ? `Document download via shared link "${link.name}"`
- : `Document download via shared link "Link ${link?.id.slice(0, 5)}"`
- }
- ]
- },
- {
- type: "actions",
- elements: [
- {
- type: "button",
- text: {
- type: "plain_text",
- text: "View activity",
- emoji: true
- },
- style: "primary",
- url: eventData.dataroomId
- ? `${process.env.NEXTAUTH_URL}/datarooms/${eventData.dataroomId}`
- : eventData.documentId
- ? `${process.env.NEXTAUTH_URL}/documents/${eventData.documentId}`
- : `${process.env.NEXTAUTH_URL}/dashboard`
- }
- ]
- }
- ]
- };
-}
-
-
-
-
-
-
-
-
-
-
-// Helper functions
-async function getDocumentInfo(documentId: string) {
- try {
- return await prisma.document.findUnique({
- where: { id: documentId },
- select: {
- id: true,
- name: true,
- description: true,
- type: true,
- },
- });
- } catch (error) {
- console.error('Error fetching document info:', error);
- return null;
- }
-}
-
-
-
-async function getDataroomInfo(dataroomId: string) {
- try {
- return await prisma.dataroom.findUnique({
- where: { id: dataroomId },
- select: {
- id: true,
- name: true,
- description: true,
- _count: {
- select: {
- documents: true,
- },
- },
- },
- }).then(dataroom => dataroom ? {
- ...dataroom,
- documentCount: dataroom._count.documents,
- } : null);
- } catch (error) {
- console.error('Error fetching dataroom info:', error);
- return null;
- }
-}
-
-
-async function getLinkInfo(linkId: string) {
- try {
- return await prisma.link.findUnique({
- where: { id: linkId },
- select: {
- id: true,
- name: true,
- linkType: true,
- },
- });
- } catch (error) {
- console.error('Error fetching link info:', error);
- return null;
- }
-}
diff --git a/lib/swr/use-slack-channels.ts b/lib/swr/use-slack-channels.ts
index b161faee..21a29cae 100644
--- a/lib/swr/use-slack-channels.ts
+++ b/lib/swr/use-slack-channels.ts
@@ -1,31 +1,32 @@
+import { useTeam } from "@/context/team-context";
import useSWR from "swr";
+import { SlackChannel } from "@/lib/integrations/slack/types";
import { fetcher } from "@/lib/utils";
-import { SlackChannelsResponse } from "@/lib/types/slack";
-interface UseSlackChannelsProps {
- teamId?: string;
- enabled?: boolean;
-}
-
-export function useSlackChannels({ teamId, enabled = true }: UseSlackChannelsProps) {
- const { data, error, isLoading, mutate } = useSWR<SlackChannelsResponse>(
- enabled && teamId ? `/api/teams/${teamId}/slack/channels` : null,
- fetcher,
- {
- revalidateOnFocus: false,
- revalidateOnReconnect: false,
- dedupingInterval: 30000,
- revalidateIfStale: false,
- errorRetryCount: 2,
- errorRetryInterval: 5000,
- }
- );
+export function useSlackChannels({ enabled = true }: { enabled?: boolean }) {
+ const { currentTeamId: teamId } = useTeam();
+ const { data, error, isLoading, mutate } = useSWR<{
+ channels: SlackChannel[];
+ }>(
+ enabled && teamId
+ ? `/api/teams/${teamId}/integrations/slack/channels`
+ : null,
+ fetcher,
+ {
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ dedupingInterval: 30000,
+ revalidateIfStale: false,
+ errorRetryCount: 2,
+ errorRetryInterval: 5000,
+ },
+ );
- return {
- channels: data?.channels || [],
- error,
- loading: isLoading && !data,
- mutate,
- };
-}
\ No newline at end of file
+ return {
+ channels: data?.channels || [],
+ error,
+ loading: isLoading && !data,
+ mutate,
+ };
+}
diff --git a/lib/swr/use-slack-integration.ts b/lib/swr/use-slack-integration.ts
index 70f7ccaa..62281cf8 100644
--- a/lib/swr/use-slack-integration.ts
+++ b/lib/swr/use-slack-integration.ts
@@ -1,31 +1,29 @@
+import { useTeam } from "@/context/team-context";
import useSWR from "swr";
+import useSWRImmutable from "swr/immutable";
+import { SlackIntegration } from "@/lib/integrations/slack/types";
import { fetcher } from "@/lib/utils";
-import { SlackIntegrationResponse } from "@/lib/types/slack";
-interface UseSlackIntegrationProps {
- teamId?: string;
- enabled?: boolean;
-}
-
-export function useSlackIntegration({ teamId, enabled = true }: UseSlackIntegrationProps) {
- const { data, error, isLoading, mutate } = useSWR<SlackIntegrationResponse>(
- enabled && teamId ? `/api/teams/${teamId}/slack` : null,
- fetcher,
- {
- revalidateOnFocus: false,
- revalidateOnReconnect: false,
- dedupingInterval: 30000,
- revalidateIfStale: false,
- errorRetryCount: 2,
- errorRetryInterval: 5000,
- }
- );
+export function useSlackIntegration({ enabled = true }: { enabled?: boolean }) {
+ const { currentTeamId: teamId } = useTeam();
+ const { data, error, isLoading, mutate } = useSWRImmutable<SlackIntegration>(
+ enabled && teamId ? `/api/teams/${teamId}/integrations/slack` : null,
+ fetcher,
+ {
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ dedupingInterval: 30000,
+ revalidateIfStale: false,
+ errorRetryCount: 2,
+ errorRetryInterval: 5000,
+ },
+ );
- return {
- integration: data || null,
- error,
- loading: isLoading && !data,
- mutate,
- };
-}
\ No newline at end of file
+ return {
+ integration: data || null,
+ error,
+ loading: isLoading && !data,
+ mutate,
+ };
+}
diff --git a/lib/types/slack.ts b/lib/types/slack.ts
deleted file mode 100644
index ac652901..00000000
--- a/lib/types/slack.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-export interface SlackChannel {
- id: string;
- name: string;
- is_archived: boolean;
- is_private: boolean;
- is_member?: boolean;
-}
-
-export interface SlackIntegration {
- id: string;
- workspaceId: string;
- workspaceName: string;
- workspaceUrl: string;
- botUserId: string;
- botUsername: string;
- enabled: boolean;
- notificationTypes: {
- document_view: boolean;
- dataroom_access: boolean;
- document_download: boolean;
- };
- defaultChannel?: string;
- enabledChannels: Record<string, SlackChannelConfig>;
- createdAt: string;
- updatedAt: string;
-}
-
-// API Request Types
-export interface UpdateSlackIntegrationRequest {
- enabled?: boolean;
- notificationTypes?: SlackIntegration['notificationTypes'];
- defaultChannel?: string;
- enabledChannels?: Record<string, SlackChannelConfig>;
-}
-
-// API Response Types
-export interface SlackChannelsResponse {
- channels: SlackChannel[];
-}
-
-export interface SlackIntegrationResponse extends SlackIntegration { }
-
-export interface SlackWorkspaceInfo {
- id: string;
- name: string;
- url: string;
- domain: string;
-}
-
-export interface SlackOAuthResponse {
- ok: boolean;
- access_token: string;
- token_type: string;
- scope: string;
- bot_user_id: string;
- team: {
- name: string;
- id: string;
- };
- enterprise?: {
- name: string;
- id: string;
- };
- authed_user: {
- id: string;
- scope: string;
- access_token: string;
- token_type: string;
- };
-}
-
-export interface SlackMessage {
- channel?: string;
- text?: string;
- blocks?: any[];
- thread_ts?: string;
- unfurl_links?: boolean;
- unfurl_media?: boolean;
-}
-
-export type SlackNotificationType = 'document_view' | 'dataroom_access' | 'document_download';
-
-export interface SlackChannelConfig {
- id: string;
- name: string;
- enabled: boolean;
- notificationTypes: SlackNotificationType[];
-}
\ No newline at end of file
diff --git a/lib/utils.ts b/lib/utils.ts
index 83269fe5..fdb36bcc 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -589,61 +589,6 @@ export function decryptEncrpytedPassword(password: string): string {
return decrypted;
}
-
-export function encryptSlackToken(token: string): string {
- if (!token) return "";
- const textParts: string[] = token.split(":");
- if (textParts.length === 2) {
- return token;
- }
- const encryptionKey = process.env.NEXT_PRIVATE_SLACK_TOKEN_KEY || process.env.NEXT_PRIVATE_DOCUMENT_PASSWORD_KEY;
- if (!encryptionKey) {
- throw new Error("NEXT_PRIVATE_SLACK_TOKEN_KEY environment variable is required for token encryption");
- }
-
- const encryptedKey: string = crypto
- .createHash("sha256")
- .update(String(encryptionKey))
- .digest("base64")
- .substring(0, 32);
-
- const IV: Buffer = crypto.randomBytes(16);
- const cipher = crypto.createCipheriv("aes-256-ctr", encryptedKey, IV);
- let encryptedText: string = cipher.update(token, "utf8", "hex");
- encryptedText += cipher.final("hex");
-
- return IV.toString("hex") + ":" + encryptedText;
-}
-
-
-export function decryptSlackToken(encryptedToken: string): string {
- if (!encryptedToken) return "";
-
- const encryptionKey = process.env.NEXT_PRIVATE_SLACK_TOKEN_KEY || process.env.NEXT_PRIVATE_DOCUMENT_PASSWORD_KEY;
- if (!encryptionKey) {
- throw new Error("NEXT_PRIVATE_SLACK_TOKEN_KEY environment variable is required for token decryption");
- }
-
- const encryptedKey: string = crypto
- .createHash("sha256")
- .update(String(encryptionKey))
- .digest("base64")
- .substring(0, 32);
-
- const textParts: string[] = encryptedToken.split(":");
- if (!textParts || textParts.length !== 2) {
- return encryptedToken;
- }
-
- const IV: Buffer = Buffer.from(textParts[0], "hex");
- const encryptedText: string = textParts[1];
- const decipher = crypto.createDecipheriv("aes-256-ctr", encryptedKey, IV);
- let decrypted: string = decipher.update(encryptedText, "hex", "utf8");
- decrypted += decipher.final("utf8");
-
- return decrypted;
-}
-
type FilterMode = "email" | "domain" | "both";
export const sanitizeList = (
diff --git a/pages/api/links/download/bulk.ts b/pages/api/links/download/bulk.ts
index f35f2e0f..92df59cf 100644
--- a/pages/api/links/download/bulk.ts
+++ b/pages/api/links/download/bulk.ts
@@ -5,9 +5,9 @@ import { InvocationType, InvokeCommand } from "@aws-sdk/client-lambda";
import { ItemType, ViewType } from "@prisma/client";
import { getLambdaClientForTeam } from "@/lib/files/aws-client";
+import { notifyDocumentDownload } from "@/lib/integrations/slack/events";
import prisma from "@/lib/prisma";
import { getIpAddress } from "@/lib/utils/ip";
-import { notifyDocumentDownload } from "@/lib/slack/events";
export const config = {
maxDuration: 300,
@@ -112,7 +112,9 @@ export default async function handle(
// if dataroom does not allow bulk download, we should not allow the download
if (!view.dataroom.allowBulkDownload) {
- return res.status(403).json({ error: "Bulk download is disabled for this dataroom" });
+ return res
+ .status(403)
+ .json({ error: "Bulk download is disabled for this dataroom" });
}
// if viewedAt is longer than 23 hours ago, we should not allow the download
@@ -279,7 +281,7 @@ export default async function handle(
// Use .file if watermark is enabled and document is PDF, otherwise use .originalFile
const fileKey =
view.link.enableWatermark &&
- doc.document.versions[0].type === "pdf"
+ doc.document.versions[0].type === "pdf"
? doc.document.versions[0].file
: (doc.document.versions[0].originalFile ??
doc.document.versions[0].file);
@@ -338,16 +340,22 @@ export default async function handle(
folderStructure: folderStructure,
watermarkConfig: view.link.enableWatermark
? {
- enabled: true,
- config: view.link.watermarkConfig,
- viewerData: {
- email: view.viewerEmail,
- date: (view.viewedAt ? new Date(view.viewedAt) : new Date()).toLocaleDateString(),
- time: (view.viewedAt ? new Date(view.viewedAt) : new Date()).toLocaleTimeString(),
- link: view.link.name,
- ipAddress: getIpAddress(req.headers),
- },
- }
+ enabled: true,
+ config: view.link.watermarkConfig,
+ viewerData: {
+ email: view.viewerEmail,
+ date: (view.viewedAt
+ ? new Date(view.viewedAt)
+ : new Date()
+ ).toLocaleDateString(),
+ time: (view.viewedAt
+ ? new Date(view.viewedAt)
+ : new Date()
+ ).toLocaleTimeString(),
+ link: view.link.name,
+ ipAddress: getIpAddress(req.headers),
+ },
+ }
: { enabled: false },
}),
};
diff --git a/pages/api/links/download/dataroom-document.ts b/pages/api/links/download/dataroom-document.ts
index 1dfe7343..0e4d5b04 100644
--- a/pages/api/links/download/dataroom-document.ts
+++ b/pages/api/links/download/dataroom-document.ts
@@ -3,10 +3,10 @@ import { NextApiRequest, NextApiResponse } from "next";
import { ItemType, ViewType } from "@prisma/client";
import { getFile } from "@/lib/files/get-file";
+import { notifyDocumentDownload } from "@/lib/integrations/slack/events";
import prisma from "@/lib/prisma";
import { getFileNameWithPdfExtension } from "@/lib/utils";
import { getIpAddress } from "@/lib/utils/ip";
-import { notifyDocumentDownload } from "@/lib/slack/events";
export const config = {
maxDuration: 180,
@@ -217,10 +217,16 @@ export default async function handle(
originalFileName: downloadDocuments[0].document!.name,
viewerData: {
email: view.viewerEmail,
- date: (view.viewedAt ? new Date(view.viewedAt) : new Date()).toLocaleDateString(),
+ date: (view.viewedAt
+ ? new Date(view.viewedAt)
+ : new Date()
+ ).toLocaleDateString(),
ipAddress: getIpAddress(req.headers),
link: view.link.name,
- time: (view.viewedAt ? new Date(view.viewedAt) : new Date()).toLocaleTimeString(),
+ time: (view.viewedAt
+ ? new Date(view.viewedAt)
+ : new Date()
+ ).toLocaleTimeString(),
},
}),
},
diff --git a/pages/api/links/download/dataroom-folder.ts b/pages/api/links/download/dataroom-folder.ts
index d7e60311..1ffab18e 100644
--- a/pages/api/links/download/dataroom-folder.ts
+++ b/pages/api/links/download/dataroom-folder.ts
@@ -6,9 +6,9 @@ import { ItemType, ViewType } from "@prisma/client";
import slugify from "@sindresorhus/slugify";
import { getLambdaClientForTeam } from "@/lib/files/aws-client";
+import { notifyDocumentDownload } from "@/lib/integrations/slack/events";
import prisma from "@/lib/prisma";
import { getIpAddress } from "@/lib/utils/ip";
-import { notifyDocumentDownload } from "@/lib/slack/events";
export const config = {
maxDuration: 300,
@@ -335,8 +335,12 @@ export default async function handler(
config: view.link.watermarkConfig,
viewerData: {
email: view.viewerEmail,
- date: new Date(view.viewedAt ? view.viewedAt : new Date()).toLocaleDateString(),
- time: new Date(view.viewedAt ? view.viewedAt : new Date()).toLocaleTimeString(),
+ date: new Date(
+ view.viewedAt ? view.viewedAt : new Date(),
+ ).toLocaleDateString(),
+ time: new Date(
+ view.viewedAt ? view.viewedAt : new Date(),
+ ).toLocaleTimeString(),
link: view.link.name,
ipAddress: getIpAddress(req.headers),
},
diff --git a/pages/api/links/download/index.ts b/pages/api/links/download/index.ts
index aa1a9ea4..29e470e7 100644
--- a/pages/api/links/download/index.ts
+++ b/pages/api/links/download/index.ts
@@ -3,10 +3,10 @@ import { NextApiRequest, NextApiResponse } from "next";
import { LinkType } from "@prisma/client";
import { getFile } from "@/lib/files/get-file";
+import { notifyDocumentDownload } from "@/lib/integrations/slack/events";
import prisma from "@/lib/prisma";
import { getFileNameWithPdfExtension } from "@/lib/utils";
import { getIpAddress } from "@/lib/utils/ip";
-import { notifyDocumentDownload } from "@/lib/slack/events";
export default async function handle(
req: NextApiRequest,
@@ -150,10 +150,14 @@ export default async function handle(
originalFileName: view.document!.name,
viewerData: {
email: view.viewerEmail,
- date: new Date(view.viewedAt ? view.viewedAt : new Date()).toLocaleDateString(),
+ date: new Date(
+ view.viewedAt ? view.viewedAt : new Date(),
+ ).toLocaleDateString(),
ipAddress: getIpAddress(req.headers),
link: view.link.name,
- time: new Date(view.viewedAt ? view.viewedAt : new Date()).toLocaleTimeString(),
+ time: new Date(
+ view.viewedAt ? view.viewedAt : new Date(),
+ ).toLocaleTimeString(),
},
}),
},
diff --git a/pages/api/slack/oauth/callback.ts b/pages/api/slack/oauth/callback.ts
deleted file mode 100644
index 9daf1b46..00000000
--- a/pages/api/slack/oauth/callback.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import { NextApiRequest, NextApiResponse } from 'next';
-import { getServerSession } from 'next-auth/next';
-import { authOptions } from '@/pages/api/auth/[...nextauth]';
-import { slackClient } from '@/lib/slack/client';
-import { CustomUser } from '@/lib/types';
-import prisma from '@/lib/prisma';
-
-import { encryptSlackToken } from '@/lib/utils';
-import { sendSlackIntegrationNotification } from '@/lib/emails/send-slack-integration-notification';
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse
-) {
- if (req.method !== 'GET') {
- return res.status(405).json({ error: 'Method not allowed' });
- }
-
- try {
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- return res.status(401).json({ error: 'Unauthorized' });
- }
- const { code, state, error } = req.query as { code: string; state: string; error?: string };
-
- const userId = (session.user as CustomUser).id;
-
- // Handle OAuth errors
- if (error) {
- return res.redirect(`/settings/slack?error=${encodeURIComponent(error)}`);
- }
-
- if (!code || !state) {
- return res.redirect(`/settings/slack?error=${encodeURIComponent('Missing authorization code or state')}`);
- }
-
- // Decode state to get teamId and userId
- let stateData: { teamId: string; userId: string };
- try {
- stateData = JSON.parse(Buffer.from(state, 'base64').toString());
- } catch (error) {
- return res.redirect(`/settings/slack?error=${encodeURIComponent('Invalid state parameter')}`);
- }
-
- const { teamId } = stateData;
-
- // Verify user has access to team
- const userTeam = await prisma.userTeam.findUnique({
- where: {
- userId_teamId: {
- userId,
- teamId,
- },
- },
- });
-
- if (!userTeam) {
- return res.redirect(`/settings/slack?error=${encodeURIComponent('Access denied')}`);
- }
-
- // Validate state parameter
- if (stateData.userId !== userId) {
- return res.redirect(`/settings/slack?error=${encodeURIComponent('Invalid state parameter')}`);
- }
-
- // Check if integration already exists
- const existingIntegration = await prisma.slackIntegration.findUnique({
- where: { teamId },
- });
-
- if (existingIntegration) {
- return res.redirect(`/settings/slack?error=${encodeURIComponent('Slack integration already exists for this team')}`);
- }
-
- // Exchange code for access token
- const redirectUri = `${process.env.NEXTAUTH_URL}/api/slack/oauth/callback`;
- const oauthResponse = await slackClient.exchangeCodeForToken(code, redirectUri);
-
-
- // Get workspace and bot information
- const workspaceInfo = await slackClient.getWorkspaceInfo(oauthResponse.access_token);
- const botInfo = await slackClient.getBotInfo(oauthResponse.access_token);
-
- // Create Slack integration
- const integration = await prisma.slackIntegration.create({
- data: {
- teamId,
- workspaceId: workspaceInfo.id,
- workspaceName: workspaceInfo.name,
- workspaceUrl: workspaceInfo.url,
- accessToken: encryptSlackToken(oauthResponse.access_token),
- botUserId: botInfo.id,
- botUsername: botInfo.name,
- enabledChannels: {},
- notificationTypes: {
- document_view: true,
- dataroom_access: true,
- document_download: true,
- },
- enabled: true,
- },
- });
-
- try {
- const team = await prisma.team.findUnique({
- where: { id: teamId },
- include: {
- users: {
- include: {
- user: true,
- },
- },
- },
- });
-
- if (!team) {
- console.warn(`Team with id ${teamId} not found.`);
- return;
- }
-
- if (!team.users.length) {
- console.warn(`Team "${team.name}" has no users to notify.`);
- return;
- }
-
- const settingsUrl = `${process.env.NEXTAUTH_URL}/settings/slack`;
-
- const usersWithEmail = team.users.filter(userTeam => userTeam.user.email);
-
- const emailPromises = usersWithEmail.map(async (userTeam) => {
- try {
- await sendSlackIntegrationNotification({
- userEmail: userTeam.user.email!,
- teamName: team.name,
- settingsUrl,
- });
- } catch (emailError) {
- console.error(`Failed to send Slack integration notification email to ${userTeam.user.email}:`, emailError);
- }
- });
-
- await Promise.allSettled(emailPromises)
- .then(results => {
- const rejected = results.filter(r => r.status === 'rejected');
- if (rejected.length) {
- console.error('Some Slack integration notification emails failed:', rejected);
- }
- });
- } catch (err) {
- console.error('Unexpected error sending Slack integration notification emails:', err);
- }
-
-
- const redirectParams = new URLSearchParams({
- success: 'true',
- integrationId: integration.id,
- });
-
- return res.redirect(`/settings/slack?${redirectParams.toString()}`);
-
- } catch (error) {
- console.error('Slack OAuth callback error:', error);
- return res.redirect(`/settings/slack?error=${encodeURIComponent('Failed to complete Slack integration')}`);
- }
-}
\ No newline at end of file
diff --git a/pages/api/teams/[teamId]/integrations/slack/channels.ts b/pages/api/teams/[teamId]/integrations/slack/channels.ts
new file mode 100644
index 00000000..4133a2b1
--- /dev/null
+++ b/pages/api/teams/[teamId]/integrations/slack/channels.ts
@@ -0,0 +1,131 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import { slackClient } from "@/lib/integrations/slack/client";
+import { getSlackEnv } from "@/lib/integrations/slack/env";
+import { SlackCredential } from "@/lib/integrations/slack/types";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).json({ error: "Unauthorized" });
+ }
+
+ const { teamId } = req.query as { teamId: string };
+ const userId = (session.user as CustomUser).id;
+
+ const userTeam = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId,
+ teamId,
+ },
+ },
+ });
+
+ if (!userTeam) {
+ return res.status(403).json({ error: "Access denied" });
+ }
+
+ const env = getSlackEnv();
+
+ if (req.method === "GET") {
+ try {
+ const integration = await prisma.installedIntegration.findUnique({
+ where: {
+ teamId_integrationId: {
+ teamId,
+ integrationId: env.SLACK_INTEGRATION_ID,
+ },
+ },
+ select: {
+ credentials: true,
+ },
+ });
+
+ if (!integration) {
+ return res.status(404).json({ error: "Slack integration not found" });
+ }
+
+ try {
+ const channels = await slackClient.getChannels(
+ (integration.credentials as SlackCredential).accessToken,
+ );
+
+ const availableChannels = channels
+ .filter((channel) => !channel.is_archived)
+ .map((channel) => ({
+ id: channel.id,
+ name: channel.name,
+ is_private: channel.is_private,
+ is_member: channel.is_member || false,
+ }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+ return res.status(200).json({ channels: availableChannels });
+ } catch (slackError) {
+ if (
+ slackError instanceof Error &&
+ slackError.message.includes("missing_scope")
+ ) {
+ return res.status(403).json({
+ error:
+ "Insufficient permissions. The Slack app needs channels:read permission.",
+ });
+ }
+
+ if (
+ slackError instanceof Error &&
+ slackError.message.includes("invalid_auth")
+ ) {
+ return res.status(401).json({
+ error:
+ "Invalid Slack access token. Please reconnect your Slack integration.",
+ });
+ }
+ return res.status(200).json({ channels: [] });
+ }
+ } catch (error) {
+ console.error("Error fetching Slack channels:", error);
+ return res.status(500).json({ error: "Internal server error" });
+ }
+ }
+
+ if (req.method === "PUT") {
+ try {
+ const { enabledChannels } = req.body;
+
+ if (!enabledChannels) {
+ return res.status(400).json({ error: "enabledChannels is required" });
+ }
+
+ await prisma.installedIntegration.update({
+ where: {
+ teamId_integrationId: {
+ teamId,
+ integrationId: env.SLACK_INTEGRATION_ID,
+ },
+ },
+ data: { configuration: { enabledChannels } },
+ });
+
+ return res.status(200).json({
+ success: true,
+ enabledChannels,
+ updatedAt: new Date().toISOString(),
+ });
+ } catch (error) {
+ console.error("Error updating Slack channels:", error);
+ return res.status(500).json({ error: "Internal server error" });
+ }
+ }
+
+ return res.status(405).json({ error: "Method not allowed" });
+}
diff --git a/pages/api/teams/[teamId]/integrations/slack/index.ts b/pages/api/teams/[teamId]/integrations/slack/index.ts
new file mode 100644
index 00000000..407a8e8a
--- /dev/null
+++ b/pages/api/teams/[teamId]/integrations/slack/index.ts
@@ -0,0 +1,199 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+import { z } from "zod";
+
+import { getSlackEnv } from "@/lib/integrations/slack/env";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+
+const slackIntegrationUpdateSchema = z.object({
+ enabled: z.boolean().optional(),
+ enabledChannels: z.record(z.string(), z.boolean()).optional(),
+});
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).json({ error: "Unauthorized" });
+ }
+
+ const { teamId } = req.query as { teamId: string };
+ const userId = (session.user as CustomUser).id;
+
+ const userTeam = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId,
+ teamId,
+ },
+ },
+ });
+
+ if (!userTeam) {
+ return res.status(403).json({ error: "Access denied" });
+ }
+
+ switch (req.method) {
+ case "GET":
+ return handleGet(req, res, teamId);
+ case "PUT":
+ return handleUpdate(req, res, teamId);
+ case "DELETE":
+ return handleDelete(req, res, teamId);
+ default:
+ return res.status(405).json({ error: "Method not allowed" });
+ }
+}
+
+async function handleGet(
+ req: NextApiRequest,
+ res: NextApiResponse,
+ teamId: string,
+) {
+ const env = getSlackEnv();
+
+ try {
+ const integration = await prisma.installedIntegration.findUnique({
+ where: {
+ teamId_integrationId: {
+ teamId,
+ integrationId: env.SLACK_INTEGRATION_ID,
+ },
+ },
+ select: {
+ id: true,
+ credentials: true,
+ configuration: true,
+ enabled: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ });
+
+ if (!integration) {
+ return res.status(404).json({ error: "Slack integration not found" });
+ }
+
+ return res.status(200).json(integration);
+ } catch (error) {
+ console.error("Error fetching Slack integration:", error);
+ return res.status(500).json({ error: "Internal server error" });
+ }
+}
+
+async function handleUpdate(
+ req: NextApiRequest,
+ res: NextApiResponse,
+ teamId: string,
+) {
+ const env = getSlackEnv();
+ try {
+ const validationResult = slackIntegrationUpdateSchema.safeParse(req.body);
+
+ if (!validationResult.success) {
+ return res.status(400).json({
+ error: "Invalid request payload",
+ details: validationResult.error.errors,
+ });
+ }
+
+ const { enabled, enabledChannels } = validationResult.data;
+
+ if (enabledChannels && Object.keys(validationResult.data).length === 1) {
+ await prisma.installedIntegration.update({
+ where: {
+ teamId_integrationId: {
+ teamId,
+ integrationId: env.SLACK_INTEGRATION_ID,
+ },
+ },
+ data: { configuration: { enabledChannels } },
+ });
+
+ return res.status(200).json({
+ success: true,
+ enabledChannels,
+ updatedAt: new Date().toISOString(),
+ });
+ }
+
+ const updateData: {
+ enabled?: boolean;
+ enabledChannels?: Record<string, boolean>;
+ } = {};
+
+ if (enabled !== undefined) updateData.enabled = enabled;
+
+ if (enabledChannels) updateData.enabledChannels = enabledChannels;
+
+ if (Object.keys(updateData).length === 0) {
+ return res.status(400).json({ error: "No fields to update" });
+ }
+
+ const updatedIntegration = await prisma.installedIntegration.update({
+ where: {
+ teamId_integrationId: {
+ teamId,
+ integrationId: env.SLACK_INTEGRATION_ID,
+ },
+ },
+ data: updateData,
+ select: {
+ id: true,
+ credentials: true,
+ configuration: true,
+ enabled: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ });
+
+ return res.status(200).json(updatedIntegration);
+ } catch (error) {
+ console.error("Error updating Slack integration:", error);
+ return res.status(500).json({ error: "Internal server error" });
+ }
+}
+
+async function handleDelete(
+ req: NextApiRequest,
+ res: NextApiResponse,
+ teamId: string,
+) {
+ const env = getSlackEnv();
+ try {
+ const integration = await prisma.installedIntegration.findUnique({
+ where: {
+ teamId_integrationId: {
+ teamId,
+ integrationId: env.SLACK_INTEGRATION_ID,
+ },
+ },
+ });
+
+ if (!integration) {
+ return res.status(404).json({ error: "Slack integration not found" });
+ }
+
+ await prisma.installedIntegration.delete({
+ where: {
+ teamId_integrationId: {
+ teamId,
+ integrationId: env.SLACK_INTEGRATION_ID,
+ },
+ },
+ });
+
+ return res
+ .status(200)
+ .json({ message: "Slack integration deleted successfully" });
+ } catch (error) {
+ console.error("Error deleting Slack integration:", error);
+ return res.status(500).json({ error: "Internal server error" });
+ }
+}
diff --git a/pages/api/teams/[teamId]/slack/channels.ts b/pages/api/teams/[teamId]/slack/channels.ts
deleted file mode 100644
index 5015c8dd..00000000
--- a/pages/api/teams/[teamId]/slack/channels.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import { NextApiRequest, NextApiResponse } from 'next';
-import { getServerSession } from 'next-auth/next';
-import { authOptions } from '@/pages/api/auth/[...nextauth]';
-import { CustomUser } from '@/lib/types';
-import prisma from '@/lib/prisma';
-import { slackClient } from '@/lib/slack/client';
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse
-) {
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- return res.status(401).json({ error: 'Unauthorized' });
- }
-
- const { teamId } = req.query as { teamId: string };
- const userId = (session.user as CustomUser).id;
-
- const userTeam = await prisma.userTeam.findUnique({
- where: {
- userId_teamId: {
- userId,
- teamId,
- },
- },
- });
-
- if (!userTeam) {
- return res.status(403).json({ error: 'Access denied' });
- }
-
- if (req.method === 'GET') {
- try {
- const integration = await prisma.slackIntegration.findUnique({
- where: { teamId },
- });
-
- if (!integration) {
- return res.status(404).json({ error: 'Slack integration not found' });
- }
-
- try {
- const channels = await slackClient.getChannels(integration.accessToken);
-
- const availableChannels = channels
- .filter(channel => !channel.is_archived)
- .map(channel => ({
- id: channel.id,
- name: channel.name,
- is_private: channel.is_private,
- is_member: channel.is_member || false,
- }))
- .sort((a, b) => a.name.localeCompare(b.name));
-
- return res.status(200).json({ channels: availableChannels });
- } catch (slackError) {
- if (slackError instanceof Error && slackError.message.includes('missing_scope')) {
- return res.status(403).json({
- error: 'Insufficient permissions. The Slack app needs channels:read permission.'
- });
- }
-
- if (slackError instanceof Error && slackError.message.includes('invalid_auth')) {
- return res.status(401).json({
- error: 'Invalid Slack access token. Please reconnect your Slack integration.'
- });
- }
- return res.status(200).json({ channels: [] });
- }
- } catch (error) {
- console.error('Error fetching Slack channels:', error);
- return res.status(500).json({ error: 'Internal server error' });
- }
- }
-
- if (req.method === 'PUT') {
- try {
- const { enabledChannels } = req.body;
-
- if (!enabledChannels) {
- return res.status(400).json({ error: 'enabledChannels is required' });
- }
-
- await prisma.slackIntegration.update({
- where: { teamId },
- data: { enabledChannels },
- });
-
- return res.status(200).json({
- success: true,
- enabledChannels,
- updatedAt: new Date().toISOString()
- });
- } catch (error) {
- console.error('Error updating Slack channels:', error);
- return res.status(500).json({ error: 'Internal server error' });
- }
- }
-
- return res.status(405).json({ error: 'Method not allowed' });
-}
\ No newline at end of file
diff --git a/pages/api/teams/[teamId]/slack/index.ts b/pages/api/teams/[teamId]/slack/index.ts
deleted file mode 100644
index 6b138e32..00000000
--- a/pages/api/teams/[teamId]/slack/index.ts
+++ /dev/null
@@ -1,201 +0,0 @@
-import { NextApiRequest, NextApiResponse } from 'next';
-import { getServerSession } from 'next-auth/next';
-import { authOptions } from '@/pages/api/auth/[...nextauth]';
-import { CustomUser } from '@/lib/types';
-import prisma from '@/lib/prisma';
-import { z } from 'zod';
-
-const slackIntegrationUpdateSchema = z.object({
- enabled: z.boolean().optional(),
- defaultChannel: z.string().nullable().optional(),
- enabledChannels: z.record(z.string(), z.boolean()).optional(),
- notificationTypes: z.object({
- document_view: z.boolean().optional(),
- document_download: z.boolean().optional(),
- dataroom_access: z.boolean().optional(),
- document_comment: z.boolean().optional(),
- document_reaction: z.boolean().optional(),
- }).optional(),
-});
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse
-) {
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- return res.status(401).json({ error: 'Unauthorized' });
- }
-
- const { teamId } = req.query as { teamId: string };
- const userId = (session.user as CustomUser).id;
-
- const userTeam = await prisma.userTeam.findUnique({
- where: {
- userId_teamId: {
- userId,
- teamId,
- },
- },
- });
-
- if (!userTeam) {
- return res.status(403).json({ error: 'Access denied' });
- }
-
- switch (req.method) {
- case 'GET':
- return handleGet(req, res, teamId);
- case 'PUT':
- return handleUpdate(req, res, teamId);
- case 'DELETE':
- return handleDelete(req, res, teamId);
- default:
- return res.status(405).json({ error: 'Method not allowed' });
- }
-}
-
-async function handleGet(
- req: NextApiRequest,
- res: NextApiResponse,
- teamId: string
-) {
- try {
- const integration = await prisma.slackIntegration.findUnique({
- where: { teamId },
- select: {
- id: true,
- workspaceId: true,
- workspaceName: true,
- workspaceUrl: true,
- botUserId: true,
- botUsername: true,
- enabled: true,
- notificationTypes: true,
- defaultChannel: true,
- enabledChannels: true,
- createdAt: true,
- updatedAt: true,
- },
- });
-
- if (!integration) {
- return res.status(404).json({ error: 'Slack integration not found' });
- }
-
- return res.status(200).json(integration);
- } catch (error) {
- console.error('Error fetching Slack integration:', error);
- return res.status(500).json({ error: 'Internal server error' });
- }
-}
-
-async function handleUpdate(
- req: NextApiRequest,
- res: NextApiResponse,
- teamId: string
-) {
- try {
- const validationResult = slackIntegrationUpdateSchema.safeParse(req.body);
-
- if (!validationResult.success) {
- return res.status(400).json({
- error: 'Invalid request payload',
- details: validationResult.error.errors
- });
- }
-
- const {
- enabled,
- notificationTypes,
- defaultChannel,
- enabledChannels,
- } = validationResult.data;
-
- if (enabledChannels && Object.keys(validationResult.data).length === 1) {
- await prisma.slackIntegration.update({
- where: { teamId },
- data: { enabledChannels },
- });
-
- return res.status(200).json({
- success: true,
- enabledChannels,
- updatedAt: new Date().toISOString()
- });
- }
-
- const updateData: {
- enabled?: boolean;
- notificationTypes?: {
- document_view?: boolean;
- document_download?: boolean;
- dataroom_access?: boolean;
- document_comment?: boolean;
- document_reaction?: boolean;
- };
- defaultChannel?: string | null;
- enabledChannels?: Record<string, boolean>;
- } = {};
-
- if (enabled !== undefined) updateData.enabled = enabled;
- if (notificationTypes) updateData.notificationTypes = notificationTypes;
- if (defaultChannel !== undefined) updateData.defaultChannel = defaultChannel;
- if (enabledChannels) updateData.enabledChannels = enabledChannels;
-
- if (Object.keys(updateData).length === 0) {
- return res.status(400).json({ error: 'No fields to update' });
- }
-
- const updatedIntegration = await prisma.slackIntegration.update({
- where: { teamId },
- data: updateData,
- select: {
- id: true,
- workspaceId: true,
- workspaceName: true,
- workspaceUrl: true,
- botUserId: true,
- botUsername: true,
- enabled: true,
- notificationTypes: true,
- defaultChannel: true,
- enabledChannels: true,
- createdAt: true,
- updatedAt: true,
- },
- });
-
-
-
- return res.status(200).json(updatedIntegration);
- } catch (error) {
- console.error('Error updating Slack integration:', error);
- return res.status(500).json({ error: 'Internal server error' });
- }
-}
-
-async function handleDelete(
- req: NextApiRequest,
- res: NextApiResponse,
- teamId: string
-) {
- try {
- const integration = await prisma.slackIntegration.findUnique({
- where: { teamId },
- });
-
- if (!integration) {
- return res.status(404).json({ error: 'Slack integration not found' });
- }
-
- await prisma.slackIntegration.delete({
- where: { teamId },
- });
-
- return res.status(200).json({ message: 'Slack integration deleted successfully' });
- } catch (error) {
- console.error('Error deleting Slack integration:', error);
- return res.status(500).json({ error: 'Internal server error' });
- }
-}
\ No newline at end of file
diff --git a/pages/api/teams/[teamId]/slack/oauth/authorize.ts b/pages/api/teams/[teamId]/slack/oauth/authorize.ts
deleted file mode 100644
index a78a01ce..00000000
--- a/pages/api/teams/[teamId]/slack/oauth/authorize.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { NextApiRequest, NextApiResponse } from 'next';
-import { getServerSession } from 'next-auth/next';
-import { authOptions } from '@/pages/api/auth/[...nextauth]';
-import { slackClient } from '@/lib/slack/client';
-import { CustomUser } from '@/lib/types';
-import prisma from '@/lib/prisma';
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse
-) {
- if (req.method !== 'GET') {
- return res.status(405).json({ error: 'Method not allowed' });
- }
-
- try {
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- return res.status(401).json({ error: 'Unauthorized' });
- }
-
- const { teamId } = req.query as { teamId: string };
- const userId = (session.user as CustomUser).id;
-
- const userTeam = await prisma.userTeam.findUnique({
- where: {
- userId_teamId: {
- userId,
- teamId,
- },
- },
- });
-
- if (!userTeam) {
- return res.status(403).json({ error: 'Access denied' });
- }
-
- const existingIntegration = await prisma.slackIntegration.findUnique({
- where: { teamId },
- });
-
- if (existingIntegration) {
- return res.status(400).json({
- error: 'Slack integration already exists for this team',
- integrationId: existingIntegration.id
- });
- }
-
- const state = Buffer.from(JSON.stringify({ teamId, userId })).toString('base64');
-
- const redirectUri = `${process.env.NEXTAUTH_URL}/api/slack/oauth/callback`;
-
- const oauthUrl = slackClient.getOAuthUrl(state, redirectUri);
-
- return res.status(200).json({
- oauthUrl,
- state
- });
-
- } catch (error) {
- console.error('Slack OAuth authorization error:', error);
- return res.status(500).json({ error: 'Internal server error' });
- }
-}
\ No newline at end of file
diff --git a/pages/settings/slack.tsx b/pages/settings/slack.tsx
index 47eed3af..f939de8a 100644
--- a/pages/settings/slack.tsx
+++ b/pages/settings/slack.tsx
@@ -6,20 +6,17 @@ import { useTeam } from "@/context/team-context";
import { CircleHelpIcon, Hash, Settings, XCircleIcon } from "lucide-react";
import { toast } from "sonner";
-import { useSlackChannels } from "@/lib/swr/use-slack-channels";
-import { useSlackIntegration } from "@/lib/swr/use-slack-integration";
import {
SlackChannelConfig,
SlackIntegration,
- SlackIntegrationResponse,
- UpdateSlackIntegrationRequest,
-} from "@/lib/types/slack";
+} from "@/lib/integrations/slack/types";
+import { useSlackChannels } from "@/lib/swr/use-slack-channels";
+import { useSlackIntegration } from "@/lib/swr/use-slack-integration";
import AppLayout from "@/components/layouts/app";
import { SettingsHeader } from "@/components/settings/settings-header";
import SlackSettingsSkeleton from "@/components/settings/slack-settings-skeleton";
import { SlackIcon } from "@/components/shared/icons/slack-icon";
-import { Alert, AlertDescription } from "@/components/ui/alert";
import { CommonAlertDialog } from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
@@ -51,7 +48,6 @@ export default function SlackSettings() {
loading: loadingIntegration,
mutate: mutateIntegration,
} = useSlackIntegration({
- teamId,
enabled: !!teamId,
});
@@ -61,7 +57,6 @@ export default function SlackSettings() {
error: channelsError,
mutate: mutateChannels,
} = useSlackChannels({
- teamId,
enabled: !!integration,
});
@@ -91,35 +86,35 @@ export default function SlackSettings() {
[filteredChannels, ChannelIcon],
);
- const handleIntegrationUpdate = (updatedIntegration: SlackIntegration) => {
- mutateIntegration(updatedIntegration, false);
- };
+ // const handleIntegrationUpdate = (updatedIntegration: SlackIntegration) => {
+ // mutateIntegration(updatedIntegration, false);
+ // };
- useEffect(() => {
- let timeoutId: NodeJS.Timeout | null = null;
+ // useEffect(() => {
+ // let timeoutId: NodeJS.Timeout | null = null;
- if (router.query.success) {
- toast.success("Slack integration connected successfully!");
- mutateIntegration();
+ // if (router.query.success) {
+ // toast.success("Slack integration connected successfully!");
+ // mutateIntegration();
- if (router.query.warning) {
- toast.warning(`Warning: ${router.query.warning}`);
- }
+ // if (router.query.warning) {
+ // toast.warning(`Warning: ${router.query.warning}`);
+ // }
- timeoutId = setTimeout(() => {
- router.replace("/settings/slack", undefined, { shallow: true });
- }, 100);
- } else if (router.query.error) {
- toast.error(`Failed to connect Slack: ${router.query.error}`);
- timeoutId = setTimeout(() => {
- router.replace("/settings/slack", undefined, { shallow: true });
- }, 100);
- }
+ // timeoutId = setTimeout(() => {
+ // router.replace("/settings/slack", undefined, { shallow: true });
+ // }, 100);
+ // } else if (router.query.error) {
+ // toast.error(`Failed to connect Slack: ${router.query.error}`);
+ // timeoutId = setTimeout(() => {
+ // router.replace("/settings/slack", undefined, { shallow: true });
+ // }, 100);
+ // }
- return () => {
- if (timeoutId) clearTimeout(timeoutId);
- };
- }, [router.query, mutateIntegration]);
+ // return () => {
+ // if (timeoutId) clearTimeout(timeoutId);
+ // };
+ // }, [router.query, mutateIntegration]);
const handleConnect = async () => {
if (!teamId) return;
@@ -127,7 +122,7 @@ export default function SlackSettings() {
setConnecting(true);
try {
const response = await fetch(
- `/api/teams/${teamId}/slack/oauth/authorize`,
+ `/api/integrations/slack/oauth/authorize?teamId=${teamId}`,
);
const data = await response.json();
@@ -147,7 +142,7 @@ export default function SlackSettings() {
const handleDisconnect = async () => {
const disconnectPromise = async () => {
- const response = await fetch(`/api/teams/${teamId}/slack`, {
+ const response = await fetch(`/api/teams/${teamId}/integrations/slack`, {
method: "DELETE",
});
@@ -203,7 +198,9 @@ export default function SlackSettings() {
mutateIntegration(
{
...integration,
- enabledChannels: updatedChannels,
+ configuration: {
+ enabledChannels: updatedChannels,
+ },
},
false,
);
@@ -214,14 +211,16 @@ export default function SlackSettings() {
};
const startTime = performance.now();
- const response = await fetch(`/api/teams/${teamId}/slack/channels`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(requestBody),
- });
+ const response = await fetch(
+ `/api/teams/${teamId}/integrations/slack/channels`,
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(requestBody),
+ },
+ );
const endTime = performance.now();
-
if (!response.ok) {
const errorData = await response.json();
throw new Error(
@@ -236,7 +235,9 @@ export default function SlackSettings() {
mutateIntegration(
{
...integration,
- enabledChannels: result.enabledChannels,
+ configuration: {
+ enabledChannels: result.enabledChannels,
+ },
updatedAt: result.updatedAt,
},
false,
@@ -295,17 +296,16 @@ export default function SlackSettings() {
false,
);
- const requestBody: UpdateSlackIntegrationRequest = {
- enabled: checked,
- };
-
- const response = await fetch(`/api/teams/${teamId}/slack`, {
- method: "PUT",
- headers: {
- "Content-Type": "application/json",
+ const response = await fetch(
+ `/api/teams/${teamId}/integrations/slack`,
+ {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ enabled: checked }),
},
- body: JSON.stringify(requestBody),
- });
+ );
if (!response.ok) {
// Rollback on error
@@ -319,8 +319,7 @@ export default function SlackSettings() {
throw new Error("Failed to update notification settings");
}
- const updatedIntegration: SlackIntegrationResponse =
- await response.json();
+ const updatedIntegration: SlackIntegration = await response.json();
mutateIntegration(updatedIntegration, false);
return checked
@@ -418,7 +417,7 @@ export default function SlackSettings() {
General Settings
</CardTitle>
<CardDescription>
- Connected to {integration.workspaceName}
+ Connected to {integration.credentials.team.name}
</CardDescription>
</CardHeader>
<CardContent>
@@ -498,7 +497,7 @@ export default function SlackSettings() {
loading={false}
options={channelOptions}
value={Object.keys(
- integration.enabledChannels || {},
+ integration.configuration.enabledChannels || {},
)}
setIsPopoverOpen={setIsChannelPopoverOpen}
isPopoverOpen={isChannelPopoverOpen}
@@ -527,4 +526,4 @@ export default function SlackSettings() {
</main>
</AppLayout>
);
-}
\ No newline at end of file
+}
diff --git a/prisma/migrations/20250904040013_slack_integration/migration.sql b/prisma/migrations/20250904040013_slack_integration/migration.sql
deleted file mode 100644
index 7d131e1d..00000000
--- a/prisma/migrations/20250904040013_slack_integration/migration.sql
+++ /dev/null
@@ -1,28 +0,0 @@
--- CreateTable
-CREATE TABLE "SlackIntegration" (
- "id" TEXT NOT NULL,
- "teamId" TEXT NOT NULL,
- "workspaceId" TEXT NOT NULL,
- "workspaceName" TEXT NOT NULL,
- "workspaceUrl" TEXT NOT NULL,
- "accessToken" TEXT NOT NULL,
- "botUserId" TEXT NOT NULL,
- "botUsername" TEXT NOT NULL,
- "defaultChannel" TEXT,
- "enabledChannels" JSONB NOT NULL,
- "enabled" BOOLEAN NOT NULL DEFAULT true,
- "notificationTypes" JSONB NOT NULL,
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
- "updatedAt" TIMESTAMP(3) NOT NULL,
-
- CONSTRAINT "SlackIntegration_pkey" PRIMARY KEY ("id")
-);
-
--- CreateIndex
-CREATE INDEX "SlackIntegration_teamId_idx" ON "SlackIntegration"("teamId");
-
--- CreateIndex
-CREATE UNIQUE INDEX "SlackIntegration_teamId_key" ON "SlackIntegration"("teamId");
-
--- AddForeignKey
-ALTER TABLE "SlackIntegration" ADD CONSTRAINT "SlackIntegration_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/prisma/migrations/20250913000000_add_integrations/migration.sql b/prisma/migrations/20250913000000_add_integrations/migration.sql
new file mode 100644
index 00000000..302e5b1c
--- /dev/null
+++ b/prisma/migrations/20250913000000_add_integrations/migration.sql
@@ -0,0 +1,57 @@
+-- CreateTable
+CREATE TABLE "InstalledIntegration" (
+ "id" TEXT NOT NULL,
+ "credentials" JSONB,
+ "enabled" BOOLEAN NOT NULL DEFAULT true,
+ "integrationId" TEXT NOT NULL,
+ "userId" TEXT,
+ "teamId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+ "configuration" JSONB,
+
+ CONSTRAINT "InstalledIntegration_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "Integration" (
+ "id" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "slug" TEXT NOT NULL,
+ "description" TEXT,
+ "readme" TEXT,
+ "developer" TEXT NOT NULL,
+ "website" TEXT NOT NULL,
+ "logo" TEXT,
+ "screenshots" JSONB,
+ "verified" BOOLEAN NOT NULL DEFAULT false,
+ "installUrl" TEXT,
+ "category" TEXT,
+ "comingSoon" BOOLEAN NOT NULL DEFAULT false,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "Integration_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "InstalledIntegration_integrationId_idx" ON "InstalledIntegration"("integrationId" ASC);
+
+-- CreateIndex
+CREATE INDEX "InstalledIntegration_teamId_idx" ON "InstalledIntegration"("teamId" ASC);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "InstalledIntegration_teamId_integrationId_key" ON "InstalledIntegration"("teamId" ASC, "integrationId" ASC);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "Integration_slug_key" ON "Integration"("slug" ASC);
+
+-- AddForeignKey
+ALTER TABLE "InstalledIntegration" ADD CONSTRAINT "InstalledIntegration_integrationId_fkey" FOREIGN KEY ("integrationId") REFERENCES "Integration"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "InstalledIntegration" ADD CONSTRAINT "InstalledIntegration_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "InstalledIntegration" ADD CONSTRAINT "InstalledIntegration_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
diff --git a/prisma/schema/conversation.prisma b/prisma/schema/conversation.prisma
index 192d2660..bd415a2a 100644
--- a/prisma/schema/conversation.prisma
+++ b/prisma/schema/conversation.prisma
@@ -149,58 +149,58 @@ model ConversationView {
// Published FAQ items for datarooms
model DataroomFaqItem {
- id String @id @default(cuid())
- title String? // Optional title for the FAQ
- editedQuestion String // Admin-edited version of the question
- originalQuestion String? // Original question from visitor (for reference)
- answer String // The answer content
- description String? // Optional context or description
-
+ id String @id @default(cuid())
+ title String? // Optional title for the FAQ
+ editedQuestion String // Admin-edited version of the question
+ originalQuestion String? // Original question from visitor (for reference)
+ answer String // The answer content
+ description String? // Optional context or description
+
// Relationships
- dataroomId String
- dataroom Dataroom @relation(fields: [dataroomId], references: [id], onDelete: Cascade)
-
- linkId String? // Optional: specific link visibility
- link Link? @relation(fields: [linkId], references: [id], onDelete: SetNull)
-
- dataroomDocumentId String? // Optional: document-specific FAQ
- dataroomDocument DataroomDocument? @relation(fields: [dataroomDocumentId], references: [id], onDelete: SetNull)
-
+ dataroomId String
+ dataroom Dataroom @relation(fields: [dataroomId], references: [id], onDelete: Cascade)
+
+ linkId String? // Optional: specific link visibility
+ link Link? @relation(fields: [linkId], references: [id], onDelete: SetNull)
+
+ dataroomDocumentId String? // Optional: document-specific FAQ
+ dataroomDocument DataroomDocument? @relation(fields: [dataroomDocumentId], references: [id], onDelete: SetNull)
+
// Source conversation and messages (for reference and editing)
- sourceConversationId String? // Original conversation
- sourceConversation Conversation? @relation(fields: [sourceConversationId], references: [id], onDelete: SetNull)
-
- questionMessageId String? // Reference to original question message
- questionMessage Message? @relation(name: "FAQQuestionMessage", fields: [questionMessageId], references: [id], onDelete: SetNull)
-
- answerMessageId String? // Reference to answer message
- answerMessage Message? @relation(name: "FAQAnswerMessage", fields: [answerMessageId], references: [id], onDelete: SetNull)
-
+ sourceConversationId String? // Original conversation
+ sourceConversation Conversation? @relation(fields: [sourceConversationId], references: [id], onDelete: SetNull)
+
+ questionMessageId String? // Reference to original question message
+ questionMessage Message? @relation(name: "FAQQuestionMessage", fields: [questionMessageId], references: [id], onDelete: SetNull)
+
+ answerMessageId String? // Reference to answer message
+ answerMessage Message? @relation(name: "FAQAnswerMessage", fields: [answerMessageId], references: [id], onDelete: SetNull)
+
// Publishing details
- teamId String
- team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
-
- publishedByUserId String
- publishedByUser User @relation(fields: [publishedByUserId], references: [id], onDelete: Cascade)
-
+ teamId String
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+
+ publishedByUserId String
+ publishedByUser User @relation(fields: [publishedByUserId], references: [id], onDelete: Cascade)
+
// Visibility and status
- visibilityMode FaqVisibility @default(PUBLIC_DATAROOM)
- status FaqStatus @default(PUBLISHED)
- isAnonymized Boolean @default(true)
-
+ visibilityMode FaqVisibility @default(PUBLIC_DATAROOM)
+ status FaqStatus @default(PUBLISHED)
+ isAnonymized Boolean @default(true)
+
// Analytics
- viewCount Int @default(0)
-
+ viewCount Int @default(0)
+
// Optional categorization
- tags String[] @default([])
-
+ tags String[] @default([])
+
// Metadata
- documentPageNumber Int? // Optional: specific page reference
- documentVersionNumber Int? // Optional: specific version reference
-
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
-
+ documentPageNumber Int? // Optional: specific page reference
+ documentVersionNumber Int? // Optional: specific version reference
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
@@index([dataroomId])
@@index([linkId])
@@index([dataroomDocumentId])
@@ -214,14 +214,14 @@ model DataroomFaqItem {
// Define FAQ visibility options
enum FaqVisibility {
- PUBLIC_DATAROOM // Visible to all dataroom visitors
- PUBLIC_LINK // Visible only to specific link visitors
- PUBLIC_DOCUMENT // Visible only when viewing specific document
+ PUBLIC_DATAROOM // Visible to all dataroom visitors
+ PUBLIC_LINK // Visible only to specific link visitors
+ PUBLIC_DOCUMENT // Visible only when viewing specific document
}
// Define FAQ status
enum FaqStatus {
- DRAFT // Not yet published
- PUBLISHED // Live and visible to visitors
- ARCHIVED // No longer visible but kept for reference
+ DRAFT // Not yet published
+ PUBLISHED // Live and visible to visitors
+ ARCHIVED // No longer visible but kept for reference
}
diff --git a/prisma/schema/dataroom.prisma b/prisma/schema/dataroom.prisma
index 8d179d2c..ce291e9d 100644
--- a/prisma/schema/dataroom.prisma
+++ b/prisma/schema/dataroom.prisma
@@ -44,15 +44,15 @@ model Dataroom {
}
model DataroomDocument {
- id String @id @default(cuid())
- dataroomId String
- dataroom Dataroom @relation(fields: [dataroomId], references: [id], onDelete: Cascade)
- documentId String
- document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)
- folderId String?
- folder DataroomFolder? @relation(fields: [folderId], references: [id], onDelete: SetNull)
- orderIndex Int?
- hierarchicalIndex String? // Computed field like "1.2.3" for hierarchical display
+ id String @id @default(cuid())
+ dataroomId String
+ dataroom Dataroom @relation(fields: [dataroomId], references: [id], onDelete: Cascade)
+ documentId String
+ document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)
+ folderId String?
+ folder DataroomFolder? @relation(fields: [folderId], references: [id], onDelete: SetNull)
+ orderIndex Int?
+ hierarchicalIndex String? // Computed field like "1.2.3" for hierarchical display
conversations Conversation[]
@@ -70,17 +70,17 @@ model DataroomDocument {
}
model DataroomFolder {
- id String @id @default(cuid())
- name String
- path String // the materialized path to the folder; starts always with "/"
- parentId String?
- documents DataroomDocument[]
- childFolders DataroomFolder[] @relation("SubFolders")
- parentFolder DataroomFolder? @relation("SubFolders", fields: [parentId], references: [id], onDelete: SetNull)
- dataroomId String
- dataroom Dataroom @relation(fields: [dataroomId], references: [id], onDelete: Cascade)
- orderIndex Int?
- hierarchicalIndex String? // Computed field like "1.2" for hierarchical display
+ id String @id @default(cuid())
+ name String
+ path String // the materialized path to the folder; starts always with "/"
+ parentId String?
+ documents DataroomDocument[]
+ childFolders DataroomFolder[] @relation("SubFolders")
+ parentFolder DataroomFolder? @relation("SubFolders", fields: [parentId], references: [id], onDelete: SetNull)
+ dataroomId String
+ dataroom Dataroom @relation(fields: [dataroomId], references: [id], onDelete: Cascade)
+ orderIndex Int?
+ hierarchicalIndex String? // Computed field like "1.2" for hierarchical display
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
diff --git a/prisma/schema/document.prisma b/prisma/schema/document.prisma
index a501c2ac..df36886d 100644
--- a/prisma/schema/document.prisma
+++ b/prisma/schema/document.prisma
@@ -138,4 +138,4 @@ model DocumentUpload {
@@index([teamId])
@@index([dataroomId])
@@index([dataroomDocumentId])
-}
\ No newline at end of file
+}
diff --git a/prisma/schema/integration.prisma b/prisma/schema/integration.prisma
new file mode 100644
index 00000000..066ce15d
--- /dev/null
+++ b/prisma/schema/integration.prisma
@@ -0,0 +1,40 @@
+model Integration {
+ id String @id @default(cuid())
+ name String
+ slug String @unique
+ description String?
+ readme String?
+ developer String
+ website String
+ logo String?
+ screenshots Json?
+ verified Boolean @default(false)
+ installUrl String?
+ category String?
+ comingSoon Boolean @default(false)
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ installedIntegrations InstalledIntegration[]
+}
+
+model InstalledIntegration {
+ id String @id @default(cuid())
+ credentials Json?
+ configuration Json?
+ enabled Boolean @default(true)
+
+ integrationId String
+ integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)
+ userId String? // user who installed the integration
+ user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
+ teamId String // team where the integration was installed
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@unique([teamId, integrationId])
+ @@index([teamId])
+ @@index([integrationId])
+}
diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prisma
index 60b5e8c1..034198b1 100644
--- a/prisma/schema/schema.prisma
+++ b/prisma/schema/schema.prisma
@@ -62,11 +62,12 @@ model User {
// conversation
participatedConversations ConversationParticipant[]
messages Message[]
-
+
// FAQ system
publishedFaqItems DataroomFaqItem[]
-}
+ installedIntegrations InstalledIntegration[]
+}
model Brand {
id String @id @default(cuid())
@@ -272,9 +273,9 @@ model FeedbackResponse {
}
model Agreement {
- id String @id @default(cuid())
- name String // Easily identifiable name for the agreement
- content String // This will store the agreement content (URL or text)
+ id String @id @default(cuid())
+ name String // Easily identifiable name for the agreement
+ content String // This will store the agreement content (URL or text)
contentType String @default("LINK") // "LINK" or "TEXT" - determines how content should be displayed
links Link[]
@@ -433,25 +434,3 @@ model TagItem {
@@index([tagId, documentId])
@@index([tagId, dataroomId])
}
-
-model SlackIntegration {
- id String @id @default(cuid())
- teamId String
- team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
- workspaceId String // Slack workspace ID
- workspaceName String // Slack workspace name
- workspaceUrl String // Slack workspace URL
- accessToken String // Bot token for sending messages
- botUserId String // Bot user ID
- botUsername String // Bot username
- defaultChannel String? // Default channel for notifications
- enabledChannels Json // { "channel_id": { "name": "channel-name", "enabled": true } }
- enabled Boolean @default(true)
- notificationTypes Json // { "document_view": true, "dataroom_access": true, "document_download": true }
-
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
-
- @@unique([teamId])
- @@index([teamId])
-}
diff --git a/prisma/schema/team.prisma b/prisma/schema/team.prisma
index 117e7889..45d991e6 100644
--- a/prisma/schema/team.prisma
+++ b/prisma/schema/team.prisma
@@ -19,10 +19,11 @@ model Team {
restrictedTokens RestrictedToken[]
webhooks Webhook[]
conversations Conversation[]
- dataroomFaqItems DataroomFaqItem[]
+ dataroomFaqItems DataroomFaqItem[]
uploadedDocuments DocumentUpload[]
Tag Tag[]
- slackIntegration SlackIntegration?
+
+ installedIntegrations InstalledIntegration[]
links Link[]
views View[]