Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
improvement
Ashish Viradiyab70dabd641ee
diff --git a/components/settings/slack-channel-modal.tsx b/components/settings/slack-channel-modal.tsxindex 65d0b28d..90ad4ddf 100644--- a/components/settings/slack-channel-modal.tsx+++ b/components/settings/slack-channel-modal.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useState } from "react";+import { useCallback, useEffect, useState } from "react";import { Hash, Loader2 } from "lucide-react";import { toast } from "sonner";@@ -61,14 +61,8 @@ export default function SlackChannelModal({const [loading, setLoading] = useState(false);const [saving, setSaving] = useState(false);- // Fetch channels when modal opens- useEffect(() => {- if (open) {- fetchChannels();- }- }, [open, teamId]);-- const fetchChannels = async () => {+ // Memoize fetchChannels to prevent stale closures+ const fetchChannels = useCallback(async () => {setLoading(true);try {const response = await fetch(`/api/teams/${teamId}/slack/channels`);@@ -83,7 +77,13 @@ export default function SlackChannelModal({} finally {setLoading(false);}- };+ }, [teamId]);++ useEffect(() => {+ if (open) {+ fetchChannels();+ }+ }, [open, fetchChannels]);const handleChannelToggle = (channelId: string, channelName: string) => {setSelectedChannels((prev) => {@@ -239,4 +239,4 @@ export default function SlackChannelModal({</DialogContent></Dialog>);-}+}\ No newline at end of filediff --git a/components/settings/slack-frequency-settings.tsx b/components/settings/slack-frequency-settings.tsxindex 080e081b..1731a53a 100644--- a/components/settings/slack-frequency-settings.tsx+++ b/components/settings/slack-frequency-settings.tsx@@ -2,6 +2,7 @@ import { Clock, Globe, HelpCircle } from "lucide-react";import { toast } from "sonner";import { getTimezoneOptions } from "@/lib/slack/timezone-utils";+import { NotificationFrequency, SlackChannelConfig } from "@/lib/slack/types";import {Card,@@ -23,17 +24,34 @@ import { Separator } from "@/components/ui/separator";import { BadgeTooltip } from "../ui/tooltip";+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;+ document_reaction: boolean;+ };+ frequency: NotificationFrequency;+ timezone: string;+ dailyTime?: string;+ weeklyDay?: string;+ defaultChannel?: string;+ enabledChannels: Record<string, SlackChannelConfig>;+ createdAt: string;+ updatedAt: string;+}+interface SlackFrequencySettingsProps {teamId: string;- integration: {- id: string;- frequency: "instant" | "daily" | "weekly";- timezone: string;- dailyTime?: string;- weeklyDay?: string;- enabledChannels: Record<string, any>;- };- onUpdate: (updatedIntegration: any) => void;+ integration: SlackIntegration;+ onUpdate: (updatedIntegration: SlackIntegration) => void;}const timezones = getTimezoneOptions();@@ -53,7 +71,11 @@ const weekDays = [{ value: "sunday", label: "Sunday" },];-const frequencyOptions = [+const frequencyOptions: Array<{+ value: NotificationFrequency;+ label: string;+ tooltip: string;+}> = [{value: "instant",label: "Instantly",@@ -83,20 +105,31 @@ export default function SlackFrequencySettings({updates: Partial<typeof integration>,successMessage?: string,) => {- const response = await fetch(`/api/teams/${teamId}/slack`, {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ ...integration, ...updates }),- });+ try {+ const response = await fetch(`/api/teams/${teamId}/slack`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ...integration, ...updates }),+ });- if (response.ok) {- const updatedIntegration = await response.json();- onUpdate(updatedIntegration);- if (successMessage) {- toast.success(successMessage);+ if (response.ok) {+ const updatedIntegration = await response.json();+ onUpdate(updatedIntegration);+ if (successMessage) {+ toast.success(successMessage);+ }+ } else {+ const errorData = await response+ .json()+ .catch(() => ({ error: "Unknown error" }));+ throw new Error(+ errorData.error || `Failed to update settings (${response.status})`,+ );}- } else {- throw new Error("Failed to update settings");+ } catch (error) {+ throw error instanceof Error+ ? error+ : new Error("Failed to update settings");}};@@ -126,29 +159,32 @@ export default function SlackFrequencySettings({});};- const updateFrequency = async (frequency: "instant" | "daily" | "weekly") => {+ const updateFrequency = async (frequency: NotificationFrequency) => {const updatePromise = async () => {await updateIntegration({ frequency });if (frequency === "daily" || frequency === "weekly") {- const updatedChannels = { ...integration.enabledChannels };- let channelsUpdated = false;+ const updatedChannels = Object.keys(integration.enabledChannels).reduce(+ (acc, channelId) => {+ const channel = integration.enabledChannels[channelId];+ if (channel && !channel.notificationTypes.includes("digest")) {+ acc[channelId] = {+ ...channel,+ notificationTypes: [...channel.notificationTypes, "digest"],+ };+ } else {+ acc[channelId] = channel;+ }+ return acc;+ },+ {} as Record<string, SlackChannelConfig>,+ );- Object.keys(updatedChannels).forEach((channelId) => {- if (- updatedChannels[channelId] &&- !updatedChannels[channelId].notificationTypes.includes("digest")- ) {- updatedChannels[channelId] = {- ...updatedChannels[channelId],- notificationTypes: [- ...updatedChannels[channelId].notificationTypes,- "digest",- ],- };- channelsUpdated = true;- }- });+ const channelsUpdated = Object.keys(updatedChannels).some(+ (channelId) =>+ updatedChannels[channelId] !==+ integration.enabledChannels[channelId],+ );if (channelsUpdated) {await updateIntegration({ enabledChannels: updatedChannels });@@ -189,7 +225,7 @@ export default function SlackFrequencySettings({<RadioGroupvalue={integration.frequency}onValueChange={(value) =>- updateFrequency(value as "instant" | "daily" | "weekly")+ updateFrequency(value as NotificationFrequency)}><div className="flex flex-row space-x-6">@@ -325,4 +361,4 @@ export default function SlackFrequencySettings({</CardContent></Card>);-}+}\ No newline at end of filediff --git a/components/upload-zone.tsx b/components/upload-zone.tsxindex 95d50a0e..72515212 100644--- a/components/upload-zone.tsx+++ b/components/upload-zone.tsx@@ -101,8 +101,6 @@ export default function UploadZone({? limits?.documents - limits?.usage?.documents: 0;- const uploadProgress = useRef<number[]>([]);-const fileSizeLimits = useMemo(() =>getFileSizeLimits({@@ -231,18 +229,19 @@ export default function UploadZone({Math.round((bytesUploaded / bytesTotal) * 100),99,);- setUploads((prevUploads) =>- prevUploads.map((upload) =>+ setUploads((prevUploads) => {+ const updatedUploads = prevUploads.map((upload) =>upload.uploadId === newUploads[index].uploadId? { ...upload, progress }: upload,- ),- );+ );+ const currentUpload = updatedUploads.find(+ (upload) => upload.uploadId === newUploads[index].uploadId,+ );- const _progress = uploadProgress.current.reduce(- (acc, progress) => acc + progress,- 0,- );+ onUploadProgress(index, progress, currentUpload?.documentId);+ return updatedUploads;+ });},onError: (error) => {setUploads((prev) =>diff --git a/lib/slack/client.ts b/lib/slack/client.tsindex 682483d0..e4394e00 100644--- a/lib/slack/client.ts+++ b/lib/slack/client.ts@@ -1,4 +1,5 @@import { SlackOAuthResponse, SlackChannel, SlackMessage, SlackWorkspaceInfo } from './types';+import { decryptSlackToken } from '@/lib/utils';export class SlackClient {private clientId: string;@@ -15,6 +16,10 @@ export class SlackClient {}}+ private decryptToken(accessToken: string): string {+ return decryptSlackToken(accessToken);+ }+/*** Get OAuth URL for Slack app installation*/@@ -26,15 +31,8 @@ export class SlackClient {state: state,});- // Point at the correct OAuth authorization endpoint:const oauthUrl = `${this.oauthUrl}?${params.toString()}`;- // Debug logging- console.log('SlackClient: Generated OAuth URL:', oauthUrl);- console.log('SlackClient: Client ID:', this.clientId);- console.log('SlackClient: Redirect URI:', redirectUri);- console.log('SlackClient: State:', state);-return oauthUrl;}@@ -72,9 +70,10 @@ export class SlackClient {* 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 ${accessToken}`,+ 'Authorization': `Bearer ${decryptedToken}`,'Content-Type': 'application/json',},});@@ -101,9 +100,10 @@ export class SlackClient {* 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 ${accessToken}`,+ 'Authorization': `Bearer ${decryptedToken}`,'Content-Type': 'application/json',},});@@ -129,9 +129,10 @@ export class SlackClient {*/async getChannels(accessToken: string): Promise<SlackChannel[]> {try {+ const decryptedToken = this.decryptToken(accessToken);const response = await fetch(`${this.baseUrl}/conversations.list?types=public_channel,private_channel`, {headers: {- 'Authorization': `Bearer ${accessToken}`,+ 'Authorization': `Bearer ${decryptedToken}`,'Content-Type': 'application/json',},});@@ -155,7 +156,6 @@ export class SlackClient {}));} catch (error) {console.error('SlackClient.getChannels error:', error);- console.error('Access token (first 10 chars):', accessToken ? accessToken.substring(0, 10) + '...' : 'undefined');throw error;}}@@ -164,10 +164,11 @@ export class SlackClient {* 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 ${accessToken}`,+ 'Authorization': `Bearer ${decryptedToken}`,'Content-Type': 'application/json',},body: JSON.stringify(message),diff --git a/lib/slack/digest-processor.ts b/lib/slack/digest-processor.tsindex 723cf488..4ceac039 100644--- a/lib/slack/digest-processor.ts+++ b/lib/slack/digest-processor.ts@@ -148,16 +148,18 @@ export class SlackDigestProcessor {}try {- await prisma.slackNotification.updateMany({- where: {- id: {- in: notificationIds,+ await prisma.$transaction(async (tx) => {+ await tx.slackNotification.updateMany({+ where: {+ id: {+ in: notificationIds,+ },},- },- data: {- status: 'PROCESSED',- processedAt: new Date(),- },+ data: {+ status: 'PROCESSED',+ processedAt: new Date(),+ },+ });});} catch (error) {console.error(`[${new Date().toISOString()}] Error marking notifications as processed:`, error);@@ -174,16 +176,18 @@ export class SlackDigestProcessor {}try {- await prisma.slackNotification.updateMany({- where: {- id: {- in: notificationIds,+ await prisma.$transaction(async (tx) => {+ await tx.slackNotification.updateMany({+ where: {+ id: {+ in: notificationIds,+ },},- },- data: {- status: 'FAILED',- processedAt: new Date(),- },+ data: {+ status: 'FAILED',+ processedAt: new Date(),+ },+ });});} catch (error) {console.error(`[${new Date().toISOString()}] Error marking notifications as failed:`, error);diff --git a/lib/slack/events.ts b/lib/slack/events.tsindex 74b3146a..c0d08678 100644--- a/lib/slack/events.ts+++ b/lib/slack/events.ts@@ -1,3 +1,4 @@+import { SlackIntegration } from "@prisma/client";import { SlackClient } from "./client";import { createSlackMessage } from "./templates";import prisma from "@/lib/prisma";@@ -27,19 +28,14 @@ export class SlackEventManager {const integration = await this.getSlackIntegration(eventData.teamId);if (!integration || !integration.enabled) {- console.log("No integration found or integration disabled for team:", eventData.teamId);return;}- console.log("Integration found:", { enabled: integration.enabled, frequency: integration.frequency });if (!this.isEventTypeEnabled(eventData.eventType, integration)) {- console.log("Event type not enabled:", eventData.eventType, "Integration notification types:", integration.notificationTypes);return;}- console.log("Event type enabled, processing...");-if (integration.frequency === 'instant') {await this.sendInstantNotification(eventData, integration);} else {@@ -56,27 +52,25 @@ export class SlackEventManager {*/private async sendInstantNotification(eventData: SlackEventData,- integration: any+ integration: SlackIntegration): Promise<void> {try {const channels = await this.getNotificationChannels(eventData, integration);if (channels.length === 0) {- console.log(`No enabled channels found for event type ${eventData.eventType}`);return;}for (const channel of channels) {try {- const message = await createSlackMessage(eventData, channel);+ const message = await createSlackMessage(eventData);if (message) {const slackMessage = {...message,channel: channel.id};await this.client.sendMessage(integration.accessToken, slackMessage);- console.log(`Sent instant notification to channel ${channel.name || channel.id}`);}} catch (channelError) {console.error(`Error sending to channel ${channel.name || channel.id}:`, channelError);@@ -107,15 +101,13 @@ export class SlackEventManager {}}- private async getSlackIntegration(teamId: string) {+ private async getSlackIntegration(teamId: string): Promise<SlackIntegration | null> {return await prisma.slackIntegration.findFirst({where: { teamId, enabled: true },});}- /**- * Check if event type is enabled in integration config- */+private isEventTypeEnabled(eventType: string,integration: any@@ -124,19 +116,15 @@ export class SlackEventManager {return notificationTypes[eventType] || false;}- /**- * Get channels to send notifications to- */private async getNotificationChannels(eventData: SlackEventData,- integration: any+ 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));}-}diff --git a/lib/slack/schedule-manager.ts b/lib/slack/schedule-manager.tsindex c3b55445..b1a76684 100644--- a/lib/slack/schedule-manager.ts+++ b/lib/slack/schedule-manager.ts@@ -1,11 +1,7 @@import { schedules } from "@trigger.dev/sdk/v3";import { processSlackDigestJob } from "@/lib/trigger/slack-digest";import prisma from "@/lib/prisma";-export class SlackScheduleManager {- /**- * Create or update a schedule for a Slack integration- */async createOrUpdateSchedule(integration: any): Promise<void> {try {await this.deleteSchedule(integration.id);@@ -18,12 +14,6 @@ export class SlackScheduleManager {const cronPattern = this.generateCronPattern(integration);const timezone = integration.timezone || 'UTC';- console.log(`Creating schedule for integration ${integration.id}:`, {- cron: cronPattern,- timezone: timezone,- frequency: integration.frequency- });-await schedules.create({task: processSlackDigestJob.id,cron: cronPattern,@@ -31,18 +21,12 @@ export class SlackScheduleManager {externalId: integration.id,deduplicationKey: `slack-integration-${integration.id}`,});-- console.log(`Successfully created schedule for integration ${integration.id}`);-} catch (error) {- console.error(`Error creating schedule for integration ${integration.id}:`, error);+ console.log(error)throw error;}}- /**- * Delete a schedule for a Slack integration- */async deleteSchedule(integrationId: string): Promise<void> {try {const allSchedules = await schedules.list();@@ -53,7 +37,6 @@ export class SlackScheduleManager {if (integrationSchedule) {await schedules.del(integrationSchedule.id);- console.log(`Deleted schedule for integration ${integrationId}`);} else {console.log(`No schedule found for integration ${integrationId}`);}@@ -63,9 +46,6 @@ export class SlackScheduleManager {}}- /**- * Clean up old notifications when switching from instant to digest- */async cleanupOldNotifications(integrationId: string): Promise<void> {try {await prisma.slackNotification.deleteMany({@@ -86,15 +66,15 @@ export class SlackScheduleManager {const [hours, minutes] = time.split(':').map(Number);if (isNaN(hours) || isNaN(minutes) || hours < 0 || hours > 23 || minutes < 0 || minutes > 59) {- console.warn(`Invalid time format: ${time}, using default 10:00`);return `0 10 * * *`;}switch (integration.frequency) {- case 'daily':+ case 'daily': {return `${minutes} ${hours} * * *`;+ }- case 'weekly':+ case 'weekly': {const weeklyDay = integration.weeklyDay || 'monday';const dayMap: Record<string, number> = {'sunday': 0, 'monday': 1, 'tuesday': 2, 'wednesday': 3,@@ -108,9 +88,11 @@ export class SlackScheduleManager {}return `${minutes} ${hours} * * ${dayOfWeek}`;+ }- default:+ default: {return `0 10 * * *`;+ }}}@@ -138,7 +120,7 @@ export class SlackScheduleManager {try {await this.deleteSchedule(integration.id);} catch (error) {- console.error(`Error deleting schedule for integration ${integration.id}:`, error)+ console.error(`Error deleting schedule for integration ${integration.id}:`, error);}}} catch (error) {diff --git a/lib/slack/templates.ts b/lib/slack/templates.tsindex c44c8110..1652db96 100644--- a/lib/slack/templates.ts+++ b/lib/slack/templates.ts@@ -1,4 +1,5 @@import { SlackEventData } from "./events";+import prisma from "@/lib/prisma";export interface SlackChannelConfig {id: string;@@ -18,7 +19,6 @@ export interface SlackMessage {export async function createSlackMessage(eventData: SlackEventData,- channel: SlackChannelConfig): Promise<SlackMessage | null> {try {switch (eventData.eventType) {@@ -448,8 +448,7 @@ export async function createDigestMessage(): Promise<SlackMessage> {const team = await getTeamInfo(teamId);- // Get detailed activity breakdown- const activityDetails = await generateActivityDetails(events, teamId);+ const activityDetails = await generateActivityDetails(events);const summaryBlocks = [];@@ -553,8 +552,7 @@ export async function createDigestMessage(* Generate detailed activity breakdown from events*/async function generateActivityDetails(- events: Array<{ eventData: SlackEventData; count: number }>,- teamId: string+ events: Array<{ eventData: SlackEventData; count: number }>): Promise<{documentActivities: Array<{eventType: string;@@ -588,34 +586,56 @@ async function generateActivityDetails(viewerEmail?: string;}> = [];- // Process each event+ const uniqueDocumentIds = new Set<string>();+ const uniqueDataroomIds = new Set<string>();+ const uniqueLinkIds = new Set<string>();++ const eventsToProcess: Array<{ eventData: SlackEventData; count: number }> = [];+for (const { eventData, count } of events) {- // Handle multiple occurrences of the same eventfor (let i = 0; i < count; i++) {+ eventsToProcess.push({ eventData, count: 1 });+if (eventData.documentId) {- const doc = await getDocumentInfo(eventData.documentId);- documentActivities.push({- eventType: eventData.eventType,- documentName: doc?.name || 'Unknown Document',- viewerEmail: eventData.viewerEmail- });+ uniqueDocumentIds.add(eventData.documentId);} else if (eventData.dataroomId) {- const dataroom = await getDataroomInfo(eventData.dataroomId);- dataroomActivities.push({- dataroomName: dataroom?.name || 'Unknown Dataroom',- viewerEmail: eventData.viewerEmail- });+ uniqueDataroomIds.add(eventData.dataroomId);} else if (eventData.linkId) {- const link = await getLinkInfo(eventData.linkId);- linkActivities.push({- eventType: eventData.eventType,- linkName: link?.name || 'Unknown Link',- viewerEmail: eventData.viewerEmail- });+ uniqueLinkIds.add(eventData.linkId);}}}+ const [documents, datarooms, links] = await Promise.all([+ uniqueDocumentIds.size > 0 ? batchGetDocumentInfo(Array.from(uniqueDocumentIds)) : Promise.resolve(new Map()),+ uniqueDataroomIds.size > 0 ? batchGetDataroomInfo(Array.from(uniqueDataroomIds)) : Promise.resolve(new Map()),+ uniqueLinkIds.size > 0 ? batchGetLinkInfo(Array.from(uniqueLinkIds)) : Promise.resolve(new Map()),+ ]);++ for (const { eventData } of eventsToProcess) {+ if (eventData.documentId) {+ const doc = documents.get(eventData.documentId);+ documentActivities.push({+ eventType: eventData.eventType,+ documentName: doc?.name || 'Unknown Document',+ viewerEmail: eventData.viewerEmail+ });+ } else if (eventData.dataroomId) {+ const dataroom = datarooms.get(eventData.dataroomId);+ dataroomActivities.push({+ dataroomName: dataroom?.name || 'Unknown Dataroom',+ viewerEmail: eventData.viewerEmail+ });+ } else if (eventData.linkId) {+ const link = links.get(eventData.linkId);+ linkActivities.push({+ eventType: eventData.eventType,+ linkName: link?.name || `Link ${link?.id.slice(0, 5)}`,+ viewerEmail: eventData.viewerEmail+ });+ }+ }+return {documentActivities,dataroomActivities,@@ -644,7 +664,6 @@ function getActivityAction(eventType: string): string {// Helper functionsasync function getDocumentInfo(documentId: string) {try {- const prisma = (await import("@/lib/prisma")).default;return await prisma.document.findUnique({where: { id: documentId },select: {@@ -660,9 +679,28 @@ async function getDocumentInfo(documentId: string) {}}+async function batchGetDocumentInfo(documentIds: string[]) {+ try {+ const documents = await prisma.document.findMany({+ where: { id: { in: documentIds } },+ select: {+ id: true,+ name: true,+ description: true,+ type: true,+ },+ });+ const documentMap = new Map();+ documents.forEach(doc => documentMap.set(doc.id, doc));+ return documentMap;+ } catch (error) {+ console.error('Error fetching batch document info:', error);+ return new Map();+ }+}+async function getDataroomInfo(dataroomId: string) {try {- const prisma = (await import("@/lib/prisma")).default;return await prisma.dataroom.findUnique({where: { id: dataroomId },select: {@@ -685,9 +723,37 @@ async function getDataroomInfo(dataroomId: string) {}}+async function batchGetDataroomInfo(dataroomIds: string[]) {+ try {+ const datarooms = await prisma.dataroom.findMany({+ where: { id: { in: dataroomIds } },+ select: {+ id: true,+ name: true,+ description: true,+ _count: {+ select: {+ documents: true,+ },+ },+ },+ });+ const dataroomMap = new Map();+ datarooms.forEach(dataroom => {+ dataroomMap.set(dataroom.id, {+ ...dataroom,+ documentCount: dataroom._count.documents,+ });+ });+ return dataroomMap;+ } catch (error) {+ console.error('Error fetching batch dataroom info:', error);+ return new Map();+ }+}+async function getUserInfo(userId: string) {try {- const prisma = (await import("@/lib/prisma")).default;return await prisma.user.findUnique({where: { id: userId },select: {@@ -704,7 +770,6 @@ async function getUserInfo(userId: string) {async function getTeamInfo(teamId: string) {try {- const prisma = (await import("@/lib/prisma")).default;return await prisma.team.findUnique({where: { id: teamId },select: {@@ -720,7 +785,6 @@ async function getTeamInfo(teamId: string) {async function getLinkInfo(linkId: string) {try {- const prisma = (await import("@/lib/prisma")).default;return await prisma.link.findUnique({where: { id: linkId },select: {@@ -735,12 +799,22 @@ async function getLinkInfo(linkId: string) {}}-function getEventDisplayName(eventType: string): string {- switch (eventType) {- case 'document_view': return 'Document Views';- case 'dataroom_access': return 'Dataroom Access';- case 'document_download': return 'Document Downloads';- case 'document_reaction': return 'Document Reactions';- default: return 'Unknown Events';+async function batchGetLinkInfo(linkIds: string[]) {+ try {+ const links = await prisma.link.findMany({+ where: { id: { in: linkIds } },+ select: {+ id: true,+ name: true,+ linkType: true,+ },+ });++ const linkMap = new Map();+ links.forEach(link => linkMap.set(link.id, link));+ return linkMap;+ } catch (error) {+ console.error('Error fetching batch link info:', error);+ return new Map();}-}\ No newline at end of file+}\ No newline at end of filediff --git a/lib/utils.ts b/lib/utils.tsindex a94c6212..8a774b0c 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -580,6 +580,61 @@ 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/debug/trigger-digest.ts b/pages/api/debug/trigger-digest.tsindex 81e3d918..d91b2050 100644--- a/pages/api/debug/trigger-digest.ts+++ b/pages/api/debug/trigger-digest.ts@@ -21,6 +21,10 @@ export default async function handler(const userId = (session.user as CustomUser).id;const { teamId } = req.query as { teamId: string };+ if (!teamId || typeof teamId !== 'string') {+ return res.status(400).json({ error: 'Invalid or missing teamId parameter' });+ }+try {// Verify user has access to teamconst userTeam = await prisma.userTeam.findUnique({@@ -52,9 +56,6 @@ export default async function handler(},});- console.log(`[DEBUG] Manually triggering digest for integration ${integration.id}`);- console.log(`[DEBUG] Pending notifications before: ${pendingBefore}`);-await processSlackDigests(integration.id);const pendingAfter = await prisma.slackNotification.count({diff --git a/pages/api/slack/oauth/callback.ts b/pages/api/slack/oauth/callback.tsindex 01b28582..e71accf3 100644--- a/pages/api/slack/oauth/callback.ts+++ b/pages/api/slack/oauth/callback.ts@@ -5,6 +5,7 @@ import { slackClient } from '@/lib/slack/client';import { CustomUser } from '@/lib/types';import prisma from '@/lib/prisma';import { slackScheduleManager } from '@/lib/slack/schedule-manager';+import { encryptSlackToken } from '@/lib/utils';export default async function handler(req: NextApiRequest,@@ -19,7 +20,6 @@ export default async function handler(if (!session) {return res.status(401).json({ error: 'Unauthorized' });}- console.log('req.query', req.query)const { code, state, error } = req.query as { code: string; state: string; error?: string };const userId = (session.user as CustomUser).id;@@ -87,7 +87,7 @@ export default async function handler(workspaceId: workspaceInfo.id,workspaceName: workspaceInfo.name,workspaceUrl: workspaceInfo.url,- accessToken: oauthResponse.access_token,+ accessToken: encryptSlackToken(oauthResponse.access_token),botUserId: botInfo.id,botUsername: botInfo.name,enabledChannels: {},@@ -104,14 +104,23 @@ export default async function handler(},});+ let scheduleWarning = false;try {await slackScheduleManager.createOrUpdateSchedule(integration);} catch (scheduleError) {console.error('Error creating schedule for new integration:', scheduleError);+ scheduleWarning = true;+ }+ const redirectParams = new URLSearchParams({+ success: 'true',+ integrationId: integration.id,+ });++ if (scheduleWarning) {+ redirectParams.append('warning', 'Schedule creation failed.');}- // Redirect back to settings with success- return res.redirect(`/settings/slack?success=true&integrationId=${integration.id}`);+ return res.redirect(`/settings/slack?${redirectParams.toString()}`);} catch (error) {console.error('Slack OAuth callback error:', error);diff --git a/pages/api/teams/[teamId]/index.ts b/pages/api/teams/[teamId]/index.tsindex 5363e158..70647611 100644--- a/pages/api/teams/[teamId]/index.ts+++ b/pages/api/teams/[teamId]/index.ts@@ -158,17 +158,11 @@ export default async function handle(},});- await prisma.slackIntegration.findUnique({- where: { teamId },- select: { id: true },- });-let files: string[] = [];let hasBlobDocuments = false;if (documentsUsingBlob) {hasBlobDocuments = true;- // flatten documents and extract file fieldsfiles = documentsUsingBlob.flatMap((doc) => [doc.file,...doc.versions.flatMap((version) => [diff --git a/pages/settings/slack.tsx b/pages/settings/slack.tsxindex 353c9db8..025530fa 100644--- a/pages/settings/slack.tsx+++ b/pages/settings/slack.tsx@@ -56,53 +56,91 @@ export default function SlackSettings() {const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;const [error, setError] = useState<string | null>(null);- const [reactError, setReactError] = useState<string | null>(null);-const [integration, setIntegration] = useState<SlackIntegration | null>(null);const [loading, setLoading] = useState(true);const [connecting, setConnecting] = useState(false);const [showChannelModal, setShowChannelModal] = useState(false);+ const handleIntegrationUpdate = (updatedIntegration: SlackIntegration) => {+ setIntegration(updatedIntegration);+ };+useEffect(() => {+ let timeoutId: NodeJS.Timeout | null = null;+if (router.query.success) {toast.success("Slack integration connected successfully!");- setTimeout(() => {++ if (router.query.warning) {+ toast.warning(`Warning: ${router.query.warning}`);+ }++ timeoutId = setTimeout(() => {router.replace("/settings/slack", undefined, { shallow: true });}, 100);- }- if (router.query.error) {+ } else if (router.query.error) {toast.error(`Failed to connect Slack: ${router.query.error}`);- setTimeout(() => {+ timeoutId = setTimeout(() => {router.replace("/settings/slack", undefined, { shallow: true });}, 100);}++ return () => {+ if (timeoutId) clearTimeout(timeoutId);+ };}, [router.query]);- useEffect(() => {- if (!teamId) return;+ const fetchIntegration = async (controller: AbortController) => {+ try {+ setError(null);+ setLoading(true);- const fetchIntegration = async () => {- try {+ const response = await fetch(`/api/teams/${teamId}/slack`, {+ signal: controller.signal,+ });++ if (response.ok) {+ const data = await response.json();+ setIntegration(data);setError(null);- const response = await fetch(`/api/teams/${teamId}/slack`);- if (response.ok) {- const data = await response.json();- setIntegration(data);- } else if (response.status === 404) {- setIntegration(null);- } else {- const errorData = await response.json();- setError(errorData.error || "Failed to fetch integration");+ } else if (response.status === 404) {+ setIntegration(null);+ setError(null);+ } else {+ let errorData: { error?: string } = {};+ try {+ errorData = await response.json();+ } catch {+ console.log("error");}- } catch (error) {+ setError(errorData.error || "Failed to fetch integration");+ setIntegration(null);+ }+ } catch (error: unknown) {+ if (error instanceof DOMException && error.name === "AbortError") {+ } else {console.error("Error fetching Slack integration:", error);setError("Failed to fetch integration");- } finally {- setLoading(false);+ setIntegration(null);}- };+ } finally {+ setLoading(false);+ }+ };++ useEffect(() => {+ if (!teamId) {+ setIntegration(null);+ setLoading(false);+ setError(null);+ return;+ }- fetchIntegration();+ const controller = new AbortController();++ fetchIntegration(controller);++ return () => controller.abort();}, [teamId]);const handleConnect = async () => {@@ -182,20 +220,6 @@ export default function SlackSettings() {);};- if (reactError) {- return (- <AppLayout>- <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">- <SettingsHeader />- <Alert className="mb-4">- <XCircleIcon className="h-4 w-4" />- <AlertDescription>React Error: {reactError}</AlertDescription>- </Alert>- </main>- </AppLayout>- );- }-return (<AppLayout><main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">@@ -411,7 +435,7 @@ export default function SlackSettings() {<SlackFrequencySettingsteamId={teamId!}integration={integration!}- onUpdate={setIntegration}+ onUpdate={handleIntegrationUpdate}/><SlackChannelModalopen={showChannelModal}