refactor: 标准化项目结构 frontend/ + backend/ + SQLite + run.sh

- 目录重构: app/ -> frontend/,与 backend/ 并列
- 数据库: 默认 SQLite(零配置),修复 DSN() bug
- run.sh: 一键启动前后端,支持 start/stop/restart/status
- Makefile: install/dev/build/lint/clean 快捷命令
- vite.config.ts: 配置 dev server 端口 5173 + API 代理到 8080
- config.yaml: SQLite 默认配置,开箱即用
- docs/: 完整开发文档(项目结构/API/数据库/规范/部署)
- 修复: GORM foreign key 关联声明
- 修复: go get gorm.io/driver/sqlite 依赖
This commit is contained in:
attacker committed 2026-06-13 23:34:23 +08:00
1 parent 7d6674bddd
commit 97c4207ff8
132 files changed
+1572 -34

No files matched your search

@@ -0,0 +1,703 @@
import React, { useState, useEffect } from 'react';
import {
Play, FileCode, Server, Clock, CheckCircle, XCircle, RotateCcw, Eye,
Download, Plus, Search, Filter, Trash2, Edit, Copy, Terminal,
BookOpen, Settings, ChevronRight, Pause, RefreshCw, FolderOpen,
Zap, AlertTriangle, History, Code, Users, Globe, Shield
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import {
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter
} from '@/components/ui/dialog';
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue
} from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import { ScrollArea } from '@/components/ui/scroll-area';
import { toast } from 'sonner';
import { ansibleApi } from '@/services/api';
interface Playbook {
id: string;
name: string;
description: string;
content: string;
tags: string[];
category: string;
createdAt: string;
updatedAt: string;
createdBy: string;
variables: PlaybookVariable[];
}
interface PlaybookVariable {
name: string;
defaultValue: string;
description: string;
required: boolean;
}
interface Job {
id: string;
playbookId: string;
playbookName: string;
status: 'pending' | 'running' | 'success' | 'failed' | 'cancelled';
targetHosts: string[];
variables: Record<string, string>;
startedAt: string;
completedAt?: string;
duration?: number;
output: string;
triggeredBy: string;
}
interface Inventory {
id: string;
name: string;
hosts: Host[];
groups: Group[];
}
interface Host {
id: string;
name: string;
ip: string;
port: number;
user: string;
os: string;
}
interface Group {
id: string;
name: string;
hosts: string[];
}
const AnsibleManager: React.FC = () => {
const [playbooks, setPlaybooks] = useState<Playbook[]>([]);
const [jobs, setJobs] = useState<Job[]>([]);
const [inventories, setInventories] = useState<Inventory[]>([]);
const [loading, setLoading] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [categoryFilter, setCategoryFilter] = useState<string>('all');
const [activeTab, setActiveTab] = useState('playbooks');
// Dialog states
const [createOpen, setCreateOpen] = useState(false);
const [executeOpen, setExecuteOpen] = useState(false);
const [detailOpen, setDetailOpen] = useState(false);
const [logsOpen, setLogsOpen] = useState(false);
const [selectedPlaybook, setSelectedPlaybook] = useState<Playbook | null>(null);
const [selectedJob, setSelectedJob] = useState<Job | null>(null);
// Form states
const [newPlaybook, setNewPlaybook] = useState({
name: '',
description: '',
content: '',
category: 'deployment',
tags: ''
});
const [executionConfig, setExecutionConfig] = useState({
inventoryId: '',
targetHosts: [] as string[],
variables: {} as Record<string, string>
});
useEffect(() => {
fetchPlaybooks();
fetchJobs();
fetchInventories();
}, []);
const fetchPlaybooks = async () => {
setLoading(true);
try {
const res = await ansibleApi.getPlaybooks();
setPlaybooks(res.data || []);
} catch (error) {
toast.error('获取Playbook列表失败');
} finally {
setLoading(false);
}
};
const fetchJobs = async () => {
try {
const res = await ansibleApi.getJobs();
setJobs(res.data || []);
} catch (error) {
toast.error('获取执行记录失败');
}
};
const fetchInventories = async () => {
try {
const res = await ansibleApi.getInventories();
setInventories(res.data || []);
} catch (error) {
toast.error('获取主机清单失败');
}
};
const handleCreatePlaybook = async () => {
if (!newPlaybook.name || !newPlaybook.content) {
toast.error('请填写完整信息');
return;
}
try {
await ansibleApi.createPlaybook({
...newPlaybook,
tags: newPlaybook.tags.split(',').map(t => t.trim())
});
toast.success('Playbook创建成功');
setCreateOpen(false);
setNewPlaybook({ name: '', description: '', content: '', category: 'deployment', tags: '' });
fetchPlaybooks();
} catch (error) {
toast.error('创建失败');
}
};
const handleExecute = async () => {
if (!selectedPlaybook || !executionConfig.inventoryId) {
toast.error('请选择目标主机清单');
return;
}
try {
await ansibleApi.executePlaybook(selectedPlaybook.id, executionConfig);
toast.success('Playbook执行已启动');
setExecuteOpen(false);
fetchJobs();
} catch (error) {
toast.error('执行失败');
}
};
const handleDelete = async (id: string) => {
if (!confirm('确定删除此Playbook吗?')) return;
try {
await ansibleApi.deletePlaybook(id);
toast.success('删除成功');
fetchPlaybooks();
} catch (error) {
toast.error('删除失败');
}
};
const handleClone = async (playbook: Playbook) => {
try {
await ansibleApi.createPlaybook({
...playbook,
name: `${playbook.name} (副本)`,
id: undefined
});
toast.success('复制成功');
fetchPlaybooks();
} catch (error) {
toast.error('复制失败');
}
};
const getStatusBadge = (status: string) => {
switch (status) {
case 'pending':
return <Badge variant="outline" className="gap-1"><Clock className="w-3 h-3" />等待中</Badge>;
case 'running':
return <Badge variant="default" className="bg-blue-500 gap-1"><RefreshCw className="w-3 h-3 animate-spin" />执行中</Badge>;
case 'success':
return <Badge variant="default" className="bg-green-500 gap-1"><CheckCircle className="w-3 h-3" />成功</Badge>;
case 'failed':
return <Badge variant="destructive" className="gap-1"><XCircle className="w-3 h-3" />失败</Badge>;
case 'cancelled':
return <Badge variant="secondary" className="gap-1"><Pause className="w-3 h-3" />已取消</Badge>;
default:
return <Badge variant="secondary">未知</Badge>;
}
};
const filteredPlaybooks = playbooks.filter(pb => {
const matchSearch = pb.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
pb.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
pb.tags.some(t => t.toLowerCase().includes(searchQuery.toLowerCase()));
const matchCategory = categoryFilter === 'all' || pb.category === categoryFilter;
return matchSearch && matchCategory;
});
const categories = [
{ value: 'deployment', label: '应用部署' },
{ value: 'configuration', label: '配置管理' },
{ value: 'maintenance', label: '系统维护' },
{ value: 'security', label: '安全加固' },
{ value: 'backup', label: '备份恢复' },
{ value: 'monitoring', label: '监控配置' }
];
const samplePlaybook = `---
- name: Deploy Application
hosts: all
become: yes
vars:
app_name: myapp
app_version: "1.0.0"
deploy_path: /opt/{{ app_name }}
tasks:
- name: Install dependencies
apt:
name:
- docker.io
- docker-compose
state: present
update_cache: yes
- name: Create deploy directory
file:
path: "{{ deploy_path }}"
state: directory
mode: '0755'
- name: Deploy application
template:
src: docker-compose.yml.j2
dest: "{{ deploy_path }}/docker-compose.yml"
notify: restart app
handlers:
- name: restart app
command: docker-compose up -d
args:
chdir: "{{ deploy_path }}"`;
return (
<div className="space-y-6">
{/* 统计卡片 */}
<div className="grid grid-cols-4 gap-4">
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-muted-foreground">Playbook总数</p>
<p className="text-2xl font-bold">{playbooks.length}</p>
</div>
<div className="p-3 bg-blue-100 rounded-lg">
<FileCode className="w-5 h-5 text-blue-600" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-muted-foreground">执行中</p>
<p className="text-2xl font-bold text-blue-600">
{jobs.filter(j => j.status === 'running').length}
</p>
</div>
<div className="p-3 bg-blue-100 rounded-lg">
<RefreshCw className="w-5 h-5 text-blue-600" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-muted-foreground">今日成功</p>
<p className="text-2xl font-bold text-green-600">
{jobs.filter(j => j.status === 'success').length}
</p>
</div>
<div className="p-3 bg-green-100 rounded-lg">
<CheckCircle className="w-5 h-5 text-green-600" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-muted-foreground">执行失败</p>
<p className="text-2xl font-bold text-red-600">
{jobs.filter(j => j.status === 'failed').length}
</p>
</div>
<div className="p-3 bg-red-100 rounded-lg">
<XCircle className="w-5 h-5 text-red-600" />
</div>
</div>
</CardContent>
</Card>
</div>
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList className="grid w-full grid-cols-3 lg:w-[450px]">
<TabsTrigger value="playbooks">Playbook管理</TabsTrigger>
<TabsTrigger value="jobs">执行记录</TabsTrigger>
<TabsTrigger value="inventories">主机清单</TabsTrigger>
</TabsList>
<TabsContent value="playbooks" className="space-y-4">
{/* 操作栏 */}
<div className="flex flex-wrap items-center justify-between gap-4">
<div className="flex items-center gap-2 flex-1 min-w-[300px]">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<Input
placeholder="搜索Playbook名称、标签..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10"
/>
</div>
<Select value={categoryFilter} onValueChange={setCategoryFilter}>
<SelectTrigger className="w-[140px]">
<SelectValue placeholder="分类" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">全部分类</SelectItem>
{categories.map(c => (
<SelectItem key={c.value} value={c.value}>{c.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" onClick={fetchPlaybooks}>
<RefreshCw className="w-4 h-4 mr-2" />
刷新
</Button>
<Button onClick={() => { setNewPlaybook({ ...newPlaybook, content: samplePlaybook }); setCreateOpen(true); }}>
<Plus className="w-4 h-4 mr-2" />
新建Playbook
</Button>
</div>
</div>
{/* Playbook列表 */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{loading ? (
<div className="col-span-full text-center py-8 text-muted-foreground">加载中...</div>
) : filteredPlaybooks.length === 0 ? (
<div className="col-span-full text-center py-8 text-muted-foreground">暂无Playbook</div>
) : (
filteredPlaybooks.map((playbook) => (
<Card key={playbook.id} className="hover:shadow-md transition-shadow">
<CardHeader className="pb-3">
<div className="flex items-start justify-between">
<div className="flex items-center gap-2">
<FileCode className="w-5 h-5 text-blue-500" />
<CardTitle className="text-base">{playbook.name}</CardTitle>
</div>
<Badge variant="outline">
{categories.find(c => c.value === playbook.category)?.label || playbook.category}
</Badge>
</div>
<CardDescription className="line-clamp-2">{playbook.description}</CardDescription>
</CardHeader>
<CardContent className="pt-0">
<div className="flex flex-wrap gap-1 mb-3">
{playbook.tags.map((tag, idx) => (
<Badge key={idx} variant="secondary" className="text-xs">{tag}</Badge>
))}
</div>
<div className="flex items-center justify-between text-xs text-muted-foreground mb-3">
<span>创建者: {playbook.createdBy}</span>
<span>更新: {playbook.updatedAt}</span>
</div>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => { setSelectedPlaybook(playbook); setDetailOpen(true); }}
>
<Eye className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => { setSelectedPlaybook(playbook); setExecutionConfig({ ...executionConfig, variables: {} }); setExecuteOpen(true); }}
>
<Play className="w-4 h-4 text-green-600" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => handleClone(playbook)}
>
<Copy className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => handleDelete(playbook.id)}
>
<Trash2 className="w-4 h-4 text-red-600" />
</Button>
</div>
</CardContent>
</Card>
))
)}
</div>
</TabsContent>
<TabsContent value="jobs" className="space-y-4">
<Card>
<CardContent className="p-0">
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-muted/50">
<tr>
<th className="px-4 py-3 text-left text-sm font-medium">任务ID</th>
<th className="px-4 py-3 text-left text-sm font-medium">Playbook</th>
<th className="px-4 py-3 text-left text-sm font-medium">状态</th>
<th className="px-4 py-3 text-left text-sm font-medium">目标主机</th>
<th className="px-4 py-3 text-left text-sm font-medium">执行人</th>
<th className="px-4 py-3 text-left text-sm font-medium">开始时间</th>
<th className="px-4 py-3 text-left text-sm font-medium">耗时</th>
<th className="px-4 py-3 text-left text-sm font-medium">操作</th>
</tr>
</thead>
<tbody className="divide-y">
{jobs.length === 0 ? (
<tr>
<td colSpan={8} className="px-4 py-8 text-center text-muted-foreground">
暂无执行记录
</td>
</tr>
) : (
jobs.map((job) => (
<tr key={job.id} className="hover:bg-muted/50">
<td className="px-4 py-3 text-sm font-mono">{job.id.slice(0, 8)}</td>
<td className="px-4 py-3 text-sm">{job.playbookName}</td>
<td className="px-4 py-3">{getStatusBadge(job.status)}</td>
<td className="px-4 py-3 text-sm">{job.targetHosts.length} 台</td>
<td className="px-4 py-3 text-sm">{job.triggeredBy}</td>
<td className="px-4 py-3 text-sm text-muted-foreground">{job.startedAt}</td>
<td className="px-4 py-3 text-sm">
{job.duration ? `${Math.floor(job.duration / 1000)}s` : '-'}
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => { setSelectedJob(job); setLogsOpen(true); }}
>
<Terminal className="w-4 h-4" />
</Button>
{job.status === 'running' && (
<Button variant="ghost" size="sm">
<Pause className="w-4 h-4 text-orange-600" />
</Button>
)}
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="inventories" className="space-y-4">
<div className="flex justify-end">
<Button>
<Plus className="w-4 h-4 mr-2" />
新建清单
</Button>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{inventories.map((inventory) => (
<Card key={inventory.id}>
<CardHeader>
<div className="flex items-center gap-2">
<Server className="w-5 h-5 text-blue-500" />
<CardTitle className="text-base">{inventory.name}</CardTitle>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">主机数量</span>
<span className="font-medium">{inventory.hosts.length}</span>
</div>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">分组数量</span>
<span className="font-medium">{inventory.groups.length}</span>
</div>
</div>
<div className="mt-4 flex gap-2">
<Button variant="outline" size="sm" className="flex-1">
<Eye className="w-4 h-4 mr-2" />
查看
</Button>
<Button variant="outline" size="sm" className="flex-1">
<Edit className="w-4 h-4 mr-2" />
编辑
</Button>
</div>
</CardContent>
</Card>
))}
</div>
</TabsContent>
</Tabs>
{/* 创建Playbook对话框 */}
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
<DialogContent className="max-w-4xl max-h-[90vh]">
<DialogHeader>
<DialogTitle>新建Playbook</DialogTitle>
<DialogDescription>编写Ansible Playbook实现自动化运维</DialogDescription>
</DialogHeader>
<div className="space-y-4 overflow-y-auto max-h-[60vh]">
<div className="grid grid-cols-2 gap-4">
<div>
<Label>名称</Label>
<Input
value={newPlaybook.name}
onChange={(e) => setNewPlaybook({ ...newPlaybook, name: e.target.value })}
placeholder="Playbook名称"
/>
</div>
<div>
<Label>分类</Label>
<Select
value={newPlaybook.category}
onValueChange={(v) => setNewPlaybook({ ...newPlaybook, category: v })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{categories.map(c => (
<SelectItem key={c.value} value={c.value}>{c.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div>
<Label>描述</Label>
<Input
value={newPlaybook.description}
onChange={(e) => setNewPlaybook({ ...newPlaybook, description: e.target.value })}
placeholder="Playbook描述"
/>
</div>
<div>
<Label>标签(逗号分隔)</Label>
<Input
value={newPlaybook.tags}
onChange={(e) => setNewPlaybook({ ...newPlaybook, tags: e.target.value })}
placeholder="如: deployment, docker, production"
/>
</div>
<div>
<Label>Playbook内容 (YAML)</Label>
<Textarea
value={newPlaybook.content}
onChange={(e) => setNewPlaybook({ ...newPlaybook, content: e.target.value })}
className="min-h-[400px] font-mono text-sm"
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setCreateOpen(false)}>取消</Button>
<Button onClick={handleCreatePlaybook}>
<CheckCircle className="w-4 h-4 mr-2" />
创建
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 执行Playbook对话框 */}
<Dialog open={executeOpen} onOpenChange={setExecuteOpen}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>执行Playbook</DialogTitle>
<DialogDescription>{selectedPlaybook?.name}</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<Label>目标主机清单</Label>
<Select
value={executionConfig.inventoryId}
onValueChange={(v) => setExecutionConfig({ ...executionConfig, inventoryId: v })}
>
<SelectTrigger>
<SelectValue placeholder="选择主机清单" />
</SelectTrigger>
<SelectContent>
{inventories.map(inv => (
<SelectItem key={inv.id} value={inv.id}>{inv.name} ({inv.hosts.length}台主机)</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedPlaybook?.variables.map((variable) => (
<div key={variable.name}>
<Label>{variable.name} {variable.required && <span className="text-red-500">*</span>}</Label>
<Input
placeholder={variable.description}
value={executionConfig.variables[variable.name] || ''}
onChange={(e) => setExecutionConfig({
...executionConfig,
variables: { ...executionConfig.variables, [variable.name]: e.target.value }
})}
/>
<p className="text-xs text-muted-foreground mt-1">{variable.description}</p>
</div>
))}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setExecuteOpen(false)}>取消</Button>
<Button onClick={handleExecute}>
<Play className="w-4 h-4 mr-2" />
开始执行
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 执行日志对话框 */}
<Dialog open={logsOpen} onOpenChange={setLogsOpen}>
<DialogContent className="max-w-4xl max-h-[90vh]">
<DialogHeader>
<DialogTitle>执行日志</DialogTitle>
<DialogDescription>任务ID: {selectedJob?.id}</DialogDescription>
</DialogHeader>
<ScrollArea className="h-[500px] w-full rounded-md border bg-black">
<div className="p-4 font-mono text-sm text-green-400 whitespace-pre-wrap">
{selectedJob?.output || '暂无日志输出...'}
</div>
</ScrollArea>
<DialogFooter>
<Button variant="outline" onClick={() => setLogsOpen(false)}>关闭</Button>
<Button variant="outline">
<Download className="w-4 h-4 mr-2" />
下载日志
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
};
export default AnsibleManager;
@@ -0,0 +1,475 @@
import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import {
PlayCircle,
Plus,
Search,
Clock,
Play,
Pause,
RotateCw,
FileCode,
History,
Eye,
Edit,
Copy,
Download,
} from 'lucide-react';
import { cronJobs, scripts } from '@/mocks/data';
import type { CronJob, Script } from '@/types';
export function AutomationManager() {
const [activeTab, setActiveTab] = useState('cronjobs');
const [searchQuery, setSearchQuery] = useState('');
const [selectedScript, setSelectedScript] = useState<Script | null>(null);
const [isExecuteDialogOpen, setIsExecuteDialogOpen] = useState(false);
const filteredJobs = cronJobs.filter(
(job) =>
job.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
job.description.toLowerCase().includes(searchQuery.toLowerCase())
);
const filteredScripts = scripts.filter(
(script) =>
script.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
script.description.toLowerCase().includes(searchQuery.toLowerCase())
);
const getJobStatusBadge = (status: CronJob['status']) => {
return status === 'running' ? (
<Badge variant="outline" className="border-emerald-500/30 text-emerald-400 bg-emerald-500/10">
<Play className="h-3 w-3 mr-1" />
运行中
</Badge>
) : (
<Badge variant="outline" className="border-slate-500/30 text-slate-400 bg-slate-500/10">
<Pause className="h-3 w-3 mr-1" />
已暂停
</Badge>
);
};
const getLanguageBadge = (language: Script['language']) => {
const colors = {
bash: 'border-green-500/30 text-green-400 bg-green-500/10',
python: 'border-blue-500/30 text-blue-400 bg-blue-500/10',
powershell: 'border-cyan-500/30 text-cyan-400 bg-cyan-500/10',
};
return (
<Badge variant="outline" className={colors[language]}>
{language.toUpperCase()}
</Badge>
);
};
return (
<div className="space-y-6">
{/* Page Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-slate-100">自动化运维</h1>
<p className="text-sm text-slate-500 mt-1">定时任务与脚本管理</p>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" className="border-slate-700 text-slate-300 hover:text-slate-100 hover:bg-slate-800">
<History className="h-4 w-4 mr-2" />
执行历史
</Button>
<Button className="bg-blue-600 hover:bg-blue-700 text-white">
<Plus className="h-4 w-4 mr-2" />
新建任务
</Button>
</div>
</div>
{/* Stats Cards */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<Card className="bg-slate-900 border-slate-800">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-slate-500">定时任务</p>
<p className="text-2xl font-bold text-slate-100">{cronJobs.length}</p>
</div>
<div className="p-3 rounded-lg bg-blue-500/10 text-blue-400">
<Clock className="h-5 w-5" />
</div>
</div>
</CardContent>
</Card>
<Card className="bg-slate-900 border-slate-800">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-slate-500">运行中</p>
<p className="text-2xl font-bold text-emerald-400">
{cronJobs.filter((j) => j.status === 'running').length}
</p>
</div>
<div className="p-3 rounded-lg bg-emerald-500/10 text-emerald-400">
<Play className="h-5 w-5" />
</div>
</div>
</CardContent>
</Card>
<Card className="bg-slate-900 border-slate-800">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-slate-500">脚本数量</p>
<p className="text-2xl font-bold text-slate-100">{scripts.length}</p>
</div>
<div className="p-3 rounded-lg bg-purple-500/10 text-purple-400">
<FileCode className="h-5 w-5" />
</div>
</div>
</CardContent>
</Card>
<Card className="bg-slate-900 border-slate-800">
<CardContent className="p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-slate-500">今日执行</p>
<p className="text-2xl font-bold text-blue-400">156</p>
</div>
<div className="p-3 rounded-lg bg-cyan-500/10 text-cyan-400">
<RotateCw className="h-5 w-5" />
</div>
</div>
</CardContent>
</Card>
</div>
{/* Filters */}
<div className="flex items-center gap-3">
<div className="relative w-64">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500" />
<Input
placeholder="搜索任务或脚本..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"
/>
</div>
</div>
{/* Tabs */}
<Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
<TabsList className="bg-slate-800 border border-slate-700">
<TabsTrigger value="cronjobs" className="data-[state=active]:bg-slate-700">
<Clock className="h-4 w-4 mr-2" />
定时任务
</TabsTrigger>
<TabsTrigger value="scripts" className="data-[state=active]:bg-slate-700">
<FileCode className="h-4 w-4 mr-2" />
脚本库
</TabsTrigger>
<TabsTrigger value="playbooks" className="data-[state=active]:bg-slate-700">
<PlayCircle className="h-4 w-4 mr-2" />
任务编排
</TabsTrigger>
</TabsList>
<TabsContent value="cronjobs" className="mt-4">
<Card className="bg-slate-900 border-slate-800">
<CardContent className="p-0">
<div className="border-t border-slate-800">
<Table>
<TableHeader>
<TableRow className="border-slate-800 hover:bg-transparent">
<TableHead className="text-slate-400">任务名称</TableHead>
<TableHead className="text-slate-400">状态</TableHead>
<TableHead className="text-slate-400">Cron表达式</TableHead>
<TableHead className="text-slate-400">上次执行</TableHead>
<TableHead className="text-slate-400">下次执行</TableHead>
<TableHead className="text-slate-400">执行统计</TableHead>
<TableHead className="text-slate-400 text-right">操作</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filteredJobs.map((job) => (
<TableRow key={job.id} className="border-slate-800 hover:bg-slate-800/50">
<TableCell>
<div>
<div className="flex items-center gap-2">
<Clock className="h-4 w-4 text-slate-500" />
<span className="text-sm font-medium text-slate-200">{job.name}</span>
</div>
<p className="text-xs text-slate-500 mt-0.5">{job.description}</p>
</div>
</TableCell>
<TableCell>{getJobStatusBadge(job.status)}</TableCell>
<TableCell>
<code className="text-xs text-slate-300 bg-slate-800 px-2 py-0.5 rounded">
{job.cron}
</code>
</TableCell>
<TableCell>
<span className="text-sm text-slate-400">
{job.lastRunAt ? new Date(job.lastRunAt).toLocaleString() : '--'}
</span>
</TableCell>
<TableCell>
<span className="text-sm text-slate-400">
{job.nextRunAt ? new Date(job.nextRunAt).toLocaleString() : '--'}
</span>
</TableCell>
<TableCell>
<div className="text-sm">
<span className="text-emerald-400">{job.successCount}</span>
<span className="text-slate-500 mx-1">/</span>
<span className="text-red-400">{job.failCount}</span>
</div>
</TableCell>
<TableCell className="text-right">
<div className="flex items-center justify-end gap-1">
<Button variant="ghost" size="icon" className="h-8 w-8 text-slate-400 hover:text-blue-400">
<Play className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" className="h-8 w-8 text-slate-400 hover:text-slate-100">
<Edit className="h-4 w-4" />
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="scripts" className="mt-4">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{filteredScripts.map((script) => (
<Card key={script.id} className="bg-slate-900 border-slate-800">
<CardHeader className="pb-2">
<div className="flex items-start justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-lg bg-purple-500/10 flex items-center justify-center">
<FileCode className="h-5 w-5 text-purple-400" />
</div>
<div>
<CardTitle className="text-base text-slate-100">{script.name}</CardTitle>
<p className="text-slate-500 text-sm">{script.description}</p>
</div>
</div>
<div className="flex items-center gap-1">
{getLanguageBadge(script.language)}
</div>
</div>
</CardHeader>
<CardContent>
<div className="bg-slate-950 rounded-lg p-3 font-mono text-xs text-slate-400 overflow-x-auto">
<pre className="whitespace-pre-wrap">{script.content.slice(0, 200)}...</pre>
</div>
<div className="flex items-center justify-between mt-4">
<div className="flex gap-2">
{script.params.map((param) => (
<Badge key={param.name} variant="outline" className="border-slate-700 text-slate-400 text-xs">
{param.name}
{param.required && <span className="text-red-400 ml-0.5">*</span>}
</Badge>
))}
</div>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-slate-400 hover:text-slate-100"
onClick={() => setSelectedScript(script)}
>
<Eye className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" className="h-8 w-8 text-slate-400 hover:text-slate-100">
<Edit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 text-blue-400 hover:text-blue-400"
onClick={() => {
setSelectedScript(script);
setIsExecuteDialogOpen(true);
}}
>
<Play className="h-4 w-4 mr-1" />
执行
</Button>
</div>
</div>
</CardContent>
</Card>
))}
</div>
</TabsContent>
<TabsContent value="playbooks" className="mt-4">
<Card className="bg-slate-900 border-slate-800">
<CardContent className="p-8">
<div className="text-center">
<PlayCircle className="h-12 w-12 mx-auto text-slate-500 mb-4" />
<h3 className="text-lg font-medium text-slate-300 mb-2">任务编排</h3>
<p className="text-sm text-slate-500 mb-4">可视化编排复杂运维任务流程</p>
<Button className="bg-blue-600 hover:bg-blue-700 text-white">
<Plus className="h-4 w-4 mr-2" />
创建编排
</Button>
</div>
</CardContent>
</Card>
</TabsContent>
</Tabs>
{/* Script Detail Dialog */}
<Dialog open={!!selectedScript && !isExecuteDialogOpen} onOpenChange={() => setSelectedScript(null)}>
<DialogContent className="max-w-3xl bg-slate-900 border-slate-800">
<DialogHeader>
<DialogTitle className="text-slate-100 flex items-center gap-2">
<FileCode className="h-5 w-5 text-purple-400" />
{selectedScript?.name}
</DialogTitle>
<DialogDescription className="text-slate-500">
{selectedScript?.description}
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="flex items-center gap-2">
{selectedScript && getLanguageBadge(selectedScript.language)}
<span className="text-sm text-slate-500">
更新于 {selectedScript && new Date(selectedScript.updatedAt).toLocaleDateString()}
</span>
</div>
<div className="bg-slate-950 rounded-lg p-4 font-mono text-sm text-slate-300 overflow-x-auto max-h-80">
<pre className="whitespace-pre">{selectedScript?.content}</pre>
</div>
{selectedScript && selectedScript.params.length > 0 && (
<div>
<h4 className="text-sm font-medium text-slate-300 mb-2">参数</h4>
<div className="space-y-2">
{selectedScript.params.map((param) => (
<div key={param.name} className="flex items-center gap-2 p-2 rounded-lg bg-slate-800/50">
<code className="text-sm text-slate-300">{param.name}</code>
<Badge variant="outline" className="border-slate-700 text-slate-400 text-xs">
{param.type}
</Badge>
{param.required && (
<Badge variant="outline" className="border-red-700 text-red-400 text-xs">
必填
</Badge>
)}
<span className="text-sm text-slate-500">{param.description}</span>
</div>
))}
</div>
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" className="border-slate-700 text-slate-300">
<Copy className="h-4 w-4 mr-2" />
复制
</Button>
<Button variant="outline" className="border-slate-700 text-slate-300">
<Download className="h-4 w-4 mr-2" />
下载
</Button>
<Button
className="bg-blue-600 hover:bg-blue-700 text-white"
onClick={() => setIsExecuteDialogOpen(true)}
>
<Play className="h-4 w-4 mr-2" />
执行
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Execute Script Dialog */}
<Dialog open={isExecuteDialogOpen} onOpenChange={setIsExecuteDialogOpen}>
<DialogContent className="bg-slate-900 border-slate-800">
<DialogHeader>
<DialogTitle className="text-slate-100">执行脚本</DialogTitle>
<DialogDescription className="text-slate-500">
{selectedScript?.name}
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div>
<label className="text-sm font-medium text-slate-300">目标服务器</label>
<Select>
<SelectTrigger className="mt-1 bg-slate-800 border-slate-700 text-slate-200">
<SelectValue placeholder="选择服务器" />
</SelectTrigger>
<SelectContent className="bg-slate-800 border-slate-700">
<SelectItem value="all">全部服务器</SelectItem>
<SelectItem value="web">Web服务器组</SelectItem>
<SelectItem value="app">应用服务器组</SelectItem>
<SelectItem value="db">数据库服务器组</SelectItem>
</SelectContent>
</Select>
</div>
{selectedScript?.params.map((param) => (
<div key={param.name}>
<label className="text-sm font-medium text-slate-300">
{param.name}
{param.required && <span className="text-red-400">*</span>}
</label>
<Input
placeholder={param.description}
defaultValue={param.default}
className="mt-1 bg-slate-800 border-slate-700 text-slate-200"
/>
</div>
))}
</div>
<DialogFooter>
<Button variant="outline" className="border-slate-700 text-slate-300" onClick={() => setIsExecuteDialogOpen(false)}>
取消
</Button>
<Button className="bg-blue-600 hover:bg-blue-700 text-white">
<Play className="h-4 w-4 mr-2" />
开始执行
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
@@ -0,0 +1,474 @@
import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import {
Play,
Plus,
Search,
Clock,
Pause,
RotateCw,
Edit,
Trash2,
History,
CheckCircle,
XCircle,
Loader2,
Server,
Calendar,
Terminal,
MoreHorizontal,
Eye,
Copy,
} from 'lucide-react';
import { cronJobs } from '@/mocks/data';
interface CronJob {
id: string;
name: string;
description: string;
schedule: string;
command: string;
status: 'enabled' | 'disabled';
lastRun: string;
lastStatus: 'success' | 'failed' | 'running' | 'never';
nextRun: string;
targetServers: string[];
createdAt: string;
createdBy: string;
}
const mockCronJobs: CronJob[] = [
{
id: 'cron-001',
name: '数据库备份',
description: '每日凌晨2点备份数据库',
schedule: '0 2 * * *',
command: '/scripts/backup-db.sh --type=full',
status: 'enabled',
lastRun: '2025-04-14 02:00:00',
lastStatus: 'success',
nextRun: '2025-04-15 02:00:00',
targetServers: ['db-server-01', 'db-server-02'],
createdAt: '2025-01-15',
createdBy: 'admin',
},
{
id: 'cron-002',
name: '日志清理',
description: '每周日凌晨3点清理过期日志',
schedule: '0 3 * * 0',
command: '/scripts/clean-logs.sh --days=30',
status: 'enabled',
lastRun: '2025-04-13 03:00:00',
lastStatus: 'success',
nextRun: '2025-04-20 03:00:00',
targetServers: ['all'],
createdAt: '2025-01-20',
createdBy: 'admin',
},
{
id: 'cron-003',
name: '健康检查',
description: '每5分钟执行健康检查',
schedule: '*/5 * * * *',
command: '/scripts/health-check.sh',
status: 'enabled',
lastRun: '2025-04-14 11:55:00',
lastStatus: 'running',
nextRun: '2025-04-14 12:00:00',
targetServers: ['web-server-01', 'web-server-02', 'app-server-01'],
createdAt: '2025-02-01',
createdBy: 'ops01',
},
{
id: 'cron-004',
name: '数据同步',
description: '每小时同步数据到备份服务器',
schedule: '0 * * * *',
command: '/scripts/sync-data.sh --target=backup',
status: 'disabled',
lastRun: '2025-04-14 10:00:00',
lastStatus: 'failed',
nextRun: '-',
targetServers: ['app-server-01'],
createdAt: '2025-02-15',
createdBy: 'ops02',
},
{
id: 'cron-005',
name: '生成报表',
description: '每周一上午9点生成业务报表',
schedule: '0 9 * * 1',
command: '/scripts/generate-report.sh --type=weekly',
status: 'enabled',
lastRun: '2025-04-07 09:00:00',
lastStatus: 'success',
nextRun: '2025-04-21 09:00:00',
targetServers: ['report-server'],
createdAt: '2025-03-01',
createdBy: 'admin',
},
];
const executionLogs = [
{ id: 1, jobName: '数据库备份', startTime: '2025-04-14 02:00:00', endTime: '2025-04-14 02:15:30', duration: '15m 30s', status: 'success', output: '备份完成: 15.2GB' },
{ id: 2, jobName: '健康检查', startTime: '2025-04-14 11:55:00', endTime: '2025-04-14 11:55:05', duration: '5s', status: 'success', output: '所有服务正常' },
{ id: 3, jobName: '数据同步', startTime: '2025-04-14 10:00:00', endTime: '2025-04-14 10:05:23', duration: '5m 23s', status: 'failed', output: '连接超时' },
{ id: 4, jobName: '日志清理', startTime: '2025-04-13 03:00:00', endTime: '2025-04-13 03:02:15', duration: '2m 15s', status: 'success', output: '清理完成: 2.3GB' },
];
export function CronJobManager() {
const [searchQuery, setSearchQuery] = useState('');
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const [isLogDialogOpen, setIsLogDialogOpen] = useState(false);
const [selectedJob, setSelectedJob] = useState<CronJob | null>(null);
const [newJob, setNewJob] = useState({
name: '',
description: '',
schedule: '',
command: '',
targetServers: '',
});
const filteredJobs = mockCronJobs.filter(
(job) =>
job.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
job.description.toLowerCase().includes(searchQuery.toLowerCase())
);
const getStatusBadge = (status: CronJob['lastStatus']) => {
switch (status) {
case 'success':
return (
<Badge variant="outline" className="border-emerald-500/30 text-emerald-400 bg-emerald-500/10">
<CheckCircle className="h-3 w-3 mr-1" />
成功
</Badge>
);
case 'failed':
return (
<Badge variant="outline" className="border-red-500/30 text-red-400 bg-red-500/10">
<XCircle className="h-3 w-3 mr-1" />
失败
</Badge>
);
case 'running':
return (
<Badge variant="outline" className="border-blue-500/30 text-blue-400 bg-blue-500/10 animate-pulse">
<Loader2 className="h-3 w-3 mr-1 animate-spin" />
执行中
</Badge>
);
default:
return (
<Badge variant="outline" className="border-slate-500/30 text-slate-400 bg-slate-500/10">
从未执行
</Badge>
);
}
};
const parseCron = (schedule: string) => {
const patterns: Record<string, string> = {
'0 2 * * *': '每天 02:00',
'0 3 * * 0': '每周日 03:00',
'*/5 * * * *': '每 5 分钟',
'0 * * * *': '每小时',
'0 9 * * 1': '每周一 09:00',
};
return patterns[schedule] || schedule;
};
const handleCreateJob = () => {
setIsCreateDialogOpen(false);
setNewJob({ name: '', description: '', schedule: '', command: '', targetServers: '' });
};
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-slate-100">定时任务</h1>
<p className="text-sm text-slate-500 mt-1">Cron 任务管理与执行</p>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" className="border-slate-700 text-slate-300" onClick={() => setIsLogDialogOpen(true)}>
<History className="h-4 w-4 mr-2" />
执行历史
</Button>
<Button className="bg-blue-600 hover:bg-blue-700" onClick={() => setIsCreateDialogOpen(true)}>
<Plus className="h-4 w-4 mr-2" />
新建任务
</Button>
</div>
</div>
{/* Stats */}
<div className="grid grid-cols-4 gap-4">
<Card className="bg-slate-800 border-slate-700">
<CardContent className="p-4">
<p className="text-slate-400 text-sm">任务总数</p>
<p className="text-2xl font-bold text-slate-100">{mockCronJobs.length}</p>
</CardContent>
</Card>
<Card className="bg-slate-800 border-slate-700">
<CardContent className="p-4">
<p className="text-slate-400 text-sm">已启用</p>
<p className="text-2xl font-bold text-emerald-400">
{mockCronJobs.filter((j) => j.status === 'enabled').length}
</p>
</CardContent>
</Card>
<Card className="bg-slate-800 border-slate-700">
<CardContent className="p-4">
<p className="text-slate-400 text-sm">执行中</p>
<p className="text-2xl font-bold text-blue-400">
{mockCronJobs.filter((j) => j.lastStatus === 'running').length}
</p>
</CardContent>
</Card>
<Card className="bg-slate-800 border-slate-700">
<CardContent className="p-4">
<p className="text-slate-400 text-sm">今日失败</p>
<p className="text-2xl font-bold text-red-400">
{mockCronJobs.filter((j) => j.lastStatus === 'failed').length}
</p>
</CardContent>
</Card>
</div>
{/* Filters */}
<div className="flex items-center gap-4">
<div className="relative flex-1 max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
<Input
placeholder="搜索任务..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10 bg-slate-800 border-slate-700 text-slate-100"
/>
</div>
</div>
{/* Job List */}
<div className="space-y-3">
{filteredJobs.map((job) => (
<Card key={job.id} className="bg-slate-800 border-slate-700">
<CardContent className="p-4">
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-3">
<h3 className="font-medium text-slate-100">{job.name}</h3>
<Badge
variant="outline"
className={
job.status === 'enabled'
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
: 'border-slate-500/30 text-slate-400 bg-slate-500/10'
}
>
{job.status === 'enabled' ? '已启用' : '已禁用'}
</Badge>
{getStatusBadge(job.lastStatus)}
</div>
<p className="text-sm text-slate-400 mt-1">{job.description}</p>
<div className="flex items-center gap-4 mt-2 text-sm">
<span className="flex items-center gap-1 text-slate-400">
<Clock className="h-3 w-3" />
{parseCron(job.schedule)}
</span>
<span className="flex items-center gap-1 text-slate-400">
<Terminal className="h-3 w-3" />
<code className="text-xs bg-slate-900 px-2 py-0.5 rounded">{job.command}</code>
</span>
</div>
<div className="flex items-center gap-4 mt-2 text-xs text-slate-500">
<span>上次执行: {job.lastRun}</span>
<span>下次执行: {job.nextRun}</span>
<span>目标: {job.targetServers.join(', ')}</span>
</div>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" className="border-emerald-600 text-emerald-400 hover:bg-emerald-600/20">
<Play className="h-4 w-4 mr-1" />
立即执行
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-slate-400 hover:text-blue-400"
>
<Edit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-slate-400 hover:text-red-400"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</CardContent>
</Card>
))}
</div>
{/* Create Job Dialog */}
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogContent className="max-w-2xl bg-slate-900 border-slate-700 text-slate-100">
<DialogHeader>
<DialogTitle>新建定时任务</DialogTitle>
<DialogDescription className="text-slate-500">配置 Cron 定时任务</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div>
<Label className="text-slate-300">任务名称</Label>
<Input
value={newJob.name}
onChange={(e) => setNewJob({ ...newJob, name: e.target.value })}
placeholder="例如: 数据库备份"
className="bg-slate-800 border-slate-700 text-slate-100 mt-1"
/>
</div>
<div>
<Label className="text-slate-300">描述</Label>
<Textarea
value={newJob.description}
onChange={(e) => setNewJob({ ...newJob, description: e.target.value })}
placeholder="任务描述..."
className="bg-slate-800 border-slate-700 text-slate-100 mt-1"
/>
</div>
<div>
<Label className="text-slate-300">Cron 表达式</Label>
<div className="flex gap-2">
<Input
value={newJob.schedule}
onChange={(e) => setNewJob({ ...newJob, schedule: e.target.value })}
placeholder="0 2 * * *"
className="bg-slate-800 border-slate-700 text-slate-100 mt-1"
/>
<Select onValueChange={(v) => setNewJob({ ...newJob, schedule: v })}>
<SelectTrigger className="w-48 bg-slate-800 border-slate-700 text-slate-100 mt-1">
<SelectValue placeholder="快速选择" />
</SelectTrigger>
<SelectContent className="bg-slate-800 border-slate-700">
<SelectItem value="*/5 * * * *" className="text-slate-100">每 5 分钟</SelectItem>
<SelectItem value="0 * * * *" className="text-slate-100">每小时</SelectItem>
<SelectItem value="0 2 * * *" className="text-slate-100">每天 02:00</SelectItem>
<SelectItem value="0 3 * * 0" className="text-slate-100">每周日 03:00</SelectItem>
<SelectItem value="0 9 * * 1" className="text-slate-100">每周一 09:00</SelectItem>
</SelectContent>
</Select>
</div>
<p className="text-xs text-slate-500 mt-1">格式: 分 时 日 月 周</p>
</div>
<div>
<Label className="text-slate-300">执行命令</Label>
<Textarea
value={newJob.command}
onChange={(e) => setNewJob({ ...newJob, command: e.target.value })}
placeholder="/scripts/backup.sh"
className="bg-slate-800 border-slate-700 text-slate-100 mt-1 font-mono"
/>
</div>
<div>
<Label className="text-slate-300">目标服务器</Label>
<Input
value={newJob.targetServers}
onChange={(e) => setNewJob({ ...newJob, targetServers: e.target.value })}
placeholder="server1,server2 或 all"
className="bg-slate-800 border-slate-700 text-slate-100 mt-1"
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setIsCreateDialogOpen(false)} className="border-slate-700 text-slate-300">
取消
</Button>
<Button className="bg-blue-600 hover:bg-blue-700" onClick={handleCreateJob}>
创建任务
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Execution Log Dialog */}
<Dialog open={isLogDialogOpen} onOpenChange={setIsLogDialogOpen}>
<DialogContent className="max-w-4xl bg-slate-900 border-slate-700 text-slate-100">
<DialogHeader>
<DialogTitle>执行历史</DialogTitle>
<DialogDescription className="text-slate-500">定时任务执行记录</DialogDescription>
</DialogHeader>
<div className="mt-4">
<Table>
<TableHeader>
<TableRow className="border-slate-700">
<TableHead className="text-slate-400">任务</TableHead>
<TableHead className="text-slate-400">开始时间</TableHead>
<TableHead className="text-slate-400">耗时</TableHead>
<TableHead className="text-slate-400">状态</TableHead>
<TableHead className="text-slate-400">输出</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{executionLogs.map((log) => (
<TableRow key={log.id} className="border-slate-700">
<TableCell className="text-slate-200">{log.jobName}</TableCell>
<TableCell className="text-slate-400">{log.startTime}</TableCell>
<TableCell className="text-slate-400">{log.duration}</TableCell>
<TableCell>
<Badge
variant="outline"
className={
log.status === 'success'
? 'border-emerald-500/30 text-emerald-400 bg-emerald-500/10'
: 'border-red-500/30 text-red-400 bg-red-500/10'
}
>
{log.status === 'success' ? '成功' : '失败'}
</Badge>
</TableCell>
<TableCell className="text-slate-400 text-sm">{log.output}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</DialogContent>
</Dialog>
</div>
);
}