import { BrowserFrame } from "@/components/Browser/BrowserFrame"; import { useState } from "react"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { ScrollArea } from "@/components/ui/scroll-area"; import { Badge } from "@/components/ui/badge"; import { Input } from "@/components/ui/input"; import { Plus, Play, Pause, Trash2, Settings, Clock, Zap, Webhook, Mail, MessageSquare, Bot, Database, FileText, Loader2, CheckCircle, XCircle, AlertCircle, ChevronRight, Calendar } from "lucide-react"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; interface Automation { id: number; name: string; description: string | null; triggerType: string; triggerConfig: string | null; isActive: string | null; createdAt: string; } interface AutomationLog { id: number; status: string; result: string | null; error: string | null; startedAt: string; completedAt: string | null; } const TRIGGER_TYPES = [ { value: "schedule", label: "Agendamento", icon: Clock, description: "Executa em horários programados" }, { value: "webhook", label: "Webhook", icon: Webhook, description: "Executa quando recebe uma requisição" }, { value: "manual", label: "Manual", icon: Play, description: "Executa apenas quando você clicar" }, { value: "event", label: "Evento", icon: Zap, description: "Executa quando algo acontece no sistema" }, ]; const ACTION_TYPES = [ { value: "agent_task", label: "Tarefa do Agente IA", icon: Bot, description: "Executa uma tarefa autônoma com o Agente" }, { value: "send_notification", label: "Enviar Notificação", icon: AlertCircle, description: "Envia uma notificação interna" }, { value: "send_email", label: "Enviar Email", icon: Mail, description: "Envia um email" }, { value: "send_whatsapp", label: "Enviar WhatsApp", icon: MessageSquare, description: "Envia mensagem no WhatsApp" }, { value: "erp_sync", label: "Sincronizar ERP", icon: Database, description: "Sincroniza dados com o ERP" }, { value: "generate_report", label: "Gerar Relatório", icon: FileText, description: "Gera um relatório automático" }, { value: "webhook", label: "Chamar Webhook", icon: Webhook, description: "Faz uma requisição HTTP" }, { value: "database_backup", label: "Backup de Banco de Dados", icon: Database, description: "Executa backup de uma fonte de dados" }, ]; async function fetchDataSources(): Promise { const response = await fetch("/api/bi/data-sources", { credentials: "include" }); if (!response.ok) return []; return response.json(); } async function fetchAutomations(): Promise { const response = await fetch("/api/automations", { credentials: "include" }); if (!response.ok) throw new Error("Failed to fetch automations"); return response.json(); } async function createAutomation(data: any): Promise { const response = await fetch("/api/automations", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), credentials: "include", }); if (!response.ok) throw new Error("Failed to create automation"); return response.json(); } async function deleteAutomation(id: number): Promise { const response = await fetch(`/api/automations/${id}`, { method: "DELETE", credentials: "include", }); if (!response.ok) throw new Error("Failed to delete automation"); } async function toggleAutomation(id: number, isActive: boolean): Promise { const response = await fetch(`/api/automations/${id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ isActive: isActive ? "true" : "false" }), credentials: "include", }); if (!response.ok) throw new Error("Failed to toggle automation"); } async function runAutomation(id: number): Promise { const response = await fetch(`/api/automations/${id}/run`, { method: "POST", credentials: "include", }); if (!response.ok) throw new Error("Failed to run automation"); return response.json(); } async function fetchAutomationLogs(id: number): Promise { const response = await fetch(`/api/automations/${id}/logs`, { credentials: "include" }); if (!response.ok) throw new Error("Failed to fetch logs"); return response.json(); } function CreateAutomationDialog({ onCreated }: { onCreated: () => void }) { const [open, setOpen] = useState(false); const [name, setName] = useState(""); const [description, setDescription] = useState(""); const [triggerType, setTriggerType] = useState("manual"); const [actionType, setActionType] = useState("agent_task"); const [actionPrompt, setActionPrompt] = useState(""); const [intervalMinutes, setIntervalMinutes] = useState("60"); const [selectedDataSource, setSelectedDataSource] = useState(""); const { data: dataSources = [] } = useQuery({ queryKey: ["data-sources"], queryFn: fetchDataSources, }); const createMutation = useMutation({ mutationFn: createAutomation, onSuccess: () => { setOpen(false); setName(""); setDescription(""); setTriggerType("manual"); setActionType("agent_task"); setActionPrompt(""); setSelectedDataSource(""); onCreated(); }, }); const handleCreate = () => { if (!name.trim()) return; let actionConfig: any = {}; if (actionType === "agent_task") { actionConfig = { prompt: actionPrompt }; } else if (actionType === "database_backup" && selectedDataSource) { actionConfig = { dataSourceId: parseInt(selectedDataSource) }; } createMutation.mutate({ name, description, triggerType, actions: [ { actionType, actionConfig, }, ], schedule: triggerType === "schedule" ? { intervalMinutes: parseInt(intervalMinutes) } : undefined, }); }; return ( Criar Nova Automação
setName(e.target.value)} placeholder="Ex: Relatório diário de vendas" className="bg-[#162638] border-white/20 text-white" data-testid="input-automation-name" />
setDescription(e.target.value)} placeholder="O que esta automação faz..." className="bg-[#162638] border-white/20 text-white" data-testid="input-automation-description" />
{TRIGGER_TYPES.map((trigger) => ( ))}
{triggerType === "schedule" && (
setIntervalMinutes(e.target.value)} placeholder="60" className="bg-[#162638] border-white/20 text-white" data-testid="input-interval" />
)}
{actionType === "agent_task" && (