mirror of
https://github.com/domfelipe/mika-agent-assist.git
synced 2026-08-07 12:36:50 +00:00
Criou Etapa E (cronjobs)
X-Lovable-Edit-ID: edt-4b7e2fe6-d462-49a7-ba53-9751b8ad642a Co-authored-by: domfelipe <53182096+domfelipe@users.noreply.github.com>
This commit is contained in:
commit
00df1c7db5
9 changed files with 1224 additions and 1 deletions
BIN
bun.lockb
BIN
bun.lockb
Binary file not shown.
189
src/components/mika/cronjobs/CronjobCard.tsx
Normal file
189
src/components/mika/cronjobs/CronjobCard.tsx
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
"use client";
|
||||
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { Pause, Play, Trash2, Clock, AlertTriangle } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import {
|
||||
type ScheduledJob,
|
||||
useDeleteCronjob,
|
||||
useUpdateCronjobStatus,
|
||||
} from "@/hooks/use-cronjobs";
|
||||
import { useAvailableMcps, useUserIntegrations } from "@/hooks/use-integrations";
|
||||
|
||||
interface Props {
|
||||
job: ScheduledJob;
|
||||
}
|
||||
|
||||
export function CronjobCard({ job }: Props) {
|
||||
const updateMut = useUpdateCronjobStatus();
|
||||
const deleteMut = useDeleteCronjob();
|
||||
const { data: mcps = [] } = useAvailableMcps();
|
||||
const { data: integrations = [] } = useUserIntegrations();
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
|
||||
const connectedMcpIds = new Set(
|
||||
integrations.filter((i) => i.status === "active").map((i) => i.mcp_id),
|
||||
);
|
||||
const requiredMcps = job.required_mcp_slugs
|
||||
.map((slug) => mcps.find((m) => m.slug === slug))
|
||||
.filter((m): m is NonNullable<typeof m> => !!m);
|
||||
const missingMcps = requiredMcps.filter((m) => !connectedMcpIds.has(m.id));
|
||||
|
||||
const isActive = job.status === "active";
|
||||
const isAutoPaused = job.status === "auto_paused";
|
||||
|
||||
async function toggle() {
|
||||
try {
|
||||
await updateMut.mutateAsync({
|
||||
id: job.id,
|
||||
status: isActive ? "paused" : "active",
|
||||
});
|
||||
toast.success(isActive ? "Automação pausada." : "Automação ativada.");
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "Erro ao atualizar.");
|
||||
}
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
try {
|
||||
await deleteMut.mutateAsync(job.id);
|
||||
toast.success("Automação excluída.");
|
||||
setConfirmDelete(false);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "Erro ao excluir.");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-border bg-card p-5 shadow-soft space-y-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<h3 className="font-semibold truncate">{job.name}</h3>
|
||||
{isActive && <Badge variant="success">Ativa</Badge>}
|
||||
{job.status === "paused" && <Badge variant="secondary">Pausada</Badge>}
|
||||
{isAutoPaused && (
|
||||
<Badge variant="destructive" className="gap-1">
|
||||
<AlertTriangle className="h-3 w-3" /> Auto-pausada
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-1 line-clamp-2">
|
||||
{job.human_readable}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isAutoPaused && job.auto_paused_reason && (
|
||||
<p className="text-xs text-destructive">{job.auto_paused_reason}</p>
|
||||
)}
|
||||
|
||||
{missingMcps.length > 0 && isActive && (
|
||||
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-2 text-xs">
|
||||
<span className="text-amber-700 dark:text-amber-400 font-medium">
|
||||
Integrações faltando:{" "}
|
||||
</span>
|
||||
{missingMcps.map((m) => m.name).join(", ")}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{requiredMcps.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{requiredMcps.map((m) => {
|
||||
const ok = connectedMcpIds.has(m.id);
|
||||
return (
|
||||
<Badge key={m.id} variant={ok ? "outline" : "destructive"} className="text-xs">
|
||||
{m.name}
|
||||
</Badge>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-3 text-xs text-muted-foreground">
|
||||
<span className="font-mono">{job.cron_expression}</span>
|
||||
{job.next_run_at && (
|
||||
<span className="flex items-center gap-1">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(job.next_run_at).toLocaleString("pt-BR", {
|
||||
timeZone: job.timezone,
|
||||
dateStyle: "short",
|
||||
timeStyle: "short",
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-2 pt-2 border-t border-border">
|
||||
<Button asChild variant="ghost" size="sm">
|
||||
<Link to="/painel/cronjobs/$id" params={{ id: job.id }}>
|
||||
Detalhes
|
||||
</Link>
|
||||
</Button>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={toggle}
|
||||
disabled={updateMut.isPending}
|
||||
>
|
||||
{isActive ? (
|
||||
<>
|
||||
<Pause className="h-3 w-3 mr-1" /> Pausar
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="h-3 w-3 mr-1" /> Ativar
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<AlertDialog open={confirmDelete} onOpenChange={setConfirmDelete}>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="text-destructive">
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Excluir automação?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Esta ação remove permanentemente a automação “{job.name}”.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleteMut.isPending}>
|
||||
Cancelar
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
remove();
|
||||
}}
|
||||
disabled={deleteMut.isPending}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleteMut.isPending ? "Excluindo..." : "Excluir"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
379
src/components/mika/cronjobs/CronjobWizard.tsx
Normal file
379
src/components/mika/cronjobs/CronjobWizard.tsx
Normal file
|
|
@ -0,0 +1,379 @@
|
|||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { Loader2, Sparkles, AlertTriangle, ArrowLeft, CheckCircle2, Plug } from "lucide-react";
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { invokeFunction } from "@/lib/invoke-function";
|
||||
import { useCreateCronjob } from "@/hooks/use-cronjobs";
|
||||
import { useAvailableMcps, useUserIntegrations } from "@/hooks/use-integrations";
|
||||
import { useAgentInstance } from "@/hooks/use-agent-instance";
|
||||
import { useProfile } from "@/hooks/use-profile";
|
||||
|
||||
interface ParseResult {
|
||||
cron_expression: string;
|
||||
human_readable: string;
|
||||
action_description: string;
|
||||
required_mcp_slugs: string[];
|
||||
warnings: string[];
|
||||
confidence: "high" | "medium" | "low";
|
||||
next_run_at: string | null;
|
||||
}
|
||||
|
||||
type Step = "input" | "review" | "confirm";
|
||||
|
||||
interface Props {
|
||||
onCreated?: (id: string) => void;
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
export function CronjobWizard({ onCreated, onCancel }: Props) {
|
||||
const [step, setStep] = useState<Step>("input");
|
||||
const [naturalInput, setNaturalInput] = useState("");
|
||||
const [parsing, setParsing] = useState(false);
|
||||
const [parsed, setParsed] = useState<ParseResult | null>(null);
|
||||
|
||||
// Form fields editáveis na revisão
|
||||
const [name, setName] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [cronExpression, setCronExpression] = useState("");
|
||||
const [humanReadable, setHumanReadable] = useState("");
|
||||
const [actionPrompt, setActionPrompt] = useState("");
|
||||
const [requiredMcps, setRequiredMcps] = useState<string[]>([]);
|
||||
const [reviewConfirmed, setReviewConfirmed] = useState(false);
|
||||
|
||||
const { data: profile } = useProfile();
|
||||
const { data: agent } = useAgentInstance();
|
||||
const { data: mcps = [] } = useAvailableMcps();
|
||||
const { data: integrations = [] } = useUserIntegrations();
|
||||
const createMut = useCreateCronjob();
|
||||
|
||||
const tz = profile && "timezone" in profile && typeof (profile as { timezone?: string }).timezone === "string"
|
||||
? (profile as { timezone: string }).timezone
|
||||
: "America/Sao_Paulo";
|
||||
|
||||
const mcpsBySlug = useMemo(() => {
|
||||
const m = new Map<string, { id: string; name: string }>();
|
||||
for (const x of mcps) m.set(x.slug, { id: x.id, name: x.name });
|
||||
return m;
|
||||
}, [mcps]);
|
||||
|
||||
const connectedSlugs = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
for (const it of integrations) {
|
||||
if (it.status !== "active") continue;
|
||||
const mcp = mcps.find((m) => m.id === it.mcp_id);
|
||||
if (mcp) set.add(mcp.slug);
|
||||
}
|
||||
return set;
|
||||
}, [integrations, mcps]);
|
||||
|
||||
const missingMcps = requiredMcps.filter((s) => !connectedSlugs.has(s));
|
||||
|
||||
async function handleParse() {
|
||||
const trimmed = naturalInput.trim();
|
||||
if (trimmed.length < 5) {
|
||||
toast.error("Descreva a automação com mais detalhes.");
|
||||
return;
|
||||
}
|
||||
setParsing(true);
|
||||
const { data, error } = await invokeFunction<ParseResult>(
|
||||
"parse-cronjob-natural-language",
|
||||
{ natural_language_input: trimmed, user_timezone: tz },
|
||||
);
|
||||
setParsing(false);
|
||||
if (error || !data) {
|
||||
toast.error(error?.message ?? "Não conseguimos interpretar. Tente reescrever.");
|
||||
return;
|
||||
}
|
||||
setParsed(data);
|
||||
// Pré-preenche campos
|
||||
const suggestedName = trimmed.length <= 60 ? trimmed : trimmed.slice(0, 57) + "...";
|
||||
setName(suggestedName);
|
||||
setDescription("");
|
||||
setCronExpression(data.cron_expression);
|
||||
setHumanReadable(data.human_readable);
|
||||
setActionPrompt(data.action_description || trimmed);
|
||||
setRequiredMcps(data.required_mcp_slugs);
|
||||
setReviewConfirmed(false);
|
||||
setStep("review");
|
||||
}
|
||||
|
||||
async function handleCreate() {
|
||||
if (!agent) {
|
||||
toast.error("Agente ainda não está pronto.");
|
||||
return;
|
||||
}
|
||||
if (!name.trim()) {
|
||||
toast.error("Dê um nome à automação.");
|
||||
return;
|
||||
}
|
||||
if (!cronExpression.trim() || !actionPrompt.trim()) {
|
||||
toast.error("Preencha o cron e a ação.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const job = await createMut.mutateAsync({
|
||||
agent_instance_id: agent.id,
|
||||
name: name.trim(),
|
||||
description: description.trim() || null,
|
||||
natural_language_input: naturalInput.trim(),
|
||||
cron_expression: cronExpression.trim(),
|
||||
human_readable: humanReadable.trim() || cronExpression.trim(),
|
||||
action_prompt: actionPrompt.trim(),
|
||||
required_mcp_slugs: requiredMcps,
|
||||
timezone: tz,
|
||||
next_run_at: parsed?.next_run_at ?? null,
|
||||
});
|
||||
toast.success("Automação criada!");
|
||||
onCreated?.(job.id);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : "Erro ao criar automação";
|
||||
toast.error(msg);
|
||||
}
|
||||
}
|
||||
|
||||
// STEP 1 — Input
|
||||
if (step === "input") {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-xl border border-border bg-card p-6">
|
||||
<Label htmlFor="nl-input" className="text-base font-semibold flex items-center gap-2">
|
||||
<Sparkles className="h-4 w-4 text-primary" />
|
||||
Descreva sua automação em português
|
||||
</Label>
|
||||
<p className="text-sm text-muted-foreground mt-1 mb-3">
|
||||
Diga o quê, quando e quais ferramentas usar. A IA traduz para um cronjob.
|
||||
</p>
|
||||
<Textarea
|
||||
id="nl-input"
|
||||
value={naturalInput}
|
||||
onChange={(e) => setNaturalInput(e.target.value)}
|
||||
rows={5}
|
||||
maxLength={1000}
|
||||
placeholder="Ex: todo dia útil às 9h, me envie um resumo dos e-mails do Gmail recebidos no dia anterior."
|
||||
disabled={parsing}
|
||||
/>
|
||||
<div className="flex items-center justify-between mt-2">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{naturalInput.length}/1000 — Fuso: {tz}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 rounded-md bg-muted/40 p-3 text-xs text-muted-foreground space-y-1">
|
||||
<p className="font-medium text-foreground">Exemplos:</p>
|
||||
<p>• Toda segunda-feira às 8h, criar uma página no Notion com tarefas da semana.</p>
|
||||
<p>• A cada hora útil, verificar Todoist e me lembrar das tarefas atrasadas.</p>
|
||||
<p>• Todo primeiro dia do mês às 10h, enviar relatório do Cal.com por e-mail.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
{onCancel && (
|
||||
<Button variant="ghost" onClick={onCancel} disabled={parsing}>
|
||||
Cancelar
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={handleParse} disabled={parsing || naturalInput.trim().length < 5}>
|
||||
{parsing ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" /> Interpretando...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Sparkles className="h-4 w-4 mr-2" /> Interpretar com IA
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// STEP 2 — Review (obrigatório)
|
||||
if (step === "review" && parsed) {
|
||||
const confidenceColor =
|
||||
parsed.confidence === "high"
|
||||
? "success"
|
||||
: parsed.confidence === "medium"
|
||||
? "secondary"
|
||||
: "destructive";
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-xl border border-border bg-card p-6 space-y-4">
|
||||
<div className="flex items-center justify-between flex-wrap gap-2">
|
||||
<h2 className="text-lg font-semibold">Revisar interpretação</h2>
|
||||
<Badge variant={confidenceColor as "success" | "secondary" | "destructive"}>
|
||||
Confiança: {parsed.confidence === "high" ? "alta" : parsed.confidence === "medium" ? "média" : "baixa"}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{parsed.warnings.length > 0 && (
|
||||
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-sm">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertTriangle className="h-4 w-4 text-amber-600 mt-0.5 shrink-0" />
|
||||
<div>
|
||||
<p className="font-medium text-amber-700 dark:text-amber-400">
|
||||
Suposições da IA — confira:
|
||||
</p>
|
||||
<ul className="list-disc list-inside mt-1 text-muted-foreground">
|
||||
{parsed.warnings.map((w, i) => (
|
||||
<li key={i}>{w}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<Label htmlFor="job-name">Nome</Label>
|
||||
<Input
|
||||
id="job-name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
maxLength={100}
|
||||
placeholder="Ex: Resumo diário de e-mails"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="job-cron">Expressão cron</Label>
|
||||
<Input
|
||||
id="job-cron"
|
||||
value={cronExpression}
|
||||
onChange={(e) => setCronExpression(e.target.value)}
|
||||
className="font-mono"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="job-human">Quando vai rodar</Label>
|
||||
<Input
|
||||
id="job-human"
|
||||
value={humanReadable}
|
||||
onChange={(e) => setHumanReadable(e.target.value)}
|
||||
/>
|
||||
{parsed.next_run_at && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Próxima execução:{" "}
|
||||
{new Date(parsed.next_run_at).toLocaleString("pt-BR", {
|
||||
timeZone: tz,
|
||||
dateStyle: "short",
|
||||
timeStyle: "short",
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="job-action">Ação (prompt enviado ao agente)</Label>
|
||||
<Textarea
|
||||
id="job-action"
|
||||
value={actionPrompt}
|
||||
onChange={(e) => setActionPrompt(e.target.value)}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="job-desc">Descrição (opcional)</Label>
|
||||
<Textarea
|
||||
id="job-desc"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
rows={2}
|
||||
maxLength={500}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Integrações necessárias</Label>
|
||||
{requiredMcps.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Nenhuma integração externa detectada.
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-2 mt-2">
|
||||
{requiredMcps.map((slug) => {
|
||||
const mcp = mcpsBySlug.get(slug);
|
||||
const connected = connectedSlugs.has(slug);
|
||||
return (
|
||||
<Badge
|
||||
key={slug}
|
||||
variant={connected ? "success" : "destructive"}
|
||||
className="gap-1"
|
||||
>
|
||||
{connected ? <CheckCircle2 className="h-3 w-3" /> : <Plug className="h-3 w-3" />}
|
||||
{mcp?.name ?? slug}
|
||||
{!connected && " (não conectado)"}
|
||||
</Badge>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{missingMcps.length > 0 && (
|
||||
<div className="mt-3 rounded-md border border-destructive bg-destructive/10 p-3 text-sm">
|
||||
<p className="text-destructive font-medium">
|
||||
Conecte as integrações faltantes antes de criar.
|
||||
</p>
|
||||
<Button asChild size="sm" variant="outline" className="mt-2">
|
||||
<Link to="/painel/integracoes">Ir para Integrações</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<label className="flex items-start gap-2 mt-4 p-3 rounded-md border border-border bg-muted/30 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={reviewConfirmed}
|
||||
onChange={(e) => setReviewConfirmed(e.target.checked)}
|
||||
className="mt-1"
|
||||
/>
|
||||
<span className="text-sm">
|
||||
Revisei e confirmo que a expressão cron, o horário e a ação acima estão corretos.
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => setStep("input")}
|
||||
disabled={createMut.isPending}
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" /> Voltar
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleCreate}
|
||||
disabled={
|
||||
createMut.isPending ||
|
||||
!reviewConfirmed ||
|
||||
missingMcps.length > 0 ||
|
||||
!name.trim() ||
|
||||
!cronExpression.trim() ||
|
||||
!actionPrompt.trim()
|
||||
}
|
||||
>
|
||||
{createMut.isPending ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" /> Criando...
|
||||
</>
|
||||
) : (
|
||||
"Criar automação"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
171
src/hooks/use-cronjobs.ts
Normal file
171
src/hooks/use-cronjobs.ts
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
"use client";
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { supabase } from "@/integrations/supabase/client";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
|
||||
export interface ScheduledJob {
|
||||
id: string;
|
||||
user_id: string;
|
||||
agent_instance_id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
natural_language_input: string;
|
||||
cron_expression: string;
|
||||
human_readable: string;
|
||||
action_prompt: string;
|
||||
required_mcp_slugs: string[];
|
||||
status: "active" | "paused" | "auto_paused";
|
||||
auto_paused_reason: string | null;
|
||||
last_run_at: string | null;
|
||||
next_run_at: string | null;
|
||||
timezone: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
function normalizeJob(row: unknown): ScheduledJob {
|
||||
const r = row as ScheduledJob & { required_mcp_slugs: unknown };
|
||||
return {
|
||||
...r,
|
||||
required_mcp_slugs: Array.isArray(r.required_mcp_slugs)
|
||||
? (r.required_mcp_slugs as string[])
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function useCronjobs() {
|
||||
const { user } = useAuth();
|
||||
return useQuery({
|
||||
queryKey: ["cronjobs", user?.id],
|
||||
enabled: !!user,
|
||||
queryFn: async (): Promise<ScheduledJob[]> => {
|
||||
const { data, error } = await supabase
|
||||
.from("scheduled_jobs")
|
||||
.select("*")
|
||||
.eq("user_id", user!.id)
|
||||
.order("created_at", { ascending: false });
|
||||
if (error) throw error;
|
||||
return (data ?? []).map(normalizeJob);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useCronjob(id: string | undefined) {
|
||||
const { user } = useAuth();
|
||||
return useQuery({
|
||||
queryKey: ["cronjob", id, user?.id],
|
||||
enabled: !!user && !!id,
|
||||
queryFn: async (): Promise<ScheduledJob | null> => {
|
||||
const { data, error } = await supabase
|
||||
.from("scheduled_jobs")
|
||||
.select("*")
|
||||
.eq("id", id!)
|
||||
.eq("user_id", user!.id)
|
||||
.maybeSingle();
|
||||
if (error) throw error;
|
||||
return data ? normalizeJob(data) : null;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUserJobsLimits() {
|
||||
const { user } = useAuth();
|
||||
return useQuery({
|
||||
queryKey: ["user-jobs-limits", user?.id],
|
||||
enabled: !!user,
|
||||
queryFn: async () => {
|
||||
const { data, error } = await supabase
|
||||
.from("user_jobs_limits")
|
||||
.select("*")
|
||||
.eq("user_id", user!.id)
|
||||
.maybeSingle();
|
||||
if (error) throw error;
|
||||
return data as {
|
||||
user_id: string;
|
||||
plan_slug: string | null;
|
||||
current_jobs_count: number | null;
|
||||
max_jobs: number | null;
|
||||
} | null;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export interface CreateJobInput {
|
||||
agent_instance_id: string;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
natural_language_input: string;
|
||||
cron_expression: string;
|
||||
human_readable: string;
|
||||
action_prompt: string;
|
||||
required_mcp_slugs: string[];
|
||||
timezone: string;
|
||||
next_run_at: string | null;
|
||||
}
|
||||
|
||||
export function useCreateCronjob() {
|
||||
const { user } = useAuth();
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (input: CreateJobInput) => {
|
||||
const { data, error } = await supabase
|
||||
.from("scheduled_jobs")
|
||||
.insert({
|
||||
user_id: user!.id,
|
||||
agent_instance_id: input.agent_instance_id,
|
||||
name: input.name,
|
||||
description: input.description ?? null,
|
||||
natural_language_input: input.natural_language_input,
|
||||
cron_expression: input.cron_expression,
|
||||
human_readable: input.human_readable,
|
||||
action_prompt: input.action_prompt,
|
||||
required_mcp_slugs: input.required_mcp_slugs,
|
||||
timezone: input.timezone,
|
||||
next_run_at: input.next_run_at,
|
||||
status: "active",
|
||||
})
|
||||
.select("*")
|
||||
.single();
|
||||
if (error) throw error;
|
||||
return normalizeJob(data);
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["cronjobs"] });
|
||||
qc.invalidateQueries({ queryKey: ["user-jobs-limits"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateCronjobStatus() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async ({ id, status }: { id: string; status: "active" | "paused" }) => {
|
||||
const update: { status: "active" | "paused"; auto_paused_reason?: null } = { status };
|
||||
if (status === "paused") update.auto_paused_reason = null;
|
||||
const { error } = await supabase
|
||||
.from("scheduled_jobs")
|
||||
.update(update)
|
||||
.eq("id", id);
|
||||
if (error) throw error;
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["cronjobs"] });
|
||||
qc.invalidateQueries({ queryKey: ["cronjob"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteCronjob() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
const { error } = await supabase.from("scheduled_jobs").delete().eq("id", id);
|
||||
if (error) throw error;
|
||||
},
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ["cronjobs"] });
|
||||
qc.invalidateQueries({ queryKey: ["user-jobs-limits"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -23,10 +23,13 @@ import { Route as PainelAgenteRouteImport } from './routes/painel.agente'
|
|||
import { Route as CheckoutSucessoRouteImport } from './routes/checkout.sucesso'
|
||||
import { Route as PainelSkillsIndexRouteImport } from './routes/painel.skills.index'
|
||||
import { Route as PainelIntegracoesIndexRouteImport } from './routes/painel.integracoes.index'
|
||||
import { Route as PainelCronjobsIndexRouteImport } from './routes/painel.cronjobs.index'
|
||||
import { Route as PainelSkillsPreviewRouteImport } from './routes/painel.skills.preview'
|
||||
import { Route as PainelSkillsNovaRouteImport } from './routes/painel.skills.nova'
|
||||
import { Route as PainelSkillsIdRouteImport } from './routes/painel.skills.$id'
|
||||
import { Route as PainelIntegracoesSlugRouteImport } from './routes/painel.integracoes.$slug'
|
||||
import { Route as PainelCronjobsNovaRouteImport } from './routes/painel.cronjobs.nova'
|
||||
import { Route as PainelCronjobsIdRouteImport } from './routes/painel.cronjobs.$id'
|
||||
|
||||
const SignupRoute = SignupRouteImport.update({
|
||||
id: '/signup',
|
||||
|
|
@ -98,6 +101,11 @@ const PainelIntegracoesIndexRoute = PainelIntegracoesIndexRouteImport.update({
|
|||
path: '/integracoes/',
|
||||
getParentRoute: () => PainelRoute,
|
||||
} as any)
|
||||
const PainelCronjobsIndexRoute = PainelCronjobsIndexRouteImport.update({
|
||||
id: '/cronjobs/',
|
||||
path: '/cronjobs/',
|
||||
getParentRoute: () => PainelRoute,
|
||||
} as any)
|
||||
const PainelSkillsPreviewRoute = PainelSkillsPreviewRouteImport.update({
|
||||
id: '/preview',
|
||||
path: '/preview',
|
||||
|
|
@ -118,6 +126,16 @@ const PainelIntegracoesSlugRoute = PainelIntegracoesSlugRouteImport.update({
|
|||
path: '/integracoes/$slug',
|
||||
getParentRoute: () => PainelRoute,
|
||||
} as any)
|
||||
const PainelCronjobsNovaRoute = PainelCronjobsNovaRouteImport.update({
|
||||
id: '/cronjobs/nova',
|
||||
path: '/cronjobs/nova',
|
||||
getParentRoute: () => PainelRoute,
|
||||
} as any)
|
||||
const PainelCronjobsIdRoute = PainelCronjobsIdRouteImport.update({
|
||||
id: '/cronjobs/$id',
|
||||
path: '/cronjobs/$id',
|
||||
getParentRoute: () => PainelRoute,
|
||||
} as any)
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof IndexRoute
|
||||
|
|
@ -132,10 +150,13 @@ export interface FileRoutesByFullPath {
|
|||
'/painel/faturamento': typeof PainelFaturamentoRoute
|
||||
'/painel/skills': typeof PainelSkillsRouteWithChildren
|
||||
'/painel/': typeof PainelIndexRoute
|
||||
'/painel/cronjobs/$id': typeof PainelCronjobsIdRoute
|
||||
'/painel/cronjobs/nova': typeof PainelCronjobsNovaRoute
|
||||
'/painel/integracoes/$slug': typeof PainelIntegracoesSlugRoute
|
||||
'/painel/skills/$id': typeof PainelSkillsIdRoute
|
||||
'/painel/skills/nova': typeof PainelSkillsNovaRoute
|
||||
'/painel/skills/preview': typeof PainelSkillsPreviewRoute
|
||||
'/painel/cronjobs/': typeof PainelCronjobsIndexRoute
|
||||
'/painel/integracoes/': typeof PainelIntegracoesIndexRoute
|
||||
'/painel/skills/': typeof PainelSkillsIndexRoute
|
||||
}
|
||||
|
|
@ -150,10 +171,13 @@ export interface FileRoutesByTo {
|
|||
'/painel/configuracoes': typeof PainelConfiguracoesRoute
|
||||
'/painel/faturamento': typeof PainelFaturamentoRoute
|
||||
'/painel': typeof PainelIndexRoute
|
||||
'/painel/cronjobs/$id': typeof PainelCronjobsIdRoute
|
||||
'/painel/cronjobs/nova': typeof PainelCronjobsNovaRoute
|
||||
'/painel/integracoes/$slug': typeof PainelIntegracoesSlugRoute
|
||||
'/painel/skills/$id': typeof PainelSkillsIdRoute
|
||||
'/painel/skills/nova': typeof PainelSkillsNovaRoute
|
||||
'/painel/skills/preview': typeof PainelSkillsPreviewRoute
|
||||
'/painel/cronjobs': typeof PainelCronjobsIndexRoute
|
||||
'/painel/integracoes': typeof PainelIntegracoesIndexRoute
|
||||
'/painel/skills': typeof PainelSkillsIndexRoute
|
||||
}
|
||||
|
|
@ -171,10 +195,13 @@ export interface FileRoutesById {
|
|||
'/painel/faturamento': typeof PainelFaturamentoRoute
|
||||
'/painel/skills': typeof PainelSkillsRouteWithChildren
|
||||
'/painel/': typeof PainelIndexRoute
|
||||
'/painel/cronjobs/$id': typeof PainelCronjobsIdRoute
|
||||
'/painel/cronjobs/nova': typeof PainelCronjobsNovaRoute
|
||||
'/painel/integracoes/$slug': typeof PainelIntegracoesSlugRoute
|
||||
'/painel/skills/$id': typeof PainelSkillsIdRoute
|
||||
'/painel/skills/nova': typeof PainelSkillsNovaRoute
|
||||
'/painel/skills/preview': typeof PainelSkillsPreviewRoute
|
||||
'/painel/cronjobs/': typeof PainelCronjobsIndexRoute
|
||||
'/painel/integracoes/': typeof PainelIntegracoesIndexRoute
|
||||
'/painel/skills/': typeof PainelSkillsIndexRoute
|
||||
}
|
||||
|
|
@ -193,10 +220,13 @@ export interface FileRouteTypes {
|
|||
| '/painel/faturamento'
|
||||
| '/painel/skills'
|
||||
| '/painel/'
|
||||
| '/painel/cronjobs/$id'
|
||||
| '/painel/cronjobs/nova'
|
||||
| '/painel/integracoes/$slug'
|
||||
| '/painel/skills/$id'
|
||||
| '/painel/skills/nova'
|
||||
| '/painel/skills/preview'
|
||||
| '/painel/cronjobs/'
|
||||
| '/painel/integracoes/'
|
||||
| '/painel/skills/'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
|
|
@ -211,10 +241,13 @@ export interface FileRouteTypes {
|
|||
| '/painel/configuracoes'
|
||||
| '/painel/faturamento'
|
||||
| '/painel'
|
||||
| '/painel/cronjobs/$id'
|
||||
| '/painel/cronjobs/nova'
|
||||
| '/painel/integracoes/$slug'
|
||||
| '/painel/skills/$id'
|
||||
| '/painel/skills/nova'
|
||||
| '/painel/skills/preview'
|
||||
| '/painel/cronjobs'
|
||||
| '/painel/integracoes'
|
||||
| '/painel/skills'
|
||||
id:
|
||||
|
|
@ -231,10 +264,13 @@ export interface FileRouteTypes {
|
|||
| '/painel/faturamento'
|
||||
| '/painel/skills'
|
||||
| '/painel/'
|
||||
| '/painel/cronjobs/$id'
|
||||
| '/painel/cronjobs/nova'
|
||||
| '/painel/integracoes/$slug'
|
||||
| '/painel/skills/$id'
|
||||
| '/painel/skills/nova'
|
||||
| '/painel/skills/preview'
|
||||
| '/painel/cronjobs/'
|
||||
| '/painel/integracoes/'
|
||||
| '/painel/skills/'
|
||||
fileRoutesById: FileRoutesById
|
||||
|
|
@ -349,6 +385,13 @@ declare module '@tanstack/react-router' {
|
|||
preLoaderRoute: typeof PainelIntegracoesIndexRouteImport
|
||||
parentRoute: typeof PainelRoute
|
||||
}
|
||||
'/painel/cronjobs/': {
|
||||
id: '/painel/cronjobs/'
|
||||
path: '/cronjobs'
|
||||
fullPath: '/painel/cronjobs/'
|
||||
preLoaderRoute: typeof PainelCronjobsIndexRouteImport
|
||||
parentRoute: typeof PainelRoute
|
||||
}
|
||||
'/painel/skills/preview': {
|
||||
id: '/painel/skills/preview'
|
||||
path: '/preview'
|
||||
|
|
@ -377,6 +420,20 @@ declare module '@tanstack/react-router' {
|
|||
preLoaderRoute: typeof PainelIntegracoesSlugRouteImport
|
||||
parentRoute: typeof PainelRoute
|
||||
}
|
||||
'/painel/cronjobs/nova': {
|
||||
id: '/painel/cronjobs/nova'
|
||||
path: '/cronjobs/nova'
|
||||
fullPath: '/painel/cronjobs/nova'
|
||||
preLoaderRoute: typeof PainelCronjobsNovaRouteImport
|
||||
parentRoute: typeof PainelRoute
|
||||
}
|
||||
'/painel/cronjobs/$id': {
|
||||
id: '/painel/cronjobs/$id'
|
||||
path: '/cronjobs/$id'
|
||||
fullPath: '/painel/cronjobs/$id'
|
||||
preLoaderRoute: typeof PainelCronjobsIdRouteImport
|
||||
parentRoute: typeof PainelRoute
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -404,7 +461,10 @@ interface PainelRouteChildren {
|
|||
PainelFaturamentoRoute: typeof PainelFaturamentoRoute
|
||||
PainelSkillsRoute: typeof PainelSkillsRouteWithChildren
|
||||
PainelIndexRoute: typeof PainelIndexRoute
|
||||
PainelCronjobsIdRoute: typeof PainelCronjobsIdRoute
|
||||
PainelCronjobsNovaRoute: typeof PainelCronjobsNovaRoute
|
||||
PainelIntegracoesSlugRoute: typeof PainelIntegracoesSlugRoute
|
||||
PainelCronjobsIndexRoute: typeof PainelCronjobsIndexRoute
|
||||
PainelIntegracoesIndexRoute: typeof PainelIntegracoesIndexRoute
|
||||
}
|
||||
|
||||
|
|
@ -414,7 +474,10 @@ const PainelRouteChildren: PainelRouteChildren = {
|
|||
PainelFaturamentoRoute: PainelFaturamentoRoute,
|
||||
PainelSkillsRoute: PainelSkillsRouteWithChildren,
|
||||
PainelIndexRoute: PainelIndexRoute,
|
||||
PainelCronjobsIdRoute: PainelCronjobsIdRoute,
|
||||
PainelCronjobsNovaRoute: PainelCronjobsNovaRoute,
|
||||
PainelIntegracoesSlugRoute: PainelIntegracoesSlugRoute,
|
||||
PainelCronjobsIndexRoute: PainelCronjobsIndexRoute,
|
||||
PainelIntegracoesIndexRoute: PainelIntegracoesIndexRoute,
|
||||
}
|
||||
|
||||
|
|
|
|||
267
src/routes/painel.cronjobs.$id.tsx
Normal file
267
src/routes/painel.cronjobs.$id.tsx
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
"use client";
|
||||
|
||||
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
|
||||
import { ArrowLeft, Clock, AlertTriangle, Pause, Play, Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import {
|
||||
useCronjob,
|
||||
useDeleteCronjob,
|
||||
useUpdateCronjobStatus,
|
||||
} from "@/hooks/use-cronjobs";
|
||||
import { useAvailableMcps, useUserIntegrations } from "@/hooks/use-integrations";
|
||||
|
||||
export const Route = createFileRoute("/painel/cronjobs/$id")({
|
||||
component: CronjobDetailPage,
|
||||
});
|
||||
|
||||
function CronjobDetailPage() {
|
||||
const { id } = Route.useParams();
|
||||
const navigate = useNavigate();
|
||||
const { data: job, isLoading, error } = useCronjob(id);
|
||||
const { data: mcps = [] } = useAvailableMcps();
|
||||
const { data: integrations = [] } = useUserIntegrations();
|
||||
const updateMut = useUpdateCronjobStatus();
|
||||
const deleteMut = useDeleteCronjob();
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="h-32 rounded-xl bg-muted/30 animate-pulse" />;
|
||||
}
|
||||
if (error || !job) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Button asChild variant="ghost" size="sm">
|
||||
<Link to="/painel/cronjobs">
|
||||
<ArrowLeft className="h-4 w-4 mr-2" /> Voltar
|
||||
</Link>
|
||||
</Button>
|
||||
<div className="rounded-md border border-destructive bg-destructive/10 p-4 text-sm text-destructive">
|
||||
Automação não encontrada.
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const connectedMcpIds = new Set(
|
||||
integrations.filter((i) => i.status === "active").map((i) => i.mcp_id),
|
||||
);
|
||||
const requiredMcps = job.required_mcp_slugs
|
||||
.map((slug) => mcps.find((m) => m.slug === slug))
|
||||
.filter((m): m is NonNullable<typeof m> => !!m);
|
||||
const missingMcps = requiredMcps.filter((m) => !connectedMcpIds.has(m.id));
|
||||
|
||||
const isActive = job.status === "active";
|
||||
const isAutoPaused = job.status === "auto_paused";
|
||||
|
||||
async function toggle() {
|
||||
try {
|
||||
await updateMut.mutateAsync({
|
||||
id: job!.id,
|
||||
status: isActive ? "paused" : "active",
|
||||
});
|
||||
toast.success(isActive ? "Pausada." : "Ativada.");
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "Erro");
|
||||
}
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
try {
|
||||
await deleteMut.mutateAsync(job!.id);
|
||||
toast.success("Excluída.");
|
||||
navigate({ to: "/painel/cronjobs" });
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "Erro");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Button asChild variant="ghost" size="sm">
|
||||
<Link to="/painel/cronjobs">
|
||||
<ArrowLeft className="h-4 w-4 mr-2" /> Voltar para automações
|
||||
</Link>
|
||||
</Button>
|
||||
|
||||
<div className="flex items-start justify-between gap-3 flex-wrap">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">{job.name}</h1>
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
{isActive && <Badge variant="success">Ativa</Badge>}
|
||||
{job.status === "paused" && <Badge variant="secondary">Pausada</Badge>}
|
||||
{isAutoPaused && (
|
||||
<Badge variant="destructive" className="gap-1">
|
||||
<AlertTriangle className="h-3 w-3" /> Auto-pausada
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={toggle} disabled={updateMut.isPending}>
|
||||
{isActive ? (
|
||||
<>
|
||||
<Pause className="h-4 w-4 mr-2" /> Pausar
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="h-4 w-4 mr-2" /> Ativar
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="text-destructive"
|
||||
onClick={() => setConfirmDelete(true)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" /> Excluir
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isAutoPaused && job.auto_paused_reason && (
|
||||
<div className="rounded-md border border-destructive bg-destructive/10 p-4 text-sm">
|
||||
<p className="font-medium text-destructive">Auto-pausada</p>
|
||||
<p className="text-muted-foreground mt-1">{job.auto_paused_reason}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{missingMcps.length > 0 && isActive && (
|
||||
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-4 text-sm">
|
||||
<p className="font-medium text-amber-700 dark:text-amber-400">
|
||||
Integrações necessárias não conectadas:
|
||||
</p>
|
||||
<ul className="list-disc list-inside mt-1 text-muted-foreground">
|
||||
{missingMcps.map((m) => (
|
||||
<li key={m.id}>{m.name}</li>
|
||||
))}
|
||||
</ul>
|
||||
<Button asChild size="sm" variant="outline" className="mt-3">
|
||||
<Link to="/painel/integracoes">Conectar agora</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-xl border border-border bg-card p-6 space-y-4">
|
||||
<Section label="Quando vai rodar" value={job.human_readable} />
|
||||
<Section label="Expressão cron" value={job.cron_expression} mono />
|
||||
<Section
|
||||
label="Próxima execução"
|
||||
value={
|
||||
job.next_run_at
|
||||
? new Date(job.next_run_at).toLocaleString("pt-BR", {
|
||||
timeZone: job.timezone,
|
||||
dateStyle: "full",
|
||||
timeStyle: "short",
|
||||
})
|
||||
: "—"
|
||||
}
|
||||
icon={<Clock className="h-4 w-4 text-muted-foreground" />}
|
||||
/>
|
||||
<Section
|
||||
label="Última execução"
|
||||
value={
|
||||
job.last_run_at
|
||||
? new Date(job.last_run_at).toLocaleString("pt-BR", {
|
||||
timeZone: job.timezone,
|
||||
dateStyle: "full",
|
||||
timeStyle: "short",
|
||||
})
|
||||
: "Nunca"
|
||||
}
|
||||
/>
|
||||
<Section label="Fuso horário" value={job.timezone} />
|
||||
<Section label="Descrição original (NL)" value={job.natural_language_input} />
|
||||
{job.description && <Section label="Notas" value={job.description} />}
|
||||
<div>
|
||||
<p className="text-xs uppercase tracking-wide text-muted-foreground">
|
||||
Ação enviada ao agente
|
||||
</p>
|
||||
<pre className="mt-1 rounded-md bg-muted/40 p-3 text-sm whitespace-pre-wrap">
|
||||
{job.action_prompt}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-xs uppercase tracking-wide text-muted-foreground mb-2">
|
||||
Integrações necessárias
|
||||
</p>
|
||||
{requiredMcps.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">Nenhuma.</p>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{requiredMcps.map((m) => {
|
||||
const ok = connectedMcpIds.has(m.id);
|
||||
return (
|
||||
<Badge key={m.id} variant={ok ? "success" : "destructive"}>
|
||||
{m.name} {ok ? "✓" : "(não conectado)"}
|
||||
</Badge>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AlertDialog open={confirmDelete} onOpenChange={setConfirmDelete}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Excluir automação?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Esta ação remove permanentemente “{job.name}”.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleteMut.isPending}>Cancelar</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
remove();
|
||||
}}
|
||||
disabled={deleteMut.isPending}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleteMut.isPending ? "Excluindo..." : "Excluir"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({
|
||||
label,
|
||||
value,
|
||||
mono,
|
||||
icon,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
mono?: boolean;
|
||||
icon?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<p className="text-xs uppercase tracking-wide text-muted-foreground">{label}</p>
|
||||
<p
|
||||
className={`mt-1 text-sm flex items-center gap-2 ${mono ? "font-mono" : ""}`}
|
||||
>
|
||||
{icon}
|
||||
{value}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
124
src/routes/painel.cronjobs.index.tsx
Normal file
124
src/routes/painel.cronjobs.index.tsx
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
"use client";
|
||||
|
||||
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
|
||||
import { CalendarClock, Plus, Lock } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useCronjobs, useUserJobsLimits } from "@/hooks/use-cronjobs";
|
||||
import { useAgentInstance } from "@/hooks/use-agent-instance";
|
||||
import { CronjobCard } from "@/components/mika/cronjobs/CronjobCard";
|
||||
|
||||
export const Route = createFileRoute("/painel/cronjobs/")({
|
||||
component: CronjobsPage,
|
||||
});
|
||||
|
||||
function CronjobsPage() {
|
||||
const { data: jobs = [], isLoading, error } = useCronjobs();
|
||||
const { data: limits } = useUserJobsLimits();
|
||||
const { data: agent } = useAgentInstance();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const agentReady = agent?.status === "active" || agent?.status === "ready";
|
||||
const planAllows = (limits?.max_jobs ?? 0) > 0;
|
||||
const limitReached =
|
||||
!!limits && limits.max_jobs !== null
|
||||
? (limits.current_jobs_count ?? 0) >= (limits.max_jobs ?? 0)
|
||||
: false;
|
||||
const canCreate = agentReady && planAllows && !limitReached;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-start justify-between gap-4 flex-wrap">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold flex items-center gap-2">
|
||||
<CalendarClock className="h-6 w-6 text-primary" /> Automações
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Crie cronjobs em linguagem natural — a IA traduz para você.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
{limits && limits.max_jobs !== null && (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<span className="font-semibold text-foreground">
|
||||
{limits.current_jobs_count ?? 0}
|
||||
</span>
|
||||
{" / "}
|
||||
{limits.max_jobs} automações
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
onClick={() => navigate({ to: "/painel/cronjobs/nova" })}
|
||||
disabled={!canCreate}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" /> Nova automação
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!agentReady && (
|
||||
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-4 text-sm text-amber-700 dark:text-amber-400">
|
||||
Seu agente ainda está sendo provisionado. As automações serão liberadas em seguida.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{agentReady && !planAllows && (
|
||||
<div className="rounded-md border border-border bg-muted/30 p-4 text-sm flex items-center justify-between gap-3 flex-wrap">
|
||||
<div className="flex items-center gap-2">
|
||||
<Lock className="h-4 w-4 text-muted-foreground" />
|
||||
<span>
|
||||
Seu plano <strong>{limits?.plan_slug ?? "atual"}</strong> não inclui automações.
|
||||
</span>
|
||||
</div>
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<Link to="/painel/faturamento">Fazer upgrade</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{agentReady && planAllows && limitReached && (
|
||||
<div className="rounded-md border border-border bg-muted/30 p-4 text-sm">
|
||||
Você atingiu o limite de {limits?.max_jobs} automações do plano{" "}
|
||||
<strong>{limits?.plan_slug}</strong>. Pause ou exclua para criar novas, ou faça upgrade.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="rounded-md border border-destructive bg-destructive/10 p-4 text-sm text-destructive">
|
||||
Erro ao carregar automações: {error.message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading ? (
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="h-44 rounded-xl border border-border bg-muted/30 animate-pulse"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : jobs.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed border-border p-12 text-center space-y-3">
|
||||
<CalendarClock className="h-10 w-10 text-muted-foreground mx-auto" />
|
||||
<div>
|
||||
<p className="font-medium">Nenhuma automação ainda</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Comece descrevendo o que você quer automatizar em português.
|
||||
</p>
|
||||
</div>
|
||||
{canCreate && (
|
||||
<Button onClick={() => navigate({ to: "/painel/cronjobs/nova" })}>
|
||||
<Plus className="h-4 w-4 mr-2" /> Criar primeira automação
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{jobs.map((j) => (
|
||||
<CronjobCard key={j.id} job={j} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
28
src/routes/painel.cronjobs.nova.tsx
Normal file
28
src/routes/painel.cronjobs.nova.tsx
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
"use client";
|
||||
|
||||
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CronjobWizard } from "@/components/mika/cronjobs/CronjobWizard";
|
||||
|
||||
export const Route = createFileRoute("/painel/cronjobs/nova")({
|
||||
component: NovaCronjobPage,
|
||||
});
|
||||
|
||||
function NovaCronjobPage() {
|
||||
const navigate = useNavigate();
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Button asChild variant="ghost" size="sm">
|
||||
<Link to="/painel/cronjobs">
|
||||
<ArrowLeft className="h-4 w-4 mr-2" /> Voltar
|
||||
</Link>
|
||||
</Button>
|
||||
<h1 className="text-2xl font-bold">Nova automação</h1>
|
||||
<CronjobWizard
|
||||
onCreated={() => navigate({ to: "/painel/cronjobs" })}
|
||||
onCancel={() => navigate({ to: "/painel/cronjobs" })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import { createFileRoute, Outlet, redirect, Link, useNavigate, useLocation } fro
|
|||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
Bot,
|
||||
CalendarClock,
|
||||
CreditCard,
|
||||
Home,
|
||||
LogOut,
|
||||
|
|
@ -59,7 +60,7 @@ export const Route = createFileRoute("/painel")({
|
|||
});
|
||||
|
||||
interface NavItem {
|
||||
to: "/painel" | "/painel/agente" | "/painel/skills" | "/painel/integracoes" | "/painel/faturamento" | "/painel/configuracoes";
|
||||
to: "/painel" | "/painel/agente" | "/painel/skills" | "/painel/integracoes" | "/painel/cronjobs" | "/painel/faturamento" | "/painel/configuracoes";
|
||||
label: string;
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
disabled?: boolean;
|
||||
|
|
@ -76,6 +77,7 @@ const NAV: (NavItem | DisabledNavItem)[] = [
|
|||
{ to: "/painel", label: "Dashboard", icon: Home },
|
||||
{ to: "/painel/agente", label: "Meu Agente", icon: Bot },
|
||||
{ to: "/painel/skills", label: "Skills", icon: Sparkles },
|
||||
{ to: "/painel/cronjobs", label: "Automações", icon: CalendarClock },
|
||||
{ to: "/painel/integracoes", label: "Integrações", icon: Plug },
|
||||
{ to: "/painel/faturamento", label: "Faturamento", icon: CreditCard },
|
||||
{ to: "/painel/configuracoes", label: "Configurações", icon: Settings },
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue