Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

7.7 KB
Raw Blame
import React from "react";
import { CheckCircle, AlertCircle, Unlink } from "@langfuse/icons";
import { Badge } from "@/src/components/design-system/Badge/Badge";
import { Button } from "@/src/components/design-system/Button/Button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/src/components/ui/card";
import { Alert } from "@/src/components/design-system/Alert/Alert";
import { api } from "@/src/utils/api";
import { SlackConnectButton } from "@/src/features/slack/components/SlackConnectButton";
import { SlackDisconnectDialogController } from "@/src/features/slack/components/SlackDisconnectDialogController";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";

/**
 * Props for the SlackConnectionCard component
 */
interface SlackConnectionCardProps {
  /** Project ID for the Slack integration */
  projectId: string;
  /** Whether the component is disabled */
  disabled?: boolean;
  /** Optional callback when connection status changes */
  onConnectionChange?: (connected: boolean) => void;
  /** Whether to show the connect button in the card */
  showConnectButton?: boolean;
}

/**
 * A reusable card component that displays Slack connection status and management controls.
 *
 * This component handles:
 * - Displaying current connection status
 * - Showing team information when connected
 * - Providing connection and disconnection actions
 * - Handling error states with appropriate messaging
 *
 * The component automatically fetches the integration status and updates when the connection changes.
 *
 * @param projectId - The project ID for the Slack integration
 * @param disabled - Whether the component should be disabled
 * @param onConnectionChange - Optional callback when connection status changes
 * @param showConnectButton - Whether to show the connect button in the card (default: true)
 */
export const SlackConnectionCard: React.FC<SlackConnectionCardProps> = ({
  projectId,
  disabled = false,
  onConnectionChange,
  showConnectButton = true,
}) => {
  // Connecting and disconnecting a workspace is project integration config,
  // separate from managing the automations that use it.
  const canManageIntegration = useHasProjectAccess({
    projectId,
    scope: "integrations:CRUD",
  });

  // Get Slack integration status
  const {
    data: integrationStatus,
    isLoading,
    refetch: refetchStatus,
    error: statusError,
  } = api.slack.getIntegrationStatus.useQuery(
    { projectId },
    {
      enabled: !!projectId,
      // Refetch every 30 seconds to keep status up to date
      refetchInterval: 30000,
    },
  );

  // Handle connection status change
  const handleConnectionChange = (connected: boolean) => {
    refetchStatus();
    onConnectionChange?.(connected);
  };

  // Handle loading state
  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            Slack Connection
          </CardTitle>
          <CardDescription>Checking connection status...</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="text-muted-foreground flex items-center gap-2">
            <div className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
            <span>Loading...</span>
          </div>
        </CardContent>
      </Card>
    );
  }

  // Handle error state
  if (statusError) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            Slack Connection
          </CardTitle>
          <CardDescription>Error loading connection status</CardDescription>
        </CardHeader>
        <CardContent>
          <Alert icon={AlertCircle}>
            <Alert.Description>
              Failed to load Slack integration status. Please try again.
            </Alert.Description>
          </Alert>
        </CardContent>
      </Card>
    );
  }

  // Handle not connected state
  if (!integrationStatus?.isConnected) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            Slack Connection
          </CardTitle>
          <CardDescription>
            Connect your Slack workspace to send notifications
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {integrationStatus?.error && (
            <Alert icon={AlertCircle}>
              <Alert.Description>{integrationStatus.error}</Alert.Description>
            </Alert>
          )}

          <div className="space-y-2">
            <p className="text-muted-foreground text-sm">
              Connect your Slack workspace to enable real-time notifications for
              your automations.
            </p>

            {!canManageIntegration && (
              <p className="text-muted-foreground text-sm">
                Ask a project admin to connect Slack.
              </p>
            )}

            {showConnectButton && (
              <SlackConnectButton
                projectId={projectId}
                disabled={disabled || !canManageIntegration}
                onSuccess={() => handleConnectionChange(true)}
                onError={(error: Error) => {
                  console.error("Slack connection error:", error);
                }}
              />
            )}
          </div>
        </CardContent>
      </Card>
    );
  }

  // Handle connected state
  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          Slack Connection
        </CardTitle>
        <CardDescription>Connected to your Slack workspace</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Connection Status */}
        <div className="flex items-center gap-2">
          <CheckCircle size="base" __rawClassName="text-green-500" />
          <span className="text-sm font-bold">Connected</span>
        </div>

        {/* Team Information */}
        <div className="space-y-2">
          <div className="flex items-center gap-2">
            <span className="text-sm font-bold">Workspace:</span>
            <Badge color="filled" text={integrationStatus.teamName ?? ""} />
          </div>

          <div className="flex items-center gap-2">
            <span className="text-sm font-bold">Team ID:</span>
            <Badge
              color="primary"
              font="mono"
              text={integrationStatus.teamId ?? ""}
            />
          </div>

          {integrationStatus.botUserId && (
            <div className="flex items-center gap-2">
              <span className="text-sm font-bold">Bot User:</span>
              <Badge
                color="primary"
                font="mono"
                text={integrationStatus.botUserId}
              />
            </div>
          )}
        </div>

        {/* Management Actions */}
        <div className="flex gap-2 pt-2">
          <SlackDisconnectDialogController
            projectId={projectId}
            onSuccess={() => handleConnectionChange(false)}
            onError={(error: Error) => {
              console.error("Slack disconnection error:", error);
            }}
          >
            {({ isPending, openDialog }) => (
              <Button
                text="Disconnect"
                icon={Unlink}
                variant="destructive"
                size="sm"
                onClick={openDialog}
                disabled={disabled || isPending || !canManageIntegration}
              />
            )}
          </SlackDisconnectDialogController>

          <Button
            text="Refresh Status"
            variant="secondary"
            size="sm"
            onClick={() => refetchStatus()}
            disabled={disabled}
          />
        </div>
      </CardContent>
    </Card>
  );
};