Skip to content

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

Feat: Slack native integration

Ashish Viradiya2ec19e7f78e4
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.ts
index 247b9791..474c0dea 100644
--- a/app/api/views-dataroom/route.ts
+++ b/app/api/views-dataroom/route.ts
@@ -28,6 +28,7 @@ import { generateOTP } from "@/lib/utils/generate-otp";
import { LOCALHOST_IP } from "@/lib/utils/geo";
import { checkGlobalBlockList } from "@/lib/utils/global-block-list";
import { validateEmail } from "@/lib/utils/validate-email";
+import { notifyDataroomAccess, notifyDocumentView } from "@/lib/slack/events";
export async function POST(request: NextRequest) {
try {
@@ -603,28 +604,28 @@ export async function POST(request: NextRequest) {
...(link.enableAgreement &&
link.agreementId &&
hasConfirmedAgreement && {
- agreementResponse: {
- create: {
- agreementId: link.agreementId,
- },
+ agreementResponse: {
+ create: {
+ agreementId: link.agreementId,
},
- }),
+ },
+ }),
...(link.audienceType === LinkAudienceType.GROUP &&
link.groupId && {
- groupId: link.groupId,
- }),
+ groupId: link.groupId,
+ }),
...(customFields &&
link.customFields.length > 0 && {
- customFieldResponse: {
- create: {
- data: link.customFields.map((field) => ({
- identifier: field.identifier,
- label: field.label,
- response: customFields[field.identifier] || "",
- })),
- },
+ customFieldResponse: {
+ create: {
+ data: link.customFields.map((field) => ({
+ identifier: field.identifier,
+ label: field.label,
+ response: customFields[field.identifier] || "",
+ })),
},
- }),
+ },
+ }),
};
// ** DATAROOM_VIEW **
@@ -657,6 +658,24 @@ export async function POST(request: NextRequest) {
enableNotification: link.enableNotification,
}),
);
+
+ if (link.teamId) {
+ waitUntil(
+ (async () => {
+ try {
+ await notifyDataroomAccess({
+ teamId: link.teamId!,
+ dataroomId,
+ linkId,
+ viewerEmail: verifiedEmail ?? email,
+ viewerId: viewer?.id,
+ });
+ } catch (error) {
+ console.error("Error sending Slack notification:", error);
+ }
+ })()
+ );
+ }
}
const dataroomViewId =
@@ -768,6 +787,24 @@ export async function POST(request: NextRequest) {
select: { id: true },
});
console.timeEnd("create-view");
+ if (link.teamId) {
+ waitUntil(
+ (async () => {
+ try {
+ await notifyDocumentView({
+ teamId: link.teamId!,
+ documentId,
+ dataroomId,
+ linkId,
+ viewerEmail: verifiedEmail ?? email,
+ viewerId: viewer?.id,
+ });
+ } catch (error) {
+ console.error("Error sending Slack notification:", error);
+ }
+ })()
+ );
+ }
}
// if document version has pages, then return pages
diff --git a/app/api/views/route.ts b/app/api/views/route.ts
index 931f8bb2..416a0605 100644
--- a/app/api/views/route.ts
+++ b/app/api/views/route.ts
@@ -18,6 +18,7 @@ import prisma from "@/lib/prisma";
import { ratelimit } from "@/lib/redis";
import { parseSheet } from "@/lib/sheet";
import { recordLinkView } from "@/lib/tracking/record-link-view";
+import { notifyDocumentView } from "@/lib/slack/events";
import { CustomUser, WatermarkConfigSchema } from "@/lib/types";
import { checkPassword, decryptEncrpytedPassword, log } from "@/lib/utils";
import { isEmailMatched } from "@/lib/utils/email-domain";
@@ -636,6 +637,17 @@ 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);
+ })
+ );
}
const returnObject = {
diff --git a/components/layouts/breadcrumb.tsx b/components/layouts/breadcrumb.tsx
index 64ffe34f..e49e3199 100644
--- a/components/layouts/breadcrumb.tsx
+++ b/components/layouts/breadcrumb.tsx
@@ -220,6 +220,8 @@ const SettingsBreadcrumb = () => {
return "API Tokens";
case "/settings/webhooks":
return "Webhooks";
+ case "/settings/slack":
+ return "Slack";
case "/settings/incoming-webhooks":
return "Incoming Webhooks";
case "/settings/branding":
diff --git a/components/settings/settings-header.tsx b/components/settings/settings-header.tsx
index d857833f..9a5e7881 100644
--- a/components/settings/settings-header.tsx
+++ b/components/settings/settings-header.tsx
@@ -67,6 +67,11 @@ export function SettingsHeader() {
href: `/settings/webhooks`,
segment: "webhooks",
},
+ {
+ label: "Slack",
+ href: `/settings/slack`,
+ segment: "slack",
+ },
{
label: "Tokens",
href: `/settings/tokens`,
diff --git a/components/settings/slack-channel-modal.tsx b/components/settings/slack-channel-modal.tsx
new file mode 100644
index 00000000..65d0b28d
--- /dev/null
+++ b/components/settings/slack-channel-modal.tsx
@@ -0,0 +1,242 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+import { Hash, Loader2 } from "lucide-react";
+import { toast } from "sonner";
+
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+
+interface SlackChannel {
+ id: string;
+ name: string;
+ is_private: boolean;
+ is_archived: boolean;
+ is_member?: boolean;
+}
+
+interface SlackChannelConfig {
+ id: string;
+ name: string;
+ enabled: boolean;
+ notificationTypes: string[];
+}
+
+interface SlackChannelModalProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ teamId: string;
+ onChannelsUpdate: (channels: Record<string, SlackChannelConfig>) => void;
+ currentChannels?: Record<string, SlackChannelConfig>;
+}
+
+const NOTIFICATION_TYPES = [
+ { id: "document_view", label: "Document Views", emoji: "📄" },
+ { id: "dataroom_access", label: "Dataroom Access", emoji: "🏢" },
+ { id: "document_download", label: "Document Downloads", emoji: "⬇️" },
+ { id: "document_reaction", label: "Document Reactions", emoji: "👍" },
+ { id: "digest", label: "Digest Summaries", emoji: "📊" },
+];
+
+export default function SlackChannelModal({
+ open,
+ onOpenChange,
+ teamId,
+ onChannelsUpdate,
+ currentChannels = {},
+}: SlackChannelModalProps) {
+ const [channels, setChannels] = useState<SlackChannel[]>([]);
+ const [selectedChannels, setSelectedChannels] =
+ useState<Record<string, SlackChannelConfig>>(currentChannels);
+ const [loading, setLoading] = useState(false);
+ const [saving, setSaving] = useState(false);
+
+ // Fetch channels when modal opens
+ useEffect(() => {
+ if (open) {
+ fetchChannels();
+ }
+ }, [open, teamId]);
+
+ const fetchChannels = async () => {
+ setLoading(true);
+ try {
+ const response = await fetch(`/api/teams/${teamId}/slack/channels`);
+ if (!response.ok) {
+ throw new Error("Failed to fetch channels");
+ }
+ const data = await response.json();
+ setChannels(data.channels || []);
+ } catch (error) {
+ console.error("Error fetching channels:", error);
+ toast.error("Failed to fetch Slack channels");
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleChannelToggle = (channelId: string, channelName: string) => {
+ setSelectedChannels((prev) => {
+ const newChannels = { ...prev };
+ if (newChannels[channelId]) {
+ delete newChannels[channelId];
+ } else {
+ newChannels[channelId] = {
+ id: channelId,
+ name: channelName,
+ enabled: true,
+ notificationTypes: ["document_view", "dataroom_access"],
+ };
+ }
+ return newChannels;
+ });
+ };
+
+ const handleNotificationTypeToggle = (
+ channelId: string,
+ notificationType: string,
+ ) => {
+ setSelectedChannels((prev) => {
+ const channel = prev[channelId];
+ if (!channel) return prev;
+
+ const newChannels = { ...prev };
+ newChannels[channelId] = {
+ ...channel,
+ notificationTypes: channel.notificationTypes.includes(notificationType)
+ ? channel.notificationTypes.filter(
+ (type) => type !== notificationType,
+ )
+ : [...channel.notificationTypes, notificationType],
+ };
+ return newChannels;
+ });
+ };
+
+ const handleSave = async () => {
+ setSaving(true);
+ try {
+ onChannelsUpdate(selectedChannels);
+ onOpenChange(false);
+ } catch (error) {
+ console.error("Error saving channel settings:", error);
+ toast.error("Failed to save channel settings");
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const isChannelSelected = (channelId: string) => {
+ return !!selectedChannels[channelId];
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="flex max-h-[80vh] max-w-2xl flex-col overflow-hidden">
+ <DialogHeader>
+ <DialogTitle>Configure Slack Channels</DialogTitle>
+ <DialogDescription>
+ Select which channels should receive notifications and configure
+ what types of events to send.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="flex-1 space-y-4 overflow-y-auto">
+ {loading ? (
+ <div className="flex items-center justify-center py-8">
+ <Loader2 className="h-6 w-6 animate-spin" />
+ <span className="ml-2">Loading channels...</span>
+ </div>
+ ) : channels.length === 0 ? (
+ <div className="py-8 text-center text-muted-foreground">
+ No channels found. Make sure your Slack app has been added to the
+ channels you want to use.
+ </div>
+ ) : (
+ <div className="space-y-4">
+ {channels.map((channel) => (
+ <div key={channel.id} className="rounded-lg border p-2">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center space-x-2">
+ <Hash className="h-4 w-4 text-muted-foreground" />
+ <span className="font-medium">{channel.name}</span>
+ {channel.is_private && (
+ <Badge variant="secondary" className="text-xs">
+ Private
+ </Badge>
+ )}
+ {channel.is_archived && (
+ <Badge variant="outline" className="text-xs">
+ Archived
+ </Badge>
+ )}
+ </div>
+ <Checkbox
+ checked={isChannelSelected(channel.id)}
+ onCheckedChange={() =>
+ handleChannelToggle(channel.id, channel.name)
+ }
+ />
+ </div>
+
+ {isChannelSelected(channel.id) && (
+ <div className="mt-2 space-y-2">
+ <p className="mb-2 text-sm text-muted-foreground">
+ Notification types for this channel:
+ </p>
+ <div className="grid grid-cols-2 gap-2">
+ {NOTIFICATION_TYPES.map((notificationType) => (
+ <div
+ key={notificationType.id}
+ className="flex items-center space-x-2"
+ >
+ <Checkbox
+ checked={selectedChannels[
+ channel.id
+ ]?.notificationTypes.includes(
+ notificationType.id,
+ )}
+ onCheckedChange={() =>
+ handleNotificationTypeToggle(
+ channel.id,
+ notificationType.id,
+ )
+ }
+ />
+ <span className="text-sm">
+ {notificationType.emoji} {notificationType.label}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button onClick={handleSave} disabled={saving}>
+ {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+ Save Changes
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/settings/slack-frequency-settings.tsx b/components/settings/slack-frequency-settings.tsx
new file mode 100644
index 00000000..080e081b
--- /dev/null
+++ b/components/settings/slack-frequency-settings.tsx
@@ -0,0 +1,328 @@
+import { Clock, Globe, HelpCircle } from "lucide-react";
+import { toast } from "sonner";
+
+import { getTimezoneOptions } from "@/lib/slack/timezone-utils";
+
+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 SlackFrequencySettingsProps {
+ teamId: string;
+ integration: {
+ id: string;
+ frequency: "instant" | "daily" | "weekly";
+ timezone: string;
+ dailyTime?: string;
+ weeklyDay?: string;
+ enabledChannels: Record<string, any>;
+ };
+ onUpdate: (updatedIntegration: any) => 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 = [
+ {
+ 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,
+ ) => {
+ 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 {
+ throw 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: "instant" | "daily" | "weekly") => {
+ const updatePromise = async () => {
+ await updateIntegration({ frequency });
+
+ if (frequency === "daily" || frequency === "weekly") {
+ const updatedChannels = { ...integration.enabledChannels };
+ let channelsUpdated = false;
+
+ Object.keys(updatedChannels).forEach((channelId) => {
+ if (
+ updatedChannels[channelId] &&
+ !updatedChannels[channelId].notificationTypes.includes("digest")
+ ) {
+ updatedChannels[channelId] = {
+ ...updatedChannels[channelId],
+ notificationTypes: [
+ ...updatedChannels[channelId].notificationTypes,
+ "digest",
+ ],
+ };
+ channelsUpdated = true;
+ }
+ });
+
+ if (channelsUpdated) {
+ await updateIntegration({ enabledChannels: updatedChannels });
+ }
+ }
+ };
+
+ toast.promise(updatePromise(), {
+ loading: `Updating notification frequency to ${frequency}...`,
+ success: (data) => {
+ const messages = [`Frequency updated to ${frequency}`];
+
+ if (frequency === "daily" || frequency === "weekly") {
+ messages.push(
+ "Digest summaries automatically enabled for all selected channels",
+ );
+ }
+
+ return messages.join(". ");
+ },
+ 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 "instant" | "daily" | "weekly")
+ }
+ >
+ <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>
+ <p className="mt-1 text-xs text-blue-600">
+ 💡 Digest summaries will be automatically enabled for all
+ selected channels
+ </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>
+ );
+}
diff --git a/components/settings/slack-settings-skeleton.tsx b/components/settings/slack-settings-skeleton.tsx
new file mode 100644
index 00000000..7c4edc08
--- /dev/null
+++ b/components/settings/slack-settings-skeleton.tsx
@@ -0,0 +1,82 @@
+import { Skeleton } from "@/components/ui/skeleton";
+
+export default function SlackSettingsSkeleton() {
+ return (
+ <div className="space-y-6">
+ {/* Header Skeleton */}
+ <div className="mb-4 flex items-center justify-between md:mb-8 lg:mb-12">
+ <div className="space-y-2">
+ <Skeleton className="h-8 w-48" />
+ <Skeleton className="h-4 w-80" />
+ </div>
+ <Skeleton className="h-10 w-32" />
+ </div>
+
+ {/* Main Content Skeleton */}
+ <div className="space-y-6">
+ {/* Card 1 */}
+ <div className="rounded-lg border bg-card p-6">
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <Skeleton className="h-6 w-40" />
+ <Skeleton className="h-4 w-60" />
+ </div>
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <Skeleton className="h-5 w-32" />
+ <Skeleton className="h-4 w-48" />
+ </div>
+ <Skeleton className="h-6 w-11" />
+ </div>
+ <div className="space-y-3">
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-32" />
+ <Skeleton className="h-4 w-64" />
+ </div>
+ <div className="flex items-center rounded-lg border border-border bg-background">
+ <div className="flex flex-1 items-center gap-2 px-2">
+ <Skeleton className="h-6 w-20" />
+ <Skeleton className="h-6 w-24" />
+ </div>
+ <Skeleton className="h-6 w-px" />
+ <Skeleton className="h-8 w-32 shrink-0" />
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Card 2 */}
+ <div className="rounded-lg border bg-card p-6">
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <Skeleton className="h-6 w-44" />
+ <Skeleton className="h-4 w-72" />
+ </div>
+ <div className="space-y-4">
+ <div className="flex space-x-6">
+ {[1, 2, 3].map((i) => (
+ <div key={i} className="flex items-center space-x-2">
+ <Skeleton className="h-4 w-4" />
+ <Skeleton className="h-4 w-16" />
+ </div>
+ ))}
+ </div>
+ <div className="grid gap-4 md:grid-cols-2">
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-12" />
+ <Skeleton className="h-10 w-full" />
+ </div>
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-20" />
+ <Skeleton className="h-10 w-full" />
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/components/shared/icons/slack-icon.tsx b/components/shared/icons/slack-icon.tsx
new file mode 100644
index 00000000..111a28a4
--- /dev/null
+++ b/components/shared/icons/slack-icon.tsx
@@ -0,0 +1,20 @@
+import React from "react";
+
+interface SlackIconProps {
+ className?: string;
+ size?: number;
+}
+
+export function SlackIcon({ className = "", size = 24 }: SlackIconProps) {
+ return (
+ <svg
+ width={size}
+ height={size}
+ viewBox="0 0 24 24"
+ fill="currentColor"
+ className={className}
+ >
+ <path d="M6.194 14.644c0 1.16-.943 2.107-2.107 2.107-1.16 0-2.107-.943-2.107-2.107 0-1.16.943-2.107 2.107-2.107h2.107v2.107zm1.061 0c0-1.16.943-2.107 2.107-2.107 1.16 0 2.107.943 2.107 2.107v5.374c0 1.16-.943 2.107-2.107 2.107-1.16 0-2.107-.943-2.107-2.107v-5.374zm2.107-8.456c-1.16 0-2.107-.943-2.107-2.107 0-1.16.943-2.107 2.107-2.107s2.107.943 2.107 2.107v2.107h-2.107zm0 1.061c1.16 0 2.107.943 2.107 2.107s-.943 2.107-2.107 2.107h-5.374c-1.16 0-2.107-.943-2.107-2.107s.943-2.107 2.107-2.107h5.374zm8.456 2.107c0-1.16.943-2.107 2.107-2.107s2.107.943 2.107 2.107-.943 2.107-2.107 2.107h-2.107v-2.107zm-1.061 0c0 1.16-.943 2.107-2.107 2.107s-2.107-.943-2.107-2.107v-5.374c0-1.16.943-2.107 2.107-2.107s2.107.943 2.107 2.107v5.374zm-2.107 8.456c1.16 0 2.107.943 2.107 2.107s-.943 2.107-2.107 2.107-2.107-.943-2.107-2.107v-2.107h2.107zm0-1.061c-1.16 0-2.107-.943-2.107-2.107s.943-2.107 2.107-2.107h5.374c1.16 0 2.107.943 2.107 2.107s-.943 2.107-2.107 2.107h-5.374z" />
+ </svg>
+ );
+}
diff --git a/components/sidebar/app-sidebar.tsx b/components/sidebar/app-sidebar.tsx
index c2176cbf..9d282f41 100644
--- a/components/sidebar/app-sidebar.tsx
+++ b/components/sidebar/app-sidebar.tsx
@@ -150,6 +150,11 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
url: "/settings/webhooks",
current: router.pathname.includes("settings/webhooks"),
},
+ {
+ title: "Slack",
+ url: "/settings/slack",
+ current: router.pathname.includes("settings/slack"),
+ },
{
title: "Billing",
url: "/settings/billing",
diff --git a/components/ui/alert-dialog.tsx b/components/ui/alert-dialog.tsx
index d49272a6..3925083b 100644
--- a/components/ui/alert-dialog.tsx
+++ b/components/ui/alert-dialog.tsx
@@ -1,12 +1,13 @@
"use client";
import * as React from "react";
+import { useState } from "react";
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
import { cn } from "@/lib/utils";
-import { buttonVariants } from "@/components/ui/button";
+import { Button, buttonVariants } from "@/components/ui/button";
const AlertDialog = AlertDialogPrimitive.Root;
@@ -134,7 +135,63 @@ const AlertDialogCancel = React.forwardRef<
));
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
+interface SingleAlertDialogProps {
+ title: string;
+ description: string;
+ action: string;
+ onAction: () => void;
+ actionUpdate?: string;
+ disabled?: boolean;
+ loading?: boolean;
+}
+
+const CommonAlertDialog = ({
+ title,
+ description,
+ action,
+ onAction,
+ actionUpdate,
+ disabled = false,
+ loading = false,
+}: SingleAlertDialogProps) => {
+ const [showDisconnectDialog, setShowDisconnectDialog] = useState(false);
+
+ const handleDisconnect = async () => {
+ onAction();
+ setShowDisconnectDialog(false);
+ };
+
+ return (
+ <AlertDialog
+ open={showDisconnectDialog}
+ onOpenChange={setShowDisconnectDialog}
+ >
+ <AlertDialogTrigger asChild>
+ <Button variant="destructive" size="sm" disabled={disabled || loading}>
+ {loading ? `${actionUpdate}...` : action}
+ </Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle> {title} </AlertDialogTitle>
+ <AlertDialogDescription>{description}</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={handleDisconnect}
+ className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
+ >
+ {action}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+};
+
export {
+ CommonAlertDialog,
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
diff --git a/components/upload-zone.tsx b/components/upload-zone.tsx
index d4b38dc0..f7b90845 100644
--- a/components/upload-zone.tsx
+++ b/components/upload-zone.tsx
@@ -1,769 +1,769 @@
-import { useRouter } from "next/router";
-
-import { useCallback, useMemo, useRef, useState } from "react";
-
-import { useTeam } from "@/context/team-context";
-import { DocumentStorageType } from "@prisma/client";
-import { useSession } from "next-auth/react";
-import { DropEvent, FileRejection, useDropzone } from "react-dropzone";
-import { toast } from "sonner";
-import { mutate } from "swr";
-
-import { useAnalytics } from "@/lib/analytics";
-import { SUPPORTED_DOCUMENT_MIME_TYPES } from "@/lib/constants";
-import { DocumentData, createDocument } from "@/lib/documents/create-document";
-import { resumableUpload } from "@/lib/files/tus-upload";
-import {
- createFolderInBoth,
- createFolderInMainDocs,
- determineFolderPaths,
- isSystemFile,
-} from "@/lib/folders/create-folder";
-import { usePlan } from "@/lib/swr/use-billing";
-import useLimits from "@/lib/swr/use-limits";
-import { CustomUser } from "@/lib/types";
-import { cn } from "@/lib/utils";
-import { getSupportedContentType } from "@/lib/utils/get-content-type";
-import {
- getFileSizeLimit,
- getFileSizeLimits,
-} from "@/lib/utils/get-file-size-limits";
-import { getPagesCount } from "@/lib/utils/get-page-number-count";
-
-// Originally these mime values were directly used in the dropzone hook.
-// There was a solid reason to take them out of the scope, primarily to solve a browser compatibility issue to determine the file type when user dropped a folder.
-// you will figure out how this change helped to fix the compatibility issue once you have went through reading of `getFilesFromDropEvent` and `traverseFolder`
-const acceptableDropZoneMimeTypesWhenIsFreePlanAndNotTrail = {
- "application/pdf": [], // ".pdf"
- "application/vnd.ms-excel": [], // ".xls"
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [], // ".xlsx"
- "text/csv": [], // ".csv"
- "application/vnd.oasis.opendocument.spreadsheet": [], // ".ods"
- "image/png": [], // ".png"
- "image/jpeg": [], // ".jpeg"
- "image/jpg": [], // ".jpg"
-};
-const allAcceptableDropZoneMimeTypes = {
- "application/pdf": [], // ".pdf"
- "application/vnd.ms-excel": [], // ".xls"
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [], // ".xlsx"
- "application/vnd.ms-excel.sheet.macroEnabled.12": [".xlsm"], // ".xlsm"
- "text/csv": [], // ".csv"
- "application/vnd.oasis.opendocument.spreadsheet": [], // ".ods"
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [], // ".docx"
- "application/vnd.openxmlformats-officedocument.presentationml.presentation":
- [], // ".pptx"
- "application/vnd.ms-powerpoint": [], // ".ppt"
- "application/msword": [], // ".doc"
- "application/vnd.oasis.opendocument.text": [], // ".odt"
- "application/vnd.oasis.opendocument.presentation": [], // ".odp"
- "image/vnd.dwg": [".dwg"], // ".dwg"
- "image/vnd.dxf": [".dxf"], // ".dxf"
- "image/png": [], // ".png"
- "image/jpeg": [], // ".jpeg"
- "image/jpg": [], // ".jpg"
- "application/zip": [], // ".zip"
- "application/x-zip-compressed": [], // ".zip"
- "video/mp4": [], // ".mp4"
- "video/webm": [], // ".webm"
- "video/quicktime": [], // ".mov"
- "video/x-msvideo": [], // ".avi"
- "video/ogg": [], // ".ogg"
- "application/vnd.google-earth.kml+xml": [".kml"], // ".kml"
- "application/vnd.google-earth.kmz": [".kmz"], // ".kmz"
- "application/vnd.ms-outlook": [".msg"], // ".msg"
-};
-
-interface FileWithPaths extends File {
- path?: string;
- whereToUploadPath?: string;
- dataroomUploadPath?: string;
-}
-
-export interface UploadState {
- fileName: string;
- progress: number;
- documentId?: string;
- uploadId: string;
-}
-
-export interface RejectedFile {
- fileName: string;
- message: string;
-}
-
-interface UploadZoneProps extends React.PropsWithChildren {
- onUploadStart: (uploads: UploadState[]) => void;
- onUploadProgress: (
- index: number,
- progress: number,
- documentId?: string,
- ) => void;
- onUploadRejected: (rejected: RejectedFile[]) => void;
- onUploadSuccess?: (
- files: {
- fileName: string;
- documentId: string;
- dataroomDocumentId: string;
- }[],
- ) => void;
- setUploads: React.Dispatch<React.SetStateAction<UploadState[]>>;
- setRejectedFiles: React.Dispatch<React.SetStateAction<RejectedFile[]>>;
- folderPathName?: string;
- dataroomId?: string;
-}
-
-export default function UploadZone({
- children,
- onUploadStart,
- onUploadProgress,
- onUploadRejected,
- onUploadSuccess,
- folderPathName,
- setUploads,
- setRejectedFiles,
- dataroomId,
-}: UploadZoneProps) {
- const analytics = useAnalytics();
- const { plan, isFree, isTrial } = usePlan();
- const router = useRouter();
- const teamInfo = useTeam();
- const { data: session } = useSession();
- const { limits, canAddDocuments } = useLimits();
- const remainingDocuments = limits?.documents
- ? limits?.documents - limits?.usage?.documents
- : 0;
-
- const [progress, setProgress] = useState<number>(0);
- const [showProgress, setShowProgress] = useState(false);
- const uploadProgress = useRef<number[]>([]);
-
- const fileSizeLimits = useMemo(
- () =>
- getFileSizeLimits({
- limits,
- isFree,
- isTrial,
- }),
- [limits, isFree, isTrial],
- );
-
- const acceptableDropZoneFileTypes =
- isFree && !isTrial
- ? acceptableDropZoneMimeTypesWhenIsFreePlanAndNotTrail
- : allAcceptableDropZoneMimeTypes;
-
- // this var will help to determine the correct api endpoint to request folder creation (If needed).
- const endpointTargetType = dataroomId
- ? `datarooms/${dataroomId}/folders`
- : "folders";
-
- const onDropRejected = useCallback(
- (rejectedFiles: FileRejection[]) => {
- const rejected = rejectedFiles.map(({ file, errors }) => {
- let message = "";
- if (errors.find(({ code }) => code === "file-too-large")) {
- const fileSizeLimitMB = getFileSizeLimit(file.type, fileSizeLimits);
- message = `File size too big (max. ${fileSizeLimitMB} MB). Upgrade to a paid plan to increase the limit.`;
- } else if (errors.find(({ code }) => code === "file-invalid-type")) {
- const isSupported = SUPPORTED_DOCUMENT_MIME_TYPES.includes(file.type);
- message = `File type not supported ${
- isFree && !isTrial && isSupported ? `on free plan` : ""
- }`;
- }
- return { fileName: file.name, message };
- });
- onUploadRejected(rejected);
- },
- [onUploadRejected, fileSizeLimits, isFree, isTrial],
- );
-
- const onDrop = useCallback(
- async (acceptedFiles: FileWithPaths[]) => {
- if (!canAddDocuments && acceptedFiles.length > remainingDocuments) {
- toast.error("You have reached the maximum number of documents.");
- return;
- }
-
- // Validate files and separate into valid and invalid
- const validatedFiles = acceptedFiles.reduce<{
- valid: FileWithPaths[];
- invalid: { fileName: string; message: string }[];
- }>(
- (acc, file) => {
- const fileSizeLimitMB = getFileSizeLimit(file.type, fileSizeLimits);
- const fileSizeLimit = fileSizeLimitMB * 1024 * 1024; // Convert to bytes
-
- if (file.size > fileSizeLimit) {
- acc.invalid.push({
- fileName: file.name,
- message: `File size too big (max. ${fileSizeLimitMB} MB)${
- isFree && !isTrial
- ? ". Upgrade to a paid plan to increase the limit"
- : ""
- }`,
- });
- } else {
- acc.valid.push(file);
- }
- return acc;
- },
- { valid: [], invalid: [] },
- );
-
- // Handle rejected files first
- if (validatedFiles.invalid.length > 0) {
- setRejectedFiles((prev) => [...validatedFiles.invalid, ...prev]);
-
- // If all files were rejected, show a summary toast
- if (validatedFiles.valid.length === 0) {
- toast.error(
- `${validatedFiles.invalid.length} file(s) exceeded size limits`,
- );
- return;
- }
- }
-
- // Continue with valid files
- const newUploads = validatedFiles.valid.map((file) => ({
- fileName: file.name,
- progress: 0,
- uploadId: crypto.randomUUID(),
- }));
-
- onUploadStart(newUploads);
-
- const uploadPromises = validatedFiles.valid.map(async (file, index) => {
- // Due to `getFilesFromEvent` file.path will always hold a valid value and represents the value of webkitRelativePath.
- // We no longer need to use webkitRelativePath because everything is been handled in `getFilesFromEvent`
- const path = file.path || file.name;
-
- // count the number of pages in the file
- let numPages = 1;
- if (file.type === "application/pdf") {
- const buffer = await file.arrayBuffer();
- numPages = await getPagesCount(buffer);
-
- if (numPages > fileSizeLimits.maxPages) {
- setUploads((prev) =>
- prev.filter((upload) => upload.fileName !== file.name),
- );
-
- return setRejectedFiles((prev) => [
- {
- fileName: file.name,
- message: `File has too many pages (max. ${fileSizeLimits.maxPages})`,
- },
- ...prev,
- ]);
- }
- }
-
- const { complete } = await resumableUpload({
- file, // File
- onProgress: (bytesUploaded, bytesTotal) => {
- const progress = Math.min(
- Math.round((bytesUploaded / bytesTotal) * 100),
- 99,
- );
- setUploads((prevUploads) =>
- prevUploads.map((upload) =>
- upload.uploadId === newUploads[index].uploadId
- ? { ...upload, progress }
- : upload,
- ),
- );
-
- const _progress = uploadProgress.current.reduce(
- (acc, progress) => acc + progress,
- 0,
- );
- },
- onError: (error) => {
- setUploads((prev) =>
- prev.filter(
- (upload) => upload.uploadId !== newUploads[index].uploadId,
- ),
- );
-
- setRejectedFiles((prev) => [
- { fileName: file.name, message: "Error uploading file" },
- ...prev,
- ]);
- },
- ownerId: (session?.user as CustomUser).id,
- teamId: teamInfo?.currentTeam?.id as string,
- numPages,
- relativePath: path.substring(0, path.lastIndexOf("/")),
- });
-
- const uploadResult = await complete;
-
- let contentType = uploadResult.fileType;
- let supportedFileType = getSupportedContentType(contentType) ?? "";
-
- if (
- uploadResult.fileName.endsWith(".dwg") ||
- uploadResult.fileName.endsWith(".dxf")
- ) {
- supportedFileType = "cad";
- contentType = `image/vnd.${uploadResult.fileName.split(".").pop()}`;
- }
-
- if (uploadResult.fileName.endsWith(".xlsm")) {
- supportedFileType = "sheet";
- contentType = "application/vnd.ms-excel.sheet.macroEnabled.12";
- }
-
- if (
- uploadResult.fileName.endsWith(".kml") ||
- uploadResult.fileName.endsWith(".kmz")
- ) {
- supportedFileType = "map";
- contentType = `application/vnd.google-earth.${uploadResult.fileName.endsWith(".kml") ? "kml+xml" : "kmz"}`;
- }
-
- const documentData: DocumentData = {
- key: uploadResult.id,
- supportedFileType: supportedFileType,
- name: file.name,
- storageType: DocumentStorageType.S3_PATH,
- contentType: contentType,
- fileSize: file.size,
- };
-
- const fileUploadPathName = file?.whereToUploadPath;
- const dataroomUploadPathName = file?.dataroomUploadPath;
-
- const response = await createDocument({
- documentData,
- teamId: teamInfo?.currentTeam?.id as string,
- numPages: uploadResult.numPages,
- folderPathName: fileUploadPathName,
- });
-
- // add the new document to the list
- mutate(`/api/teams/${teamInfo?.currentTeam?.id}/documents`);
-
- fileUploadPathName &&
- mutate(
- `/api/teams/${teamInfo?.currentTeam?.id}/folders/documents/${fileUploadPathName}`,
- );
-
- const document = await response.json();
- let dataroomResponse;
- if (dataroomId) {
- try {
- dataroomResponse = await fetch(
- `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- documentId: document.id,
- folderPathName: dataroomUploadPathName || fileUploadPathName,
- }),
- },
- );
-
- if (!dataroomResponse?.ok) {
- const { message } = await dataroomResponse.json();
- console.error(
- "An error occurred while adding document to the dataroom: ",
- message,
- );
- return;
- }
-
- mutate(
- `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents`,
- );
- (dataroomUploadPathName || fileUploadPathName) &&
- mutate(
- `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders/documents/${dataroomUploadPathName || fileUploadPathName}`,
- );
- } catch (error) {
- console.error(
- "An error occurred while adding document to the dataroom: ",
- error,
- );
- }
- }
-
- // update progress to 100%
- setUploads((prevUploads) =>
- prevUploads.map((upload) =>
- upload.uploadId === newUploads[index].uploadId
- ? { ...upload, progress: 100, documentId: document.id }
- : upload,
- ),
- );
-
- analytics.capture("Document Added", {
- documentId: document.id,
- name: document.name,
- numPages: document.numPages,
- path: router.asPath,
- type: document.type,
- contentType: document.contentType,
- teamId: teamInfo?.currentTeam?.id,
- bulkupload: true,
- dataroomId: dataroomId,
- $set: {
- teamId: teamInfo?.currentTeam?.id,
- teamPlan: plan,
- },
- });
- const dataroomDocumentId = dataroomResponse?.ok
- ? (await dataroomResponse.json()).id
- : null;
-
- return { ...document, dataroomDocumentId: dataroomDocumentId };
- });
-
- const documents = Promise.all(uploadPromises).finally(() => {
- /* If it a parentFolder was created prior to the upload, we would need to update that
- how many documents and folders does this folder contain rather than displaying 0
- */
-
- mutate(
- `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}?root=true`,
- );
- mutate(`/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}`);
- folderPathName &&
- mutate(
- `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/${folderPathName}`,
- );
- });
- const uploadedDocuments = await documents;
- const dataroomDocuments = uploadedDocuments.map((document) => ({
- documentId: document.id,
- dataroomDocumentId: document.dataroomDocumentId,
- fileName: document.name,
- }));
- onUploadSuccess?.(dataroomDocuments);
- },
- [
- onUploadStart,
- onUploadProgress,
- endpointTargetType,
- fileSizeLimits,
- isFree,
- isTrial,
- ],
- );
-
- const getFilesFromEvent = useCallback(
- async (event: DropEvent) => {
- // This callback also run when event.type =`dragenter`. We only need to compute files when the event.type is `drop`.
- if ("type" in event && event.type !== "drop" && event.type !== "change") {
- return [];
- }
-
- let filesToBePassedToOnDrop: FileWithPaths[] = [];
-
- /** *********** START OF `traverseFolder` *********** */
- const traverseFolder = async (
- entry: FileSystemEntry,
- parentPathOfThisEntry?: string,
- dataroomParentPath?: string,
- ): Promise<FileWithPaths[]> => {
- /**
- * Summary of this function:
- * 1. if it find a folder then corresponding folder will be created at backend.
- * 2. Smoothly handles the deeply nested folders.
- * 3. Upon folder creation it assign the path and whereToUploadPath to each entry. (Those values will be helpful for `onDrop` to upload document correctly)
- */
-
- let files: FileWithPaths[] = [];
-
- if (isSystemFile(entry.name)) {
- return files;
- }
-
- if (entry.isDirectory) {
- /**
- * Let's create the folder.
- * Fact that reader can skip: For Consistency, child files will only be pushed if folder successfully gets created.
- */
- try {
- // An empty folder name can cause the unexpected url problems.
- if (entry.name.trim() === "") {
- setRejectedFiles((prev) => [
- {
- fileName: entry.name,
- message: "Folder name cannot be empty",
- },
- ...prev,
- ]);
- throw new Error("Folder name cannot be empty");
- }
-
- if (!teamInfo?.currentTeam?.id) {
- /** This case probably may not happen */
- setRejectedFiles((prev) => [
- {
- fileName: "Unknown Team",
- message: "Team Id not found",
- },
- ...prev,
- ]);
- throw new Error("No team found");
- }
-
- // Create folder in main documents if not in dataroom
- if (!dataroomId) {
- // Create folder in main documents only
- const { path: folderPath } = await createFolderInMainDocs({
- teamId: teamInfo.currentTeam.id,
- name: entry.name,
- path: parentPathOfThisEntry ?? folderPathName,
- });
-
- analytics.capture("Folder Added", { folderName: entry.name });
-
- const dirReader = (
- entry as FileSystemDirectoryEntry
- ).createReader();
- const subEntries = await new Promise<FileSystemEntry[]>(
- (resolve) => dirReader.readEntries(resolve),
- );
-
- const filteredSubEntries = subEntries.filter(
- (subEntry) => !isSystemFile(subEntry.name),
- );
-
- const resolvedFolderPath = folderPath.startsWith("/")
- ? folderPath.slice(1)
- : folderPath;
-
- for (const subEntry of filteredSubEntries) {
- files.push(
- ...(await traverseFolder(
- subEntry,
- resolvedFolderPath,
- undefined,
- )),
- );
- }
- } else {
- const isFirstLevelFolder =
- (parentPathOfThisEntry ?? folderPathName) === folderPathName;
-
- const {
- parentDataroomPath: targetParentDataroomPath,
- parentMainDocsPath: targetParentMainDocsPath,
- } = determineFolderPaths({
- currentDataroomPath: dataroomParentPath ?? folderPathName,
- currentMainDocsPath: parentPathOfThisEntry,
- isFirstLevelFolder,
- });
-
- const { dataroomPath, mainDocsPath } = await createFolderInBoth({
- teamId: teamInfo.currentTeam.id,
- dataroomId,
- name: entry.name,
- parentMainDocsPath: targetParentMainDocsPath,
- parentDataroomPath: targetParentDataroomPath,
- setRejectedFiles,
- analytics,
- });
-
- const dirReader = (
- entry as FileSystemDirectoryEntry
- ).createReader();
- const subEntries = await new Promise<FileSystemEntry[]>(
- (resolve) => dirReader.readEntries(resolve),
- );
-
- const filteredSubEntries = subEntries.filter(
- (subEntry) => !isSystemFile(subEntry.name),
- );
-
- // Use the resolved paths for all children
- const resolvedMainDocsPath = mainDocsPath.startsWith("/")
- ? mainDocsPath.slice(1)
- : mainDocsPath;
- const resolvedDataroomPath = dataroomPath.startsWith("/")
- ? dataroomPath.slice(1)
- : dataroomPath;
-
- for (const subEntry of filteredSubEntries) {
- files.push(
- ...(await traverseFolder(
- subEntry,
- resolvedMainDocsPath,
- resolvedDataroomPath,
- )),
- );
- }
- }
- } catch (error) {
- console.error(
- "An error occurred while creating the folder: ",
- error,
- );
- setRejectedFiles((prev) => [
- {
- fileName: entry.name,
- message: "Failed to create the folder",
- },
- ...prev,
- ]);
- }
- } else if (entry.isFile) {
- if (isSystemFile(entry.name)) {
- return files;
- }
-
- let file = await new Promise<FileWithPaths>((resolve) =>
- (entry as FileSystemFileEntry).file(resolve),
- );
-
- /** In some browsers e.g firefox is not able to detect the file type. (This only happens when user upload folder) */
- const browserFileTypeCompatibilityIssue = file.type === "";
-
- if (browserFileTypeCompatibilityIssue) {
- const fileExtension = file.name.split(".").pop()?.toLowerCase();
- let correctMimeType: string | undefined;
- if (fileExtension) {
- // Iterate through acceptableDropZoneFileTypes to find the MIME type for the extension
- for (const [mime, extsUntyped] of Object.entries(
- acceptableDropZoneFileTypes,
- )) {
- const exts = extsUntyped as string[]; // Explicitly type exts
- if (
- exts.some((ext) => ext.toLowerCase() === "." + fileExtension)
- ) {
- correctMimeType = mime;
- break;
- }
- }
- }
-
- if (correctMimeType) {
- // if we can't do like ```file.type = fileType``` because of [Error: Setting getter-only property "type"]
- // The following is the only best way to resolve the problem
- file = new File([file], file.name, {
- type: correctMimeType,
- lastModified: file.lastModified,
- });
- }
- }
-
- // Reason of removing "/" because webkitRelativePath doesn't start with "/"
- file.path = entry.fullPath.startsWith("/")
- ? entry.fullPath.substring(1)
- : entry.fullPath;
-
- file.whereToUploadPath = parentPathOfThisEntry ?? folderPathName;
- file.dataroomUploadPath = dataroomParentPath;
-
- files.push(file);
- }
-
- return files;
- };
- /** *********** END OF `traverseFolder` *********** */
-
- if ("dataTransfer" in event && event.dataTransfer) {
- const items = event.dataTransfer.items;
-
- const fileResults = await Promise.all(
- Array.from(items, (item) => {
- // MDN Note: This function is implemented as webkitGetAsEntry() in non-WebKit browsers including Firefox at this time; it may be renamed to getAsEntry() in the future, so you should code defensively, looking for both.
- const entry =
- (typeof item?.webkitGetAsEntry === "function" &&
- item.webkitGetAsEntry()) ??
- (typeof (item as any)?.getAsEntry === "function" &&
- (item as any).getAsEntry()) ??
- null;
- return entry
- ? traverseFolder(
- entry,
- folderPathName,
- dataroomId ? folderPathName : undefined,
- )
- : [];
- }),
- );
- fileResults.forEach((fileResult) =>
- filesToBePassedToOnDrop.push(...fileResult),
- );
- } else if (
- "target" in event &&
- event.target &&
- event.target instanceof HTMLInputElement &&
- event.target.files
- ) {
- for (let i = 0; i < event.target.files.length; i++) {
- const file: FileWithPaths = event.target.files[i];
- file.path = file.name;
- file.whereToUploadPath = folderPathName;
- file.dataroomUploadPath = folderPathName;
- filesToBePassedToOnDrop.push(event.target.files[i]);
- }
- }
-
- return filesToBePassedToOnDrop;
- },
- [folderPathName, endpointTargetType, teamInfo],
- );
-
- const { getRootProps, getInputProps, isDragActive } = useDropzone({
- accept: acceptableDropZoneFileTypes,
- multiple: true,
- // maxSize: maxSize * 1024 * 1024, // 30 MB
- maxFiles: fileSizeLimits.maxFiles ?? 150,
- onDrop,
- onDropRejected,
- getFilesFromEvent,
- });
-
- return (
- <div
- {...getRootProps({ onClick: (evt) => evt.stopPropagation() })}
- className={cn(
- "relative",
- dataroomId ? "min-h-[calc(100vh-350px)]" : "min-h-[calc(100vh-270px)]",
- )}
- >
- <div
- className={cn(
- "absolute inset-0 z-40 -m-1 rounded-lg border-2 border-dashed",
- isDragActive
- ? "pointer-events-auto border-primary/50 bg-gray-100/75 backdrop-blur-sm dark:bg-gray-800/75"
- : "pointer-events-none border-none",
- )}
- >
- <input
- {...getInputProps()}
- name="file"
- id="upload-multi-files-zone"
- className="sr-only"
- />
-
- {isDragActive && (
- <div className="sticky top-1/2 z-50 -translate-y-1/2 px-2">
- <div className="flex justify-center">
- <div className="inline-flex flex-col rounded-lg bg-background/95 px-6 py-4 text-center ring-1 ring-gray-900/5 dark:bg-gray-900/95 dark:ring-white/10">
- <span className="font-medium text-foreground">
- Drop your file(s) here
- </span>
- <p className="mt-1 text-xs leading-5 text-muted-foreground">
- {isFree && !isTrial
- ? `Only *.pdf, *.xls, *.xlsx, *.csv, *.ods, *.png, *.jpeg, *.jpg`
- : `Only *.pdf, *.pptx, *.docx, *.xlsx, *.xls, *.csv, *.ods, *.ppt, *.odp, *.doc, *.odt, *.dwg, *.dxf, *.png, *.jpg, *.jpeg, *.mp4, *.mov, *.avi, *.webm, *.ogg`}
- </p>
- </div>
- </div>
- </div>
- )}
- </div>
-
- {children}
- </div>
- );
-}
+import { useRouter } from "next/router";
+
+import { useCallback, useMemo, useRef, useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { DocumentStorageType } from "@prisma/client";
+import { useSession } from "next-auth/react";
+import { DropEvent, FileRejection, useDropzone } from "react-dropzone";
+import { toast } from "sonner";
+import { mutate } from "swr";
+
+import { useAnalytics } from "@/lib/analytics";
+import { SUPPORTED_DOCUMENT_MIME_TYPES } from "@/lib/constants";
+import { DocumentData, createDocument } from "@/lib/documents/create-document";
+import { resumableUpload } from "@/lib/files/tus-upload";
+import {
+ createFolderInBoth,
+ createFolderInMainDocs,
+ determineFolderPaths,
+ isSystemFile,
+} from "@/lib/folders/create-folder";
+import { usePlan } from "@/lib/swr/use-billing";
+import useLimits from "@/lib/swr/use-limits";
+import { CustomUser } from "@/lib/types";
+import { cn } from "@/lib/utils";
+import { getSupportedContentType } from "@/lib/utils/get-content-type";
+import {
+ getFileSizeLimit,
+ getFileSizeLimits,
+} from "@/lib/utils/get-file-size-limits";
+import { getPagesCount } from "@/lib/utils/get-page-number-count";
+
+// Originally these mime values were directly used in the dropzone hook.
+// There was a solid reason to take them out of the scope, primarily to solve a browser compatibility issue to determine the file type when user dropped a folder.
+// you will figure out how this change helped to fix the compatibility issue once you have went through reading of `getFilesFromDropEvent` and `traverseFolder`
+const acceptableDropZoneMimeTypesWhenIsFreePlanAndNotTrail = {
+ "application/pdf": [], // ".pdf"
+ "application/vnd.ms-excel": [], // ".xls"
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [], // ".xlsx"
+ "text/csv": [], // ".csv"
+ "application/vnd.oasis.opendocument.spreadsheet": [], // ".ods"
+ "image/png": [], // ".png"
+ "image/jpeg": [], // ".jpeg"
+ "image/jpg": [], // ".jpg"
+};
+const allAcceptableDropZoneMimeTypes = {
+ "application/pdf": [], // ".pdf"
+ "application/vnd.ms-excel": [], // ".xls"
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [], // ".xlsx"
+ "application/vnd.ms-excel.sheet.macroEnabled.12": [".xlsm"], // ".xlsm"
+ "text/csv": [], // ".csv"
+ "application/vnd.oasis.opendocument.spreadsheet": [], // ".ods"
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [], // ".docx"
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation":
+ [], // ".pptx"
+ "application/vnd.ms-powerpoint": [], // ".ppt"
+ "application/msword": [], // ".doc"
+ "application/vnd.oasis.opendocument.text": [], // ".odt"
+ "application/vnd.oasis.opendocument.presentation": [], // ".odp"
+ "image/vnd.dwg": [".dwg"], // ".dwg"
+ "image/vnd.dxf": [".dxf"], // ".dxf"
+ "image/png": [], // ".png"
+ "image/jpeg": [], // ".jpeg"
+ "image/jpg": [], // ".jpg"
+ "application/zip": [], // ".zip"
+ "application/x-zip-compressed": [], // ".zip"
+ "video/mp4": [], // ".mp4"
+ "video/webm": [], // ".webm"
+ "video/quicktime": [], // ".mov"
+ "video/x-msvideo": [], // ".avi"
+ "video/ogg": [], // ".ogg"
+ "application/vnd.google-earth.kml+xml": [".kml"], // ".kml"
+ "application/vnd.google-earth.kmz": [".kmz"], // ".kmz"
+ "application/vnd.ms-outlook": [".msg"], // ".msg"
+};
+
+interface FileWithPaths extends File {
+ path?: string;
+ whereToUploadPath?: string;
+ dataroomUploadPath?: string;
+}
+
+export interface UploadState {
+ fileName: string;
+ progress: number;
+ documentId?: string;
+ uploadId: string;
+}
+
+export interface RejectedFile {
+ fileName: string;
+ message: string;
+}
+
+interface UploadZoneProps extends React.PropsWithChildren {
+ onUploadStart: (uploads: UploadState[]) => void;
+ onUploadProgress: (
+ index: number,
+ progress: number,
+ documentId?: string,
+ ) => void;
+ onUploadRejected: (rejected: RejectedFile[]) => void;
+ onUploadSuccess?: (
+ files: {
+ fileName: string;
+ documentId: string;
+ dataroomDocumentId: string;
+ }[],
+ ) => void;
+ setUploads: React.Dispatch<React.SetStateAction<UploadState[]>>;
+ setRejectedFiles: React.Dispatch<React.SetStateAction<RejectedFile[]>>;
+ folderPathName?: string;
+ dataroomId?: string;
+}
+
+export default function UploadZone({
+ children,
+ onUploadStart,
+ onUploadProgress,
+ onUploadRejected,
+ onUploadSuccess,
+ folderPathName,
+ setUploads,
+ setRejectedFiles,
+ dataroomId,
+}: UploadZoneProps) {
+ const analytics = useAnalytics();
+ const { plan, isFree, isTrial } = usePlan();
+ const router = useRouter();
+ const teamInfo = useTeam();
+ const { data: session } = useSession();
+ const { limits, canAddDocuments } = useLimits();
+ const remainingDocuments = limits?.documents
+ ? limits?.documents - limits?.usage?.documents
+ : 0;
+
+ const [progress, setProgress] = useState<number>(0);
+ const [showProgress, setShowProgress] = useState(false);
+ const uploadProgress = useRef<number[]>([]);
+
+ const fileSizeLimits = useMemo(
+ () =>
+ getFileSizeLimits({
+ limits,
+ isFree,
+ isTrial,
+ }),
+ [limits, isFree, isTrial],
+ );
+
+ const acceptableDropZoneFileTypes =
+ isFree && !isTrial
+ ? acceptableDropZoneMimeTypesWhenIsFreePlanAndNotTrail
+ : allAcceptableDropZoneMimeTypes;
+
+ // this var will help to determine the correct api endpoint to request folder creation (If needed).
+ const endpointTargetType = dataroomId
+ ? `datarooms/${dataroomId}/folders`
+ : "folders";
+
+ const onDropRejected = useCallback(
+ (rejectedFiles: FileRejection[]) => {
+ const rejected = rejectedFiles.map(({ file, errors }) => {
+ let message = "";
+ if (errors.find(({ code }) => code === "file-too-large")) {
+ const fileSizeLimitMB = getFileSizeLimit(file.type, fileSizeLimits);
+ message = `File size too big (max. ${fileSizeLimitMB} MB). Upgrade to a paid plan to increase the limit.`;
+ } else if (errors.find(({ code }) => code === "file-invalid-type")) {
+ const isSupported = SUPPORTED_DOCUMENT_MIME_TYPES.includes(file.type);
+ message = `File type not supported ${
+ isFree && !isTrial && isSupported ? `on free plan` : ""
+ }`;
+ }
+ return { fileName: file.name, message };
+ });
+ onUploadRejected(rejected);
+ },
+ [onUploadRejected, fileSizeLimits, isFree, isTrial],
+ );
+
+ const onDrop = useCallback(
+ async (acceptedFiles: FileWithPaths[]) => {
+ if (!canAddDocuments && acceptedFiles.length > remainingDocuments) {
+ toast.error("You have reached the maximum number of documents.");
+ return;
+ }
+
+ // Validate files and separate into valid and invalid
+ const validatedFiles = acceptedFiles.reduce<{
+ valid: FileWithPaths[];
+ invalid: { fileName: string; message: string }[];
+ }>(
+ (acc, file) => {
+ const fileSizeLimitMB = getFileSizeLimit(file.type, fileSizeLimits);
+ const fileSizeLimit = fileSizeLimitMB * 1024 * 1024; // Convert to bytes
+
+ if (file.size > fileSizeLimit) {
+ acc.invalid.push({
+ fileName: file.name,
+ message: `File size too big (max. ${fileSizeLimitMB} MB)${
+ isFree && !isTrial
+ ? ". Upgrade to a paid plan to increase the limit"
+ : ""
+ }`,
+ });
+ } else {
+ acc.valid.push(file);
+ }
+ return acc;
+ },
+ { valid: [], invalid: [] },
+ );
+
+ // Handle rejected files first
+ if (validatedFiles.invalid.length > 0) {
+ setRejectedFiles((prev) => [...validatedFiles.invalid, ...prev]);
+
+ // If all files were rejected, show a summary toast
+ if (validatedFiles.valid.length === 0) {
+ toast.error(
+ `${validatedFiles.invalid.length} file(s) exceeded size limits`,
+ );
+ return;
+ }
+ }
+
+ // Continue with valid files
+ const newUploads = validatedFiles.valid.map((file) => ({
+ fileName: file.name,
+ progress: 0,
+ uploadId: crypto.randomUUID(),
+ }));
+
+ onUploadStart(newUploads);
+
+ const uploadPromises = validatedFiles.valid.map(async (file, index) => {
+ // Due to `getFilesFromEvent` file.path will always hold a valid value and represents the value of webkitRelativePath.
+ // We no longer need to use webkitRelativePath because everything is been handled in `getFilesFromEvent`
+ const path = file.path || file.name;
+
+ // count the number of pages in the file
+ let numPages = 1;
+ if (file.type === "application/pdf") {
+ const buffer = await file.arrayBuffer();
+ numPages = await getPagesCount(buffer);
+
+ if (numPages > fileSizeLimits.maxPages) {
+ setUploads((prev) =>
+ prev.filter((upload) => upload.fileName !== file.name),
+ );
+
+ return setRejectedFiles((prev) => [
+ {
+ fileName: file.name,
+ message: `File has too many pages (max. ${fileSizeLimits.maxPages})`,
+ },
+ ...prev,
+ ]);
+ }
+ }
+
+ const { complete } = await resumableUpload({
+ file, // File
+ onProgress: (bytesUploaded, bytesTotal) => {
+ const progress = Math.min(
+ Math.round((bytesUploaded / bytesTotal) * 100),
+ 99,
+ );
+ setUploads((prevUploads) =>
+ prevUploads.map((upload) =>
+ upload.uploadId === newUploads[index].uploadId
+ ? { ...upload, progress }
+ : upload,
+ ),
+ );
+
+ const _progress = uploadProgress.current.reduce(
+ (acc, progress) => acc + progress,
+ 0,
+ );
+ },
+ onError: (error) => {
+ setUploads((prev) =>
+ prev.filter(
+ (upload) => upload.uploadId !== newUploads[index].uploadId,
+ ),
+ );
+
+ setRejectedFiles((prev) => [
+ { fileName: file.name, message: "Error uploading file" },
+ ...prev,
+ ]);
+ },
+ ownerId: (session?.user as CustomUser).id,
+ teamId: teamInfo?.currentTeam?.id as string,
+ numPages,
+ relativePath: path.substring(0, path.lastIndexOf("/")),
+ });
+
+ const uploadResult = await complete;
+
+ let contentType = uploadResult.fileType;
+ let supportedFileType = getSupportedContentType(contentType) ?? "";
+
+ if (
+ uploadResult.fileName.endsWith(".dwg") ||
+ uploadResult.fileName.endsWith(".dxf")
+ ) {
+ supportedFileType = "cad";
+ contentType = `image/vnd.${uploadResult.fileName.split(".").pop()}`;
+ }
+
+ if (uploadResult.fileName.endsWith(".xlsm")) {
+ supportedFileType = "sheet";
+ contentType = "application/vnd.ms-excel.sheet.macroEnabled.12";
+ }
+
+ if (
+ uploadResult.fileName.endsWith(".kml") ||
+ uploadResult.fileName.endsWith(".kmz")
+ ) {
+ supportedFileType = "map";
+ contentType = `application/vnd.google-earth.${uploadResult.fileName.endsWith(".kml") ? "kml+xml" : "kmz"}`;
+ }
+
+ const documentData: DocumentData = {
+ key: uploadResult.id,
+ supportedFileType: supportedFileType,
+ name: file.name,
+ storageType: DocumentStorageType.S3_PATH,
+ contentType: contentType,
+ fileSize: file.size,
+ };
+
+ const fileUploadPathName = file?.whereToUploadPath;
+ const dataroomUploadPathName = file?.dataroomUploadPath;
+
+ const response = await createDocument({
+ documentData,
+ teamId: teamInfo?.currentTeam?.id as string,
+ numPages: uploadResult.numPages,
+ folderPathName: fileUploadPathName,
+ });
+
+ // add the new document to the list
+ mutate(`/api/teams/${teamInfo?.currentTeam?.id}/documents`);
+
+ fileUploadPathName &&
+ mutate(
+ `/api/teams/${teamInfo?.currentTeam?.id}/folders/documents/${fileUploadPathName}`,
+ );
+
+ const document = await response.json();
+ let dataroomResponse;
+ if (dataroomId) {
+ try {
+ dataroomResponse = await fetch(
+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ documentId: document.id,
+ folderPathName: dataroomUploadPathName || fileUploadPathName,
+ }),
+ },
+ );
+
+ if (!dataroomResponse?.ok) {
+ const { message } = await dataroomResponse.json();
+ console.error(
+ "An error occurred while adding document to the dataroom: ",
+ message,
+ );
+ return;
+ }
+
+ mutate(
+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents`,
+ );
+ (dataroomUploadPathName || fileUploadPathName) &&
+ mutate(
+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders/documents/${dataroomUploadPathName || fileUploadPathName}`,
+ );
+ } catch (error) {
+ console.error(
+ "An error occurred while adding document to the dataroom: ",
+ error,
+ );
+ }
+ }
+
+ // update progress to 100%
+ setUploads((prevUploads) =>
+ prevUploads.map((upload) =>
+ upload.uploadId === newUploads[index].uploadId
+ ? { ...upload, progress: 100, documentId: document.id }
+ : upload,
+ ),
+ );
+
+ analytics.capture("Document Added", {
+ documentId: document.id,
+ name: document.name,
+ numPages: document.numPages,
+ path: router.asPath,
+ type: document.type,
+ contentType: document.contentType,
+ teamId: teamInfo?.currentTeam?.id,
+ bulkupload: true,
+ dataroomId: dataroomId,
+ $set: {
+ teamId: teamInfo?.currentTeam?.id,
+ teamPlan: plan,
+ },
+ });
+ const dataroomDocumentId = dataroomResponse?.ok
+ ? (await dataroomResponse.json()).id
+ : null;
+
+ return { ...document, dataroomDocumentId: dataroomDocumentId };
+ });
+
+ const documents = Promise.all(uploadPromises).finally(() => {
+ /* If it a parentFolder was created prior to the upload, we would need to update that
+ how many documents and folders does this folder contain rather than displaying 0
+ */
+
+ mutate(
+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}?root=true`,
+ );
+ mutate(`/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}`);
+ folderPathName &&
+ mutate(
+ `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/${folderPathName}`,
+ );
+ });
+ const uploadedDocuments = await documents;
+ const dataroomDocuments = uploadedDocuments.map((document) => ({
+ documentId: document.id,
+ dataroomDocumentId: document.dataroomDocumentId,
+ fileName: document.name,
+ }));
+ onUploadSuccess?.(dataroomDocuments);
+ },
+ [
+ onUploadStart,
+ onUploadProgress,
+ endpointTargetType,
+ fileSizeLimits,
+ isFree,
+ isTrial,
+ ],
+ );
+
+ const getFilesFromEvent = useCallback(
+ async (event: DropEvent) => {
+ // This callback also run when event.type =`dragenter`. We only need to compute files when the event.type is `drop`.
+ if ("type" in event && event.type !== "drop" && event.type !== "change") {
+ return [];
+ }
+
+ let filesToBePassedToOnDrop: FileWithPaths[] = [];
+
+ /** *********** START OF `traverseFolder` *********** */
+ const traverseFolder = async (
+ entry: FileSystemEntry,
+ parentPathOfThisEntry?: string,
+ dataroomParentPath?: string,
+ ): Promise<FileWithPaths[]> => {
+ /**
+ * Summary of this function:
+ * 1. if it find a folder then corresponding folder will be created at backend.
+ * 2. Smoothly handles the deeply nested folders.
+ * 3. Upon folder creation it assign the path and whereToUploadPath to each entry. (Those values will be helpful for `onDrop` to upload document correctly)
+ */
+
+ let files: FileWithPaths[] = [];
+
+ if (isSystemFile(entry.name)) {
+ return files;
+ }
+
+ if (entry.isDirectory) {
+ /**
+ * Let's create the folder.
+ * Fact that reader can skip: For Consistency, child files will only be pushed if folder successfully gets created.
+ */
+ try {
+ // An empty folder name can cause the unexpected url problems.
+ if (entry.name.trim() === "") {
+ setRejectedFiles((prev) => [
+ {
+ fileName: entry.name,
+ message: "Folder name cannot be empty",
+ },
+ ...prev,
+ ]);
+ throw new Error("Folder name cannot be empty");
+ }
+
+ if (!teamInfo?.currentTeam?.id) {
+ /** This case probably may not happen */
+ setRejectedFiles((prev) => [
+ {
+ fileName: "Unknown Team",
+ message: "Team Id not found",
+ },
+ ...prev,
+ ]);
+ throw new Error("No team found");
+ }
+
+ // Create folder in main documents if not in dataroom
+ if (!dataroomId) {
+ // Create folder in main documents only
+ const { path: folderPath } = await createFolderInMainDocs({
+ teamId: teamInfo.currentTeam.id,
+ name: entry.name,
+ path: parentPathOfThisEntry ?? folderPathName,
+ });
+
+ analytics.capture("Folder Added", { folderName: entry.name });
+
+ const dirReader = (
+ entry as FileSystemDirectoryEntry
+ ).createReader();
+ const subEntries = await new Promise<FileSystemEntry[]>(
+ (resolve) => dirReader.readEntries(resolve),
+ );
+
+ const filteredSubEntries = subEntries.filter(
+ (subEntry) => !isSystemFile(subEntry.name),
+ );
+
+ const resolvedFolderPath = folderPath.startsWith("/")
+ ? folderPath.slice(1)
+ : folderPath;
+
+ for (const subEntry of filteredSubEntries) {
+ files.push(
+ ...(await traverseFolder(
+ subEntry,
+ resolvedFolderPath,
+ undefined,
+ )),
+ );
+ }
+ } else {
+ const isFirstLevelFolder =
+ (parentPathOfThisEntry ?? folderPathName) === folderPathName;
+
+ const {
+ parentDataroomPath: targetParentDataroomPath,
+ parentMainDocsPath: targetParentMainDocsPath,
+ } = determineFolderPaths({
+ currentDataroomPath: dataroomParentPath ?? folderPathName,
+ currentMainDocsPath: parentPathOfThisEntry,
+ isFirstLevelFolder,
+ });
+
+ const { dataroomPath, mainDocsPath } = await createFolderInBoth({
+ teamId: teamInfo.currentTeam.id,
+ dataroomId,
+ name: entry.name,
+ parentMainDocsPath: targetParentMainDocsPath,
+ parentDataroomPath: targetParentDataroomPath,
+ setRejectedFiles,
+ analytics,
+ });
+
+ const dirReader = (
+ entry as FileSystemDirectoryEntry
+ ).createReader();
+ const subEntries = await new Promise<FileSystemEntry[]>(
+ (resolve) => dirReader.readEntries(resolve),
+ );
+
+ const filteredSubEntries = subEntries.filter(
+ (subEntry) => !isSystemFile(subEntry.name),
+ );
+
+ // Use the resolved paths for all children
+ const resolvedMainDocsPath = mainDocsPath.startsWith("/")
+ ? mainDocsPath.slice(1)
+ : mainDocsPath;
+ const resolvedDataroomPath = dataroomPath.startsWith("/")
+ ? dataroomPath.slice(1)
+ : dataroomPath;
+
+ for (const subEntry of filteredSubEntries) {
+ files.push(
+ ...(await traverseFolder(
+ subEntry,
+ resolvedMainDocsPath,
+ resolvedDataroomPath,
+ )),
+ );
+ }
+ }
+ } catch (error) {
+ console.error(
+ "An error occurred while creating the folder: ",
+ error,
+ );
+ setRejectedFiles((prev) => [
+ {
+ fileName: entry.name,
+ message: "Failed to create the folder",
+ },
+ ...prev,
+ ]);
+ }
+ } else if (entry.isFile) {
+ if (isSystemFile(entry.name)) {
+ return files;
+ }
+
+ let file = await new Promise<FileWithPaths>((resolve) =>
+ (entry as FileSystemFileEntry).file(resolve),
+ );
+
+ /** In some browsers e.g firefox is not able to detect the file type. (This only happens when user upload folder) */
+ const browserFileTypeCompatibilityIssue = file.type === "";
+
+ if (browserFileTypeCompatibilityIssue) {
+ const fileExtension = file.name.split(".").pop()?.toLowerCase();
+ let correctMimeType: string | undefined;
+ if (fileExtension) {
+ // Iterate through acceptableDropZoneFileTypes to find the MIME type for the extension
+ for (const [mime, extsUntyped] of Object.entries(
+ acceptableDropZoneFileTypes,
+ )) {
+ const exts = extsUntyped as string[]; // Explicitly type exts
+ if (
+ exts.some((ext) => ext.toLowerCase() === "." + fileExtension)
+ ) {
+ correctMimeType = mime;
+ break;
+ }
+ }
+ }
+
+ if (correctMimeType) {
+ // if we can't do like ```file.type = fileType``` because of [Error: Setting getter-only property "type"]
+ // The following is the only best way to resolve the problem
+ file = new File([file], file.name, {
+ type: correctMimeType,
+ lastModified: file.lastModified,
+ });
+ }
+ }
+
+ // Reason of removing "/" because webkitRelativePath doesn't start with "/"
+ file.path = entry.fullPath.startsWith("/")
+ ? entry.fullPath.substring(1)
+ : entry.fullPath;
+
+ file.whereToUploadPath = parentPathOfThisEntry ?? folderPathName;
+ file.dataroomUploadPath = dataroomParentPath;
+
+ files.push(file);
+ }
+
+ return files;
+ };
+ /** *********** END OF `traverseFolder` *********** */
+
+ if ("dataTransfer" in event && event.dataTransfer) {
+ const items = event.dataTransfer.items;
+
+ const fileResults = await Promise.all(
+ Array.from(items, (item) => {
+ // MDN Note: This function is implemented as webkitGetAsEntry() in non-WebKit browsers including Firefox at this time; it may be renamed to getAsEntry() in the future, so you should code defensively, looking for both.
+ const entry =
+ (typeof item?.webkitGetAsEntry === "function" &&
+ item.webkitGetAsEntry()) ??
+ (typeof (item as any)?.getAsEntry === "function" &&
+ (item as any).getAsEntry()) ??
+ null;
+ return entry
+ ? traverseFolder(
+ entry,
+ folderPathName,
+ dataroomId ? folderPathName : undefined,
+ )
+ : [];
+ }),
+ );
+ fileResults.forEach((fileResult) =>
+ filesToBePassedToOnDrop.push(...fileResult),
+ );
+ } else if (
+ "target" in event &&
+ event.target &&
+ event.target instanceof HTMLInputElement &&
+ event.target.files
+ ) {
+ for (let i = 0; i < event.target.files.length; i++) {
+ const file: FileWithPaths = event.target.files[i];
+ file.path = file.name;
+ file.whereToUploadPath = folderPathName;
+ file.dataroomUploadPath = folderPathName;
+ filesToBePassedToOnDrop.push(event.target.files[i]);
+ }
+ }
+
+ return filesToBePassedToOnDrop;
+ },
+ [folderPathName, endpointTargetType, teamInfo],
+ );
+
+ const { getRootProps, getInputProps, isDragActive } = useDropzone({
+ accept: acceptableDropZoneFileTypes,
+ multiple: true,
+ // maxSize: maxSize * 1024 * 1024, // 30 MB
+ maxFiles: fileSizeLimits.maxFiles ?? 150,
+ onDrop,
+ onDropRejected,
+ getFilesFromEvent,
+ });
+
+ return (
+ <div
+ {...getRootProps({ onClick: (evt) => evt.stopPropagation() })}
+ className={cn(
+ "relative",
+ dataroomId ? "min-h-[calc(100vh-350px)]" : "min-h-[calc(100vh-270px)]",
+ )}
+ >
+ <div
+ className={cn(
+ "absolute inset-0 z-40 -m-1 rounded-lg border-2 border-dashed",
+ isDragActive
+ ? "pointer-events-auto border-primary/50 bg-gray-100/75 backdrop-blur-sm dark:bg-gray-800/75"
+ : "pointer-events-none border-none",
+ )}
+ >
+ <input
+ {...getInputProps()}
+ name="file"
+ id="upload-multi-files-zone"
+ className="sr-only"
+ />
+
+ {isDragActive && (
+ <div className="sticky top-1/2 z-50 -translate-y-1/2 px-2">
+ <div className="flex justify-center">
+ <div className="inline-flex flex-col rounded-lg bg-background/95 px-6 py-4 text-center ring-1 ring-gray-900/5 dark:bg-gray-900/95 dark:ring-white/10">
+ <span className="font-medium text-foreground">
+ Drop your file(s) here
+ </span>
+ <p className="mt-1 text-xs leading-5 text-muted-foreground">
+ {isFree && !isTrial
+ ? `Only *.pdf, *.xls, *.xlsx, *.csv, *.ods, *.png, *.jpeg, *.jpg`
+ : `Only *.pdf, *.pptx, *.docx, *.xlsx, *.xls, *.csv, *.ods, *.ppt, *.odp, *.doc, *.odt, *.dwg, *.dxf, *.png, *.jpg, *.jpeg, *.mp4, *.mov, *.avi, *.webm, *.ogg`}
+ </p>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {children}
+ </div>
+ );
+}
diff --git a/lib/slack/client.ts b/lib/slack/client.ts
new file mode 100644
index 00000000..682483d0
--- /dev/null
+++ b/lib/slack/client.ts
@@ -0,0 +1,197 @@
+import { SlackOAuthResponse, SlackChannel, SlackMessage, SlackWorkspaceInfo } from './types';
+
+export class SlackClient {
+ private clientId: string;
+ private clientSecret: string;
+ private baseUrl = 'https://slack.com/api';
+ private oauthUrl = 'https://slack.com/oauth/v2/authorize';
+
+ constructor() {
+ this.clientId = process.env.SLACK_CLIENT_ID!;
+ this.clientSecret = process.env.SLACK_CLIENT_SECRET!;
+
+ if (!this.clientId || !this.clientSecret) {
+ throw new Error('SLACK_CLIENT_ID and SLACK_CLIENT_SECRET must be set');
+ }
+ }
+
+ /**
+ * Get OAuth URL for Slack app installation
+ */
+ getOAuthUrl(state: string, redirectUri: string): string {
+ const params = new URLSearchParams({
+ client_id: this.clientId,
+ scope: 'channels:read,groups:read,mpim:read,im:read,chat:write,chat:write.public,team:read,users:read,users:read.email',
+ redirect_uri: redirectUri,
+ state: state,
+ });
+
+ // 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;
+ }
+
+ /**
+ * Exchange authorization code for access token
+ */
+ async exchangeCodeForToken(code: string, redirectUri: string): Promise<SlackOAuthResponse> {
+ const response = await fetch(`${this.baseUrl}/oauth.v2.access`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ body: new URLSearchParams({
+ client_id: this.clientId,
+ client_secret: this.clientSecret,
+ code: code,
+ redirect_uri: redirectUri,
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error(`Slack OAuth failed: ${response.statusText}`);
+ }
+
+ const data = await response.json();
+
+ if (!data.ok) {
+ throw new Error(`Slack OAuth error: ${data.error}`);
+ }
+
+ return data;
+ }
+
+ /**
+ * Get workspace information
+ */
+ async getWorkspaceInfo(accessToken: string): Promise<SlackWorkspaceInfo> {
+ const response = await fetch(`${this.baseUrl}/team.info`, {
+ headers: {
+ 'Authorization': `Bearer ${accessToken}`,
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to get workspace info: ${response.statusText}`);
+ }
+
+ const data = await response.json();
+
+ if (!data.ok) {
+ throw new Error(`Slack API error: ${data.error}`);
+ }
+
+ return {
+ id: data.team.id,
+ name: data.team.name,
+ url: data.team.url,
+ domain: data.team.domain,
+ };
+ }
+
+ /**
+ * Get bot information
+ */
+ async getBotInfo(accessToken: string): Promise<{ id: string; name: string }> {
+ const response = await fetch(`${this.baseUrl}/auth.test`, {
+ headers: {
+ 'Authorization': `Bearer ${accessToken}`,
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to get bot info: ${response.statusText}`);
+ }
+
+ const data = await response.json();
+
+ if (!data.ok) {
+ throw new Error(`Slack API error: ${data.error}`);
+ }
+
+ return {
+ id: data.bot_id,
+ name: data.user,
+ };
+ }
+
+ /**
+ * Get list of channels
+ */
+ async getChannels(accessToken: string): Promise<SlackChannel[]> {
+ try {
+ const response = await fetch(`${this.baseUrl}/conversations.list?types=public_channel,private_channel`, {
+ headers: {
+ 'Authorization': `Bearer ${accessToken}`,
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to get channels: ${response.statusText}`);
+ }
+
+ const data = await response.json();
+
+ if (!data.ok) {
+ throw new Error(`Slack API error: ${data.error}`);
+ }
+
+ return data.channels.map((channel: any) => ({
+ id: channel.id,
+ name: channel.name,
+ is_private: channel.is_private,
+ is_archived: channel.is_archived,
+ is_member: channel.is_member,
+ }));
+ } catch (error) {
+ console.error('SlackClient.getChannels error:', error);
+ console.error('Access token (first 10 chars):', accessToken ? accessToken.substring(0, 10) + '...' : 'undefined');
+ throw error;
+ }
+ }
+
+ /**
+ * Send message to Slack channel
+ */
+ async sendMessage(accessToken: string, message: SlackMessage): Promise<{ ok: boolean; ts?: string; error?: string }> {
+ const response = await fetch(`${this.baseUrl}/chat.postMessage`, {
+ method: 'POST',
+ headers: {
+ 'Authorization': `Bearer ${accessToken}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(message),
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to send message: ${response.statusText}`);
+ }
+
+ const data = await response.json();
+
+ if (!data.ok) {
+ return {
+ ok: false,
+ error: data.error,
+ };
+ }
+
+ return {
+ ok: true,
+ ts: data.ts,
+ };
+ }
+}
+
+// Export singleton instance
+export const slackClient = new SlackClient();
\ No newline at end of file
diff --git a/lib/slack/digest-processor.ts b/lib/slack/digest-processor.ts
new file mode 100644
index 00000000..723cf488
--- /dev/null
+++ b/lib/slack/digest-processor.ts
@@ -0,0 +1,287 @@
+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.includes('digest'));
+
+ 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.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.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
new file mode 100644
index 00000000..74b3146a
--- /dev/null
+++ b/lib/slack/events.ts
@@ -0,0 +1,160 @@
+import { SlackClient } from "./client";
+import { createSlackMessage } from "./templates";
+import prisma from "@/lib/prisma";
+
+export interface SlackEventData {
+ teamId: string;
+ eventType: string;
+ documentId?: string;
+ dataroomId?: string;
+ linkId?: string;
+ viewerEmail?: string;
+ viewerId?: string;
+ userId?: string;
+ metadata?: Record<string, any>;
+}
+
+export class SlackEventManager {
+ private client: SlackClient;
+
+ constructor() {
+ this.client = new SlackClient();
+ }
+
+
+ async processEvent(eventData: SlackEventData): Promise<void> {
+ try {
+
+ const integration = await this.getSlackIntegration(eventData.teamId);
+ if (!integration || !integration.enabled) {
+ 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 {
+ await this.storeForDigest(eventData, integration);
+ }
+
+ } catch (error) {
+ console.error('Error processing Slack event:', error);
+ }
+ }
+
+ /**
+ * Send instant notification for an event
+ */
+ private async sendInstantNotification(
+ eventData: SlackEventData,
+ integration: any
+ ): 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);
+ 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);
+ }
+ }
+ } catch (error) {
+ console.error('Error sending instant notification:', error);
+ }
+ }
+
+ 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) {
+ return await prisma.slackIntegration.findFirst({
+ where: { teamId, enabled: true },
+ });
+ }
+
+ /**
+ * Check if event type is enabled in integration config
+ */
+ private isEventTypeEnabled(
+ eventType: string,
+ integration: any
+ ): boolean {
+ const notificationTypes = integration.notificationTypes || {};
+ return notificationTypes[eventType] || false;
+ }
+
+ /**
+ * Get channels to send notifications to
+ */
+ private async getNotificationChannels(
+ eventData: SlackEventData,
+ integration: any
+ ): Promise<any[]> {
+ const enabledChannels = integration.enabledChannels || {};
+ return Object.values(enabledChannels)
+ .filter((channel: any) => channel.enabled)
+ .filter((channel: any) => channel.notificationTypes && channel.notificationTypes.includes(eventData.eventType));
+ }
+
+}
+
+
+export const slackEventManager = new SlackEventManager();
+
+export async function notifyDocumentView(data: Omit<SlackEventData, 'eventType'>) {
+ await slackEventManager.processEvent({ ...data, eventType: 'document_view' });
+}
+
+export async function notifyDataroomAccess(data: Omit<SlackEventData, 'eventType'>) {
+ await slackEventManager.processEvent({ ...data, eventType: 'dataroom_access' });
+}
+
+
+export async function notifyDocumentDownload(data: Omit<SlackEventData, 'eventType'>) {
+ await slackEventManager.processEvent({ ...data, eventType: 'document_download' });
+}
+
+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
new file mode 100644
index 00000000..c3b55445
--- /dev/null
+++ b/lib/slack/schedule-manager.ts
@@ -0,0 +1,151 @@
+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);
+
+ if (integration.frequency === 'instant') {
+ await this.cleanupOldNotifications(integration.id);
+ return;
+ }
+
+ 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,
+ timezone: timezone,
+ 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);
+ throw error;
+ }
+ }
+
+ /**
+ * Delete a schedule for a Slack integration
+ */
+ 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);
+ console.log(`Deleted schedule for integration ${integrationId}`);
+ } else {
+ console.log(`No schedule found for integration ${integrationId}`);
+ }
+
+ } catch (error) {
+ console.error(`Error deleting schedule for integration ${integrationId}:`, error);
+ }
+ }
+
+ /**
+ * Clean up old notifications when switching from instant to digest
+ */
+ 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) {
+ console.warn(`Invalid time format: ${time}, using default 10:00`);
+ 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
new file mode 100644
index 00000000..c44c8110
--- /dev/null
+++ b/lib/slack/templates.ts
@@ -0,0 +1,746 @@
+import { SlackEventData } from "./events";
+
+export interface SlackChannelConfig {
+ id: string;
+ name: string;
+ enabled: boolean;
+ notificationTypes: string[];
+}
+
+export interface SlackMessage {
+ channel?: string;
+ text?: string;
+ blocks?: any[];
+ thread_ts?: string;
+ unfurl_links?: boolean;
+ unfurl_media?: boolean;
+}
+
+export async function createSlackMessage(
+ eventData: SlackEventData,
+ channel: SlackChannelConfig
+): Promise<SlackMessage | null> {
+ try {
+ switch (eventData.eventType) {
+ case 'document_view':
+ return await createDocumentViewMessage(eventData);
+ case 'dataroom_access':
+ return await createDataroomAccessMessage(eventData);
+ case 'document_download':
+ return await createDocumentDownloadMessage(eventData);
+ case 'document_reaction':
+ return await createDocumentReactionMessage(eventData);
+ default:
+ return null;
+ }
+ } catch (error) {
+ console.error('Error creating Slack message:', error);
+ return null;
+ }
+}
+
+/**
+ * Document View Message Template
+ */
+async function createDocumentViewMessage(eventData: SlackEventData): Promise<SlackMessage> {
+ const document = eventData.documentId ? await getDocumentInfo(eventData.documentId) : null;
+ const dataroom = eventData.dataroomId ? await getDataroomInfo(eventData.dataroomId) : null;
+ const link = eventData.linkId ? await getLinkInfo(eventData.linkId) : null;
+
+ const viewerDisplay = eventData.viewerEmail || 'Anonymous';
+ const viewerMention = eventData.viewerEmail ? `<mailto:${eventData.viewerEmail}|${viewerDisplay}>` : viewerDisplay;
+
+ let accessContext = "";
+ if (eventData.dataroomId && dataroom) {
+ accessContext = `in dataroom "${dataroom.name}"`;
+ } else if (link?.name) {
+ accessContext = `via shared link "${link.name}"`;
+ } else {
+ accessContext = `via shared link "Link ${link?.id.slice(0, 5)}"`;
+ }
+
+ return {
+ text: `Your document has been viewed: ${document?.name || 'Unknown document'} by ${viewerDisplay} ${accessContext}`,
+ blocks: [
+ {
+ type: "header",
+ text: {
+ type: "plain_text",
+ text: "Your document has been viewed",
+ emoji: false
+ }
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Document:*\n${document?.name || 'Unknown'}`
+ },
+ {
+ type: "mrkdwn",
+ text: `*Viewer:*\n${viewerMention}`
+ }
+ ]
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: dataroom?.name
+ ? `*Dataroom:*\n${dataroom.name}`
+ : link?.name
+ ? `*Shared Link:*\n${link.name}`
+ : `*Access:*\nDirect access`
+ },
+ {
+ type: "mrkdwn",
+ text: `*Time:*\n${new Date().toLocaleString()}`
+ }
+ ]
+ },
+ {
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: eventData.dataroomId
+ ? `Viewed document in dataroom "${dataroom?.name || 'Unknown'}"`
+ : link?.name
+ ? `Viewed document via shared link "${link.name}"`
+ : `Viewed document via shared link "Link ${link?.id.slice(0, 5)}"`
+ }
+ ]
+ },
+ {
+ type: "actions",
+ elements: [
+ {
+ type: "button",
+ text: {
+ type: "plain_text",
+ text: "View document",
+ emoji: true
+ },
+ style: "primary",
+ url: eventData.documentId
+ ? `${process.env.NEXTAUTH_URL}/documents/${eventData.documentId}`
+ : `${process.env.NEXTAUTH_URL}/dashboard`
+ }
+ ]
+ }
+ ]
+ };
+}
+
+/**
+ * Dataroom Access Message Template
+ */
+async function createDataroomAccessMessage(eventData: SlackEventData): Promise<SlackMessage> {
+ const dataroom = eventData.dataroomId ? await getDataroomInfo(eventData.dataroomId) : null;
+ const link = eventData.linkId ? await getLinkInfo(eventData.linkId) : null;
+
+ const viewerDisplay = eventData.viewerEmail || 'Anonymous';
+ const viewerMention = eventData.viewerEmail ? `<mailto:${eventData.viewerEmail}|${viewerDisplay}>` : viewerDisplay;
+
+
+ const accessContext = link?.name ? `via shared link "${link.name}"` : `via shared link "Link ${link?.id.slice(0, 5)}"`;
+
+ return {
+ text: `Your dataroom has been viewed: ${dataroom?.name || 'Unknown dataroom'} by ${viewerDisplay} ${accessContext}`,
+ blocks: [
+ {
+ type: "header",
+ text: {
+ type: "plain_text",
+ text: "Your dataroom has been viewed",
+ emoji: false
+ }
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Dataroom:*\n${dataroom?.name || 'Unknown'}`
+ },
+ {
+ type: "mrkdwn",
+ text: `*Viewer:*\n${viewerMention}`
+ }
+ ]
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: link?.name
+ ? `*Shared Link:*\n${link.name}`
+ : `*Access:*\nDirect access`
+ },
+ {
+ type: "mrkdwn",
+ text: `*Time:*\n${new Date().toLocaleString()}`
+ }
+ ]
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Documents:*\n${dataroom?.documentCount || 0} documents`
+ }
+ ]
+ },
+ {
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: link?.name
+ ? `Dataroom accessed via shared link "${link.name}"`
+ : `Dataroom accessed via shared link "Link ${link?.id.slice(0, 5)}"`
+ }
+ ]
+ },
+ {
+ type: "actions",
+ elements: [
+ {
+ type: "button",
+ text: {
+ type: "plain_text",
+ text: "View dataroom",
+ emoji: true
+ },
+ style: "primary",
+ url: eventData.dataroomId
+ ? `${process.env.NEXTAUTH_URL}/datarooms/${eventData.dataroomId}`
+ : `${process.env.NEXTAUTH_URL}/dashboard`
+ }
+ ]
+ }
+ ]
+ };
+}
+
+
+
+/**
+ * Document Download Message Template
+ */
+async function createDocumentDownloadMessage(eventData: SlackEventData): Promise<SlackMessage> {
+ const document = eventData.documentId ? await getDocumentInfo(eventData.documentId) : null;
+ const dataroom = eventData.dataroomId ? await getDataroomInfo(eventData.dataroomId) : null;
+ const link = eventData.linkId ? await getLinkInfo(eventData.linkId) : null;
+
+ const viewerDisplay = eventData.viewerEmail || 'Anonymous';
+ const viewerMention = eventData.viewerEmail ? `<mailto:${eventData.viewerEmail}|${viewerDisplay}>` : viewerDisplay;
+
+
+ const isBulkDownload = eventData.metadata?.isBulkDownload;
+ const isFolderDownload = eventData.metadata?.isFolderDownload;
+ const folderName = eventData.metadata?.folderName;
+ const documentCount = eventData.metadata?.documentCount;
+
+ let downloadType = "Document";
+ let downloadContext = "";
+
+ if (isBulkDownload) {
+ downloadType = "Dataroom";
+ downloadContext = `(${documentCount} documents)`;
+ } else if (isFolderDownload) {
+ downloadType = "Folder";
+ downloadContext = `"${folderName}" (${documentCount} documents)`;
+ } else if (dataroom) {
+ downloadContext = `from dataroom "${dataroom.name}"`;
+ } else if (link?.name) {
+ downloadContext = `via shared link "${link.name}"`;
+ } else {
+ downloadContext = `via shared link "Link ${link?.id.slice(0, 5)}"`;
+ }
+
+ return {
+ text: `${downloadType} has been downloaded: ${document?.name || downloadContext} by ${viewerDisplay}`,
+ blocks: [
+ {
+ type: "header",
+ text: {
+ type: "plain_text",
+ text: `${downloadType} has been downloaded`,
+ emoji: false
+ }
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: document?.name
+ ? `*${downloadType}:*\n${document.name}`
+ : `*${downloadType}:*\n${downloadContext}`
+ },
+ {
+ type: "mrkdwn",
+ text: `*Downloaded by:*\n${viewerMention}`
+ }
+ ]
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: dataroom?.name
+ ? `*From Dataroom:*\n${dataroom.name}`
+ : link?.name
+ ? `*Shared Link:*\n${link.name}`
+ : `*Context:*\n${downloadContext}`
+ },
+ {
+ type: "mrkdwn",
+ text: `*Time:*\n${new Date().toLocaleString()}`
+ }
+ ]
+ },
+ {
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: isBulkDownload
+ ? `Bulk dataroom download`
+ : isFolderDownload
+ ? `Folder download`
+ : link?.name
+ ? `Document download via shared link "${link.name}"`
+ : `Document download via shared link "Link ${link?.id.slice(0, 5)}"`
+ }
+ ]
+ },
+ {
+ type: "actions",
+ elements: [
+ {
+ type: "button",
+ text: {
+ type: "plain_text",
+ text: "View activity",
+ emoji: true
+ },
+ style: "primary",
+ url: eventData.dataroomId
+ ? `${process.env.NEXTAUTH_URL}/datarooms/${eventData.dataroomId}`
+ : eventData.documentId
+ ? `${process.env.NEXTAUTH_URL}/documents/${eventData.documentId}`
+ : `${process.env.NEXTAUTH_URL}/dashboard`
+ }
+ ]
+ }
+ ]
+ };
+}
+
+/**
+ * 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);
+
+ // Get detailed activity breakdown
+ const activityDetails = await generateActivityDetails(events, teamId);
+
+ 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 }>,
+ teamId: string
+): 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;
+ }> = [];
+
+ // Process each event
+ for (const { eventData, count } of events) {
+ // Handle multiple occurrences of the same event
+ for (let i = 0; i < count; i++) {
+ if (eventData.documentId) {
+ const doc = await getDocumentInfo(eventData.documentId);
+ documentActivities.push({
+ eventType: eventData.eventType,
+ documentName: doc?.name || 'Unknown Document',
+ viewerEmail: eventData.viewerEmail
+ });
+ } else if (eventData.dataroomId) {
+ const dataroom = await getDataroomInfo(eventData.dataroomId);
+ dataroomActivities.push({
+ dataroomName: dataroom?.name || 'Unknown Dataroom',
+ viewerEmail: eventData.viewerEmail
+ });
+ } else if (eventData.linkId) {
+ const link = await getLinkInfo(eventData.linkId);
+ linkActivities.push({
+ eventType: eventData.eventType,
+ linkName: link?.name || 'Unknown Link',
+ 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) {
+ try {
+ const prisma = (await import("@/lib/prisma")).default;
+ return await prisma.document.findUnique({
+ where: { id: documentId },
+ select: {
+ id: true,
+ name: true,
+ description: true,
+ type: true,
+ },
+ });
+ } catch (error) {
+ console.error('Error fetching document info:', error);
+ return null;
+ }
+}
+
+async function getDataroomInfo(dataroomId: string) {
+ try {
+ const prisma = (await import("@/lib/prisma")).default;
+ return await prisma.dataroom.findUnique({
+ where: { id: dataroomId },
+ select: {
+ id: true,
+ name: true,
+ description: true,
+ _count: {
+ select: {
+ documents: true,
+ },
+ },
+ },
+ }).then(dataroom => dataroom ? {
+ ...dataroom,
+ documentCount: dataroom._count.documents,
+ } : null);
+ } catch (error) {
+ console.error('Error fetching dataroom info:', error);
+ return null;
+ }
+}
+
+async function getUserInfo(userId: string) {
+ try {
+ const prisma = (await import("@/lib/prisma")).default;
+ 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 {
+ const prisma = (await import("@/lib/prisma")).default;
+ 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 {
+ const prisma = (await import("@/lib/prisma")).default;
+ return await prisma.link.findUnique({
+ where: { id: linkId },
+ select: {
+ id: true,
+ name: true,
+ linkType: true,
+ },
+ });
+ } catch (error) {
+ console.error('Error fetching link info:', error);
+ return null;
+ }
+}
+
+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';
+ }
+}
\ No newline at end of file
diff --git a/lib/slack/timezone-utils.ts b/lib/slack/timezone-utils.ts
new file mode 100644
index 00000000..c0e6e115
--- /dev/null
+++ b/lib/slack/timezone-utils.ts
@@ -0,0 +1,162 @@
+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
new file mode 100644
index 00000000..1c208f62
--- /dev/null
+++ b/lib/slack/types.ts
@@ -0,0 +1,78 @@
+export interface SlackWorkspaceInfo {
+ id: string;
+ name: string;
+ url: string;
+ domain: string;
+}
+
+export interface SlackBotInfo {
+ id: string;
+ name: string;
+ team_id: string;
+}
+
+export interface SlackChannel {
+ id: string;
+ name: string;
+ is_private: boolean;
+ is_archived: boolean;
+ is_member?: boolean;
+}
+
+export interface SlackOAuthResponse {
+ ok: boolean;
+ access_token: string;
+ token_type: string;
+ scope: string;
+ bot_user_id: string;
+ team: {
+ name: string;
+ id: string;
+ };
+ enterprise?: {
+ name: string;
+ id: string;
+ };
+ authed_user: {
+ id: string;
+ scope: string;
+ access_token: string;
+ token_type: string;
+ };
+}
+
+export interface SlackMessage {
+ channel: string;
+ text?: string;
+ blocks?: any[];
+ thread_ts?: string;
+ unfurl_links?: boolean;
+ unfurl_media?: boolean;
+}
+
+export interface SlackNotificationConfig {
+ document_view: boolean;
+ dataroom_access: boolean;
+ document_download: boolean;
+ document_reaction: boolean;
+}
+
+export interface SlackChannelConfig {
+ id: string;
+ name: string;
+ enabled: boolean;
+ 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
new file mode 100644
index 00000000..49ab3d46
--- /dev/null
+++ b/lib/trigger/slack-digest.ts
@@ -0,0 +1,22 @@
+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/package.json b/package.json
index 55bf1105..209be543 100644
--- a/package.json
+++ b/package.json
@@ -84,6 +84,7 @@
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"date-fns": "^3.6.0",
+ "date-fns-tz": "^3.2.0",
"eslint": "8.57.0",
"eslint-config-next": "^14.2.30",
"exceljs": "^4.4.0",
diff --git a/pages/api/debug/slack-schedules.ts b/pages/api/debug/slack-schedules.ts
new file mode 100644
index 00000000..c7361a4b
--- /dev/null
+++ b/pages/api/debug/slack-schedules.ts
@@ -0,0 +1,133 @@
+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
new file mode 100644
index 00000000..81e3d918
--- /dev/null
+++ b/pages/api/debug/trigger-digest.ts
@@ -0,0 +1,106 @@
+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 };
+
+ 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',
+ },
+ });
+
+ 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({
+ 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/links/download/bulk.ts b/pages/api/links/download/bulk.ts
index 4f6a3b08..68abe96e 100644
--- a/pages/api/links/download/bulk.ts
+++ b/pages/api/links/download/bulk.ts
@@ -7,6 +7,7 @@ import { ItemType, ViewType } from "@prisma/client";
import { getLambdaClientForTeam } from "@/lib/files/aws-client";
import prisma from "@/lib/prisma";
import { getIpAddress } from "@/lib/utils/ip";
+import { notifyDocumentDownload } from "@/lib/slack/events";
export const config = {
maxDuration: 180,
@@ -46,6 +47,7 @@ export default async function handle(
groupId: true,
dataroom: {
select: {
+ id: true,
teamId: true,
folders: {
select: {
@@ -271,7 +273,7 @@ export default async function handle(
// Use .file if watermark is enabled and document is PDF, otherwise use .originalFile
const fileKey =
view.link.enableWatermark &&
- doc.document.versions[0].type === "pdf"
+ doc.document.versions[0].type === "pdf"
? doc.document.versions[0].file
: (doc.document.versions[0].originalFile ??
doc.document.versions[0].file);
@@ -295,6 +297,25 @@ export default async function handle(
return res.status(404).json({ error: "No files to download" });
}
+ if (view.dataroom?.teamId) {
+ try {
+ await notifyDocumentDownload({
+ teamId: view.dataroom.teamId,
+ documentId: undefined, // Bulk download, no specific document
+ dataroomId: view.dataroom.id,
+ linkId,
+ viewerEmail: view.viewerEmail ?? undefined,
+ viewerId: undefined,
+ metadata: {
+ documentCount: downloadDocuments.length,
+ isBulkDownload: true,
+ },
+ });
+ } catch (error) {
+ console.error("Error sending Slack notification:", error);
+ }
+ }
+
// Get team-specific storage configuration
const teamId = view.dataroom!.teamId;
const [client, storageConfig] = await Promise.all([
@@ -311,16 +332,16 @@ export default async function handle(
folderStructure: folderStructure,
watermarkConfig: view.link.enableWatermark
? {
- enabled: true,
- config: view.link.watermarkConfig,
- viewerData: {
- email: view.viewerEmail,
- date: new Date(view.viewedAt).toLocaleDateString(),
- time: new Date(view.viewedAt).toLocaleTimeString(),
- link: view.link.name,
- ipAddress: getIpAddress(req.headers),
- },
- }
+ enabled: true,
+ config: view.link.watermarkConfig,
+ viewerData: {
+ email: view.viewerEmail,
+ date: new Date(view.viewedAt).toLocaleDateString(),
+ time: new Date(view.viewedAt).toLocaleTimeString(),
+ link: view.link.name,
+ ipAddress: getIpAddress(req.headers),
+ },
+ }
: { enabled: false },
}),
};
diff --git a/pages/api/links/download/dataroom-document.ts b/pages/api/links/download/dataroom-document.ts
index 1878ee8f..1341860d 100644
--- a/pages/api/links/download/dataroom-document.ts
+++ b/pages/api/links/download/dataroom-document.ts
@@ -5,6 +5,7 @@ import { ItemType, ViewType } from "@prisma/client";
import { getFile } from "@/lib/files/get-file";
import prisma from "@/lib/prisma";
import { getIpAddress } from "@/lib/utils/ip";
+import { notifyDocumentDownload } from "@/lib/slack/events";
export const config = {
maxDuration: 180,
@@ -44,6 +45,7 @@ export default async function handle(
watermarkConfig: true,
name: true,
permissionGroupId: true,
+ teamId: true,
},
},
groupId: true,
@@ -164,6 +166,23 @@ export default async function handle(
},
});
+ if (view.link.teamId) {
+ try {
+ await notifyDocumentDownload({
+ teamId: view.link.teamId,
+ documentId,
+ dataroomId: view.dataroom.id,
+ linkId,
+ viewerEmail: view.viewerEmail ?? undefined,
+ viewerId: view.viewerId ?? undefined,
+ });
+ } catch (error) {
+ console.error("Error sending Slack notification:", error);
+ }
+ } else {
+ console.log("No teamId found, skipping Slack notification");
+ }
+
const file =
view.link.enableWatermark &&
downloadDocuments[0].document!.versions[0].type === "pdf"
diff --git a/pages/api/links/download/dataroom-folder.ts b/pages/api/links/download/dataroom-folder.ts
index 8f1eb682..d42b8da4 100644
--- a/pages/api/links/download/dataroom-folder.ts
+++ b/pages/api/links/download/dataroom-folder.ts
@@ -8,6 +8,7 @@ import slugify from "@sindresorhus/slugify";
import { getLambdaClientForTeam } from "@/lib/files/aws-client";
import prisma from "@/lib/prisma";
import { getIpAddress } from "@/lib/utils/ip";
+import { notifyDocumentDownload } from "@/lib/slack/events";
export const config = {
maxDuration: 180,
@@ -295,6 +296,26 @@ export default async function handler(
};
}
+ if (view.link.teamId) {
+ try {
+ await notifyDocumentDownload({
+ teamId: view.link.teamId,
+ documentId: undefined,
+ dataroomId,
+ linkId,
+ viewerEmail: view.viewerEmail ?? undefined,
+ viewerId: undefined,
+ metadata: {
+ folderName: rootFolder.name,
+ documentCount: allDocuments.length,
+ isFolderDownload: true,
+ },
+ });
+ } catch (error) {
+ console.error("Error sending Slack notification:", error);
+ }
+ }
+
// Get team-specific storage configuration
const [client, storageConfig] = await Promise.all([
getLambdaClientForTeam(view.link.teamId!),
diff --git a/pages/api/links/download/index.ts b/pages/api/links/download/index.ts
index a04201cb..1f06528a 100644
--- a/pages/api/links/download/index.ts
+++ b/pages/api/links/download/index.ts
@@ -5,6 +5,7 @@ import { LinkType } from "@prisma/client";
import { getFile } from "@/lib/files/get-file";
import prisma from "@/lib/prisma";
import { getIpAddress } from "@/lib/utils/ip";
+import { notifyDocumentDownload } from "@/lib/slack/events";
export default async function handle(
req: NextApiRequest,
@@ -37,6 +38,7 @@ export default async function handle(
},
document: {
select: {
+ id: true,
teamId: true,
downloadOnly: true,
versions: {
@@ -97,6 +99,21 @@ export default async function handle(
data: { downloadedAt: new Date() },
});
+ if (view.document?.teamId) {
+ try {
+ await notifyDocumentDownload({
+ teamId: view.document.teamId,
+ documentId: view.document.id,
+ dataroomId: undefined,
+ linkId,
+ viewerEmail: view.viewerEmail ?? undefined,
+ viewerId: undefined,
+ });
+ } catch (error) {
+ console.error("Error sending Slack notification:", error);
+ }
+ }
+
// get the file to be downloaded, if watermark is enabled and document is not pdf, then get the pdf file, otherwise return the original file
// if watermark is enabled and document version is pdf, then get the file
// if watermark is not enabled, then get the original file
diff --git a/pages/api/record_reaction.ts b/pages/api/record_reaction.ts
index 07f27684..744b5a0e 100644
--- a/pages/api/record_reaction.ts
+++ b/pages/api/record_reaction.ts
@@ -1,6 +1,7 @@
import { NextApiRequest, NextApiResponse } from "next";
import prisma from "@/lib/prisma";
+import { notifyDocumentReaction } from "@/lib/slack/events";
export default async function handle(
req: NextApiRequest,
@@ -27,6 +28,18 @@ export default async function handle(
pageNumber,
type,
},
+ include: {
+ view: {
+ select: {
+ documentId: true,
+ dataroomId: true,
+ linkId: true,
+ viewerEmail: true,
+ viewerId: true,
+ teamId: true,
+ },
+ },
+ },
});
if (!reaction) {
@@ -34,6 +47,25 @@ 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;
} catch (error) {
diff --git a/pages/api/slack/oauth/callback.ts b/pages/api/slack/oauth/callback.ts
new file mode 100644
index 00000000..01b28582
--- /dev/null
+++ b/pages/api/slack/oauth/callback.ts
@@ -0,0 +1,120 @@
+import { NextApiRequest, NextApiResponse } from 'next';
+import { getServerSession } from 'next-auth/next';
+import { authOptions } from '@/pages/api/auth/[...nextauth]';
+import { slackClient } from '@/lib/slack/client';
+import { CustomUser } from '@/lib/types';
+import prisma from '@/lib/prisma';
+import { slackScheduleManager } from '@/lib/slack/schedule-manager';
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ if (req.method !== 'GET') {
+ return res.status(405).json({ error: 'Method not allowed' });
+ }
+
+ try {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).json({ error: 'Unauthorized' });
+ }
+ 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;
+
+ // Handle OAuth errors
+ if (error) {
+ return res.redirect(`/settings/slack?error=${encodeURIComponent(error)}`);
+ }
+
+ if (!code || !state) {
+ return res.redirect(`/settings/slack?error=${encodeURIComponent('Missing authorization code or state')}`);
+ }
+
+ // Decode state to get teamId and userId
+ let stateData: { teamId: string; userId: string };
+ try {
+ stateData = JSON.parse(Buffer.from(state, 'base64').toString());
+ } catch (error) {
+ return res.redirect(`/settings/slack?error=${encodeURIComponent('Invalid state parameter')}`);
+ }
+
+ const { teamId } = stateData;
+
+ // Verify user has access to team
+ const userTeam = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId,
+ teamId,
+ },
+ },
+ });
+
+ if (!userTeam) {
+ return res.redirect(`/settings/slack?error=${encodeURIComponent('Access denied')}`);
+ }
+
+ // Validate state parameter
+ if (stateData.userId !== userId) {
+ return res.redirect(`/settings/slack?error=${encodeURIComponent('Invalid state parameter')}`);
+ }
+
+ // Check if integration already exists
+ const existingIntegration = await prisma.slackIntegration.findUnique({
+ where: { teamId },
+ });
+
+ if (existingIntegration) {
+ return res.redirect(`/settings/slack?error=${encodeURIComponent('Slack integration already exists for this team')}`);
+ }
+
+ // Exchange code for access token
+ const redirectUri = `${process.env.NEXTAUTH_URL}/api/slack/oauth/callback`;
+ const oauthResponse = await slackClient.exchangeCodeForToken(code, redirectUri);
+
+
+ // Get workspace and bot information
+ const workspaceInfo = await slackClient.getWorkspaceInfo(oauthResponse.access_token);
+ const botInfo = await slackClient.getBotInfo(oauthResponse.access_token);
+
+ // Create Slack integration
+ const integration = await prisma.slackIntegration.create({
+ data: {
+ teamId,
+ workspaceId: workspaceInfo.id,
+ workspaceName: workspaceInfo.name,
+ workspaceUrl: workspaceInfo.url,
+ accessToken: oauthResponse.access_token,
+ botUserId: botInfo.id,
+ botUsername: botInfo.name,
+ enabledChannels: {},
+ notificationTypes: {
+ document_view: true,
+ dataroom_access: true,
+ document_download: true,
+ document_reaction: true,
+ },
+ enabled: true,
+ frequency: 'instant',
+ timezone: 'UTC',
+ dailyTime: '10:00',
+ },
+ });
+
+ try {
+ await slackScheduleManager.createOrUpdateSchedule(integration);
+ } catch (scheduleError) {
+ console.error('Error creating schedule for new integration:', scheduleError);
+ }
+
+ // Redirect back to settings with success
+ return res.redirect(`/settings/slack?success=true&integrationId=${integration.id}`);
+
+ } catch (error) {
+ console.error('Slack OAuth callback error:', error);
+ return res.redirect(`/settings/slack?error=${encodeURIComponent('Failed to complete Slack integration')}`);
+ }
+}
\ No newline at end of file
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts
index 9d57c698..bbf7abf6 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts
@@ -6,7 +6,6 @@ import { waitUntil } from "@vercel/functions";
import { getServerSession } from "next-auth/next";
import { errorhandler } from "@/lib/errorHandler";
-import { getFeatureFlags } from "@/lib/featureFlags";
import prisma from "@/lib/prisma";
import { sendDataroomChangeNotificationTask } from "@/lib/trigger/dataroom-change-notification";
import { CustomUser } from "@/lib/types";
diff --git a/pages/api/teams/[teamId]/index.ts b/pages/api/teams/[teamId]/index.ts
index bd179ef6..5363e158 100644
--- a/pages/api/teams/[teamId]/index.ts
+++ b/pages/api/teams/[teamId]/index.ts
@@ -10,6 +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";
@@ -157,6 +158,11 @@ export default async function handle(
},
});
+ await prisma.slackIntegration.findUnique({
+ where: { teamId },
+ select: { id: true },
+ });
+
let files: string[] = [];
let hasBlobDocuments = false;
@@ -217,18 +223,21 @@ export default async function handle(
team.domains && domainPromises,
// delete subscription, if exists on team
team.stripeId &&
- cancelSubscription(team.stripeId, isOldAccount(team.plan)),
+ cancelSubscription(team.stripeId, isOldAccount(team.plan)),
// delete user from contact book
unsubscribe((session.user as CustomUser).email ?? ""),
// delete user, if no other teams
userTeams.length === 1 &&
- prisma.user.delete({
- where: {
- id: (session.user as CustomUser).id,
- },
- }),
+ prisma.user.delete({
+ where: {
+ id: (session.user as CustomUser).id,
+ },
+ }),
// 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/channels.ts b/pages/api/teams/[teamId]/slack/channels.ts
new file mode 100644
index 00000000..3993f756
--- /dev/null
+++ b/pages/api/teams/[teamId]/slack/channels.ts
@@ -0,0 +1,79 @@
+import { NextApiRequest, NextApiResponse } from 'next';
+import { getServerSession } from 'next-auth/next';
+import { authOptions } from '@/pages/api/auth/[...nextauth]';
+import { CustomUser } from '@/lib/types';
+import prisma from '@/lib/prisma';
+import { slackClient } from '@/lib/slack/client';
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ if (req.method !== 'GET') {
+ return res.status(405).json({ error: 'Method not allowed' });
+ }
+
+ try {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).json({ error: 'Unauthorized' });
+ }
+
+ const { teamId } = req.query as { teamId: string };
+ const userId = (session.user as CustomUser).id;
+
+ const userTeam = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId,
+ teamId,
+ },
+ },
+ });
+
+ if (!userTeam) {
+ return res.status(403).json({ error: 'Access denied' });
+ }
+
+ const integration = await prisma.slackIntegration.findUnique({
+ where: { teamId },
+ });
+
+ if (!integration) {
+ return res.status(404).json({ error: 'Slack integration not found' });
+ }
+
+ try {
+ const channels = await slackClient.getChannels(integration.accessToken);
+
+ const availableChannels = channels
+ .filter(channel => !channel.is_archived)
+ .map(channel => ({
+ id: channel.id,
+ name: channel.name,
+ is_private: channel.is_private,
+ is_member: channel.is_member || false,
+ }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+ return res.status(200).json({ channels: availableChannels });
+ } catch (slackError) {
+ if (slackError instanceof Error && slackError.message.includes('missing_scope')) {
+ return res.status(403).json({
+ error: 'Insufficient permissions. The Slack app needs channels:read permission.'
+ });
+ }
+
+ if (slackError instanceof Error && slackError.message.includes('invalid_auth')) {
+ return res.status(401).json({
+ error: 'Invalid Slack access token. Please reconnect your Slack integration.'
+ });
+ }
+ return res.status(200).json({ channels: [] });
+ }
+
+ } catch (error) {
+ console.error('Error fetching Slack channels:', error);
+ return res.status(500).json({ error: 'Internal server error' });
+ }
+}
\ No newline at end of file
diff --git a/pages/api/teams/[teamId]/slack/index.ts b/pages/api/teams/[teamId]/slack/index.ts
new file mode 100644
index 00000000..691c2144
--- /dev/null
+++ b/pages/api/teams/[teamId]/slack/index.ts
@@ -0,0 +1,187 @@
+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' });
+ }
+
+ const { teamId } = req.query as { teamId: string };
+ const userId = (session.user as CustomUser).id;
+
+ const userTeam = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId,
+ teamId,
+ },
+ },
+ });
+
+ if (!userTeam) {
+ return res.status(403).json({ error: 'Access denied' });
+ }
+
+ switch (req.method) {
+ case 'GET':
+ return handleGet(req, res, teamId);
+ case 'PUT':
+ return handleUpdate(req, res, teamId);
+ case 'DELETE':
+ return handleDelete(req, res, teamId);
+ default:
+ return res.status(405).json({ error: 'Method not allowed' });
+ }
+}
+
+async function handleGet(
+ req: NextApiRequest,
+ res: NextApiResponse,
+ teamId: string
+) {
+ try {
+ const integration = await prisma.slackIntegration.findUnique({
+ where: { teamId },
+ select: {
+ id: true,
+ workspaceId: true,
+ workspaceName: true,
+ workspaceUrl: true,
+ botUserId: true,
+ botUsername: true,
+ enabled: true,
+ notificationTypes: true,
+ frequency: true,
+ timezone: true,
+ dailyTime: true,
+ weeklyDay: true,
+ defaultChannel: true,
+ enabledChannels: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ });
+
+ if (!integration) {
+ return res.status(404).json({ error: 'Slack integration not found' });
+ }
+
+ return res.status(200).json(integration);
+ } catch (error) {
+ console.error('Error fetching Slack integration:', error);
+ return res.status(500).json({ error: 'Internal server error' });
+ }
+}
+
+async function handleUpdate(
+ req: NextApiRequest,
+ res: NextApiResponse,
+ teamId: string
+) {
+ try {
+ const {
+ enabled,
+ notificationTypes,
+ frequency,
+ timezone,
+ dailyTime,
+ weeklyDay,
+ defaultChannel,
+ enabledChannels,
+ } = req.body;
+
+ const integration = await prisma.slackIntegration.findUnique({
+ where: { teamId },
+ });
+
+ if (!integration) {
+ return res.status(404).json({ error: 'Slack integration not found' });
+ }
+
+ const updatedIntegration = await prisma.slackIntegration.update({
+ where: { teamId },
+ data: {
+ enabled: enabled !== undefined ? enabled : integration.enabled,
+ notificationTypes: notificationTypes || integration.notificationTypes,
+ frequency: frequency || integration.frequency,
+ timezone: timezone || integration.timezone,
+ dailyTime: dailyTime !== undefined ? dailyTime : integration.dailyTime,
+ weeklyDay: weeklyDay !== undefined ? weeklyDay : integration.weeklyDay,
+ defaultChannel: defaultChannel !== undefined ? defaultChannel : integration.defaultChannel,
+ enabledChannels: enabledChannels || integration.enabledChannels,
+ },
+ select: {
+ id: true,
+ workspaceId: true,
+ workspaceName: true,
+ workspaceUrl: true,
+ botUserId: true,
+ botUsername: true,
+ enabled: true,
+ notificationTypes: true,
+ frequency: true,
+ timezone: true,
+ dailyTime: true,
+ weeklyDay: true,
+ defaultChannel: true,
+ enabledChannels: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ });
+
+ try {
+ await slackScheduleManager.createOrUpdateSchedule(updatedIntegration);
+ } catch (scheduleError) {
+ console.error('Error updating schedule for integration:', scheduleError);
+ }
+
+ return res.status(200).json(updatedIntegration);
+ } catch (error) {
+ console.error('Error updating Slack integration:', error);
+ return res.status(500).json({ error: 'Internal server error' });
+ }
+}
+
+async function handleDelete(
+ req: NextApiRequest,
+ res: NextApiResponse,
+ teamId: string
+) {
+ try {
+ const integration = await prisma.slackIntegration.findUnique({
+ where: { teamId },
+ });
+
+ if (!integration) {
+ return res.status(404).json({ error: 'Slack integration not found' });
+ }
+
+ 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 },
+ });
+
+ return res.status(200).json({ message: 'Slack integration deleted successfully' });
+ } catch (error) {
+ console.error('Error deleting Slack integration:', error);
+ return res.status(500).json({ error: 'Internal server error' });
+ }
+}
\ No newline at end of file
diff --git a/pages/api/teams/[teamId]/slack/oauth/authorize.ts b/pages/api/teams/[teamId]/slack/oauth/authorize.ts
new file mode 100644
index 00000000..a78a01ce
--- /dev/null
+++ b/pages/api/teams/[teamId]/slack/oauth/authorize.ts
@@ -0,0 +1,64 @@
+import { NextApiRequest, NextApiResponse } from 'next';
+import { getServerSession } from 'next-auth/next';
+import { authOptions } from '@/pages/api/auth/[...nextauth]';
+import { slackClient } from '@/lib/slack/client';
+import { CustomUser } from '@/lib/types';
+import prisma from '@/lib/prisma';
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ if (req.method !== 'GET') {
+ return res.status(405).json({ error: 'Method not allowed' });
+ }
+
+ try {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).json({ error: 'Unauthorized' });
+ }
+
+ const { teamId } = req.query as { teamId: string };
+ const userId = (session.user as CustomUser).id;
+
+ const userTeam = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId,
+ teamId,
+ },
+ },
+ });
+
+ if (!userTeam) {
+ return res.status(403).json({ error: 'Access denied' });
+ }
+
+ const existingIntegration = await prisma.slackIntegration.findUnique({
+ where: { teamId },
+ });
+
+ if (existingIntegration) {
+ return res.status(400).json({
+ error: 'Slack integration already exists for this team',
+ integrationId: existingIntegration.id
+ });
+ }
+
+ const state = Buffer.from(JSON.stringify({ teamId, userId })).toString('base64');
+
+ const redirectUri = `${process.env.NEXTAUTH_URL}/api/slack/oauth/callback`;
+
+ const oauthUrl = slackClient.getOAuthUrl(state, redirectUri);
+
+ return res.status(200).json({
+ oauthUrl,
+ state
+ });
+
+ } catch (error) {
+ console.error('Slack OAuth authorization error:', error);
+ return res.status(500).json({ error: 'Internal server error' });
+ }
+}
\ No newline at end of file
diff --git a/pages/settings/slack.tsx b/pages/settings/slack.tsx
new file mode 100644
index 00000000..353c9db8
--- /dev/null
+++ b/pages/settings/slack.tsx
@@ -0,0 +1,431 @@
+import { useRouter } from "next/router";
+
+import { useEffect, useState } from "react";
+
+import { useTeam } from "@/context/team-context";
+import { CircleHelpIcon, Hash, Settings, X, XCircleIcon } from "lucide-react";
+import { toast } from "sonner";
+
+import AppLayout from "@/components/layouts/app";
+import { SettingsHeader } from "@/components/settings/settings-header";
+import SlackChannelModal from "@/components/settings/slack-channel-modal";
+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";
+import { CommonAlertDialog } from "@/components/ui/alert-dialog";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Separator } from "@/components/ui/separator";
+import { Switch } from "@/components/ui/switch";
+import { BadgeTooltip } from "@/components/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: "instant" | "daily" | "weekly";
+ timezone: string;
+ dailyTime?: string;
+ weeklyDay?: string;
+ defaultChannel?: string;
+ enabledChannels: Record<string, any>;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export default function SlackSettings() {
+ const router = useRouter();
+ 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);
+
+ useEffect(() => {
+ if (router.query.success) {
+ toast.success("Slack integration connected successfully!");
+ setTimeout(() => {
+ router.replace("/settings/slack", undefined, { shallow: true });
+ }, 100);
+ }
+ if (router.query.error) {
+ toast.error(`Failed to connect Slack: ${router.query.error}`);
+ setTimeout(() => {
+ router.replace("/settings/slack", undefined, { shallow: true });
+ }, 100);
+ }
+ }, [router.query]);
+
+ useEffect(() => {
+ if (!teamId) return;
+
+ const fetchIntegration = async () => {
+ try {
+ 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");
+ }
+ } catch (error) {
+ console.error("Error fetching Slack integration:", error);
+ setError("Failed to fetch integration");
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ fetchIntegration();
+ }, [teamId]);
+
+ const handleConnect = async () => {
+ if (!teamId) return;
+
+ setConnecting(true);
+ try {
+ const response = await fetch(
+ `/api/teams/${teamId}/slack/oauth/authorize`,
+ );
+ const data = await response.json();
+
+ if (response.ok) {
+ // Redirect to Slack OAuth
+ window.location.href = data.oauthUrl;
+ } else {
+ toast.error(data.error || "Failed to start OAuth process");
+ }
+ } catch (error) {
+ console.error("Error starting OAuth:", error);
+ toast.error("Failed to start OAuth process");
+ } finally {
+ setConnecting(false);
+ }
+ };
+
+ const handleDisconnect = async () => {
+ const disconnectPromise = async () => {
+ const response = await fetch(`/api/teams/${teamId}/slack`, {
+ method: "DELETE",
+ });
+
+ if (response.ok) {
+ setIntegration(null);
+ } else {
+ const data = await response.json();
+ throw new Error(data.error || "Failed to disconnect Slack");
+ }
+ };
+
+ toast.promise(disconnectPromise(), {
+ loading: "Disconnecting Slack integration...",
+ success: "Slack integration disconnected successfully",
+ error: "Failed to disconnect Slack integration. Please try again.",
+ });
+ };
+
+ const handleChannelsUpdate = async (channels: Record<string, any>) => {
+ if (!teamId || !integration) return;
+
+ await toast.promise(
+ async () => {
+ const response = await fetch(`/api/teams/${teamId}/slack`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ ...integration,
+ enabledChannels: channels,
+ }),
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(
+ errorData.error || "Failed to update channel settings",
+ );
+ }
+
+ const updatedIntegration = await response.json();
+ setIntegration(updatedIntegration);
+ },
+ {
+ loading: "Updating channels...",
+ success: "Channel settings updated successfully",
+ error: (err) => err?.message || "Failed to update channel settings",
+ },
+ );
+ };
+
+ 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">
+ <SettingsHeader />
+
+ <div>
+ {error && (
+ <Alert className="mb-4">
+ <XCircleIcon className="h-4 w-4" />
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
+ )}
+
+ {loading ? (
+ <SlackSettingsSkeleton />
+ ) : (
+ <>
+ <div className="mb-4 flex items-center justify-between md:mb-8 lg:mb-12">
+ <div className="space-y-1">
+ <h3 className="flex items-center gap-2 text-2xl font-semibold tracking-tight text-foreground">
+ <SlackIcon className="h-6 w-6" />
+ Slack Integration
+ </h3>
+ <p className="text-sm text-muted-foreground">
+ Receive notifications in your Slack channels when documents
+ are viewed or accessed
+ </p>
+ </div>
+ {!integration ? (
+ <Button onClick={handleConnect} disabled={connecting}>
+ {connecting ? (
+ <>
+ <div className="mr-2 h-4 w-4 animate-spin rounded-full border-b-2 border-white"></div>
+ Connecting...
+ </>
+ ) : (
+ <>
+ <SlackIcon className="mr-2 h-4 w-4" />
+ Connect to Slack
+ </>
+ )}
+ </Button>
+ ) : (
+ <CommonAlertDialog
+ title="Disconnect Slack Integration"
+ description="Are you sure you want to disconnect Slack? This will remove all notification settings and stop sending notifications to your Slack channels."
+ action="Disconnect"
+ actionUpdate="Disconnecting"
+ onAction={handleDisconnect}
+ />
+ )}
+ </div>
+ {!integration ? (
+ // Not connected state
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <SlackIcon className="h-5 w-5" />
+ Connect Slack
+ </CardTitle>
+ <CardDescription>
+ Connect your Slack workspace to receive real-time
+ notifications about document activity.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-4">
+ <div className="flex items-center space-x-2">
+ <Switch disabled={true} />
+ <span className="text-sm font-medium">
+ Slack notifications
+ </span>
+ <Badge variant="secondary">Not connected</Badge>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ ) : (
+ // Connected state
+ <div className="space-y-6">
+ {/* General Settings */}
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <Settings className="h-5 w-5" />
+ General Settings
+ </CardTitle>
+ <CardDescription>
+ Connected to {integration.workspaceName}
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-6">
+ {/* Slack Notification Toggle */}
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <div className="flex items-center gap-2">
+ <SlackIcon className="h-5 w-5" />
+ <h4 className="font-medium">
+ Slack notification
+ </h4>
+ </div>
+ <p className="text-sm text-muted-foreground">
+ Receive notifications in your Slack channels
+ </p>
+ </div>
+ <Switch
+ checked={integration.enabled}
+ onCheckedChange={async (checked) => {
+ try {
+ const response = await fetch(
+ `/api/teams/${teamId}/slack`,
+ {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ ...integration,
+ enabled: checked,
+ }),
+ },
+ );
+ if (response.ok) {
+ setIntegration(await response.json());
+ toast.success(
+ checked
+ ? "Slack notifications enabled"
+ : "Slack notifications disabled",
+ );
+ }
+ } catch (error) {
+ toast.error(
+ "Failed to update notification settings",
+ );
+ }
+ }}
+ />
+ </div>
+
+ <Separator />
+ <div className="space-y-3">
+ <div>
+ <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"
+ key="tag_tooltip"
+ >
+ <CircleHelpIcon className="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" />
+ </BadgeTooltip>
+ </label>
+ <p className="text-sm text-muted-foreground">
+ Select the Slack channel(s) where you want to
+ receive new mentions.
+ </p>
+ </div>
+
+ <div className="flex items-center rounded-lg border border-border bg-background">
+ <div className="flex flex-1 items-center gap-2 px-1">
+ {Object.keys(integration.enabledChannels || {})
+ .length > 0 ? (
+ Object.entries(integration.enabledChannels).map(
+ ([channelId, channel]: [string, any]) => (
+ <div
+ key={channelId}
+ className="flex items-center gap-1.5 rounded-md border bg-white px-2 py-1 text-sm shadow-sm"
+ >
+ <Hash className="h-3 w-3 text-muted-foreground" />
+ <span className="text-sm font-medium text-foreground">
+ {channel.name}
+ </span>
+ <button
+ onClick={() =>
+ handleChannelsUpdate(
+ Object.fromEntries(
+ Object.entries(
+ integration.enabledChannels,
+ ).filter(
+ ([id]) => id !== channelId,
+ ),
+ ),
+ )
+ }
+ className="ml-1 rounded-full p-0.5 text-muted-foreground transition-all duration-200 hover:scale-110 hover:bg-gray-100 hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1"
+ aria-label={`Remove ${channel.name} channel`}
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </div>
+ ),
+ )
+ ) : (
+ <span className="pl-2 text-sm text-muted-foreground">
+ No channels selected
+ </span>
+ )}
+ </div>
+ <div className="h-9 w-px bg-border" />
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() => setShowChannelModal(true)}
+ className="shrink-0 rounded-l-none border-0 px-3 py-1.5 text-sm font-medium"
+ >
+ Select Channels
+ </Button>
+ </div>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ <SlackFrequencySettings
+ teamId={teamId!}
+ integration={integration!}
+ onUpdate={setIntegration}
+ />
+ <SlackChannelModal
+ open={showChannelModal}
+ onOpenChange={setShowChannelModal}
+ teamId={teamId!}
+ onChannelsUpdate={handleChannelsUpdate}
+ currentChannels={integration.enabledChannels}
+ />
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ </main>
+ </AppLayout>
+ );
+}
diff --git a/prisma/migrations/20250805171352_added_slack_notification/migration.sql b/prisma/migrations/20250805171352_added_slack_notification/migration.sql
new file mode 100644
index 00000000..be77888a
--- /dev/null
+++ b/prisma/migrations/20250805171352_added_slack_notification/migration.sql
@@ -0,0 +1,69 @@
+-- CreateTable
+CREATE TABLE "SlackIntegration" (
+ "id" TEXT NOT NULL,
+ "teamId" TEXT NOT NULL,
+ "workspaceId" TEXT NOT NULL,
+ "workspaceName" TEXT NOT NULL,
+ "workspaceUrl" TEXT NOT NULL,
+ "accessToken" TEXT NOT NULL,
+ "botUserId" TEXT NOT NULL,
+ "botUsername" TEXT NOT NULL,
+ "defaultChannel" TEXT,
+ "enabledChannels" JSONB NOT NULL,
+ "enabled" BOOLEAN NOT NULL DEFAULT true,
+ "notificationTypes" JSONB NOT NULL,
+ "frequency" TEXT NOT NULL DEFAULT 'instant',
+ "timezone" TEXT NOT NULL DEFAULT 'UTC',
+ "dailyTime" TEXT DEFAULT '10:00',
+ "weeklyDay" TEXT,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "SlackIntegration_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "SlackNotification" (
+ "id" TEXT NOT NULL,
+ "teamId" TEXT NOT NULL,
+ "slackIntegrationId" TEXT NOT NULL,
+ "eventType" TEXT NOT NULL,
+ "eventData" JSONB NOT NULL,
+ "status" TEXT NOT NULL DEFAULT 'PENDING',
+ "scheduledFor" TIMESTAMP(3) NOT NULL,
+ "processedAt" TIMESTAMP(3),
+ "errorMessage" TEXT,
+ "retryCount" INTEGER NOT NULL DEFAULT 0,
+ "maxRetries" INTEGER NOT NULL DEFAULT 3,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "SlackNotification_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "SlackIntegration_teamId_idx" ON "SlackIntegration"("teamId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "SlackIntegration_teamId_key" ON "SlackIntegration"("teamId");
+
+-- CreateIndex
+CREATE INDEX "SlackNotification_teamId_idx" ON "SlackNotification"("teamId");
+
+-- CreateIndex
+CREATE INDEX "SlackNotification_slackIntegrationId_idx" ON "SlackNotification"("slackIntegrationId");
+
+-- CreateIndex
+CREATE INDEX "SlackNotification_status_scheduledFor_idx" ON "SlackNotification"("status", "scheduledFor");
+
+-- CreateIndex
+CREATE INDEX "SlackNotification_createdAt_idx" ON "SlackNotification"("createdAt");
+
+-- AddForeignKey
+ALTER TABLE "SlackIntegration" ADD CONSTRAINT "SlackIntegration_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "SlackNotification" ADD CONSTRAINT "SlackNotification_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "SlackNotification" ADD CONSTRAINT "SlackNotification_slackIntegrationId_fkey" FOREIGN KEY ("slackIntegrationId") REFERENCES "SlackIntegration"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prisma
index dc5b3973..2668adad 100644
--- a/prisma/schema/schema.prisma
+++ b/prisma/schema/schema.prisma
@@ -94,13 +94,15 @@ model Team {
limits Json? // Plan limits // {datarooms: 1, users: 1, domains: 1, customDomainOnPro: boolean, customDomainInDataroom: boolean}
- incomingWebhooks IncomingWebhook[]
- restrictedTokens RestrictedToken[]
- webhooks Webhook[]
+ incomingWebhooks IncomingWebhook[]
+ restrictedTokens RestrictedToken[]
+ webhooks Webhook[]
+ slackNotifications SlackNotification[]
conversations Conversation[]
uploadedDocuments DocumentUpload[]
+ slackIntegration SlackIntegration?
// team settings
enableExcelAdvancedMode Boolean @default(false) // Enable Excel advanced mode for all documents in the team
@@ -641,3 +643,59 @@ model TagItem {
@@index([tagId, documentId])
@@index([tagId, dataroomId])
}
+
+model SlackIntegration {
+ id String @id @default(cuid())
+ teamId String
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+ workspaceId String // Slack workspace ID
+ workspaceName String // Slack workspace name
+ workspaceUrl String // Slack workspace URL
+ accessToken String // Bot token for sending messages
+ botUserId String // Bot user ID
+ botUsername String // Bot username
+ defaultChannel String? // Default channel for notifications
+ enabledChannels Json // { "channel_id": { "name": "channel-name", "enabled": true } }
+ enabled Boolean @default(true)
+ notificationTypes Json // { "document_view": true, "dataroom_access": true, "document_download": true, "document_reaction": true }
+ frequency String @default("instant") // "instant", "daily", "weekly"
+ timezone String @default("UTC")
+ dailyTime String? @default("10:00")
+ weeklyDay String?
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ notifications SlackNotification[]
+
+ @@unique([teamId])
+ @@index([teamId])
+}
+
+model SlackNotification {
+ id String @id @default(cuid())
+ teamId String
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+ slackIntegrationId String
+ slackIntegration SlackIntegration @relation(fields: [slackIntegrationId], references: [id], onDelete: Cascade)
+
+ // Event Details
+ eventType String // "document_view", "dataroom_access", "document_download", "document_reaction"
+ eventData Json // Complete event data for processing
+
+ // Status
+ status String @default("PENDING") // "PENDING", "PROCESSED", "FAILED"
+ scheduledFor DateTime // When to process this notification
+ processedAt DateTime?
+ errorMessage String?
+ retryCount Int @default(0)
+ maxRetries Int @default(3)
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([teamId])
+ @@index([slackIntegrationId])
+ @@index([status, scheduledFor])
+ @@index([createdAt])
+}