feat: 累积功能变更 — 聊天集成、租户管理、小程序更新、ETL 增强、迁移脚本
包含多个会话的累积代码变更: - backend: AI 聊天服务、触发器调度、认证增强、WebSocket、调度器最小间隔 - admin-web: ETL 状态页、任务管理、调度配置、登录优化 - miniprogram: 看板页面、聊天集成、UI 组件、导航更新 - etl: DWS 新任务(finance_area_daily/board_cache)、连接器增强 - tenant-admin: 项目初始化 - db: 19 个迁移脚本(etl_feiqiu 11 + zqyy_app 8) - packages/shared: 枚举和工具函数更新 - tools: 数据库工具、报表生成、健康检查 - docs: PRD/架构/部署/合约文档更新 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -2,8 +2,15 @@
|
||||
* 主布局与路由配置。
|
||||
*
|
||||
* - Ant Design Layout:Sider + Content + Footer(状态栏)
|
||||
* - react-router-dom:6 个功能页面路由 + 登录页路由
|
||||
* - react-router-dom:路由守卫 + 7 个一级菜单模块
|
||||
* - 路由守卫:未登录重定向到登录页
|
||||
*
|
||||
* CHANGE 2026-03-23 | Task 6 Change B:新增「定时任务」菜单项和 /trigger-jobs 路由;
|
||||
* 新增租户管理员、AI 监控子菜单组(4 子路由)、开发调试日志路由;
|
||||
* import 7 个新页面组件(TriggerJobs/TenantAdmins/AIDashboard/AITriggerJobs/AIRunLogs/AIOperations/DevTrace)
|
||||
* CHANGE 2026-07-14 | Task 7.1:侧边栏菜单从 11 个一级项重组为 7 个;
|
||||
* 新增 Dashboard/ETLTasks/TriggerManager 占位页面;路由重构(新增重定向、移动路由);
|
||||
* 移除 LogViewer 及不再直接路由的页面 import;登录后导航到 /dashboard
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
@@ -12,12 +19,12 @@ import { Layout, Menu, Spin, Space, Typography, Tag, Button, Tooltip } from "ant
|
||||
import {
|
||||
SettingOutlined,
|
||||
UnorderedListOutlined,
|
||||
ToolOutlined,
|
||||
DatabaseOutlined,
|
||||
DashboardOutlined,
|
||||
FileTextOutlined,
|
||||
ClockCircleOutlined,
|
||||
LogoutOutlined,
|
||||
DesktopOutlined,
|
||||
TeamOutlined,
|
||||
BugOutlined,
|
||||
ApartmentOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import type { MenuProps } from "antd";
|
||||
import { useAuthStore } from "./store/authStore";
|
||||
@@ -25,31 +32,85 @@ import { useBusinessDayStore } from "./store/businessDayStore";
|
||||
import { fetchQueue } from "./api/execution";
|
||||
import type { QueuedTask } from "./types";
|
||||
import Login from "./pages/Login";
|
||||
import TaskConfig from "./pages/TaskConfig";
|
||||
import TaskManager from "./pages/TaskManager";
|
||||
import EnvConfig from "./pages/EnvConfig";
|
||||
import DBViewer from "./pages/DBViewer";
|
||||
import ETLStatus from "./pages/ETLStatus";
|
||||
import LogViewer from "./pages/LogViewer";
|
||||
import OpsPanel from "./pages/OpsPanel";
|
||||
import TenantAdmins from "./pages/TenantAdmins";
|
||||
import AIRunLogs from "./pages/AIRunLogs";
|
||||
import DevTrace from "./pages/DevTrace";
|
||||
import TriggerJobs from "./pages/TriggerJobs";
|
||||
import TransferLog from "./pages/TransferLog";
|
||||
import PendingReview from "./pages/PendingReview";
|
||||
import TaskEngineConfig from "./pages/TaskEngineConfig";
|
||||
import Dashboard from "./pages/Dashboard";
|
||||
import ETLTasks from "./pages/ETLTasks";
|
||||
import TriggerManager from "./pages/TriggerManager";
|
||||
|
||||
const { Sider, Content, Footer } = Layout;
|
||||
const { Text } = Typography;
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 侧边栏导航配置 */
|
||||
/* 侧边栏导航配置(7 个一级菜单) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const NAV_ITEMS: MenuProps["items"] = [
|
||||
{ key: "/", icon: <SettingOutlined />, label: "任务配置" },
|
||||
{ key: "/task-manager", icon: <UnorderedListOutlined />, label: "任务管理" },
|
||||
{ key: "/etl-status", icon: <DashboardOutlined />, label: "ETL 状态" },
|
||||
{ key: "/db-viewer", icon: <DatabaseOutlined />, label: "数据库" },
|
||||
{ key: "/log-viewer", icon: <FileTextOutlined />, label: "日志" },
|
||||
{ key: "/env-config", icon: <ToolOutlined />, label: "环境配置" },
|
||||
{ key: "/ops-panel", icon: <DesktopOutlined />, label: "运维面板" },
|
||||
export const NAV_ITEMS: MenuProps["items"] = [
|
||||
{ key: "/dashboard", icon: <DashboardOutlined />, label: "运行状态" },
|
||||
{ key: "/etl-tasks", icon: <UnorderedListOutlined />, label: "ETL 任务管理" },
|
||||
{
|
||||
key: "task-engine-group", icon: <ApartmentOutlined />, label: "小程序任务管理",
|
||||
children: [
|
||||
{ key: "/task-engine/trigger-jobs", label: "定时任务" },
|
||||
{ key: "/task-engine/transfer-log", label: "转移日志" },
|
||||
{ key: "/task-engine/pending-review", label: "待审核任务" },
|
||||
{ key: "/task-engine/config", label: "参数管理" },
|
||||
],
|
||||
},
|
||||
{ key: "/triggers", icon: <ClockCircleOutlined />, label: "触发器管理" },
|
||||
{ key: "/tenant-admins", icon: <TeamOutlined />, label: "租户管理员" },
|
||||
{
|
||||
key: "settings-group", icon: <SettingOutlined />, label: "系统设置",
|
||||
children: [
|
||||
{ key: "/settings/env-config", label: "环境配置" },
|
||||
{ key: "/triggers?tab=biz", label: "触发器配置" },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "logs-group", icon: <BugOutlined />, label: "日志调试",
|
||||
children: [
|
||||
{ key: "/logs/dev-trace", label: "DevTrace" },
|
||||
{ key: "/logs/ai-run-logs", label: "AI 调用明细" },
|
||||
{ key: "/logs/db-viewer", label: "数据库查看器" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 侧边栏高亮辅助函数 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** 根据当前路径计算 selectedKeys */
|
||||
export function getSelectedKeys(pathname: string, search: string): string[] {
|
||||
const fullPath = pathname + search;
|
||||
// 精确匹配含查询参数的菜单项(如 /triggers?tab=biz)
|
||||
if (fullPath === "/triggers?tab=biz") return ["/triggers?tab=biz"];
|
||||
// 子路由匹配
|
||||
if (pathname.startsWith("/task-engine/")) return [pathname];
|
||||
if (pathname.startsWith("/settings/")) return [pathname];
|
||||
if (pathname.startsWith("/logs/")) return [pathname];
|
||||
// 一级路由直接匹配
|
||||
return [pathname];
|
||||
}
|
||||
|
||||
/** 根据当前路径计算 defaultOpenKeys */
|
||||
export function getDefaultOpenKeys(pathname: string): string[] {
|
||||
const keys: string[] = [];
|
||||
if (pathname.startsWith("/task-engine/")) keys.push("task-engine-group");
|
||||
if (pathname.startsWith("/settings/")) keys.push("settings-group");
|
||||
if (pathname.startsWith("/logs/")) keys.push("logs-group");
|
||||
// 触发器配置跳转入口也需要展开系统设置
|
||||
if (pathname === "/triggers") keys.push("settings-group");
|
||||
return keys;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 路由守卫 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
@@ -97,7 +158,15 @@ const AppLayout: React.FC = () => {
|
||||
<Layout style={{ minHeight: "100vh" }}>
|
||||
<Sider
|
||||
collapsible
|
||||
style={{ display: "flex", flexDirection: "column" }}
|
||||
style={{
|
||||
overflow: "auto",
|
||||
height: "100vh",
|
||||
position: "sticky",
|
||||
top: 0,
|
||||
left: 0,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
@@ -118,7 +187,8 @@ const AppLayout: React.FC = () => {
|
||||
<Menu
|
||||
theme="dark"
|
||||
mode="inline"
|
||||
selectedKeys={[location.pathname]}
|
||||
selectedKeys={getSelectedKeys(location.pathname, location.search)}
|
||||
defaultOpenKeys={getDefaultOpenKeys(location.pathname)}
|
||||
items={NAV_ITEMS}
|
||||
onClick={onMenuClick}
|
||||
/>
|
||||
@@ -138,13 +208,31 @@ const AppLayout: React.FC = () => {
|
||||
<Layout>
|
||||
<Content style={{ margin: 16, minHeight: 280 }}>
|
||||
<Routes>
|
||||
<Route path="/" element={<TaskConfig />} />
|
||||
<Route path="/task-manager" element={<TaskManager />} />
|
||||
<Route path="/env-config" element={<EnvConfig />} />
|
||||
<Route path="/db-viewer" element={<DBViewer />} />
|
||||
<Route path="/etl-status" element={<ETLStatus />} />
|
||||
<Route path="/log-viewer" element={<LogViewer />} />
|
||||
<Route path="/ops-panel" element={<OpsPanel />} />
|
||||
{/* 重定向 */}
|
||||
<Route path="/" element={<Navigate to="/dashboard" replace />} />
|
||||
<Route path="/log-viewer" element={<Navigate to="/etl-tasks?tab=queue" replace />} />
|
||||
|
||||
{/* 新页面 */}
|
||||
<Route path="/dashboard" element={<Dashboard />} />
|
||||
<Route path="/etl-tasks" element={<ETLTasks />} />
|
||||
<Route path="/triggers" element={<TriggerManager />} />
|
||||
|
||||
{/* 小程序任务管理 */}
|
||||
<Route path="/task-engine/trigger-jobs" element={<TriggerJobs />} />
|
||||
<Route path="/task-engine/transfer-log" element={<TransferLog />} />
|
||||
<Route path="/task-engine/pending-review" element={<PendingReview />} />
|
||||
<Route path="/task-engine/config" element={<TaskEngineConfig />} />
|
||||
|
||||
{/* 系统设置 */}
|
||||
<Route path="/settings/env-config" element={<EnvConfig />} />
|
||||
|
||||
{/* 日志调试 */}
|
||||
<Route path="/logs/dev-trace" element={<DevTrace />} />
|
||||
<Route path="/logs/ai-run-logs" element={<AIRunLogs />} />
|
||||
<Route path="/logs/db-viewer" element={<DBViewer />} />
|
||||
|
||||
{/* 不变 */}
|
||||
<Route path="/tenant-admins" element={<TenantAdmins />} />
|
||||
</Routes>
|
||||
</Content>
|
||||
<Footer
|
||||
|
||||
299
apps/admin-web/src/__tests__/dashboard.test.tsx
Normal file
299
apps/admin-web/src/__tests__/dashboard.test.tsx
Normal file
@@ -0,0 +1,299 @@
|
||||
/**
|
||||
* 单元测试:Dashboard 页面 + DbHealthCard 组件
|
||||
*
|
||||
* _Requirements: 2.1, 2.2, 2.3, 2.4, 2.5_
|
||||
*
|
||||
* - 测试 4 个区块正确渲染
|
||||
* - 测试跳转链接指向正确路由
|
||||
* - 测试 DbHealthCard connected/disconnected/timeout 状态渲染
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest";
|
||||
import { render, screen, fireEvent } from "@testing-library/react";
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import React from "react";
|
||||
import DbHealthCard from "../components/DbHealthCard";
|
||||
import type { DbHealthItem } from "../api/dbHealth";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Ant Design jsdom 兼容:polyfill window.matchMedia */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation((query: string) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Mock 所有 Dashboard 依赖的 API 模块 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
vi.mock("../api/opsPanel", () => ({
|
||||
fetchSystemInfo: vi.fn().mockResolvedValue({
|
||||
cpu_percent: 25,
|
||||
memory_total_gb: 16,
|
||||
memory_used_gb: 8,
|
||||
memory_percent: 50,
|
||||
disk_total_gb: 500,
|
||||
disk_used_gb: 250,
|
||||
disk_percent: 50,
|
||||
boot_time: "2026-01-01T00:00:00",
|
||||
}),
|
||||
fetchServicesStatus: vi.fn().mockResolvedValue([
|
||||
{
|
||||
env: "prod",
|
||||
label: "生产环境",
|
||||
running: true,
|
||||
pid: 1234,
|
||||
port: 8000,
|
||||
uptime_seconds: 3600,
|
||||
memory_mb: 256,
|
||||
cpu_percent: 10,
|
||||
},
|
||||
]),
|
||||
fetchGitInfo: vi.fn().mockResolvedValue([
|
||||
{
|
||||
env: "prod",
|
||||
branch: "main",
|
||||
last_commit_hash: "abc1234",
|
||||
last_commit_message: "test commit",
|
||||
last_commit_time: "2026-01-01T00:00:00",
|
||||
has_local_changes: false,
|
||||
},
|
||||
]),
|
||||
startService: vi.fn(),
|
||||
stopService: vi.fn(),
|
||||
restartService: vi.fn(),
|
||||
gitPull: vi.fn(),
|
||||
syncDeps: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../api/dbHealth", () => ({
|
||||
fetchDbHealth: vi.fn().mockResolvedValue([
|
||||
{
|
||||
db_name: "etl_feiqiu",
|
||||
status: "connected",
|
||||
active_connections: 5,
|
||||
idle_connections: 10,
|
||||
db_size_mb: 128.5,
|
||||
slow_query_count: 2,
|
||||
},
|
||||
{
|
||||
db_name: "test_etl_feiqiu",
|
||||
status: "disconnected",
|
||||
active_connections: null,
|
||||
idle_connections: null,
|
||||
db_size_mb: null,
|
||||
slow_query_count: null,
|
||||
},
|
||||
]),
|
||||
}));
|
||||
|
||||
vi.mock("../api/adminAI", () => ({
|
||||
getTriggerJobs: vi.fn().mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
page: 1,
|
||||
page_size: 50,
|
||||
today_skipped_duplicates: 0,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock AIDashboard 为简单占位,避免其内部 API 调用
|
||||
vi.mock("../pages/AIDashboard", () => ({
|
||||
default: () => <div data-testid="ai-dashboard-mock">AIDashboard</div>,
|
||||
}));
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Dashboard 页面测试 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("Dashboard 页面 (Requirements 2.1, 2.2)", () => {
|
||||
let Dashboard: React.FC;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
const mod = await import("../pages/Dashboard");
|
||||
Dashboard = mod.default;
|
||||
});
|
||||
|
||||
it("渲染 4 个区块:OpsPanel 子组件、DbHealthCard、AI 运行总览、AI 调度摘要", async () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/dashboard"]}>
|
||||
<Dashboard />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
// 区块 1:OpsPanel 子组件 — 页面标题"运行状态"
|
||||
expect(await screen.findByText("运行状态")).toBeInTheDocument();
|
||||
|
||||
// 区块 2:数据库健康监控
|
||||
expect(screen.getByText("数据库健康监控")).toBeInTheDocument();
|
||||
|
||||
// 区块 3:AI 运行总览(mocked AIDashboard)
|
||||
expect(screen.getByText("AI 运行总览")).toBeInTheDocument();
|
||||
expect(screen.getByTestId("ai-dashboard-mock")).toBeInTheDocument();
|
||||
|
||||
// 区块 4:AI 调度摘要(Divider + Card title 各出现一次)
|
||||
const summaryElements = screen.getAllByText("AI 调度摘要");
|
||||
expect(summaryElements.length).toBeGreaterThanOrEqual(1);
|
||||
expect(screen.getByText("今日触发数")).toBeInTheDocument();
|
||||
expect(screen.getByText("今日成功率")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("跳转链接:ETL 状态详情、触发器详情、AI 调度详情", async () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/dashboard"]}>
|
||||
<Dashboard />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
await screen.findByText("运行状态");
|
||||
|
||||
expect(screen.getByText(/ETL 状态详情/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/触发器详情/)).toBeInTheDocument();
|
||||
|
||||
// AI 调度详情出现两次(顶部按钮 + 底部链接),取第一个
|
||||
const aiButtons = screen.getAllByText(/AI 调度详情/);
|
||||
expect(aiButtons.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* DbHealthCard 组件测试(纯展示组件,不需要 mock API) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("DbHealthCard — connected 状态 (Requirements 2.3, 2.4)", () => {
|
||||
const connectedItems: DbHealthItem[] = [
|
||||
{
|
||||
db_name: "etl_feiqiu",
|
||||
status: "connected",
|
||||
active_connections: 5,
|
||||
idle_connections: 10,
|
||||
db_size_mb: 128.5,
|
||||
slow_query_count: 2,
|
||||
},
|
||||
{
|
||||
db_name: "zqyy_app",
|
||||
status: "connected",
|
||||
active_connections: 3,
|
||||
idle_connections: 7,
|
||||
db_size_mb: 256.0,
|
||||
slow_query_count: 0,
|
||||
},
|
||||
];
|
||||
|
||||
it("为每个 connected 数据库渲染卡片,显示「已连接」标签", () => {
|
||||
render(<DbHealthCard items={connectedItems} />);
|
||||
|
||||
expect(screen.getByText("etl_feiqiu")).toBeInTheDocument();
|
||||
expect(screen.getByText("zqyy_app")).toBeInTheDocument();
|
||||
|
||||
const connectedTags = screen.getAllByText("已连接");
|
||||
expect(connectedTags).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("展示连接池指标(活跃/空闲连接数)", () => {
|
||||
render(<DbHealthCard items={connectedItems} />);
|
||||
|
||||
expect(screen.getByText(/活跃 5/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/空闲 10/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("展示数据库大小和慢查询数量", () => {
|
||||
render(<DbHealthCard items={connectedItems} />);
|
||||
|
||||
const sizeLabels = screen.getAllByText("数据库大小");
|
||||
expect(sizeLabels.length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
const slowLabels = screen.getAllByText(/慢查询/);
|
||||
expect(slowLabels.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("DbHealthCard — disconnected 状态 (Requirement 2.5)", () => {
|
||||
const disconnectedItems: DbHealthItem[] = [
|
||||
{
|
||||
db_name: "test_etl_feiqiu",
|
||||
status: "disconnected",
|
||||
active_connections: null,
|
||||
idle_connections: null,
|
||||
db_size_mb: null,
|
||||
slow_query_count: null,
|
||||
},
|
||||
];
|
||||
|
||||
it("disconnected 数据库显示「未连接」标签", () => {
|
||||
render(<DbHealthCard items={disconnectedItems} />);
|
||||
|
||||
expect(screen.getByText("test_etl_feiqiu")).toBeInTheDocument();
|
||||
expect(screen.getByText("未连接")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("disconnected 数据库显示无法获取指标提示", () => {
|
||||
render(<DbHealthCard items={disconnectedItems} />);
|
||||
|
||||
expect(screen.getByText("数据库未连接,无法获取指标")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("DbHealthCard — timeout 状态", () => {
|
||||
it("超时时显示「加载超时」标签", () => {
|
||||
render(<DbHealthCard items={[]} timeout={true} />);
|
||||
|
||||
expect(screen.getByText("加载超时")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("超时时显示重试按钮,点击触发 onRetry", () => {
|
||||
const onRetry = vi.fn();
|
||||
render(<DbHealthCard items={[]} timeout={true} onRetry={onRetry} />);
|
||||
|
||||
const retryBtn = screen.getByText("重试");
|
||||
expect(retryBtn).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(retryBtn);
|
||||
expect(onRetry).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("DbHealthCard — mixed 状态(connected + disconnected)", () => {
|
||||
const mixedItems: DbHealthItem[] = [
|
||||
{
|
||||
db_name: "etl_feiqiu",
|
||||
status: "connected",
|
||||
active_connections: 5,
|
||||
idle_connections: 10,
|
||||
db_size_mb: 128.5,
|
||||
slow_query_count: 2,
|
||||
},
|
||||
{
|
||||
db_name: "test_etl_feiqiu",
|
||||
status: "disconnected",
|
||||
active_connections: null,
|
||||
idle_connections: null,
|
||||
db_size_mb: null,
|
||||
slow_query_count: null,
|
||||
},
|
||||
];
|
||||
|
||||
it("同时渲染 connected 和 disconnected 卡片", () => {
|
||||
render(<DbHealthCard items={mixedItems} />);
|
||||
|
||||
expect(screen.getByText("已连接")).toBeInTheDocument();
|
||||
expect(screen.getByText("未连接")).toBeInTheDocument();
|
||||
expect(screen.getByText("etl_feiqiu")).toBeInTheDocument();
|
||||
expect(screen.getByText("test_etl_feiqiu")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
238
apps/admin-web/src/__tests__/etlTasks.test.tsx
Normal file
238
apps/admin-web/src/__tests__/etlTasks.test.tsx
Normal file
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* 单元测试:ETLTasks 页面
|
||||
*
|
||||
* _Requirements: 3.1, 3.2, 3.3, 3.4, 10.4_
|
||||
*
|
||||
* - 测试默认 Tab 为 config(发起)
|
||||
* - 测试 5 个 Tab 内容正确渲染
|
||||
* - 测试 URL 参数驱动 Tab 选择
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeAll, afterEach } from "vitest";
|
||||
import { render, screen, cleanup } from "@testing-library/react";
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Ant Design jsdom 兼容:polyfill window.matchMedia */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation((query: string) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Mock 子组件,避免内部 API 调用 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
vi.mock("../pages/TaskConfig", () => ({
|
||||
default: () => <div data-testid="mock-task-config">TaskConfig Mock</div>,
|
||||
}));
|
||||
vi.mock("../pages/TaskManager", () => ({
|
||||
QueueTab: () => <div data-testid="mock-queue-tab">QueueTab Mock</div>,
|
||||
HistoryTab: () => <div data-testid="mock-history-tab">HistoryTab Mock</div>,
|
||||
}));
|
||||
vi.mock("../components/ScheduleTab", () => ({
|
||||
default: () => <div data-testid="mock-schedule-tab">ScheduleTab Mock</div>,
|
||||
}));
|
||||
vi.mock("../pages/ETLStatus", () => ({
|
||||
default: () => <div data-testid="mock-etl-status">ETLStatus Mock</div>,
|
||||
}));
|
||||
|
||||
import ETLTasks from "../pages/ETLTasks";
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 测试:默认 Tab 为 config(Requirements 3.1, 3.2) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("ETLTasks — 默认 Tab (Requirements 3.1, 3.2)", () => {
|
||||
it("无 ?tab 参数时,默认激活 config Tab(发起)", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/etl-tasks"]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
const activeTab = document.querySelector(".ant-tabs-tab-active");
|
||||
expect(activeTab).not.toBeNull();
|
||||
expect(activeTab!.textContent).toContain("发起");
|
||||
});
|
||||
|
||||
it("无效 ?tab 参数时,回退到默认 config Tab", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/etl-tasks?tab=invalid"]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
const activeTab = document.querySelector(".ant-tabs-tab-active");
|
||||
expect(activeTab).not.toBeNull();
|
||||
expect(activeTab!.textContent).toContain("发起");
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 测试:4 个 Tab 内容正确渲染(Requirements 3.2, 3.3, 3.4) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("ETLTasks — 5 个 Tab 内容渲染 (Requirements 3.2, 3.3, 3.4)", () => {
|
||||
it("config Tab 渲染 TaskConfig 组件", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/etl-tasks?tab=config"]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("mock-task-config")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("queue Tab 渲染 QueueTab 组件", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/etl-tasks?tab=queue"]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("mock-queue-tab")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("schedule Tab 渲染 ScheduleTab 组件", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/etl-tasks?tab=schedule"]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("mock-schedule-tab")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("history Tab 渲染 HistoryTab 组件", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/etl-tasks?tab=history"]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("mock-history-tab")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("status Tab 渲染 ETLStatus 组件", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/etl-tasks?tab=status"]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("mock-etl-status")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("页面标题包含「ETL 任务管理」", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/etl-tasks"]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
expect(screen.getByText("ETL 任务管理")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("5 个 Tab 标签文本正确:发起、队列、调度、历史、状态", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/etl-tasks"]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
const tabs = document.querySelectorAll(".ant-tabs-tab");
|
||||
expect(tabs).toHaveLength(5);
|
||||
|
||||
const tabTexts = Array.from(tabs).map((t) => t.textContent);
|
||||
expect(tabTexts).toContain("发起");
|
||||
expect(tabTexts).toContain("队列");
|
||||
expect(tabTexts).toContain("调度");
|
||||
expect(tabTexts).toContain("历史");
|
||||
expect(tabTexts).toContain("状态");
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 测试:URL 参数驱动 Tab 选择(Requirement 10.4) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("ETLTasks — URL 参数驱动 Tab 选择 (Requirement 10.4)", () => {
|
||||
it("?tab=config 激活「发起」Tab", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/etl-tasks?tab=config"]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
const activeTab = document.querySelector(".ant-tabs-tab-active");
|
||||
expect(activeTab).not.toBeNull();
|
||||
expect(activeTab!.textContent).toContain("发起");
|
||||
});
|
||||
|
||||
it("?tab=queue 激活「队列」Tab", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/etl-tasks?tab=queue"]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
const activeTab = document.querySelector(".ant-tabs-tab-active");
|
||||
expect(activeTab).not.toBeNull();
|
||||
expect(activeTab!.textContent).toContain("队列");
|
||||
});
|
||||
|
||||
it("?tab=schedule 激活「调度」Tab", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/etl-tasks?tab=schedule"]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
const activeTab = document.querySelector(".ant-tabs-tab-active");
|
||||
expect(activeTab).not.toBeNull();
|
||||
expect(activeTab!.textContent).toContain("调度");
|
||||
});
|
||||
|
||||
it("?tab=history 激活「历史」Tab", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/etl-tasks?tab=history"]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
const activeTab = document.querySelector(".ant-tabs-tab-active");
|
||||
expect(activeTab).not.toBeNull();
|
||||
expect(activeTab!.textContent).toContain("历史");
|
||||
});
|
||||
|
||||
it("?tab=status 激活「状态」Tab", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/etl-tasks?tab=status"]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
const activeTab = document.querySelector(".ant-tabs-tab-active");
|
||||
expect(activeTab).not.toBeNull();
|
||||
expect(activeTab!.textContent).toContain("状态");
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,7 @@
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { filterLogLines } from "../pages/LogViewer";
|
||||
import { filterLogLines } from "../pages/_archived/LogViewer";
|
||||
|
||||
describe("filterLogLines — 日志过滤正确性", () => {
|
||||
/* ---- 1. 空关键词返回所有行 ---- */
|
||||
|
||||
140
apps/admin-web/src/__tests__/menuAndRedirects.test.tsx
Normal file
140
apps/admin-web/src/__tests__/menuAndRedirects.test.tsx
Normal file
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* 单元测试:菜单结构与路由重定向
|
||||
*
|
||||
* _Requirements: 1.1, 8.3, 10.1, 10.2_
|
||||
*
|
||||
* - 验证 NAV_ITEMS 包含 7 个一级菜单项且子项正确
|
||||
* - 验证 `/` 重定向到 `/dashboard`
|
||||
* - 验证 `/log-viewer` 重定向到 `/etl-tasks?tab=queue`
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { render } from "@testing-library/react";
|
||||
import { MemoryRouter, Routes, Route, Navigate, useLocation } from "react-router-dom";
|
||||
import { NAV_ITEMS } from "../App";
|
||||
import type { MenuProps } from "antd";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 菜单结构测试(纯数据,无 DOM) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
type MenuItem = NonNullable<MenuProps["items"]>[number] & {
|
||||
key?: string;
|
||||
label?: string;
|
||||
children?: MenuItem[];
|
||||
};
|
||||
|
||||
describe("菜单结构验证 (Requirement 1.1)", () => {
|
||||
const items = NAV_ITEMS as MenuItem[];
|
||||
|
||||
it("NAV_ITEMS 包含 7 个一级菜单项", () => {
|
||||
expect(items).toHaveLength(7);
|
||||
});
|
||||
|
||||
it("7 个一级菜单项的 label 和顺序正确", () => {
|
||||
const labels = items.map((item) => item.label);
|
||||
expect(labels).toEqual([
|
||||
"运行状态",
|
||||
"ETL 任务管理",
|
||||
"小程序任务管理",
|
||||
"触发器管理",
|
||||
"租户管理员",
|
||||
"系统设置",
|
||||
"日志调试",
|
||||
]);
|
||||
});
|
||||
|
||||
it("「小程序任务管理」包含 4 个子项:定时任务、转移日志、待审核任务、参数管理", () => {
|
||||
const taskEngine = items.find((i) => i.label === "小程序任务管理");
|
||||
expect(taskEngine).toBeDefined();
|
||||
const children = taskEngine!.children ?? [];
|
||||
expect(children).toHaveLength(4);
|
||||
expect(children.map((c) => c.label)).toEqual([
|
||||
"定时任务",
|
||||
"转移日志",
|
||||
"待审核任务",
|
||||
"参数管理",
|
||||
]);
|
||||
});
|
||||
|
||||
it("「系统设置」包含 2 个子项:环境配置、触发器配置", () => {
|
||||
const settings = items.find((i) => i.label === "系统设置");
|
||||
expect(settings).toBeDefined();
|
||||
const children = settings!.children ?? [];
|
||||
expect(children).toHaveLength(2);
|
||||
expect(children.map((c) => c.label)).toEqual(["环境配置", "触发器配置"]);
|
||||
});
|
||||
|
||||
it("「日志调试」包含 3 个子项:DevTrace、AI 调用明细、数据库查看器", () => {
|
||||
const logs = items.find((i) => i.label === "日志调试");
|
||||
expect(logs).toBeDefined();
|
||||
const children = logs!.children ?? [];
|
||||
expect(children).toHaveLength(3);
|
||||
expect(children.map((c) => c.label)).toEqual([
|
||||
"DevTrace",
|
||||
"AI 调用明细",
|
||||
"数据库查看器",
|
||||
]);
|
||||
});
|
||||
|
||||
it("无子项的一级菜单(运行状态、ETL 任务管理、触发器管理、租户管理员)没有 children", () => {
|
||||
const noChildrenLabels = ["运行状态", "ETL 任务管理", "触发器管理", "租户管理员"];
|
||||
for (const label of noChildrenLabels) {
|
||||
const item = items.find((i) => i.label === label);
|
||||
expect(item).toBeDefined();
|
||||
expect((item as MenuItem).children).toBeUndefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 路由重定向测试 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/**
|
||||
* 辅助组件:捕获当前 location 用于断言。
|
||||
* 渲染后通过 testId 读取 pathname + search。
|
||||
*/
|
||||
function LocationDisplay() {
|
||||
const location = useLocation();
|
||||
return (
|
||||
<div data-testid="location">
|
||||
{location.pathname}
|
||||
{location.search}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 最小路由配置:只包含重定向规则和一个 LocationDisplay 兜底,
|
||||
* 不需要渲染完整 App(避免 mock 大量依赖)。
|
||||
*/
|
||||
function RedirectTestApp() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/" element={<Navigate to="/dashboard" replace />} />
|
||||
<Route path="/log-viewer" element={<Navigate to="/etl-tasks?tab=queue" replace />} />
|
||||
<Route path="*" element={<LocationDisplay />} />
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
|
||||
describe("路由重定向 (Requirements 8.3, 10.1, 10.2)", () => {
|
||||
it("/ 重定向到 /dashboard", () => {
|
||||
const { getByTestId } = render(
|
||||
<MemoryRouter initialEntries={["/"]}>
|
||||
<RedirectTestApp />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
expect(getByTestId("location").textContent).toBe("/dashboard");
|
||||
});
|
||||
|
||||
it("/log-viewer 重定向到 /etl-tasks?tab=queue", () => {
|
||||
const { getByTestId } = render(
|
||||
<MemoryRouter initialEntries={["/log-viewer"]}>
|
||||
<RedirectTestApp />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
expect(getByTestId("location").textContent).toBe("/etl-tasks?tab=queue");
|
||||
});
|
||||
});
|
||||
160
apps/admin-web/src/__tests__/sidebarHighlight.property.test.ts
Normal file
160
apps/admin-web/src/__tests__/sidebarHighlight.property.test.ts
Normal file
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* 属性测试:侧边栏高亮与当前路由一致
|
||||
*
|
||||
* Feature: admin-web-restructure, Property 7: 侧边栏高亮与当前路由一致
|
||||
* **Validates: Requirements 10.3**
|
||||
*
|
||||
* 对于任意有效的应用路由路径,侧边栏中被高亮(selectedKeys)的菜单项
|
||||
* 应对应该路由所属的一级模块。
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import * as fc from "fast-check";
|
||||
import { getSelectedKeys, NAV_ITEMS } from "../App";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 路由 → 一级模块映射(从 NAV_ITEMS 和路由配置提取) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/**
|
||||
* 所有有效路由及其所属一级模块 key 的映射。
|
||||
* 一级模块 key 定义:
|
||||
* - 无子菜单的项:直接用 item.key(如 "/dashboard")
|
||||
* - 有子菜单的项:用 group key(如 "task-engine-group")
|
||||
*/
|
||||
const ROUTE_TO_MODULE: Array<{
|
||||
pathname: string;
|
||||
search: string;
|
||||
moduleKey: string;
|
||||
/** 该路由在菜单中对应的 selectedKey */
|
||||
expectedSelectedKey: string;
|
||||
}> = [
|
||||
// 运行状态
|
||||
{ pathname: "/dashboard", search: "", moduleKey: "/dashboard", expectedSelectedKey: "/dashboard" },
|
||||
// ETL 任务管理
|
||||
{ pathname: "/etl-tasks", search: "", moduleKey: "/etl-tasks", expectedSelectedKey: "/etl-tasks" },
|
||||
{ pathname: "/etl-tasks", search: "?tab=config", moduleKey: "/etl-tasks", expectedSelectedKey: "/etl-tasks" },
|
||||
{ pathname: "/etl-tasks", search: "?tab=queue", moduleKey: "/etl-tasks", expectedSelectedKey: "/etl-tasks" },
|
||||
{ pathname: "/etl-tasks", search: "?tab=schedule", moduleKey: "/etl-tasks", expectedSelectedKey: "/etl-tasks" },
|
||||
{ pathname: "/etl-tasks", search: "?tab=history", moduleKey: "/etl-tasks", expectedSelectedKey: "/etl-tasks" },
|
||||
{ pathname: "/etl-tasks", search: "?tab=status", moduleKey: "/etl-tasks", expectedSelectedKey: "/etl-tasks" },
|
||||
// 小程序任务管理
|
||||
{ pathname: "/task-engine/trigger-jobs", search: "", moduleKey: "task-engine-group", expectedSelectedKey: "/task-engine/trigger-jobs" },
|
||||
{ pathname: "/task-engine/transfer-log", search: "", moduleKey: "task-engine-group", expectedSelectedKey: "/task-engine/transfer-log" },
|
||||
{ pathname: "/task-engine/pending-review", search: "", moduleKey: "task-engine-group", expectedSelectedKey: "/task-engine/pending-review" },
|
||||
{ pathname: "/task-engine/config", search: "", moduleKey: "task-engine-group", expectedSelectedKey: "/task-engine/config" },
|
||||
// 触发器管理
|
||||
{ pathname: "/triggers", search: "", moduleKey: "/triggers", expectedSelectedKey: "/triggers" },
|
||||
{ pathname: "/triggers", search: "?tab=all", moduleKey: "/triggers", expectedSelectedKey: "/triggers" },
|
||||
// 特殊情况:/triggers?tab=biz 同时是"系统设置 > 触发器配置"的快捷入口,
|
||||
// getSelectedKeys 会精确匹配到 settings-group 下的子项
|
||||
{ pathname: "/triggers", search: "?tab=biz", moduleKey: "settings-group", expectedSelectedKey: "/triggers?tab=biz" },
|
||||
{ pathname: "/triggers", search: "?tab=ai", moduleKey: "/triggers", expectedSelectedKey: "/triggers" },
|
||||
{ pathname: "/triggers", search: "?tab=etl", moduleKey: "/triggers", expectedSelectedKey: "/triggers" },
|
||||
// 租户管理员
|
||||
{ pathname: "/tenant-admins", search: "", moduleKey: "/tenant-admins", expectedSelectedKey: "/tenant-admins" },
|
||||
// 系统设置
|
||||
{ pathname: "/settings/env-config", search: "", moduleKey: "settings-group", expectedSelectedKey: "/settings/env-config" },
|
||||
// 日志调试
|
||||
{ pathname: "/logs/dev-trace", search: "", moduleKey: "logs-group", expectedSelectedKey: "/logs/dev-trace" },
|
||||
{ pathname: "/logs/ai-run-logs", search: "", moduleKey: "logs-group", expectedSelectedKey: "/logs/ai-run-logs" },
|
||||
{ pathname: "/logs/db-viewer", search: "", moduleKey: "logs-group", expectedSelectedKey: "/logs/db-viewer" },
|
||||
];
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 辅助:从 NAV_ITEMS 构建 selectedKey → moduleKey 的反查表 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** 收集所有菜单叶子节点的 key,映射到其所属一级模块 key */
|
||||
function buildKeyToModuleMap(): Map<string, string> {
|
||||
const map = new Map<string, string>();
|
||||
for (const item of NAV_ITEMS ?? []) {
|
||||
if (!item || !("key" in item)) continue;
|
||||
const topKey = item.key as string;
|
||||
if ("children" in item && item.children) {
|
||||
// 有子菜单:子项 key → group key
|
||||
for (const child of item.children) {
|
||||
if (child && "key" in child) {
|
||||
map.set(child.key as string, topKey);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 无子菜单:自身 key → 自身 key
|
||||
map.set(topKey, topKey);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
const KEY_TO_MODULE = buildKeyToModuleMap();
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 属性测试 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("Property 7: 侧边栏高亮与当前路由一致", () => {
|
||||
// 生成器:从所有有效路由中随机选取
|
||||
const routeArb = fc.constantFrom(...ROUTE_TO_MODULE);
|
||||
|
||||
it("对任意有效路由,selectedKeys 应包含该路由对应的菜单项 key", () => {
|
||||
fc.assert(
|
||||
fc.property(routeArb, (route) => {
|
||||
const selectedKeys = getSelectedKeys(route.pathname, route.search);
|
||||
|
||||
// selectedKeys 不应为空
|
||||
expect(selectedKeys.length).toBeGreaterThan(0);
|
||||
|
||||
// selectedKeys 中应包含预期的 key
|
||||
expect(selectedKeys).toContain(route.expectedSelectedKey);
|
||||
}),
|
||||
{ numRuns: 100 },
|
||||
);
|
||||
});
|
||||
|
||||
it("对任意有效路由,selectedKeys 对应的一级模块应与路由所属模块一致", () => {
|
||||
fc.assert(
|
||||
fc.property(routeArb, (route) => {
|
||||
const selectedKeys = getSelectedKeys(route.pathname, route.search);
|
||||
const selectedKey = selectedKeys[0];
|
||||
|
||||
// 查找 selectedKey 所属的一级模块
|
||||
const actualModule = KEY_TO_MODULE.get(selectedKey);
|
||||
|
||||
// 如果 selectedKey 不在菜单叶子节点中(如一级路由直接匹配),
|
||||
// 则 selectedKey 本身就是模块 key
|
||||
const resolvedModule = actualModule ?? selectedKey;
|
||||
|
||||
expect(resolvedModule).toBe(route.moduleKey);
|
||||
}),
|
||||
{ numRuns: 100 },
|
||||
);
|
||||
});
|
||||
|
||||
it("NAV_ITEMS 应包含 7 个一级菜单项", () => {
|
||||
expect(NAV_ITEMS).toHaveLength(7);
|
||||
});
|
||||
|
||||
it("所有有效路由的 selectedKey 都能在 NAV_ITEMS 中找到对应菜单项", () => {
|
||||
fc.assert(
|
||||
fc.property(routeArb, (route) => {
|
||||
const selectedKeys = getSelectedKeys(route.pathname, route.search);
|
||||
const selectedKey = selectedKeys[0];
|
||||
|
||||
// selectedKey 必须存在于菜单的叶子节点或一级节点中
|
||||
const allMenuKeys = new Set<string>();
|
||||
for (const item of NAV_ITEMS ?? []) {
|
||||
if (!item || !("key" in item)) continue;
|
||||
allMenuKeys.add(item.key as string);
|
||||
if ("children" in item && item.children) {
|
||||
for (const child of item.children) {
|
||||
if (child && "key" in child) allMenuKeys.add(child.key as string);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(allMenuKeys.has(selectedKey)).toBe(true);
|
||||
}),
|
||||
{ numRuns: 100 },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* 属性测试:Tab 切换状态保持 round-trip
|
||||
*
|
||||
* Feature: admin-web-restructure, Property 2: Tab 切换状态保持 round-trip
|
||||
* **Validates: Requirements 3.5**
|
||||
*
|
||||
* 对于任意 ETL 任务管理的 Tab 视图,在某个 Tab 中设置筛选条件后
|
||||
* 切换到另一个 Tab 再切回来,原 Tab 的筛选条件应保持不变。
|
||||
*
|
||||
* 策略:Mock 子组件为带 text input 的有状态组件,
|
||||
* 通过输入文本 → 切换 Tab → 切回 → 验证文本保留来证明状态保持。
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import * as fc from "fast-check";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Mock 子组件:带有状态的简单输入框 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function StatefulTab({ tabKey }: { tabKey: string }) {
|
||||
const [value, setValue] = useState("");
|
||||
return (
|
||||
<div data-testid={`tab-panel-${tabKey}`}>
|
||||
<input
|
||||
data-testid={`state-input-${tabKey}`}
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
vi.mock("../pages/TaskConfig", () => ({
|
||||
default: () => <StatefulTab tabKey="config" />,
|
||||
}));
|
||||
vi.mock("../pages/TaskManager", () => ({
|
||||
default: () => <StatefulTab tabKey="manager" />,
|
||||
}));
|
||||
vi.mock("../pages/ETLStatus", () => ({
|
||||
default: () => <StatefulTab tabKey="status" />,
|
||||
}));
|
||||
|
||||
import ETLTasks from "../pages/ETLTasks";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 常量 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const VALID_TABS = ["config", "manager", "status"] as const;
|
||||
type TabKey = (typeof VALID_TABS)[number];
|
||||
|
||||
const TAB_LABELS: Record<TabKey, string> = {
|
||||
config: "任务配置",
|
||||
manager: "任务管理",
|
||||
status: "ETL 状态",
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 辅助函数 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** 点击指定 Tab */
|
||||
function clickTab(tabKey: TabKey) {
|
||||
const tabElements = document.querySelectorAll(".ant-tabs-tab");
|
||||
for (const el of tabElements) {
|
||||
if (el.textContent?.includes(TAB_LABELS[tabKey])) {
|
||||
fireEvent.click(el);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new Error(`Tab "${tabKey}" not found`);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 每次测试后清理 DOM */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 属性测试 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
// DOM 渲染属性测试:numRuns=20 覆盖所有 tab 组合多次,避免 jsdom 超时
|
||||
const PBT_NUM_RUNS = 20;
|
||||
const PBT_TIMEOUT = 30_000;
|
||||
|
||||
describe("Property 2: Tab 切换状态保持 round-trip", () => {
|
||||
// 生成器:从有效 tab 值中随机选取两个不同的 tab
|
||||
const distinctTabPairArb = fc
|
||||
.tuple(fc.constantFrom(...VALID_TABS), fc.constantFrom(...VALID_TABS))
|
||||
.filter(([a, b]) => a !== b);
|
||||
|
||||
// 生成器:模拟用户输入的筛选条件文本
|
||||
// 使用 constantFrom 避免 fast-check v4 API 兼容性问题(char/stringOf 已移除)
|
||||
const inputTextArb = fc.constantFrom(
|
||||
"hello", "test-filter", "ETL_001", "搜索关键词", "abc123",
|
||||
"x", "long-filter-value-example", "special!@#", " spaces ", "UPPER",
|
||||
);
|
||||
|
||||
it("在某 Tab 设置状态 → 切换到另一 Tab → 切回 → 状态保持不变", () => {
|
||||
fc.assert(
|
||||
fc.property(distinctTabPairArb, inputTextArb, ([sourceTab, otherTab], text) => {
|
||||
cleanup();
|
||||
|
||||
// 渲染页面,初始 Tab 为 sourceTab
|
||||
render(
|
||||
<MemoryRouter initialEntries={[`/etl-tasks?tab=${sourceTab}`]}>
|
||||
<ETLTasks />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
// 1. 在 sourceTab 的输入框中输入文本
|
||||
const input = screen.getByTestId(`state-input-${sourceTab}`) as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: text } });
|
||||
expect(input.value).toBe(text);
|
||||
|
||||
// 2. 切换到 otherTab
|
||||
clickTab(otherTab);
|
||||
|
||||
// 3. 切回 sourceTab
|
||||
clickTab(sourceTab);
|
||||
|
||||
// 4. 验证 sourceTab 的输入框文本保持不变
|
||||
const inputAfter = screen.getByTestId(`state-input-${sourceTab}`) as HTMLInputElement;
|
||||
expect(inputAfter.value).toBe(text);
|
||||
|
||||
cleanup();
|
||||
}),
|
||||
{ numRuns: PBT_NUM_RUNS },
|
||||
);
|
||||
}, PBT_TIMEOUT);
|
||||
});
|
||||
191
apps/admin-web/src/__tests__/tabUrlSync.property.test.tsx
Normal file
191
apps/admin-web/src/__tests__/tabUrlSync.property.test.tsx
Normal file
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* 属性测试:Tab 切换与 URL 查询参数同步 round-trip
|
||||
*
|
||||
* Feature: admin-web-restructure, Property 8: Tab 切换与 URL 查询参数同步 round-trip
|
||||
* **Validates: Requirements 10.4**
|
||||
*
|
||||
* 对于任意 Tab 视图页面,设置 URL 查询参数 `?tab=X` 后渲染页面,
|
||||
* 当前激活的 Tab 应为 X;点击 Tab Y 后,URL 查询参数应更新为 `?tab=Y`。
|
||||
*
|
||||
* 当前仅测试 ETLTasks(TriggerManager 待后续任务创建后扩展)。
|
||||
*/
|
||||
|
||||
import React from "react";
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import { render, fireEvent, cleanup } from "@testing-library/react";
|
||||
import { MemoryRouter, useLocation } from "react-router-dom";
|
||||
import * as fc from "fast-check";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Mock 子组件,避免内部 API 调用 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
vi.mock("../pages/TaskConfig", () => ({
|
||||
default: () => <div data-testid="tab-content-config">TaskConfig</div>,
|
||||
}));
|
||||
vi.mock("../pages/TaskManager", () => ({
|
||||
QueueTab: () => <div data-testid="tab-content-queue">QueueTab</div>,
|
||||
HistoryTab: () => <div data-testid="tab-content-history">HistoryTab</div>,
|
||||
}));
|
||||
vi.mock("../components/ScheduleTab", () => ({
|
||||
default: () => <div data-testid="tab-content-schedule">ScheduleTab</div>,
|
||||
}));
|
||||
vi.mock("../pages/ETLStatus", () => ({
|
||||
default: () => <div data-testid="tab-content-status">ETLStatus</div>,
|
||||
}));
|
||||
|
||||
import ETLTasks from "../pages/ETLTasks";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 辅助:捕获当前 URL search 参数 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function LocationSpy({ onLocation }: { onLocation: (s: string) => void }) {
|
||||
const location = useLocation();
|
||||
React.useEffect(() => {
|
||||
onLocation(location.search);
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 页面配置(可扩展 TriggerManager) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
interface TabPageConfig {
|
||||
name: string;
|
||||
validTabs: readonly string[];
|
||||
defaultTab: string;
|
||||
Component: React.FC;
|
||||
basePath: string;
|
||||
/** Tab label 文本中包含的关键字,用于定位 Tab 元素 */
|
||||
tabLabels: Record<string, string>;
|
||||
}
|
||||
|
||||
const ETL_TASKS_CONFIG: TabPageConfig = {
|
||||
name: "ETLTasks",
|
||||
validTabs: ["config", "queue", "schedule", "history", "status"],
|
||||
defaultTab: "config",
|
||||
Component: ETLTasks,
|
||||
basePath: "/etl-tasks",
|
||||
tabLabels: {
|
||||
config: "发起",
|
||||
queue: "队列",
|
||||
schedule: "调度",
|
||||
history: "历史",
|
||||
status: "状态",
|
||||
},
|
||||
};
|
||||
|
||||
// TriggerManager 配置占位,待 task 10.1 创建后启用
|
||||
// const TRIGGER_MANAGER_CONFIG: TabPageConfig = { ... };
|
||||
|
||||
const PAGE_CONFIGS: TabPageConfig[] = [ETL_TASKS_CONFIG];
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 每次测试后清理 DOM */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 属性测试 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
// DOM 渲染属性测试:numRuns=20 覆盖所有 tab 值多次,避免 jsdom 超时
|
||||
const PBT_NUM_RUNS = 20;
|
||||
// 给 DOM 属性测试更长的超时(30s)
|
||||
const PBT_TIMEOUT = 30_000;
|
||||
|
||||
describe("Property 8: Tab 切换与 URL 查询参数同步 round-trip", () => {
|
||||
for (const pageConfig of PAGE_CONFIGS) {
|
||||
const { name, validTabs, defaultTab, Component, basePath, tabLabels } = pageConfig;
|
||||
|
||||
describe(`${name} 页面`, () => {
|
||||
// 生成器:从有效 tab 值中随机选取
|
||||
const tabArb = fc.constantFrom(...validTabs);
|
||||
|
||||
it("设置 ?tab=X 后,激活的 Tab 应为 X", () => {
|
||||
fc.assert(
|
||||
fc.property(tabArb, (tab) => {
|
||||
cleanup();
|
||||
render(
|
||||
<MemoryRouter initialEntries={[`${basePath}?tab=${tab}`]}>
|
||||
<Component />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
// Ant Design Tabs 的激活 tab 有 .ant-tabs-tab-active 类
|
||||
const activeTab = document.querySelector(".ant-tabs-tab-active");
|
||||
expect(activeTab).not.toBeNull();
|
||||
expect(activeTab!.textContent).toContain(tabLabels[tab]);
|
||||
|
||||
cleanup();
|
||||
}),
|
||||
{ numRuns: PBT_NUM_RUNS },
|
||||
);
|
||||
}, PBT_TIMEOUT);
|
||||
|
||||
it("点击 Tab Y 后,URL 查询参数应更新为 ?tab=Y", () => {
|
||||
fc.assert(
|
||||
fc.property(tabArb, tabArb, (initialTab, targetTab) => {
|
||||
cleanup();
|
||||
let currentSearch = "";
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={[`${basePath}?tab=${initialTab}`]}>
|
||||
<Component />
|
||||
<LocationSpy onLocation={(s) => { currentSearch = s; }} />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
// 找到目标 Tab 并点击
|
||||
const tabElements = document.querySelectorAll(".ant-tabs-tab");
|
||||
let targetTabEl: Element | null = null;
|
||||
for (const el of tabElements) {
|
||||
if (el.textContent?.includes(tabLabels[targetTab])) {
|
||||
targetTabEl = el;
|
||||
break;
|
||||
}
|
||||
}
|
||||
expect(targetTabEl).not.toBeNull();
|
||||
fireEvent.click(targetTabEl!);
|
||||
|
||||
// 验证 URL 参数已更新
|
||||
const params = new URLSearchParams(currentSearch);
|
||||
expect(params.get("tab")).toBe(targetTab);
|
||||
|
||||
cleanup();
|
||||
}),
|
||||
{ numRuns: PBT_NUM_RUNS },
|
||||
);
|
||||
}, PBT_TIMEOUT);
|
||||
|
||||
it("无效或缺失的 tab 参数应回退到默认 Tab", () => {
|
||||
// 无 tab 参数
|
||||
render(
|
||||
<MemoryRouter initialEntries={[basePath]}>
|
||||
<Component />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
const activeTab1 = document.querySelector(".ant-tabs-tab-active");
|
||||
expect(activeTab1).not.toBeNull();
|
||||
expect(activeTab1!.textContent).toContain(tabLabels[defaultTab]);
|
||||
cleanup();
|
||||
|
||||
// 无效 tab 参数
|
||||
render(
|
||||
<MemoryRouter initialEntries={[`${basePath}?tab=invalid`]}>
|
||||
<Component />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
const activeTab2 = document.querySelector(".ant-tabs-tab-active");
|
||||
expect(activeTab2).not.toBeNull();
|
||||
expect(activeTab2!.textContent).toContain(tabLabels[defaultTab]);
|
||||
cleanup();
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
298
apps/admin-web/src/__tests__/triggerManager.test.tsx
Normal file
298
apps/admin-web/src/__tests__/triggerManager.test.tsx
Normal file
@@ -0,0 +1,298 @@
|
||||
/**
|
||||
* 单元测试:TriggerManager 页面
|
||||
*
|
||||
* _Requirements: 4.1, 4.3, 4.4, 4.7_
|
||||
*
|
||||
* - 测试 4 个 Tab 正确渲染
|
||||
* - 测试"全部"Tab 为只读(无编辑按钮)
|
||||
* - 测试"业务"Tab 编辑表单仅包含 cron_expression 和 interval_seconds
|
||||
* - 测试 422 错误在表单中展示具体错误信息
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeAll, afterEach } from "vitest";
|
||||
import { render, screen, cleanup, fireEvent, waitFor } from "@testing-library/react";
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Ant Design jsdom 兼容:polyfill window.matchMedia */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation((query: string) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Mock API 模块 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const mockFetchUnifiedTriggers = vi.fn().mockResolvedValue([
|
||||
{
|
||||
id: 1,
|
||||
name: "同步会员数据",
|
||||
source: "biz",
|
||||
trigger_condition: "cron",
|
||||
status: "running",
|
||||
last_run_at: "2026-07-15T10:00:00",
|
||||
next_run_at: "2026-07-15T12:00:00",
|
||||
last_error: null,
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "AI 事件链",
|
||||
source: "ai",
|
||||
trigger_condition: "event",
|
||||
status: "idle",
|
||||
last_run_at: null,
|
||||
next_run_at: null,
|
||||
last_error: null,
|
||||
},
|
||||
]);
|
||||
|
||||
const mockFetchTriggerJobs = vi.fn().mockResolvedValue([
|
||||
{
|
||||
id: 101,
|
||||
job_type: "sync",
|
||||
job_name: "sync_members",
|
||||
trigger_condition: "cron",
|
||||
trigger_config: { cron_expression: "0 */2 * * *", interval_seconds: 7200 },
|
||||
last_run_at: "2026-07-15T10:00:00",
|
||||
next_run_at: "2026-07-15T12:00:00",
|
||||
status: "enabled",
|
||||
description: "同步会员数据",
|
||||
last_error: null,
|
||||
created_at: "2026-01-01T00:00:00",
|
||||
},
|
||||
]);
|
||||
|
||||
const mockUpdateTriggerConfig = vi.fn().mockResolvedValue({
|
||||
id: 101,
|
||||
job_type: "sync",
|
||||
job_name: "sync_members",
|
||||
trigger_condition: "cron",
|
||||
trigger_config: { cron_expression: "0 */3 * * *", interval_seconds: 7200 },
|
||||
last_run_at: "2026-07-15T10:00:00",
|
||||
next_run_at: "2026-07-15T15:00:00",
|
||||
status: "enabled",
|
||||
description: "同步会员数据",
|
||||
last_error: null,
|
||||
created_at: "2026-01-01T00:00:00",
|
||||
});
|
||||
|
||||
const mockFetchSchedules = vi.fn().mockResolvedValue([]);
|
||||
|
||||
vi.mock("../api/triggers", () => ({
|
||||
fetchUnifiedTriggers: (...args: unknown[]) => mockFetchUnifiedTriggers(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../api/triggerJobs", () => ({
|
||||
fetchTriggerJobs: (...args: unknown[]) => mockFetchTriggerJobs(...args),
|
||||
updateTriggerConfig: (...args: unknown[]) => mockUpdateTriggerConfig(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../api/schedules", () => ({
|
||||
fetchSchedules: (...args: unknown[]) => mockFetchSchedules(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../pages/AIOperations", () => ({
|
||||
default: () => <div data-testid="mock-ai-operations">AIOperations Mock</div>,
|
||||
}));
|
||||
|
||||
vi.mock("../pages/AITriggerJobs", () => ({
|
||||
default: () => <div data-testid="mock-ai-trigger-jobs">AITriggerJobs Mock</div>,
|
||||
}));
|
||||
|
||||
import TriggerManager from "../pages/TriggerManager";
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 测试:4 个 Tab 正确渲染(Requirement 4.1) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("TriggerManager — 4 个 Tab 渲染 (Requirement 4.1)", () => {
|
||||
it("渲染 4 个 Tab 标签:全部、业务、AI、ETL", async () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/triggers"]}>
|
||||
<TriggerManager />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
const tabs = document.querySelectorAll(".ant-tabs-tab");
|
||||
expect(tabs).toHaveLength(4);
|
||||
});
|
||||
|
||||
const tabs = document.querySelectorAll(".ant-tabs-tab");
|
||||
const tabTexts = Array.from(tabs).map((t) => t.textContent);
|
||||
expect(tabTexts).toContain("全部");
|
||||
expect(tabTexts).toContain("业务");
|
||||
expect(tabTexts).toContain("AI");
|
||||
expect(tabTexts).toContain("ETL");
|
||||
});
|
||||
|
||||
it("默认激活「全部」Tab", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/triggers"]}>
|
||||
<TriggerManager />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
const activeTab = document.querySelector(".ant-tabs-tab-active");
|
||||
expect(activeTab).not.toBeNull();
|
||||
expect(activeTab!.textContent).toContain("全部");
|
||||
});
|
||||
|
||||
it("页面标题包含「触发器管理」", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/triggers"]}>
|
||||
<TriggerManager />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
expect(screen.getByText("触发器管理")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 测试:"全部"Tab 为只读(Requirement 4.3) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("TriggerManager — 全部 Tab 只读 (Requirement 4.3)", () => {
|
||||
it("「全部」Tab 表格中无「编辑」按钮", async () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/triggers?tab=all"]}>
|
||||
<TriggerManager />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
// 等待统一视图数据加载完成
|
||||
await waitFor(() => {
|
||||
expect(mockFetchUnifiedTriggers).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// 等待表格渲染数据
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("同步会员数据")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// 全部 Tab 不应有编辑按钮
|
||||
const editButtons = screen.queryAllByRole("button", { name: /编辑/ });
|
||||
expect(editButtons).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 测试:"业务"Tab 编辑表单字段(Requirement 4.4, 4.7) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("TriggerManager — 业务 Tab 编辑表单 (Requirements 4.4, 4.7)", () => {
|
||||
it("编辑 Modal 仅包含 cron_expression 和 interval_seconds 两个字段", async () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/triggers?tab=biz"]}>
|
||||
<TriggerManager />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
// 等待业务触发器数据加载
|
||||
await waitFor(() => {
|
||||
expect(mockFetchTriggerJobs).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// 等待表格渲染
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("同步会员数据")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// 点击编辑按钮
|
||||
const editBtn = screen.getByRole("button", { name: /编辑/ });
|
||||
fireEvent.click(editBtn);
|
||||
|
||||
// 等待 Modal 打开
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/编辑触发器配置/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// 验证表单包含 cron_expression 字段
|
||||
expect(screen.getByLabelText(/Cron 表达式/)).toBeInTheDocument();
|
||||
|
||||
// 验证表单包含 interval_seconds 字段
|
||||
expect(screen.getByLabelText(/间隔秒数/)).toBeInTheDocument();
|
||||
|
||||
// 验证 Modal 中的 Form.Item 数量 — 只有 2 个
|
||||
const modal = document.querySelector(".ant-modal-body");
|
||||
expect(modal).not.toBeNull();
|
||||
const formItems = modal!.querySelectorAll(".ant-form-item");
|
||||
expect(formItems).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 测试:422 错误展示具体错误信息(Requirement 4.7) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe("TriggerManager — 422 错误展示 (Requirement 4.7)", () => {
|
||||
it("422 错误时调用 updateTriggerConfig 并提取 detail 信息", async () => {
|
||||
const error422 = {
|
||||
response: {
|
||||
status: 422,
|
||||
data: { detail: "cron 表达式格式无效,需要 5 字段格式" },
|
||||
},
|
||||
};
|
||||
mockUpdateTriggerConfig.mockRejectedValueOnce(error422);
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/triggers?tab=biz"]}>
|
||||
<TriggerManager />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
// 等待数据加载
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("同步会员数据")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// 点击编辑按钮
|
||||
const editBtn = screen.getByRole("button", { name: /编辑/ });
|
||||
fireEvent.click(editBtn);
|
||||
|
||||
// 等待 Modal 打开
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/编辑触发器配置/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// 填写一个无效的 cron 表达式
|
||||
const cronInput = screen.getByLabelText(/Cron 表达式/);
|
||||
fireEvent.change(cronInput, { target: { value: "invalid-cron" } });
|
||||
|
||||
// 点击保存(Modal 的确定按钮,Ant Design 渲染为"保 存"带空格)
|
||||
const okBtn = screen.getByRole("button", { name: /保\s*存/ });
|
||||
fireEvent.click(okBtn);
|
||||
|
||||
// 验证 updateTriggerConfig 被调用(触发了 422 错误路径)
|
||||
await waitFor(() => {
|
||||
expect(mockUpdateTriggerConfig).toHaveBeenCalledWith(101, {
|
||||
cron_expression: "invalid-cron",
|
||||
interval_seconds: 7200,
|
||||
});
|
||||
});
|
||||
|
||||
// 验证 422 错误后 Modal 仍然打开(未关闭,说明错误被处理而非忽略)
|
||||
expect(screen.getByText(/编辑触发器配置/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
277
apps/admin-web/src/api/adminAI.ts
Normal file
277
apps/admin-web/src/api/adminAI.ts
Normal file
@@ -0,0 +1,277 @@
|
||||
/**
|
||||
* AI 监控后台 API
|
||||
*
|
||||
* 对接后端 /api/admin/ai/* 端点,提供 Dashboard、调度任务、调用记录、
|
||||
* 缓存管理、Token 预算、批量执行、告警管理等功能。
|
||||
*/
|
||||
|
||||
import { apiClient } from "./client";
|
||||
|
||||
// ---- 类型定义 ----
|
||||
|
||||
// Dashboard
|
||||
export interface DailyTrend {
|
||||
date: string;
|
||||
calls: number;
|
||||
success_rate: number;
|
||||
}
|
||||
|
||||
export interface AppDistItem {
|
||||
app_type: string;
|
||||
count: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export interface BudgetInfo {
|
||||
daily_used: number;
|
||||
daily_limit: number;
|
||||
daily_pct: number;
|
||||
monthly_used: number;
|
||||
monthly_limit: number;
|
||||
monthly_pct: number;
|
||||
}
|
||||
|
||||
export interface AlertItem {
|
||||
id: number;
|
||||
app_type: string;
|
||||
status: string;
|
||||
alert_status: string | null;
|
||||
error_message: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface AppHealthItem {
|
||||
app_type: string;
|
||||
last_status: string | null;
|
||||
last_call_at: string | null;
|
||||
}
|
||||
|
||||
export interface DashboardResponse {
|
||||
today_calls: number;
|
||||
today_success_rate: number;
|
||||
today_tokens: number;
|
||||
today_avg_latency_ms: number;
|
||||
trend_7d: DailyTrend[];
|
||||
app_distribution: AppDistItem[];
|
||||
budget: BudgetInfo;
|
||||
recent_alerts: AlertItem[];
|
||||
app_health: AppHealthItem[];
|
||||
}
|
||||
|
||||
// 调度任务
|
||||
export interface TriggerJobItem {
|
||||
id: number;
|
||||
event_type: string;
|
||||
member_id: number | null;
|
||||
status: string;
|
||||
app_chain: string | null;
|
||||
is_forced: boolean;
|
||||
site_id: number;
|
||||
started_at: string | null;
|
||||
finished_at: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface TriggerJobDetailResponse extends TriggerJobItem {
|
||||
payload: Record<string, unknown> | null;
|
||||
error_message: string | null;
|
||||
connector_type: string;
|
||||
}
|
||||
|
||||
export interface TriggerJobListResponse {
|
||||
items: TriggerJobItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
today_skipped_duplicates: number;
|
||||
}
|
||||
|
||||
export interface RetryResponse {
|
||||
trigger_job_id: number;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export interface TriggerJobQuery {
|
||||
event_type?: string;
|
||||
status?: string;
|
||||
site_id?: number;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
// 调用记录
|
||||
export interface RunLogItem {
|
||||
id: number;
|
||||
app_type: string;
|
||||
trigger_type: string;
|
||||
member_id: number | null;
|
||||
tokens_used: number;
|
||||
latency_ms: number | null;
|
||||
status: string;
|
||||
site_id: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface RunLogDetailResponse extends RunLogItem {
|
||||
request_prompt: string | null;
|
||||
response_text: string | null;
|
||||
error_message: string | null;
|
||||
session_id: string | null;
|
||||
finished_at: string | null;
|
||||
}
|
||||
|
||||
export interface RunLogListResponse {
|
||||
items: RunLogItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
export interface RunLogQuery {
|
||||
app_type?: string;
|
||||
status?: string;
|
||||
trigger_type?: string;
|
||||
site_id?: number;
|
||||
date_from?: string;
|
||||
date_to?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
// 缓存管理
|
||||
export interface CacheInvalidateReq {
|
||||
site_id: number;
|
||||
app_type?: string;
|
||||
member_id?: number;
|
||||
}
|
||||
|
||||
export interface CacheInvalidateResponse {
|
||||
affected_count: number;
|
||||
}
|
||||
|
||||
// Token 预算
|
||||
export interface BudgetResponse {
|
||||
daily_used: number;
|
||||
daily_limit: number;
|
||||
daily_pct: number;
|
||||
monthly_used: number;
|
||||
monthly_limit: number;
|
||||
monthly_pct: number;
|
||||
}
|
||||
|
||||
// 批量执行
|
||||
export interface BatchRunReq {
|
||||
app_types: string[];
|
||||
member_ids: number[];
|
||||
site_id: number;
|
||||
}
|
||||
|
||||
export interface BatchRunEstimate {
|
||||
batch_id: string;
|
||||
estimated_calls: number;
|
||||
estimated_tokens: number;
|
||||
}
|
||||
|
||||
export interface BatchRunConfirmResponse {
|
||||
status: string;
|
||||
}
|
||||
|
||||
// 告警
|
||||
export interface AlertQuery {
|
||||
alert_status?: string;
|
||||
site_id?: number;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface AlertListResponse {
|
||||
items: AlertItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
export interface AlertActionResponse {
|
||||
id: number;
|
||||
alert_status: string;
|
||||
}
|
||||
|
||||
// ---- API 调用 ----
|
||||
|
||||
// Dashboard
|
||||
export async function getDashboard(siteId?: number): Promise<DashboardResponse> {
|
||||
const { data } = await apiClient.get<DashboardResponse>("/admin/ai/dashboard", {
|
||||
params: siteId != null ? { site_id: siteId } : undefined,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
// 调度任务
|
||||
export async function getTriggerJobs(params: TriggerJobQuery): Promise<TriggerJobListResponse> {
|
||||
const { data } = await apiClient.get<TriggerJobListResponse>("/admin/ai/trigger-jobs", { params });
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function getTriggerJobDetail(id: number): Promise<TriggerJobDetailResponse> {
|
||||
const { data } = await apiClient.get<TriggerJobDetailResponse>(`/admin/ai/trigger-jobs/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function retryTriggerJob(id: number): Promise<RetryResponse> {
|
||||
const { data } = await apiClient.post<RetryResponse>(`/admin/ai/trigger-jobs/${id}/retry`);
|
||||
return data;
|
||||
}
|
||||
|
||||
// 调用记录
|
||||
export async function getRunLogs(params: RunLogQuery): Promise<RunLogListResponse> {
|
||||
const { data } = await apiClient.get<RunLogListResponse>("/admin/ai/run-logs", { params });
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function getRunLogDetail(id: number): Promise<RunLogDetailResponse> {
|
||||
const { data } = await apiClient.get<RunLogDetailResponse>(`/admin/ai/run-logs/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
// 缓存管理
|
||||
export async function invalidateCache(body: CacheInvalidateReq): Promise<CacheInvalidateResponse> {
|
||||
const { data } = await apiClient.post<CacheInvalidateResponse>("/admin/ai/cache/invalidate", body);
|
||||
return data;
|
||||
}
|
||||
|
||||
// Token 预算
|
||||
export async function getBudget(): Promise<BudgetResponse> {
|
||||
const { data } = await apiClient.get<BudgetResponse>("/admin/ai/budget");
|
||||
return data;
|
||||
}
|
||||
|
||||
// 批量执行
|
||||
export async function createBatchRun(body: BatchRunReq): Promise<BatchRunEstimate> {
|
||||
const { data } = await apiClient.post<BatchRunEstimate>("/admin/ai/batch-run", body);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function confirmBatchRun(batchId: string): Promise<BatchRunConfirmResponse> {
|
||||
const { data } = await apiClient.post<BatchRunConfirmResponse>("/admin/ai/batch-run/confirm", {
|
||||
batch_id: batchId,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
// 告警
|
||||
export async function getAlerts(params: AlertQuery): Promise<AlertListResponse> {
|
||||
const { data } = await apiClient.get<AlertListResponse>("/admin/ai/alerts", { params });
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function ackAlert(id: number): Promise<AlertActionResponse> {
|
||||
const { data } = await apiClient.post<AlertActionResponse>(`/admin/ai/alerts/${id}/ack`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function ignoreAlert(id: number): Promise<AlertActionResponse> {
|
||||
const { data } = await apiClient.post<AlertActionResponse>(`/admin/ai/alerts/${id}/ignore`);
|
||||
return data;
|
||||
}
|
||||
@@ -122,20 +122,22 @@ apiClient.interceptors.response.use(
|
||||
|
||||
try {
|
||||
// 用独立 axios 调用避免被自身拦截器干扰
|
||||
const { data } = await axios.post<{
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
// ResponseWrapperMiddleware 包装响应为 { code: 0, data: { access_token, refresh_token } }
|
||||
const resp = await axios.post<{
|
||||
code: number;
|
||||
data: { access_token: string; refresh_token: string };
|
||||
}>("/api/auth/refresh", { refresh_token: refreshToken });
|
||||
|
||||
localStorage.setItem(ACCESS_TOKEN_KEY, data.access_token);
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, data.refresh_token);
|
||||
const tokens = resp.data.data;
|
||||
localStorage.setItem(ACCESS_TOKEN_KEY, tokens.access_token);
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, tokens.refresh_token);
|
||||
|
||||
processPendingQueue(data.access_token, null);
|
||||
processPendingQueue(tokens.access_token, null);
|
||||
|
||||
// 重放原始请求
|
||||
originalRequest.headers = {
|
||||
...originalRequest.headers,
|
||||
Authorization: `Bearer ${data.access_token}`,
|
||||
Authorization: `Bearer ${tokens.access_token}`,
|
||||
};
|
||||
return apiClient(originalRequest);
|
||||
} catch (refreshError) {
|
||||
|
||||
21
apps/admin-web/src/api/dbHealth.ts
Normal file
21
apps/admin-web/src/api/dbHealth.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* 数据库健康监控 API 调用。
|
||||
*/
|
||||
|
||||
import { apiClient } from './client';
|
||||
|
||||
/** 数据库健康状态 */
|
||||
export interface DbHealthItem {
|
||||
db_name: string;
|
||||
status: 'connected' | 'disconnected';
|
||||
active_connections: number | null;
|
||||
idle_connections: number | null;
|
||||
db_size_mb: number | null;
|
||||
slow_query_count: number | null;
|
||||
}
|
||||
|
||||
/** 获取所有数据库健康状态 */
|
||||
export async function fetchDbHealth(): Promise<DbHealthItem[]> {
|
||||
const { data } = await apiClient.get<DbHealthItem[]>('/admin/db-health');
|
||||
return data;
|
||||
}
|
||||
84
apps/admin-web/src/api/devTrace.ts
Normal file
84
apps/admin-web/src/api/devTrace.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* 开发调试全链路日志 API。
|
||||
*
|
||||
* 对接后端 /api/admin/dev-trace/* 端点,提供日志查询、设置管理、
|
||||
* 覆盖率扫描、手动清理等功能。
|
||||
*/
|
||||
|
||||
import { apiClient } from "./client";
|
||||
import type {
|
||||
TraceFilter,
|
||||
TraceRequest,
|
||||
TraceDetail,
|
||||
TraceSettings,
|
||||
TraceCoverage,
|
||||
} from "../types/devTrace";
|
||||
|
||||
// ---- 响应类型 ----
|
||||
|
||||
export interface TraceRequestListResponse {
|
||||
items: TraceRequest[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
export interface CleanupResponse {
|
||||
deleted_dates: string[];
|
||||
deleted_files: number;
|
||||
}
|
||||
|
||||
// ---- 日期列表 ----
|
||||
|
||||
export async function fetchDates(): Promise<{ dates: string[] }> {
|
||||
const { data } = await apiClient.get<{ dates: string[] }>("/admin/dev-trace/dates");
|
||||
return data;
|
||||
}
|
||||
|
||||
// ---- 请求列表(分页 + 筛选) ----
|
||||
|
||||
export async function fetchRequests(params: TraceFilter): Promise<TraceRequestListResponse> {
|
||||
const { data } = await apiClient.get<TraceRequestListResponse>("/admin/dev-trace/requests", { params });
|
||||
return data;
|
||||
}
|
||||
|
||||
// ---- 请求详情(含完整 spans) ----
|
||||
|
||||
export async function fetchRequestDetail(requestId: string): Promise<TraceDetail> {
|
||||
const { data } = await apiClient.get<TraceDetail>(`/admin/dev-trace/request/${requestId}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
// ---- 手动清理 ----
|
||||
|
||||
export async function cleanupLogs(startDate: string, endDate: string): Promise<CleanupResponse> {
|
||||
const { data } = await apiClient.post<CleanupResponse>("/admin/dev-trace/cleanup", {
|
||||
start_date: startDate,
|
||||
end_date: endDate,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
// ---- 设置 ----
|
||||
|
||||
export async function fetchSettings(): Promise<TraceSettings> {
|
||||
const { data } = await apiClient.get<TraceSettings>("/admin/dev-trace/settings");
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateSettings(settings: Partial<TraceSettings>): Promise<TraceSettings> {
|
||||
const { data } = await apiClient.put<TraceSettings>("/admin/dev-trace/settings", settings);
|
||||
return data;
|
||||
}
|
||||
|
||||
// ---- 覆盖率 ----
|
||||
|
||||
export async function fetchCoverage(): Promise<TraceCoverage> {
|
||||
const { data } = await apiClient.get<TraceCoverage>("/admin/dev-trace/coverage");
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function triggerCoverageScan(): Promise<TraceCoverage> {
|
||||
const { data } = await apiClient.post<TraceCoverage>("/admin/dev-trace/coverage/scan");
|
||||
return data;
|
||||
}
|
||||
@@ -10,8 +10,8 @@ import { apiClient } from './client';
|
||||
/** ETL 游标信息 */
|
||||
export interface CursorInfo {
|
||||
task_code: string;
|
||||
last_fetch_time: string | null;
|
||||
record_count: number | null;
|
||||
last_start: string | null;
|
||||
last_end: string | null;
|
||||
}
|
||||
|
||||
/** 最近执行记录 */
|
||||
|
||||
@@ -45,3 +45,17 @@ export async function deleteFromQueue(id: string): Promise<void> {
|
||||
export async function cancelExecution(id: string): Promise<void> {
|
||||
await apiClient.post(`/execution/${id}/cancel`);
|
||||
}
|
||||
|
||||
// CHANGE 2026-03-22 | 重新执行历史任务
|
||||
/** 重新执行指定的历史任务 */
|
||||
export async function rerunExecution(id: string): Promise<{ execution_id: string }> {
|
||||
const { data } = await apiClient.post<{ execution_id: string }>(`/execution/${id}/rerun`);
|
||||
return data;
|
||||
}
|
||||
|
||||
// CHANGE 2026-03-27 | 清理输出目录,每类任务只保留最近 10 个运行记录
|
||||
/** 清理 EXPORT_ROOT 下旧运行记录 */
|
||||
export async function cleanupOutput(): Promise<{ task_folders_scanned: number; dirs_deleted: number; errors: string[] }> {
|
||||
const { data } = await apiClient.post<{ task_folders_scanned: number; dirs_deleted: number; errors: string[] }>('/execution/cleanup-output');
|
||||
return data;
|
||||
}
|
||||
|
||||
134
apps/admin-web/src/api/registry.ts
Normal file
134
apps/admin-web/src/api/registry.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* 注册体系 API 调用(租户/店铺/简写ID/同步)。
|
||||
*
|
||||
* 复用 apiClient(已含 JWT 拦截器 + 响应解包)。
|
||||
* 端点前缀:/admin
|
||||
*/
|
||||
|
||||
import { apiClient } from "./client";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 类型定义 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** 租户列表项(后端 CamelModel 序列化为 camelCase) */
|
||||
export interface TenantItem {
|
||||
id: number;
|
||||
tenantId: number;
|
||||
tenantName: string;
|
||||
connectorName: string;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
/** 店铺列表项 */
|
||||
export interface SiteItem {
|
||||
id: number;
|
||||
siteId: number;
|
||||
siteName: string;
|
||||
siteCode: string | null;
|
||||
siteLabel: string | null;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
/** 设置/修改简写ID 请求 */
|
||||
export interface UpdateSiteCodeRequest {
|
||||
newCode: string;
|
||||
}
|
||||
|
||||
/** 简写ID 修改结果 */
|
||||
export interface SiteCodeResult {
|
||||
siteId: number;
|
||||
oldCode: string | null;
|
||||
newCode: string;
|
||||
historyCleaned: boolean;
|
||||
}
|
||||
|
||||
/** 简写ID 变更历史条目 */
|
||||
export interface SiteCodeHistoryItem {
|
||||
id: number;
|
||||
siteCode: string;
|
||||
isCurrent: boolean;
|
||||
createdAt: string;
|
||||
retiredAt: string | null;
|
||||
}
|
||||
|
||||
/** 店铺同步结果 */
|
||||
export interface SiteSyncResult {
|
||||
inserted: number;
|
||||
updated: number;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* API 调用 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** 获取所有活跃租户列表 */
|
||||
export async function fetchTenants(): Promise<TenantItem[]> {
|
||||
const { data } = await apiClient.get<TenantItem[]>("/admin/tenants");
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 获取指定租户下所有活跃店铺 */
|
||||
export async function fetchTenantSites(
|
||||
tenantId: number,
|
||||
): Promise<SiteItem[]> {
|
||||
const { data } = await apiClient.get<SiteItem[]>(
|
||||
`/admin/tenants/${tenantId}/sites`,
|
||||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 设置/修改店铺简写ID */
|
||||
export async function updateSiteCode(
|
||||
siteId: number,
|
||||
newCode: string,
|
||||
): Promise<SiteCodeResult> {
|
||||
const { data } = await apiClient.put<SiteCodeResult>(
|
||||
`/admin/sites/${siteId}/site-code`,
|
||||
{ newCode } satisfies UpdateSiteCodeRequest,
|
||||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 查看简写ID 变更历史 */
|
||||
export async function fetchSiteCodeHistory(
|
||||
siteId: number,
|
||||
): Promise<SiteCodeHistoryItem[]> {
|
||||
const { data } = await apiClient.get<SiteCodeHistoryItem[]>(
|
||||
`/admin/sites/${siteId}/site-code-history`,
|
||||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 手动触发店铺同步 */
|
||||
export async function syncSites(): Promise<SiteSyncResult> {
|
||||
const { data } = await apiClient.post<SiteSyncResult>(
|
||||
"/admin/sites/sync",
|
||||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 测试功能:手动创建/删除店铺 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** 创建店铺请求 */
|
||||
export interface CreateSitePayload {
|
||||
tenantId: number;
|
||||
siteId: number;
|
||||
siteName: string;
|
||||
siteCode?: string;
|
||||
}
|
||||
|
||||
/** 手动创建店铺(测试功能) */
|
||||
export async function createSite(
|
||||
payload: CreateSitePayload,
|
||||
): Promise<SiteItem> {
|
||||
const { data } = await apiClient.post<SiteItem>("/admin/sites", payload);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 删除店铺(测试功能,硬删除) */
|
||||
export async function deleteSite(id: number): Promise<void> {
|
||||
await apiClient.delete(`/admin/sites/${id}`);
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
*/
|
||||
|
||||
import { apiClient } from './client';
|
||||
import type { ScheduledTask, ScheduleConfig, TaskConfig, ExecutionLog } from '../types';
|
||||
import type { ScheduledTask, ScheduleConfig, TaskConfig, ExecutionLog, MinRunIntervalItem } from '../types';
|
||||
|
||||
/** 获取调度任务列表 */
|
||||
export async function fetchSchedules(): Promise<ScheduledTask[]> {
|
||||
@@ -18,6 +18,9 @@ export async function createSchedule(payload: {
|
||||
task_config: TaskConfig;
|
||||
schedule_config: ScheduleConfig;
|
||||
run_immediately?: boolean;
|
||||
min_run_interval_value?: number;
|
||||
min_run_interval_unit?: string;
|
||||
min_run_intervals?: Record<string, MinRunIntervalItem>;
|
||||
}): Promise<ScheduledTask> {
|
||||
const { data } = await apiClient.post<ScheduledTask>('/schedules', payload);
|
||||
return data;
|
||||
@@ -31,6 +34,9 @@ export async function updateSchedule(
|
||||
task_codes: string[];
|
||||
task_config: TaskConfig;
|
||||
schedule_config: ScheduleConfig;
|
||||
min_run_interval_value: number;
|
||||
min_run_interval_unit: string;
|
||||
min_run_intervals: Record<string, MinRunIntervalItem>;
|
||||
}>,
|
||||
): Promise<ScheduledTask> {
|
||||
const { data } = await apiClient.put<ScheduledTask>(`/schedules/${id}`, payload);
|
||||
@@ -49,8 +55,10 @@ export async function toggleSchedule(id: string): Promise<ScheduledTask> {
|
||||
}
|
||||
|
||||
/** 手动执行调度任务一次(不更新调度间隔) */
|
||||
export async function runScheduleNow(id: string): Promise<{ message: string; task_id: string }> {
|
||||
const { data } = await apiClient.post<{ message: string; task_id: string }>(`/schedules/${id}/run`);
|
||||
export async function runScheduleNow(id: string, force = false): Promise<{ message: string; task_id: string }> {
|
||||
const { data } = await apiClient.post<{ message: string; task_id: string }>(`/schedules/${id}/run`, null, {
|
||||
params: force ? { force: true } : undefined,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
187
apps/admin-web/src/api/taskEngine.ts
Normal file
187
apps/admin-web/src/api/taskEngine.ts
Normal file
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* P18 任务引擎运营看板 API。
|
||||
*
|
||||
* 端点前缀:/api/admin/task-engine
|
||||
*/
|
||||
|
||||
import { apiClient } from "./client";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 类型定义 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export interface TransferLogItem {
|
||||
id: number;
|
||||
site_id: number;
|
||||
site_name: string;
|
||||
member_id: number;
|
||||
member_name: string;
|
||||
from_assistant_id: number;
|
||||
from_assistant_name: string;
|
||||
to_assistant_id: number;
|
||||
to_assistant_name: string;
|
||||
transfer_reason: string | null;
|
||||
transfer_score: number | null;
|
||||
guard_checks: Record<string, unknown> | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface TransferLogPage {
|
||||
items: TransferLogItem[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface PendingReviewItem {
|
||||
id: number;
|
||||
site_id: number;
|
||||
site_name: string;
|
||||
member_id: number;
|
||||
member_name: string;
|
||||
assistant_id: number;
|
||||
assistant_name: string;
|
||||
task_type: string;
|
||||
task_type_label: string;
|
||||
transfer_count: number;
|
||||
priority_score: number | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface PendingReviewPage {
|
||||
items: PendingReviewItem[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface ConfigParam {
|
||||
id: number;
|
||||
site_id: number | null;
|
||||
site_name: string | null;
|
||||
param_key: string;
|
||||
param_value: number;
|
||||
description: string | null;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface ConfigParamList {
|
||||
params: ConfigParam[];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 转移日志 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export interface TransferLogQuery {
|
||||
site_id?: number;
|
||||
from_date?: string;
|
||||
to_date?: string;
|
||||
assistant_id?: number;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export async function fetchTransferLogs(
|
||||
query: TransferLogQuery = {},
|
||||
): Promise<TransferLogPage> {
|
||||
const resp = await apiClient.get<TransferLogPage>(
|
||||
"/admin/task-engine/transfer-log",
|
||||
{ params: query },
|
||||
);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
export async function fetchMemberTransferHistory(
|
||||
memberId: number,
|
||||
): Promise<TransferLogItem[]> {
|
||||
const resp = await apiClient.get<TransferLogItem[]>(
|
||||
`/admin/task-engine/transfer-log/${memberId}/history`,
|
||||
);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 待审核任务 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export interface PendingReviewQuery {
|
||||
site_id?: number;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export async function fetchPendingReviews(
|
||||
query: PendingReviewQuery = {},
|
||||
): Promise<PendingReviewPage> {
|
||||
const resp = await apiClient.get<PendingReviewPage>(
|
||||
"/admin/task-engine/pending-review",
|
||||
{ params: query },
|
||||
);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
export async function reassignTask(
|
||||
taskId: number,
|
||||
toAssistantId: number,
|
||||
): Promise<{ success: boolean; new_task_id: number | null }> {
|
||||
const resp = await apiClient.post(
|
||||
`/admin/task-engine/pending-review/${taskId}/reassign`,
|
||||
{ to_assistant_id: toAssistantId },
|
||||
);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
export async function closeTask(
|
||||
taskId: number,
|
||||
reason: string,
|
||||
): Promise<{ success: boolean }> {
|
||||
const resp = await apiClient.post(
|
||||
`/admin/task-engine/pending-review/${taskId}/close`,
|
||||
{ reason },
|
||||
);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 参数管理 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export async function fetchConfigParams(
|
||||
siteId?: number,
|
||||
): Promise<ConfigParamList> {
|
||||
const resp = await apiClient.get<ConfigParamList>(
|
||||
"/admin/task-engine/config",
|
||||
{ params: siteId != null ? { site_id: siteId } : {} },
|
||||
);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
export async function updateConfigParam(
|
||||
paramId: number,
|
||||
paramValue: number,
|
||||
): Promise<{ success: boolean }> {
|
||||
const resp = await apiClient.put(
|
||||
`/admin/task-engine/config/${paramId}`,
|
||||
{ param_value: paramValue },
|
||||
);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
export async function createConfigParam(
|
||||
siteId: number,
|
||||
paramKey: string,
|
||||
paramValue: number,
|
||||
): Promise<{ success: boolean; id: number }> {
|
||||
const resp = await apiClient.post("/admin/task-engine/config", {
|
||||
site_id: siteId,
|
||||
param_key: paramKey,
|
||||
param_value: paramValue,
|
||||
});
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
export async function deleteConfigParam(
|
||||
paramId: number,
|
||||
): Promise<{ success: boolean }> {
|
||||
const resp = await apiClient.delete(
|
||||
`/admin/task-engine/config/${paramId}`,
|
||||
);
|
||||
return resp.data;
|
||||
}
|
||||
110
apps/admin-web/src/api/tenantAdmins.ts
Normal file
110
apps/admin-web/src/api/tenantAdmins.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* 租户管理员 CRUD API 调用。
|
||||
*
|
||||
* 复用 apiClient(已含 JWT 拦截器 + 响应解包)。
|
||||
* 端点前缀:/admin/tenant-admins
|
||||
*/
|
||||
|
||||
import { apiClient } from "./client";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 类型定义 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** 列表项(后端 CamelModel 序列化为 camelCase) */
|
||||
export interface TenantAdminItem {
|
||||
id: number;
|
||||
username: string;
|
||||
displayName: string | null;
|
||||
tenantId: number;
|
||||
tenantName: string | null;
|
||||
adminType: string;
|
||||
managedSiteIds: number[];
|
||||
isActive: boolean;
|
||||
createdAt: string;
|
||||
lastLoginAt: string | null;
|
||||
}
|
||||
|
||||
/** 分页响应 */
|
||||
export interface TenantAdminListResponse {
|
||||
items: TenantAdminItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
/** 创建请求 */
|
||||
export interface TenantAdminCreatePayload {
|
||||
username: string;
|
||||
password: string;
|
||||
displayName: string;
|
||||
tenantId: number;
|
||||
managedSiteIds: number[];
|
||||
}
|
||||
|
||||
/** 编辑请求(所有字段可选) */
|
||||
export interface TenantAdminEditPayload {
|
||||
username?: string;
|
||||
displayName?: string;
|
||||
managedSiteIds?: number[];
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
/** 重置密码请求 */
|
||||
export interface ResetPasswordPayload {
|
||||
newPassword: string;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* API 调用 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** 列表查询(分页 + 关键词搜索 + 可选包含已禁用) */
|
||||
export async function fetchTenantAdmins(params: {
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
keyword?: string;
|
||||
include_inactive?: boolean;
|
||||
}): Promise<TenantAdminListResponse> {
|
||||
const { data } = await apiClient.get<TenantAdminListResponse>(
|
||||
"/admin/tenant-admins",
|
||||
{ params },
|
||||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 创建租户管理员 */
|
||||
export async function createTenantAdmin(
|
||||
payload: TenantAdminCreatePayload,
|
||||
): Promise<TenantAdminItem> {
|
||||
const { data } = await apiClient.post<TenantAdminItem>(
|
||||
"/admin/tenant-admins",
|
||||
payload,
|
||||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 编辑租户管理员 */
|
||||
export async function editTenantAdmin(
|
||||
id: number,
|
||||
payload: TenantAdminEditPayload,
|
||||
): Promise<TenantAdminItem> {
|
||||
const { data } = await apiClient.patch<TenantAdminItem>(
|
||||
`/admin/tenant-admins/${id}`,
|
||||
payload,
|
||||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 重置密码 */
|
||||
export async function resetTenantAdminPassword(
|
||||
id: number,
|
||||
payload: ResetPasswordPayload,
|
||||
): Promise<void> {
|
||||
await apiClient.post(`/admin/tenant-admins/${id}/reset-password`, payload);
|
||||
}
|
||||
|
||||
/** 删除租户管理员(软删除) */
|
||||
export async function deleteTenantAdmin(id: number): Promise<void> {
|
||||
await apiClient.delete(`/admin/tenant-admins/${id}`);
|
||||
}
|
||||
62
apps/admin-web/src/api/triggerJobs.ts
Normal file
62
apps/admin-web/src/api/triggerJobs.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* 定时任务管理 API 调用。
|
||||
*/
|
||||
|
||||
import { apiClient } from './client';
|
||||
|
||||
/** 定时任务信息 */
|
||||
export interface TriggerJob {
|
||||
id: number;
|
||||
job_type: string;
|
||||
job_name: string;
|
||||
trigger_condition: string;
|
||||
trigger_config: Record<string, unknown> | null;
|
||||
last_run_at: string | null;
|
||||
next_run_at: string | null;
|
||||
status: string;
|
||||
description: string | null;
|
||||
last_error: string | null;
|
||||
created_at: string | null;
|
||||
}
|
||||
|
||||
/** 手动执行结果 */
|
||||
export interface RunJobResult {
|
||||
success: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/** 获取所有定时任务 */
|
||||
export async function fetchTriggerJobs(): Promise<TriggerJob[]> {
|
||||
const { data } = await apiClient.get<TriggerJob[]>('/trigger-jobs');
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 手动执行指定任务 */
|
||||
export async function runTriggerJob(jobId: number): Promise<RunJobResult> {
|
||||
const { data } = await apiClient.post<RunJobResult>(`/trigger-jobs/${jobId}/run`);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 触发器配置更新请求 */
|
||||
export interface UpdateTriggerConfigReq {
|
||||
cron_expression?: string;
|
||||
interval_seconds?: number;
|
||||
}
|
||||
|
||||
/** 更新触发器配置(cron 表达式或间隔秒数) */
|
||||
export async function updateTriggerConfig(
|
||||
jobId: number,
|
||||
body: UpdateTriggerConfigReq,
|
||||
): Promise<TriggerJob> {
|
||||
const { data } = await apiClient.patch<TriggerJob>(
|
||||
`/trigger-jobs/${jobId}/config`,
|
||||
body,
|
||||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 【测试】清空所有 coach_tasks */
|
||||
export async function clearAllTasks(): Promise<RunJobResult> {
|
||||
const { data } = await apiClient.delete<RunJobResult>('/admin/task-engine/clear-all-tasks');
|
||||
return data;
|
||||
}
|
||||
23
apps/admin-web/src/api/triggers.ts
Normal file
23
apps/admin-web/src/api/triggers.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* 触发器统一视图 API 调用。
|
||||
*/
|
||||
|
||||
import { apiClient } from './client';
|
||||
|
||||
/** 统一触发器条目 */
|
||||
export interface UnifiedTriggerItem {
|
||||
id: number;
|
||||
name: string;
|
||||
source: 'biz' | 'ai' | 'etl';
|
||||
trigger_condition: string;
|
||||
status: string;
|
||||
last_run_at: string | null;
|
||||
next_run_at: string | null;
|
||||
last_error: string | null;
|
||||
}
|
||||
|
||||
/** 获取所有触发器统一视图 */
|
||||
export async function fetchUnifiedTriggers(): Promise<UnifiedTriggerItem[]> {
|
||||
const { data } = await apiClient.get<UnifiedTriggerItem[]>('/admin/triggers/unified');
|
||||
return data;
|
||||
}
|
||||
167
apps/admin-web/src/components/DbHealthCard.tsx
Normal file
167
apps/admin-web/src/components/DbHealthCard.tsx
Normal file
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* 数据库健康监控卡片
|
||||
*
|
||||
* 展示每个数据库的连接池状态、大小、慢查询数量。
|
||||
* 纯展示组件,接收 DbHealthItem[] 数据 + 加载/超时状态。
|
||||
*
|
||||
* - connected:展示完整指标(进度条 + 统计数值)
|
||||
* - disconnected:显示"未连接"状态标签
|
||||
* - 加载超时:展示"加载超时"状态 + 重试按钮
|
||||
*/
|
||||
|
||||
import React from "react";
|
||||
import {
|
||||
Card,
|
||||
Row,
|
||||
Col,
|
||||
Tag,
|
||||
Progress,
|
||||
Statistic,
|
||||
Button,
|
||||
Spin,
|
||||
Empty,
|
||||
} from "antd";
|
||||
import {
|
||||
DatabaseOutlined,
|
||||
CheckCircleOutlined,
|
||||
CloseCircleOutlined,
|
||||
ReloadOutlined,
|
||||
WarningOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import type { DbHealthItem } from "../api/dbHealth";
|
||||
|
||||
export interface DbHealthCardProps {
|
||||
/** 数据库健康数据列表 */
|
||||
items: DbHealthItem[];
|
||||
/** 是否正在加载 */
|
||||
loading?: boolean;
|
||||
/** 是否加载超时 */
|
||||
timeout?: boolean;
|
||||
/** 重试回调(超时时展示重试按钮) */
|
||||
onRetry?: () => void;
|
||||
}
|
||||
|
||||
/** 连接池总数(活跃 + 空闲),用于计算进度条百分比 */
|
||||
function poolPercent(active: number | null, idle: number | null): number {
|
||||
if (active == null || idle == null) return 0;
|
||||
const total = active + idle;
|
||||
if (total === 0) return 0;
|
||||
return Math.round((active / total) * 100);
|
||||
}
|
||||
|
||||
const DbHealthCard: React.FC<DbHealthCardProps> = ({
|
||||
items,
|
||||
loading = false,
|
||||
timeout = false,
|
||||
onRetry,
|
||||
}) => {
|
||||
// 加载超时状态
|
||||
if (timeout) {
|
||||
return (
|
||||
<Card size="small" title="数据库健康监控" style={{ marginBottom: 16 }}>
|
||||
<div style={{ textAlign: "center", padding: "24px 0" }}>
|
||||
<WarningOutlined style={{ fontSize: 32, color: "#faad14", marginBottom: 12 }} />
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<Tag color="warning" icon={<WarningOutlined />}>加载超时</Tag>
|
||||
</div>
|
||||
{onRetry && (
|
||||
<Button icon={<ReloadOutlined />} onClick={onRetry}>
|
||||
重试
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// 加载中
|
||||
if (loading) {
|
||||
return (
|
||||
<Card size="small" title="数据库健康监控" style={{ marginBottom: 16 }}>
|
||||
<div style={{ textAlign: "center", padding: "24px 0" }}>
|
||||
<Spin tip="加载中..." />
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// 无数据
|
||||
if (!items || items.length === 0) {
|
||||
return (
|
||||
<Card size="small" title="数据库健康监控" style={{ marginBottom: 16 }}>
|
||||
<Empty description="暂无数据" />
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card size="small" title="数据库健康监控" style={{ marginBottom: 16 }}>
|
||||
<Row gutter={16}>
|
||||
{items.map((item) => (
|
||||
<Col span={12} key={item.db_name} style={{ marginBottom: 16 }}>
|
||||
<Card
|
||||
size="small"
|
||||
type="inner"
|
||||
title={
|
||||
<span>
|
||||
<DatabaseOutlined style={{ marginRight: 6 }} />
|
||||
{item.db_name}
|
||||
</span>
|
||||
}
|
||||
extra={
|
||||
item.status === "connected" ? (
|
||||
<Tag color="success" icon={<CheckCircleOutlined />}>已连接</Tag>
|
||||
) : (
|
||||
<Tag color="error" icon={<CloseCircleOutlined />}>未连接</Tag>
|
||||
)
|
||||
}
|
||||
>
|
||||
{item.status === "connected" ? (
|
||||
<>
|
||||
{/* 连接池进度条 */}
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<div style={{ marginBottom: 4, fontSize: 12, color: "#666" }}>
|
||||
连接池(活跃 {item.active_connections ?? 0} / 空闲 {item.idle_connections ?? 0})
|
||||
</div>
|
||||
<Progress
|
||||
percent={poolPercent(item.active_connections, item.idle_connections)}
|
||||
size="small"
|
||||
format={(pct) => `${pct}%`}
|
||||
/>
|
||||
</div>
|
||||
{/* 统计指标 */}
|
||||
<Row gutter={16}>
|
||||
<Col span={12}>
|
||||
<Statistic
|
||||
title="数据库大小"
|
||||
value={item.db_size_mb ?? "-"}
|
||||
suffix="MB"
|
||||
valueStyle={{ fontSize: 16 }}
|
||||
/>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Statistic
|
||||
title="慢查询(1h)"
|
||||
value={item.slow_query_count ?? 0}
|
||||
valueStyle={{
|
||||
fontSize: 16,
|
||||
color: (item.slow_query_count ?? 0) > 0 ? "#faad14" : undefined,
|
||||
}}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
</>
|
||||
) : (
|
||||
<div style={{ textAlign: "center", padding: "16px 0", color: "#999" }}>
|
||||
数据库未连接,无法获取指标
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default DbHealthCard;
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
import { ReloadOutlined, EditOutlined, DeleteOutlined, HistoryOutlined, PlayCircleOutlined } from '@ant-design/icons';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import dayjs from 'dayjs';
|
||||
import relativeTime from 'dayjs/plugin/relativeTime';
|
||||
import 'dayjs/locale/zh-cn';
|
||||
import type { ScheduledTask, ScheduleConfig } from '../types';
|
||||
import {
|
||||
fetchSchedules,
|
||||
@@ -25,6 +27,9 @@ import {
|
||||
} from '../api/schedules';
|
||||
import ScheduleHistoryDrawer from './ScheduleHistoryDrawer';
|
||||
|
||||
dayjs.extend(relativeTime);
|
||||
dayjs.locale('zh-cn');
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
@@ -178,6 +183,8 @@ const ScheduleTab: React.FC = () => {
|
||||
const cfg = record.schedule_config;
|
||||
form.setFieldsValue({
|
||||
name: record.name,
|
||||
min_run_interval_value: record.min_run_interval_value ?? 0,
|
||||
min_run_interval_unit: record.min_run_interval_unit ?? 'minutes',
|
||||
schedule_config: {
|
||||
...cfg,
|
||||
daily_time: cfg.daily_time ? dayjs(cfg.daily_time, 'HH:mm') : undefined,
|
||||
@@ -226,6 +233,8 @@ const ScheduleTab: React.FC = () => {
|
||||
await updateSchedule(editing.id, {
|
||||
name: values.name,
|
||||
schedule_config: scheduleConfig,
|
||||
min_run_interval_value: values.min_run_interval_value ?? 0,
|
||||
min_run_interval_unit: values.min_run_interval_unit ?? 'minutes',
|
||||
});
|
||||
message.success('调度任务已更新');
|
||||
|
||||
@@ -259,13 +268,32 @@ const ScheduleTab: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
/* 手动执行一次(不更新调度间隔) */
|
||||
const handleRunNow = async (id: string) => {
|
||||
/* 手动执行 — 状态 */
|
||||
const [runConfirmOpen, setRunConfirmOpen] = useState(false);
|
||||
const [runForceCheck, setRunForceCheck] = useState(false);
|
||||
const [runTargetId, setRunTargetId] = useState<string | null>(null);
|
||||
|
||||
/* 打开手动执行确认 Modal */
|
||||
const openRunConfirm = (id: string) => {
|
||||
setRunTargetId(id);
|
||||
setRunForceCheck(false);
|
||||
setRunConfirmOpen(true);
|
||||
};
|
||||
|
||||
/* 确认手动执行 */
|
||||
const handleRunNow = async () => {
|
||||
if (!runTargetId) return;
|
||||
try {
|
||||
await runScheduleNow(id);
|
||||
await runScheduleNow(runTargetId, runForceCheck);
|
||||
message.success('已提交到执行队列');
|
||||
} catch {
|
||||
message.error('执行失败');
|
||||
setRunConfirmOpen(false);
|
||||
} catch (err: unknown) {
|
||||
const axiosErr = err as { response?: { status?: number; data?: { detail?: string } } };
|
||||
if (axiosErr?.response?.status === 409) {
|
||||
message.warning(axiosErr.response.data?.detail ?? '任务正在运行或未达到最小间隔');
|
||||
} else {
|
||||
message.error('执行失败');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -321,17 +349,33 @@ const ScheduleTab: React.FC = () => {
|
||||
render: (s: string | null) =>
|
||||
s ? <Tag color={STATUS_COLOR[s] ?? 'default'}>{s}</Tag> : '—',
|
||||
},
|
||||
{
|
||||
title: '最小间隔',
|
||||
dataIndex: 'min_run_interval_value',
|
||||
key: 'min_run_interval',
|
||||
width: 120,
|
||||
render: (value: number, record: ScheduledTask) => {
|
||||
if (!value) return '无限制';
|
||||
const unit = INTERVAL_UNIT_LABEL[record.min_run_interval_unit] ?? record.min_run_interval_unit;
|
||||
return `${value} ${unit}`;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '上次成功',
|
||||
dataIndex: 'last_success_at',
|
||||
key: 'last_success_at',
|
||||
width: 120,
|
||||
render: (value: string | null) => (value ? dayjs(value).fromNow() : '—'),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 300,
|
||||
render: (_: unknown, record: ScheduledTask) => (
|
||||
<Space size="small">
|
||||
<Popconfirm title="确认立即执行一次?(不影响调度间隔)" onConfirm={() => handleRunNow(record.id)}>
|
||||
<Button type="link" icon={<PlayCircleOutlined />} size="small">
|
||||
立即执行
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
<Button type="link" icon={<PlayCircleOutlined />} size="small" onClick={() => openRunConfirm(record.id)}>
|
||||
立即执行
|
||||
</Button>
|
||||
<Button type="link" icon={<HistoryOutlined />} size="small" onClick={() => openHistory(record)}>
|
||||
执行历史
|
||||
</Button>
|
||||
@@ -388,6 +432,21 @@ const ScheduleTab: React.FC = () => {
|
||||
</Form.Item>
|
||||
|
||||
<ScheduleConfigFields scheduleType={scheduleType} />
|
||||
|
||||
<Form.Item label="最小运行间隔">
|
||||
<Space>
|
||||
<Form.Item name="min_run_interval_value" noStyle initialValue={0}>
|
||||
<InputNumber min={0} placeholder="0 = 无限制" style={{ width: 140 }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="min_run_interval_unit" noStyle initialValue="minutes">
|
||||
<Select style={{ width: 100 }} options={[
|
||||
{ label: '分钟', value: 'minutes' },
|
||||
{ label: '小时', value: 'hours' },
|
||||
{ label: '天', value: 'days' },
|
||||
]} />
|
||||
</Form.Item>
|
||||
</Space>
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
@@ -398,6 +457,21 @@ const ScheduleTab: React.FC = () => {
|
||||
scheduleName={historyScheduleName}
|
||||
onClose={() => setHistoryOpen(false)}
|
||||
/>
|
||||
|
||||
{/* 手动执行确认 Modal */}
|
||||
<Modal
|
||||
title="确认立即执行"
|
||||
open={runConfirmOpen}
|
||||
onOk={handleRunNow}
|
||||
onCancel={() => setRunConfirmOpen(false)}
|
||||
okText="执行"
|
||||
cancelText="取消"
|
||||
>
|
||||
<p>确认立即执行一次?(不影响调度间隔)</p>
|
||||
<Checkbox checked={runForceCheck} onChange={(e) => setRunForceCheck(e.target.checked)}>
|
||||
强制执行(忽略最小间隔)
|
||||
</Checkbox>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
import React, { useEffect, useState, useMemo, useCallback } from "react";
|
||||
import {
|
||||
Collapse, Checkbox, Spin, Alert, Button, Space, Typography,
|
||||
Tag, Badge, Modal, Tooltip, Divider,
|
||||
Tag, Badge, Modal, Tooltip, Divider, InputNumber, Select,
|
||||
} from "antd";
|
||||
import {
|
||||
CheckCircleOutlined, WarningOutlined, SyncOutlined, TableOutlined,
|
||||
@@ -21,7 +21,7 @@ import {
|
||||
import type { CheckboxChangeEvent } from "antd/es/checkbox";
|
||||
import { fetchTaskRegistry, fetchDwdTablesRich, checkTaskSync } from "../api/tasks";
|
||||
import type { DwdTableItem as ApiDwdTableItem, SyncCheckResult } from "../api/tasks";
|
||||
import type { TaskDefinition, DwdTableItem } from "../types";
|
||||
import type { TaskDefinition, DwdTableItem, MinRunIntervalItem } from "../types";
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
@@ -44,6 +44,9 @@ export interface TaskSelectorProps {
|
||||
onTasksChange: (tasks: string[]) => void;
|
||||
selectedDwdTables?: string[];
|
||||
onDwdTablesChange?: (tables: string[]) => void;
|
||||
/** per-task-code 最小执行间隔 */
|
||||
taskIntervals?: Record<string, MinRunIntervalItem>;
|
||||
onTaskIntervalsChange?: (intervals: Record<string, MinRunIntervalItem>) => void;
|
||||
}
|
||||
|
||||
interface DomainGroup {
|
||||
@@ -105,6 +108,7 @@ function buildDomainGroups(
|
||||
const TaskSelector: React.FC<TaskSelectorProps> = ({
|
||||
layers, selectedTasks, onTasksChange,
|
||||
selectedDwdTables = [], onDwdTablesChange,
|
||||
taskIntervals = {}, onTaskIntervalsChange,
|
||||
}) => {
|
||||
const [registry, setRegistry] = useState<Record<string, TaskDefinition[]>>({});
|
||||
const [dwdTableGroups, setDwdTableGroups] = useState<Record<string, DwdTableItem[]>>({});
|
||||
@@ -241,6 +245,24 @@ const TaskSelector: React.FC<TaskSelectorProps> = ({
|
||||
[selectedDwdTables, onDwdTablesChange],
|
||||
);
|
||||
|
||||
/* 间隔设置 */
|
||||
const handleIntervalChange = useCallback(
|
||||
(code: string, field: "value" | "unit", val: number | string) => {
|
||||
if (!onTaskIntervalsChange) return;
|
||||
const current = taskIntervals[code] ?? { value: 0, unit: "minutes" as const };
|
||||
const updated = { ...current, [field]: val };
|
||||
if (updated.value === 0 || updated.value === null) {
|
||||
// 值为 0 时移除该任务的间隔设置
|
||||
const next = { ...taskIntervals };
|
||||
delete next[code];
|
||||
onTaskIntervalsChange(next);
|
||||
} else {
|
||||
onTaskIntervalsChange({ ...taskIntervals, [code]: updated as MinRunIntervalItem });
|
||||
}
|
||||
},
|
||||
[taskIntervals, onTaskIntervalsChange],
|
||||
);
|
||||
|
||||
/* 渲染 */
|
||||
if (loading) return <Spin tip="加载任务列表…" />;
|
||||
if (error) return <Alert type="error" message="加载失败" description={error} />;
|
||||
@@ -373,7 +395,7 @@ const TaskSelector: React.FC<TaskSelectorProps> = ({
|
||||
</div>
|
||||
<div style={{ paddingLeft: 4 }}>
|
||||
{lt.tasks.map((t) => (
|
||||
<div key={t.code} style={{ padding: "2px 0" }}>
|
||||
<div key={t.code} style={{ padding: "2px 0", display: "flex", alignItems: "center", gap: 8 }}>
|
||||
<Checkbox
|
||||
checked={selectedTasks.includes(t.code)}
|
||||
onChange={(e) => handleTaskToggle(t.code, e.target.checked)}
|
||||
@@ -385,6 +407,31 @@ const TaskSelector: React.FC<TaskSelectorProps> = ({
|
||||
)}
|
||||
{!t.is_common && <Tag color="default" style={{ marginLeft: 6, fontSize: 11 }}>不常用</Tag>}
|
||||
</Checkbox>
|
||||
{/* per-task 最小执行间隔 */}
|
||||
{onTaskIntervalsChange && (
|
||||
<Space size={2} style={{ marginLeft: "auto", flexShrink: 0 }}>
|
||||
<InputNumber
|
||||
size="small"
|
||||
min={0}
|
||||
max={9999}
|
||||
placeholder="间隔"
|
||||
value={taskIntervals[t.code]?.value || null}
|
||||
onChange={(v) => handleIntervalChange(t.code, "value", v ?? 0)}
|
||||
style={{ width: 70 }}
|
||||
/>
|
||||
<Select
|
||||
size="small"
|
||||
value={taskIntervals[t.code]?.unit ?? "minutes"}
|
||||
onChange={(v) => handleIntervalChange(t.code, "unit", v)}
|
||||
style={{ width: 72 }}
|
||||
options={[
|
||||
{ label: "分钟", value: "minutes" },
|
||||
{ label: "小时", value: "hours" },
|
||||
{ label: "天", value: "days" },
|
||||
]}
|
||||
/>
|
||||
</Space>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
145
apps/admin-web/src/components/ops/GitStatusSection.tsx
Normal file
145
apps/admin-web/src/components/ops/GitStatusSection.tsx
Normal file
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* Git 状态与配置区块
|
||||
*
|
||||
* 展示各环境 Git 分支/提交信息,支持 pull / 同步依赖 / 查看 .env 配置。
|
||||
* 从 OpsPanel 拆分,可独立使用(如 Dashboard 聚合页)。
|
||||
*/
|
||||
|
||||
import React, { useState } from "react";
|
||||
import {
|
||||
Card,
|
||||
Row,
|
||||
Col,
|
||||
Tag,
|
||||
Button,
|
||||
Space,
|
||||
Descriptions,
|
||||
Modal,
|
||||
Tooltip,
|
||||
Typography,
|
||||
Input,
|
||||
message,
|
||||
} from "antd";
|
||||
import {
|
||||
CloudDownloadOutlined,
|
||||
SyncOutlined,
|
||||
FileTextOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import type { ServiceStatus, GitInfo } from "../../api/opsPanel";
|
||||
import { fetchEnvFile } from "../../api/opsPanel";
|
||||
|
||||
const { Text } = Typography;
|
||||
const { TextArea } = Input;
|
||||
|
||||
export interface GitStatusSectionProps {
|
||||
gitInfos: GitInfo[];
|
||||
/** 用于查找 env 对应的 label */
|
||||
services: ServiceStatus[];
|
||||
actionLoading: Record<string, boolean>;
|
||||
onPull: (env: string) => void;
|
||||
onSyncDeps: (env: string) => void;
|
||||
}
|
||||
|
||||
const GitStatusSection: React.FC<GitStatusSectionProps> = ({
|
||||
gitInfos,
|
||||
services,
|
||||
actionLoading,
|
||||
onPull,
|
||||
onSyncDeps,
|
||||
}) => {
|
||||
const [envModalOpen, setEnvModalOpen] = useState(false);
|
||||
const [envModalContent, setEnvModalContent] = useState("");
|
||||
const [envModalTitle, setEnvModalTitle] = useState("");
|
||||
|
||||
const handleViewEnv = async (env: string, label: string) => {
|
||||
try {
|
||||
const r = await fetchEnvFile(env);
|
||||
setEnvModalTitle(`${label} .env 配置`);
|
||||
setEnvModalContent(r.content);
|
||||
setEnvModalOpen(true);
|
||||
} catch {
|
||||
message.error("读取配置文件失败");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card size="small" title="代码与配置" style={{ marginBottom: 16 }}>
|
||||
<Row gutter={16}>
|
||||
{gitInfos.map((git) => {
|
||||
const envCfg = services.find((s) => s.env === git.env);
|
||||
const label = envCfg?.label ?? git.env;
|
||||
return (
|
||||
<Col span={12} key={git.env}>
|
||||
<Card size="small" type="inner" title={label}>
|
||||
<Descriptions size="small" column={1} style={{ marginBottom: 12 }}>
|
||||
<Descriptions.Item label="分支">
|
||||
<Tag color="blue">{git.branch}</Tag>
|
||||
{git.has_local_changes && (
|
||||
<Tooltip title="工作区有未提交的变更">
|
||||
<Tag color="warning">有变更</Tag>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="最新提交">
|
||||
<Text code style={{ fontSize: 12 }}>{git.last_commit_hash}</Text>
|
||||
<Text type="secondary" style={{ marginLeft: 8, fontSize: 12 }}>
|
||||
{git.last_commit_message}
|
||||
</Text>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="提交时间">
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>{git.last_commit_time}</Text>
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<Space>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<CloudDownloadOutlined />}
|
||||
loading={actionLoading[`pull-${git.env}`]}
|
||||
onClick={() => onPull(git.env)}
|
||||
>
|
||||
Git Pull
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<SyncOutlined />}
|
||||
loading={actionLoading[`sync-${git.env}`]}
|
||||
onClick={() => onSyncDeps(git.env)}
|
||||
>
|
||||
同步依赖
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<FileTextOutlined />}
|
||||
onClick={() => handleViewEnv(git.env, label)}
|
||||
>
|
||||
查看配置
|
||||
</Button>
|
||||
</Space>
|
||||
</Card>
|
||||
</Col>
|
||||
);
|
||||
})}
|
||||
</Row>
|
||||
</Card>
|
||||
|
||||
{/* 配置查看弹窗 */}
|
||||
<Modal
|
||||
title={envModalTitle}
|
||||
open={envModalOpen}
|
||||
onCancel={() => setEnvModalOpen(false)}
|
||||
footer={null}
|
||||
width={700}
|
||||
>
|
||||
<TextArea
|
||||
value={envModalContent}
|
||||
readOnly
|
||||
autoSize={{ minRows: 10, maxRows: 30 }}
|
||||
style={{ fontFamily: "monospace", fontSize: 12 }}
|
||||
/>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default GitStatusSection;
|
||||
127
apps/admin-web/src/components/ops/ServiceStatusSection.tsx
Normal file
127
apps/admin-web/src/components/ops/ServiceStatusSection.tsx
Normal file
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* 服务状态区块
|
||||
*
|
||||
* 展示各环境服务运行状态,支持启动/停止/重启操作。
|
||||
* 从 OpsPanel 拆分,可独立使用(如 Dashboard 聚合页)。
|
||||
*/
|
||||
|
||||
import React from "react";
|
||||
import {
|
||||
Card,
|
||||
Row,
|
||||
Col,
|
||||
Tag,
|
||||
Button,
|
||||
Space,
|
||||
Descriptions,
|
||||
} from "antd";
|
||||
import {
|
||||
PlayCircleOutlined,
|
||||
PauseCircleOutlined,
|
||||
ReloadOutlined,
|
||||
CheckCircleOutlined,
|
||||
CloseCircleOutlined,
|
||||
ClockCircleOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import type { ServiceStatus } from "../../api/opsPanel";
|
||||
|
||||
/** 秒数格式化为 "Xd Xh Xm" */
|
||||
function formatUptime(seconds: number | null): string {
|
||||
if (seconds == null) return "-";
|
||||
const d = Math.floor(seconds / 86400);
|
||||
const h = Math.floor((seconds % 86400) / 3600);
|
||||
const m = Math.floor((seconds % 3600) / 60);
|
||||
const parts: string[] = [];
|
||||
if (d > 0) parts.push(`${d}天`);
|
||||
if (h > 0) parts.push(`${h}时`);
|
||||
parts.push(`${m}分`);
|
||||
return parts.join(" ");
|
||||
}
|
||||
|
||||
export interface ServiceStatusSectionProps {
|
||||
services: ServiceStatus[];
|
||||
actionLoading: Record<string, boolean>;
|
||||
onStart: (env: string) => void;
|
||||
onStop: (env: string) => void;
|
||||
onRestart: (env: string) => void;
|
||||
}
|
||||
|
||||
const ServiceStatusSection: React.FC<ServiceStatusSectionProps> = ({
|
||||
services,
|
||||
actionLoading,
|
||||
onStart,
|
||||
onStop,
|
||||
onRestart,
|
||||
}) => (
|
||||
<Card size="small" title="服务状态" style={{ marginBottom: 16 }}>
|
||||
<Row gutter={16}>
|
||||
{services.map((svc) => (
|
||||
<Col span={12} key={svc.env}>
|
||||
<Card
|
||||
size="small"
|
||||
type="inner"
|
||||
title={
|
||||
<Space>
|
||||
{svc.running
|
||||
? <CheckCircleOutlined style={{ color: "#52c41a" }} />
|
||||
: <CloseCircleOutlined style={{ color: "#ff4d4f" }} />}
|
||||
{svc.label}
|
||||
<Tag color={svc.running ? "success" : "error"}>
|
||||
{svc.running ? "运行中" : "已停止"}
|
||||
</Tag>
|
||||
</Space>
|
||||
}
|
||||
extra={<Tag>:{svc.port}</Tag>}
|
||||
>
|
||||
{svc.running && (
|
||||
<Descriptions size="small" column={3} style={{ marginBottom: 12 }}>
|
||||
<Descriptions.Item label="PID">{svc.pid}</Descriptions.Item>
|
||||
<Descriptions.Item label="运行时长">
|
||||
<ClockCircleOutlined style={{ marginRight: 4 }} />
|
||||
{formatUptime(svc.uptime_seconds)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="内存">{svc.memory_mb ?? "-"} MB</Descriptions.Item>
|
||||
</Descriptions>
|
||||
)}
|
||||
<Space>
|
||||
{!svc.running && (
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
icon={<PlayCircleOutlined />}
|
||||
loading={actionLoading[`start-${svc.env}`]}
|
||||
onClick={() => onStart(svc.env)}
|
||||
>
|
||||
启动
|
||||
</Button>
|
||||
)}
|
||||
{svc.running && (
|
||||
<>
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
icon={<PauseCircleOutlined />}
|
||||
loading={actionLoading[`stop-${svc.env}`]}
|
||||
onClick={() => onStop(svc.env)}
|
||||
>
|
||||
停止
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<ReloadOutlined />}
|
||||
loading={actionLoading[`restart-${svc.env}`]}
|
||||
onClick={() => onRestart(svc.env)}
|
||||
>
|
||||
重启
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
</Card>
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
</Card>
|
||||
);
|
||||
|
||||
export default ServiceStatusSection;
|
||||
65
apps/admin-web/src/components/ops/SystemResourceSection.tsx
Normal file
65
apps/admin-web/src/components/ops/SystemResourceSection.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* 系统资源区块
|
||||
*
|
||||
* 展示服务器 CPU / 内存 / 磁盘使用情况。
|
||||
* 从 OpsPanel 拆分,可独立使用(如 Dashboard 聚合页)。
|
||||
*/
|
||||
|
||||
import React from "react";
|
||||
import { Card, Row, Col, Statistic, Progress, Typography } from "antd";
|
||||
import type { SystemInfo } from "../../api/opsPanel";
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
export interface SystemResourceSectionProps {
|
||||
system: SystemInfo;
|
||||
}
|
||||
|
||||
const SystemResourceSection: React.FC<SystemResourceSectionProps> = ({ system }) => (
|
||||
<Card size="small" title="服务器资源" style={{ marginBottom: 16 }}>
|
||||
<Row gutter={24}>
|
||||
<Col span={8}>
|
||||
<Statistic title="CPU 使用率" value={system.cpu_percent} suffix="%" />
|
||||
<Progress
|
||||
percent={system.cpu_percent}
|
||||
size="small"
|
||||
status={system.cpu_percent > 80 ? "exception" : "normal"}
|
||||
showInfo={false}
|
||||
/>
|
||||
</Col>
|
||||
<Col span={8}>
|
||||
<Statistic
|
||||
title="内存"
|
||||
value={system.memory_used_gb}
|
||||
suffix={`/ ${system.memory_total_gb} GB`}
|
||||
precision={1}
|
||||
/>
|
||||
<Progress
|
||||
percent={system.memory_percent}
|
||||
size="small"
|
||||
status={system.memory_percent > 85 ? "exception" : "normal"}
|
||||
showInfo={false}
|
||||
/>
|
||||
</Col>
|
||||
<Col span={8}>
|
||||
<Statistic
|
||||
title="磁盘"
|
||||
value={system.disk_used_gb}
|
||||
suffix={`/ ${system.disk_total_gb} GB`}
|
||||
precision={1}
|
||||
/>
|
||||
<Progress
|
||||
percent={system.disk_percent}
|
||||
size="small"
|
||||
status={system.disk_percent > 90 ? "exception" : "normal"}
|
||||
showInfo={false}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
<Text type="secondary" style={{ fontSize: 12, marginTop: 8, display: "block" }}>
|
||||
开机时间:{new Date(system.boot_time).toLocaleString()}
|
||||
</Text>
|
||||
</Card>
|
||||
);
|
||||
|
||||
export default SystemResourceSection;
|
||||
14
apps/admin-web/src/components/ops/index.ts
Normal file
14
apps/admin-web/src/components/ops/index.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* OpsPanel 子组件导出
|
||||
*
|
||||
* 从 OpsPanel 拆分的三个独立区块,可被 Dashboard 等页面单独引用。
|
||||
*/
|
||||
|
||||
export { default as SystemResourceSection } from "./SystemResourceSection";
|
||||
export type { SystemResourceSectionProps } from "./SystemResourceSection";
|
||||
|
||||
export { default as ServiceStatusSection } from "./ServiceStatusSection";
|
||||
export type { ServiceStatusSectionProps } from "./ServiceStatusSection";
|
||||
|
||||
export { default as GitStatusSection } from "./GitStatusSection";
|
||||
export type { GitStatusSectionProps } from "./GitStatusSection";
|
||||
217
apps/admin-web/src/pages/AIDashboard.tsx
Normal file
217
apps/admin-web/src/pages/AIDashboard.tsx
Normal file
@@ -0,0 +1,217 @@
|
||||
/**
|
||||
* AI 运行总览 Dashboard 页面。
|
||||
*
|
||||
* - 顶部:门店筛选 + 刷新
|
||||
* - 第一行:4 个统计卡片(今日调用、成功率、Token 消耗、平均延迟)
|
||||
* - 第二行:7 天趋势表格 + App 调用占比表格
|
||||
* - 第三行:Token 预算进度条 + App 健康状态
|
||||
* - 第四行:告警列表
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import {
|
||||
Card, Row, Col, Statistic, Table, Tag, Badge, Progress,
|
||||
Select, Button, message, Typography, Space,
|
||||
} from "antd";
|
||||
import { ReloadOutlined } from "@ant-design/icons";
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
import {
|
||||
getDashboard,
|
||||
type DashboardResponse, type DailyTrend, type AppDistItem,
|
||||
type AlertItem, type AppHealthItem,
|
||||
} from "../api/adminAI";
|
||||
|
||||
const { Title } = Typography;
|
||||
|
||||
const ALERT_STATUS_COLOR: Record<string, string> = {
|
||||
failed: "red", timeout: "orange", circuit_open: "volcano",
|
||||
};
|
||||
|
||||
const ALERT_MGMT_COLOR: Record<string, string> = {
|
||||
pending: "warning", acknowledged: "success", ignored: "default",
|
||||
};
|
||||
|
||||
const HEALTH_STATUS: Record<string, "success" | "error" | "warning" | "default"> = {
|
||||
success: "success", failed: "error", timeout: "warning", circuit_open: "error",
|
||||
};
|
||||
|
||||
function fmtTime(raw: string | null): string {
|
||||
if (!raw) return "—";
|
||||
const d = new Date(raw);
|
||||
return Number.isNaN(d.getTime()) ? raw : d.toLocaleString("zh-CN");
|
||||
}
|
||||
|
||||
// ---- 表格列定义 ----
|
||||
|
||||
const trendColumns: ColumnsType<DailyTrend> = [
|
||||
{ title: "日期", dataIndex: "date", key: "date", width: 120 },
|
||||
{ title: "调用量", dataIndex: "calls", key: "calls", align: "right" },
|
||||
{
|
||||
title: "成功率", dataIndex: "success_rate", key: "success_rate", align: "right",
|
||||
render: (v: number) => `${(v * 100).toFixed(1)}%`,
|
||||
},
|
||||
];
|
||||
|
||||
const distColumns: ColumnsType<AppDistItem> = [
|
||||
{ title: "App 类型", dataIndex: "app_type", key: "app_type" },
|
||||
{ title: "调用次数", dataIndex: "count", key: "count", align: "right" },
|
||||
{
|
||||
title: "占比", dataIndex: "percentage", key: "percentage", align: "right",
|
||||
render: (v: number) => `${(v * 100).toFixed(1)}%`,
|
||||
},
|
||||
];
|
||||
|
||||
const alertColumns: ColumnsType<AlertItem> = [
|
||||
{ title: "ID", dataIndex: "id", key: "id", width: 80 },
|
||||
{ title: "App", dataIndex: "app_type", key: "app_type", width: 160 },
|
||||
{
|
||||
title: "状态", dataIndex: "status", key: "status", width: 110,
|
||||
render: (v: string) => <Tag color={ALERT_STATUS_COLOR[v] ?? "default"}>{v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: "告警状态", dataIndex: "alert_status", key: "alert_status", width: 110,
|
||||
render: (v: string | null) => v ? <Tag color={ALERT_MGMT_COLOR[v] ?? "default"}>{v}</Tag> : "—",
|
||||
},
|
||||
{
|
||||
title: "错误信息", dataIndex: "error_message", key: "error_message", ellipsis: true,
|
||||
render: (v: string | null) => v ?? "—",
|
||||
},
|
||||
{ title: "时间", dataIndex: "created_at", key: "created_at", width: 170, render: fmtTime },
|
||||
];
|
||||
|
||||
// ---- 页面组件 ----
|
||||
|
||||
const AIDashboard: React.FC = () => {
|
||||
const [data, setData] = useState<DashboardResponse | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [siteId, setSiteId] = useState<number | undefined>(undefined);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await getDashboard(siteId);
|
||||
setData(res);
|
||||
} catch {
|
||||
message.error("加载 Dashboard 失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [siteId]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* 顶部:门店筛选 + 刷新 */}
|
||||
<Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
|
||||
<Space>
|
||||
<Title level={4} style={{ margin: 0 }}>AI 运行总览</Title>
|
||||
<Select
|
||||
allowClear placeholder="门店筛选" style={{ width: 200 }}
|
||||
value={siteId} onChange={(v) => setSiteId(v)}
|
||||
options={[{ label: "默认门店", value: 2790685415443269 }]}
|
||||
/>
|
||||
</Space>
|
||||
<Button icon={<ReloadOutlined />} onClick={load} loading={loading}>刷新</Button>
|
||||
</Row>
|
||||
|
||||
{/* 第一行:4 个统计卡片 */}
|
||||
<Row gutter={16} style={{ marginBottom: 16 }}>
|
||||
<Col span={6}>
|
||||
<Card><Statistic title="今日调用次数" value={data?.today_calls ?? 0} /></Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card>
|
||||
<Statistic
|
||||
title="今日成功率" suffix="%"
|
||||
value={data ? (data.today_success_rate * 100).toFixed(1) : "0.0"}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card><Statistic title="今日 Token 消耗" value={data?.today_tokens ?? 0} /></Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card>
|
||||
<Statistic
|
||||
title="平均延迟" suffix="ms"
|
||||
value={data ? data.today_avg_latency_ms.toFixed(0) : "0"}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* 第二行:7 天趋势 + App 调用占比 */}
|
||||
<Row gutter={16} style={{ marginBottom: 16 }}>
|
||||
<Col span={12}>
|
||||
<Card title="近 7 天趋势" size="small">
|
||||
<Table<DailyTrend>
|
||||
columns={trendColumns}
|
||||
dataSource={data?.trend_7d ?? []}
|
||||
rowKey="date" size="small" pagination={false}
|
||||
loading={loading}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Card title="App 调用占比" size="small">
|
||||
<Table<AppDistItem>
|
||||
columns={distColumns}
|
||||
dataSource={data?.app_distribution ?? []}
|
||||
rowKey="app_type" size="small" pagination={false}
|
||||
loading={loading}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* 第三行:Token 预算 + App 健康状态 */}
|
||||
<Row gutter={16} style={{ marginBottom: 16 }}>
|
||||
<Col span={12}>
|
||||
<Card title="Token 预算" size="small">
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<span>日预算:{data?.budget.daily_used ?? 0} / {data?.budget.daily_limit ?? 0}</span>
|
||||
<Progress
|
||||
percent={data ? +(data.budget.daily_pct * 100).toFixed(1) : 0}
|
||||
status={data && data.budget.daily_pct > 0.9 ? "exception" : "active"}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<span>月预算:{data?.budget.monthly_used ?? 0} / {data?.budget.monthly_limit ?? 0}</span>
|
||||
<Progress
|
||||
percent={data ? +(data.budget.monthly_pct * 100).toFixed(1) : 0}
|
||||
status={data && data.budget.monthly_pct > 0.9 ? "exception" : "active"}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Card title="App 健康状态" size="small">
|
||||
{(data?.app_health ?? []).map((item: AppHealthItem) => (
|
||||
<div key={item.app_type} style={{ display: "flex", justifyContent: "space-between", padding: "4px 0" }}>
|
||||
<span>{item.app_type}</span>
|
||||
<Space>
|
||||
<Badge status={HEALTH_STATUS[item.last_status ?? ""] ?? "default"} text={item.last_status ?? "无记录"} />
|
||||
<span style={{ fontSize: 12, color: "#999" }}>{fmtTime(item.last_call_at)}</span>
|
||||
</Space>
|
||||
</div>
|
||||
))}
|
||||
{(data?.app_health ?? []).length === 0 && <span style={{ color: "#999" }}>暂无数据</span>}
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* 第四行:告警列表 */}
|
||||
<Card title="告警列表" size="small">
|
||||
<Table<AlertItem>
|
||||
columns={alertColumns}
|
||||
dataSource={data?.recent_alerts ?? []}
|
||||
rowKey="id" size="small" pagination={{ pageSize: 10 }}
|
||||
loading={loading}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AIDashboard;
|
||||
329
apps/admin-web/src/pages/AIOperations.tsx
Normal file
329
apps/admin-web/src/pages/AIOperations.tsx
Normal file
@@ -0,0 +1,329 @@
|
||||
/**
|
||||
* AI 手动操作页面。
|
||||
*
|
||||
* 4 个 Card 区域:
|
||||
* - Card 1:手动重跑(App + member_id + site_id → 执行)
|
||||
* - Card 2:缓存失效(app_type + member_id + site_id → 失效)
|
||||
* - Card 3:批量执行(app_types + member_ids + site_id → 预估 → 确认)
|
||||
* - Card 4:告警管理(告警列表 + 确认/忽略)
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import {
|
||||
Card, Row, Col, Select, Input, Button, Table, Tag, Space,
|
||||
Checkbox, Modal, Statistic, message, Typography,
|
||||
} from "antd";
|
||||
import { ReloadOutlined } from "@ant-design/icons";
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
import {
|
||||
retryTriggerJob, invalidateCache, createBatchRun, confirmBatchRun,
|
||||
getAlerts, ackAlert, ignoreAlert,
|
||||
type AlertItem, type BatchRunEstimate,
|
||||
} from "../api/adminAI";
|
||||
|
||||
const { TextArea } = Input;
|
||||
const { Title } = Typography;
|
||||
|
||||
const APP_TYPE_OPTIONS = [
|
||||
{ label: "App3 维客线索", value: "app3_clue" },
|
||||
{ label: "App4 关系分析", value: "app4_analysis" },
|
||||
{ label: "App5 话术参考", value: "app5_tactics" },
|
||||
{ label: "App6 备注分析", value: "app6_note_analysis" },
|
||||
{ label: "App7 客户分析", value: "app7_customer_analysis" },
|
||||
{ label: "App8 线索整理", value: "app8_clue_consolidated" },
|
||||
];
|
||||
|
||||
const ALERT_STATUS_COLOR: Record<string, string> = {
|
||||
failed: "red", timeout: "orange", circuit_open: "volcano",
|
||||
};
|
||||
|
||||
const ALERT_MGMT_COLOR: Record<string, string> = {
|
||||
pending: "warning", acknowledged: "success", ignored: "default",
|
||||
};
|
||||
|
||||
function fmtTime(raw: string | null): string {
|
||||
if (!raw) return "—";
|
||||
const d = new Date(raw);
|
||||
return Number.isNaN(d.getTime()) ? raw : d.toLocaleString("zh-CN");
|
||||
}
|
||||
|
||||
const AIOperations: React.FC = () => {
|
||||
// ---- Card 1: 手动重跑 ----
|
||||
const [retryJobId, setRetryJobId] = useState<string>("");
|
||||
const [retryLoading, setRetryLoading] = useState(false);
|
||||
|
||||
const handleRetry = async () => {
|
||||
const id = Number(retryJobId);
|
||||
if (!id || Number.isNaN(id)) { message.warning("请输入有效的任务 ID"); return; }
|
||||
setRetryLoading(true);
|
||||
try {
|
||||
const res = await retryTriggerJob(id);
|
||||
message.success(`已创建重跑任务 #${res.trigger_job_id}`);
|
||||
setRetryJobId("");
|
||||
} catch {
|
||||
message.error("重跑失败");
|
||||
} finally {
|
||||
setRetryLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ---- Card 2: 缓存失效 ----
|
||||
const [cacheAppType, setCacheAppType] = useState<string | undefined>();
|
||||
const [cacheMemberId, setCacheMemberId] = useState<string>("");
|
||||
const [cacheSiteId, setCacheSiteId] = useState<number>(2790685415443269);
|
||||
const [cacheLoading, setCacheLoading] = useState(false);
|
||||
const [cacheResult, setCacheResult] = useState<number | null>(null);
|
||||
|
||||
const handleInvalidate = async () => {
|
||||
setCacheLoading(true);
|
||||
setCacheResult(null);
|
||||
try {
|
||||
const res = await invalidateCache({
|
||||
site_id: cacheSiteId,
|
||||
app_type: cacheAppType,
|
||||
member_id: cacheMemberId ? Number(cacheMemberId) : undefined,
|
||||
});
|
||||
setCacheResult(res.affected_count);
|
||||
message.success(`已失效 ${res.affected_count} 条缓存`);
|
||||
} catch {
|
||||
message.error("缓存失效操作失败");
|
||||
} finally {
|
||||
setCacheLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ---- Card 3: 批量执行 ----
|
||||
const [batchAppTypes, setBatchAppTypes] = useState<string[]>([]);
|
||||
const [batchMemberIds, setBatchMemberIds] = useState<string>("");
|
||||
const [batchSiteId, setBatchSiteId] = useState<number>(2790685415443269);
|
||||
const [batchLoading, setBatchLoading] = useState(false);
|
||||
const [batchEstimate, setBatchEstimate] = useState<BatchRunEstimate | null>(null);
|
||||
const [confirmVisible, setConfirmVisible] = useState(false);
|
||||
const [confirmLoading, setConfirmLoading] = useState(false);
|
||||
|
||||
const parseMemberIds = (text: string): number[] =>
|
||||
text.split(/[\n,;\s]+/).map(Number).filter((n) => !Number.isNaN(n) && n > 0);
|
||||
|
||||
const handleBatchEstimate = async () => {
|
||||
const memberIds = parseMemberIds(batchMemberIds);
|
||||
if (batchAppTypes.length === 0) { message.warning("请选择至少一个 App"); return; }
|
||||
if (memberIds.length === 0) { message.warning("请输入有效的会员 ID"); return; }
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
const res = await createBatchRun({ app_types: batchAppTypes, member_ids: memberIds, site_id: batchSiteId });
|
||||
setBatchEstimate(res);
|
||||
setConfirmVisible(true);
|
||||
} catch {
|
||||
message.error("预估失败");
|
||||
} finally {
|
||||
setBatchLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBatchConfirm = async () => {
|
||||
if (!batchEstimate) return;
|
||||
setConfirmLoading(true);
|
||||
try {
|
||||
await confirmBatchRun(batchEstimate.batch_id);
|
||||
message.success("批量执行已启动");
|
||||
setConfirmVisible(false);
|
||||
setBatchEstimate(null);
|
||||
setBatchAppTypes([]);
|
||||
setBatchMemberIds("");
|
||||
} catch {
|
||||
message.error("确认执行失败");
|
||||
} finally {
|
||||
setConfirmLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ---- Card 4: 告警管理 ----
|
||||
const [alerts, setAlerts] = useState<AlertItem[]>([]);
|
||||
const [alertTotal, setAlertTotal] = useState(0);
|
||||
const [alertLoading, setAlertLoading] = useState(false);
|
||||
const [alertPage, setAlertPage] = useState(1);
|
||||
|
||||
const loadAlerts = useCallback(async () => {
|
||||
setAlertLoading(true);
|
||||
try {
|
||||
const res = await getAlerts({ page: alertPage, page_size: 10 });
|
||||
setAlerts(res.items);
|
||||
setAlertTotal(res.total);
|
||||
} catch {
|
||||
message.error("加载告警列表失败");
|
||||
} finally {
|
||||
setAlertLoading(false);
|
||||
}
|
||||
}, [alertPage]);
|
||||
|
||||
useEffect(() => { loadAlerts(); }, [loadAlerts]);
|
||||
|
||||
const handleAck = async (id: number) => {
|
||||
try {
|
||||
await ackAlert(id);
|
||||
message.success("已确认告警");
|
||||
loadAlerts();
|
||||
} catch {
|
||||
message.error("确认失败");
|
||||
}
|
||||
};
|
||||
|
||||
const handleIgnore = async (id: number) => {
|
||||
try {
|
||||
await ignoreAlert(id);
|
||||
message.success("已忽略告警");
|
||||
loadAlerts();
|
||||
} catch {
|
||||
message.error("忽略失败");
|
||||
}
|
||||
};
|
||||
|
||||
const alertColumns: ColumnsType<AlertItem> = [
|
||||
{ title: "ID", dataIndex: "id", key: "id", width: 70 },
|
||||
{ title: "App", dataIndex: "app_type", key: "app_type", width: 150 },
|
||||
{
|
||||
title: "状态", dataIndex: "status", key: "status", width: 100,
|
||||
render: (v: string) => <Tag color={ALERT_STATUS_COLOR[v] ?? "default"}>{v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: "告警状态", dataIndex: "alert_status", key: "alert_status", width: 100,
|
||||
render: (v: string | null) => v ? <Tag color={ALERT_MGMT_COLOR[v] ?? "default"}>{v}</Tag> : "—",
|
||||
},
|
||||
{ title: "错误信息", dataIndex: "error_message", key: "error_message", ellipsis: true, render: (v) => v ?? "—" },
|
||||
{ title: "时间", dataIndex: "created_at", key: "created_at", width: 160, render: fmtTime },
|
||||
{
|
||||
title: "操作", key: "action", width: 140,
|
||||
render: (_: unknown, r: AlertItem) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => handleAck(r.id)} disabled={r.alert_status === "acknowledged"}>确认</Button>
|
||||
<Button size="small" onClick={() => handleIgnore(r.id)} disabled={r.alert_status === "ignored"}>忽略</Button>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Title level={4} style={{ marginBottom: 16 }}>AI 手动操作</Title>
|
||||
|
||||
<Row gutter={16} style={{ marginBottom: 16 }}>
|
||||
{/* Card 1: 手动重跑 */}
|
||||
<Col span={12}>
|
||||
<Card title="手动重跑" size="small">
|
||||
<Space direction="vertical" style={{ width: "100%" }}>
|
||||
<Input
|
||||
placeholder="调度任务 ID" value={retryJobId}
|
||||
onChange={(e) => setRetryJobId(e.target.value)}
|
||||
/>
|
||||
<Button type="primary" onClick={handleRetry} loading={retryLoading}>执行重跑</Button>
|
||||
</Space>
|
||||
</Card>
|
||||
</Col>
|
||||
|
||||
{/* Card 2: 缓存失效 */}
|
||||
<Col span={12}>
|
||||
<Card title="缓存失效" size="small">
|
||||
<Space direction="vertical" style={{ width: "100%" }}>
|
||||
<Select
|
||||
allowClear placeholder="App 类型(可选)" style={{ width: "100%" }}
|
||||
value={cacheAppType} onChange={setCacheAppType}
|
||||
options={APP_TYPE_OPTIONS}
|
||||
/>
|
||||
<Input
|
||||
placeholder="会员 ID(可选)" value={cacheMemberId}
|
||||
onChange={(e) => setCacheMemberId(e.target.value)}
|
||||
/>
|
||||
<Select
|
||||
placeholder="门店" style={{ width: "100%" }}
|
||||
value={cacheSiteId} onChange={setCacheSiteId}
|
||||
options={[{ label: "默认门店", value: 2790685415443269 }]}
|
||||
/>
|
||||
<Space>
|
||||
<Button type="primary" danger onClick={handleInvalidate} loading={cacheLoading}>执行失效</Button>
|
||||
{cacheResult != null && <Statistic title="受影响记录" value={cacheResult} />}
|
||||
</Space>
|
||||
</Space>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* Card 3: 批量执行 */}
|
||||
<Card title="批量执行" size="small" style={{ marginBottom: 16 }}>
|
||||
<Row gutter={16}>
|
||||
<Col span={8}>
|
||||
<div style={{ marginBottom: 8, fontWeight: 500 }}>选择 App</div>
|
||||
<Checkbox.Group
|
||||
options={APP_TYPE_OPTIONS}
|
||||
value={batchAppTypes}
|
||||
onChange={(v) => setBatchAppTypes(v as string[])}
|
||||
style={{ display: "flex", flexDirection: "column", gap: 4 }}
|
||||
/>
|
||||
</Col>
|
||||
<Col span={8}>
|
||||
<div style={{ marginBottom: 8, fontWeight: 500 }}>会员 ID(每行一个或逗号分隔)</div>
|
||||
<TextArea
|
||||
rows={6} value={batchMemberIds}
|
||||
onChange={(e) => setBatchMemberIds(e.target.value)}
|
||||
placeholder="例如: 12345 67890"
|
||||
/>
|
||||
</Col>
|
||||
<Col span={8}>
|
||||
<div style={{ marginBottom: 8, fontWeight: 500 }}>门店</div>
|
||||
<Select
|
||||
style={{ width: "100%", marginBottom: 16 }}
|
||||
value={batchSiteId} onChange={setBatchSiteId}
|
||||
options={[{ label: "默认门店", value: 2790685415443269 }]}
|
||||
/>
|
||||
<Button type="primary" onClick={handleBatchEstimate} loading={batchLoading}>
|
||||
预估并执行
|
||||
</Button>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
|
||||
{/* 批量执行确认弹窗 */}
|
||||
<Modal
|
||||
title="确认批量执行"
|
||||
open={confirmVisible}
|
||||
onCancel={() => { setConfirmVisible(false); setBatchEstimate(null); }}
|
||||
onOk={handleBatchConfirm}
|
||||
confirmLoading={confirmLoading}
|
||||
okText="确认执行" cancelText="取消"
|
||||
>
|
||||
{batchEstimate && (
|
||||
<Row gutter={16}>
|
||||
<Col span={12}>
|
||||
<Statistic title="预估调用次数" value={batchEstimate.estimated_calls} suffix="次" />
|
||||
</Col>
|
||||
<Col span={12}>
|
||||
<Statistic title="预估 Token 消耗" value={batchEstimate.estimated_tokens} />
|
||||
</Col>
|
||||
</Row>
|
||||
)}
|
||||
<p style={{ marginTop: 16, color: "#faad14" }}>
|
||||
确认后将在后台异步执行,请确保预算充足。
|
||||
</p>
|
||||
</Modal>
|
||||
|
||||
{/* Card 4: 告警管理 */}
|
||||
<Card
|
||||
title="告警管理" size="small"
|
||||
extra={<Button icon={<ReloadOutlined />} size="small" onClick={loadAlerts}>刷新</Button>}
|
||||
>
|
||||
<Table<AlertItem>
|
||||
columns={alertColumns}
|
||||
dataSource={alerts}
|
||||
rowKey="id" size="small"
|
||||
loading={alertLoading}
|
||||
pagination={{
|
||||
current: alertPage, pageSize: 10, total: alertTotal,
|
||||
onChange: (p) => setAlertPage(p),
|
||||
showTotal: (t) => `共 ${t} 条`,
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AIOperations;
|
||||
229
apps/admin-web/src/pages/AIRunLogs.tsx
Normal file
229
apps/admin-web/src/pages/AIRunLogs.tsx
Normal file
@@ -0,0 +1,229 @@
|
||||
/**
|
||||
* AI 调用明细页面。
|
||||
*
|
||||
* - 顶部筛选器:app_type / status / trigger_type / site_id / 日期范围
|
||||
* - 主体:分页表格(app_type、trigger_type、member_id、tokens、延迟、状态)
|
||||
* - 点击行:Drawer 展示完整 prompt / response / error_message
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import {
|
||||
Card, Table, Tag, Select, Button, DatePicker, Row, Space,
|
||||
Drawer, Descriptions, message, Typography,
|
||||
} from "antd";
|
||||
import { ReloadOutlined } from "@ant-design/icons";
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
import {
|
||||
getRunLogs, getRunLogDetail,
|
||||
type RunLogItem, type RunLogDetailResponse, type RunLogQuery,
|
||||
} from "../api/adminAI";
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
const { Title } = Typography;
|
||||
|
||||
const STATUS_COLOR: Record<string, string> = {
|
||||
success: "green", failed: "red", timeout: "orange",
|
||||
circuit_open: "volcano", pending: "default", running: "processing",
|
||||
};
|
||||
|
||||
function fmtTime(raw: string | null): string {
|
||||
if (!raw) return "—";
|
||||
const d = new Date(raw);
|
||||
return Number.isNaN(d.getTime()) ? raw : d.toLocaleString("zh-CN");
|
||||
}
|
||||
|
||||
const AIRunLogs: React.FC = () => {
|
||||
const [items, setItems] = useState<RunLogItem[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize] = useState(20);
|
||||
|
||||
// 筛选状态
|
||||
const [appType, setAppType] = useState<string | undefined>();
|
||||
const [status, setStatus] = useState<string | undefined>();
|
||||
const [triggerType, setTriggerType] = useState<string | undefined>();
|
||||
const [siteId, setSiteId] = useState<number | undefined>();
|
||||
const [dateRange, setDateRange] = useState<[string, string] | null>(null);
|
||||
|
||||
// Drawer 详情
|
||||
const [drawerVisible, setDrawerVisible] = useState(false);
|
||||
const [detail, setDetail] = useState<RunLogDetailResponse | null>(null);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params: RunLogQuery = {
|
||||
page, page_size: pageSize,
|
||||
app_type: appType, status, trigger_type: triggerType,
|
||||
site_id: siteId,
|
||||
date_from: dateRange?.[0], date_to: dateRange?.[1],
|
||||
};
|
||||
const res = await getRunLogs(params);
|
||||
setItems(res.items);
|
||||
setTotal(res.total);
|
||||
} catch {
|
||||
message.error("加载调用记录失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [page, pageSize, appType, status, triggerType, siteId, dateRange]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const handleRowClick = async (id: number) => {
|
||||
setDetailLoading(true);
|
||||
setDrawerVisible(true);
|
||||
try {
|
||||
const res = await getRunLogDetail(id);
|
||||
setDetail(res);
|
||||
} catch {
|
||||
message.error("加载详情失败");
|
||||
} finally {
|
||||
setDetailLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const APP_TYPE_OPTIONS = [
|
||||
"app1_chat", "app2_finance", "app3_clue", "app4_analysis",
|
||||
"app5_tactics", "app6_note_analysis", "app7_customer_analysis",
|
||||
"app8_clue_consolidated",
|
||||
].map((v) => ({ label: v, value: v }));
|
||||
|
||||
const columns: ColumnsType<RunLogItem> = [
|
||||
{ title: "ID", dataIndex: "id", key: "id", width: 70 },
|
||||
{ title: "App 类型", dataIndex: "app_type", key: "app_type", width: 160 },
|
||||
{ title: "触发方式", dataIndex: "trigger_type", key: "trigger_type", width: 110 },
|
||||
{ title: "会员 ID", dataIndex: "member_id", key: "member_id", width: 100, render: (v) => v ?? "—" },
|
||||
{ title: "Tokens", dataIndex: "tokens_used", key: "tokens_used", width: 90, align: "right" },
|
||||
{
|
||||
title: "延迟", dataIndex: "latency_ms", key: "latency_ms", width: 90, align: "right",
|
||||
render: (v: number | null) => v != null ? `${v}ms` : "—",
|
||||
},
|
||||
{
|
||||
title: "状态", dataIndex: "status", key: "status", width: 110,
|
||||
render: (v: string) => <Tag color={STATUS_COLOR[v] ?? "default"}>{v}</Tag>,
|
||||
},
|
||||
{ title: "时间", dataIndex: "created_at", key: "created_at", width: 170, render: fmtTime },
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
|
||||
<Title level={4} style={{ margin: 0 }}>AI 调用明细</Title>
|
||||
<Button icon={<ReloadOutlined />} onClick={load} loading={loading}>刷新</Button>
|
||||
</Row>
|
||||
|
||||
{/* 筛选器行 */}
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<Space wrap>
|
||||
<Select
|
||||
allowClear placeholder="App 类型" style={{ width: 180 }}
|
||||
value={appType} onChange={(v) => { setAppType(v); setPage(1); }}
|
||||
options={APP_TYPE_OPTIONS}
|
||||
/>
|
||||
<Select
|
||||
allowClear placeholder="状态" style={{ width: 130 }}
|
||||
value={status} onChange={(v) => { setStatus(v); setPage(1); }}
|
||||
options={[
|
||||
{ label: "success", value: "success" },
|
||||
{ label: "failed", value: "failed" },
|
||||
{ label: "timeout", value: "timeout" },
|
||||
{ label: "circuit_open", value: "circuit_open" },
|
||||
]}
|
||||
/>
|
||||
<Select
|
||||
allowClear placeholder="触发方式" style={{ width: 130 }}
|
||||
value={triggerType} onChange={(v) => { setTriggerType(v); setPage(1); }}
|
||||
options={[
|
||||
{ label: "event", value: "event" },
|
||||
{ label: "scheduled", value: "scheduled" },
|
||||
{ label: "manual", value: "manual" },
|
||||
{ label: "backfill", value: "backfill" },
|
||||
]}
|
||||
/>
|
||||
<Select
|
||||
allowClear placeholder="门店" style={{ width: 180 }}
|
||||
value={siteId} onChange={(v) => { setSiteId(v); setPage(1); }}
|
||||
options={[{ label: "默认门店", value: 2790685415443269 }]}
|
||||
/>
|
||||
<RangePicker
|
||||
onChange={(_, dateStrings) => {
|
||||
setDateRange(dateStrings[0] ? [dateStrings[0], dateStrings[1]] : null);
|
||||
setPage(1);
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
{/* 主体表格 */}
|
||||
<Table<RunLogItem>
|
||||
columns={columns}
|
||||
dataSource={items}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
scroll={{ x: 1000 }}
|
||||
onRow={(record) => ({
|
||||
onClick: () => handleRowClick(record.id),
|
||||
style: { cursor: "pointer" },
|
||||
})}
|
||||
pagination={{
|
||||
current: page, pageSize, total,
|
||||
onChange: (p) => setPage(p),
|
||||
showTotal: (t) => `共 ${t} 条`,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 详情 Drawer */}
|
||||
<Drawer
|
||||
title={`调用记录详情 #${detail?.id ?? ""}`}
|
||||
open={drawerVisible}
|
||||
onClose={() => { setDrawerVisible(false); setDetail(null); }}
|
||||
width={640}
|
||||
loading={detailLoading}
|
||||
>
|
||||
{detail && (
|
||||
<>
|
||||
<Descriptions column={2} bordered size="small" style={{ marginBottom: 16 }}>
|
||||
<Descriptions.Item label="App 类型">{detail.app_type}</Descriptions.Item>
|
||||
<Descriptions.Item label="触发方式">{detail.trigger_type}</Descriptions.Item>
|
||||
<Descriptions.Item label="会员 ID">{detail.member_id ?? "—"}</Descriptions.Item>
|
||||
<Descriptions.Item label="门店 ID">{detail.site_id}</Descriptions.Item>
|
||||
<Descriptions.Item label="Tokens">{detail.tokens_used}</Descriptions.Item>
|
||||
<Descriptions.Item label="延迟">{detail.latency_ms != null ? `${detail.latency_ms}ms` : "—"}</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">
|
||||
<Tag color={STATUS_COLOR[detail.status] ?? "default"}>{detail.status}</Tag>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="Session ID">{detail.session_id ?? "—"}</Descriptions.Item>
|
||||
<Descriptions.Item label="创建时间" span={2}>{fmtTime(detail.created_at)}</Descriptions.Item>
|
||||
<Descriptions.Item label="完成时间" span={2}>{fmtTime(detail.finished_at)}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
|
||||
{detail.error_message && (
|
||||
<Card title="错误信息" size="small" style={{ marginBottom: 16 }}>
|
||||
<pre style={{ margin: 0, whiteSpace: "pre-wrap", color: "#cf1322" }}>
|
||||
{detail.error_message}
|
||||
</pre>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card title="Request Prompt" size="small" style={{ marginBottom: 16 }}>
|
||||
<pre style={{ margin: 0, whiteSpace: "pre-wrap", maxHeight: 300, overflow: "auto", background: "#f5f5f5", padding: 8, borderRadius: 4 }}>
|
||||
{detail.request_prompt ?? "(无)"}
|
||||
</pre>
|
||||
</Card>
|
||||
|
||||
<Card title="Response" size="small">
|
||||
<pre style={{ margin: 0, whiteSpace: "pre-wrap", maxHeight: 300, overflow: "auto", background: "#f5f5f5", padding: 8, borderRadius: 4 }}>
|
||||
{detail.response_text ?? "(无)"}
|
||||
</pre>
|
||||
</Card>
|
||||
</>
|
||||
)}
|
||||
</Drawer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AIRunLogs;
|
||||
247
apps/admin-web/src/pages/AITriggerJobs.tsx
Normal file
247
apps/admin-web/src/pages/AITriggerJobs.tsx
Normal file
@@ -0,0 +1,247 @@
|
||||
/**
|
||||
* AI 调度状态页面。
|
||||
*
|
||||
* - 顶部筛选器:event_type / status / site_id / 日期范围
|
||||
* - 统计行:今日去重跳过数
|
||||
* - 主体:分页表格(事件类型、会员、状态、执行链、耗时、操作列)
|
||||
* - 操作列:查看详情 Modal、手动重跑 Popconfirm
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import {
|
||||
Card, Table, Tag, Select, Button, DatePicker, Row, Col, Space,
|
||||
Statistic, Modal, Popconfirm, Descriptions, message, Typography,
|
||||
} from "antd";
|
||||
import { ReloadOutlined } from "@ant-design/icons";
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
import {
|
||||
getTriggerJobs, getTriggerJobDetail, retryTriggerJob,
|
||||
type TriggerJobItem, type TriggerJobDetailResponse, type TriggerJobQuery,
|
||||
} from "../api/adminAI";
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
const { Title } = Typography;
|
||||
|
||||
const STATUS_COLOR: Record<string, string> = {
|
||||
pending: "default", running: "processing", success: "success",
|
||||
failed: "error", skipped_duplicate: "warning", timeout: "orange",
|
||||
};
|
||||
|
||||
function fmtTime(raw: string | null): string {
|
||||
if (!raw) return "—";
|
||||
const d = new Date(raw);
|
||||
return Number.isNaN(d.getTime()) ? raw : d.toLocaleString("zh-CN");
|
||||
}
|
||||
|
||||
function calcDuration(start: string | null, end: string | null): string {
|
||||
if (!start || !end) return "—";
|
||||
const ms = new Date(end).getTime() - new Date(start).getTime();
|
||||
if (Number.isNaN(ms) || ms < 0) return "—";
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
return `${(ms / 1000).toFixed(1)}s`;
|
||||
}
|
||||
|
||||
const AITriggerJobs: React.FC = () => {
|
||||
const [items, setItems] = useState<TriggerJobItem[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [skipped, setSkipped] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize] = useState(20);
|
||||
|
||||
// 筛选状态
|
||||
const [eventType, setEventType] = useState<string | undefined>();
|
||||
const [status, setStatus] = useState<string | undefined>();
|
||||
const [siteId, setSiteId] = useState<number | undefined>();
|
||||
const [dateRange, setDateRange] = useState<[string, string] | null>(null);
|
||||
|
||||
// 详情 Modal
|
||||
const [detailVisible, setDetailVisible] = useState(false);
|
||||
const [detail, setDetail] = useState<TriggerJobDetailResponse | null>(null);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params: TriggerJobQuery = {
|
||||
page, page_size: pageSize,
|
||||
event_type: eventType, status, site_id: siteId,
|
||||
date_from: dateRange?.[0], date_to: dateRange?.[1],
|
||||
};
|
||||
const res = await getTriggerJobs(params);
|
||||
setItems(res.items);
|
||||
setTotal(res.total);
|
||||
setSkipped(res.today_skipped_duplicates);
|
||||
} catch {
|
||||
message.error("加载调度任务失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [page, pageSize, eventType, status, siteId, dateRange]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const handleViewDetail = async (id: number) => {
|
||||
setDetailLoading(true);
|
||||
setDetailVisible(true);
|
||||
try {
|
||||
const res = await getTriggerJobDetail(id);
|
||||
setDetail(res);
|
||||
} catch {
|
||||
message.error("加载详情失败");
|
||||
} finally {
|
||||
setDetailLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRetry = async (id: number) => {
|
||||
try {
|
||||
const res = await retryTriggerJob(id);
|
||||
message.success(`已创建重跑任务 #${res.trigger_job_id}`);
|
||||
load();
|
||||
} catch {
|
||||
message.error("重跑失败");
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnsType<TriggerJobItem> = [
|
||||
{ title: "ID", dataIndex: "id", key: "id", width: 70 },
|
||||
{ title: "事件类型", dataIndex: "event_type", key: "event_type", width: 140 },
|
||||
{ title: "会员 ID", dataIndex: "member_id", key: "member_id", width: 100, render: (v) => v ?? "—" },
|
||||
{
|
||||
title: "状态", dataIndex: "status", key: "status", width: 120,
|
||||
render: (v: string) => <Tag color={STATUS_COLOR[v] ?? "default"}>{v}</Tag>,
|
||||
},
|
||||
{ title: "执行链", dataIndex: "app_chain", key: "app_chain", ellipsis: true, render: (v) => v ?? "—" },
|
||||
{
|
||||
title: "强制执行", dataIndex: "is_forced", key: "is_forced", width: 80,
|
||||
render: (v: boolean) => v ? <Tag color="blue">是</Tag> : "否",
|
||||
},
|
||||
{
|
||||
title: "耗时", key: "duration", width: 90,
|
||||
render: (_: unknown, r: TriggerJobItem) => calcDuration(r.started_at, r.finished_at),
|
||||
},
|
||||
{ title: "创建时间", dataIndex: "created_at", key: "created_at", width: 170, render: fmtTime },
|
||||
{
|
||||
title: "操作", key: "action", width: 160, fixed: "right" as const,
|
||||
render: (_: unknown, r: TriggerJobItem) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => handleViewDetail(r.id)}>详情</Button>
|
||||
<Popconfirm title="确认手动重跑此任务?" onConfirm={() => handleRetry(r.id)}>
|
||||
<Button size="small" type="link" danger>重跑</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
|
||||
<Title level={4} style={{ margin: 0 }}>AI 调度状态</Title>
|
||||
<Button icon={<ReloadOutlined />} onClick={load} loading={loading}>刷新</Button>
|
||||
</Row>
|
||||
|
||||
{/* 筛选器行 */}
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<Space wrap>
|
||||
<Select
|
||||
allowClear placeholder="事件类型" style={{ width: 160 }}
|
||||
value={eventType} onChange={(v) => { setEventType(v); setPage(1); }}
|
||||
options={[
|
||||
{ label: "consumption", value: "consumption" },
|
||||
{ label: "note", value: "note" },
|
||||
{ label: "task_assign", value: "task_assign" },
|
||||
{ label: "coach_consumption", value: "coach_consumption" },
|
||||
{ label: "scheduled", value: "scheduled" },
|
||||
]}
|
||||
/>
|
||||
<Select
|
||||
allowClear placeholder="状态" style={{ width: 140 }}
|
||||
value={status} onChange={(v) => { setStatus(v); setPage(1); }}
|
||||
options={[
|
||||
{ label: "pending", value: "pending" },
|
||||
{ label: "running", value: "running" },
|
||||
{ label: "success", value: "success" },
|
||||
{ label: "failed", value: "failed" },
|
||||
{ label: "skipped_duplicate", value: "skipped_duplicate" },
|
||||
]}
|
||||
/>
|
||||
<Select
|
||||
allowClear placeholder="门店" style={{ width: 180 }}
|
||||
value={siteId} onChange={(v) => { setSiteId(v); setPage(1); }}
|
||||
options={[{ label: "默认门店", value: 2790685415443269 }]}
|
||||
/>
|
||||
<RangePicker
|
||||
onChange={(_, dateStrings) => {
|
||||
setDateRange(dateStrings[0] ? [dateStrings[0], dateStrings[1]] : null);
|
||||
setPage(1);
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
{/* 统计行 */}
|
||||
<Row style={{ marginBottom: 16 }}>
|
||||
<Col>
|
||||
<Statistic title="今日去重跳过数" value={skipped} />
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* 主体表格 */}
|
||||
<Table<TriggerJobItem>
|
||||
columns={columns}
|
||||
dataSource={items}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
scroll={{ x: 1100 }}
|
||||
pagination={{
|
||||
current: page, pageSize, total,
|
||||
onChange: (p) => setPage(p),
|
||||
showTotal: (t) => `共 ${t} 条`,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 详情 Modal */}
|
||||
<Modal
|
||||
title={`调度任务详情 #${detail?.id ?? ""}`}
|
||||
open={detailVisible}
|
||||
onCancel={() => { setDetailVisible(false); setDetail(null); }}
|
||||
footer={null} width={640}
|
||||
loading={detailLoading}
|
||||
>
|
||||
{detail && (
|
||||
<Descriptions column={2} bordered size="small">
|
||||
<Descriptions.Item label="事件类型">{detail.event_type}</Descriptions.Item>
|
||||
<Descriptions.Item label="状态">
|
||||
<Tag color={STATUS_COLOR[detail.status] ?? "default"}>{detail.status}</Tag>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="会员 ID">{detail.member_id ?? "—"}</Descriptions.Item>
|
||||
<Descriptions.Item label="门店 ID">{detail.site_id}</Descriptions.Item>
|
||||
<Descriptions.Item label="执行链">{detail.app_chain ?? "—"}</Descriptions.Item>
|
||||
<Descriptions.Item label="连接器">{detail.connector_type}</Descriptions.Item>
|
||||
<Descriptions.Item label="强制执行">{detail.is_forced ? "是" : "否"}</Descriptions.Item>
|
||||
<Descriptions.Item label="耗时">{calcDuration(detail.started_at, detail.finished_at)}</Descriptions.Item>
|
||||
<Descriptions.Item label="创建时间" span={2}>{fmtTime(detail.created_at)}</Descriptions.Item>
|
||||
{detail.error_message && (
|
||||
<Descriptions.Item label="错误信息" span={2}>
|
||||
<pre style={{ margin: 0, whiteSpace: "pre-wrap", maxHeight: 200, overflow: "auto" }}>
|
||||
{detail.error_message}
|
||||
</pre>
|
||||
</Descriptions.Item>
|
||||
)}
|
||||
{detail.payload && (
|
||||
<Descriptions.Item label="Payload" span={2}>
|
||||
<pre style={{ margin: 0, whiteSpace: "pre-wrap", maxHeight: 200, overflow: "auto" }}>
|
||||
{JSON.stringify(detail.payload, null, 2)}
|
||||
</pre>
|
||||
</Descriptions.Item>
|
||||
)}
|
||||
</Descriptions>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AITriggerJobs;
|
||||
380
apps/admin-web/src/pages/Dashboard.tsx
Normal file
380
apps/admin-web/src/pages/Dashboard.tsx
Normal file
@@ -0,0 +1,380 @@
|
||||
/**
|
||||
* 运行状态仪表盘(Dashboard)
|
||||
*
|
||||
* 登录后默认首页,聚合 4 个区块:
|
||||
* 1. OpsPanel 子组件(系统资源、服务状态、Git 状态)
|
||||
* 2. 数据库健康监控(DbHealthCard)
|
||||
* 3. AI 运行总览(复用 AIDashboard)
|
||||
* 4. AI 调度摘要(今日触发数、成功率、最近错误 + 跳转链接)
|
||||
*
|
||||
* 跳转链接:
|
||||
* - "ETL 状态详情" → /etl-tasks?tab=status
|
||||
* - "触发器详情" → /triggers?tab=all
|
||||
* - "AI 调度详情" → /triggers?tab=ai
|
||||
*
|
||||
* _Requirements: 2.1, 2.2, 2.6, 2.7, 2.8, 7.1, 7.2_
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import {
|
||||
Typography,
|
||||
Spin,
|
||||
message,
|
||||
Modal,
|
||||
Card,
|
||||
Row,
|
||||
Col,
|
||||
Statistic,
|
||||
Tag,
|
||||
Button,
|
||||
Space,
|
||||
Divider,
|
||||
List,
|
||||
} from "antd";
|
||||
import {
|
||||
DashboardOutlined,
|
||||
ReloadOutlined,
|
||||
RightOutlined,
|
||||
CloseCircleOutlined,
|
||||
ThunderboltOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import type { SystemInfo, ServiceStatus, GitInfo } from "../api/opsPanel";
|
||||
import {
|
||||
fetchSystemInfo,
|
||||
fetchServicesStatus,
|
||||
fetchGitInfo,
|
||||
startService,
|
||||
stopService,
|
||||
restartService,
|
||||
gitPull,
|
||||
syncDeps,
|
||||
} from "../api/opsPanel";
|
||||
import {
|
||||
SystemResourceSection,
|
||||
ServiceStatusSection,
|
||||
GitStatusSection,
|
||||
} from "../components/ops";
|
||||
import { fetchDbHealth } from "../api/dbHealth";
|
||||
import type { DbHealthItem } from "../api/dbHealth";
|
||||
import DbHealthCard from "../components/DbHealthCard";
|
||||
import AIDashboard from "./AIDashboard";
|
||||
import { getTriggerJobs, type TriggerJobItem } from "../api/adminAI";
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
|
||||
/* 超时阈值(毫秒) */
|
||||
const DB_HEALTH_TIMEOUT = 10_000;
|
||||
|
||||
const Dashboard: React.FC = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
// ---- OpsPanel 数据 ----
|
||||
const [system, setSystem] = useState<SystemInfo | null>(null);
|
||||
const [services, setServices] = useState<ServiceStatus[]>([]);
|
||||
const [gitInfos, setGitInfos] = useState<GitInfo[]>([]);
|
||||
const [opsLoading, setOpsLoading] = useState(true);
|
||||
const [actionLoading, setActionLoading] = useState<Record<string, boolean>>({});
|
||||
|
||||
// ---- DB 健康数据 ----
|
||||
const [dbItems, setDbItems] = useState<DbHealthItem[]>([]);
|
||||
const [dbLoading, setDbLoading] = useState(true);
|
||||
const [dbTimeout, setDbTimeout] = useState(false);
|
||||
|
||||
// ---- AI 调度摘要 ----
|
||||
const [triggerItems, setTriggerItems] = useState<TriggerJobItem[]>([]);
|
||||
const [triggerTotal, setTriggerTotal] = useState(0);
|
||||
const [triggerLoading, setTriggerLoading] = useState(true);
|
||||
|
||||
// ---- OpsPanel 数据加载(复用 OpsPanel.tsx 逻辑) ----
|
||||
|
||||
const loadOps = useCallback(async () => {
|
||||
try {
|
||||
const [sys, svc, git] = await Promise.all([
|
||||
fetchSystemInfo(),
|
||||
fetchServicesStatus(),
|
||||
fetchGitInfo(),
|
||||
]);
|
||||
setSystem(sys);
|
||||
setServices(svc);
|
||||
setGitInfos(git);
|
||||
} catch {
|
||||
message.error("加载运维数据失败");
|
||||
} finally {
|
||||
setOpsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// ---- DB 健康加载 ----
|
||||
|
||||
const loadDbHealth = useCallback(async () => {
|
||||
setDbLoading(true);
|
||||
setDbTimeout(false);
|
||||
const timer = setTimeout(() => {
|
||||
setDbTimeout(true);
|
||||
setDbLoading(false);
|
||||
}, DB_HEALTH_TIMEOUT);
|
||||
try {
|
||||
const items = await fetchDbHealth();
|
||||
clearTimeout(timer);
|
||||
setDbItems(items);
|
||||
setDbTimeout(false);
|
||||
} catch {
|
||||
clearTimeout(timer);
|
||||
message.error("加载数据库健康数据失败");
|
||||
} finally {
|
||||
setDbLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// ---- AI 调度摘要加载 ----
|
||||
|
||||
const loadTriggerSummary = useCallback(async () => {
|
||||
setTriggerLoading(true);
|
||||
try {
|
||||
const res = await getTriggerJobs({ page: 1, page_size: 50 });
|
||||
setTriggerItems(res.items);
|
||||
setTriggerTotal(res.total);
|
||||
} catch {
|
||||
message.error("加载 AI 调度数据失败");
|
||||
} finally {
|
||||
setTriggerLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// ---- 初始化 + 定时刷新 ----
|
||||
|
||||
useEffect(() => {
|
||||
loadOps();
|
||||
loadDbHealth();
|
||||
loadTriggerSummary();
|
||||
const timer = setInterval(loadOps, 15_000);
|
||||
return () => clearInterval(timer);
|
||||
}, [loadOps, loadDbHealth, loadTriggerSummary]);
|
||||
|
||||
// ---- OpsPanel 操作处理(复用 OpsPanel.tsx 逻辑) ----
|
||||
|
||||
const withAction = async (key: string, fn: () => Promise<void>) => {
|
||||
setActionLoading((prev) => ({ ...prev, [key]: true }));
|
||||
try {
|
||||
await fn();
|
||||
} finally {
|
||||
setActionLoading((prev) => ({ ...prev, [key]: false }));
|
||||
}
|
||||
};
|
||||
|
||||
const handleStart = (env: string) =>
|
||||
withAction(`start-${env}`, async () => {
|
||||
const r = await startService(env);
|
||||
r.success ? message.success(r.message) : message.warning(r.message);
|
||||
await loadOps();
|
||||
});
|
||||
|
||||
const handleStop = (env: string) =>
|
||||
withAction(`stop-${env}`, async () => {
|
||||
const r = await stopService(env);
|
||||
r.success ? message.success(r.message) : message.warning(r.message);
|
||||
await loadOps();
|
||||
});
|
||||
|
||||
const handleRestart = (env: string) =>
|
||||
withAction(`restart-${env}`, async () => {
|
||||
const r = await restartService(env);
|
||||
r.success ? message.success(r.message) : message.warning(r.message);
|
||||
await loadOps();
|
||||
});
|
||||
|
||||
const handlePull = (env: string) =>
|
||||
withAction(`pull-${env}`, async () => {
|
||||
const r = await gitPull(env);
|
||||
if (r.success) {
|
||||
message.success("拉取成功");
|
||||
Modal.info({
|
||||
title: `Git Pull - ${env}`,
|
||||
content: (
|
||||
<pre style={{ maxHeight: 300, overflow: "auto", fontSize: 12 }}>
|
||||
{r.output}
|
||||
</pre>
|
||||
),
|
||||
width: 600,
|
||||
});
|
||||
} else {
|
||||
message.error("拉取失败");
|
||||
Modal.error({
|
||||
title: `Git Pull 失败 - ${env}`,
|
||||
content: (
|
||||
<pre style={{ maxHeight: 300, overflow: "auto", fontSize: 12 }}>
|
||||
{r.output}
|
||||
</pre>
|
||||
),
|
||||
width: 600,
|
||||
});
|
||||
}
|
||||
await loadOps();
|
||||
});
|
||||
|
||||
const handleSyncDeps = (env: string) =>
|
||||
withAction(`sync-${env}`, async () => {
|
||||
const r = await syncDeps(env);
|
||||
r.success ? message.success("依赖同步完成") : message.error(r.message);
|
||||
});
|
||||
|
||||
// ---- AI 调度摘要计算 ----
|
||||
|
||||
const todayStr = new Date().toISOString().slice(0, 10);
|
||||
const todayJobs = triggerItems.filter(
|
||||
(j) => j.created_at && j.created_at.startsWith(todayStr),
|
||||
);
|
||||
const todayCount = todayJobs.length;
|
||||
const todaySuccess = todayJobs.filter((j) => j.status === "success").length;
|
||||
const todaySuccessRate =
|
||||
todayCount > 0 ? ((todaySuccess / todayCount) * 100).toFixed(1) : "0.0";
|
||||
const recentErrors = triggerItems
|
||||
.filter((j) => j.status === "failed")
|
||||
.slice(0, 5);
|
||||
|
||||
// ---- 渲染 ----
|
||||
|
||||
if (opsLoading) {
|
||||
return (
|
||||
<Spin
|
||||
size="large"
|
||||
style={{ display: "flex", justifyContent: "center", marginTop: 120 }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* 页面标题 + 快捷跳转 */}
|
||||
<Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
|
||||
<Title level={4} style={{ margin: 0 }}>
|
||||
<DashboardOutlined style={{ marginRight: 8 }} />
|
||||
运行状态
|
||||
</Title>
|
||||
<Space>
|
||||
<Button size="small" onClick={() => navigate("/etl-tasks?tab=status")}>
|
||||
ETL 状态详情 <RightOutlined />
|
||||
</Button>
|
||||
<Button size="small" onClick={() => navigate("/triggers?tab=all")}>
|
||||
触发器详情 <RightOutlined />
|
||||
</Button>
|
||||
<Button size="small" onClick={() => navigate("/triggers?tab=ai")}>
|
||||
AI 调度详情 <RightOutlined />
|
||||
</Button>
|
||||
</Space>
|
||||
</Row>
|
||||
|
||||
{/* 区块 1:OpsPanel 子组件 */}
|
||||
{system && <SystemResourceSection system={system} />}
|
||||
|
||||
<ServiceStatusSection
|
||||
services={services}
|
||||
actionLoading={actionLoading}
|
||||
onStart={handleStart}
|
||||
onStop={handleStop}
|
||||
onRestart={handleRestart}
|
||||
/>
|
||||
|
||||
<GitStatusSection
|
||||
gitInfos={gitInfos}
|
||||
services={services}
|
||||
actionLoading={actionLoading}
|
||||
onPull={handlePull}
|
||||
onSyncDeps={handleSyncDeps}
|
||||
/>
|
||||
|
||||
{/* 区块 2:数据库健康监控 */}
|
||||
<DbHealthCard
|
||||
items={dbItems}
|
||||
loading={dbLoading}
|
||||
timeout={dbTimeout}
|
||||
onRetry={loadDbHealth}
|
||||
/>
|
||||
|
||||
{/* 区块 3:AI 运行总览(复用 AIDashboard) */}
|
||||
<Divider orientation="left">AI 运行总览</Divider>
|
||||
<AIDashboard />
|
||||
|
||||
{/* 区块 4:AI 调度摘要 */}
|
||||
<Divider orientation="left">AI 调度摘要</Divider>
|
||||
<Card
|
||||
size="small"
|
||||
title={
|
||||
<Space>
|
||||
<ThunderboltOutlined />
|
||||
<span>AI 调度摘要</span>
|
||||
</Space>
|
||||
}
|
||||
extra={
|
||||
<Button
|
||||
size="small"
|
||||
icon={<ReloadOutlined />}
|
||||
onClick={loadTriggerSummary}
|
||||
loading={triggerLoading}
|
||||
>
|
||||
刷新
|
||||
</Button>
|
||||
}
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
{/* 统计卡片行 */}
|
||||
<Row gutter={16} style={{ marginBottom: 16 }}>
|
||||
<Col span={8}>
|
||||
<Statistic title="今日触发数" value={todayCount} />
|
||||
</Col>
|
||||
<Col span={8}>
|
||||
<Statistic title="今日成功率" value={todaySuccessRate} suffix="%" />
|
||||
</Col>
|
||||
<Col span={8}>
|
||||
<Statistic
|
||||
title="总记录数"
|
||||
value={triggerTotal}
|
||||
valueStyle={{ fontSize: 16 }}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* 最近错误列表 */}
|
||||
<Card type="inner" size="small" title="最近错误" style={{ marginBottom: 12 }}>
|
||||
{recentErrors.length === 0 ? (
|
||||
<Text type="secondary">暂无失败记录</Text>
|
||||
) : (
|
||||
<List
|
||||
size="small"
|
||||
dataSource={recentErrors}
|
||||
renderItem={(item) => (
|
||||
<List.Item>
|
||||
<Space>
|
||||
<CloseCircleOutlined style={{ color: "#ff4d4f" }} />
|
||||
<Tag color="error">{item.status}</Tag>
|
||||
<Text>{item.event_type}</Text>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
ID: {item.id}
|
||||
</Text>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{item.created_at
|
||||
? new Date(item.created_at).toLocaleString("zh-CN")
|
||||
: "—"}
|
||||
</Text>
|
||||
</Space>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* 跳转链接 */}
|
||||
<Button
|
||||
type="link"
|
||||
onClick={() => navigate("/triggers?tab=ai")}
|
||||
style={{ padding: 0 }}
|
||||
>
|
||||
查看 AI 调度详情 <RightOutlined />
|
||||
</Button>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Dashboard;
|
||||
760
apps/admin-web/src/pages/DevTrace.tsx
Normal file
760
apps/admin-web/src/pages/DevTrace.tsx
Normal file
@@ -0,0 +1,760 @@
|
||||
/**
|
||||
* 开发调试全链路日志页面。
|
||||
*
|
||||
* - 顶部:覆盖率状态栏 + 筛选栏
|
||||
* - 左侧:请求列表(Table,分页)
|
||||
* - 右侧:选中请求的 span 链路树
|
||||
* - 设置面板:Drawer(日志开关、保留天数、清理等)
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import {
|
||||
Table, Tag, Alert, Button, Select, Input, InputNumber,
|
||||
Checkbox, DatePicker, TimePicker, Space, Typography, Row, Col,
|
||||
Drawer, Switch, message, Spin, Tooltip, Divider, Progress,
|
||||
} from "antd";
|
||||
import {
|
||||
SettingOutlined, ReloadOutlined, SearchOutlined,
|
||||
DeleteOutlined, ScanOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
import dayjs from "dayjs";
|
||||
import {
|
||||
fetchDates, fetchRequests, fetchRequestDetail,
|
||||
fetchCoverage, triggerCoverageScan,
|
||||
fetchSettings, updateSettings, cleanupLogs,
|
||||
} from "../api/devTrace";
|
||||
import type {
|
||||
TraceRequest, TraceDetail, TraceSpan, TraceSettings,
|
||||
TraceFilter, TraceCoverage, SpanType, TraceType, CoverageCategory,
|
||||
} from "../types/devTrace";
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
|
||||
// ---- 常量 ----
|
||||
|
||||
const SPAN_TYPE_OPTIONS: SpanType[] = [
|
||||
"HTTP_IN", "AUTH", "ROUTE", "SERVICE",
|
||||
"DB_QUERY", "DB_CONN", "DB_CONN_RELEASE",
|
||||
"HTTP_OUT", "ERROR", "DB_ERROR",
|
||||
"MIDDLEWARE", "MIDDLEWARE_ERROR",
|
||||
"SSE_START", "SSE_EVENT", "SSE_END",
|
||||
"AI_CALL", "AI_STREAM", "AI_ERROR",
|
||||
"WS_CONNECT", "WS_MESSAGE", "WS_DISCONNECT",
|
||||
"JOB_START", "JOB_END", "JOB_ERROR",
|
||||
];
|
||||
|
||||
const TRACE_TYPE_OPTIONS: { label: string; value: TraceType }[] = [
|
||||
{ label: "HTTP", value: "http" },
|
||||
{ label: "SSE", value: "sse" },
|
||||
{ label: "WebSocket", value: "ws" },
|
||||
{ label: "Job", value: "job" },
|
||||
];
|
||||
|
||||
const METHOD_OPTIONS = ["GET", "POST", "PUT", "DELETE", "PATCH"];
|
||||
|
||||
/** span_type → 颜色映射 */
|
||||
const SPAN_COLOR: Record<string, string> = {
|
||||
HTTP_IN: "#1890ff", HTTP_OUT: "#1890ff",
|
||||
AUTH: "#fa8c16",
|
||||
ROUTE: "#1890ff",
|
||||
SERVICE: "#52c41a",
|
||||
DB_QUERY: "#722ed1", DB_CONN: "#722ed1", DB_CONN_RELEASE: "#722ed1",
|
||||
DB_ERROR: "#f5222d",
|
||||
ERROR: "#f5222d",
|
||||
MIDDLEWARE: "#8c8c8c", MIDDLEWARE_ERROR: "#f5222d",
|
||||
SSE_START: "#13c2c2", SSE_EVENT: "#13c2c2", SSE_END: "#13c2c2",
|
||||
AI_CALL: "#2f54eb", AI_STREAM: "#2f54eb", AI_ERROR: "#f5222d",
|
||||
WS_CONNECT: "#faad14", WS_MESSAGE: "#faad14", WS_DISCONNECT: "#faad14",
|
||||
JOB_START: "#8c8c8c", JOB_END: "#8c8c8c", JOB_ERROR: "#f5222d",
|
||||
};
|
||||
|
||||
const ERROR_SPAN_TYPES = new Set(["ERROR", "DB_ERROR", "MIDDLEWARE_ERROR", "AI_ERROR", "JOB_ERROR"]);
|
||||
|
||||
// ---- 辅助函数 ----
|
||||
|
||||
function fmtTime(raw: string | null | undefined): string {
|
||||
if (!raw) return "—";
|
||||
const d = new Date(raw);
|
||||
return Number.isNaN(d.getTime()) ? raw : d.toLocaleString("zh-CN");
|
||||
}
|
||||
|
||||
function fmtDuration(ms: number): string {
|
||||
if (ms < 1000) return `${ms.toFixed(0)}ms`;
|
||||
return `${(ms / 1000).toFixed(2)}s`;
|
||||
}
|
||||
|
||||
function coveragePct(cat: CoverageCategory): number {
|
||||
return cat.total === 0 ? 100 : Math.round((cat.covered / cat.total) * 100);
|
||||
}
|
||||
|
||||
// ---- 覆盖率状态栏 ----
|
||||
|
||||
const CoverageBar: React.FC<{
|
||||
coverage: TraceCoverage | null;
|
||||
loading: boolean;
|
||||
onScan: () => void;
|
||||
}> = ({ coverage, loading, onScan }) => {
|
||||
if (!coverage) {
|
||||
return (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
style={{ marginBottom: 12 }}
|
||||
message={
|
||||
<Row align="middle" gutter={16}>
|
||||
<Col>
|
||||
<Text strong>Trace 覆盖率</Text>
|
||||
</Col>
|
||||
<Col>
|
||||
<Text type="secondary">暂无扫描数据</Text>
|
||||
</Col>
|
||||
<Col>
|
||||
<Button
|
||||
size="small" icon={<ScanOutlined />}
|
||||
loading={loading} onClick={onScan}
|
||||
>
|
||||
扫描
|
||||
</Button>
|
||||
</Col>
|
||||
</Row>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const dims: { label: string; cat: CoverageCategory }[] = [
|
||||
{ label: "路由", cat: coverage.routes },
|
||||
{ label: "Service", cat: coverage.services },
|
||||
{ label: "Job", cat: coverage.jobs },
|
||||
{ label: "SSE", cat: coverage.sse_endpoints },
|
||||
{ label: "WS", cat: coverage.ws_endpoints },
|
||||
];
|
||||
|
||||
const allUncovered = dims.flatMap((d) =>
|
||||
d.cat.uncovered.map((name) => `${d.label}: ${name}`),
|
||||
);
|
||||
|
||||
return (
|
||||
<Alert
|
||||
type={allUncovered.length === 0 ? "success" : "warning"}
|
||||
showIcon
|
||||
style={{ marginBottom: 12 }}
|
||||
message={
|
||||
<Row align="middle" gutter={16}>
|
||||
<Col>
|
||||
<Text strong>Trace 覆盖率</Text>
|
||||
</Col>
|
||||
{dims.map((d) => (
|
||||
<Col key={d.label}>
|
||||
<Space size={4}>
|
||||
<Text type="secondary">{d.label}</Text>
|
||||
<Progress
|
||||
type="circle" size={28}
|
||||
percent={coveragePct(d.cat)}
|
||||
format={(p) => `${p}%`}
|
||||
/>
|
||||
</Space>
|
||||
</Col>
|
||||
))}
|
||||
<Col>
|
||||
<Button
|
||||
size="small" icon={<ScanOutlined />}
|
||||
loading={loading} onClick={onScan}
|
||||
>
|
||||
扫描
|
||||
</Button>
|
||||
</Col>
|
||||
</Row>
|
||||
}
|
||||
description={
|
||||
allUncovered.length > 0 ? (
|
||||
<div style={{ marginTop: 4 }}>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
未覆盖:{allUncovered.join("、")}
|
||||
</Text>
|
||||
</div>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
// ---- Span 链路树 ----
|
||||
|
||||
const SpanTree: React.FC<{ detail: TraceDetail | null; loading: boolean }> = ({ detail, loading }) => {
|
||||
if (loading) return <Spin style={{ display: "block", marginTop: 40, textAlign: "center" }} />;
|
||||
if (!detail) {
|
||||
return <Text type="secondary" style={{ display: "block", textAlign: "center", marginTop: 40 }}>点击左侧请求查看链路详情</Text>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ padding: "0 8px" }}>
|
||||
<div style={{ marginBottom: 8 }}>
|
||||
<Text strong>{detail.method} {detail.path}</Text>
|
||||
<Tag color={detail.error ? "red" : "green"} style={{ marginLeft: 8 }}>
|
||||
{detail.status_code ?? "—"}
|
||||
</Tag>
|
||||
<Text type="secondary" style={{ marginLeft: 8 }}>{fmtDuration(detail.total_duration_ms)}</Text>
|
||||
</div>
|
||||
<Divider style={{ margin: "8px 0" }} />
|
||||
{detail.spans.map((span, idx) => (
|
||||
<SpanRow key={idx} span={span} index={idx} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const SpanRow: React.FC<{ span: TraceSpan; index: number }> = ({ span, index }) => {
|
||||
const isError = ERROR_SPAN_TYPES.has(span.span_type);
|
||||
const color = SPAN_COLOR[span.span_type] ?? "#8c8c8c";
|
||||
const isDbQuery = span.span_type === "DB_QUERY";
|
||||
|
||||
// 根据 span 类型决定缩进层级
|
||||
const indent = getSpanIndent(span.span_type);
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
marginLeft: indent * 16,
|
||||
padding: "4px 8px",
|
||||
marginBottom: 2,
|
||||
borderLeft: `3px solid ${color}`,
|
||||
background: isError ? "#fff2f0" : index % 2 === 0 ? "#fafafa" : "#fff",
|
||||
borderRadius: 2,
|
||||
fontSize: 13,
|
||||
}}
|
||||
>
|
||||
<Row justify="space-between" align="top">
|
||||
<Col flex="auto">
|
||||
<Tag color={color} style={{ fontSize: 11, lineHeight: "18px" }}>
|
||||
{span.span_type}
|
||||
</Tag>
|
||||
<Text style={{ color: isError ? "#f5222d" : undefined }}>
|
||||
{span.description_zh || `${span.module}.${span.function}`}
|
||||
</Text>
|
||||
</Col>
|
||||
<Col flex="none">
|
||||
<Text type="secondary" style={{ fontSize: 12, whiteSpace: "nowrap" }}>
|
||||
{fmtDuration(span.duration_ms)}
|
||||
</Text>
|
||||
</Col>
|
||||
</Row>
|
||||
{/* DB_QUERY / DB_ERROR:展示 SQL 详情 */}
|
||||
{(isDbQuery || span.span_type === "DB_ERROR") && !!span.extra?.sql && (
|
||||
<div style={{ margin: "4px 0 0", fontSize: 11 }}>
|
||||
<pre style={{
|
||||
margin: 0, padding: "4px 8px",
|
||||
background: span.span_type === "DB_ERROR" ? "#fff1f0" : "#f0f5ff",
|
||||
border: `1px solid ${span.span_type === "DB_ERROR" ? "#ffa39e" : "#adc6ff"}`,
|
||||
borderRadius: 2,
|
||||
whiteSpace: "pre-wrap", wordBreak: "break-all",
|
||||
maxHeight: 200, overflow: "auto",
|
||||
fontFamily: "'Cascadia Code', 'Fira Code', Consolas, monospace",
|
||||
}}>
|
||||
{String(span.extra.sql)}
|
||||
</pre>
|
||||
{/* 绑定参数 */}
|
||||
{span.extra.params != null && (
|
||||
<div style={{ marginTop: 2, color: "#8c8c8c" }}>
|
||||
<span style={{ color: "#722ed1" }}>参数:</span>
|
||||
{JSON.stringify(span.extra.params)}
|
||||
</div>
|
||||
)}
|
||||
{/* 行数 + 调用来源 */}
|
||||
<div style={{ marginTop: 2, color: "#8c8c8c", display: "flex", gap: 12 }}>
|
||||
{span.extra.row_count != null && (
|
||||
<span><span style={{ color: "#1890ff" }}>行数:</span>{String(span.extra.row_count)}</span>
|
||||
)}
|
||||
{span.extra.caller != null && (
|
||||
<span><span style={{ color: "#52c41a" }}>来源:</span>{String(span.extra.caller)}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* 通用 params 展示(非 DB_QUERY/DB_ERROR,且 params 非空) */}
|
||||
{!isDbQuery && span.span_type !== "DB_ERROR" && span.params && Object.keys(span.params).length > 0 && (
|
||||
<div style={{ marginTop: 4, fontSize: 11, color: "#8c8c8c" }}>
|
||||
<span style={{ color: "#722ed1" }}>参数:</span>
|
||||
<span style={{ fontFamily: "'Cascadia Code', 'Fira Code', Consolas, monospace" }}>
|
||||
{JSON.stringify(span.params, null, 0)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{/* ERROR:展示错误信息 */}
|
||||
{isError && span.result_summary && (
|
||||
<div style={{ marginTop: 4, color: "#f5222d", fontSize: 12 }}>
|
||||
{span.result_summary}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
/** 根据 span_type 返回缩进层级(模拟层级关系) */
|
||||
function getSpanIndent(spanType: SpanType): number {
|
||||
switch (spanType) {
|
||||
case "HTTP_IN": case "HTTP_OUT": return 0;
|
||||
case "MIDDLEWARE": case "MIDDLEWARE_ERROR": return 1;
|
||||
case "AUTH": return 1;
|
||||
case "ROUTE": return 1;
|
||||
case "SERVICE": return 2;
|
||||
case "DB_QUERY": case "DB_CONN": case "DB_CONN_RELEASE": case "DB_ERROR": return 3;
|
||||
case "SSE_START": case "SSE_END": return 1;
|
||||
case "SSE_EVENT": case "AI_CALL": case "AI_STREAM": case "AI_ERROR": return 2;
|
||||
case "WS_CONNECT": case "WS_DISCONNECT": return 1;
|
||||
case "WS_MESSAGE": return 2;
|
||||
case "JOB_START": case "JOB_END": case "JOB_ERROR": return 0;
|
||||
case "ERROR": return 1;
|
||||
default: return 1;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 设置面板(Task 20) ----
|
||||
|
||||
const SettingsDrawer: React.FC<{
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}> = ({ open, onClose }) => {
|
||||
const [settings, setSettings] = useState<TraceSettings | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [cleanRange, setCleanRange] = useState<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);
|
||||
const [cleaning, setCleaning] = useState(false);
|
||||
|
||||
const loadSettings = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetchSettings();
|
||||
setSettings(res);
|
||||
} catch {
|
||||
message.error("加载设置失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) loadSettings();
|
||||
}, [open, loadSettings]);
|
||||
|
||||
const handleToggle = async (field: keyof TraceSettings, value: boolean) => {
|
||||
try {
|
||||
const res = await updateSettings({ [field]: value });
|
||||
setSettings(res);
|
||||
message.success("设置已更新");
|
||||
} catch {
|
||||
message.error("更新失败");
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveRetention = async () => {
|
||||
if (!settings) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await updateSettings({ retention_days: settings.retention_days });
|
||||
setSettings(res);
|
||||
message.success("保留天数已更新");
|
||||
} catch {
|
||||
message.error("更新失败");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCleanup = async () => {
|
||||
if (!cleanRange) { message.warning("请选择日期范围"); return; }
|
||||
setCleaning(true);
|
||||
try {
|
||||
const res = await cleanupLogs(
|
||||
cleanRange[0].format("YYYY-MM-DD"),
|
||||
cleanRange[1].format("YYYY-MM-DD"),
|
||||
);
|
||||
message.success(`已清理 ${res.deleted_files} 个文件(${res.deleted_dates.length} 天)`);
|
||||
} catch {
|
||||
message.error("清理失败");
|
||||
} finally {
|
||||
setCleaning(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
title="Trace 设置" open={open} onClose={onClose}
|
||||
width={400} destroyOnClose
|
||||
>
|
||||
{loading ? <Spin /> : settings && (
|
||||
<div>
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<Text strong>日志开关</Text>
|
||||
<Switch
|
||||
checked={settings.enabled}
|
||||
onChange={(v) => handleToggle("enabled", v)}
|
||||
style={{ marginLeft: 12 }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<Text strong>记录 SQL</Text>
|
||||
<Switch
|
||||
checked={settings.log_sql}
|
||||
onChange={(v) => handleToggle("log_sql", v)}
|
||||
style={{ marginLeft: 12 }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<Text strong>记录参数</Text>
|
||||
<Switch
|
||||
checked={settings.log_params}
|
||||
onChange={(v) => handleToggle("log_params", v)}
|
||||
style={{ marginLeft: 12 }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Divider />
|
||||
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<Text strong>保留天数</Text>
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<Space>
|
||||
<InputNumber
|
||||
min={1} max={365}
|
||||
value={settings.retention_days}
|
||||
onChange={(v) => v && setSettings({ ...settings, retention_days: v })}
|
||||
/>
|
||||
<Button type="primary" size="small" loading={saving} onClick={handleSaveRetention}>
|
||||
保存
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<Text strong>日志目录</Text>
|
||||
<div style={{ marginTop: 4 }}>
|
||||
<Text type="secondary" copyable style={{ fontSize: 12 }}>{settings.log_dir}</Text>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Divider />
|
||||
|
||||
<div>
|
||||
<Text strong>手动清理</Text>
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<Space direction="vertical" style={{ width: "100%" }}>
|
||||
<DatePicker.RangePicker
|
||||
style={{ width: "100%" }}
|
||||
value={cleanRange}
|
||||
onChange={(v) => setCleanRange(v as [dayjs.Dayjs, dayjs.Dayjs] | null)}
|
||||
/>
|
||||
<Button
|
||||
danger icon={<DeleteOutlined />}
|
||||
loading={cleaning} onClick={handleCleanup}
|
||||
block
|
||||
>
|
||||
清理选定范围
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Drawer>
|
||||
);
|
||||
};
|
||||
|
||||
// ---- 请求列表列定义 ----
|
||||
|
||||
const requestColumns: ColumnsType<TraceRequest> = [
|
||||
{
|
||||
title: "时间", dataIndex: "timestamp", key: "timestamp", width: 170,
|
||||
render: fmtTime,
|
||||
},
|
||||
{
|
||||
title: "类型", dataIndex: "trace_type", key: "trace_type", width: 70,
|
||||
render: (v: TraceType) => {
|
||||
const colors: Record<TraceType, string> = { http: "blue", sse: "cyan", ws: "gold", job: "default" };
|
||||
return <Tag color={colors[v]}>{v.toUpperCase()}</Tag>;
|
||||
},
|
||||
},
|
||||
{ title: "方法", dataIndex: "method", key: "method", width: 70 },
|
||||
{
|
||||
title: "路径", dataIndex: "path", key: "path", ellipsis: true,
|
||||
render: (v: string) => <Tooltip title={v}>{v}</Tooltip>,
|
||||
},
|
||||
{
|
||||
title: "状态", dataIndex: "status_code", key: "status_code", width: 60,
|
||||
render: (v: number | null) => {
|
||||
if (v == null) return "—";
|
||||
const color = v >= 400 ? "red" : v >= 300 ? "orange" : "green";
|
||||
return <Tag color={color}>{v}</Tag>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "耗时", dataIndex: "total_duration_ms", key: "duration", width: 90,
|
||||
render: fmtDuration,
|
||||
sorter: (a, b) => a.total_duration_ms - b.total_duration_ms,
|
||||
},
|
||||
{
|
||||
title: "DB", dataIndex: "db_query_count", key: "db", width: 50,
|
||||
render: (v: number) => v > 0 ? <Text type="secondary">{v}</Text> : "—",
|
||||
},
|
||||
{
|
||||
title: "错误", dataIndex: "error", key: "error", width: 60,
|
||||
render: (v: string | null) => v ? <Tag color="red">有</Tag> : null,
|
||||
},
|
||||
];
|
||||
|
||||
// ---- 主页面组件 ----
|
||||
|
||||
const DevTrace: React.FC = () => {
|
||||
// 数据状态
|
||||
const [dates, setDates] = useState<string[]>([]);
|
||||
const [requests, setRequests] = useState<TraceRequest[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [detail, setDetail] = useState<TraceDetail | null>(null);
|
||||
const [coverage, setCoverage] = useState<TraceCoverage | null>(null);
|
||||
|
||||
// 加载状态
|
||||
const [listLoading, setListLoading] = useState(false);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
const [coverageLoading, setCoverageLoading] = useState(false);
|
||||
|
||||
// 筛选状态
|
||||
const [filter, setFilter] = useState<TraceFilter>({
|
||||
date: dayjs().format("YYYY-MM-DD"),
|
||||
page: 1,
|
||||
page_size: 30,
|
||||
});
|
||||
|
||||
// UI 状态
|
||||
const [selectedRowKey, setSelectedRowKey] = useState<string | null>(null);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [hiddenIds, setHiddenIds] = useState<Set<string>>(new Set());
|
||||
|
||||
// 加载日期列表
|
||||
const loadDates = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetchDates();
|
||||
setDates(res.dates);
|
||||
} catch {
|
||||
// 静默降级
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 加载请求列表
|
||||
const loadRequests = useCallback(async () => {
|
||||
setListLoading(true);
|
||||
try {
|
||||
const res = await fetchRequests(filter);
|
||||
setRequests(res.items);
|
||||
setTotal(res.total);
|
||||
} catch {
|
||||
message.error("加载请求列表失败");
|
||||
} finally {
|
||||
setListLoading(false);
|
||||
}
|
||||
}, [filter]);
|
||||
|
||||
// 加载覆盖率
|
||||
const loadCoverage = useCallback(async () => {
|
||||
setCoverageLoading(true);
|
||||
try {
|
||||
const res = await fetchCoverage();
|
||||
setCoverage(res);
|
||||
} catch {
|
||||
message.warning("覆盖率数据加载失败,可点击扫描按钮重试");
|
||||
} finally {
|
||||
setCoverageLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 手动扫描覆盖率
|
||||
const handleScan = async () => {
|
||||
setCoverageLoading(true);
|
||||
try {
|
||||
const res = await triggerCoverageScan();
|
||||
setCoverage(res);
|
||||
message.success("覆盖率扫描完成");
|
||||
} catch {
|
||||
message.error("扫描失败");
|
||||
} finally {
|
||||
setCoverageLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 点击行查看详情
|
||||
const handleRowClick = async (record: TraceRequest) => {
|
||||
setSelectedRowKey(record.request_id);
|
||||
setDetailLoading(true);
|
||||
try {
|
||||
const res = await fetchRequestDetail(record.request_id);
|
||||
setDetail(res);
|
||||
} catch {
|
||||
message.error("加载详情失败");
|
||||
} finally {
|
||||
setDetailLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 初始化
|
||||
useEffect(() => { loadDates(); loadCoverage(); }, [loadDates, loadCoverage]);
|
||||
useEffect(() => { loadRequests(); }, [loadRequests]);
|
||||
|
||||
// 筛选变更辅助
|
||||
const updateFilter = (patch: Partial<TraceFilter>) => {
|
||||
setFilter((prev) => ({ ...prev, ...patch, page: 1 }));
|
||||
};
|
||||
|
||||
// 过滤掉被屏蔽的记录
|
||||
const visibleRequests = requests.filter((r) => !hiddenIds.has(r.request_id));
|
||||
|
||||
// 清空:把当前可见记录全部加入屏蔽集合(累积)
|
||||
const handleClearList = () => {
|
||||
setHiddenIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
for (const r of requests) next.add(r.request_id);
|
||||
return next;
|
||||
});
|
||||
setDetail(null);
|
||||
setSelectedRowKey(null);
|
||||
};
|
||||
|
||||
// 取消清空:清空屏蔽集合
|
||||
const handleUnclearList = () => {
|
||||
setHiddenIds(new Set());
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* 标题栏 */}
|
||||
<Row justify="space-between" align="middle" style={{ marginBottom: 12 }}>
|
||||
<Title level={4} style={{ margin: 0 }}>开发调试日志</Title>
|
||||
<Space>
|
||||
<Button icon={<DeleteOutlined />} onClick={handleClearList} disabled={visibleRequests.length === 0}>
|
||||
清空
|
||||
</Button>
|
||||
{hiddenIds.size > 0 && (
|
||||
<Button onClick={handleUnclearList}>
|
||||
取消清空({hiddenIds.size})
|
||||
</Button>
|
||||
)}
|
||||
<Button icon={<ReloadOutlined />} onClick={() => { loadRequests(); loadCoverage(); }} loading={listLoading}>
|
||||
刷新
|
||||
</Button>
|
||||
<Button icon={<SettingOutlined />} onClick={() => setSettingsOpen(true)}>
|
||||
设置
|
||||
</Button>
|
||||
</Space>
|
||||
</Row>
|
||||
|
||||
{/* 覆盖率状态栏 */}
|
||||
<CoverageBar coverage={coverage} loading={coverageLoading} onScan={handleScan} />
|
||||
|
||||
{/* 筛选栏 */}
|
||||
<div style={{ marginBottom: 12, background: "#fafafa", padding: "10px 12px", borderRadius: 4 }}>
|
||||
<Space wrap size={[8, 8]}>
|
||||
<Select
|
||||
placeholder="日期" style={{ width: 130 }}
|
||||
value={filter.date}
|
||||
onChange={(v) => updateFilter({ date: v })}
|
||||
options={dates.map((d) => ({ label: d, value: d }))}
|
||||
showSearch
|
||||
/>
|
||||
<TimePicker.RangePicker
|
||||
format="HH:mm"
|
||||
placeholder={["开始时间", "结束时间"]}
|
||||
onChange={(_, strs) => updateFilter({
|
||||
start_time: strs[0] || undefined,
|
||||
end_time: strs[1] || undefined,
|
||||
})}
|
||||
/>
|
||||
<Select
|
||||
placeholder="类型" style={{ width: 100 }} allowClear
|
||||
options={TRACE_TYPE_OPTIONS}
|
||||
onChange={(v) => updateFilter({ trace_type: v })}
|
||||
/>
|
||||
<Select
|
||||
placeholder="方法" style={{ width: 100 }} allowClear
|
||||
options={METHOD_OPTIONS.map((m) => ({ label: m, value: m }))}
|
||||
onChange={(v) => updateFilter({ method: v })}
|
||||
/>
|
||||
<Input
|
||||
placeholder="路径关键词" style={{ width: 160 }}
|
||||
prefix={<SearchOutlined />} allowClear
|
||||
onPressEnter={(e) => updateFilter({ path_contains: (e.target as HTMLInputElement).value || undefined })}
|
||||
onBlur={(e) => updateFilter({ path_contains: e.target.value || undefined })}
|
||||
/>
|
||||
<InputNumber
|
||||
placeholder="状态码" style={{ width: 90 }}
|
||||
min={100} max={599}
|
||||
onChange={(v) => updateFilter({ status_code: v ?? undefined })}
|
||||
/>
|
||||
<InputNumber
|
||||
placeholder="最小耗时(ms)" style={{ width: 130 }}
|
||||
min={0}
|
||||
onChange={(v) => updateFilter({ min_duration: v ?? undefined })}
|
||||
/>
|
||||
<Checkbox
|
||||
onChange={(e) => updateFilter({ has_error: e.target.checked || undefined })}
|
||||
>
|
||||
仅错误
|
||||
</Checkbox>
|
||||
<Select
|
||||
placeholder="Span 类型" style={{ width: 150 }} allowClear
|
||||
options={SPAN_TYPE_OPTIONS.map((s) => ({ label: s, value: s }))}
|
||||
onChange={(v) => updateFilter({ span_type: v })}
|
||||
/>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
{/* 左右分栏 */}
|
||||
<Row gutter={12} style={{ minHeight: 500 }}>
|
||||
{/* 左侧:请求列表 */}
|
||||
<Col span={14}>
|
||||
<Table<TraceRequest>
|
||||
columns={requestColumns}
|
||||
dataSource={visibleRequests}
|
||||
rowKey="request_id"
|
||||
size="small"
|
||||
loading={listLoading}
|
||||
pagination={{
|
||||
current: filter.page,
|
||||
pageSize: filter.page_size,
|
||||
total,
|
||||
showSizeChanger: true,
|
||||
pageSizeOptions: ["20", "30", "50", "100"],
|
||||
showTotal: (t) => `共 ${t} 条`,
|
||||
onChange: (page, pageSize) => setFilter((prev) => ({ ...prev, page, page_size: pageSize })),
|
||||
}}
|
||||
onRow={(record) => ({
|
||||
onClick: () => handleRowClick(record),
|
||||
style: {
|
||||
cursor: "pointer",
|
||||
background: record.request_id === selectedRowKey ? "#e6f7ff" : undefined,
|
||||
},
|
||||
})}
|
||||
scroll={{ y: 520 }}
|
||||
/>
|
||||
</Col>
|
||||
|
||||
{/* 右侧:Span 链路树 */}
|
||||
<Col span={10}>
|
||||
<div style={{
|
||||
border: "1px solid #f0f0f0", borderRadius: 4,
|
||||
padding: 12, minHeight: 520, maxHeight: 600,
|
||||
overflow: "auto", background: "#fff",
|
||||
}}>
|
||||
<SpanTree detail={detail} loading={detailLoading} />
|
||||
</div>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
{/* 设置面板 */}
|
||||
<SettingsDrawer open={settingsOpen} onClose={() => setSettingsOpen(false)} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DevTrace;
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
type CursorInfo, type RecentRun,
|
||||
} from '../api/etlStatus';
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
const { Title } = Typography;
|
||||
|
||||
const STATUS_COLOR: Record<string, string> = {
|
||||
success: 'green', failed: 'red', running: 'blue', cancelled: 'orange',
|
||||
@@ -38,11 +38,8 @@ function formatDuration(ms: number | null): string {
|
||||
|
||||
const cursorColumns: ColumnsType<CursorInfo> = [
|
||||
{ title: '任务编码', dataIndex: 'task_code', key: 'task_code', render: (v: string) => <code>{v}</code> },
|
||||
{ title: '最后抓取时间', dataIndex: 'last_fetch_time', key: 'last_fetch_time', render: (v: string | null) => formatTime(v) },
|
||||
{
|
||||
title: '记录数', dataIndex: 'record_count', key: 'record_count', align: 'right',
|
||||
render: (v: number | null) => (v != null ? <Text strong>{v.toLocaleString()}</Text> : '—'),
|
||||
},
|
||||
{ title: '数据起始时间', dataIndex: 'last_start', key: 'last_start', render: (v: string | null) => formatTime(v) },
|
||||
{ title: '数据截止时间', dataIndex: 'last_end', key: 'last_end', render: (v: string | null) => formatTime(v) },
|
||||
];
|
||||
|
||||
const runColumns: ColumnsType<RecentRun> = [
|
||||
|
||||
121
apps/admin-web/src/pages/ETLTasks.tsx
Normal file
121
apps/admin-web/src/pages/ETLTasks.tsx
Normal file
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* ETL 任务管理页面 — 合并 TaskConfig / QueueTab / ScheduleTab / ETLStatus 为 Tab 视图。
|
||||
*
|
||||
* - 5 个 Tab:config(发起)、queue(队列)、schedule(调度)、history(历史)、status(状态)
|
||||
* - Tab 切换通过 useSearchParams 同步 URL 查询参数 ?tab=config|queue|schedule|history|status
|
||||
* - destroyInactiveTabPane={false} 保持 Tab 状态不丢失
|
||||
*
|
||||
* CHANGE 2026-07-14 | Task 9.1:从占位页面替换为完整 Tab 视图实现
|
||||
* CHANGE 2026-03-25 | 将 TaskManager 内部子 Tab(队列/调度)提升到顶层,去掉历史 Tab
|
||||
*/
|
||||
|
||||
import React, { useMemo } from 'react';
|
||||
import { Tabs, Typography } from 'antd';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import {
|
||||
SettingOutlined,
|
||||
UnorderedListOutlined,
|
||||
ClockCircleOutlined,
|
||||
HistoryOutlined,
|
||||
DashboardOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import TaskConfig from './TaskConfig';
|
||||
import { QueueTab, HistoryTab } from './TaskManager';
|
||||
import ScheduleTab from '../components/ScheduleTab';
|
||||
import ETLStatus from './ETLStatus';
|
||||
|
||||
const { Title } = Typography;
|
||||
|
||||
const VALID_TABS = ['config', 'queue', 'schedule', 'history', 'status'] as const;
|
||||
type TabKey = (typeof VALID_TABS)[number];
|
||||
const DEFAULT_TAB: TabKey = 'config';
|
||||
|
||||
function isValidTab(value: string | null): value is TabKey {
|
||||
return value != null && (VALID_TABS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
const ETLTasks: React.FC = () => {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const activeTab: TabKey = useMemo(() => {
|
||||
const raw = searchParams.get('tab');
|
||||
return isValidTab(raw) ? raw : DEFAULT_TAB;
|
||||
}, [searchParams]);
|
||||
|
||||
const handleTabChange = (key: string) => {
|
||||
setSearchParams({ tab: key }, { replace: true });
|
||||
};
|
||||
|
||||
const items = useMemo(
|
||||
() => [
|
||||
{
|
||||
key: 'config' as TabKey,
|
||||
label: (
|
||||
<span>
|
||||
<SettingOutlined style={{ marginRight: 6 }} />
|
||||
发起
|
||||
</span>
|
||||
),
|
||||
children: <TaskConfig />,
|
||||
},
|
||||
{
|
||||
key: 'queue' as TabKey,
|
||||
label: (
|
||||
<span>
|
||||
<UnorderedListOutlined style={{ marginRight: 6 }} />
|
||||
队列
|
||||
</span>
|
||||
),
|
||||
children: <QueueTab />,
|
||||
},
|
||||
{
|
||||
key: 'schedule' as TabKey,
|
||||
label: (
|
||||
<span>
|
||||
<ClockCircleOutlined style={{ marginRight: 6 }} />
|
||||
调度
|
||||
</span>
|
||||
),
|
||||
children: <ScheduleTab />,
|
||||
},
|
||||
{
|
||||
key: 'history' as TabKey,
|
||||
label: (
|
||||
<span>
|
||||
<HistoryOutlined style={{ marginRight: 6 }} />
|
||||
历史
|
||||
</span>
|
||||
),
|
||||
children: <HistoryTab />,
|
||||
},
|
||||
{
|
||||
key: 'status' as TabKey,
|
||||
label: (
|
||||
<span>
|
||||
<DashboardOutlined style={{ marginRight: 6 }} />
|
||||
状态
|
||||
</span>
|
||||
),
|
||||
children: <ETLStatus />,
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Title level={4} style={{ marginBottom: 16 }}>
|
||||
<UnorderedListOutlined style={{ marginRight: 8 }} />
|
||||
ETL 任务管理
|
||||
</Title>
|
||||
<Tabs
|
||||
activeKey={activeTab}
|
||||
onChange={handleTabChange}
|
||||
items={items}
|
||||
destroyInactiveTabPane={false}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ETLTasks;
|
||||
@@ -25,7 +25,7 @@ const Login: React.FC = () => {
|
||||
try {
|
||||
await login(values.username, values.password);
|
||||
message.success("登录成功");
|
||||
navigate("/", { replace: true });
|
||||
navigate("/dashboard", { replace: true });
|
||||
} catch (err: unknown) {
|
||||
const detail =
|
||||
(err as { response?: { data?: { detail?: string } } })?.response?.data
|
||||
|
||||
@@ -6,43 +6,16 @@
|
||||
* - 各环境服务状态 + 启停重启按钮
|
||||
* - 各环境 Git 状态 + pull / 同步依赖按钮
|
||||
* - 各环境 .env 配置查看(敏感值脱敏)
|
||||
*
|
||||
* CHANGE 2026-07-25 | admin-web-restructure 8.1
|
||||
* 拆分为 SystemResourceSection / ServiceStatusSection / GitStatusSection 三个子组件,
|
||||
* 本页面改为组合子组件,功能不变。
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import {
|
||||
Card,
|
||||
Row,
|
||||
Col,
|
||||
Tag,
|
||||
Button,
|
||||
Space,
|
||||
Statistic,
|
||||
Progress,
|
||||
Modal,
|
||||
message,
|
||||
Descriptions,
|
||||
Spin,
|
||||
Tooltip,
|
||||
Typography,
|
||||
Input,
|
||||
} from "antd";
|
||||
import {
|
||||
PlayCircleOutlined,
|
||||
PauseCircleOutlined,
|
||||
ReloadOutlined,
|
||||
CloudDownloadOutlined,
|
||||
SyncOutlined,
|
||||
FileTextOutlined,
|
||||
CheckCircleOutlined,
|
||||
CloseCircleOutlined,
|
||||
ClockCircleOutlined,
|
||||
DesktopOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import type {
|
||||
SystemInfo,
|
||||
ServiceStatus,
|
||||
GitInfo,
|
||||
} from "../api/opsPanel";
|
||||
import { Modal, message, Spin, Typography } from "antd";
|
||||
import { DesktopOutlined } from "@ant-design/icons";
|
||||
import type { SystemInfo, ServiceStatus, GitInfo } from "../api/opsPanel";
|
||||
import {
|
||||
fetchSystemInfo,
|
||||
fetchServicesStatus,
|
||||
@@ -52,28 +25,14 @@ import {
|
||||
restartService,
|
||||
gitPull,
|
||||
syncDeps,
|
||||
fetchEnvFile,
|
||||
} from "../api/opsPanel";
|
||||
import {
|
||||
SystemResourceSection,
|
||||
ServiceStatusSection,
|
||||
GitStatusSection,
|
||||
} from "../components/ops";
|
||||
|
||||
const { Text, Title } = Typography;
|
||||
const { TextArea } = Input;
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 工具函数 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** 秒数格式化为 "Xd Xh Xm" */
|
||||
function formatUptime(seconds: number | null): string {
|
||||
if (seconds == null) return "-";
|
||||
const d = Math.floor(seconds / 86400);
|
||||
const h = Math.floor((seconds % 86400) / 3600);
|
||||
const m = Math.floor((seconds % 3600) / 60);
|
||||
const parts: string[] = [];
|
||||
if (d > 0) parts.push(`${d}天`);
|
||||
if (h > 0) parts.push(`${h}时`);
|
||||
parts.push(`${m}分`);
|
||||
return parts.join(" ");
|
||||
}
|
||||
const { Title } = Typography;
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* 组件 */
|
||||
@@ -85,9 +44,6 @@ const OpsPanel: React.FC = () => {
|
||||
const [gitInfos, setGitInfos] = useState<GitInfo[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [actionLoading, setActionLoading] = useState<Record<string, boolean>>({});
|
||||
const [envModalOpen, setEnvModalOpen] = useState(false);
|
||||
const [envModalContent, setEnvModalContent] = useState("");
|
||||
const [envModalTitle, setEnvModalTitle] = useState("");
|
||||
|
||||
// ---- 数据加载 ----
|
||||
|
||||
@@ -165,17 +121,6 @@ const OpsPanel: React.FC = () => {
|
||||
r.success ? message.success("依赖同步完成") : message.error(r.message);
|
||||
});
|
||||
|
||||
const handleViewEnv = async (env: string, label: string) => {
|
||||
try {
|
||||
const r = await fetchEnvFile(env);
|
||||
setEnvModalTitle(`${label} .env 配置`);
|
||||
setEnvModalContent(r.content);
|
||||
setEnvModalOpen(true);
|
||||
} catch {
|
||||
message.error("读取配置文件失败");
|
||||
}
|
||||
};
|
||||
|
||||
// ---- 渲染 ----
|
||||
|
||||
if (loading) {
|
||||
@@ -189,175 +134,23 @@ const OpsPanel: React.FC = () => {
|
||||
运维控制面板
|
||||
</Title>
|
||||
|
||||
{/* ---- 系统资源 ---- */}
|
||||
{system && (
|
||||
<Card size="small" title="服务器资源" style={{ marginBottom: 16 }}>
|
||||
<Row gutter={24}>
|
||||
<Col span={8}>
|
||||
<Statistic title="CPU 使用率" value={system.cpu_percent} suffix="%" />
|
||||
<Progress percent={system.cpu_percent} size="small" status={system.cpu_percent > 80 ? "exception" : "normal"} showInfo={false} />
|
||||
</Col>
|
||||
<Col span={8}>
|
||||
<Statistic title="内存" value={system.memory_used_gb} suffix={`/ ${system.memory_total_gb} GB`} precision={1} />
|
||||
<Progress percent={system.memory_percent} size="small" status={system.memory_percent > 85 ? "exception" : "normal"} showInfo={false} />
|
||||
</Col>
|
||||
<Col span={8}>
|
||||
<Statistic title="磁盘" value={system.disk_used_gb} suffix={`/ ${system.disk_total_gb} GB`} precision={1} />
|
||||
<Progress percent={system.disk_percent} size="small" status={system.disk_percent > 90 ? "exception" : "normal"} showInfo={false} />
|
||||
</Col>
|
||||
</Row>
|
||||
<Text type="secondary" style={{ fontSize: 12, marginTop: 8, display: "block" }}>
|
||||
开机时间:{new Date(system.boot_time).toLocaleString()}
|
||||
</Text>
|
||||
</Card>
|
||||
)}
|
||||
{system && <SystemResourceSection system={system} />}
|
||||
|
||||
{/* ---- 服务状态 ---- */}
|
||||
<Card size="small" title="服务状态" style={{ marginBottom: 16 }}>
|
||||
<Row gutter={16}>
|
||||
{services.map((svc) => (
|
||||
<Col span={12} key={svc.env}>
|
||||
<Card
|
||||
size="small"
|
||||
type="inner"
|
||||
title={
|
||||
<Space>
|
||||
{svc.running
|
||||
? <CheckCircleOutlined style={{ color: "#52c41a" }} />
|
||||
: <CloseCircleOutlined style={{ color: "#ff4d4f" }} />}
|
||||
{svc.label}
|
||||
<Tag color={svc.running ? "success" : "error"}>
|
||||
{svc.running ? "运行中" : "已停止"}
|
||||
</Tag>
|
||||
</Space>
|
||||
}
|
||||
extra={<Tag>:{svc.port}</Tag>}
|
||||
>
|
||||
{svc.running && (
|
||||
<Descriptions size="small" column={3} style={{ marginBottom: 12 }}>
|
||||
<Descriptions.Item label="PID">{svc.pid}</Descriptions.Item>
|
||||
<Descriptions.Item label="运行时长">
|
||||
<ClockCircleOutlined style={{ marginRight: 4 }} />
|
||||
{formatUptime(svc.uptime_seconds)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="内存">{svc.memory_mb ?? "-"} MB</Descriptions.Item>
|
||||
</Descriptions>
|
||||
)}
|
||||
<Space>
|
||||
{!svc.running && (
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
icon={<PlayCircleOutlined />}
|
||||
loading={actionLoading[`start-${svc.env}`]}
|
||||
onClick={() => handleStart(svc.env)}
|
||||
>
|
||||
启动
|
||||
</Button>
|
||||
)}
|
||||
{svc.running && (
|
||||
<>
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
icon={<PauseCircleOutlined />}
|
||||
loading={actionLoading[`stop-${svc.env}`]}
|
||||
onClick={() => handleStop(svc.env)}
|
||||
>
|
||||
停止
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<ReloadOutlined />}
|
||||
loading={actionLoading[`restart-${svc.env}`]}
|
||||
onClick={() => handleRestart(svc.env)}
|
||||
>
|
||||
重启
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
</Card>
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
</Card>
|
||||
<ServiceStatusSection
|
||||
services={services}
|
||||
actionLoading={actionLoading}
|
||||
onStart={handleStart}
|
||||
onStop={handleStop}
|
||||
onRestart={handleRestart}
|
||||
/>
|
||||
|
||||
{/* ---- Git 状态 & 配置 ---- */}
|
||||
<Card size="small" title="代码与配置" style={{ marginBottom: 16 }}>
|
||||
<Row gutter={16}>
|
||||
{gitInfos.map((git) => {
|
||||
const envCfg = services.find((s) => s.env === git.env);
|
||||
const label = envCfg?.label ?? git.env;
|
||||
return (
|
||||
<Col span={12} key={git.env}>
|
||||
<Card size="small" type="inner" title={label}>
|
||||
<Descriptions size="small" column={1} style={{ marginBottom: 12 }}>
|
||||
<Descriptions.Item label="分支">
|
||||
<Tag color="blue">{git.branch}</Tag>
|
||||
{git.has_local_changes && (
|
||||
<Tooltip title="工作区有未提交的变更">
|
||||
<Tag color="warning">有变更</Tag>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="最新提交">
|
||||
<Text code style={{ fontSize: 12 }}>{git.last_commit_hash}</Text>
|
||||
<Text type="secondary" style={{ marginLeft: 8, fontSize: 12 }}>
|
||||
{git.last_commit_message}
|
||||
</Text>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="提交时间">
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>{git.last_commit_time}</Text>
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<Space>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<CloudDownloadOutlined />}
|
||||
loading={actionLoading[`pull-${git.env}`]}
|
||||
onClick={() => handlePull(git.env)}
|
||||
>
|
||||
Git Pull
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<SyncOutlined />}
|
||||
loading={actionLoading[`sync-${git.env}`]}
|
||||
onClick={() => handleSyncDeps(git.env)}
|
||||
>
|
||||
同步依赖
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<FileTextOutlined />}
|
||||
onClick={() => handleViewEnv(git.env, label)}
|
||||
>
|
||||
查看配置
|
||||
</Button>
|
||||
</Space>
|
||||
</Card>
|
||||
</Col>
|
||||
);
|
||||
})}
|
||||
</Row>
|
||||
</Card>
|
||||
|
||||
{/* ---- 配置查看弹窗 ---- */}
|
||||
<Modal
|
||||
title={envModalTitle}
|
||||
open={envModalOpen}
|
||||
onCancel={() => setEnvModalOpen(false)}
|
||||
footer={null}
|
||||
width={700}
|
||||
>
|
||||
<TextArea
|
||||
value={envModalContent}
|
||||
readOnly
|
||||
autoSize={{ minRows: 10, maxRows: 30 }}
|
||||
style={{ fontFamily: "monospace", fontSize: 12 }}
|
||||
/>
|
||||
</Modal>
|
||||
<GitStatusSection
|
||||
gitInfos={gitInfos}
|
||||
services={services}
|
||||
actionLoading={actionLoading}
|
||||
onPull={handlePull}
|
||||
onSyncDeps={handleSyncDeps}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
293
apps/admin-web/src/pages/PendingReview.tsx
Normal file
293
apps/admin-web/src/pages/PendingReview.tsx
Normal file
@@ -0,0 +1,293 @@
|
||||
/**
|
||||
* P18 待审核任务页面。
|
||||
*
|
||||
* 展示 status='pending_review' 的任务,支持重新分配和关闭操作。
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import {
|
||||
Table, Card, Typography, Button, Space, InputNumber, Tag, Tooltip,
|
||||
Modal, Input, Drawer, message,
|
||||
} from "antd";
|
||||
import {
|
||||
ReloadOutlined, ExclamationCircleOutlined, AuditOutlined,
|
||||
SwapOutlined, CloseCircleOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
import dayjs from "dayjs";
|
||||
import {
|
||||
fetchPendingReviews, reassignTask, closeTask,
|
||||
fetchMemberTransferHistory,
|
||||
type PendingReviewItem, type PendingReviewQuery, type TransferLogItem,
|
||||
} from "../api/taskEngine";
|
||||
import { useAuthStore } from "../store/authStore";
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
const { TextArea } = Input;
|
||||
|
||||
function formatTime(raw: string | null): string {
|
||||
if (!raw) return "—";
|
||||
return dayjs(raw).format("YYYY-MM-DD HH:mm");
|
||||
}
|
||||
|
||||
const PendingReview: React.FC = () => {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const isSuperAdmin = user?.roles?.includes("super_admin") ?? false;
|
||||
|
||||
const [items, setItems] = useState<PendingReviewItem[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [query, setQuery] = useState<PendingReviewQuery>({ page: 1, page_size: 20 });
|
||||
|
||||
// 重新分配弹窗
|
||||
const [reassignVisible, setReassignVisible] = useState(false);
|
||||
const [reassignTaskId, setReassignTaskId] = useState<number | null>(null);
|
||||
const [toAssistantId, setToAssistantId] = useState<number | null>(null);
|
||||
const [reassigning, setReassigning] = useState(false);
|
||||
|
||||
// 关闭弹窗
|
||||
const [closeVisible, setCloseVisible] = useState(false);
|
||||
const [closeTaskId, setCloseTaskId] = useState<number | null>(null);
|
||||
const [closeReason, setCloseReason] = useState("");
|
||||
const [closing, setClosing] = useState(false);
|
||||
|
||||
// 转移历史抽屉
|
||||
const [historyVisible, setHistoryVisible] = useState(false);
|
||||
const [historyMemberId, setHistoryMemberId] = useState<number | null>(null);
|
||||
const [historyItems, setHistoryItems] = useState<TransferLogItem[]>([]);
|
||||
const [historyLoading, setHistoryLoading] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await fetchPendingReviews(query);
|
||||
setItems(data.items);
|
||||
setTotal(data.total);
|
||||
} catch {
|
||||
message.error("加载待审核任务失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [query]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const handleReassign = async () => {
|
||||
if (!reassignTaskId || !toAssistantId) return;
|
||||
setReassigning(true);
|
||||
try {
|
||||
await reassignTask(reassignTaskId, toAssistantId);
|
||||
message.success("重新分配成功");
|
||||
setReassignVisible(false);
|
||||
setToAssistantId(null);
|
||||
load();
|
||||
} catch {
|
||||
message.error("重新分配失败");
|
||||
} finally {
|
||||
setReassigning(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = async () => {
|
||||
if (!closeTaskId || !closeReason.trim()) return;
|
||||
setClosing(true);
|
||||
try {
|
||||
await closeTask(closeTaskId, closeReason.trim());
|
||||
message.success("任务已关闭");
|
||||
setCloseVisible(false);
|
||||
setCloseReason("");
|
||||
load();
|
||||
} catch {
|
||||
message.error("关闭任务失败");
|
||||
} finally {
|
||||
setClosing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const showHistory = async (memberId: number) => {
|
||||
setHistoryMemberId(memberId);
|
||||
setHistoryVisible(true);
|
||||
setHistoryLoading(true);
|
||||
try {
|
||||
const data = await fetchMemberTransferHistory(memberId);
|
||||
setHistoryItems(data);
|
||||
} catch {
|
||||
message.error("加载转移历史失败");
|
||||
} finally {
|
||||
setHistoryLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnsType<PendingReviewItem> = [
|
||||
{
|
||||
title: "创建时间", dataIndex: "created_at", key: "created_at", width: 160,
|
||||
render: (v: string) => formatTime(v),
|
||||
},
|
||||
{
|
||||
title: "门店", dataIndex: "site_name", key: "site_name", width: 120,
|
||||
render: (v: string, r) => v || `#${r.site_id}`,
|
||||
},
|
||||
{
|
||||
title: "客户", key: "member", width: 140,
|
||||
render: (_: unknown, r) => (
|
||||
<Tooltip title={`ID: ${r.member_id}`}>
|
||||
<a onClick={() => showHistory(r.member_id)}>
|
||||
{r.member_name || `会员#${r.member_id}`}
|
||||
</a>
|
||||
</Tooltip>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "当前助教", key: "assistant", width: 120,
|
||||
render: (_: unknown, r) => r.assistant_name || `#${r.assistant_id}`,
|
||||
},
|
||||
{
|
||||
title: "任务类型", dataIndex: "task_type_label", key: "type", width: 120,
|
||||
render: (v: string) => <Tag color="blue">{v || "未知"}</Tag>,
|
||||
},
|
||||
{
|
||||
title: "转移次数", dataIndex: "transfer_count", key: "tc", width: 90,
|
||||
render: (v: number) => (
|
||||
<Tag color={v >= 2 ? "red" : "default"} icon={v >= 2 ? <ExclamationCircleOutlined /> : undefined}>
|
||||
{v}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "优先级分", dataIndex: "priority_score", key: "score", width: 90,
|
||||
render: (v: number | null) => v != null ? v.toFixed(2) : "—",
|
||||
},
|
||||
];
|
||||
|
||||
// 超级管理员才显示操作列
|
||||
if (isSuperAdmin) {
|
||||
columns.push({
|
||||
title: "操作", key: "action", width: 180, fixed: "right",
|
||||
render: (_: unknown, r) => (
|
||||
<Space size={4}>
|
||||
<Button
|
||||
type="primary" size="small" icon={<SwapOutlined />}
|
||||
onClick={() => { setReassignTaskId(r.id); setReassignVisible(true); }}
|
||||
>
|
||||
分配
|
||||
</Button>
|
||||
<Button
|
||||
danger size="small" icon={<CloseCircleOutlined />}
|
||||
onClick={() => { setCloseTaskId(r.id); setCloseVisible(true); }}
|
||||
>
|
||||
关闭
|
||||
</Button>
|
||||
</Space>
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
|
||||
<Title level={4} style={{ margin: 0 }}>
|
||||
<AuditOutlined style={{ marginRight: 8 }} />
|
||||
待审核任务
|
||||
</Title>
|
||||
<Button icon={<ReloadOutlined />} onClick={load} loading={loading}>刷新</Button>
|
||||
</div>
|
||||
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<Space wrap>
|
||||
<InputNumber
|
||||
placeholder="门店 ID"
|
||||
style={{ width: 140 }}
|
||||
onChange={(v) => setQuery((q) => ({ ...q, site_id: (v as number) ?? undefined, page: 1 }))}
|
||||
/>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
<Card size="small">
|
||||
<Table<PendingReviewItem>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={items}
|
||||
loading={loading}
|
||||
size="small"
|
||||
scroll={{ x: 1100 }}
|
||||
pagination={{
|
||||
current: query.page,
|
||||
pageSize: query.page_size,
|
||||
total,
|
||||
showSizeChanger: true,
|
||||
showTotal: (t) => `共 ${t} 条`,
|
||||
onChange: (page, pageSize) => setQuery((q) => ({ ...q, page, page_size: pageSize })),
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* 重新分配弹窗 */}
|
||||
<Modal
|
||||
title="重新分配任务"
|
||||
open={reassignVisible}
|
||||
onOk={handleReassign}
|
||||
onCancel={() => { setReassignVisible(false); setToAssistantId(null); }}
|
||||
confirmLoading={reassigning}
|
||||
okButtonProps={{ disabled: !toAssistantId }}
|
||||
>
|
||||
<Text>请输入目标助教 ID:</Text>
|
||||
<InputNumber
|
||||
style={{ width: "100%", marginTop: 8 }}
|
||||
placeholder="目标助教 ID"
|
||||
value={toAssistantId}
|
||||
onChange={(v) => setToAssistantId(v)}
|
||||
/>
|
||||
<Text type="secondary" style={{ display: "block", marginTop: 8, fontSize: 12 }}>
|
||||
提示:POOL 为空时无法自动推荐候选助教。如需强制指定,操作将标记为 manual_override。
|
||||
</Text>
|
||||
</Modal>
|
||||
|
||||
{/* 关闭任务弹窗 */}
|
||||
<Modal
|
||||
title="关闭任务"
|
||||
open={closeVisible}
|
||||
onOk={handleClose}
|
||||
onCancel={() => { setCloseVisible(false); setCloseReason(""); }}
|
||||
confirmLoading={closing}
|
||||
okButtonProps={{ disabled: !closeReason.trim(), danger: true }}
|
||||
okText="确认关闭"
|
||||
>
|
||||
<Text>请填写关闭原因:</Text>
|
||||
<TextArea
|
||||
rows={3}
|
||||
maxLength={500}
|
||||
showCount
|
||||
style={{ marginTop: 8 }}
|
||||
value={closeReason}
|
||||
onChange={(e) => setCloseReason(e.target.value)}
|
||||
placeholder="例如:客户已流失,无需继续跟进"
|
||||
/>
|
||||
</Modal>
|
||||
|
||||
{/* 转移历史抽屉 */}
|
||||
<Drawer
|
||||
title={`会员 #${historyMemberId} 转移历史`}
|
||||
open={historyVisible}
|
||||
onClose={() => setHistoryVisible(false)}
|
||||
width={600}
|
||||
>
|
||||
<Table<TransferLogItem>
|
||||
rowKey="id"
|
||||
dataSource={historyItems}
|
||||
loading={historyLoading}
|
||||
size="small"
|
||||
pagination={false}
|
||||
columns={[
|
||||
{ title: "时间", dataIndex: "created_at", render: (v: string) => formatTime(v), width: 140 },
|
||||
{ title: "原助教", key: "from", render: (_: unknown, r: TransferLogItem) => r.from_assistant_name || `#${r.from_assistant_id}`, width: 100 },
|
||||
{ title: "新助教", key: "to", render: (_: unknown, r: TransferLogItem) => r.to_assistant_name || `#${r.to_assistant_id}`, width: 100 },
|
||||
{ title: "原因", dataIndex: "transfer_reason", width: 120 },
|
||||
{ title: "得分", dataIndex: "transfer_score", render: (v: number | null) => v != null ? v.toFixed(2) : "—", width: 80 },
|
||||
]}
|
||||
/>
|
||||
</Drawer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PendingReview;
|
||||
@@ -47,7 +47,7 @@ import { useNavigate } from "react-router-dom";
|
||||
import TaskSelector from "../components/TaskSelector";
|
||||
import { validateTaskConfig, fetchFlows } from "../api/tasks";
|
||||
import type { FlowDef, ProcessingModeDef } from "../api/tasks";
|
||||
import { submitToQueue, executeDirectly } from "../api/execution";
|
||||
import { submitToQueue, executeDirectly, cleanupOutput } from "../api/execution";
|
||||
import { createSchedule } from "../api/schedules";
|
||||
import { useAuthStore } from "../store/authStore";
|
||||
import BusinessDayHint from "../components/BusinessDayHint";
|
||||
@@ -55,6 +55,7 @@ import type { RadioChangeEvent } from "antd";
|
||||
import type { Dayjs } from "dayjs";
|
||||
import dayjs from "dayjs";
|
||||
import type { TaskConfig as TaskConfigType, ScheduleConfig } from "../types";
|
||||
import type { MinRunIntervalItem } from "../types";
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
const { TextArea } = Input;
|
||||
@@ -228,6 +229,7 @@ const TaskConfig: React.FC = () => {
|
||||
/* ---------- 任务选择 ---------- */
|
||||
const [selectedTasks, setSelectedTasks] = useState<string[]>([]);
|
||||
const [selectedDwdTables, setSelectedDwdTables] = useState<string[]>([]);
|
||||
const [taskIntervals, setTaskIntervals] = useState<Record<string, MinRunIntervalItem>>({});
|
||||
|
||||
/* ---------- 高级选项 ---------- */
|
||||
const [dryRun, setDryRun] = useState(false);
|
||||
@@ -320,12 +322,26 @@ const TaskConfig: React.FC = () => {
|
||||
/* ---------- 事件处理 ---------- */
|
||||
const handleFlowChange = (e: RadioChangeEvent) => setFlow(e.target.value);
|
||||
|
||||
// CHANGE 2026-03-27 | 包含 ODS 层的 flow 执行前清理输出目录,每类任务只保留最近 10 个运行记录
|
||||
const tryCleanupOutput = async () => {
|
||||
if (!layers.includes("ODS")) return;
|
||||
try {
|
||||
const result = await cleanupOutput();
|
||||
if (result.dirs_deleted > 0) {
|
||||
message.info(`已清理 ${result.dirs_deleted} 个旧运行记录`);
|
||||
}
|
||||
} catch {
|
||||
message.warning("输出目录清理失败,不影响任务执行");
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmitToQueue = async () => {
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await tryCleanupOutput();
|
||||
await submitToQueue(buildTaskConfig());
|
||||
message.success("已提交到执行队列");
|
||||
navigate("/task-manager");
|
||||
navigate("/etl-tasks?tab=queue");
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : "提交失败";
|
||||
message.error(`提交到队列失败:${msg}`);
|
||||
@@ -334,12 +350,14 @@ const TaskConfig: React.FC = () => {
|
||||
}
|
||||
};
|
||||
|
||||
// CHANGE 2026-03-27 | 直接执行后跳转历史 tab 并自动打开任务详情
|
||||
const handleExecuteDirectly = async () => {
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await executeDirectly(buildTaskConfig());
|
||||
await tryCleanupOutput();
|
||||
const { execution_id } = await executeDirectly(buildTaskConfig());
|
||||
message.success("任务已开始执行");
|
||||
navigate("/task-manager");
|
||||
navigate(`/etl-tasks?tab=history&openExecution=${execution_id}`);
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : "执行失败";
|
||||
message.error(`直接执行失败:${msg}`);
|
||||
@@ -399,6 +417,7 @@ const TaskConfig: React.FC = () => {
|
||||
task_config: taskConfig,
|
||||
schedule_config: scheduleConfig,
|
||||
run_immediately: !!values.run_immediately,
|
||||
min_run_intervals: Object.keys(taskIntervals).length > 0 ? taskIntervals : undefined,
|
||||
});
|
||||
message.success("调度任务已创建");
|
||||
setScheduleModalOpen(false);
|
||||
@@ -681,13 +700,15 @@ const TaskConfig: React.FC = () => {
|
||||
</Card>
|
||||
|
||||
{/* ---- 任务选择(含 DWD 表过滤) ---- */}
|
||||
<Card size="small" title="任务选择" style={cardStyle}>
|
||||
<Card size="small" title={<Space size={8}>任务选择<Text type="secondary" style={{ fontSize: 11, fontWeight: 400 }}>右侧可设置每个任务的最小执行间隔</Text></Space>} style={cardStyle}>
|
||||
<TaskSelector
|
||||
layers={layers}
|
||||
selectedTasks={selectedTasks}
|
||||
onTasksChange={setSelectedTasks}
|
||||
selectedDwdTables={selectedDwdTables}
|
||||
onDwdTablesChange={setSelectedDwdTables}
|
||||
taskIntervals={taskIntervals}
|
||||
onTaskIntervalsChange={setTaskIntervals}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
|
||||
353
apps/admin-web/src/pages/TaskEngineConfig.tsx
Normal file
353
apps/admin-web/src/pages/TaskEngineConfig.tsx
Normal file
@@ -0,0 +1,353 @@
|
||||
/**
|
||||
* P18 任务引擎参数管理页面。
|
||||
*
|
||||
* 展示 biz.cfg_task_generator_params 全局默认 + 门店覆盖参数。
|
||||
* 超级管理员可编辑/新增/删除;门店管理员只读。
|
||||
* 权重参数(w_rs/w_ms/w_ml)以卡片形式整体编辑,后端联合校验。
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import {
|
||||
Table, Card, Typography, Button, Space, Tag, InputNumber,
|
||||
Modal, Select, Popconfirm, Tooltip, message,
|
||||
} from "antd";
|
||||
import {
|
||||
ReloadOutlined, SettingOutlined, PlusOutlined,
|
||||
EditOutlined, DeleteOutlined, SaveOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
import dayjs from "dayjs";
|
||||
import {
|
||||
fetchConfigParams, updateConfigParam, createConfigParam, deleteConfigParam,
|
||||
type ConfigParam,
|
||||
} from "../api/taskEngine";
|
||||
import { useAuthStore } from "../store/authStore";
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
|
||||
/** 参数中文描述映射 */
|
||||
const PARAM_LABELS: Record<string, string> = {
|
||||
high_priority_recall_threshold: "高优先召回阈值",
|
||||
priority_recall_threshold: "优先召回阈值",
|
||||
rs_min_for_relationship: "关系构建 RS 下限",
|
||||
rs_max_for_relationship: "关系构建 RS 上限",
|
||||
consecutive_recall_fail_cycles: "连续失败触发转移轮数",
|
||||
min_wbi_for_transfer: "触发转移最低 WBI",
|
||||
guard_assistant_coverage_ratio: "助教绑定率保护阈值",
|
||||
guard_new_assistant_days: "新助教入驻保护天数",
|
||||
transfer_score_w_rs: "转移排序 RS 权重",
|
||||
transfer_score_w_ms: "转移排序 MS 权重",
|
||||
transfer_score_w_ml: "转移排序 ML 权重",
|
||||
max_transfer_count: "单客户最大转移次数",
|
||||
follow_up_visit_retention_hours: "回访任务保留时长(h)",
|
||||
};
|
||||
|
||||
const WEIGHT_KEYS = ["transfer_score_w_rs", "transfer_score_w_ms", "transfer_score_w_ml"];
|
||||
|
||||
const TaskEngineConfig: React.FC = () => {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const isSuperAdmin = user?.roles?.includes("super_admin") ?? false;
|
||||
|
||||
const [params, setParams] = useState<ConfigParam[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
// 行内编辑
|
||||
const [editingId, setEditingId] = useState<number | null>(null);
|
||||
const [editValue, setEditValue] = useState<number>(0);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
// 新增弹窗
|
||||
const [addVisible, setAddVisible] = useState(false);
|
||||
const [addSiteId, setAddSiteId] = useState<number | null>(null);
|
||||
const [addKey, setAddKey] = useState<string>("");
|
||||
const [addValue, setAddValue] = useState<number>(0);
|
||||
const [adding, setAdding] = useState(false);
|
||||
|
||||
// 权重卡片编辑
|
||||
const [weightVisible, setWeightVisible] = useState(false);
|
||||
const [weightSiteId, setWeightSiteId] = useState<number | null>(null);
|
||||
const [wRs, setWRs] = useState(0.5);
|
||||
const [wMs, setWMs] = useState(0.3);
|
||||
const [wMl, setWMl] = useState(0.2);
|
||||
const [weightSaving, setWeightSaving] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await fetchConfigParams();
|
||||
setParams(data.params);
|
||||
} catch {
|
||||
message.error("加载参数配置失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (editingId == null) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await updateConfigParam(editingId, editValue);
|
||||
message.success("参数已更新");
|
||||
setEditingId(null);
|
||||
load();
|
||||
} catch (err: unknown) {
|
||||
const msg = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail;
|
||||
message.error(msg || "更新失败");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAdd = async () => {
|
||||
if (!addSiteId || !addKey) return;
|
||||
setAdding(true);
|
||||
try {
|
||||
await createConfigParam(addSiteId, addKey, addValue);
|
||||
message.success("门店覆盖参数已添加");
|
||||
setAddVisible(false);
|
||||
setAddKey("");
|
||||
setAddValue(0);
|
||||
load();
|
||||
} catch (err: unknown) {
|
||||
const msg = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail;
|
||||
message.error(msg || "添加失败");
|
||||
} finally {
|
||||
setAdding(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (paramId: number) => {
|
||||
try {
|
||||
await deleteConfigParam(paramId);
|
||||
message.success("门店覆盖已删除");
|
||||
load();
|
||||
} catch (err: unknown) {
|
||||
const msg = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail;
|
||||
message.error(msg || "删除失败");
|
||||
}
|
||||
};
|
||||
|
||||
/** 打开权重卡片编辑弹窗 */
|
||||
const openWeightEditor = (siteId: number | null) => {
|
||||
const siteParams = params.filter(
|
||||
(p) => p.site_id === siteId && WEIGHT_KEYS.includes(p.param_key),
|
||||
);
|
||||
const findVal = (key: string) => siteParams.find((p) => p.param_key === key)?.param_value ?? 0;
|
||||
setWeightSiteId(siteId);
|
||||
setWRs(findVal("transfer_score_w_rs"));
|
||||
setWMs(findVal("transfer_score_w_ms"));
|
||||
setWMl(findVal("transfer_score_w_ml"));
|
||||
setWeightVisible(true);
|
||||
};
|
||||
|
||||
const handleWeightSave = async () => {
|
||||
const sum = wRs + wMs + wMl;
|
||||
if (Math.abs(sum - 1.0) > 0.001) {
|
||||
message.error(`权重之和必须为 1.0,当前为 ${sum.toFixed(4)}`);
|
||||
return;
|
||||
}
|
||||
setWeightSaving(true);
|
||||
try {
|
||||
// 逐个更新三个权重参数
|
||||
const weightParams = params.filter(
|
||||
(p) => p.site_id === weightSiteId && WEIGHT_KEYS.includes(p.param_key),
|
||||
);
|
||||
const valMap: Record<string, number> = {
|
||||
transfer_score_w_rs: wRs,
|
||||
transfer_score_w_ms: wMs,
|
||||
transfer_score_w_ml: wMl,
|
||||
};
|
||||
for (const wp of weightParams) {
|
||||
await updateConfigParam(wp.id, valMap[wp.param_key]);
|
||||
}
|
||||
message.success("权重配置已更新");
|
||||
setWeightVisible(false);
|
||||
load();
|
||||
} catch (err: unknown) {
|
||||
const msg = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail;
|
||||
message.error(msg || "权重更新失败");
|
||||
} finally {
|
||||
setWeightSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnsType<ConfigParam> = [
|
||||
{
|
||||
title: "参数", dataIndex: "param_key", key: "param_key", width: 220,
|
||||
render: (v: string) => (
|
||||
<Tooltip title={v}>
|
||||
<Text strong>{PARAM_LABELS[v] || v}</Text>
|
||||
<br />
|
||||
<Text type="secondary" style={{ fontSize: 11 }}>{v}</Text>
|
||||
</Tooltip>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "门店", key: "site", width: 120,
|
||||
render: (_: unknown, r) => r.site_id == null
|
||||
? <Tag color="blue">全局默认</Tag>
|
||||
: <span>{r.site_name || `#${r.site_id}`}</span>,
|
||||
},
|
||||
{
|
||||
title: "参数值", key: "value", width: 160,
|
||||
render: (_: unknown, r) => {
|
||||
if (editingId === r.id) {
|
||||
return (
|
||||
<Space>
|
||||
<InputNumber
|
||||
size="small"
|
||||
value={editValue}
|
||||
onChange={(v) => v != null && setEditValue(v)}
|
||||
step={WEIGHT_KEYS.includes(r.param_key) ? 0.01 : 1}
|
||||
/>
|
||||
<Button size="small" type="primary" icon={<SaveOutlined />} loading={saving} onClick={handleSave} />
|
||||
<Button size="small" onClick={() => setEditingId(null)}>取消</Button>
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
return <Text>{r.param_value}</Text>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "说明", dataIndex: "description", key: "desc", width: 200,
|
||||
render: (v: string | null) => v || "—",
|
||||
},
|
||||
{
|
||||
title: "更新时间", dataIndex: "updated_at", key: "updated_at", width: 160,
|
||||
render: (v: string) => dayjs(v).format("YYYY-MM-DD HH:mm"),
|
||||
},
|
||||
];
|
||||
|
||||
if (isSuperAdmin) {
|
||||
columns.push({
|
||||
title: "操作", key: "action", width: 160, fixed: "right",
|
||||
render: (_: unknown, r) => {
|
||||
// 权重参数用卡片编辑
|
||||
if (WEIGHT_KEYS.includes(r.param_key)) {
|
||||
return (
|
||||
<Button
|
||||
size="small" icon={<EditOutlined />}
|
||||
onClick={() => openWeightEditor(r.site_id)}
|
||||
>
|
||||
权重编辑
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Space size={4}>
|
||||
<Button
|
||||
size="small" icon={<EditOutlined />}
|
||||
onClick={() => { setEditingId(r.id); setEditValue(r.param_value); }}
|
||||
>
|
||||
编辑
|
||||
</Button>
|
||||
{r.site_id != null && (
|
||||
<Popconfirm title="确认删除此门店覆盖?" onConfirm={() => handleDelete(r.id)}>
|
||||
<Button size="small" danger icon={<DeleteOutlined />}>删除</Button>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
|
||||
<Title level={4} style={{ margin: 0 }}>
|
||||
<SettingOutlined style={{ marginRight: 8 }} />
|
||||
任务引擎参数管理
|
||||
</Title>
|
||||
<Space>
|
||||
{isSuperAdmin && (
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={() => setAddVisible(true)}>
|
||||
新增门店覆盖
|
||||
</Button>
|
||||
)}
|
||||
<Button icon={<ReloadOutlined />} onClick={load} loading={loading}>刷新</Button>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
<Card size="small">
|
||||
<Table<ConfigParam>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={params}
|
||||
loading={loading}
|
||||
size="small"
|
||||
scroll={{ x: 1000 }}
|
||||
pagination={false}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* 新增门店覆盖弹窗 */}
|
||||
<Modal
|
||||
title="新增门店覆盖参数"
|
||||
open={addVisible}
|
||||
onOk={handleAdd}
|
||||
onCancel={() => setAddVisible(false)}
|
||||
confirmLoading={adding}
|
||||
okButtonProps={{ disabled: !addSiteId || !addKey }}
|
||||
>
|
||||
<Space direction="vertical" style={{ width: "100%" }}>
|
||||
<div>
|
||||
<Text>门店 ID:</Text>
|
||||
<InputNumber style={{ width: "100%" }} value={addSiteId} onChange={(v) => setAddSiteId(v)} />
|
||||
</div>
|
||||
<div>
|
||||
<Text>参数名:</Text>
|
||||
<Select
|
||||
style={{ width: "100%" }}
|
||||
value={addKey || undefined}
|
||||
onChange={(v) => setAddKey(v)}
|
||||
placeholder="选择参数"
|
||||
options={Object.entries(PARAM_LABELS).map(([k, label]) => ({ value: k, label: `${label} (${k})` }))}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Text>参数值:</Text>
|
||||
<InputNumber style={{ width: "100%" }} value={addValue} onChange={(v) => v != null && setAddValue(v)} />
|
||||
</div>
|
||||
</Space>
|
||||
</Modal>
|
||||
|
||||
{/* 权重卡片编辑弹窗 */}
|
||||
<Modal
|
||||
title={`权重配置${weightSiteId != null ? ` — 门店 #${weightSiteId}` : "(全局)"}`}
|
||||
open={weightVisible}
|
||||
onOk={handleWeightSave}
|
||||
onCancel={() => setWeightVisible(false)}
|
||||
confirmLoading={weightSaving}
|
||||
>
|
||||
<Text type="secondary" style={{ display: "block", marginBottom: 12 }}>
|
||||
三项权重之和必须等于 1.0(容差 0.001)
|
||||
</Text>
|
||||
<Space direction="vertical" style={{ width: "100%" }}>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
|
||||
<Text style={{ width: 120 }}>RS 权重 (w_rs):</Text>
|
||||
<InputNumber value={wRs} onChange={(v) => v != null && setWRs(v)} step={0.05} min={0} max={1} style={{ flex: 1 }} />
|
||||
</div>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
|
||||
<Text style={{ width: 120 }}>MS 权重 (w_ms):</Text>
|
||||
<InputNumber value={wMs} onChange={(v) => v != null && setWMs(v)} step={0.05} min={0} max={1} style={{ flex: 1 }} />
|
||||
</div>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
|
||||
<Text style={{ width: 120 }}>ML 权重 (w_ml):</Text>
|
||||
<InputNumber value={wMl} onChange={(v) => v != null && setWMl(v)} step={0.05} min={0} max={1} style={{ flex: 1 }} />
|
||||
</div>
|
||||
<div style={{ textAlign: "right", marginTop: 8 }}>
|
||||
<Text type={Math.abs(wRs + wMs + wMl - 1.0) > 0.001 ? "danger" : "success"}>
|
||||
当前合计:{(wRs + wMs + wMl).toFixed(4)}
|
||||
</Text>
|
||||
</div>
|
||||
</Space>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TaskEngineConfig;
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useCallback, useRef } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import {
|
||||
Tabs, Table, Tag, Button, Popconfirm, Space, message, Drawer,
|
||||
Typography, Descriptions, Empty, Spin,
|
||||
@@ -14,12 +15,12 @@ import {
|
||||
import {
|
||||
ReloadOutlined, DeleteOutlined, StopOutlined,
|
||||
UnorderedListOutlined, ClockCircleOutlined, HistoryOutlined,
|
||||
FileTextOutlined,
|
||||
FileTextOutlined, PlayCircleOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import type { QueuedTask, ExecutionLog } from '../types';
|
||||
import {
|
||||
fetchQueue, fetchHistory, deleteFromQueue, cancelExecution,
|
||||
fetchQueue, fetchHistory, deleteFromQueue, cancelExecution, rerunExecution,
|
||||
} from '../api/execution';
|
||||
import { apiClient } from '../api/client';
|
||||
import LogStream from '../components/LogStream';
|
||||
@@ -37,6 +38,7 @@ const STATUS_COLOR: Record<string, string> = {
|
||||
success: 'success',
|
||||
failed: 'error',
|
||||
cancelled: 'warning',
|
||||
interrupted: 'volcano',
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
@@ -62,7 +64,7 @@ function fmtDuration(ms: number | null | undefined): string {
|
||||
/* 队列 Tab */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const QueueTab: React.FC = () => {
|
||||
export const QueueTab: React.FC = () => {
|
||||
const [data, setData] = useState<QueuedTask[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
@@ -236,7 +238,7 @@ const QueueTab: React.FC = () => {
|
||||
/* 历史 Tab */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const HistoryTab: React.FC = () => {
|
||||
export const HistoryTab: React.FC = () => {
|
||||
const [data, setData] = useState<ExecutionLog[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [detail, setDetail] = useState<ExecutionLog | null>(null);
|
||||
@@ -263,6 +265,16 @@ const HistoryTab: React.FC = () => {
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// CHANGE 2026-03-22 | 重新执行历史任务
|
||||
const handleRerun = useCallback(async (id: string) => {
|
||||
try {
|
||||
const { execution_id } = await rerunExecution(id);
|
||||
message.success(`已重新执行,新 ID: ${execution_id.slice(0, 8)}…`);
|
||||
load();
|
||||
} catch { message.error('重新执行失败'); }
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try { setData(await fetchHistory()); }
|
||||
@@ -330,6 +342,23 @@ const HistoryTab: React.FC = () => {
|
||||
}
|
||||
}, [closeHistoryWs, load]);
|
||||
|
||||
// CHANGE 2026-03-27 | 支持 URL 参数 openExecution 自动打开任务详情
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const openExecutionHandled = useRef(false);
|
||||
useEffect(() => {
|
||||
const openId = searchParams.get('openExecution');
|
||||
if (!openId || openExecutionHandled.current || loading || data.length === 0) return;
|
||||
openExecutionHandled.current = true;
|
||||
const target = data.find((r) => r.id === openId);
|
||||
if (target) {
|
||||
handleRowClick(target);
|
||||
} else {
|
||||
handleRowClick({ id: openId, status: 'running' } as ExecutionLog);
|
||||
}
|
||||
searchParams.delete('openExecution');
|
||||
setSearchParams(searchParams, { replace: true });
|
||||
}, [data, loading, searchParams, setSearchParams, handleRowClick]);
|
||||
|
||||
const columns: ColumnsType<ExecutionLog> = [
|
||||
{
|
||||
title: '执行 ID', dataIndex: 'id', key: 'id', width: 120,
|
||||
@@ -366,19 +395,25 @@ const HistoryTab: React.FC = () => {
|
||||
) : '—',
|
||||
},
|
||||
{
|
||||
title: '操作', key: 'action', width: 80, align: 'center',
|
||||
render: (_: unknown, record: ExecutionLog) => {
|
||||
if (record.status === 'running') {
|
||||
return (
|
||||
title: '操作', key: 'action', width: 140, align: 'center',
|
||||
render: (_: unknown, record: ExecutionLog) => (
|
||||
<Space size={0}>
|
||||
{record.status === 'running' && (
|
||||
<Popconfirm title="确认终止该任务?" onConfirm={(e) => { e?.stopPropagation(); handleCancelHistory(record.id); }} onCancel={(e) => e?.stopPropagation()}>
|
||||
<Button type="link" danger icon={<StopOutlined />} size="small" onClick={(e) => e.stopPropagation()}>
|
||||
终止
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
)}
|
||||
{record.status !== 'running' && (
|
||||
<Popconfirm title="确认重新执行该任务?" onConfirm={(e) => { e?.stopPropagation(); handleRerun(record.id); }} onCancel={(e) => e?.stopPropagation()}>
|
||||
<Button type="link" icon={<PlayCircleOutlined />} size="small" onClick={(e) => e.stopPropagation()}>
|
||||
重新执行
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
1134
apps/admin-web/src/pages/TenantAdmins/index.tsx
Normal file
1134
apps/admin-web/src/pages/TenantAdmins/index.tsx
Normal file
File diff suppressed because it is too large
Load Diff
181
apps/admin-web/src/pages/TransferLog.tsx
Normal file
181
apps/admin-web/src/pages/TransferLog.tsx
Normal file
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* P18 客户转移日志页面。
|
||||
*
|
||||
* 展示 biz.coach_task_transfer_log 分页列表,支持门店/时间/助教筛选。
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useCallback } from "react";
|
||||
import {
|
||||
Table, Card, Typography, Button, Space, DatePicker, InputNumber,
|
||||
Tag, Tooltip, message,
|
||||
} from "antd";
|
||||
import {
|
||||
ReloadOutlined, SwapOutlined, CheckCircleOutlined, CloseCircleOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
import dayjs from "dayjs";
|
||||
import {
|
||||
fetchTransferLogs, type TransferLogItem, type TransferLogQuery,
|
||||
} from "../api/taskEngine";
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
function formatTime(raw: string | null): string {
|
||||
if (!raw) return "—";
|
||||
return dayjs(raw).format("YYYY-MM-DD HH:mm");
|
||||
}
|
||||
|
||||
/** guard_checks JSON → 三项检查标签 */
|
||||
function renderGuardChecks(checks: Record<string, unknown> | null) {
|
||||
if (!checks) return <Text type="secondary">—</Text>;
|
||||
return (
|
||||
<Space size={4} wrap>
|
||||
{Object.entries(checks).map(([k, v]) => (
|
||||
<Tag
|
||||
key={k}
|
||||
color={v ? "success" : "error"}
|
||||
icon={v ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
|
||||
>
|
||||
{k}
|
||||
</Tag>
|
||||
))}
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
|
||||
const REASON_LABELS: Record<string, string> = {
|
||||
consecutive_recall_fail: "连续召回失败",
|
||||
manual_reassign: "人工重新分配",
|
||||
ownership_change: "归属变更",
|
||||
};
|
||||
|
||||
const TransferLog: React.FC = () => {
|
||||
const [items, setItems] = useState<TransferLogItem[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [query, setQuery] = useState<TransferLogQuery>({ page: 1, page_size: 20 });
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await fetchTransferLogs(query);
|
||||
setItems(data.items);
|
||||
setTotal(data.total);
|
||||
} catch {
|
||||
message.error("加载转移日志失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [query]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const columns: ColumnsType<TransferLogItem> = [
|
||||
{
|
||||
title: "转移时间", dataIndex: "created_at", key: "created_at", width: 160,
|
||||
render: (v: string) => formatTime(v),
|
||||
},
|
||||
{
|
||||
title: "门店", dataIndex: "site_name", key: "site_name", width: 120,
|
||||
render: (v: string, r) => v || `#${r.site_id}`,
|
||||
},
|
||||
{
|
||||
title: "客户", key: "member", width: 140,
|
||||
render: (_: unknown, r) => (
|
||||
<Tooltip title={`ID: ${r.member_id}`}>
|
||||
{r.member_name || `会员#${r.member_id}`}
|
||||
</Tooltip>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "原助教", key: "from", width: 120,
|
||||
render: (_: unknown, r) => r.from_assistant_name || `#${r.from_assistant_id}`,
|
||||
},
|
||||
{
|
||||
title: "新助教", key: "to", width: 120,
|
||||
render: (_: unknown, r) => r.to_assistant_name || `#${r.to_assistant_id}`,
|
||||
},
|
||||
{
|
||||
title: "转移原因", dataIndex: "transfer_reason", key: "reason", width: 140,
|
||||
render: (v: string | null) => v ? (
|
||||
<Tag>{REASON_LABELS[v] || v}</Tag>
|
||||
) : "—",
|
||||
},
|
||||
{
|
||||
title: "转移得分", dataIndex: "transfer_score", key: "score", width: 90,
|
||||
render: (v: number | null) => v != null ? v.toFixed(2) : "—",
|
||||
},
|
||||
{
|
||||
title: "保护检查", dataIndex: "guard_checks", key: "guards", width: 200,
|
||||
render: (v: Record<string, unknown> | null) => renderGuardChecks(v),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
|
||||
<Title level={4} style={{ margin: 0 }}>
|
||||
<SwapOutlined style={{ marginRight: 8 }} />
|
||||
客户转移日志
|
||||
</Title>
|
||||
<Button icon={<ReloadOutlined />} onClick={load} loading={loading}>刷新</Button>
|
||||
</div>
|
||||
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<Space wrap>
|
||||
<RangePicker
|
||||
placeholder={["开始日期", "结束日期"]}
|
||||
onChange={(dates) => {
|
||||
setQuery((q) => ({
|
||||
...q,
|
||||
from_date: dates?.[0]?.format("YYYY-MM-DD"),
|
||||
to_date: dates?.[1]?.format("YYYY-MM-DD"),
|
||||
page: 1,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
<InputNumber
|
||||
placeholder="助教 ID"
|
||||
style={{ width: 140 }}
|
||||
onChange={(v) => setQuery((q) => ({
|
||||
...q,
|
||||
assistant_id: (v as number) ?? undefined,
|
||||
page: 1,
|
||||
}))}
|
||||
/>
|
||||
<InputNumber
|
||||
placeholder="门店 ID"
|
||||
style={{ width: 140 }}
|
||||
onChange={(v) => setQuery((q) => ({
|
||||
...q,
|
||||
site_id: (v as number) ?? undefined,
|
||||
page: 1,
|
||||
}))}
|
||||
/>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
<Card size="small">
|
||||
<Table<TransferLogItem>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={items}
|
||||
loading={loading}
|
||||
size="small"
|
||||
scroll={{ x: 1200 }}
|
||||
pagination={{
|
||||
current: query.page,
|
||||
pageSize: query.page_size,
|
||||
total,
|
||||
showSizeChanger: true,
|
||||
showTotal: (t) => `共 ${t} 条`,
|
||||
onChange: (page, pageSize) => setQuery((q) => ({ ...q, page, page_size: pageSize })),
|
||||
}}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TransferLog;
|
||||
206
apps/admin-web/src/pages/TriggerJobs.tsx
Normal file
206
apps/admin-web/src/pages/TriggerJobs.tsx
Normal file
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* 定时任务管理页面。
|
||||
*
|
||||
* 展示 biz.trigger_jobs 表中所有定时任务,支持手动执行。
|
||||
*/
|
||||
|
||||
import React, { useEffect, useState, useCallback } from 'react';
|
||||
import { Table, Tag, Button, message, Modal, Typography, Card, Space, Popconfirm, Tooltip } from 'antd';
|
||||
import {
|
||||
ReloadOutlined,
|
||||
ClockCircleOutlined,
|
||||
PlayCircleOutlined,
|
||||
CheckCircleOutlined,
|
||||
ExclamationCircleOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { fetchTriggerJobs, runTriggerJob, clearAllTasks, type TriggerJob } from '../api/triggerJobs';
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
|
||||
const TRIGGER_LABEL: Record<string, string> = {
|
||||
cron: '定时(Cron)',
|
||||
interval: '间隔',
|
||||
event: '事件触发',
|
||||
};
|
||||
|
||||
const STATUS_COLOR: Record<string, string> = {
|
||||
enabled: 'green',
|
||||
disabled: 'default',
|
||||
};
|
||||
|
||||
function formatTime(raw: string | null): string {
|
||||
if (!raw) return '—';
|
||||
const d = new Date(raw);
|
||||
return Number.isNaN(d.getTime()) ? raw : d.toLocaleString('zh-CN');
|
||||
}
|
||||
|
||||
function formatTriggerConfig(job: TriggerJob): string {
|
||||
const cfg = job.trigger_config;
|
||||
if (!cfg) return '—';
|
||||
if (job.trigger_condition === 'cron') return cfg.cron_expression as string || '—';
|
||||
if (job.trigger_condition === 'interval') {
|
||||
const sec = cfg.interval_seconds as number;
|
||||
if (sec >= 3600) return `每 ${sec / 3600} 小时`;
|
||||
if (sec >= 60) return `每 ${sec / 60} 分钟`;
|
||||
return `每 ${sec} 秒`;
|
||||
}
|
||||
if (job.trigger_condition === 'event') return `事件: ${cfg.event_name || '—'}`;
|
||||
return JSON.stringify(cfg);
|
||||
}
|
||||
|
||||
const TriggerJobs: React.FC = () => {
|
||||
const [jobs, setJobs] = useState<TriggerJob[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [runningId, setRunningId] = useState<number | null>(null);
|
||||
const [clearing, setClearing] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await fetchTriggerJobs();
|
||||
setJobs(data);
|
||||
} catch {
|
||||
message.error('加载定时任务失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const handleRun = async (jobId: number) => {
|
||||
setRunningId(jobId);
|
||||
try {
|
||||
const result = await runTriggerJob(jobId);
|
||||
if (result.success) {
|
||||
message.success(result.message);
|
||||
} else {
|
||||
message.error(result.message);
|
||||
}
|
||||
await load();
|
||||
} catch {
|
||||
message.error('执行失败');
|
||||
} finally {
|
||||
setRunningId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearAllTasks = async () => {
|
||||
setClearing(true);
|
||||
try {
|
||||
const result = await clearAllTasks();
|
||||
if (result.success) {
|
||||
Modal.success({
|
||||
title: '清空完成',
|
||||
content: result.message,
|
||||
});
|
||||
await load();
|
||||
} else {
|
||||
message.error(result.message);
|
||||
}
|
||||
} catch {
|
||||
message.error('清空任务失败');
|
||||
} finally {
|
||||
setClearing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const columns: ColumnsType<TriggerJob> = [
|
||||
{
|
||||
title: '任务名称', dataIndex: 'job_name', key: 'job_name', width: 180,
|
||||
render: (name: string, record) => (
|
||||
<Tooltip title={record.description || name}>
|
||||
<Text strong>{record.description || name}</Text>
|
||||
<br />
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>{name}</Text>
|
||||
</Tooltip>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '触发方式', dataIndex: 'trigger_condition', key: 'trigger_condition', width: 120,
|
||||
render: (v: string) => <Tag>{TRIGGER_LABEL[v] || v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '触发配置', key: 'trigger_config', width: 150,
|
||||
render: (_: unknown, record) => <code style={{ fontSize: 12 }}>{formatTriggerConfig(record)}</code>,
|
||||
},
|
||||
{
|
||||
title: '状态', dataIndex: 'status', key: 'status', width: 80,
|
||||
render: (v: string) => <Tag color={STATUS_COLOR[v] || 'default'}>{v === 'enabled' ? '启用' : '禁用'}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '上次执行', dataIndex: 'last_run_at', key: 'last_run_at', width: 170,
|
||||
render: (v: string | null) => formatTime(v),
|
||||
},
|
||||
{
|
||||
title: '下次执行', dataIndex: 'next_run_at', key: 'next_run_at', width: 170,
|
||||
render: (v: string | null) => formatTime(v),
|
||||
},
|
||||
{
|
||||
title: '最近错误', dataIndex: 'last_error', key: 'last_error', width: 200,
|
||||
render: (v: string | null) => v
|
||||
? <Tooltip title={v}><Text type="danger" ellipsis style={{ maxWidth: 180 }}><ExclamationCircleOutlined /> {v}</Text></Tooltip>
|
||||
: <Text type="success"><CheckCircleOutlined /> 正常</Text>,
|
||||
},
|
||||
{
|
||||
title: '操作', key: 'action', width: 100, fixed: 'right',
|
||||
render: (_: unknown, record) => (
|
||||
<Popconfirm
|
||||
title={`确认手动执行「${record.description || record.job_name}」?`}
|
||||
onConfirm={() => handleRun(record.id)}
|
||||
okText="执行"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
icon={<PlayCircleOutlined />}
|
||||
loading={runningId === record.id}
|
||||
disabled={record.status !== 'enabled'}
|
||||
>
|
||||
执行
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<Title level={4} style={{ margin: 0 }}>
|
||||
<ClockCircleOutlined style={{ marginRight: 8 }} />
|
||||
定时任务管理
|
||||
</Title>
|
||||
<Space>
|
||||
<Popconfirm
|
||||
title="确认清空所有助教任务?"
|
||||
description="将删除 coach_tasks 和 coach_task_history 中的全部数据,此操作不可撤销。"
|
||||
onConfirm={handleClearAllTasks}
|
||||
okText="确认清空"
|
||||
cancelText="取消"
|
||||
okButtonProps={{ danger: true }}
|
||||
>
|
||||
<Button danger loading={clearing}>🧹 清空所有任务</Button>
|
||||
</Popconfirm>
|
||||
<Button icon={<ReloadOutlined />} onClick={load} loading={loading}>刷新</Button>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
<Card size="small">
|
||||
<Table<TriggerJob>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={jobs}
|
||||
loading={loading}
|
||||
pagination={false}
|
||||
size="small"
|
||||
scroll={{ x: 1200 }}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TriggerJobs;
|
||||
462
apps/admin-web/src/pages/TriggerManager.tsx
Normal file
462
apps/admin-web/src/pages/TriggerManager.tsx
Normal file
@@ -0,0 +1,462 @@
|
||||
/**
|
||||
* 触发器统一管理页面 — 聚合 biz / ai / etl 三类触发器为 Tab 视图。
|
||||
*
|
||||
* - 4 个 Tab:all(全部,只读统一视图)、biz(业务)、ai(AI)、etl(ETL)
|
||||
* - Tab 切换通过 useSearchParams 同步 URL 查询参数 ?tab=all|biz|ai|etl
|
||||
* - destroyInactiveTabPane={false} 保持 Tab 状态不丢失
|
||||
* - "全部"Tab 调用 fetchUnifiedTriggers(),展示统一字段表格
|
||||
* - "业务"Tab 复用 TriggerJobs 组件 + 编辑 Modal
|
||||
* - "AI"Tab 复用 AIOperations + AITriggerJobs 组件
|
||||
* - "ETL"Tab 展示 scheduled_tasks 数据
|
||||
*
|
||||
* CHANGE 2026-07-15 | Task 10.1:创建 TriggerManager 页面
|
||||
*/
|
||||
|
||||
import React, { useMemo, useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
Tabs, Typography, Table, Tag, message, Modal, Form, Input, InputNumber, Space,
|
||||
Button, Card,
|
||||
} from 'antd';
|
||||
import {
|
||||
AppstoreOutlined,
|
||||
SettingOutlined,
|
||||
RobotOutlined,
|
||||
CloudServerOutlined,
|
||||
EditOutlined,
|
||||
ReloadOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
|
||||
import { fetchUnifiedTriggers, type UnifiedTriggerItem } from '../api/triggers';
|
||||
import {
|
||||
fetchTriggerJobs, updateTriggerConfig,
|
||||
type TriggerJob, type UpdateTriggerConfigReq,
|
||||
} from '../api/triggerJobs';
|
||||
import { fetchSchedules } from '../api/schedules';
|
||||
import type { ScheduledTask } from '../types';
|
||||
import AIOperations from './AIOperations';
|
||||
import AITriggerJobs from './AITriggerJobs';
|
||||
|
||||
const { Title } = Typography;
|
||||
|
||||
/* ───────── Tab 常量 ───────── */
|
||||
|
||||
const VALID_TABS = ['all', 'biz', 'ai', 'etl'] as const;
|
||||
type TabKey = (typeof VALID_TABS)[number];
|
||||
const DEFAULT_TAB: TabKey = 'all';
|
||||
|
||||
function isValidTab(value: string | null): value is TabKey {
|
||||
return value != null && (VALID_TABS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
/* ───────── 工具函数 ───────── */
|
||||
|
||||
const SOURCE_COLOR: Record<string, string> = {
|
||||
biz: 'blue', ai: 'purple', etl: 'green',
|
||||
};
|
||||
const SOURCE_LABEL: Record<string, string> = {
|
||||
biz: '业务', ai: 'AI', etl: 'ETL',
|
||||
};
|
||||
|
||||
function formatTime(raw: string | null): string {
|
||||
if (!raw) return '—';
|
||||
const d = new Date(raw);
|
||||
return Number.isNaN(d.getTime()) ? raw : d.toLocaleString('zh-CN');
|
||||
}
|
||||
|
||||
/* ───────── "全部"Tab:统一视图(只读) ───────── */
|
||||
|
||||
const AllTriggersTab: React.FC = () => {
|
||||
const [data, setData] = useState<UnifiedTriggerItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
setData(await fetchUnifiedTriggers());
|
||||
} catch {
|
||||
message.error('加载统一触发器数据失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const columns: ColumnsType<UnifiedTriggerItem> = [
|
||||
{ title: '名称', dataIndex: 'name', key: 'name', width: 200 },
|
||||
{
|
||||
title: '类型', dataIndex: 'source', key: 'source', width: 80,
|
||||
render: (v: string) => (
|
||||
<Tag color={SOURCE_COLOR[v] ?? 'default'}>{SOURCE_LABEL[v] ?? v}</Tag>
|
||||
),
|
||||
},
|
||||
{ title: '触发条件', dataIndex: 'trigger_condition', key: 'trigger_condition', width: 120 },
|
||||
{
|
||||
title: '状态', dataIndex: 'status', key: 'status', width: 100,
|
||||
render: (v: string) => {
|
||||
const color = v === 'running' ? 'processing' : v === 'error' ? 'error'
|
||||
: v === 'disabled' ? 'default' : 'success';
|
||||
return <Tag color={color}>{v}</Tag>;
|
||||
},
|
||||
},
|
||||
{ title: '上次执行', dataIndex: 'last_run_at', key: 'last_run_at', width: 170, render: formatTime },
|
||||
{ title: '下次执行', dataIndex: 'next_run_at', key: 'next_run_at', width: 170, render: formatTime },
|
||||
{
|
||||
title: '最近错误', dataIndex: 'last_error', key: 'last_error', ellipsis: true,
|
||||
render: (v: string | null) => v
|
||||
? <Typography.Text type="danger" ellipsis style={{ maxWidth: 200 }}>{v}</Typography.Text>
|
||||
: '—',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Card
|
||||
size="small"
|
||||
extra={<Button icon={<ReloadOutlined />} size="small" onClick={load} loading={loading}>刷新</Button>}
|
||||
>
|
||||
<Table<UnifiedTriggerItem>
|
||||
rowKey={(r) => `${r.source}-${r.id}`}
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
loading={loading}
|
||||
pagination={{ pageSize: 20, showTotal: (t) => `共 ${t} 条` }}
|
||||
size="small"
|
||||
scroll={{ x: 1000 }}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
/* ───────── "业务"Tab:TriggerJobs + 编辑 Modal ───────── */
|
||||
|
||||
const BizTriggersTab: React.FC = () => {
|
||||
const [jobs, setJobs] = useState<TriggerJob[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [editingJob, setEditingJob] = useState<TriggerJob | null>(null);
|
||||
const [editModalOpen, setEditModalOpen] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [form] = Form.useForm<UpdateTriggerConfigReq>();
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
setJobs(await fetchTriggerJobs());
|
||||
} catch {
|
||||
message.error('加载业务触发器失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const openEdit = (job: TriggerJob) => {
|
||||
setEditingJob(job);
|
||||
const cfg = job.trigger_config ?? {};
|
||||
form.setFieldsValue({
|
||||
cron_expression: (cfg.cron_expression as string) ?? undefined,
|
||||
interval_seconds: (cfg.interval_seconds as number) ?? undefined,
|
||||
});
|
||||
setEditModalOpen(true);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!editingJob) return;
|
||||
try {
|
||||
const values = await form.validateFields();
|
||||
// 只发送有值的字段
|
||||
const body: UpdateTriggerConfigReq = {};
|
||||
if (values.cron_expression != null && values.cron_expression !== '') {
|
||||
body.cron_expression = values.cron_expression;
|
||||
}
|
||||
if (values.interval_seconds != null) {
|
||||
body.interval_seconds = values.interval_seconds;
|
||||
}
|
||||
if (!body.cron_expression && body.interval_seconds == null) {
|
||||
message.warning('请至少填写 cron 表达式或间隔秒数');
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
await updateTriggerConfig(editingJob.id, body);
|
||||
message.success('触发器配置已更新');
|
||||
setEditModalOpen(false);
|
||||
setEditingJob(null);
|
||||
form.resetFields();
|
||||
await load();
|
||||
} catch (err: unknown) {
|
||||
// 422 错误展示具体信息
|
||||
if (err && typeof err === 'object' && 'response' in err) {
|
||||
const resp = (err as { response?: { status?: number; data?: { detail?: string } } }).response;
|
||||
if (resp?.status === 422 && resp.data?.detail) {
|
||||
message.error(resp.data.detail);
|
||||
return;
|
||||
}
|
||||
}
|
||||
message.error('保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const TRIGGER_LABEL: Record<string, string> = {
|
||||
cron: '定时(Cron)', interval: '间隔', event: '事件触发',
|
||||
};
|
||||
|
||||
const formatTriggerConfig = (job: TriggerJob): string => {
|
||||
const cfg = job.trigger_config;
|
||||
if (!cfg) return '—';
|
||||
if (job.trigger_condition === 'cron') return (cfg.cron_expression as string) || '—';
|
||||
if (job.trigger_condition === 'interval') {
|
||||
const sec = cfg.interval_seconds as number;
|
||||
if (sec >= 3600) return `每 ${sec / 3600} 小时`;
|
||||
if (sec >= 60) return `每 ${sec / 60} 分钟`;
|
||||
return `每 ${sec} 秒`;
|
||||
}
|
||||
if (job.trigger_condition === 'event') return `事件: ${cfg.event_name || '—'}`;
|
||||
return JSON.stringify(cfg);
|
||||
};
|
||||
|
||||
const columns: ColumnsType<TriggerJob> = [
|
||||
{
|
||||
title: '任务名称', dataIndex: 'job_name', key: 'job_name', width: 180,
|
||||
render: (name: string, record) => (
|
||||
<>
|
||||
<Typography.Text strong>{record.description || name}</Typography.Text>
|
||||
<br />
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>{name}</Typography.Text>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '触发方式', dataIndex: 'trigger_condition', key: 'trigger_condition', width: 120,
|
||||
render: (v: string) => <Tag>{TRIGGER_LABEL[v] || v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '触发配置', key: 'trigger_config', width: 150,
|
||||
render: (_: unknown, record) => <code style={{ fontSize: 12 }}>{formatTriggerConfig(record)}</code>,
|
||||
},
|
||||
{
|
||||
title: '状态', dataIndex: 'status', key: 'status', width: 80,
|
||||
render: (v: string) => (
|
||||
<Tag color={v === 'enabled' ? 'green' : 'default'}>{v === 'enabled' ? '启用' : '禁用'}</Tag>
|
||||
),
|
||||
},
|
||||
{ title: '上次执行', dataIndex: 'last_run_at', key: 'last_run_at', width: 170, render: formatTime },
|
||||
{ title: '下次执行', dataIndex: 'next_run_at', key: 'next_run_at', width: 170, render: formatTime },
|
||||
{
|
||||
title: '最近错误', dataIndex: 'last_error', key: 'last_error', width: 200,
|
||||
render: (v: string | null) => v
|
||||
? <Typography.Text type="danger" ellipsis style={{ maxWidth: 180 }}>{v}</Typography.Text>
|
||||
: <Typography.Text type="success">正常</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: '操作', key: 'action', width: 80, fixed: 'right',
|
||||
render: (_: unknown, record) => (
|
||||
<Button
|
||||
size="small"
|
||||
icon={<EditOutlined />}
|
||||
onClick={() => openEdit(record)}
|
||||
disabled={record.status !== 'enabled'}
|
||||
>
|
||||
编辑
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card
|
||||
size="small"
|
||||
extra={<Button icon={<ReloadOutlined />} size="small" onClick={load} loading={loading}>刷新</Button>}
|
||||
>
|
||||
<Table<TriggerJob>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={jobs}
|
||||
loading={loading}
|
||||
pagination={false}
|
||||
size="small"
|
||||
scroll={{ x: 1200 }}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<Modal
|
||||
title={`编辑触发器配置 — ${editingJob?.description || editingJob?.job_name || ''}`}
|
||||
open={editModalOpen}
|
||||
onCancel={() => { setEditModalOpen(false); setEditingJob(null); form.resetFields(); }}
|
||||
onOk={handleSave}
|
||||
confirmLoading={saving}
|
||||
okText="保存"
|
||||
cancelText="取消"
|
||||
destroyOnClose
|
||||
>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item
|
||||
name="cron_expression"
|
||||
label="Cron 表达式(5 字段格式)"
|
||||
help="例如:0 */2 * * *(每 2 小时执行)"
|
||||
>
|
||||
<Input placeholder="分 时 日 月 周" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="interval_seconds"
|
||||
label="间隔秒数"
|
||||
help="最小值为 1"
|
||||
rules={[{ type: 'number', min: 1, message: 'interval_seconds 必须 >= 1' }]}
|
||||
>
|
||||
<InputNumber style={{ width: '100%' }} min={1} placeholder="秒" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
/* ───────── "AI"Tab:AIOperations + AITriggerJobs ───────── */
|
||||
|
||||
const AITriggersTab: React.FC = () => (
|
||||
<Space direction="vertical" style={{ width: '100%' }} size="large">
|
||||
<AIOperations />
|
||||
<AITriggerJobs />
|
||||
</Space>
|
||||
);
|
||||
|
||||
/* ───────── "ETL"Tab:scheduled_tasks 数据 ───────── */
|
||||
|
||||
const ETLTriggersTab: React.FC = () => {
|
||||
const [data, setData] = useState<ScheduledTask[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
setData(await fetchSchedules());
|
||||
} catch {
|
||||
message.error('加载 ETL 调度任务失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const columns: ColumnsType<ScheduledTask> = [
|
||||
{ title: '名称', dataIndex: 'name', key: 'name', width: 200 },
|
||||
{
|
||||
title: '任务代码', dataIndex: 'task_codes', key: 'task_codes', width: 200,
|
||||
render: (v: string[]) => v?.join(', ') ?? '—',
|
||||
},
|
||||
{
|
||||
title: '状态', dataIndex: 'enabled', key: 'enabled', width: 80,
|
||||
render: (v: boolean) => <Tag color={v ? 'green' : 'default'}>{v ? '启用' : '禁用'}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '上次状态', dataIndex: 'last_status', key: 'last_status', width: 100,
|
||||
render: (v: string | null) => v
|
||||
? <Tag color={v === 'success' ? 'success' : v === 'failed' ? 'error' : 'default'}>{v}</Tag>
|
||||
: '—',
|
||||
},
|
||||
{ title: '上次执行', dataIndex: 'last_run_at', key: 'last_run_at', width: 170, render: formatTime },
|
||||
{ title: '下次执行', dataIndex: 'next_run_at', key: 'next_run_at', width: 170, render: formatTime },
|
||||
{ title: '执行次数', dataIndex: 'run_count', key: 'run_count', width: 90 },
|
||||
{ title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 170, render: formatTime },
|
||||
];
|
||||
|
||||
return (
|
||||
<Card
|
||||
size="small"
|
||||
extra={<Button icon={<ReloadOutlined />} size="small" onClick={load} loading={loading}>刷新</Button>}
|
||||
>
|
||||
<Table<ScheduledTask>
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={data}
|
||||
loading={loading}
|
||||
pagination={{ pageSize: 20, showTotal: (t) => `共 ${t} 条` }}
|
||||
size="small"
|
||||
scroll={{ x: 1000 }}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
/* ───────── 主组件 ───────── */
|
||||
|
||||
const TriggerManager: React.FC = () => {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const activeTab: TabKey = useMemo(() => {
|
||||
const raw = searchParams.get('tab');
|
||||
return isValidTab(raw) ? raw : DEFAULT_TAB;
|
||||
}, [searchParams]);
|
||||
|
||||
const handleTabChange = (key: string) => {
|
||||
setSearchParams({ tab: key }, { replace: true });
|
||||
};
|
||||
|
||||
const items = useMemo(
|
||||
() => [
|
||||
{
|
||||
key: 'all' as TabKey,
|
||||
label: (
|
||||
<span>
|
||||
<AppstoreOutlined style={{ marginRight: 6 }} />
|
||||
全部
|
||||
</span>
|
||||
),
|
||||
children: <AllTriggersTab />,
|
||||
},
|
||||
{
|
||||
key: 'biz' as TabKey,
|
||||
label: (
|
||||
<span>
|
||||
<SettingOutlined style={{ marginRight: 6 }} />
|
||||
业务
|
||||
</span>
|
||||
),
|
||||
children: <BizTriggersTab />,
|
||||
},
|
||||
{
|
||||
key: 'ai' as TabKey,
|
||||
label: (
|
||||
<span>
|
||||
<RobotOutlined style={{ marginRight: 6 }} />
|
||||
AI
|
||||
</span>
|
||||
),
|
||||
children: <AITriggersTab />,
|
||||
},
|
||||
{
|
||||
key: 'etl' as TabKey,
|
||||
label: (
|
||||
<span>
|
||||
<CloudServerOutlined style={{ marginRight: 6 }} />
|
||||
ETL
|
||||
</span>
|
||||
),
|
||||
children: <ETLTriggersTab />,
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Title level={4} style={{ marginBottom: 16 }}>
|
||||
<SettingOutlined style={{ marginRight: 8 }} />
|
||||
触发器管理
|
||||
</Title>
|
||||
<Tabs
|
||||
activeKey={activeTab}
|
||||
onChange={handleTabChange}
|
||||
items={items}
|
||||
destroyInactiveTabPane={false}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TriggerManager;
|
||||
@@ -1,5 +1,9 @@
|
||||
/**
|
||||
* 日志查看器页面。
|
||||
* [ARCHIVED] 日志查看器页面。
|
||||
*
|
||||
* 已废弃:功能已合并到 ETLTasks 页面的"任务管理"Tab。
|
||||
* 归档日期:2026-03-25
|
||||
* 归档原因:admin-web-restructure spec,需求 8(LogViewer 废弃)
|
||||
*
|
||||
* - 输入执行 ID,通过 WebSocket 实时接收日志
|
||||
* - 支持加载历史日志
|
||||
@@ -13,9 +17,9 @@ import {
|
||||
FileTextOutlined, SearchOutlined, ClearOutlined,
|
||||
AppstoreOutlined, UnorderedListOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import { apiClient } from "../api/client";
|
||||
import LogStream from "../components/LogStream";
|
||||
import TaskLogViewer from "../components/TaskLogViewer";
|
||||
import { apiClient } from "../../api/client";
|
||||
import LogStream from "../../components/LogStream";
|
||||
import TaskLogViewer from "../../components/TaskLogViewer";
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
|
||||
@@ -19,6 +19,7 @@ export interface AuthUser {
|
||||
username: string;
|
||||
display_name: string;
|
||||
site_id: number;
|
||||
roles: string[];
|
||||
}
|
||||
|
||||
/** 后端 /api/auth/login 响应体 */
|
||||
@@ -64,6 +65,7 @@ function parseJwtPayload(token: string): AuthUser | null {
|
||||
username: payload.username as string,
|
||||
display_name: (payload.display_name as string) ?? "",
|
||||
site_id: payload.site_id as number,
|
||||
roles: (payload.roles as string[]) ?? [],
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
92
apps/admin-web/src/types/devTrace.ts
Normal file
92
apps/admin-web/src/types/devTrace.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* 开发调试全链路日志 — TypeScript 类型定义。
|
||||
*
|
||||
* 与后端 trace 模块的 Pydantic 模型和 JSON Lines 输出结构对应。
|
||||
*/
|
||||
|
||||
// ---- Span 类型枚举 ----
|
||||
|
||||
export type SpanType =
|
||||
| "HTTP_IN" | "AUTH" | "ROUTE" | "SERVICE"
|
||||
| "DB_QUERY" | "DB_CONN" | "DB_CONN_RELEASE"
|
||||
| "HTTP_OUT" | "ERROR" | "DB_ERROR"
|
||||
| "MIDDLEWARE" | "MIDDLEWARE_ERROR"
|
||||
| "SSE_START" | "SSE_EVENT" | "SSE_END"
|
||||
| "AI_CALL" | "AI_STREAM" | "AI_ERROR"
|
||||
| "WS_CONNECT" | "WS_MESSAGE" | "WS_DISCONNECT"
|
||||
| "JOB_START" | "JOB_END" | "JOB_ERROR";
|
||||
|
||||
export type TraceType = "http" | "sse" | "ws" | "job";
|
||||
|
||||
// ---- 数据模型 ----
|
||||
|
||||
export interface TraceSpan {
|
||||
span_type: SpanType;
|
||||
module: string;
|
||||
function: string;
|
||||
description_zh: string;
|
||||
description_en: string;
|
||||
params: Record<string, unknown>;
|
||||
result_summary: string;
|
||||
duration_ms: number;
|
||||
timestamp: string;
|
||||
extra: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface TraceRequest {
|
||||
request_id: string;
|
||||
trace_type: TraceType;
|
||||
timestamp: string;
|
||||
method: string;
|
||||
path: string;
|
||||
status_code: number | null;
|
||||
total_duration_ms: number;
|
||||
user_id: number | null;
|
||||
site_id: number | null;
|
||||
db_query_count: number;
|
||||
db_total_ms: number;
|
||||
error: string | null;
|
||||
span_count: number;
|
||||
}
|
||||
|
||||
export interface TraceDetail extends Omit<TraceRequest, "span_count"> {
|
||||
spans: TraceSpan[];
|
||||
}
|
||||
|
||||
export interface TraceSettings {
|
||||
enabled: boolean;
|
||||
log_dir: string;
|
||||
retention_days: number;
|
||||
log_sql: boolean;
|
||||
log_params: boolean;
|
||||
}
|
||||
|
||||
export interface TraceFilter {
|
||||
date: string;
|
||||
start_time?: string;
|
||||
end_time?: string;
|
||||
trace_type?: TraceType;
|
||||
method?: string;
|
||||
path_contains?: string;
|
||||
status_code?: number;
|
||||
min_duration?: number;
|
||||
has_error?: boolean;
|
||||
span_type?: SpanType;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface CoverageCategory {
|
||||
total: number;
|
||||
covered: number;
|
||||
uncovered: string[];
|
||||
}
|
||||
|
||||
export interface TraceCoverage {
|
||||
scan_time: string;
|
||||
routes: CoverageCategory;
|
||||
services: CoverageCategory;
|
||||
jobs: CoverageCategory;
|
||||
sse_endpoints: CoverageCategory;
|
||||
ws_endpoints: CoverageCategory;
|
||||
}
|
||||
@@ -125,6 +125,12 @@ export interface ExecutionLog {
|
||||
schedule_id: string | null;
|
||||
}
|
||||
|
||||
/** 单个任务的最小执行间隔 */
|
||||
export interface MinRunIntervalItem {
|
||||
value: number;
|
||||
unit: "minutes" | "hours" | "days";
|
||||
}
|
||||
|
||||
/** 调度任务 */
|
||||
export interface ScheduledTask {
|
||||
id: string;
|
||||
@@ -138,6 +144,10 @@ export interface ScheduledTask {
|
||||
next_run_at: string | null;
|
||||
run_count: number;
|
||||
last_status: string | null;
|
||||
min_run_interval_value: number;
|
||||
min_run_interval_unit: string;
|
||||
last_success_at: string | null;
|
||||
min_run_intervals: Record<string, MinRunIntervalItem>;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user