Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
slack integration improvement
Ashish Viradiyaf4e19c1f713b
diff --git a/components/emails/slack-integration-notification.tsx b/components/emails/slack-integration-notification.tsxnew file mode 100644index 00000000..9ac70abf--- /dev/null+++ b/components/emails/slack-integration-notification.tsx@@ -0,0 +1,84 @@+import React from "react";++import {+ Body,+ Button,+ Container,+ Head,+ Hr,+ Html,+ Preview,+ Section,+ Tailwind,+ Text,+} from "@react-email/components";++export default function SlackIntegrationNotification({+ teamName,+ userEmail,+ settingsUrl,+}: {+ teamName: string;+ userEmail: string;+ settingsUrl: string;+}) {+ return (+ <Html>+ <Head />+ <Preview>Slack integration has been added to your workspace</Preview>+ <Tailwind>+ <Body className="mx-auto my-auto bg-white font-sans">+ <Container className="mx-auto my-10 w-[465px] p-5">+ <Text className="mx-0 mb-8 mt-4 p-0 text-center text-2xl font-normal">+ <span className="font-bold tracking-tighter">Papermark</span>+ </Text>+ <Text className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">+ An integration has been added to your workspace+ </Text>+ <Text className="text-sm leading-6 text-black">+ The Slack integration has been added to your workspace{" "}+ <span className="font-semibold">{teamName}</span> on{" "}+ <span className="font-semibold">Papermark</span>.+ </Text>+ <Text className="text-sm leading-6 text-black">+ You can now receive notifications about document views, dataroom+ access, downloads, and reactions directly in your Slack channels.+ </Text>+ <Section className="my-8 text-center">+ <Button+ className="rounded bg-black text-center text-xs font-semibold text-white no-underline"+ href={settingsUrl}+ style={{ padding: "12px 20px" }}+ >+ View installed integration+ </Button>+ </Section>+ <Text className="text-sm leading-6 text-black">+ or copy and paste this URL into your browser:+ </Text>+ <Text className="max-w-sm flex-wrap break-words font-medium text-purple-600 no-underline">+ {settingsUrl.replace(/^https?:\/\//, "")}+ </Text>+ <Hr />+ <Section className="mt-8 text-gray-400">+ <Text className="text-xs">+ © {new Date().getFullYear()}{" "}+ <a+ href="https://www.papermark.com"+ className="text-gray-400 no-underline hover:text-gray-400"+ target="_blank"+ >+ papermark.com+ </a>+ </Text>+ <Text className="text-xs">+ If you have any feedback or questions about this email, simply+ reply to it. I'd love to hear from you!+ </Text>+ </Section>+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+}diff --git a/components/settings/slack-channel-modal.tsx b/components/settings/slack-channel-modal.tsxdeleted file mode 100644index 90ad4ddf..00000000--- a/components/settings/slack-channel-modal.tsx+++ /dev/null@@ -1,242 +0,0 @@-"use client";--import { useCallback, 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);-- // Memoize fetchChannels to prevent stale closures- const fetchChannels = useCallback(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);- }- }, [teamId]);-- useEffect(() => {- if (open) {- fetchChannels();- }- }, [open, fetchChannels]);-- 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>- );-}\ No newline at end of filediff --git a/components/settings/slack-frequency-settings.tsx b/components/settings/slack-frequency-settings.tsxindex 1731a53a..e6cb049a 100644--- a/components/settings/slack-frequency-settings.tsx+++ b/components/settings/slack-frequency-settings.tsx@@ -162,49 +162,11 @@ export default function SlackFrequencySettings({const updateFrequency = async (frequency: NotificationFrequency) => {const updatePromise = async () => {await updateIntegration({ frequency });-- if (frequency === "daily" || frequency === "weekly") {- const updatedChannels = Object.keys(integration.enabledChannels).reduce(- (acc, channelId) => {- const channel = integration.enabledChannels[channelId];- if (channel && !channel.notificationTypes.includes("digest")) {- acc[channelId] = {- ...channel,- notificationTypes: [...channel.notificationTypes, "digest"],- };- } else {- acc[channelId] = channel;- }- return acc;- },- {} as Record<string, SlackChannelConfig>,- );-- const channelsUpdated = Object.keys(updatedChannels).some(- (channelId) =>- updatedChannels[channelId] !==- integration.enabledChannels[channelId],- );-- 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(". ");- },+ success: `Frequency updated to ${frequency}`,error: "Failed to update notification frequency. Please try again.",});};@@ -260,10 +222,6 @@ export default function SlackFrequencySettings({Choose when to receive your {integration.frequency} digestnotifications</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">diff --git a/components/shared/icons/slack-icon.tsx b/components/shared/icons/slack-icon.tsxindex 111a28a4..8435b2aa 100644--- a/components/shared/icons/slack-icon.tsx+++ b/components/shared/icons/slack-icon.tsx@@ -11,10 +11,26 @@ export function SlackIcon({ className = "", size = 24 }: SlackIconProps) {width={size}height={size}viewBox="0 0 24 24"- fill="currentColor"+ fill="none"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" />+ {/* Slack logo with proper colors */}+ <path+ d="M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zM6.313 15.165a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313z"+ fill="#E01E5A"+ />+ <path+ d="M8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.527 2.527 0 0 1 8.834 0a2.527 2.527 0 0 1 2.521 2.522v2.52H8.834zM8.834 6.313a2.528 2.528 0 0 1 2.521 2.52 2.527 2.527 0 0 1-2.521 2.521H2.522A2.527 2.527 0 0 1 0 8.833a2.528 2.528 0 0 1 2.522-2.52h6.312z"+ fill="#36C5F0"+ />+ <path+ d="M18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.527 2.527 0 0 1 24 8.834a2.527 2.527 0 0 1-2.522 2.52h-2.522V8.834zM17.688 8.834a2.527 2.527 0 0 1-2.52 2.52 2.526 2.526 0 0 1-2.52-2.52V2.522A2.527 2.527 0 0 1 15.166 0a2.527 2.527 0 0 1 2.522 2.522v6.312z"+ fill="#2EB67D"+ />+ <path+ d="M15.166 18.956a2.528 2.528 0 0 1 2.52 2.522A2.527 2.527 0 0 1 15.166 24a2.527 2.527 0 0 1-2.52-2.522v-2.52h2.52zM15.166 17.688a2.527 2.527 0 0 1-2.52-2.52 2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.168a2.528 2.528 0 0 1-2.522 2.52h-6.312z"+ fill="#ECB22E"+ /></svg>);}diff --git a/components/ui/multi-select-v2.tsx b/components/ui/multi-select-v2.tsxindex 0c5ba01b..0a32e10f 100644--- a/components/ui/multi-select-v2.tsx+++ b/components/ui/multi-select-v2.tsx@@ -118,6 +118,7 @@ interface MultiSelectProps<isPopoverOpen: boolean;setIsPopoverOpen: React.Dispatch<React.SetStateAction<boolean>>;loading?: boolean;+ triggerIcon?: React.ReactNode;}export type ComboboxOption<@@ -155,6 +156,7 @@ export const MultiSelect = React.forwardRef<setIsPopoverOpen,isPopoverOpen,loading,+ triggerIcon,...props},ref,@@ -229,7 +231,9 @@ export const MultiSelect = React.forwardRef<className,)}>- <TagIcon className="!size-4 shrink-0 text-muted-foreground" />+ {triggerIcon || (+ <TagIcon className="!size-4 shrink-0 text-muted-foreground" />+ )}{loading ? (<div className="mx-auto flex w-full items-center justify-between"><LoadingSpinner className="size-4 shrink-0" />@@ -252,7 +256,7 @@ export const MultiSelect = React.forwardRef<className="my-auto block whitespace-nowrap rounded-md border px-2 py-0.5 text-sm text-foreground dark:border-gray-500"style={{ animationDuration: `${animation}s` }}>- {`+ ${value.length - maxCount} more`}+ +{value.length - maxCount} more</span>)}</div>diff --git a/lib/emails/send-slack-integration-notification.ts b/lib/emails/send-slack-integration-notification.tsnew file mode 100644index 00000000..dcb380cc--- /dev/null+++ b/lib/emails/send-slack-integration-notification.ts@@ -0,0 +1,29 @@+import SlackIntegrationNotification from "@/components/emails/slack-integration-notification";++import { sendEmail } from "@/lib/resend";++export const sendSlackIntegrationNotification = async ({+ userEmail,+ teamName,+ settingsUrl,+}: {+ userEmail: string;+ teamName: string;+ settingsUrl: string;+}) => {+ try {+ await sendEmail({+ to: userEmail,+ subject: `Slack integration added to ${teamName}`,+ react: SlackIntegrationNotification({+ userEmail,+ teamName,+ settingsUrl,+ }),+ test: process.env.NODE_ENV === "development",+ system: true,+ });+ } catch (e) {+ console.error("Failed to send Slack integration notification:", e);+ }+};\ No newline at end of filediff --git a/lib/slack/digest-processor.ts b/lib/slack/digest-processor.tsindex 4ceac039..067453e6 100644--- a/lib/slack/digest-processor.ts+++ b/lib/slack/digest-processor.ts@@ -89,7 +89,7 @@ export class SlackDigestProcessor {}} catch (error) {- throw error;+ throw error;}}@@ -130,7 +130,7 @@ export class SlackDigestProcessor {const channels = Object.values(integration.enabledChannels).filter((channel: any) => channel && channel.enabled)- .filter((channel: any) => channel.notificationTypes && channel.notificationTypes.includes('digest'));+ .filter((channel: any) => channel.notificationTypes && channel.notificationTypes.length > 0);return channels;} catch (error) {diff --git a/lib/swr/use-slack-channels.ts b/lib/swr/use-slack-channels.tsnew file mode 100644index 00000000..b161faee--- /dev/null+++ b/lib/swr/use-slack-channels.ts@@ -0,0 +1,31 @@+import useSWR from "swr";++import { fetcher } from "@/lib/utils";+import { SlackChannelsResponse } from "@/lib/types/slack";++interface UseSlackChannelsProps {+ teamId?: string;+ enabled?: boolean;+}++export function useSlackChannels({ teamId, enabled = true }: UseSlackChannelsProps) {+ const { data, error, isLoading, mutate } = useSWR<SlackChannelsResponse>(+ enabled && teamId ? `/api/teams/${teamId}/slack/channels` : null,+ fetcher,+ {+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ dedupingInterval: 30000,+ revalidateIfStale: false,+ errorRetryCount: 2,+ errorRetryInterval: 5000,+ }+ );++ return {+ channels: data?.channels || [],+ error,+ loading: isLoading && !data,+ mutate,+ };+}\ No newline at end of filediff --git a/lib/swr/use-slack-integration.ts b/lib/swr/use-slack-integration.tsnew file mode 100644index 00000000..70f7ccaa--- /dev/null+++ b/lib/swr/use-slack-integration.ts@@ -0,0 +1,31 @@+import useSWR from "swr";++import { fetcher } from "@/lib/utils";+import { SlackIntegrationResponse } from "@/lib/types/slack";++interface UseSlackIntegrationProps {+ teamId?: string;+ enabled?: boolean;+}++export function useSlackIntegration({ teamId, enabled = true }: UseSlackIntegrationProps) {+ const { data, error, isLoading, mutate } = useSWR<SlackIntegrationResponse>(+ enabled && teamId ? `/api/teams/${teamId}/slack` : null,+ fetcher,+ {+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ dedupingInterval: 30000,+ revalidateIfStale: false,+ errorRetryCount: 2,+ errorRetryInterval: 5000,+ }+ );++ return {+ integration: data || null,+ error,+ loading: isLoading && !data,+ mutate,+ };+}\ No newline at end of filediff --git a/lib/types/slack.ts b/lib/types/slack.tsnew file mode 100644index 00000000..dadc531e--- /dev/null+++ b/lib/types/slack.ts@@ -0,0 +1,56 @@+export interface SlackChannel {+ id: string;+ name: string;+ is_archived: boolean;+ is_private: boolean;+}++export interface SlackChannelConfig {+ id: string;+ name: string;+ enabled: boolean;+ notificationTypes: string[];+}++export interface SlackIntegration {+ id: string;+ workspaceId: string;+ workspaceName: string;+ workspaceUrl: string;+ botUserId: string;+ botUsername: string;+ enabled: boolean;+ notificationTypes: {+ document_view: boolean;+ dataroom_access: boolean;+ document_download: boolean;+ document_reaction: boolean;+ };+ frequency: "instant" | "daily" | "weekly";+ timezone: string;+ dailyTime?: string;+ weeklyDay?: string;+ defaultChannel?: string;+ enabledChannels: Record<string, SlackChannelConfig>;+ createdAt: string;+ updatedAt: string;+}++// API Request Types+export interface UpdateSlackIntegrationRequest {+ enabled?: boolean;+ notificationTypes?: SlackIntegration['notificationTypes'];+ frequency?: SlackIntegration['frequency'];+ timezone?: string;+ dailyTime?: string;+ weeklyDay?: string;+ defaultChannel?: string;+ enabledChannels?: Record<string, SlackChannelConfig>;+}++// API Response Types+export interface SlackChannelsResponse {+ channels: SlackChannel[];+}++export interface SlackIntegrationResponse extends SlackIntegration { }\ No newline at end of filediff --git a/pages/api/slack/oauth/callback.ts b/pages/api/slack/oauth/callback.tsindex e71accf3..77d3a6b0 100644--- a/pages/api/slack/oauth/callback.ts+++ b/pages/api/slack/oauth/callback.ts@@ -6,6 +6,7 @@ import { CustomUser } from '@/lib/types';import prisma from '@/lib/prisma';import { slackScheduleManager } from '@/lib/slack/schedule-manager';import { encryptSlackToken } from '@/lib/utils';+import { sendSlackIntegrationNotification } from '@/lib/emails/send-slack-integration-notification';export default async function handler(req: NextApiRequest,@@ -104,6 +105,56 @@ export default async function handler(},});+ try {+ const team = await prisma.team.findUnique({+ where: { id: teamId },+ include: {+ users: {+ include: {+ user: true,+ },+ },+ },+ });++ if (!team) {+ console.warn(`Team with id ${teamId} not found.`);+ return;+ }++ if (!team.users.length) {+ console.warn(`Team "${team.name}" has no users to notify.`);+ return;+ }++ const settingsUrl = `${process.env.NEXTAUTH_URL}/settings/slack`;++ const usersWithEmail = team.users.filter(userTeam => userTeam.user.email);++ const emailPromises = usersWithEmail.map(async (userTeam) => {+ try {+ await sendSlackIntegrationNotification({+ userEmail: userTeam.user.email!,+ teamName: team.name,+ settingsUrl,+ });+ } catch (emailError) {+ console.error(`Failed to send Slack integration notification email to ${userTeam.user.email}:`, emailError);+ }+ });++ await Promise.allSettled(emailPromises)+ .then(results => {+ const rejected = results.filter(r => r.status === 'rejected');+ if (rejected.length) {+ console.error('Some Slack integration notification emails failed:', rejected);+ }+ });+ } catch (err) {+ console.error('Unexpected error sending Slack integration notification emails:', err);+ }++let scheduleWarning = false;try {await slackScheduleManager.createOrUpdateSchedule(integration);diff --git a/pages/api/teams/[teamId]/slack/channels.ts b/pages/api/teams/[teamId]/slack/channels.tsindex 3993f756..5015c8dd 100644--- a/pages/api/teams/[teamId]/slack/channels.ts+++ b/pages/api/teams/[teamId]/slack/channels.ts@@ -9,71 +9,94 @@ export default async function handler(req: NextApiRequest,res: NextApiResponse) {- if (req.method !== 'GET') {- 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' });}- 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 { teamId } = req.query as { teamId: string };+ const userId = (session.user as CustomUser).id;- const userTeam = await prisma.userTeam.findUnique({- where: {- userId_teamId: {- userId,- teamId,- },+ const userTeam = await prisma.userTeam.findUnique({+ where: {+ userId_teamId: {+ userId,+ teamId,},- });+ },+ });- if (!userTeam) {- return res.status(403).json({ error: 'Access denied' });- }+ if (!userTeam) {+ return res.status(403).json({ error: 'Access denied' });+ }- const integration = await prisma.slackIntegration.findUnique({- where: { teamId },- });+ if (req.method === 'GET') {+ try {+ const integration = await prisma.slackIntegration.findUnique({+ where: { teamId },+ });- if (!integration) {- return res.status(404).json({ error: 'Slack integration not found' });- }+ if (!integration) {+ return res.status(404).json({ error: 'Slack integration not found' });+ }- try {- const channels = await slackClient.getChannels(integration.accessToken);+ 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));+ 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.'- });- }+ 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.'- });+ 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: [] });}- return res.status(200).json({ channels: [] });+ } catch (error) {+ console.error('Error fetching Slack channels:', error);+ return res.status(500).json({ error: 'Internal server error' });}+ }++ if (req.method === 'PUT') {+ try {+ const { enabledChannels } = req.body;++ if (!enabledChannels) {+ return res.status(400).json({ error: 'enabledChannels is required' });+ }++ await prisma.slackIntegration.update({+ where: { teamId },+ data: { enabledChannels },+ });- } catch (error) {- console.error('Error fetching Slack channels:', error);- return res.status(500).json({ error: 'Internal server error' });+ return res.status(200).json({+ success: true,+ enabledChannels,+ updatedAt: new Date().toISOString()+ });+ } catch (error) {+ console.error('Error updating Slack channels:', error);+ return res.status(500).json({ error: 'Internal server error' });+ }}++ return res.status(405).json({ error: 'Method not allowed' });}\ No newline at end of filediff --git a/pages/api/teams/[teamId]/slack/index.ts b/pages/api/teams/[teamId]/slack/index.tsindex 691c2144..cdf2c28a 100644--- a/pages/api/teams/[teamId]/slack/index.ts+++ b/pages/api/teams/[teamId]/slack/index.ts@@ -98,26 +98,36 @@ async function handleUpdate(enabledChannels,} = req.body;- const integration = await prisma.slackIntegration.findUnique({- where: { teamId },- });-- if (!integration) {- return res.status(404).json({ error: 'Slack integration not found' });+ if (enabledChannels && Object.keys(req.body).length === 1) {+ await prisma.slackIntegration.update({+ where: { teamId },+ data: { enabledChannels },+ });++ return res.status(200).json({+ success: true,+ enabledChannels,+ updatedAt: new Date().toISOString()+ });+ }+ const updateData: any = {};++ if (enabled !== undefined) updateData.enabled = enabled;+ if (notificationTypes) updateData.notificationTypes = notificationTypes;+ if (frequency) updateData.frequency = frequency;+ if (timezone) updateData.timezone = timezone;+ if (dailyTime !== undefined) updateData.dailyTime = dailyTime;+ if (weeklyDay !== undefined) updateData.weeklyDay = weeklyDay;+ if (defaultChannel !== undefined) updateData.defaultChannel = defaultChannel;+ if (enabledChannels) updateData.enabledChannels = enabledChannels;++ if (Object.keys(updateData).length === 0) {+ return res.status(400).json({ error: 'No fields to update' });}const updatedIntegration = await prisma.slackIntegration.update({where: { teamId },- data: {- 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,- },+ data: updateData,select: {id: true,workspaceId: true,@@ -138,10 +148,18 @@ async function handleUpdate(},});- try {- await slackScheduleManager.createOrUpdateSchedule(updatedIntegration);- } catch (scheduleError) {- console.error('Error updating schedule for integration:', scheduleError);+ const scheduleNeedsUpdate =+ frequency !== undefined ||+ timezone !== undefined ||+ dailyTime !== undefined ||+ weeklyDay !== undefined;++ if (scheduleNeedsUpdate) {+ try {+ await slackScheduleManager.createOrUpdateSchedule(updatedIntegration);+ } catch (scheduleError) {+ console.error('Error updating schedule for integration:', scheduleError);+ }}return res.status(200).json(updatedIntegration);diff --git a/pages/settings/slack.tsx b/pages/settings/slack.tsxindex 9e4ee9b6..dcb225a0 100644--- a/pages/settings/slack.tsx+++ b/pages/settings/slack.tsx@@ -1,14 +1,22 @@import { useRouter } from "next/router";-import { useEffect, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import { useTeam } from "@/context/team-context";-import { CircleHelpIcon, Hash, Settings, X, XCircleIcon } from "lucide-react";+import { CircleHelpIcon, Hash, Settings, XCircleIcon } from "lucide-react";import { toast } from "sonner";+import { useSlackChannels } from "@/lib/swr/use-slack-channels";+import { useSlackIntegration } from "@/lib/swr/use-slack-integration";+import {+ SlackChannelConfig,+ SlackIntegration,+ SlackIntegrationResponse,+ UpdateSlackIntegrationRequest,+} from "@/lib/types/slack";+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";@@ -23,46 +31,69 @@ import {CardHeader,CardTitle,} from "@/components/ui/card";+import { Label } from "@/components/ui/label";+import { MultiSelect } from "@/components/ui/multi-select-v2";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 [integration, setIntegration] = useState<SlackIntegration | null>(null);- const [loading, setLoading] = useState(true);const [connecting, setConnecting] = useState(false);- const [showChannelModal, setShowChannelModal] = useState(false);+ const [isChannelPopoverOpen, setIsChannelPopoverOpen] = useState(false);+ const [pendingChannelUpdate, setPendingChannelUpdate] = useState(false);++ // Use SWR hook for integration data+ const {+ integration,+ error: integrationError,+ loading: loadingIntegration,+ mutate: mutateIntegration,+ } = useSlackIntegration({+ teamId,+ enabled: !!teamId,+ });++ const {+ channels,+ loading: loadingChannels,+ error: channelsError,+ mutate: mutateChannels,+ } = useSlackChannels({+ teamId,+ enabled: !!integration,+ });++ const ChannelIcon = useMemo(+ () => <Hash className="h-4 w-4 text-muted-foreground" />,+ [],+ );++ const filteredChannels = useMemo(+ () => channels.filter((channel) => !channel.is_archived),+ [channels],+ );++ const channelOptions = useMemo(+ () =>+ filteredChannels.map((channel) => ({+ value: channel.id,+ label: channel.name,+ icon: ChannelIcon,+ meta: {+ color: "slate",+ description: channel.is_private+ ? "Private channel"+ : "Public channel",+ },+ })),+ [filteredChannels, ChannelIcon],+ );const handleIntegrationUpdate = (updatedIntegration: SlackIntegration) => {- setIntegration(updatedIntegration);+ mutateIntegration(updatedIntegration, false);};useEffect(() => {@@ -70,6 +101,7 @@ export default function SlackSettings() {if (router.query.success) {toast.success("Slack integration connected successfully!");+ mutateIntegration();if (router.query.warning) {toast.warning(`Warning: ${router.query.warning}`);@@ -88,60 +120,7 @@ export default function SlackSettings() {return () => {if (timeoutId) clearTimeout(timeoutId);};- }, [router.query]);-- const fetchIntegration = async (controller: AbortController) => {- try {- setError(null);- setLoading(true);-- const response = await fetch(`/api/teams/${teamId}/slack`, {- signal: controller.signal,- });-- if (response.ok) {- const data = await response.json();- setIntegration(data);- setError(null);- } else if (response.status === 404) {- setIntegration(null);- setError(null);- } else {- let errorData: { error?: string } = {};- try {- errorData = await response.json();- } catch {- console.log("error");- }- setError(errorData.error || "Failed to fetch integration");- setIntegration(null);- }- } catch (error: unknown) {- if (error instanceof DOMException && error.name === "AbortError") {- } else {- console.error("Error fetching Slack integration:", error);- setError("Failed to fetch integration");- setIntegration(null);- }- } finally {- setLoading(false);- }- };-- useEffect(() => {- if (!teamId) {- setIntegration(null);- setLoading(false);- setError(null);- return;- }-- const controller = new AbortController();-- fetchIntegration(controller);-- return () => controller.abort();- }, [teamId]);+ }, [router.query, mutateIntegration]);const handleConnect = async () => {if (!teamId) return;@@ -174,7 +153,7 @@ export default function SlackSettings() {});if (response.ok) {- setIntegration(null);+ mutateIntegration(undefined, false);} else {const data = await response.json();throw new Error(data.error || "Failed to disconnect Slack");@@ -188,37 +167,180 @@ export default function SlackSettings() {});};- const handleChannelsUpdate = async (channels: Record<string, any>) => {- if (!teamId || !integration) return;+ const handleChannelsUpdate = useCallback(+ async (selectedChannelIds: string[]) => {+ if (!teamId || !integration) return;+ setIsChannelPopoverOpen(false);++ const updatePromise = async () => {+ const validChannelIds = selectedChannelIds.filter((id) =>+ channels.some((channel) => channel.id === id),+ );++ if (validChannelIds.length !== selectedChannelIds.length) {+ throw new Error("Some selected channels are no longer available");+ }++ const updatedChannels = validChannelIds.reduce(+ (acc, channelId) => {+ const channel = channels.find((c) => c.id === channelId);+ if (channel) {+ acc[channelId] = {+ id: channelId,+ name: channel.name,+ enabled: true,+ notificationTypes: [+ "document_view",+ "dataroom_access",+ "document_download",+ "document_reaction",+ ],+ } as SlackChannelConfig;+ }+ return acc;+ },+ {} as Record<string, SlackChannelConfig>,+ );+ const previousIntegration = integration;+ mutateIntegration(+ {+ ...integration,+ enabledChannels: updatedChannels,+ },+ false,+ );++ try {+ const requestBody = {+ enabledChannels: updatedChannels,+ };++ const startTime = performance.now();+ const response = await fetch(`/api/teams/${teamId}/slack/channels`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(requestBody),+ });+ const endTime = performance.now();++ // Log performance for debugging+ console.log(`Channel update API call took ${endTime - startTime}ms`);++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(+ errorData.error || "Failed to update channel settings",+ );+ }++ const result = await response.json();++ // Handle the simplified response+ if (result.success) {+ mutateIntegration(+ {+ ...integration,+ enabledChannels: result.enabledChannels,+ updatedAt: result.updatedAt,+ },+ false,+ );+ } else {+ // Fallback for full integration response+ mutateIntegration(result, false);+ }++ mutateChannels();++ return "Channel settings updated successfully";+ } catch (error) {+ // Rollback on error+ mutateIntegration(previousIntegration, false);+ throw error;+ }+ };++ toast.promise(updatePromise(), {+ loading: "Updating channel settings...",+ success: (message) => message,+ error: (error) => error.message || "Failed to update channel settings",+ });+ },+ [+ teamId,+ integration,+ channels,+ mutateChannels,+ mutateIntegration,+ setIsChannelPopoverOpen,+ ],+ );++ const debouncedChannelsUpdate = (selectedChannelIds: string[]) => {+ setPendingChannelUpdate(true);+ handleChannelsUpdate(selectedChannelIds).finally(() => {+ setPendingChannelUpdate(false);+ });+ };++ const handleIntegrationToggle = useCallback(+ async (checked: boolean) => {+ if (!teamId || !integration) return;++ const togglePromise = async () => {+ const previousState = integration.enabled;++ // Optimistic update+ mutateIntegration(+ {+ ...integration,+ enabled: checked,+ },+ false,+ );++ const requestBody: UpdateSlackIntegrationRequest = {+ ...integration,+ enabled: checked,+ };- 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,- }),+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(requestBody),});if (!response.ok) {- const errorData = await response.json();- throw new Error(- errorData.error || "Failed to update channel settings",+ // Rollback on error+ mutateIntegration(+ {+ ...integration,+ enabled: previousState,+ },+ false,);+ throw new Error("Failed to update notification 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",- },- );- };+ const updatedIntegration: SlackIntegrationResponse =+ await response.json();+ mutateIntegration(updatedIntegration, false);++ return checked+ ? "Slack notifications enabled"+ : "Slack notifications disabled";+ };++ toast.promise(togglePromise(), {+ loading: "Updating notification settings...",+ success: (message) => message,+ error: "Failed to update notification settings",+ });+ },+ [teamId, integration, mutateIntegration],+ );return (<AppLayout>@@ -226,14 +348,14 @@ export default function SlackSettings() {<SettingsHeader /><div>- {error && (+ {integrationError && (<Alert className="mb-4"><XCircleIcon className="h-4 w-4" />- <AlertDescription>{error}</AlertDescription>+ <AlertDescription>{integrationError.message}</AlertDescription></Alert>)}- {loading ? (+ {loadingIntegration ? (<SlackSettingsSkeleton />) : (<>@@ -326,108 +448,85 @@ export default function SlackSettings() {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 className="flex items-center gap-2">+ <Switch+ checked={integration.enabled}+ disabled={false}+ onCheckedChange={handleIntegrationToggle}+ />+ </div></div><Separator /><div className="space-y-3"><div>- <label className="flex items-center gap-2 text-sm font-medium">+ <Label className="flex items-center gap-2 text-sm font-medium">Slack channel(s) *<BadgeTooltipcontent="Get notifications in Slack based on frequency settings when someone views, downloads, or interacts with your documents and datarooms"- key="tag_tooltip"+ key="channel_tooltip"><CircleHelpIcon className="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" /></BadgeTooltip>- </label>+ </Label><p className="text-sm text-muted-foreground">Select the Slack channel(s) where you want to- receive new mentions.+ receive notifications.</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-background 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-muted 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>- )}+ {!integration ? (+ <div className="flex items-center gap-2 rounded-md border border-gray-200 bg-gray-50 p-3 text-sm text-gray-600 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-400">+ <div className="h-4 w-4 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600 dark:border-gray-600 dark:border-t-gray-400"></div>+ <span>Loading integration...</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>+ ) : channelsError ? (+ <div className="flex items-center justify-between rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-700 dark:border-red-800 dark:bg-red-950 dark:text-red-400">+ <div className="flex items-center gap-2">+ <XCircleIcon className="h-4 w-4" />+ <div>+ <p className="font-medium">+ Failed to load channels+ </p>+ </div>+ </div>+ </div>+ ) : loadingChannels ? (+ <div className="flex items-center gap-2 rounded-md border border-gray-200 bg-gray-50 p-3 text-sm text-gray-600 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-400">+ <div className="h-4 w-4 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600 dark:border-gray-600 dark:border-t-gray-400"></div>+ <span>Loading channels...</span>+ </div>+ ) : channels.length === 0 ? (+ <div className="flex items-center gap-2 rounded-md border border-gray-200 bg-gray-50 p-3 text-sm text-gray-600 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-400">+ <Hash className="h-4 w-4" />+ <div>+ <p className="font-medium">+ No channels available+ </p>+ </div>+ </div>+ ) : (+ <MultiSelect+ loading={false}+ options={channelOptions}+ value={Object.keys(+ integration.enabledChannels || {},+ )}+ setIsPopoverOpen={setIsChannelPopoverOpen}+ isPopoverOpen={isChannelPopoverOpen}+ onValueChange={debouncedChannelsUpdate}+ placeholder={+ pendingChannelUpdate+ ? "Saving changes..."+ : "Select channels..."+ }+ maxCount={5}+ searchPlaceholder="Search channels..."+ triggerIcon={+ <Hash className="h-4 w-4 text-muted-foreground" />+ }+ />+ )}</div></div></CardContent>@@ -437,13 +536,6 @@ export default function SlackSettings() {integration={integration!}onUpdate={handleIntegrationUpdate}/>- <SlackChannelModal- open={showChannelModal}- onOpenChange={setShowChannelModal}- teamId={teamId!}- onChannelsUpdate={handleChannelsUpdate}- currentChannels={integration.enabledChannels}- /></div>)}</>