Skip to content

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

slack integration

Ashish Viradiya9a90173527c4
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.ts
index 474c0dea..d8128863 100644
--- a/app/api/views-dataroom/route.ts
+++ b/app/api/views-dataroom/route.ts
@@ -659,7 +659,7 @@ export async function POST(request: NextRequest) {
}),
);
- if (link.teamId) {
+ if (link.teamId && !isPreview) {
waitUntil(
(async () => {
try {
@@ -787,7 +787,8 @@ export async function POST(request: NextRequest) {
select: { id: true },
});
console.timeEnd("create-view");
- if (link.teamId) {
+ // Only send Slack notifications for non-preview views
+ if (link.teamId && !isPreview) {
waitUntil(
(async () => {
try {
diff --git a/app/api/views/route.ts b/app/api/views/route.ts
index 416a0605..c9611956 100644
--- a/app/api/views/route.ts
+++ b/app/api/views/route.ts
@@ -637,17 +637,19 @@ export async function POST(request: NextRequest) {
enableNotification: link.enableNotification,
}),
);
- waitUntil(
- notifyDocumentView({
- teamId: link.teamId!,
- documentId,
- linkId,
- viewerEmail: email ?? undefined,
- viewerId: viewer?.id ?? undefined,
- }).catch((error) => {
- console.error("Error sending Slack notification:", error);
- })
- );
+ if (!isPreview) {
+ waitUntil(
+ notifyDocumentView({
+ teamId: link.teamId!,
+ documentId,
+ linkId,
+ viewerEmail: email ?? undefined,
+ viewerId: viewer?.id ?? undefined,
+ }).catch((error) => {
+ console.error("Error sending Slack notification:", error);
+ })
+ );
+ }
}
const returnObject = {
diff --git a/components/emails/slack-integration-notification.tsx b/components/emails/slack-integration-notification.tsx
index 9ac70abf..6e1b6b8a 100644
--- a/components/emails/slack-integration-notification.tsx
+++ b/components/emails/slack-integration-notification.tsx
@@ -42,7 +42,7 @@ export default function SlackIntegrationNotification({
</Text>
<Text className="text-sm leading-6 text-black">
You can now receive notifications about document views, dataroom
- access, downloads, and reactions directly in your Slack channels.
+ access and downloads directly in your Slack channels.
</Text>
<Section className="my-8 text-center">
<Button
diff --git a/components/settings/slack-frequency-settings.tsx b/components/settings/slack-frequency-settings.tsx
deleted file mode 100644
index e6cb049a..00000000
--- a/components/settings/slack-frequency-settings.tsx
+++ /dev/null
@@ -1,322 +0,0 @@
-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,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
-import { Label } from "@/components/ui/label";
-import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-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: SlackIntegration;
- onUpdate: (updatedIntegration: SlackIntegration) => void;
-}
-
-const timezones = getTimezoneOptions();
-
-const timeOptions = Array.from({ length: 24 }, (_, i) => {
- const hour = i.toString().padStart(2, "0");
- return { value: `${hour}:00`, label: `${hour}:00` };
-});
-
-const weekDays = [
- { value: "monday", label: "Monday" },
- { value: "tuesday", label: "Tuesday" },
- { value: "wednesday", label: "Wednesday" },
- { value: "thursday", label: "Thursday" },
- { value: "friday", label: "Friday" },
- { value: "saturday", label: "Saturday" },
- { value: "sunday", label: "Sunday" },
-];
-
-const frequencyOptions: Array<{
- value: NotificationFrequency;
- label: string;
- tooltip: string;
-}> = [
- {
- value: "instant",
- label: "Instantly",
- tooltip:
- "Send notifications immediately when events occur (document views, downloads, reactions, etc.)",
- },
- {
- value: "daily",
- label: "Daily",
- tooltip:
- "Send a summary digest of all events once per day at your chosen time",
- },
- {
- value: "weekly",
- label: "Weekly",
- tooltip:
- "Send a summary digest of all events once per week on your chosen day and time",
- },
-];
-
-export default function SlackFrequencySettings({
- teamId,
- integration,
- onUpdate,
-}: SlackFrequencySettingsProps) {
- const updateIntegration = async (
- updates: Partial<typeof integration>,
- successMessage?: string,
- ) => {
- 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);
- }
- } else {
- const errorData = await response
- .json()
- .catch(() => ({ error: "Unknown error" }));
- throw new Error(
- errorData.error || `Failed to update settings (${response.status})`,
- );
- }
- } catch (error) {
- throw error instanceof Error
- ? error
- : new Error("Failed to update settings");
- }
- };
-
- const updateDailyTime = (dailyTime: string) => {
- toast.promise(updateIntegration({ dailyTime }), {
- loading: "Updating digest time...",
- success: `Digest time updated to ${dailyTime}`,
- error: "Failed to update digest time. Please try again.",
- });
- };
-
- const updateTimezone = (timezone: string) => {
- toast.promise(updateIntegration({ timezone }), {
- loading: "Updating timezone...",
- success: `Timezone updated to ${timezones.find((tz) => tz.value === timezone)?.label || timezone}`,
- error: "Failed to update timezone. Please try again.",
- });
- };
-
- const updateWeeklyDay = (weeklyDay: string) => {
- const dayLabel =
- weekDays.find((day) => day.value === weeklyDay)?.label || weeklyDay;
- toast.promise(updateIntegration({ weeklyDay }), {
- loading: "Updating weekly schedule...",
- success: `Weekly digest scheduled for ${dayLabel}`,
- error: "Failed to update weekly schedule. Please try again.",
- });
- };
-
- const updateFrequency = async (frequency: NotificationFrequency) => {
- const updatePromise = async () => {
- await updateIntegration({ frequency });
- };
-
- toast.promise(updatePromise(), {
- loading: `Updating notification frequency to ${frequency}...`,
- success: `Frequency updated to ${frequency}`,
- error: "Failed to update notification frequency. Please try again.",
- });
- };
-
- return (
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <Clock className="h-5 w-5" />
- Notification Frequency
- </CardTitle>
- <CardDescription>
- Choose how often you want to receive notifications in your Slack
- channels
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-6">
- <RadioGroup
- value={integration.frequency}
- onValueChange={(value) =>
- updateFrequency(value as NotificationFrequency)
- }
- >
- <div className="flex flex-row space-x-6">
- {frequencyOptions.map((option) => (
- <div key={option.value} className="flex items-center space-x-2">
- <RadioGroupItem value={option.value} id={option.value} />
- <div className="flex items-center gap-2">
- <Label htmlFor={option.value} className="text-sm font-medium">
- {option.label}
- </Label>
- <BadgeTooltip
- content={option.tooltip}
- key={`${option.value}_tooltip`}
- >
- <HelpCircle className="h-4 w-4 text-muted-foreground hover:text-foreground" />
- </BadgeTooltip>
- </div>
- </div>
- ))}
- </div>
- </RadioGroup>
-
- {/* Time and Timezone Settings */}
- {(integration.frequency === "daily" ||
- integration.frequency === "weekly") && (
- <>
- <Separator />
- <div className="space-y-4">
- <div>
- <Label className="text-sm font-medium">Digest Schedule</Label>
- <p className="text-sm text-muted-foreground">
- Choose when to receive your {integration.frequency} digest
- notifications
- </p>
- </div>
-
- <div className="flex flex-col gap-4 sm:flex-row sm:items-end">
- {/* Time Selection */}
- <div className="flex-1 space-y-2">
- <Label
- htmlFor="time"
- className="flex items-center gap-2 text-sm font-medium"
- >
- <Clock className="h-4 w-4" />
- Time
- </Label>
- <Select
- value={integration.dailyTime || "10:00"}
- onValueChange={(dailyTime) => updateDailyTime(dailyTime)}
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {timeOptions.map((time) => (
- <SelectItem key={time.value} value={time.value}>
- {time.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
-
- {/* Timezone Selection */}
- <div className="flex-1 space-y-2">
- <Label
- htmlFor="timezone"
- className="flex items-center gap-2 text-sm font-medium"
- >
- <Globe className="h-4 w-4" />
- Timezone
- </Label>
- <Select
- value={integration.timezone || "UTC"}
- onValueChange={(timezone) => updateTimezone(timezone)}
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {timezones.map((tz) => (
- <SelectItem key={tz.value} value={tz.value}>
- {tz.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
-
- {/* Weekly Day Selection (only for weekly) */}
- {integration.frequency === "weekly" && (
- <div className="flex-1 space-y-2">
- <Label htmlFor="weeklyDay" className="text-sm font-medium">
- Day of Week
- </Label>
- <Select
- value={integration.weeklyDay || "monday"}
- onValueChange={(weeklyDay) => updateWeeklyDay(weeklyDay)}
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {weekDays.map((day) => (
- <SelectItem key={day.value} value={day.value}>
- {day.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- )}
- </div>
-
- {/* Preview */}
- <div className="rounded-lg bg-muted p-3">
- <p className="text-sm text-muted-foreground">
- <strong>Preview:</strong> You&apos;ll receive{" "}
- {integration.frequency} digest notifications{" "}
- {integration.frequency === "daily" &&
- `at ${integration.dailyTime || "10:00"} ${timezones.find((tz) => tz.value === integration.timezone)?.label.split(" ")[0] || "UTC"}`}
- {integration.frequency === "weekly" &&
- `every ${weekDays.find((day) => day.value === (integration.weeklyDay || "monday"))?.label} at ${integration.dailyTime || "10:00"} ${timezones.find((tz) => tz.value === integration.timezone)?.label.split(" ")[0] || "UTC"}`}
- </p>
- </div>
- </div>
- </>
- )}
- </CardContent>
- </Card>
- );
-}
\ No newline at end of file
diff --git a/lib/slack/digest-processor.ts b/lib/slack/digest-processor.ts
deleted file mode 100644
index 067453e6..00000000
--- a/lib/slack/digest-processor.ts
+++ /dev/null
@@ -1,291 +0,0 @@
-import prisma from "@/lib/prisma";
-import { SlackClient } from "./client";
-import { createDigestMessage } from "./templates";
-import { SlackEventData } from "./events";
-
-export class SlackDigestProcessor {
- private client: SlackClient;
-
- constructor() {
- this.client = new SlackClient();
- }
-
- private async processTeamDigest(
- teamId: string,
- integrationId: string,
- notifications: any[]
- ): Promise<void> {
- if (!notifications || notifications.length === 0) {
- return;
- }
-
-
- try {
- const integration = await prisma.slackIntegration.findUnique({
- where: { id: integrationId },
- });
-
- if (!integration) {
- throw new Error(`Integration ${integrationId} not found`);
- }
-
- if (!integration.enabled) {
- await this.markNotificationsAsFailed(notifications.map(n => n.id));
- return;
- }
-
- if (!integration.accessToken) {
- throw new Error(`Integration ${integrationId} has no access token`);
- }
-
- const eventCounts = this.countEventsByType(notifications);
-
- if (eventCounts.length === 0) {
- await this.markNotificationsAsProcessed(notifications.map(n => n.id));
- return;
- }
-
- // Create digest message
- const digestMessage = await createDigestMessage(
- eventCounts.map(({ eventData, count }) => ({ eventData, count })),
- teamId
- );
-
- if (!digestMessage) {
- throw new Error(`Failed to create digest message for team ${teamId}`);
- }
-
- // Get channels to send to
- const channels = this.getDigestChannels(integration);
-
- if (channels.length === 0) {
- await this.markNotificationsAsProcessed(notifications.map(n => n.id));
- return;
- }
-
- let sentToChannels = 0;
- let failedChannels = 0;
-
- // Send digest to each channel
- for (const channel of channels) {
- try {
- const slackMessage = {
- ...digestMessage,
- channel: channel.id
- };
-
- await this.client.sendMessage(integration.accessToken, slackMessage);
- sentToChannels++;
- } catch (error) {
- failedChannels++;
- console.error(`[${new Date().toISOString()}] Error sending digest to channel ${channel.id}:`, error);
- }
- }
-
- if (sentToChannels > 0) {
- await this.markNotificationsAsProcessed(notifications.map(n => n.id));
- } else {
- throw new Error(`Failed to send digest to any channels for integration ${integrationId}`);
- }
-
- } catch (error) {
- throw error;
- }
- }
-
-
- private countEventsByType(notifications: any[]): Array<{ eventData: SlackEventData; count: number }> {
- const eventCounts = new Map<string, { eventData: SlackEventData; count: number }>();
-
- for (const notification of notifications) {
- try {
- const eventData = notification.eventData as SlackEventData;
-
- if (!eventData || !eventData.eventType) {
- console.warn(`[${new Date().toISOString()}] Invalid event data for notification ${notification.id}`);
- continue;
- }
-
- const key = `${eventData.eventType}_${eventData.documentId || eventData.dataroomId || 'general'}`;
-
- if (eventCounts.has(key)) {
- eventCounts.get(key)!.count++;
- } else {
- eventCounts.set(key, { eventData, count: 1 });
- }
- } catch (error) {
- console.error(`[${new Date().toISOString()}] Error processing event data for notification ${notification.id}:`, error);
- }
- }
-
- return Array.from(eventCounts.values());
- }
-
- /**
- * Get channels for digest notifications
- */
- private getDigestChannels(integration: any): any[] {
- try {
- if (!integration?.enabledChannels) return [];
-
- const channels = Object.values(integration.enabledChannels)
- .filter((channel: any) => channel && channel.enabled)
- .filter((channel: any) => channel.notificationTypes && channel.notificationTypes.length > 0);
-
- return channels;
- } catch (error) {
- console.error(`[${new Date().toISOString()}] Error getting digest channels for integration ${integration.id}:`, error);
- return [];
- }
- }
-
- /**
- * Mark notifications as processed
- */
- private async markNotificationsAsProcessed(notificationIds: string[]): Promise<void> {
- if (!notificationIds || notificationIds.length === 0) {
- return;
- }
-
- try {
- await prisma.$transaction(async (tx) => {
- await tx.slackNotification.updateMany({
- where: {
- id: {
- in: notificationIds,
- },
- },
- data: {
- status: 'PROCESSED',
- processedAt: new Date(),
- },
- });
- });
- } catch (error) {
- console.error(`[${new Date().toISOString()}] Error marking notifications as processed:`, error);
- throw error;
- }
- }
-
- /**
- * Mark notifications as failed
- */
- private async markNotificationsAsFailed(notificationIds: string[]): Promise<void> {
- if (!notificationIds || notificationIds.length === 0) {
- return;
- }
-
- try {
- await prisma.$transaction(async (tx) => {
- await tx.slackNotification.updateMany({
- where: {
- id: {
- in: notificationIds,
- },
- },
- data: {
- status: 'FAILED',
- processedAt: new Date(),
- },
- });
- });
- } catch (error) {
- console.error(`[${new Date().toISOString()}] Error marking notifications as failed:`, error);
- throw error;
- }
- }
-
- /**
- * Process digest for a specific integration by ID
- */
- async processIntegrationDigestById(integrationId: string): Promise<void> {
- const startTime = new Date();
-
- try {
- // Get the integration with pending notifications
- const integration = await prisma.slackIntegration.findUnique({
- where: { id: integrationId },
- include: {
- team: true,
- },
- });
-
- if (!integration) {
- return;
- }
-
- if (!integration.enabled) {
- return;
- }
-
- if (integration.frequency === 'instant') {
- return;
- }
-
- // Get pending notifications for this integration
- const notifications = await prisma.slackNotification.findMany({
- where: {
- slackIntegrationId: integrationId,
- status: 'PENDING',
- },
- orderBy: {
- createdAt: 'asc',
- },
- });
-
- if (notifications.length === 0) {
- return;
- }
-
- // Process the digest for this integration
- await this.processTeamDigest(
- integration.teamId,
- integration.id,
- notifications
- );
-
- } catch (error) {
- throw error;
- }
- }
-
- /**
- * Clean up old processed notifications
- */
- async cleanupOldNotifications(daysToKeep: number = 30): Promise<void> {
- const startTime = new Date();
- try {
- const cutoffDate = new Date();
- cutoffDate.setDate(cutoffDate.getDate() - daysToKeep);
-
- const result = await prisma.slackNotification.deleteMany({
- where: {
- status: {
- in: ['PROCESSED', 'FAILED'],
- },
- processedAt: {
- lt: cutoffDate,
- },
- },
- });
-
- const endTime = new Date();
- const duration = endTime.getTime() - startTime.getTime();
-
- } catch (error) {
- console.error(`[${new Date().toISOString()}] Error cleaning up old notifications:`, error);
- throw error;
- }
- }
-}
-
-// Global instance
-export const slackDigestProcessor = new SlackDigestProcessor();
-
-export async function processSlackDigests(integrationId: string): Promise<void> {
- await slackDigestProcessor.processIntegrationDigestById(integrationId);
-}
-
-export async function cleanupSlackNotifications(daysToKeep: number = 30): Promise<void> {
- await slackDigestProcessor.cleanupOldNotifications(daysToKeep);
-}
\ No newline at end of file
diff --git a/lib/slack/events.ts b/lib/slack/events.ts
index c0d08678..84da4f85 100644
--- a/lib/slack/events.ts
+++ b/lib/slack/events.ts
@@ -36,11 +36,7 @@ export class SlackEventManager {
return;
}
- if (integration.frequency === 'instant') {
- await this.sendInstantNotification(eventData, integration);
- } else {
- await this.storeForDigest(eventData, integration);
- }
+ await this.sendInstantNotification(eventData, integration);
} catch (error) {
console.error('Error processing Slack event:', error);
@@ -81,25 +77,7 @@ export class SlackEventManager {
}
}
- private async storeForDigest(
- eventData: SlackEventData,
- integration: any
- ): Promise<void> {
- try {
- await prisma.slackNotification.create({
- data: {
- teamId: eventData.teamId,
- slackIntegrationId: integration.id,
- eventType: eventData.eventType,
- eventData: JSON.parse(JSON.stringify(eventData)),
- status: 'PENDING',
- scheduledFor: new Date(),
- },
- });
- } catch (error) {
- console.error('Error storing digest notification:', error);
- }
- }
+
private async getSlackIntegration(teamId: string): Promise<SlackIntegration | null> {
return await prisma.slackIntegration.findFirst({
@@ -143,6 +121,3 @@ export async function notifyDocumentDownload(data: Omit<SlackEventData, 'eventTy
await slackEventManager.processEvent({ ...data, eventType: 'document_download' });
}
-export async function notifyDocumentReaction(data: Omit<SlackEventData, 'eventType'>) {
- await slackEventManager.processEvent({ ...data, eventType: 'document_reaction' });
-}
\ No newline at end of file
diff --git a/lib/slack/schedule-manager.ts b/lib/slack/schedule-manager.ts
deleted file mode 100644
index b1a76684..00000000
--- a/lib/slack/schedule-manager.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-import { schedules } from "@trigger.dev/sdk/v3";
-import { processSlackDigestJob } from "@/lib/trigger/slack-digest";
-import prisma from "@/lib/prisma";
-export class SlackScheduleManager {
- async createOrUpdateSchedule(integration: any): Promise<void> {
- try {
- await this.deleteSchedule(integration.id);
-
- if (integration.frequency === 'instant') {
- await this.cleanupOldNotifications(integration.id);
- return;
- }
-
- const cronPattern = this.generateCronPattern(integration);
- const timezone = integration.timezone || 'UTC';
-
- await schedules.create({
- task: processSlackDigestJob.id,
- cron: cronPattern,
- timezone: timezone,
- externalId: integration.id,
- deduplicationKey: `slack-integration-${integration.id}`,
- });
- } catch (error) {
- console.log(error)
- throw error;
- }
- }
-
- async deleteSchedule(integrationId: string): Promise<void> {
- try {
- const allSchedules = await schedules.list();
- const schedulesList = allSchedules.data || [];
- const integrationSchedule = schedulesList.find(
- (schedule: any) => schedule.externalId === integrationId
- );
-
- if (integrationSchedule) {
- await schedules.del(integrationSchedule.id);
- } else {
- console.log(`No schedule found for integration ${integrationId}`);
- }
-
- } catch (error) {
- console.error(`Error deleting schedule for integration ${integrationId}:`, error);
- }
- }
-
- async cleanupOldNotifications(integrationId: string): Promise<void> {
- try {
- await prisma.slackNotification.deleteMany({
- where: {
- slackIntegrationId: integrationId,
- status: 'PENDING',
- },
- });
- console.log(`Cleaned up old notifications for integration ${integrationId}`);
- } catch (error) {
- console.error(`Error cleaning up old notifications for integration ${integrationId}:`, error);
- }
- }
-
-
- private generateCronPattern(integration: any): string {
- const time = integration.dailyTime || '10:00';
- const [hours, minutes] = time.split(':').map(Number);
-
- if (isNaN(hours) || isNaN(minutes) || hours < 0 || hours > 23 || minutes < 0 || minutes > 59) {
- return `0 10 * * *`;
- }
-
- switch (integration.frequency) {
- case 'daily': {
- return `${minutes} ${hours} * * *`;
- }
-
- case 'weekly': {
- const weeklyDay = integration.weeklyDay || 'monday';
- const dayMap: Record<string, number> = {
- 'sunday': 0, 'monday': 1, 'tuesday': 2, 'wednesday': 3,
- 'thursday': 4, 'friday': 5, 'saturday': 6
- };
- const dayOfWeek = dayMap[weeklyDay.toLowerCase()];
-
- if (dayOfWeek === undefined) {
- console.warn(`Invalid day: ${weeklyDay}, using Monday`);
- return `${minutes} ${hours} * * 1`;
- }
-
- return `${minutes} ${hours} * * ${dayOfWeek}`;
- }
-
- default: {
- return `0 10 * * *`;
- }
- }
- }
-
- async listSchedules(): Promise<any[]> {
- try {
- const allSchedules = await schedules.list();
- const schedulesList = allSchedules.data || [];
- return schedulesList.filter((schedule: any) =>
- schedule.externalId && schedule.task === processSlackDigestJob.id
- );
- } catch (error) {
- console.error('Error listing schedules:', error);
- return [];
- }
- }
-
-
- async cleanupTeamSchedules(teamId: string): Promise<void> {
- try {
- const integrations = await prisma.slackIntegration.findMany({
- where: { teamId },
- select: { id: true },
- });
- for (const integration of integrations) {
- try {
- await this.deleteSchedule(integration.id);
- } catch (error) {
- console.error(`Error deleting schedule for integration ${integration.id}:`, error);
- }
- }
- } catch (error) {
- console.error(`Error cleaning up schedules for team ${teamId}:`, error);
- throw error;
- }
- }
-}
-
-export const slackScheduleManager = new SlackScheduleManager();
\ No newline at end of file
diff --git a/lib/slack/templates.ts b/lib/slack/templates.ts
index 1652db96..c796e2b0 100644
--- a/lib/slack/templates.ts
+++ b/lib/slack/templates.ts
@@ -28,8 +28,7 @@ export async function createSlackMessage(
return await createDataroomAccessMessage(eventData);
case 'document_download':
return await createDocumentDownloadMessage(eventData);
- case 'document_reaction':
- return await createDocumentReactionMessage(eventData);
+
default:
return null;
}
@@ -344,322 +343,14 @@ async function createDocumentDownloadMessage(eventData: SlackEventData): Promise
};
}
-/**
- * Document Reaction Message Template
- */
-async function createDocumentReactionMessage(eventData: SlackEventData): Promise<SlackMessage> {
- const document = eventData.documentId ? await getDocumentInfo(eventData.documentId) : null;
- const link = eventData.linkId ? await getLinkInfo(eventData.linkId) : null;
- const reaction = eventData.metadata?.reaction || 'Unknown';
- // Create viewer mention with email link if available
- const viewerDisplay = eventData.viewerEmail || 'Anonymous';
- const viewerMention = eventData.viewerEmail ? `<mailto:${eventData.viewerEmail}|${viewerDisplay}>` : viewerDisplay;
- // Determine access context
- const accessContext = link?.name ? `via shared link "${link.name}"` : `via shared link "Link ${link?.id.slice(0, 5)}"`;
- return {
- text: `A reaction has been added to document: ${reaction} on ${document?.name || 'Unknown document'} by ${viewerDisplay} ${accessContext}`,
- blocks: [
- {
- type: "header",
- text: {
- type: "plain_text",
- text: "A reaction has been added to document",
- emoji: false
- }
- },
- {
- type: "section",
- fields: [
- {
- type: "mrkdwn",
- text: `*Document:*\n${document?.name || 'Unknown'}`
- },
- {
- type: "mrkdwn",
- text: `*Reaction:*\n${reaction}`
- }
- ]
- },
- {
- type: "section",
- fields: [
- {
- type: "mrkdwn",
- text: `*By:*\n${viewerMention}`
- },
- {
- type: "mrkdwn",
- text: `*Time:*\n${new Date().toLocaleString()}`
- }
- ]
- },
- {
- type: "section",
- fields: [
- {
- type: "mrkdwn",
- text: link?.name
- ? `*Shared Link:*\n${link.name}`
- : `*Access:*\nDirect access`
- }
- ]
- },
- {
- type: "context",
- elements: [
- {
- type: "mrkdwn",
- text: link?.name
- ? `Reaction added via shared link "${link.name}"`
- : `Reaction added 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`
- }
- ]
- }
- ]
- };
-}
-/**
- * Create a digest message for multiple events
- */
-export async function createDigestMessage(
- events: Array<{ eventData: SlackEventData; count: number }>,
- teamId: string,
-): Promise<SlackMessage> {
- const team = await getTeamInfo(teamId);
-
- const activityDetails = await generateActivityDetails(events);
-
- const summaryBlocks = [];
-
- // Header
- summaryBlocks.push({
- type: "header",
- text: {
- type: "plain_text",
- text: `${team?.name || 'Team'} Activity Summary`,
- emoji: false
- }
- });
-
- // Summary stats
- const totalEvents = events.reduce((sum, { count }) => sum + count, 0);
- summaryBlocks.push({
- type: "section",
- text: {
- type: "mrkdwn",
- text: `*${totalEvents} total activities* in this period`
- }
- });
-
- // Document activities
- if (activityDetails.documentActivities.length > 0) {
- const documentText = activityDetails.documentActivities
- .map(activity => {
- const action = getActivityAction(activity.eventType);
- return `• *${activity.documentName}* - ${action} by ${activity.viewerEmail || 'Unknown user'}`;
- })
- .join('\n');
-
- summaryBlocks.push({
- type: "section",
- text: {
- type: "mrkdwn",
- text: `*Document Activities:*\n${documentText}`
- }
- });
- }
- // Dataroom activities
- if (activityDetails.dataroomActivities.length > 0) {
- const dataroomText = activityDetails.dataroomActivities
- .map(activity => {
- return `• *${activity.dataroomName}* - accessed by ${activity.viewerEmail || 'Unknown user'}`;
- })
- .join('\n');
-
- summaryBlocks.push({
- type: "section",
- text: {
- type: "mrkdwn",
- text: `*Dataroom Activities:*\n${dataroomText}`
- }
- });
- }
- // Link activities
- if (activityDetails.linkActivities.length > 0) {
- const linkText = activityDetails.linkActivities
- .map(activity => {
- const action = getActivityAction(activity.eventType);
- return `• *${activity.linkName}* - ${action} by ${activity.viewerEmail || 'Unknown user'}`;
- })
- .join('\n');
-
- summaryBlocks.push({
- type: "section",
- text: {
- type: "mrkdwn",
- text: `*Link Activities:*\n${linkText}`
- }
- });
- }
-
- // Dashboard button
- summaryBlocks.push({
- type: "actions",
- elements: [
- {
- type: "button",
- text: {
- type: "plain_text",
- text: "View Dashboard",
- emoji: false
- },
- style: "primary",
- url: `${process.env.NEXTAUTH_URL}/dashboard`
- }
- ]
- });
-
- return {
- text: `${team?.name || 'Team'} Activity Summary - ${totalEvents} activities`,
- blocks: summaryBlocks
- };
-}
-
-/**
- * Generate detailed activity breakdown from events
- */
-async function generateActivityDetails(
- events: Array<{ eventData: SlackEventData; count: number }>
-): Promise<{
- documentActivities: Array<{
- eventType: string;
- documentName: string;
- viewerEmail?: string;
- }>;
- dataroomActivities: Array<{
- dataroomName: string;
- viewerEmail?: string;
- }>;
- linkActivities: Array<{
- eventType: string;
- linkName: string;
- viewerEmail?: string;
- }>;
-}> {
- const documentActivities: Array<{
- eventType: string;
- documentName: string;
- viewerEmail?: string;
- }> = [];
-
- const dataroomActivities: Array<{
- dataroomName: string;
- viewerEmail?: string;
- }> = [];
-
- const linkActivities: Array<{
- eventType: string;
- linkName: string;
- viewerEmail?: string;
- }> = [];
-
- 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) {
- for (let i = 0; i < count; i++) {
- eventsToProcess.push({ eventData, count: 1 });
-
- if (eventData.documentId) {
- uniqueDocumentIds.add(eventData.documentId);
- } else if (eventData.dataroomId) {
- uniqueDataroomIds.add(eventData.dataroomId);
- } else if (eventData.linkId) {
- 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,
- linkActivities
- };
-}
-/**
- * Get action description for activity type
- */
-function getActivityAction(eventType: string): string {
- switch (eventType) {
- case 'document_view':
- return 'viewed';
- case 'document_download':
- return 'downloaded';
- case 'document_reaction':
- return 'reacted to';
- case 'dataroom_access':
- return 'accessed';
- default:
- return 'interacted with';
- }
-}
// Helper functions
async function getDocumentInfo(documentId: string) {
@@ -679,25 +370,7 @@ 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 {
@@ -723,65 +396,6 @@ 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 {
- return await prisma.user.findUnique({
- where: { id: userId },
- select: {
- id: true,
- name: true,
- email: true,
- },
- });
- } catch (error) {
- console.error('Error fetching user info:', error);
- return null;
- }
-}
-
-async function getTeamInfo(teamId: string) {
- try {
- return await prisma.team.findUnique({
- where: { id: teamId },
- select: {
- id: true,
- name: true,
- },
- });
- } catch (error) {
- console.error('Error fetching team info:', error);
- return null;
- }
-}
async function getLinkInfo(linkId: string) {
try {
@@ -798,23 +412,3 @@ async function getLinkInfo(linkId: string) {
return null;
}
}
-
-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
diff --git a/lib/slack/timezone-utils.ts b/lib/slack/timezone-utils.ts
deleted file mode 100644
index c0e6e115..00000000
--- a/lib/slack/timezone-utils.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-export function getTimezoneOptions() {
- return [
- // UTC
- { value: "UTC", label: "UTC" },
-
- // North America
- { value: "America/New_York", label: "Eastern Time (ET)" },
- { value: "America/Chicago", label: "Central Time (CT)" },
- { value: "America/Denver", label: "Mountain Time (MT)" },
- { value: "America/Los_Angeles", label: "Pacific Time (PT)" },
- { value: "America/Anchorage", label: "Alaska Time (AKT)" },
- { value: "Pacific/Honolulu", label: "Hawaii Time (HST)" },
- { value: "America/Toronto", label: "Eastern Time - Toronto" },
- { value: "America/Vancouver", label: "Pacific Time - Vancouver" },
- { value: "America/Mexico_City", label: "Central Time - Mexico City" },
-
- // Europe
- { value: "Europe/London", label: "Greenwich Mean Time (GMT)" },
- { value: "Europe/Paris", label: "Central European Time (CET)" },
- { value: "Europe/Berlin", label: "Central European Time - Berlin" },
- { value: "Europe/Rome", label: "Central European Time - Rome" },
- { value: "Europe/Madrid", label: "Central European Time - Madrid" },
- { value: "Europe/Amsterdam", label: "Central European Time - Amsterdam" },
- { value: "Europe/Brussels", label: "Central European Time - Brussels" },
- { value: "Europe/Vienna", label: "Central European Time - Vienna" },
- { value: "Europe/Zurich", label: "Central European Time - Zurich" },
- { value: "Europe/Stockholm", label: "Central European Time - Stockholm" },
- { value: "Europe/Oslo", label: "Central European Time - Oslo" },
- { value: "Europe/Copenhagen", label: "Central European Time - Copenhagen" },
- { value: "Europe/Helsinki", label: "Eastern European Time (EET)" },
- { value: "Europe/Athens", label: "Eastern European Time - Athens" },
- { value: "Europe/Bucharest", label: "Eastern European Time - Bucharest" },
- { value: "Europe/Sofia", label: "Eastern European Time - Sofia" },
- { value: "Europe/Warsaw", label: "Central European Time - Warsaw" },
- { value: "Europe/Prague", label: "Central European Time - Prague" },
- { value: "Europe/Budapest", label: "Central European Time - Budapest" },
- { value: "Europe/Dublin", label: "Greenwich Mean Time - Dublin" },
- { value: "Europe/Lisbon", label: "Western European Time (WET)" },
- { value: "Europe/Moscow", label: "Moscow Time (MSK)" },
- { value: "Europe/Kiev", label: "Eastern European Time - Kyiv" },
- { value: "Europe/Istanbul", label: "Turkey Time (TRT)" },
-
- // Asia
- { value: "Asia/Tokyo", label: "Japan Standard Time (JST)" },
- { value: "Asia/Shanghai", label: "China Standard Time (CST)" },
- { value: "Asia/Seoul", label: "Korea Standard Time (KST)" },
- { value: "Asia/Singapore", label: "Singapore Time (SGT)" },
- { value: "Asia/Bangkok", label: "Indochina Time (ICT)" },
- { value: "Asia/Manila", label: "Philippine Time (PHT)" },
- { value: "Asia/Jakarta", label: "Western Indonesian Time (WIB)" },
- { value: "Asia/Kuala_Lumpur", label: "Malaysia Time (MYT)" },
- { value: "Asia/Hong_Kong", label: "Hong Kong Time (HKT)" },
- { value: "Asia/Taipei", label: "Taipei Time (TST)" },
- { value: "Asia/Calcutta", label: "India Standard Time (IST)" },
- { value: "Asia/Karachi", label: "Pakistan Standard Time (PKT)" },
- { value: "Asia/Dhaka", label: "Bangladesh Standard Time (BST)" },
- { value: "Asia/Kabul", label: "Afghanistan Time (AFT)" },
- { value: "Asia/Tehran", label: "Iran Standard Time (IRST)" },
- { value: "Asia/Dubai", label: "Gulf Standard Time (GST)" },
- { value: "Asia/Riyadh", label: "Arabia Standard Time (AST)" },
- { value: "Asia/Jerusalem", label: "Israel Standard Time (IST)" },
- { value: "Asia/Baghdad", label: "Arabia Standard Time - Baghdad" },
- { value: "Asia/Kuwait", label: "Arabia Standard Time - Kuwait" },
- { value: "Asia/Qatar", label: "Arabia Standard Time - Qatar" },
- { value: "Asia/Bahrain", label: "Arabia Standard Time - Bahrain" },
- { value: "Asia/Muscat", label: "Gulf Standard Time - Muscat" },
- { value: "Asia/Yerevan", label: "Armenia Time (AMT)" },
- { value: "Asia/Tbilisi", label: "Georgia Time (GET)" },
- { value: "Asia/Baku", label: "Azerbaijan Time (AZT)" },
- { value: "Asia/Tashkent", label: "Uzbekistan Time (UZT)" },
- { value: "Asia/Almaty", label: "Kazakhstan Time (ALMT)" },
- { value: "Asia/Novosibirsk", label: "Novosibirsk Time (NOVT)" },
- { value: "Asia/Krasnoyarsk", label: "Krasnoyarsk Time (KRAT)" },
- { value: "Asia/Irkutsk", label: "Irkutsk Time (IRKT)" },
- { value: "Asia/Yakutsk", label: "Yakutsk Time (YAKT)" },
- { value: "Asia/Vladivostok", label: "Vladivostok Time (VLAT)" },
- { value: "Asia/Magadan", label: "Magadan Time (MAGT)" },
- { value: "Asia/Kamchatka", label: "Kamchatka Time (PETT)" },
- { value: "Asia/Anadyr", label: "Anadyr Time (ANAT)" },
-
- // Australia & Oceania
- { value: "Australia/Sydney", label: "Australian Eastern Time (AET)" },
- { value: "Australia/Melbourne", label: "Australian Eastern Time - Melbourne" },
- { value: "Australia/Brisbane", label: "Australian Eastern Time - Brisbane" },
- { value: "Australia/Adelaide", label: "Australian Central Time (ACT)" },
- { value: "Australia/Perth", label: "Australian Western Time (AWT)" },
- { value: "Australia/Darwin", label: "Australian Central Time - Darwin" },
- { value: "Australia/Hobart", label: "Australian Eastern Time - Hobart" },
- { value: "Pacific/Auckland", label: "New Zealand Standard Time (NZST)" },
- { value: "Pacific/Fiji", label: "Fiji Time (FJT)" },
- { value: "Pacific/Guam", label: "Chamorro Standard Time (ChST)" },
- { value: "Pacific/Saipan", label: "Chamorro Standard Time - Saipan" },
- { value: "Pacific/Port_Moresby", label: "Papua New Guinea Time (PGT)" },
- { value: "Pacific/Noumea", label: "New Caledonia Time (NCT)" },
- { value: "Pacific/Tahiti", label: "Tahiti Time (TAHT)" },
-
- // South America
- { value: "America/Sao_Paulo", label: "Brasília Time (BRT)" },
- { value: "America/Buenos_Aires", label: "Argentina Time (ART)" },
- { value: "America/Santiago", label: "Chile Time (CLT)" },
- { value: "America/Lima", label: "Peru Time (PET)" },
- { value: "America/Bogota", label: "Colombia Time (COT)" },
- { value: "America/Caracas", label: "Venezuela Time (VET)" },
- { value: "America/La_Paz", label: "Bolivia Time (BOT)" },
- { value: "America/Asuncion", label: "Paraguay Time (PYT)" },
- { value: "America/Montevideo", label: "Uruguay Time (UYT)" },
- { value: "America/Cayenne", label: "French Guiana Time (GFT)" },
-
- // Africa
- { value: "Africa/Cairo", label: "Eastern European Time - Cairo" },
- { value: "Africa/Johannesburg", label: "South Africa Standard Time (SAST)" },
- { value: "Africa/Lagos", label: "West Africa Time (WAT)" },
- { value: "Africa/Nairobi", label: "East Africa Time (EAT)" },
- { value: "Africa/Casablanca", label: "Western European Time - Casablanca" },
- { value: "Africa/Algiers", label: "Central European Time - Algiers" },
- { value: "Africa/Tunis", label: "Central European Time - Tunis" },
- { value: "Africa/Tripoli", label: "Eastern European Time - Tripoli" },
- { value: "Africa/Khartoum", label: "Central Africa Time (CAT)" },
- { value: "Africa/Addis_Ababa", label: "East Africa Time - Addis Ababa" },
- { value: "Africa/Dar_es_Salaam", label: "East Africa Time - Dar es Salaam" },
- { value: "Africa/Harare", label: "Central Africa Time - Harare" },
- { value: "Africa/Luanda", label: "West Africa Time - Luanda" },
- { value: "Africa/Kinshasa", label: "West Africa Time - Kinshasa" },
- { value: "Africa/Lubumbashi", label: "Central Africa Time - Lubumbashi" },
- { value: "Africa/Lusaka", label: "Central Africa Time - Lusaka" },
- { value: "Africa/Maputo", label: "Central Africa Time - Maputo" },
- { value: "Africa/Windhoek", label: "Central Africa Time - Windhoek" },
- { value: "Africa/Gaborone", label: "Central Africa Time - Gaborone" },
- { value: "Africa/Maseru", label: "South Africa Standard Time - Maseru" },
- { value: "Africa/Mbabane", label: "South Africa Standard Time - Mbabane" },
- { value: "Africa/Libreville", label: "West Africa Time - Libreville" },
- { value: "Africa/Douala", label: "West Africa Time - Douala" },
- { value: "Africa/Brazzaville", label: "West Africa Time - Brazzaville" },
- { value: "Africa/Bangui", label: "West Africa Time - Bangui" },
- { value: "Africa/Ndjamena", label: "West Africa Time - Ndjamena" },
- { value: "Africa/Malabo", label: "West Africa Time - Malabo" },
- { value: "Africa/Sao_Tome", label: "Sao Tome Time (GMT)" },
- { value: "Africa/Accra", label: "Greenwich Mean Time - Accra" },
- { value: "Africa/Dakar", label: "Greenwich Mean Time - Dakar" },
- { value: "Africa/Bamako", label: "Greenwich Mean Time - Bamako" },
- { value: "Africa/Conakry", label: "Greenwich Mean Time - Conakry" },
- { value: "Africa/Freetown", label: "Greenwich Mean Time - Freetown" },
- { value: "Africa/Monrovia", label: "Greenwich Mean Time - Monrovia" },
- { value: "Africa/Banjul", label: "Greenwich Mean Time - Banjul" },
- { value: "Africa/Bissau", label: "Greenwich Mean Time - Bissau" },
- { value: "Africa/Nouakchott", label: "Greenwich Mean Time - Nouakchott" },
- { value: "Africa/Ouagadougou", label: "Greenwich Mean Time - Ouagadougou" },
- { value: "Africa/Porto-Novo", label: "West Africa Time - Porto-Novo" },
- { value: "Africa/Lome", label: "Greenwich Mean Time - Lome" },
- { value: "Africa/Niamey", label: "West Africa Time - Niamey" },
- { value: "Africa/El_Aaiun", label: "Western European Time - El Aaiun" },
- { value: "Africa/Ceuta", label: "Central European Time - Ceuta" },
- { value: "Africa/Asmera", label: "East Africa Time - Asmara" },
- { value: "Africa/Djibouti", label: "East Africa Time - Djibouti" },
- { value: "Africa/Mogadishu", label: "East Africa Time - Mogadishu" },
- { value: "Africa/Kampala", label: "East Africa Time - Kampala" },
- { value: "Africa/Kigali", label: "Central Africa Time - Kigali" },
- { value: "Africa/Bujumbura", label: "Central Africa Time - Bujumbura" },
- { value: "Africa/Blantyre", label: "Central Africa Time - Blantyre" },
- { value: "Africa/Juba", label: "East Africa Time - Juba" },
- ];
-}
\ No newline at end of file
diff --git a/lib/slack/types.ts b/lib/slack/types.ts
index 1c208f62..c2309f44 100644
--- a/lib/slack/types.ts
+++ b/lib/slack/types.ts
@@ -54,7 +54,6 @@ export interface SlackNotificationConfig {
document_view: boolean;
dataroom_access: boolean;
document_download: boolean;
- document_reaction: boolean;
}
export interface SlackChannelConfig {
@@ -64,15 +63,9 @@ export interface SlackChannelConfig {
notificationTypes: string[];
}
-export type NotificationFrequency = 'instant' | 'daily' | 'weekly';
-
export interface SlackIntegrationConfig {
enabled: boolean;
notificationTypes: SlackNotificationConfig;
- frequency: NotificationFrequency;
- timezone: string;
- dailyTime?: string; // "10:00"
- weeklyDay?: string; // "monday"
defaultChannel?: string;
enabledChannels: Record<string, SlackChannelConfig>;
}
\ No newline at end of file
diff --git a/lib/trigger/slack-digest.ts b/lib/trigger/slack-digest.ts
deleted file mode 100644
index 49ab3d46..00000000
--- a/lib/trigger/slack-digest.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { schedules } from "@trigger.dev/sdk/v3";
-import { processSlackDigests, cleanupSlackNotifications } from "@/lib/slack/digest-processor";
-
-
-export const processSlackDigestJob = schedules.task({
- id: "process-slack-digest",
- run: async (payload) => {
- if (!payload.externalId) {
- throw new Error("externalId (integrationId) is required");
- }
- await processSlackDigests(payload.externalId);
- },
-});
-
-
-export const cleanupSlackNotificationsJob = schedules.task({
- id: "cleanup-slack-notifications",
- cron: "0 2 * * *",
- run: async (payload) => {
- await cleanupSlackNotifications(30);
- },
-});
\ No newline at end of file
diff --git a/lib/types/slack.ts b/lib/types/slack.ts
index dadc531e..90efefc2 100644
--- a/lib/types/slack.ts
+++ b/lib/types/slack.ts
@@ -24,12 +24,7 @@ export interface SlackIntegration {
document_view: boolean;
dataroom_access: boolean;
document_download: boolean;
- document_reaction: boolean;
};
- frequency: "instant" | "daily" | "weekly";
- timezone: string;
- dailyTime?: string;
- weeklyDay?: string;
defaultChannel?: string;
enabledChannels: Record<string, SlackChannelConfig>;
createdAt: string;
@@ -40,10 +35,6 @@ export interface SlackIntegration {
export interface UpdateSlackIntegrationRequest {
enabled?: boolean;
notificationTypes?: SlackIntegration['notificationTypes'];
- frequency?: SlackIntegration['frequency'];
- timezone?: string;
- dailyTime?: string;
- weeklyDay?: string;
defaultChannel?: string;
enabledChannels?: Record<string, SlackChannelConfig>;
}
diff --git a/pages/api/debug/slack-schedules.ts b/pages/api/debug/slack-schedules.ts
deleted file mode 100644
index c7361a4b..00000000
--- a/pages/api/debug/slack-schedules.ts
+++ /dev/null
@@ -1,133 +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 { slackScheduleManager } from '@/lib/slack/schedule-manager';
-
-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' });
- }
-
- if (req.method !== 'GET' && req.method !== 'DELETE') {
- return res.status(405).json({ error: 'Method not allowed' });
- }
-
- const userId = (session.user as CustomUser).id;
-
- if (req.method === 'GET') {
- try {
- const allSchedules = await slackScheduleManager.listSchedules();
-
- const schedulesWithTeamInfo = await Promise.all(
- allSchedules.map(async (schedule) => {
- try {
- const integration = await prisma.slackIntegration.findUnique({
- where: { id: schedule.externalId },
- include: {
- team: {
- include: {
- users: {
- where: { userId },
- select: { role: true }
- }
- }
- }
- }
- });
-
- return {
- scheduleId: schedule.id,
- externalId: schedule.externalId,
- cron: schedule.generator.expression,
- timezone: schedule.timezone,
- active: schedule.active,
- team: integration?.team ? {
- id: integration.team.id,
- name: integration.team.name,
- hasAccess: integration.team.users.length > 0
- } : null,
- integration: integration ? {
- id: integration.id,
- enabled: integration.enabled,
- frequency: integration.frequency,
- workspaceName: integration.workspaceName
- } : null,
- isOrphaned: !integration
- };
- } catch (error) {
- return {
- scheduleId: schedule.id,
- externalId: schedule.externalId,
- cron: schedule.generator.expression,
- timezone: schedule.timezone,
- active: schedule.active,
- team: null,
- integration: null,
- isOrphaned: true,
- error: 'Failed to fetch integration details'
- };
- }
- })
- );
-
- return res.status(200).json({
- schedules: schedulesWithTeamInfo,
- summary: {
- total: schedulesWithTeamInfo.length,
- active: schedulesWithTeamInfo.filter(s => s.active).length,
- orphaned: schedulesWithTeamInfo.filter(s => s.isOrphaned).length,
- accessible: schedulesWithTeamInfo.filter(s => s.team?.hasAccess).length
- }
- });
- } catch (error) {
- console.error('Error fetching schedules:', error);
- return res.status(500).json({ error: 'Failed to fetch schedules' });
- }
- }
-
- if (req.method === 'DELETE') {
- try {
- const allSchedules = await slackScheduleManager.listSchedules();
- const orphanedSchedules = [];
-
- for (const schedule of allSchedules) {
- try {
- const integration = await prisma.slackIntegration.findUnique({
- where: { id: schedule.externalId }
- });
-
- if (!integration) {
- orphanedSchedules.push(schedule);
- }
- } catch (error) {
- orphanedSchedules.push(schedule);
- }
- }
-
- const deletedSchedules = [];
- for (const schedule of orphanedSchedules) {
- try {
- await slackScheduleManager.deleteSchedule(schedule.externalId);
- deletedSchedules.push(schedule.id);
- } catch (error) {
- console.error(`Failed to delete orphaned schedule ${schedule.id}:`, error);
- }
- }
-
- return res.status(200).json({
- message: `Cleaned up ${deletedSchedules.length} orphaned schedules`,
- deletedSchedules,
- totalOrphaned: orphanedSchedules.length
- });
- } catch (error) {
- console.error('Error cleaning up orphaned schedules:', error);
- return res.status(500).json({ error: 'Failed to clean up orphaned schedules' });
- }
- }
-}
\ No newline at end of file
diff --git a/pages/api/debug/trigger-digest.ts b/pages/api/debug/trigger-digest.ts
deleted file mode 100644
index d91b2050..00000000
--- a/pages/api/debug/trigger-digest.ts
+++ /dev/null
@@ -1,107 +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 { processSlackDigests } from '@/lib/slack/digest-processor';
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse
-) {
- if (req.method !== 'POST') {
- return res.status(405).json({ error: 'Method not allowed' });
- }
-
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- return res.status(401).json({ error: 'Unauthorized' });
- }
-
- 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 team
- const userTeam = await prisma.userTeam.findUnique({
- where: {
- userId_teamId: {
- userId,
- teamId,
- },
- },
- });
-
- if (!userTeam) {
- return res.status(403).json({ error: 'Access denied' });
- }
-
-
- const integration = await prisma.slackIntegration.findUnique({
- where: { teamId },
- });
-
- if (!integration) {
- return res.status(404).json({ error: 'Slack integration not found' });
- }
-
- const pendingBefore = await prisma.slackNotification.count({
- where: {
- slackIntegrationId: integration.id,
- status: 'PENDING',
- },
- });
-
- await processSlackDigests(integration.id);
-
- const pendingAfter = await prisma.slackNotification.count({
- where: {
- slackIntegrationId: integration.id,
- status: 'PENDING',
- },
- });
-
- // Get processed notifications
- const processedNotifications = await prisma.slackNotification.findMany({
- where: {
- slackIntegrationId: integration.id,
- status: {
- in: ['PROCESSED', 'FAILED'],
- },
- processedAt: {
- gte: new Date(Date.now() - 5 * 60 * 1000), // Last 5 minutes
- },
- },
- orderBy: {
- processedAt: 'desc',
- },
- });
-
- return res.status(200).json({
- success: true,
- integrationId: integration.id,
- pendingBefore,
- pendingAfter,
- processedCount: pendingBefore - pendingAfter,
- processedNotifications: processedNotifications.map(n => ({
- id: n.id,
- eventType: n.eventType,
- status: n.status,
- processedAt: n.processedAt,
- errorMessage: n.errorMessage,
- })),
- message: `Digest processing completed. Processed ${pendingBefore - pendingAfter} notifications.`
- });
-
- } catch (error) {
- console.error('Manual trigger error:', error);
- return res.status(500).json({
- error: 'Internal server error',
- details: error instanceof Error ? error.message : String(error)
- });
- }
-}
\ No newline at end of file
diff --git a/pages/api/record_reaction.ts b/pages/api/record_reaction.ts
index 744b5a0e..c35820ef 100644
--- a/pages/api/record_reaction.ts
+++ b/pages/api/record_reaction.ts
@@ -1,7 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
import prisma from "@/lib/prisma";
-import { notifyDocumentReaction } from "@/lib/slack/events";
export default async function handle(
req: NextApiRequest,
@@ -47,24 +46,7 @@ export default async function handle(
return;
}
- if (reaction.view.teamId) {
- try {
- await notifyDocumentReaction({
- teamId: reaction.view.teamId,
- documentId: reaction.view.documentId ?? undefined,
- dataroomId: reaction.view.dataroomId ?? undefined,
- linkId: reaction.view.linkId ?? undefined,
- viewerEmail: reaction.view.viewerEmail ?? undefined,
- viewerId: reaction.view.viewerId ?? undefined,
- metadata: {
- reaction: type,
- pageNumber: pageNumber,
- },
- });
- } catch (error) {
- console.error("Error sending Slack notification:", error);
- }
- }
+
res.status(200).json({ message: "Reaction recorded" });
return;
diff --git a/pages/api/slack/oauth/callback.ts b/pages/api/slack/oauth/callback.ts
index 77d3a6b0..9daf1b46 100644
--- a/pages/api/slack/oauth/callback.ts
+++ b/pages/api/slack/oauth/callback.ts
@@ -4,7 +4,7 @@ import { authOptions } from '@/pages/api/auth/[...nextauth]';
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';
import { sendSlackIntegrationNotification } from '@/lib/emails/send-slack-integration-notification';
@@ -96,12 +96,8 @@ export default async function handler(
document_view: true,
dataroom_access: true,
document_download: true,
- document_reaction: true,
},
enabled: true,
- frequency: 'instant',
- timezone: 'UTC',
- dailyTime: '10:00',
},
});
@@ -155,22 +151,11 @@ 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.');
- }
-
return res.redirect(`/settings/slack?${redirectParams.toString()}`);
} catch (error) {
diff --git a/pages/api/teams/[teamId]/index.ts b/pages/api/teams/[teamId]/index.ts
index 70647611..b87ed1dd 100644
--- a/pages/api/teams/[teamId]/index.ts
+++ b/pages/api/teams/[teamId]/index.ts
@@ -10,7 +10,7 @@ import { errorhandler } from "@/lib/errorHandler";
import { deleteFiles } from "@/lib/files/delete-team-files-server";
import prisma from "@/lib/prisma";
import { redis } from "@/lib/redis";
-import { slackScheduleManager } from "@/lib/slack/schedule-manager";
+
import { CustomUser } from "@/lib/types";
import { unsubscribe } from "@/lib/unsend";
@@ -229,9 +229,7 @@ export default async function handle(
}),
// delete team branding from redis
redis.del(`brand:logo:${teamId}`),
- slackScheduleManager.cleanupTeamSchedules(teamId).catch((error) => {
- console.error('Error cleaning up Slack schedules for team:', error);
- }),
+
// delete team
prisma.team.delete({
where: {
diff --git a/pages/api/teams/[teamId]/slack/index.ts b/pages/api/teams/[teamId]/slack/index.ts
index cdf2c28a..6f979964 100644
--- a/pages/api/teams/[teamId]/slack/index.ts
+++ b/pages/api/teams/[teamId]/slack/index.ts
@@ -3,7 +3,7 @@ import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/pages/api/auth/[...nextauth]';
import { CustomUser } from '@/lib/types';
import prisma from '@/lib/prisma';
-import { slackScheduleManager } from '@/lib/slack/schedule-manager';
+
export default async function handler(
req: NextApiRequest,
@@ -59,10 +59,6 @@ async function handleGet(
botUsername: true,
enabled: true,
notificationTypes: true,
- frequency: true,
- timezone: true,
- dailyTime: true,
- weeklyDay: true,
defaultChannel: true,
enabledChannels: true,
createdAt: true,
@@ -90,10 +86,6 @@ async function handleUpdate(
const {
enabled,
notificationTypes,
- frequency,
- timezone,
- dailyTime,
- weeklyDay,
defaultChannel,
enabledChannels,
} = req.body;
@@ -114,10 +106,6 @@ async function handleUpdate(
if (enabled !== undefined) updateData.enabled = enabled;
if (notificationTypes) updateData.notificationTypes = notificationTypes;
- if (frequency) updateData.frequency = frequency;
- if (timezone) updateData.timezone = timezone;
- if (dailyTime !== undefined) updateData.dailyTime = dailyTime;
- if (weeklyDay !== undefined) updateData.weeklyDay = weeklyDay;
if (defaultChannel !== undefined) updateData.defaultChannel = defaultChannel;
if (enabledChannels) updateData.enabledChannels = enabledChannels;
@@ -137,10 +125,6 @@ async function handleUpdate(
botUsername: true,
enabled: true,
notificationTypes: true,
- frequency: true,
- timezone: true,
- dailyTime: true,
- weeklyDay: true,
defaultChannel: true,
enabledChannels: true,
createdAt: true,
@@ -148,19 +132,7 @@ async function handleUpdate(
},
});
- const scheduleNeedsUpdate =
- frequency !== undefined ||
- timezone !== undefined ||
- dailyTime !== undefined ||
- weeklyDay !== undefined;
-
- if (scheduleNeedsUpdate) {
- try {
- await slackScheduleManager.createOrUpdateSchedule(updatedIntegration);
- } catch (scheduleError) {
- console.error('Error updating schedule for integration:', scheduleError);
- }
- }
+
return res.status(200).json(updatedIntegration);
} catch (error) {
@@ -183,16 +155,6 @@ async function handleDelete(
return res.status(404).json({ error: 'Slack integration not found' });
}
- try {
- await slackScheduleManager.deleteSchedule(integration.id);
- } catch (scheduleError) {
- console.error('Error deleting schedule for integration:', scheduleError);
- }
-
- await prisma.slackNotification.deleteMany({
- where: { slackIntegrationId: integration.id },
- });
-
await prisma.slackIntegration.delete({
where: { teamId },
});
diff --git a/pages/settings/slack.tsx b/pages/settings/slack.tsx
index dcb225a0..a7c21f57 100644
--- a/pages/settings/slack.tsx
+++ b/pages/settings/slack.tsx
@@ -17,7 +17,6 @@ import {
import AppLayout from "@/components/layouts/app";
import { SettingsHeader } from "@/components/settings/settings-header";
-import SlackFrequencySettings from "@/components/settings/slack-frequency-settings";
import SlackSettingsSkeleton from "@/components/settings/slack-settings-skeleton";
import { SlackIcon } from "@/components/shared/icons/slack-icon";
import { Alert, AlertDescription } from "@/components/ui/alert";
@@ -193,7 +192,6 @@ export default function SlackSettings() {
"document_view",
"dataroom_access",
"document_download",
- "document_reaction",
],
} as SlackChannelConfig;
}
@@ -348,13 +346,6 @@ export default function SlackSettings() {
<SettingsHeader />
<div>
- {integrationError && (
- <Alert className="mb-4">
- <XCircleIcon className="h-4 w-4" />
- <AlertDescription>{integrationError.message}</AlertDescription>
- </Alert>
- )}
-
{loadingIntegration ? (
<SlackSettingsSkeleton />
) : (
@@ -463,7 +454,7 @@ export default function SlackSettings() {
<Label className="flex items-center gap-2 text-sm font-medium">
Slack channel(s) *
<BadgeTooltip
- content="Get notifications in Slack based on frequency settings when someone views, downloads, or interacts with your documents and datarooms"
+ content="Get instant notifications in Slack when someone views, downloads, or interacts with your documents and datarooms"
key="channel_tooltip"
>
<CircleHelpIcon className="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" />
@@ -531,11 +522,6 @@ export default function SlackSettings() {
</div>
</CardContent>
</Card>
- <SlackFrequencySettings
- teamId={teamId!}
- integration={integration!}
- onUpdate={handleIntegrationUpdate}
- />
</div>
)}
</>