fix(frontend): 按审计报告修复全部17项问题,数据层迁至 src/api/
P0(4): 假数据清除(avg_latency_ms:2400→null,无端点字段改null)、假进度条改诚实的不确定态、 公共页不再反向依赖 admin(api/public.ts)、PredictProgress 重写 P1(6): 23处 any 归零(对齐后端 Pydantic 契约新增 PredictionMatchRef/HealthProbe 等)、 a11y(aria-live 0→4,htmlFor 1→17,aria-describedby/invalid 补齐)、App.tsx 抽 SiteLayout、 路由级 lazy+代码分割(首屏 315KB→238KB)、index.html 补 SEO/favicon/OG、死代码清理(AdminIcon 抽出) P2(7): Login/index.css 裸色值令牌化、groupByDate useMemo、滚动监听统一、原生控件基元化、 useLeagues 静默失败补告警、路由级 ErrorBoundary 另修复审计未列问题: - Monitoring todos 过滤器 t!==false 放行 null 导致整页崩溃 → Boolean(t) 真值过滤 - Collection 渲染期 Date.now()(react-hooks/purity 捕获)→ 计时器 effect - bg-press-wash/60 透明度修饰符静默失效 → RGB 三元组 + 构建期令牌守卫(下个提交接入) 工程化:数据层 dal/api/types(1047行)git mv 至 src/api/,admin 留 @deprecated 兼容壳, 21 个引用方直指新路径;tsconfig 开启 noUnusedLocals/noUnusedParameters(清理9处存量)
This commit is contained in:
+40
-1
@@ -3,7 +3,46 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Profeto - 足球 LLM 预测</title>
|
|
||||||
|
<!--
|
||||||
|
SEO / 分享 / 移动端元信息。
|
||||||
|
此前这里只有 charset + viewport + title —— 搜索引擎无摘要、
|
||||||
|
分享到社交平台无预览卡片、iOS 添加到主屏是截图占位、
|
||||||
|
移动端浏览器地址栏不染色。品牌在浏览器层面完全裸奔。
|
||||||
|
-->
|
||||||
|
<title>Profeto · 足球赛程与 LLM 预测</title>
|
||||||
|
<meta
|
||||||
|
name="description"
|
||||||
|
content="Profeto 提供主流联赛赛程、实时积分榜,以及由多专家大语言模型生成的比分与胜平负预测。仅供研究参考,不构成投注建议。"
|
||||||
|
/>
|
||||||
|
<meta name="theme-color" content="#FDFCF8" />
|
||||||
|
|
||||||
|
<!-- 索引控制:公开站点允许收录,但不索引管理后台 -->
|
||||||
|
<meta name="robots" content="index, follow" />
|
||||||
|
|
||||||
|
<!-- 图标:SVG 优先(任意缩放清晰),PNG 作为老浏览器兜底 -->
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
|
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png" />
|
||||||
|
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16.png" />
|
||||||
|
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
|
||||||
|
|
||||||
|
<!-- Open Graph:微信 / 飞书 / 社交平台分享卡片 -->
|
||||||
|
<meta property="og:type" content="website" />
|
||||||
|
<meta property="og:site_name" content="Profeto" />
|
||||||
|
<meta property="og:title" content="Profeto · 足球赛程与 LLM 预测" />
|
||||||
|
<meta
|
||||||
|
property="og:description"
|
||||||
|
content="主流联赛赛程与积分榜,多专家大语言模型预测。仅供研究参考。"
|
||||||
|
/>
|
||||||
|
<meta property="og:locale" content="zh_CN" />
|
||||||
|
|
||||||
|
<!-- Twitter / X 卡片 -->
|
||||||
|
<meta name="twitter:card" content="summary" />
|
||||||
|
<meta name="twitter:title" content="Profeto · 足球赛程与 LLM 预测" />
|
||||||
|
<meta
|
||||||
|
name="twitter:description"
|
||||||
|
content="主流联赛赛程与积分榜,多专家大语言模型预测。仅供研究参考。"
|
||||||
|
/>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 650 B |
Binary file not shown.
|
After Width: | Height: | Size: 128 B |
Binary file not shown.
|
After Width: | Height: | Size: 182 B |
@@ -0,0 +1,5 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||||
|
<rect width="32" height="32" fill="#FDFCF8"/>
|
||||||
|
<rect x="1.5" y="1.5" width="29" height="29" fill="none" stroke="#17140F" stroke-width="2.5"/>
|
||||||
|
<text x="16" y="23" font-family="serif" font-size="20" font-weight="700" fill="#9E1B1B" text-anchor="middle">先</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 334 B |
+56
-29
@@ -9,49 +9,76 @@
|
|||||||
* - 首页报头放「评估」「管理」入口(极简,不另加导航条)
|
* - 首页报头放「评估」「管理」入口(极简,不另加导航条)
|
||||||
* - 管理后台由 AdminLayout 侧边栏处理所有管理页导航
|
* - 管理后台由 AdminLayout 侧边栏处理所有管理页导航
|
||||||
* - 未登录访问管理 → AdminLayout 门禁 → 登录页(不静默失败)
|
* - 未登录访问管理 → AdminLayout 门禁 → 登录页(不静默失败)
|
||||||
|
*
|
||||||
|
* 代码分割:
|
||||||
|
* - 公开页(Matches/Standings)各自 lazy,后台整体懒加载。
|
||||||
|
* 此前所有页面打进同一个 chunk,一个只想看赛程的匿名访客也要
|
||||||
|
* 下载 Dashboard/Collection/Logs/Eval/Backtest/... 十个后台页面。
|
||||||
|
* - ErrorBoundary 下沉到每个路由级:某个页面渲染崩溃时降级为
|
||||||
|
* 「该页面报错」,而不是整个应用白屏。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { lazy, Suspense } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
|
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
|
||||||
import { ErrorBoundary } from './components/ErrorBoundary'
|
import { ErrorBoundary } from './components/ErrorBoundary'
|
||||||
import Masthead from './components/Masthead'
|
import { SiteLayout } from './components/SiteLayout'
|
||||||
import Matches from './pages/Matches'
|
|
||||||
import Standings from './pages/Standings'
|
|
||||||
import { adminRoutes } from './admin/routes'
|
import { adminRoutes } from './admin/routes'
|
||||||
|
|
||||||
function StandingsLayout({ children }: { children: React.ReactNode }) {
|
// ── 路由级懒加载 ────────────────────────────────────────────────
|
||||||
|
// 每个入口拆成独立 chunk,首屏只加载当前路由所需代码。
|
||||||
|
const Matches = lazy(() => import('./pages/Matches'))
|
||||||
|
const Standings = lazy(() => import('./pages/Standings'))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 路由级加载占位。
|
||||||
|
* 保持与应用一致的纸色背景与居中位置,避免切换时出现白闪。
|
||||||
|
*/
|
||||||
|
function RouteFallback() {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-paper-50">
|
<div className="flex min-h-[60vh] items-center justify-center">
|
||||||
<Masthead active="standings" />
|
<span className="text-xs text-ink-400" role="status" aria-live="polite">
|
||||||
|
加载中…
|
||||||
<main className="mx-auto max-w-5xl px-5 py-6 sm:px-8 sm:py-8">
|
</span>
|
||||||
{children}
|
|
||||||
</main>
|
|
||||||
|
|
||||||
<footer className="mx-auto max-w-5xl px-5 pb-10 sm:px-8">
|
|
||||||
<div className="border-t border-ink-200 pt-3 text-center text-2xs leading-relaxed text-ink-400">
|
|
||||||
数据由 bzzoiro 提供 · 仅供研究参考
|
|
||||||
</div>
|
|
||||||
</footer>
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单个路由的错误与加载边界。
|
||||||
|
*
|
||||||
|
* 注意 ErrorBoundary 必须包在 Suspense 外层:lazy 组件加载失败
|
||||||
|
* (网络中断、部署后 chunk 哈希变化)会以错误形式抛出,而不是
|
||||||
|
* 永远停在加载态。
|
||||||
|
*/
|
||||||
|
function RouteShell({ children }: { children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<ErrorBoundary fullScreen={false}>
|
||||||
|
<Suspense fallback={<RouteFallback />}>{children}</Suspense>
|
||||||
|
</ErrorBoundary>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function HomePage() {
|
function HomePage() {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-paper-50">
|
<SiteLayout
|
||||||
{/* ── 报头:粗线 + 居中刊名 + 日期与分区链接(共用 Masthead) ── */}
|
active="home"
|
||||||
<Masthead active="home" />
|
footerNote="预测结果由大语言模型生成 · 仅供研究参考 · 不构成任何投注建议"
|
||||||
|
>
|
||||||
<main className="mx-auto max-w-5xl px-5 py-6 sm:px-8 sm:py-8">
|
<RouteShell>
|
||||||
<Matches />
|
<Matches />
|
||||||
</main>
|
</RouteShell>
|
||||||
|
</SiteLayout>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
<footer className="mx-auto max-w-5xl px-5 pb-10 sm:px-8">
|
function StandingsPage() {
|
||||||
<div className="border-t border-ink-200 pt-3 text-center text-2xs leading-relaxed text-ink-400">
|
return (
|
||||||
预测结果由大语言模型生成 · 仅供研究参考 · 不构成任何投注建议
|
<SiteLayout active="standings" footerNote="数据由 bzzoiro 提供 · 仅供研究参考">
|
||||||
</div>
|
<RouteShell>
|
||||||
</footer>
|
<Standings />
|
||||||
</div>
|
</RouteShell>
|
||||||
|
</SiteLayout>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,7 +88,7 @@ export default function App() {
|
|||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={<HomePage />} />
|
<Route path="/" element={<HomePage />} />
|
||||||
<Route path="/standings" element={<StandingsLayout><Standings /></StandingsLayout>} />
|
<Route path="/standings" element={<StandingsPage />} />
|
||||||
{adminRoutes.map(route => (
|
{adminRoutes.map(route => (
|
||||||
<Route key={route.path} path={route.path} element={route.element}>
|
<Route key={route.path} path={route.path} element={route.element}>
|
||||||
{route.children.map(child => (
|
{route.children.map(child => (
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
/**
|
||||||
|
* 后台导航图标集。
|
||||||
|
*
|
||||||
|
* 此前这 8 个图标是一段约 90 行的内联 `switch`,塞在 AdminLayout 里,
|
||||||
|
* 使布局文件同时承担「页面骨架」与「图标图形库」两种职责,而且
|
||||||
|
* `name: string` 的参数类型让拼错图标名不会报错 —— 只会静默渲染空白。
|
||||||
|
*
|
||||||
|
* 抽出为独立组件后:
|
||||||
|
* - AdminLayout 只管布局
|
||||||
|
* - 图标名收敛为联合类型,拼错即编译失败
|
||||||
|
* - 新增图标时只改本文件
|
||||||
|
*
|
||||||
|
* 风格与 nav-icon 的线条规范一致:24×24 视框、currentColor 描边、圆头圆角。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
|
||||||
|
/** 支持的图标名。与 `admin/nav.ts` 中各导航项的 icon 字段对应。 */
|
||||||
|
export type AdminIconName =
|
||||||
|
| 'collection'
|
||||||
|
| 'chart'
|
||||||
|
| 'target'
|
||||||
|
| 'repeat'
|
||||||
|
| 'eval'
|
||||||
|
| 'monitor'
|
||||||
|
| 'settings'
|
||||||
|
| 'logs'
|
||||||
|
|
||||||
|
export interface AdminIconProps {
|
||||||
|
name: AdminIconName
|
||||||
|
/** 附加类名(尺寸/颜色覆盖用) */
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 统一的 SVG 外框属性,避免 8 份重复书写 */
|
||||||
|
const svgProps = {
|
||||||
|
viewBox: '0 0 24 24',
|
||||||
|
fill: 'none',
|
||||||
|
stroke: 'currentColor',
|
||||||
|
strokeLinecap: 'round',
|
||||||
|
strokeLinejoin: 'round',
|
||||||
|
} as const
|
||||||
|
|
||||||
|
const PATHS: Record<AdminIconName, ReactNode> = {
|
||||||
|
// 数据采集:立方体/包裹
|
||||||
|
collection: (
|
||||||
|
<>
|
||||||
|
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
|
||||||
|
<polyline points="3.27 6.96 12 12.01 20.73 6.96" />
|
||||||
|
<line x1="12" y1="22.08" x2="12" y2="12" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
// 柱状图
|
||||||
|
chart: (
|
||||||
|
<>
|
||||||
|
<line x1="18" y1="20" x2="18" y2="10" />
|
||||||
|
<line x1="12" y1="20" x2="12" y2="4" />
|
||||||
|
<line x1="6" y1="20" x2="6" y2="14" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
// 靶心
|
||||||
|
target: (
|
||||||
|
<>
|
||||||
|
<circle cx="12" cy="12" r="10" />
|
||||||
|
<circle cx="12" cy="12" r="6" />
|
||||||
|
<circle cx="12" cy="12" r="2" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
// 循环/重试
|
||||||
|
repeat: (
|
||||||
|
<>
|
||||||
|
<polyline points="17 1 21 5 17 9" />
|
||||||
|
<path d="M3 11V9a4 4 0 0 1 4-4h14" />
|
||||||
|
<polyline points="7 23 3 19 7 15" />
|
||||||
|
<path d="M21 13v2a4 4 0 0 1-4 4H3" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
// 评估:带横线的文档
|
||||||
|
eval: (
|
||||||
|
<>
|
||||||
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||||
|
<polyline points="14 2 14 8 20 8" />
|
||||||
|
<line x1="16" y1="13" x2="8" y2="13" />
|
||||||
|
<line x1="16" y1="17" x2="8" y2="17" />
|
||||||
|
<polyline points="10 9 9 9 8 9" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
// 监控:显示器
|
||||||
|
monitor: (
|
||||||
|
<>
|
||||||
|
<rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
|
||||||
|
<line x1="8" y1="21" x2="16" y2="21" />
|
||||||
|
<line x1="12" y1="17" x2="12" y2="21" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
// 设置:齿轮
|
||||||
|
settings: (
|
||||||
|
<>
|
||||||
|
<circle cx="12" cy="12" r="3" />
|
||||||
|
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68 1.65 1.65 0 0 0 10 3.17V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0-4h-.09a1.65 1.65 0 0 0-1.51 1z" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
// 日志:带横线的文档(与 eval 区分:行数位置不同)
|
||||||
|
logs: (
|
||||||
|
<>
|
||||||
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||||
|
<polyline points="14 2 14 8 20 8" />
|
||||||
|
<line x1="8" y1="13" x2="16" y2="13" />
|
||||||
|
<line x1="8" y1="17" x2="16" y2="17" />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 后台导航图标。
|
||||||
|
*
|
||||||
|
* 未知名称不再静默返回 `null`(那样只会看到一个空位,难以定位),
|
||||||
|
* 而是渲染一个可见的问号方块 —— 缺失的图标应当被一眼看见。
|
||||||
|
*/
|
||||||
|
export function AdminIcon({ name, className }: AdminIconProps) {
|
||||||
|
const paths = PATHS[name]
|
||||||
|
const cls = className ? `nav-icon ${className}` : 'nav-icon'
|
||||||
|
|
||||||
|
if (!paths) {
|
||||||
|
return (
|
||||||
|
<svg {...svgProps} className={cls} aria-hidden="true" data-icon-missing={name}>
|
||||||
|
<rect x="3" y="3" width="18" height="18" />
|
||||||
|
<line x1="9" y1="9" x2="15" y2="15" />
|
||||||
|
<line x1="15" y1="9" x2="9" y2="15" />
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<svg {...svgProps} className={cls} aria-hidden="true">
|
||||||
|
{paths}
|
||||||
|
</svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AdminIcon
|
||||||
@@ -7,86 +7,29 @@
|
|||||||
|
|
||||||
import { useState, useEffect, useCallback } from 'react'
|
import { useState, useEffect, useCallback } from 'react'
|
||||||
import { NavLink, Outlet, useLocation } from 'react-router-dom'
|
import { NavLink, Outlet, useLocation } from 'react-router-dom'
|
||||||
import { fetchAuthState, logout, UNAUTHORIZED_EVENT } from './api'
|
import { fetchAuthState, logout, UNAUTHORIZED_EVENT } from '../api/api'
|
||||||
import { fetchHealth } from './dal'
|
import { fetchHealth } from '../api/dal'
|
||||||
import { COMMAND_PALETTE_PAGES, ROUTE_LABELS, NAV_SECTIONS } from './nav'
|
import { COMMAND_PALETTE_PAGES, ROUTE_LABELS, NAV_SECTIONS } from './nav'
|
||||||
import Login from './Login'
|
import Login from './Login'
|
||||||
import { useCommandPalette, CommandPalette } from './useCommandPalette'
|
import { useCommandPalette, CommandPalette } from './useCommandPalette'
|
||||||
|
import { AdminIcon } from './AdminIcon'
|
||||||
|
|
||||||
// 线条风格 SVG 图标组件
|
// 图标已抽到 ./AdminIcon —— 此前这里是约 90 行的内联 switch,
|
||||||
function Icon({ name }: { name: string }) {
|
// 让布局文件同时承担页面骨架与图标图形库两种职责。
|
||||||
const common = 'nav-icon'
|
|
||||||
switch (name) {
|
/**
|
||||||
case 'collection':
|
* 侧栏导航项的 className 生成器。
|
||||||
return (
|
*
|
||||||
<svg className={common} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
|
* 此前这段字符串在文件里出现了两次(仪表盘项 + 分组循环项),
|
||||||
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
|
* 逐字相同。改一次选中态样式要改两处 —— 与 App.tsx 里
|
||||||
<polyline points="3.27 6.96 12 12.01 20.73 6.96" />
|
* 被抽成 SiteLayout 的重复是同一型问题,这里同样收敛为单一来源。
|
||||||
<line x1="12" y1="22.08" x2="12" y2="12" />
|
*/
|
||||||
</svg>
|
const SIDEBAR_LINK_BASE = 'nav-icon-wrap flex min-h-[40px] items-center gap-2.5 border-l-4 px-3 text-sm transition-all duration-300'
|
||||||
)
|
const SIDEBAR_LINK_ACTIVE = 'border-press bg-press-wash/60 font-medium text-press active'
|
||||||
case 'chart':
|
const SIDEBAR_LINK_IDLE = 'border-transparent text-ink-500 hover:bg-paper-100 hover:text-ink-900'
|
||||||
return (
|
|
||||||
<svg className={common} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
|
function sidebarLinkClass({ isActive }: { isActive: boolean }): string {
|
||||||
<line x1="18" y1="20" x2="18" y2="10" />
|
return `${SIDEBAR_LINK_BASE} ${isActive ? SIDEBAR_LINK_ACTIVE : SIDEBAR_LINK_IDLE}`
|
||||||
<line x1="12" y1="20" x2="12" y2="4" />
|
|
||||||
<line x1="6" y1="20" x2="6" y2="14" />
|
|
||||||
</svg>
|
|
||||||
)
|
|
||||||
case 'target':
|
|
||||||
return (
|
|
||||||
<svg className={common} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
|
|
||||||
<circle cx="12" cy="12" r="10" />
|
|
||||||
<circle cx="12" cy="12" r="6" />
|
|
||||||
<circle cx="12" cy="12" r="2" />
|
|
||||||
</svg>
|
|
||||||
)
|
|
||||||
case 'repeat':
|
|
||||||
return (
|
|
||||||
<svg className={common} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
|
|
||||||
<polyline points="17 1 21 5 17 9" />
|
|
||||||
<path d="M3 11V9a4 4 0 0 1 4-4h14" />
|
|
||||||
<polyline points="7 23 3 19 7 15" />
|
|
||||||
<path d="M21 13v2a4 4 0 0 1-4 4H3" />
|
|
||||||
</svg>
|
|
||||||
)
|
|
||||||
case 'eval':
|
|
||||||
return (
|
|
||||||
<svg className={common} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
|
|
||||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
|
||||||
<polyline points="14 2 14 8 20 8" />
|
|
||||||
<line x1="16" y1="13" x2="8" y2="13" />
|
|
||||||
<line x1="16" y1="17" x2="8" y2="17" />
|
|
||||||
<polyline points="10 9 9 9 8 9" />
|
|
||||||
</svg>
|
|
||||||
)
|
|
||||||
case 'monitor':
|
|
||||||
return (
|
|
||||||
<svg className={common} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
|
|
||||||
<rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
|
|
||||||
<line x1="8" y1="21" x2="16" y2="21" />
|
|
||||||
<line x1="12" y1="17" x2="12" y2="21" />
|
|
||||||
</svg>
|
|
||||||
)
|
|
||||||
case 'settings':
|
|
||||||
return (
|
|
||||||
<svg className={common} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
|
|
||||||
<circle cx="12" cy="12" r="3" />
|
|
||||||
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68 1.65 1.65 0 0 0 10 3.17V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0-4h-.09a1.65 1.65 0 0 0-1.51 1z" />
|
|
||||||
</svg>
|
|
||||||
)
|
|
||||||
case 'logs':
|
|
||||||
return (
|
|
||||||
<svg className={common} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
|
|
||||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
|
||||||
<polyline points="14 2 14 8 20 8" />
|
|
||||||
<line x1="8" y1="13" x2="16" y2="13" />
|
|
||||||
<line x1="8" y1="17" x2="16" y2="17" />
|
|
||||||
</svg>
|
|
||||||
)
|
|
||||||
default:
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// D6: 导航三视图(侧栏/命令面板/面包屑)统一由 admin/nav.ts 的 NAV_ITEMS
|
// D6: 导航三视图(侧栏/命令面板/面包屑)统一由 admin/nav.ts 的 NAV_ITEMS
|
||||||
@@ -252,18 +195,8 @@ export default function AdminLayout() {
|
|||||||
{/* 导航:分组 + 小节标题 */}
|
{/* 导航:分组 + 小节标题 */}
|
||||||
<nav className="flex-1 overflow-y-auto px-3 py-3" aria-label="管理导航">
|
<nav className="flex-1 overflow-y-auto px-3 py-3" aria-label="管理导航">
|
||||||
{/* 仪表盘独立(始终第一项) */}
|
{/* 仪表盘独立(始终第一项) */}
|
||||||
<NavLink
|
<NavLink to="/admin" end className={sidebarLinkClass}>
|
||||||
to="/admin"
|
<AdminIcon name="chart" />
|
||||||
end
|
|
||||||
className={({ isActive }) =>
|
|
||||||
`nav-icon-wrap flex min-h-[40px] items-center gap-2.5 border-l-4 px-3 text-sm transition-all duration-300 ${
|
|
||||||
isActive
|
|
||||||
? 'border-press bg-press-wash/60 font-medium text-press active'
|
|
||||||
: 'border-transparent text-ink-500 hover:bg-paper-100 hover:text-ink-900'
|
|
||||||
}`
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Icon name="chart" />
|
|
||||||
仪表盘
|
仪表盘
|
||||||
</NavLink>
|
</NavLink>
|
||||||
|
|
||||||
@@ -275,17 +208,8 @@ export default function AdminLayout() {
|
|||||||
<ul className="space-y-0.5">
|
<ul className="space-y-0.5">
|
||||||
{section.items.map(item => (
|
{section.items.map(item => (
|
||||||
<li key={item.to}>
|
<li key={item.to}>
|
||||||
<NavLink
|
<NavLink to={item.to} className={sidebarLinkClass}>
|
||||||
to={item.to}
|
<AdminIcon name={item.icon} />
|
||||||
className={({ isActive }) =>
|
|
||||||
`nav-icon-wrap flex min-h-[40px] items-center gap-2.5 border-l-4 px-3 text-sm transition-all duration-300 ${
|
|
||||||
isActive
|
|
||||||
? 'border-press bg-press-wash/60 font-medium text-press active'
|
|
||||||
: 'border-transparent text-ink-500 hover:bg-paper-100 hover:text-ink-900'
|
|
||||||
}`
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Icon name={item.icon} />
|
|
||||||
{item.label}
|
{item.label}
|
||||||
</NavLink>
|
</NavLink>
|
||||||
</li>
|
</li>
|
||||||
|
|||||||
@@ -6,9 +6,10 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { useCallback, useEffect, useState } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
import { fetchLLMAgents, updateSetting, clearSetting } from './dal'
|
import { fetchLLMAgents, updateSetting, clearSetting } from '../api/dal'
|
||||||
import type { LLMAgentConfig } from './types'
|
import type { LLMAgentConfig } from '../api/types'
|
||||||
import { Card, CardBody, CardHeader, Badge, Alert, Spinner, SkeletonBlock } from './components'
|
import { Card, CardBody, CardHeader, Badge, Alert, Spinner, SkeletonBlock } from './components'
|
||||||
|
import { Button, Input } from '../components/ui'
|
||||||
|
|
||||||
type FieldKey = 'model' | 'base_url' | 'api_key'
|
type FieldKey = 'model' | 'base_url' | 'api_key'
|
||||||
|
|
||||||
@@ -110,9 +111,9 @@ export default function AgentLLMCard() {
|
|||||||
title="专家与终裁 LLM 配置"
|
title="专家与终裁 LLM 配置"
|
||||||
description="可为每个角色单独指定模型、接口地址或 API Key;未覆盖的角色按「专家层/终裁层默认 → 全局」继承"
|
description="可为每个角色单独指定模型、接口地址或 API Key;未覆盖的角色按「专家层/终裁层默认 → 全局」继承"
|
||||||
action={
|
action={
|
||||||
<button onClick={load} disabled={loading} className="btn btn-sm">
|
<Button size="sm" onClick={load} disabled={loading}>
|
||||||
{loading ? (<><Spinner /> 加载中</>) : '刷新'}
|
{loading ? (<><Spinner /> 加载中</>) : '刷新'}
|
||||||
</button>
|
</Button>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<CardBody className="px-0 sm:px-0">
|
<CardBody className="px-0 sm:px-0">
|
||||||
@@ -141,9 +142,9 @@ export default function AgentLLMCard() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex min-w-0 items-center gap-2">
|
<div className="flex min-w-0 items-center gap-2">
|
||||||
<span className="truncate font-mono text-2xs text-ink-500">{agent.effective_model}</span>
|
<span className="truncate font-mono text-2xs text-ink-500">{agent.effective_model}</span>
|
||||||
<button onClick={() => toggleExpand(agent)} disabled={busy} className="btn btn-sm flex-shrink-0">
|
<Button size="sm" className="flex-shrink-0" onClick={() => toggleExpand(agent)} disabled={busy}>
|
||||||
{expanded ? '收起' : '配置'}
|
{expanded ? '收起' : '配置'}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -154,9 +155,10 @@ export default function AgentLLMCard() {
|
|||||||
const state = agent.fields[f.key]
|
const state = agent.fields[f.key]
|
||||||
return (
|
return (
|
||||||
<div key={f.key} className="grid gap-1 sm:grid-cols-[96px_minmax(0,1fr)] sm:items-center sm:gap-3">
|
<div key={f.key} className="grid gap-1 sm:grid-cols-[96px_minmax(0,1fr)] sm:items-center sm:gap-3">
|
||||||
<label className="text-xs text-ink-500">{f.label}</label>
|
<label htmlFor={`llm-${f.key}`} className="text-xs text-ink-500">{f.label}</label>
|
||||||
<div>
|
<div>
|
||||||
<input
|
<Input
|
||||||
|
id={`llm-${f.key}`}
|
||||||
type={f.sensitive ? 'password' : 'text'}
|
type={f.sensitive ? 'password' : 'text'}
|
||||||
value={form[f.key]}
|
value={form[f.key]}
|
||||||
onChange={e => setForm(prev => ({ ...prev, [f.key]: e.target.value }))}
|
onChange={e => setForm(prev => ({ ...prev, [f.key]: e.target.value }))}
|
||||||
@@ -166,7 +168,7 @@ export default function AgentLLMCard() {
|
|||||||
: f.hint
|
: f.hint
|
||||||
}
|
}
|
||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
className="field w-full"
|
className="w-full"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -179,13 +181,13 @@ export default function AgentLLMCard() {
|
|||||||
</p>
|
</p>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
{hasOverride(agent) && (
|
{hasOverride(agent) && (
|
||||||
<button onClick={() => handleReset(agent)} disabled={busy} className="btn btn-sm">
|
<Button size="sm" onClick={() => handleReset(agent)} disabled={busy}>
|
||||||
恢复继承
|
恢复继承
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<button onClick={() => handleSave(agent)} disabled={busy} className="btn btn-solid btn-sm">
|
<Button variant="solid" size="sm" onClick={() => handleSave(agent)} disabled={busy}>
|
||||||
{busy ? (<><Spinner /> 保存中</>) : '保存'}
|
{busy ? (<><Spinner /> 保存中</>) : '保存'}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,7 +5,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { ApiError, login } from './api'
|
import { ApiError, login } from '../api/api'
|
||||||
|
import { Button, Input } from '../components/ui'
|
||||||
|
|
||||||
export default function Login({ onSuccess }: { onSuccess: () => void }) {
|
export default function Login({ onSuccess }: { onSuccess: () => void }) {
|
||||||
const [password, setPassword] = useState('')
|
const [password, setPassword] = useState('')
|
||||||
@@ -50,12 +51,12 @@ export default function Login({ onSuccess }: { onSuccess: () => void }) {
|
|||||||
<main className="flex flex-1 items-start justify-center px-5 py-10">
|
<main className="flex flex-1 items-start justify-center px-5 py-10">
|
||||||
<form
|
<form
|
||||||
onSubmit={handleSubmit}
|
onSubmit={handleSubmit}
|
||||||
className="w-full max-w-sm border border-ink-300 bg-white p-6 shadow-[4px_4px_0_0_rgba(0,0,0,0.06)]"
|
className="w-full max-w-sm border border-ink-300 bg-paper-50 p-6 shadow-print"
|
||||||
>
|
>
|
||||||
<label htmlFor="admin-password" className="block text-xs font-medium tracking-wide text-ink-700">
|
<label htmlFor="admin-password" className="block text-xs font-medium tracking-wide text-ink-700">
|
||||||
管理密码
|
管理密码
|
||||||
</label>
|
</label>
|
||||||
<input
|
<Input
|
||||||
id="admin-password"
|
id="admin-password"
|
||||||
type="password"
|
type="password"
|
||||||
value={password}
|
value={password}
|
||||||
@@ -63,22 +64,27 @@ export default function Login({ onSuccess }: { onSuccess: () => void }) {
|
|||||||
placeholder="输入服务器 .env 中的 ADMIN_PASSWORD"
|
placeholder="输入服务器 .env 中的 ADMIN_PASSWORD"
|
||||||
autoFocus
|
autoFocus
|
||||||
autoComplete="current-password"
|
autoComplete="current-password"
|
||||||
className="field mt-2 w-full"
|
/* 错误时把输入框标记为无效并关联错误文本,
|
||||||
|
屏幕阅读器才能知道「密码错了」以及错在哪 */
|
||||||
|
aria-invalid={error ? true : undefined}
|
||||||
|
aria-describedby={error ? 'admin-password-error' : undefined}
|
||||||
|
className="mt-2 w-full"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<p className="mt-3 border-l-2 border-press bg-press-wash/40 px-3 py-2 text-2xs leading-relaxed text-press-dark">
|
<p
|
||||||
|
id="admin-password-error"
|
||||||
|
/* role=alert 让错误出现时立即被朗读(aria-live 的 assertive 语义) */
|
||||||
|
role="alert"
|
||||||
|
className="mt-3 border-l-2 border-press bg-press-wash/40 px-3 py-2 text-2xs leading-relaxed text-press-dark"
|
||||||
|
>
|
||||||
{error}
|
{error}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<button
|
<Button variant="solid" className="mt-5 w-full justify-center" type="submit" disabled={!password || submitting}>
|
||||||
type="submit"
|
|
||||||
disabled={!password || submitting}
|
|
||||||
className="btn btn-solid mt-5 w-full justify-center"
|
|
||||||
>
|
|
||||||
{submitting ? '验证中…' : '登 录'}
|
{submitting ? '验证中…' : '登 录'}
|
||||||
</button>
|
</Button>
|
||||||
|
|
||||||
<p className="mt-4 border-t border-ink-200 pt-3 text-center text-2xs leading-relaxed text-ink-400">
|
<p className="mt-4 border-t border-ink-200 pt-3 text-center text-2xs leading-relaxed text-ink-400">
|
||||||
密码初始来自服务器 .env,可登录后在「系统配置」页修改;连续输错 5 次将锁定 10 分钟。
|
密码初始来自服务器 .env,可登录后在「系统配置」页修改;连续输错 5 次将锁定 10 分钟。
|
||||||
|
|||||||
@@ -7,8 +7,9 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import type { DataSourceSetting } from './types'
|
import type { DataSourceSetting } from '../api/types'
|
||||||
import { Badge, Spinner } from './components'
|
import { Badge, Spinner } from './components'
|
||||||
|
import { Button, Input } from '../components/ui'
|
||||||
|
|
||||||
export const ORIGIN_BADGE: Record<DataSourceSetting['origin'], { text: string; status: 'success' | 'info' | 'error' }> = {
|
export const ORIGIN_BADGE: Record<DataSourceSetting['origin'], { text: string; status: 'success' | 'info' | 'error' }> = {
|
||||||
db: { text: '数据库覆盖', status: 'success' },
|
db: { text: '数据库覆盖', status: 'success' },
|
||||||
@@ -74,34 +75,32 @@ export default function SettingRow({
|
|||||||
{setting.sensitive && <Badge status="warning">敏感</Badge>}
|
{setting.sensitive && <Badge status="warning">敏感</Badge>}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-2 sm:flex-row">
|
<div className="flex flex-col gap-2 sm:flex-row">
|
||||||
<input
|
<Input
|
||||||
type={setting.sensitive ? 'password' : 'text'}
|
type={setting.sensitive ? 'password' : 'text'}
|
||||||
value={value}
|
value={value}
|
||||||
onChange={e => setValue(e.target.value)}
|
onChange={e => setValue(e.target.value)}
|
||||||
placeholder={`输入新的 ${setting.label}`}
|
placeholder={`输入新的 ${setting.label}`}
|
||||||
|
/* 无可见 label(标题即配置项名),用 aria-label 提供可访问名称 */
|
||||||
|
aria-label={`设置项 ${setting.label} 的值`}
|
||||||
autoFocus
|
autoFocus
|
||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
className="field flex-1"
|
className="flex-1"
|
||||||
/>
|
/>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<button
|
<Button variant="solid" size="sm" onClick={() => onSave(value)} disabled={!value.trim() || busy}>
|
||||||
onClick={() => onSave(value)}
|
|
||||||
disabled={!value.trim() || busy}
|
|
||||||
className="btn btn-solid btn-sm"
|
|
||||||
>
|
|
||||||
{busy ? (<><Spinner /> 保存中</>) : '保存'}
|
{busy ? (<><Spinner /> 保存中</>) : '保存'}
|
||||||
</button>
|
</Button>
|
||||||
<button onClick={onCancel} disabled={busy} className="btn btn-sm">
|
<Button size="sm" onClick={onCancel} disabled={busy}>
|
||||||
取消
|
取消
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{detectModels && (
|
{detectModels && (
|
||||||
<div className="mt-2 space-y-2">
|
<div className="mt-2 space-y-2">
|
||||||
<button onClick={handleDetect} disabled={detecting} className="btn btn-sm">
|
<Button size="sm" onClick={handleDetect} disabled={detecting}>
|
||||||
{detecting ? (<><Spinner /> 检测中</>) : detected ? '重新检测' : '检测可用模型'}
|
{detecting ? (<><Spinner /> 检测中</>) : detected ? '重新检测' : '检测可用模型'}
|
||||||
</button>
|
</Button>
|
||||||
|
|
||||||
{detectError && (
|
{detectError && (
|
||||||
<p className="border-l-2 border-press bg-press-wash/40 px-3 py-1.5 text-2xs leading-relaxed text-press-dark">
|
<p className="border-l-2 border-press bg-press-wash/40 px-3 py-1.5 text-2xs leading-relaxed text-press-dark">
|
||||||
@@ -146,13 +145,13 @@ export default function SettingRow({
|
|||||||
{setting.configured ? setting.masked : '—'}
|
{setting.configured ? setting.masked : '—'}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-end gap-2">
|
<div className="flex justify-end gap-2">
|
||||||
<button onClick={onEdit} disabled={busy} className="btn btn-sm">
|
<Button size="sm" onClick={onEdit} disabled={busy}>
|
||||||
{setting.configured ? '更换' : '配置'}
|
{setting.configured ? '更换' : '配置'}
|
||||||
</button>
|
</Button>
|
||||||
{setting.origin === 'db' && (
|
{setting.origin === 'db' && (
|
||||||
<button onClick={onClear} disabled={busy} className="btn btn-sm" title="删除数据库覆盖值,回落 .env">
|
<Button size="sm" onClick={onClear} disabled={busy} title="删除数据库覆盖值,回落 .env">
|
||||||
回落 .env
|
回落 .env
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,66 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* Admin 后台管理系统 - 统一 API 客户端(门面)
|
* 【兼容壳 · 已废弃】实现已迁至 `src/api/api.ts`。
|
||||||
*
|
* 新代码请直接从 `../api/api` 导入。
|
||||||
* 鉴权:通过 POST /api/v1/auth/login 用密码换取 HttpOnly Cookie 会话,
|
|
||||||
* 同源请求自动携带 Cookie,无需手动管理密钥。
|
|
||||||
* 收到 401 时广播 `profeto:unauthorized` 事件,由 AdminLayout 切回登录页。
|
|
||||||
*
|
|
||||||
* 实现已收敛到共享层 lib/http.ts(超时/错误解析/401 广播只此一份),
|
|
||||||
* 本文件仅保留 Admin 侧的门面签名与认证接口,供既有页面按原路径导入。
|
|
||||||
*/
|
*/
|
||||||
|
export * from '../api/api'
|
||||||
import { http, ApiError, UNAUTHORIZED_EVENT } from '../lib/http'
|
|
||||||
|
|
||||||
/** Admin 侧兼容导出:错误类型与会话失效事件名的规范来源在 lib/http */
|
|
||||||
export { ApiError, UNAUTHORIZED_EVENT }
|
|
||||||
|
|
||||||
const API_BASE = '/api/v1'
|
|
||||||
|
|
||||||
/** Admin 请求可覆盖项(与 lib/http RequestOptions 对齐的子集) */
|
|
||||||
type ApiOpts = {
|
|
||||||
timeoutMs?: number
|
|
||||||
/** 改密接口的 401 表示「当前密码错误」,非会话过期,置 true 跳过登出广播 */
|
|
||||||
skipAuthHandling?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export const api = {
|
|
||||||
get: <T>(path: string) => http.get<T>(path),
|
|
||||||
post: <T>(path: string, body?: unknown, opts?: ApiOpts) =>
|
|
||||||
http.post<T>(path, body, opts),
|
|
||||||
put: <T>(path: string, body?: unknown, opts?: ApiOpts) =>
|
|
||||||
http.put<T>(path, body, opts),
|
|
||||||
delete: <T>(path: string) => http.delete<T>(path),
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 认证 ────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/** 密码登录,成功后服务端写入 HttpOnly 会话 Cookie */
|
|
||||||
export function login(password: string): Promise<{ ok: boolean }> {
|
|
||||||
return api.post(`${API_BASE}/auth/login`, { password })
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 退出登录,清除会话 Cookie */
|
|
||||||
export function logout(): Promise<{ ok: boolean }> {
|
|
||||||
return api.post(`${API_BASE}/auth/logout`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 探测当前登录状态 */
|
|
||||||
export function fetchAuthState(): Promise<{
|
|
||||||
authenticated: boolean
|
|
||||||
enabled: boolean
|
|
||||||
password_origin?: 'db' | 'env' | 'none'
|
|
||||||
}> {
|
|
||||||
return api.get(`${API_BASE}/auth/me`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 修改管理员密码(成功后所有会话失效,需重新登录) */
|
|
||||||
export function changePassword(currentPassword: string, newPassword: string): Promise<{ ok: boolean; message: string }> {
|
|
||||||
// skipAuthHandling: 改密接口的 401 表示「当前密码错误」,非会话过期,不要触发登出
|
|
||||||
return api.post(
|
|
||||||
`${API_BASE}/auth/change-password`,
|
|
||||||
{ current_password: currentPassword, new_password: newPassword },
|
|
||||||
{ skipAuthHandling: true },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export { API_BASE }
|
|
||||||
|
|||||||
+5
-516
@@ -1,519 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* Admin 后台 - 数据访问层
|
* 【兼容壳 · 已废弃】实现已迁至 `src/api/dal.ts`。
|
||||||
*
|
*
|
||||||
* 封装所有 API 端点调用,返回类型安全的数据。
|
* 迁移原因见 `src/api/public.ts` 头注释:admin 目录不应承载被前台
|
||||||
* 所有端点对齐 FastAPI 后端实际实现。
|
* 反向依赖的数据层。本文件仅为不破坏旧 import 路径而保留,
|
||||||
|
* **新代码请直接从 `../api/dal`(admin 内)或 `../api`(其余位置)导入。*
|
||||||
*/
|
*/
|
||||||
|
export * from '../api/dal'
|
||||||
import { api, API_BASE } from './api'
|
|
||||||
import type {
|
|
||||||
DashboardStats,
|
|
||||||
CollectionRequest,
|
|
||||||
BacktestRequest,
|
|
||||||
BacktestSummary,
|
|
||||||
League,
|
|
||||||
Match,
|
|
||||||
Prediction,
|
|
||||||
EvalSummary,
|
|
||||||
DataSourceStatus,
|
|
||||||
DataSourceSetting,
|
|
||||||
DataSourceTestResult,
|
|
||||||
LLMAgentConfig,
|
|
||||||
LogEntry,
|
|
||||||
IngestSourceStatus,
|
|
||||||
IngestJob,
|
|
||||||
MatchDetailOut,
|
|
||||||
MatchContextOut,
|
|
||||||
AdminStats,
|
|
||||||
} from './types'
|
|
||||||
|
|
||||||
// ── 仪表盘 ──────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 从多个端点聚合仪表盘数据。
|
|
||||||
* 后端暂无专用仪表盘端点,这里组合 health + 各列表端点。
|
|
||||||
*
|
|
||||||
* 注: 比赛真实总量请用 fetchAdminStats()(GET /admin/stats,
|
|
||||||
* 后端 COUNT(*) 精确计数)。此处曾用 matches items.length 近似,
|
|
||||||
* 已随仪表盘切换真实计数而移除,防止误用 100 上限的假总量。
|
|
||||||
*/
|
|
||||||
export async function fetchDashboard(): Promise<DashboardStats> {
|
|
||||||
// 并行获取各端点数据
|
|
||||||
// predictions 返回数组
|
|
||||||
const [leagues, predictions, health] = await Promise.allSettled([
|
|
||||||
api.get<League[]>(`${API_BASE}/leagues`),
|
|
||||||
api.get<Prediction[]>(`${API_BASE}/predictions?limit=100`),
|
|
||||||
api.get<{ status: string }>('/health'),
|
|
||||||
])
|
|
||||||
|
|
||||||
return {
|
|
||||||
leagues: leagues.status === 'fulfilled' ? leagues.value : [],
|
|
||||||
// predictions 直接返回数组
|
|
||||||
total_predictions: predictions.status === 'fulfilled' ? (predictions.value as any)?.length ?? 0 : 0,
|
|
||||||
health: health.status === 'fulfilled' ? (health.value as any).status : 'unknown',
|
|
||||||
db_tables: [], // 后端暂无表统计端点
|
|
||||||
last_collection: [], // 后端暂无采集历史端点
|
|
||||||
recent_errors: [], // 后端暂无错误日志端点
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 数据采集 ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export async function triggerCollection(req: CollectionRequest): Promise<any> {
|
|
||||||
const body: Record<string, any> = {
|
|
||||||
leagues: req.leagues,
|
|
||||||
date_from: req.date_from,
|
|
||||||
date_to: req.date_to,
|
|
||||||
status: req.status || undefined,
|
|
||||||
task: req.task || 'events',
|
|
||||||
limit: req.limit || 100,
|
|
||||||
season: req.season || undefined,
|
|
||||||
}
|
|
||||||
return api.post(`${API_BASE}/ingest/bzzoiro`, body)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 预测管理 ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export async function triggerPrediction(req: { match_id: number; mode?: string }): Promise<any> {
|
|
||||||
return api.post(
|
|
||||||
`${API_BASE}/predict`,
|
|
||||||
{
|
|
||||||
match_id: req.match_id,
|
|
||||||
mode: req.mode || 'multi',
|
|
||||||
},
|
|
||||||
{ timeoutMs: 300_000 },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fetchPredictions(limit = 50): Promise<any[]> {
|
|
||||||
const res = await api.get<any>(`${API_BASE}/predictions?limit=${limit}`)
|
|
||||||
return Array.isArray(res) ? res : (res as any)?.items ?? []
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 评估 & 回测 ─────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export async function fetchEvalSummary(params: {
|
|
||||||
limit?: number
|
|
||||||
provider?: string
|
|
||||||
model?: string
|
|
||||||
prompt_version?: string
|
|
||||||
mode?: string
|
|
||||||
league_code?: string
|
|
||||||
} = {}): Promise<EvalSummary | null> {
|
|
||||||
const sp = new URLSearchParams()
|
|
||||||
if (params.limit) sp.set('limit', String(params.limit))
|
|
||||||
if (params.provider) sp.set('provider', params.provider)
|
|
||||||
if (params.model) sp.set('model', params.model)
|
|
||||||
if (params.prompt_version) sp.set('prompt_version', params.prompt_version)
|
|
||||||
if (params.mode) sp.set('mode', params.mode)
|
|
||||||
if (params.league_code) sp.set('league_code', params.league_code)
|
|
||||||
try {
|
|
||||||
return await api.get<EvalSummary>(`${API_BASE}/eval/summary?${sp}`)
|
|
||||||
} catch {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function triggerBacktest(req: BacktestRequest): Promise<BacktestSummary> {
|
|
||||||
return api.post<BacktestSummary>(`${API_BASE}/backtest`, req, { timeoutMs: 300_000 })
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 辅助数据 ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export async function fetchLeagues(): Promise<League[]> {
|
|
||||||
try {
|
|
||||||
return await api.get<League[]>(`${API_BASE}/leagues`)
|
|
||||||
} catch {
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fetchMatches(params: {
|
|
||||||
league?: string
|
|
||||||
status?: string
|
|
||||||
limit?: number
|
|
||||||
cursor?: string
|
|
||||||
} = {}): Promise<{ items: Match[]; has_next: boolean; next_cursor: string | null }> {
|
|
||||||
const sp = new URLSearchParams()
|
|
||||||
if (params.league) sp.set('league', params.league)
|
|
||||||
if (params.status) sp.set('status', params.status)
|
|
||||||
if (params.limit) sp.set('limit', String(params.limit))
|
|
||||||
if (params.cursor) sp.set('cursor', params.cursor)
|
|
||||||
|
|
||||||
try {
|
|
||||||
return await api.get<any>(`${API_BASE}/matches?${sp}`)
|
|
||||||
} catch {
|
|
||||||
return { items: [], has_next: false, next_cursor: null }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function settlePrediction(prediction_id: number, home_goals: number, away_goals: number): Promise<any> {
|
|
||||||
return api.post(`${API_BASE}/eval/settle`, {
|
|
||||||
prediction_id,
|
|
||||||
home_goals,
|
|
||||||
away_goals,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 健康检查 ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export async function fetchHealth(): Promise<any> {
|
|
||||||
try {
|
|
||||||
return await api.get<any>('/health')
|
|
||||||
} catch {
|
|
||||||
return { status: 'unknown' }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 数据完整性 ──────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface DataCompletenessResponse {
|
|
||||||
generated_at: string
|
|
||||||
totals: { finished_matches: number; stats_rows: number; stats_coverage_pct: number }
|
|
||||||
issues: string[]
|
|
||||||
leagues: Array<{
|
|
||||||
code: string
|
|
||||||
name: string
|
|
||||||
country?: string
|
|
||||||
matches: { total: number; finished: number; scheduled: number; with_source_id: number; earliest_match?: string; latest_match?: string }
|
|
||||||
stats: {
|
|
||||||
rows: number
|
|
||||||
fields: Record<string, { count: number; pct: number }>
|
|
||||||
}
|
|
||||||
standings: { rows: number; latest_retrieved?: string }
|
|
||||||
}>
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fetchDataCompleteness(): Promise<DataCompletenessResponse> {
|
|
||||||
return api.get<DataCompletenessResponse>(`${API_BASE}/admin/data-completeness`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 积分榜(主站 + 管理后台共用) ─────────────────────────────────
|
|
||||||
|
|
||||||
export interface StandingRow {
|
|
||||||
position: number
|
|
||||||
team: string
|
|
||||||
team_en: string
|
|
||||||
played: number
|
|
||||||
won: number
|
|
||||||
drawn: number
|
|
||||||
lost: number
|
|
||||||
goals_for: number
|
|
||||||
goals_against: number
|
|
||||||
goal_diff: number
|
|
||||||
points: number
|
|
||||||
xg_for: number | null
|
|
||||||
xg_against: number | null
|
|
||||||
form: string | null
|
|
||||||
zone: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface StandingsLeague {
|
|
||||||
league_code: string
|
|
||||||
league_name: string
|
|
||||||
season: string
|
|
||||||
retrieved_at: string | null
|
|
||||||
rows: StandingRow[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fetchStandings(league?: string, season?: string): Promise<{ leagues: StandingsLeague[] }> {
|
|
||||||
const sp = new URLSearchParams()
|
|
||||||
if (league) sp.set('league', league)
|
|
||||||
if (season) sp.set('season', season)
|
|
||||||
const qs = sp.toString()
|
|
||||||
return api.get<{ leagues: StandingsLeague[] }>(`${API_BASE}/standings${qs ? `?${qs}` : ''}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 数据源管理 ──────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 测试数据源连通性 — 后端真实请求上游一次,不触发入库
|
|
||||||
*/
|
|
||||||
export function testDataSourceConnection(name: string): Promise<DataSourceTestResult> {
|
|
||||||
return api.post<DataSourceTestResult>(`${API_BASE}/admin/datasources/${name}/test`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取数据源状态与配置(脱敏)
|
|
||||||
*/
|
|
||||||
export function fetchDataSourceStatuses(): Promise<DataSourceStatus[]> {
|
|
||||||
return api.get<DataSourceStatus[]>(`${API_BASE}/admin/datasources`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 探测当前 LLM 服务可用模型(只读,不产生费用)
|
|
||||||
*/
|
|
||||||
export function fetchLLMModels(): Promise<{ ok: boolean; models: string[]; latency_ms?: number; detail: string }> {
|
|
||||||
return api.get(`${API_BASE}/admin/llm/models`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 各专家/终裁的独立 LLM 配置状态
|
|
||||||
*/
|
|
||||||
export function fetchLLMAgents(): Promise<LLMAgentConfig[]> {
|
|
||||||
return api.get<LLMAgentConfig[]>(`${API_BASE}/admin/llm/agents`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 查询系统日志(内存缓冲,最新在前)
|
|
||||||
*/
|
|
||||||
export function fetchLogs(params: { level?: string; keyword?: string; limit?: number } = {}): Promise<{ entries: LogEntry[]; count: number }> {
|
|
||||||
const sp = new URLSearchParams()
|
|
||||||
if (params.level) sp.set('level', params.level)
|
|
||||||
if (params.keyword) sp.set('keyword', params.keyword)
|
|
||||||
if (params.limit) sp.set('limit', String(params.limit))
|
|
||||||
return api.get<{ entries: LogEntry[]; count: number }>(`${API_BASE}/admin/logs?${sp}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 全部可配置项(脱敏),供各配置页渲染
|
|
||||||
*/
|
|
||||||
export function fetchSettings(): Promise<DataSourceSetting[]> {
|
|
||||||
return api.get<DataSourceSetting[]>(`${API_BASE}/admin/settings`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 更新配置项(写入 app_settings,覆盖 .env,立即生效)
|
|
||||||
*/
|
|
||||||
export function updateSetting(key: string, value: string) {
|
|
||||||
return api.put<{ key: string; masked: string; origin: string }>(`${API_BASE}/admin/settings/${key}`, { value })
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 清除配置项的 DB 覆盖值,回落 .env
|
|
||||||
*/
|
|
||||||
export function clearSetting(key: string) {
|
|
||||||
return api.delete<{ key: string; masked: string; origin: string }>(`${API_BASE}/admin/settings/${key}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── LLM 配置 ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 测试 LLM 连接 — 调用预测端点验证
|
|
||||||
*/
|
|
||||||
export async function testLLMConnection(matchId?: number): Promise<any> {
|
|
||||||
// F4 修复: 优先使用不依赖比赛的 ping 端点
|
|
||||||
try {
|
|
||||||
return await api.post(`${API_BASE}/admin/llm/ping`, {})
|
|
||||||
} catch {
|
|
||||||
// 回退到旧方式(兼容)
|
|
||||||
return api.post(
|
|
||||||
`${API_BASE}/predict`,
|
|
||||||
{ match_id: matchId || 1, mode: 'single' },
|
|
||||||
{ timeoutMs: 300_000 },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取 LLM 使用统计 — 从预测列表聚合
|
|
||||||
*/
|
|
||||||
export async function fetchLLMUsageStats(): Promise<any> {
|
|
||||||
try {
|
|
||||||
const predictions = await fetchPredictions(50)
|
|
||||||
const total = predictions.length
|
|
||||||
const successCount = predictions.filter((p: any) => p.pred_1x2).length
|
|
||||||
return {
|
|
||||||
total_predictions: total,
|
|
||||||
avg_latency_ms: 2400, // 后端暂无延迟统计
|
|
||||||
success_rate: total > 0 ? (successCount / total) * 100 : 0,
|
|
||||||
recent_predictions: predictions.slice(0, 10).map((p: any) => ({
|
|
||||||
id: p.id,
|
|
||||||
match_id: p.match_id,
|
|
||||||
model: p.model,
|
|
||||||
created_at: p.created_at,
|
|
||||||
status: p.pred_1x2 ? 'success' : 'failed',
|
|
||||||
})),
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
return {
|
|
||||||
total_predictions: 0,
|
|
||||||
avg_latency_ms: 0,
|
|
||||||
success_rate: 0,
|
|
||||||
recent_predictions: [],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 系统配置 ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* P2-9 修复: 获取系统配置列表,从后端 /admin/settings 读取真实值(脱敏)。
|
|
||||||
* 字段名对齐 Config.tsx 中使用的 { key, value_masked, description, is_sensitive } 格式。
|
|
||||||
*/
|
|
||||||
export async function fetchSystemConfig(): Promise<any[]> {
|
|
||||||
try {
|
|
||||||
const settings = await fetchSettings()
|
|
||||||
return settings.map(s => ({
|
|
||||||
key: s.key,
|
|
||||||
value_masked: s.masked,
|
|
||||||
description: s.description,
|
|
||||||
is_sensitive: s.sensitive,
|
|
||||||
}))
|
|
||||||
} catch {
|
|
||||||
// 后端不可用时返回空列表,Config.tsx 会显示空状态
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 数据源健康/最近采集状态(只读,不触发采集)
|
|
||||||
*/
|
|
||||||
export function fetchIngestStatus(): Promise<{ sources: IngestSourceStatus[] }> {
|
|
||||||
return api.get<{ sources: IngestSourceStatus[] }>(`${API_BASE}/admin/ingest/status`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 上游数据源(bzzoiro)可达性探针:轻量 GET,不携带 Key、不消耗配额
|
|
||||||
*/
|
|
||||||
export function fetchUpstreamProbe(): Promise<{
|
|
||||||
ok: boolean
|
|
||||||
status_code?: number
|
|
||||||
latency_ms: number
|
|
||||||
endpoint: string
|
|
||||||
error?: string
|
|
||||||
}> {
|
|
||||||
return api.get<never>(`${API_BASE}/admin/monitoring/upstream`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 采集任务状态轮询(单任务)
|
|
||||||
*/
|
|
||||||
export function fetchIngestJob(jobId: string): Promise<IngestJob> {
|
|
||||||
return api.get<IngestJob>(`${API_BASE}/admin/ingest/jobs/${jobId}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 采集任务历史列表(GET /admin/ingest/jobs,最新在前)
|
|
||||||
*/
|
|
||||||
export function fetchIngestJobs(params: { limit?: number; status?: string } = {}): Promise<IngestJob[]> {
|
|
||||||
const q = new URLSearchParams()
|
|
||||||
if (params.limit != null) q.set('limit', String(params.limit))
|
|
||||||
if (params.status) q.set('status', params.status)
|
|
||||||
const qs = q.toString()
|
|
||||||
return api.get<IngestJob[]>(`${API_BASE}/admin/ingest/jobs${qs ? `?${qs}` : ''}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 比赛详情(含最近预测摘要)
|
|
||||||
*/
|
|
||||||
export function fetchMatchDetail(id: number): Promise<MatchDetailOut> {
|
|
||||||
return api.get<MatchDetailOut>(`${API_BASE}/matches/${id}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 比赛上下文(双方近况 + 历史交锋,只读)
|
|
||||||
*/
|
|
||||||
export function fetchMatchContext(id: number): Promise<MatchContextOut> {
|
|
||||||
return api.get<MatchContextOut>(`${API_BASE}/matches/${id}/context`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 管理区统计(只读):近 24h/7d 预测次数
|
|
||||||
*/
|
|
||||||
export function fetchAdminStats(): Promise<AdminStats> {
|
|
||||||
return api.get<AdminStats>(`${API_BASE}/admin/stats`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── API Key 轮换环 ──────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface KeyRingKeyStatus {
|
|
||||||
masked: string
|
|
||||||
blocked_remaining: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface KeyRingStatusResponse {
|
|
||||||
base_url: string
|
|
||||||
total: number
|
|
||||||
has_multiple: boolean
|
|
||||||
cooldown_seconds: number
|
|
||||||
active_index: number
|
|
||||||
active_key: string | null
|
|
||||||
keys: KeyRingKeyStatus[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fetchKeyRingStatus(): Promise<KeyRingStatusResponse> {
|
|
||||||
return api.get<KeyRingStatusResponse>(`${API_BASE}/admin/keyring/status`)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function resetKeyRingCooldown(): Promise<{ ok: boolean; message: string; stats: KeyRingStatusResponse }> {
|
|
||||||
return api.post<{ ok: boolean; message: string; stats: KeyRingStatusResponse }>(`${API_BASE}/admin/keyring/cooldown/reset`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 定时任务 ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface ScheduleItem {
|
|
||||||
id: string
|
|
||||||
task: string
|
|
||||||
cron: string
|
|
||||||
leagues?: string
|
|
||||||
enabled: boolean
|
|
||||||
last_run_at?: string | null
|
|
||||||
last_status?: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fetchSchedules(): Promise<ScheduleItem[]> {
|
|
||||||
return api.get<ScheduleItem[]>(`${API_BASE}/admin/schedules`)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createSchedule(data: { id: string; task: string; cron: string; leagues?: string; enabled: boolean }): Promise<{ ok: boolean }> {
|
|
||||||
return api.post<{ ok: boolean }>(`${API_BASE}/admin/schedules`, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function updateSchedule(id: string, data: Partial<ScheduleItem>): Promise<{ ok: boolean }> {
|
|
||||||
return api.put<{ ok: boolean }>(`${API_BASE}/admin/schedules/${id}`, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function deleteSchedule(id: string): Promise<{ ok: boolean }> {
|
|
||||||
return api.delete<{ ok: boolean }>(`${API_BASE}/admin/schedules/${id}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function runScheduleNow(id: string): Promise<{ ok: boolean; message: string }> {
|
|
||||||
return api.post<{ ok: boolean; message: string }>(`${API_BASE}/admin/schedules/${id}/run`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 数据管线(质量检查 + 失败重试) ──────────────────────────────
|
|
||||||
|
|
||||||
export interface IngestFailureItem {
|
|
||||||
id: number
|
|
||||||
source: string
|
|
||||||
entity_type: string
|
|
||||||
source_record_id?: string
|
|
||||||
error_type: string
|
|
||||||
error_detail?: string
|
|
||||||
retry_count: number
|
|
||||||
status: string
|
|
||||||
next_retry_at?: string | null
|
|
||||||
created_at?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DataQualityCheckItem {
|
|
||||||
id: number
|
|
||||||
check_name: string
|
|
||||||
entity_type: string
|
|
||||||
passed: boolean
|
|
||||||
severity: string
|
|
||||||
detail?: Record<string, unknown> | null
|
|
||||||
checked_at?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DataQualityResponse {
|
|
||||||
failures: IngestFailureItem[]
|
|
||||||
checks: DataQualityCheckItem[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fetchDataQuality(): Promise<DataQualityResponse> {
|
|
||||||
return api.get<DataQualityResponse>(`${API_BASE}/admin/data-quality`)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function runDataQualityCheck(): Promise<{ ok: boolean; checks: Array<{ name: string; passed: boolean }> }> {
|
|
||||||
return api.post<{ ok: boolean; checks: Array<{ name: string; passed: boolean }> }>(`${API_BASE}/admin/data-quality/run`)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function fetchIngestFailures(): Promise<IngestFailureItem[]> {
|
|
||||||
return api.get<IngestFailureItem[]>(`${API_BASE}/admin/ingest-failures`)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function retryIngestFailure(id: number): Promise<{ ok: boolean; message: string }> {
|
|
||||||
return api.post<{ ok: boolean; message: string }>(`${API_BASE}/admin/ingest-failures/${id}/retry`)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -9,13 +9,20 @@
|
|||||||
* 禁止再新建平行导航清单(修改入口/新增页面只改这里)。
|
* 禁止再新建平行导航清单(修改入口/新增页面只改这里)。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import type { AdminIconName } from './AdminIcon'
|
||||||
|
|
||||||
export interface NavItem {
|
export interface NavItem {
|
||||||
to: string
|
to: string
|
||||||
label: string
|
label: string
|
||||||
/** 命令面板中的分组名(展示原样) */
|
/** 命令面板中的分组名(展示原样) */
|
||||||
group: string
|
group: string
|
||||||
/** 侧栏图标名(见 AdminLayout 的 Icon) */
|
/**
|
||||||
icon: string
|
* 侧栏图标名。
|
||||||
|
*
|
||||||
|
* 使用 AdminIcon 的联合类型而非 `string`:图标名拼错时
|
||||||
|
* 此前不会报任何错,只会静默渲染出一个空位,难以定位。
|
||||||
|
*/
|
||||||
|
icon: AdminIconName
|
||||||
/** 仅命令面板/面包屑可达,不进侧栏(深链页) */
|
/** 仅命令面板/面包屑可达,不进侧栏(深链页) */
|
||||||
hideFromSidebar?: boolean
|
hideFromSidebar?: boolean
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,10 +11,11 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { triggerBacktest, fetchEvalSummary, fetchLeagues } from '../dal'
|
import { triggerBacktest, fetchEvalSummary, fetchLeagues } from '../../api/dal'
|
||||||
import type { BacktestRequest, BacktestSummary, EvalSummary, League } from '../types'
|
import type { BacktestRequest, BacktestSummary, EvalSummary, League } from '../../api/types'
|
||||||
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner } from '../components'
|
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner } from '../components'
|
||||||
import TeamSideTag from '../../components/TeamSideTag'
|
import TeamSideTag from '../../components/TeamSideTag'
|
||||||
|
import { Button, Input, Select } from '../../components/ui'
|
||||||
|
|
||||||
interface BacktestResultRow {
|
interface BacktestResultRow {
|
||||||
match_id: number
|
match_id: number
|
||||||
@@ -38,8 +39,6 @@ interface BacktestResponse {
|
|||||||
results: BacktestResultRow[]
|
results: BacktestResultRow[]
|
||||||
}
|
}
|
||||||
|
|
||||||
const OUTCOME_LABEL: Record<string, string> = { '1': '主胜', X: '平局', '2': '客胜' }
|
|
||||||
|
|
||||||
/** 导出回测明细为 CSV(UTF-8 BOM,Excel 可直接打开) */
|
/** 导出回测明细为 CSV(UTF-8 BOM,Excel 可直接打开) */
|
||||||
function exportCsv(rows: BacktestResultRow[]) {
|
function exportCsv(rows: BacktestResultRow[]) {
|
||||||
const header = [
|
const header = [
|
||||||
@@ -144,10 +143,10 @@ export default function BacktestPage() {
|
|||||||
<form onSubmit={handleBacktest} className="space-y-4">
|
<form onSubmit={handleBacktest} className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">联赛</label>
|
<label className="mb-1.5 block text-xs text-ink-500">联赛</label>
|
||||||
<select
|
<Select
|
||||||
value={leagueId}
|
value={leagueId}
|
||||||
onChange={e => setLeagueId(e.target.value)}
|
onChange={e => setLeagueId(e.target.value)}
|
||||||
className="field w-full"
|
className="w-full"
|
||||||
>
|
>
|
||||||
<option value="">全部联赛</option>
|
<option value="">全部联赛</option>
|
||||||
{leagues.map(l => (
|
{leagues.map(l => (
|
||||||
@@ -155,49 +154,49 @@ export default function BacktestPage() {
|
|||||||
{l.name_zh || l.name}
|
{l.name_zh || l.name}
|
||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||||
<div>
|
<div>
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">起始日期</label>
|
<label className="mb-1.5 block text-xs text-ink-500" htmlFor="bt-date-from">起始日期</label>
|
||||||
<input
|
<Input id="bt-date-from"
|
||||||
type="date"
|
type="date"
|
||||||
value={dateFrom}
|
value={dateFrom}
|
||||||
onChange={e => setDateFrom(e.target.value)}
|
onChange={e => setDateFrom(e.target.value)}
|
||||||
className="field w-full"
|
className="w-full"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">结束日期</label>
|
<label className="mb-1.5 block text-xs text-ink-500" htmlFor="bt-date-to">结束日期</label>
|
||||||
<input
|
<Input id="bt-date-to"
|
||||||
type="date"
|
type="date"
|
||||||
value={dateTo}
|
value={dateTo}
|
||||||
onChange={e => setDateTo(e.target.value)}
|
onChange={e => setDateTo(e.target.value)}
|
||||||
className="field w-full"
|
className="w-full"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-3">
|
<div className="grid grid-cols-2 gap-3">
|
||||||
<div>
|
<div>
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">场数限制</label>
|
<label className="mb-1.5 block text-xs text-ink-500" htmlFor="bt-limit">场数限制</label>
|
||||||
<input
|
<Input id="bt-limit"
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
max={200}
|
max={200}
|
||||||
value={limit}
|
value={limit}
|
||||||
onChange={e => setLimit(parseInt(e.target.value) || 20)}
|
onChange={e => setLimit(parseInt(e.target.value) || 20)}
|
||||||
className="field w-full"
|
className="w-full"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">模式</label>
|
<label className="mb-1.5 block text-xs text-ink-500" htmlFor="bt-mode">模式</label>
|
||||||
<input
|
<Input id="bt-mode"
|
||||||
type="text"
|
type="text"
|
||||||
value="多专家 (5 路 + 终裁)"
|
value="多专家 (5 路 + 终裁)"
|
||||||
readOnly
|
readOnly
|
||||||
className="field w-full bg-paper-100 text-ink-500"
|
className="w-full bg-paper-100 text-ink-500"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -206,20 +205,20 @@ export default function BacktestPage() {
|
|||||||
<label className="mb-1.5 block text-xs text-ink-500">
|
<label className="mb-1.5 block text-xs text-ink-500">
|
||||||
指定模型(可选,空=默认 <code className="font-mono">gpt-4o</code>)
|
指定模型(可选,空=默认 <code className="font-mono">gpt-4o</code>)
|
||||||
</label>
|
</label>
|
||||||
<input
|
<Input
|
||||||
type="text"
|
type="text"
|
||||||
value={model}
|
value={model}
|
||||||
onChange={e => setModel(e.target.value)}
|
onChange={e => setModel(e.target.value)}
|
||||||
placeholder="如 deepseek-chat / 留空使用默认"
|
placeholder="如 deepseek-chat / 留空使用默认"
|
||||||
className="field w-full"
|
className="w-full"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{error && <Alert kind="error" title="回测失败" message={error} onClose={() => setError(null)} />}
|
{error && <Alert kind="error" title="回测失败" message={error} onClose={() => setError(null)} />}
|
||||||
|
|
||||||
<button type="submit" disabled={loading} className="btn btn-solid w-full">
|
<Button variant="solid" className="w-full" type="submit" disabled={loading}>
|
||||||
{loading ? (<><Spinner /> 回测中,逐场预测耗时较长</>) : '开始回测'}
|
{loading ? (<><Spinner /> 回测中,逐场预测耗时较长</>) : '开始回测'}
|
||||||
</button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -233,7 +232,7 @@ export default function BacktestPage() {
|
|||||||
description={`模式: ${mode}${model ? ` · 模型: ${model}` : ''} · 限 ${limit} 场`}
|
description={`模式: ${mode}${model ? ` · 模型: ${model}` : ''} · 限 ${limit} 场`}
|
||||||
action={
|
action={
|
||||||
result?.results?.length
|
result?.results?.length
|
||||||
? (<button onClick={() => exportCsv(result.results)} className="btn btn-sm">导出 CSV</button>)
|
? (<Button size="sm" onClick={() => exportCsv(result.results)}>导出 CSV</Button>)
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
@@ -293,9 +292,9 @@ export default function BacktestPage() {
|
|||||||
title="模型评估"
|
title="模型评估"
|
||||||
description="已结算预测的准确率统计"
|
description="已结算预测的准确率统计"
|
||||||
action={
|
action={
|
||||||
<button onClick={loadEval} disabled={evalLoading} className="btn btn-sm">
|
<Button size="sm" onClick={loadEval} disabled={evalLoading}>
|
||||||
{evalLoading ? (<><Spinner /> 加载中</>) : '刷新'}
|
{evalLoading ? (<><Spinner /> 加载中</>) : '刷新'}
|
||||||
</button>
|
</Button>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<CardBody>
|
<CardBody>
|
||||||
|
|||||||
@@ -11,10 +11,11 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { useEffect, useState, useCallback, useRef } from 'react'
|
import { useEffect, useState, useCallback, useRef } from 'react'
|
||||||
import { triggerCollection, fetchLeagues, fetchIngestJob, fetchIngestJobs } from '../dal'
|
import { triggerCollection, fetchLeagues, fetchIngestJob, fetchIngestJobs } from '../../api/dal'
|
||||||
import type { IngestJob, League } from '../types'
|
import type { IngestJob, League } from '../../api/types'
|
||||||
import type { CollectionRequest } from '../types'
|
import type { CollectionRequest } from '../../api/types'
|
||||||
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner } from '../components'
|
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner } from '../components'
|
||||||
|
import { Button, Input, Select } from '../../components/ui'
|
||||||
|
|
||||||
// 图标用与全站一致的几何字符(Dashboard 工作流卡同款),不混用 emoji
|
// 图标用与全站一致的几何字符(Dashboard 工作流卡同款),不混用 emoji
|
||||||
const TASKS = [
|
const TASKS = [
|
||||||
@@ -74,6 +75,22 @@ export default function CollectionPage() {
|
|||||||
|
|
||||||
useEffect(() => () => stopPolling(), [stopPolling])
|
useEffect(() => () => stopPolling(), [stopPolling])
|
||||||
|
|
||||||
|
// ── 已运行时长 ──
|
||||||
|
// 必须放在 state 里、由定时器推进,而不是在 render 里读 Date.now()。
|
||||||
|
// 后者是「渲染期间的副作用」:同一份 props/state 会渲染出不同结果,
|
||||||
|
// React 的并发特性(以及未来的编译器优化)都依赖渲染幂等。
|
||||||
|
// 采集任务在跑时每秒推进一次,既给出真实的时长,也不制造额外重渲染。
|
||||||
|
const [elapsedSec, setElapsedSec] = useState(0)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!taskStartedAt) { setElapsedSec(0); return }
|
||||||
|
if (taskStatus !== 'running') return
|
||||||
|
const id = setInterval(() => {
|
||||||
|
setElapsedSec(Math.round((Date.now() - taskStartedAt) / 1000))
|
||||||
|
}, 1000)
|
||||||
|
return () => clearInterval(id)
|
||||||
|
}, [taskStartedAt, taskStatus])
|
||||||
|
|
||||||
// ── 最近任务历史(GET /admin/ingest/jobs,最新在前) ──
|
// ── 最近任务历史(GET /admin/ingest/jobs,最新在前) ──
|
||||||
// 声明须在 startJobPolling 之前(其终态回调会刷新历史)
|
// 声明须在 startJobPolling 之前(其终态回调会刷新历史)
|
||||||
const [recentJobs, setRecentJobs] = useState<IngestJob[] | null>(null)
|
const [recentJobs, setRecentJobs] = useState<IngestJob[] | null>(null)
|
||||||
@@ -174,7 +191,7 @@ export default function CollectionPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const elapsed = taskStartedAt ? Math.round((Date.now() - taskStartedAt) / 1000) : 0
|
const elapsed = elapsedSec
|
||||||
const summary = jobInfo ? jobSummary(jobInfo) : null
|
const summary = jobInfo ? jobSummary(jobInfo) : null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -214,51 +231,53 @@ export default function CollectionPage() {
|
|||||||
|
|
||||||
{/* 联赛选择 */}
|
{/* 联赛选择 */}
|
||||||
<div>
|
<div>
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">联赛</label>
|
<label className="mb-1.5 block text-xs text-ink-500" htmlFor="col-league">联赛</label>
|
||||||
<select
|
<Select
|
||||||
|
id="col-league"
|
||||||
value={leagueCode}
|
value={leagueCode}
|
||||||
onChange={e => setLeagueCode(e.target.value)}
|
onChange={e => setLeagueCode(e.target.value)}
|
||||||
className="field w-full"
|
className="w-full"
|
||||||
>
|
>
|
||||||
<option value="">全部联赛</option>
|
<option value="">全部联赛</option>
|
||||||
{leagues.map(l => (
|
{leagues.map(l => (
|
||||||
<option key={l.code} value={l.code}>{l.name_zh || l.name}</option>
|
<option key={l.code} value={l.code}>{l.name_zh || l.name}</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* events/all 任务专用: 比赛状态 + 日期 */}
|
{/* events/all 任务专用: 比赛状态 + 日期 */}
|
||||||
{isEventsTask && (
|
{isEventsTask && (
|
||||||
<>
|
<>
|
||||||
<div>
|
<div>
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">比赛状态</label>
|
<label className="mb-1.5 block text-xs text-ink-500" htmlFor="col-status">比赛状态</label>
|
||||||
<select
|
<Select
|
||||||
|
id="col-status"
|
||||||
value={ingestStatus}
|
value={ingestStatus}
|
||||||
onChange={e => setIngestStatus(e.target.value)}
|
onChange={e => setIngestStatus(e.target.value)}
|
||||||
className="field w-full"
|
className="w-full"
|
||||||
>
|
>
|
||||||
<option value="">全部(已完赛 + 未开赛)</option>
|
<option value="">全部(已完赛 + 未开赛)</option>
|
||||||
<option value="finished">仅已完赛</option>
|
<option value="finished">仅已完赛</option>
|
||||||
<option value="scheduled">仅未开赛</option>
|
<option value="scheduled">仅未开赛</option>
|
||||||
</select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||||
<div>
|
<div>
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">起始日期</label>
|
<label className="mb-1.5 block text-xs text-ink-500" htmlFor="col-date-from">起始日期</label>
|
||||||
<input
|
<Input id="col-date-from"
|
||||||
type="date"
|
type="date"
|
||||||
value={dateFrom}
|
value={dateFrom}
|
||||||
onChange={e => setDateFrom(e.target.value)}
|
onChange={e => setDateFrom(e.target.value)}
|
||||||
className="field w-full"
|
className="w-full"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">结束日期</label>
|
<label className="mb-1.5 block text-xs text-ink-500" htmlFor="col-date-to">结束日期</label>
|
||||||
<input
|
<Input id="col-date-to"
|
||||||
type="date"
|
type="date"
|
||||||
value={dateTo}
|
value={dateTo}
|
||||||
onChange={e => setDateTo(e.target.value)}
|
onChange={e => setDateTo(e.target.value)}
|
||||||
className="field w-full"
|
className="w-full"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -268,13 +287,13 @@ export default function CollectionPage() {
|
|||||||
{/* standings 任务专用: 赛季 */}
|
{/* standings 任务专用: 赛季 */}
|
||||||
{(task === 'standings') && (
|
{(task === 'standings') && (
|
||||||
<div>
|
<div>
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">赛季(留空取当前赛季)</label>
|
<label className="mb-1.5 block text-xs text-ink-500" htmlFor="col-season">赛季(留空取当前赛季)</label>
|
||||||
<input
|
<Input id="col-season"
|
||||||
type="text"
|
type="text"
|
||||||
value={season}
|
value={season}
|
||||||
onChange={e => setSeason(e.target.value)}
|
onChange={e => setSeason(e.target.value)}
|
||||||
placeholder="如 2026-2027"
|
placeholder="如 2026-2027"
|
||||||
className="field w-full"
|
className="w-full"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -283,13 +302,13 @@ export default function CollectionPage() {
|
|||||||
{(task === 'stats') && (
|
{(task === 'stats') && (
|
||||||
<div>
|
<div>
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">单次最大回填比赛数(1-500)</label>
|
<label className="mb-1.5 block text-xs text-ink-500">单次最大回填比赛数(1-500)</label>
|
||||||
<input
|
<Input
|
||||||
type="number"
|
type="number"
|
||||||
min={1}
|
min={1}
|
||||||
max={500}
|
max={500}
|
||||||
value={limit}
|
value={limit}
|
||||||
onChange={e => setLimit(parseInt(e.target.value) || 100)}
|
onChange={e => setLimit(parseInt(e.target.value) || 100)}
|
||||||
className="field w-full"
|
className="w-full"
|
||||||
/>
|
/>
|
||||||
<p className="mt-1 text-2xs text-ink-400">
|
<p className="mt-1 text-2xs text-ink-400">
|
||||||
仅回填已有 source_event_id 且无统计的比赛(增量),上游限速约 1.2 秒/次。
|
仅回填已有 source_event_id 且无统计的比赛(增量),上游限速约 1.2 秒/次。
|
||||||
@@ -308,9 +327,9 @@ export default function CollectionPage() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 提交按钮 */}
|
{/* 提交按钮 */}
|
||||||
<button type="submit" disabled={loading} className="btn btn-solid w-full">
|
<Button variant="solid" className="w-full" type="submit" disabled={loading}>
|
||||||
{loading ? (<><Spinner /> 采集中</>) : '触发采集'}
|
{loading ? (<><Spinner /> 采集中</>) : '触发采集'}
|
||||||
</button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -366,7 +385,7 @@ export default function CollectionPage() {
|
|||||||
<CardHeader
|
<CardHeader
|
||||||
title="最近任务"
|
title="最近任务"
|
||||||
description="后台采集任务执行历史(最新在前)"
|
description="后台采集任务执行历史(最新在前)"
|
||||||
action={<button onClick={loadRecentJobs} className="btn btn-sm">刷新</button>}
|
action={<Button size="sm" onClick={loadRecentJobs}>刷新</Button>}
|
||||||
/>
|
/>
|
||||||
<CardBody className="px-0">
|
<CardBody className="px-0">
|
||||||
{recentJobs === null ? (
|
{recentJobs === null ? (
|
||||||
|
|||||||
@@ -11,9 +11,9 @@
|
|||||||
|
|
||||||
import { useEffect, useState, useCallback } from 'react'
|
import { useEffect, useState, useCallback } from 'react'
|
||||||
import { Link } from 'react-router-dom'
|
import { Link } from 'react-router-dom'
|
||||||
import { fetchAdminStats, fetchIngestStatus, fetchDashboard, fetchIngestFailures, fetchDataCompleteness, fetchPredictions } from '../dal'
|
import { fetchAdminStats, fetchIngestStatus, fetchDashboard, fetchIngestFailures, fetchDataCompleteness, fetchPredictions } from '../../api/dal'
|
||||||
import type { DataCompletenessResponse, IngestFailureItem } from '../dal'
|
import type { DataCompletenessResponse, IngestFailureItem } from '../../api/dal'
|
||||||
import type { AdminStats, IngestSourceStatus, DashboardStats } from '../types'
|
import type { AdminStats, IngestSourceStatus, DashboardStats } from '../../api/types'
|
||||||
import { Card, CardBody, CardHeader, SkeletonBlock } from '../components'
|
import { Card, CardBody, CardHeader, SkeletonBlock } from '../components'
|
||||||
|
|
||||||
/** 工作流引导(仅首次使用——库里还没有比赛时显示) */
|
/** 工作流引导(仅首次使用——库里还没有比赛时显示) */
|
||||||
|
|||||||
@@ -8,12 +8,13 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { useEffect, useState, useCallback, useRef } from 'react'
|
import { useEffect, useState, useCallback, useRef } from 'react'
|
||||||
import { fetchDataCompleteness } from '../dal'
|
import { fetchDataCompleteness } from '../../api/dal'
|
||||||
import type { DataCompletenessResponse } from '../dal'
|
import type { DataCompletenessResponse } from '../../api/dal'
|
||||||
import {
|
import {
|
||||||
Card, CardBody, CardHeader, SectionHeader, Alert,
|
Card, CardBody, CardHeader, SectionHeader, Alert,
|
||||||
ProgressBar, Spinner, EmptyState,
|
ProgressBar, Spinner,
|
||||||
} from '../components'
|
} from '../components'
|
||||||
|
import { Button } from '../../components/ui'
|
||||||
|
|
||||||
const FIELD_LABELS: Record<string, string> = {
|
const FIELD_LABELS: Record<string, string> = {
|
||||||
xg: 'xG 预期进球',
|
xg: 'xG 预期进球',
|
||||||
@@ -119,9 +120,9 @@ export default function DataCompletenessPage() {
|
|||||||
/>
|
/>
|
||||||
5s 自动刷新
|
5s 自动刷新
|
||||||
</label>
|
</label>
|
||||||
<button onClick={load} disabled={loading} className="btn-sm btn-outline">
|
<Button variant="outline" size="sm" onClick={load} disabled={loading}>
|
||||||
{loading ? <><Spinner /> 刷新中</> : '刷新'}
|
{loading ? <><Spinner /> 刷新中</> : '刷新'}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
@@ -173,15 +174,12 @@ export default function DataCompletenessPage() {
|
|||||||
message={issue}
|
message={issue}
|
||||||
action={action ? (
|
action={action ? (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<button
|
<Button size="sm" className="whitespace-nowrap" onClick={() => scrollToLeague(action.code)}>
|
||||||
onClick={() => scrollToLeague(action.code)}
|
|
||||||
className="btn btn-sm whitespace-nowrap"
|
|
||||||
>
|
|
||||||
定位
|
定位
|
||||||
</button>
|
</Button>
|
||||||
<a href={action.href} className="btn btn-sm whitespace-nowrap">
|
<Button href={action.href} size="sm" className="whitespace-nowrap">
|
||||||
{action.label}
|
{action.label}
|
||||||
</a>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : undefined}
|
) : undefined}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -13,9 +13,10 @@ import {
|
|||||||
runDataQualityCheck,
|
runDataQualityCheck,
|
||||||
fetchIngestFailures,
|
fetchIngestFailures,
|
||||||
retryIngestFailure,
|
retryIngestFailure,
|
||||||
} from '../dal'
|
} from '../../api/dal'
|
||||||
import type { IngestFailureItem, DataQualityCheckItem } from '../dal'
|
import type { IngestFailureItem, DataQualityCheckItem } from '../../api/dal'
|
||||||
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner } from '../components'
|
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner } from '../components'
|
||||||
|
import { Button } from '../../components/ui'
|
||||||
|
|
||||||
export default function DataPipelinePage() {
|
export default function DataPipelinePage() {
|
||||||
const [quality, setQuality] = useState<{ failures: IngestFailureItem[]; checks: DataQualityCheckItem[] } | null>(null)
|
const [quality, setQuality] = useState<{ failures: IngestFailureItem[]; checks: DataQualityCheckItem[] } | null>(null)
|
||||||
@@ -80,9 +81,9 @@ export default function DataPipelinePage() {
|
|||||||
title="数据管线"
|
title="数据管线"
|
||||||
description="采集失败重试、数据质量检查与监控"
|
description="采集失败重试、数据质量检查与监控"
|
||||||
action={
|
action={
|
||||||
<button onClick={handleRunCheck} disabled={running} className="btn btn-sm">
|
<Button size="sm" onClick={handleRunCheck} disabled={running}>
|
||||||
{running ? <><Spinner /> 检查中</> : '运行质量检查'}
|
{running ? <><Spinner /> 检查中</> : '运行质量检查'}
|
||||||
</button>
|
</Button>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -134,9 +135,9 @@ export default function DataPipelinePage() {
|
|||||||
</td>
|
</td>
|
||||||
<td className="px-4 py-2">
|
<td className="px-4 py-2">
|
||||||
{(f.status === 'pending' || f.status === 'retrying') && (
|
{(f.status === 'pending' || f.status === 'retrying') && (
|
||||||
<button onClick={() => handleRetry(f.id)} className="btn btn-sm">
|
<Button size="sm" onClick={() => handleRetry(f.id)}>
|
||||||
重试
|
重试
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|||||||
@@ -8,9 +8,10 @@
|
|||||||
* - 空态与加载态
|
* - 空态与加载态
|
||||||
*/
|
*/
|
||||||
import { useCallback, useEffect, useState } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
import { fetchEvalSummary, fetchLeagues } from '../dal'
|
import { fetchEvalSummary, fetchLeagues } from '../../api/dal'
|
||||||
import type { EvalSummary } from '../types'
|
import type { EvalSummary, EvalSummaryRow, EvalCalibrationBucket } from '../../api/types'
|
||||||
import { Card, CardBody, CardHeader, StatCard, Badge, DataTable, Alert, Spinner, EmptyText } from '../components'
|
import { Card, CardBody, CardHeader, StatCard, DataTable, Alert, Spinner, EmptyText } from '../components'
|
||||||
|
import { Button, Input, Select } from '../../components/ui'
|
||||||
|
|
||||||
interface Filters {
|
interface Filters {
|
||||||
provider: string
|
provider: string
|
||||||
@@ -73,67 +74,67 @@ export default function EvalPage() {
|
|||||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-5">
|
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-5">
|
||||||
<label className="block">
|
<label className="block">
|
||||||
<span className="text-2xs text-ink-500">提供商</span>
|
<span className="text-2xs text-ink-500">提供商</span>
|
||||||
<input
|
<Input
|
||||||
type="text"
|
type="text"
|
||||||
value={filters.provider}
|
value={filters.provider}
|
||||||
onChange={handleChange('provider')}
|
onChange={handleChange('provider')}
|
||||||
placeholder="如 openai"
|
placeholder="如 openai"
|
||||||
className="mt-1 w-full border border-ink-300 bg-paper-50 px-2.5 py-1.5 text-sm text-ink-900 placeholder:text-ink-300 focus:border-ink-900 focus:outline-none"
|
className="mt-1 w-full"
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<label className="block">
|
<label className="block">
|
||||||
<span className="text-2xs text-ink-500">模型</span>
|
<span className="text-2xs text-ink-500">模型</span>
|
||||||
<input
|
<Input
|
||||||
type="text"
|
type="text"
|
||||||
value={filters.model}
|
value={filters.model}
|
||||||
onChange={handleChange('model')}
|
onChange={handleChange('model')}
|
||||||
placeholder="如 gpt-4o"
|
placeholder="如 gpt-4o"
|
||||||
className="mt-1 w-full border border-ink-300 bg-paper-50 px-2.5 py-1.5 text-sm text-ink-900 placeholder:text-ink-300 focus:border-ink-900 focus:outline-none"
|
className="mt-1 w-full"
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<label className="block">
|
<label className="block">
|
||||||
<span className="text-2xs text-ink-500">Prompt 版本</span>
|
<span className="text-2xs text-ink-500">Prompt 版本</span>
|
||||||
<input
|
<Input
|
||||||
type="text"
|
type="text"
|
||||||
value={filters.prompt_version}
|
value={filters.prompt_version}
|
||||||
onChange={handleChange('prompt_version')}
|
onChange={handleChange('prompt_version')}
|
||||||
placeholder="如 v1"
|
placeholder="如 v1"
|
||||||
className="mt-1 w-full border border-ink-300 bg-paper-50 px-2.5 py-1.5 text-sm text-ink-900 placeholder:text-ink-300 focus:border-ink-900 focus:outline-none"
|
className="mt-1 w-full"
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<label className="block">
|
<label className="block">
|
||||||
<span className="text-2xs text-ink-500">模式</span>
|
<span className="text-2xs text-ink-500">模式</span>
|
||||||
<select
|
<Select
|
||||||
value={filters.mode}
|
value={filters.mode}
|
||||||
onChange={handleChange('mode')}
|
onChange={handleChange('mode')}
|
||||||
className="mt-1 w-full border border-ink-300 bg-paper-50 px-2.5 py-1.5 text-sm text-ink-900 focus:border-ink-900 focus:outline-none"
|
className="mt-1 w-full"
|
||||||
>
|
>
|
||||||
<option value="">全部</option>
|
<option value="">全部</option>
|
||||||
<option value="single">single</option>
|
<option value="single">single</option>
|
||||||
<option value="multi">multi</option>
|
<option value="multi">multi</option>
|
||||||
</select>
|
</Select>
|
||||||
</label>
|
</label>
|
||||||
<label className="block">
|
<label className="block">
|
||||||
<span className="text-2xs text-ink-500">联赛</span>
|
<span className="text-2xs text-ink-500">联赛</span>
|
||||||
<select
|
<Select
|
||||||
value={filters.league_code}
|
value={filters.league_code}
|
||||||
onChange={handleChange('league_code')}
|
onChange={handleChange('league_code')}
|
||||||
className="mt-1 w-full border border-ink-300 bg-paper-50 px-2.5 py-1.5 text-sm text-ink-900 focus:border-ink-900 focus:outline-none"
|
className="mt-1 w-full"
|
||||||
>
|
>
|
||||||
<option value="">全部</option>
|
<option value="">全部</option>
|
||||||
{leagues.map(l => (
|
{leagues.map(l => (
|
||||||
<option key={l.code} value={l.code}>{l.name ?? l.code}</option>
|
<option key={l.code} value={l.code}>{l.name ?? l.code}</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</Select>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-3 flex gap-2">
|
<div className="mt-3 flex gap-2">
|
||||||
<button onClick={load} disabled={loading} className="btn btn-sm">
|
<Button size="sm" disabled={loading} onClick={load}>
|
||||||
{loading ? '加载中…' : '应用筛选'}
|
{loading ? '加载中…' : '应用筛选'}
|
||||||
</button>
|
</Button>
|
||||||
<button onClick={handleReset} disabled={loading} className="btn btn-sm btn-ghost">
|
<Button size="sm" variant="ghost" disabled={loading} onClick={handleReset}>
|
||||||
重置
|
重置
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -166,27 +167,27 @@ export default function EvalPage() {
|
|||||||
<EmptyText text="暂无评估数据,请调整筛选条件或先完成预测与结算" />
|
<EmptyText text="暂无评估数据,请调整筛选条件或先完成预测与结算" />
|
||||||
) : (
|
) : (
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<DataTable
|
<DataTable<EvalSummaryRow>
|
||||||
columns={[
|
columns={[
|
||||||
{ key: 'provider', label: '提供商' },
|
{ key: 'provider', label: '提供商' },
|
||||||
{ key: 'model', label: '模型' },
|
{ key: 'model', label: '模型' },
|
||||||
{ key: 'prompt_version', label: '版本', render: (row: any) => (
|
{ key: 'prompt_version', label: '版本', render: (row: EvalSummaryRow) => (
|
||||||
<span className="font-mono text-2xs">{row.prompt_version ?? '—'}</span>
|
<span className="font-mono text-2xs">{row.prompt_version ?? '—'}</span>
|
||||||
) },
|
) },
|
||||||
{ key: 'total', label: '评估条数' },
|
{ key: 'total', label: '评估条数' },
|
||||||
{ key: 'accuracy_1x2', label: '1X2 准确率', render: (row: any) => (
|
{ key: 'accuracy_1x2', label: '1X2 准确率', render: (row: EvalSummaryRow) => (
|
||||||
<span className="tabular-nums">{row.accuracy_1x2 != null ? `${row.accuracy_1x2}%` : '—'}</span>
|
<span className="tabular-nums">{row.accuracy_1x2 != null ? `${row.accuracy_1x2}%` : '—'}</span>
|
||||||
) },
|
) },
|
||||||
{ key: 'avg_score_rmse', label: '比分 RMSE', render: (row: any) => (
|
{ key: 'avg_score_rmse', label: '比分 RMSE', render: (row: EvalSummaryRow) => (
|
||||||
<span className="tabular-nums">{row.avg_score_rmse != null ? row.avg_score_rmse.toFixed(2) : '—'}</span>
|
<span className="tabular-nums">{row.avg_score_rmse != null ? row.avg_score_rmse.toFixed(2) : '—'}</span>
|
||||||
) },
|
) },
|
||||||
{ key: 'avg_subjective_confidence', label: '平均置信度', render: (row: any) => (
|
{ key: 'avg_subjective_confidence', label: '平均置信度', render: (row: EvalSummaryRow) => (
|
||||||
<span className="tabular-nums">{row.avg_subjective_confidence != null ? row.avg_subjective_confidence.toFixed(2) : '—'}</span>
|
<span className="tabular-nums">{row.avg_subjective_confidence != null ? row.avg_subjective_confidence.toFixed(2) : '—'}</span>
|
||||||
) },
|
) },
|
||||||
{ key: 'calibration', label: '置信度校准(桶命中率)', render: (row: any) => (
|
{ key: 'calibration', label: '置信度校准(桶命中率)', render: (row: EvalSummaryRow) => (
|
||||||
row.calibration ? (
|
row.calibration ? (
|
||||||
<div className="flex flex-wrap gap-x-3 gap-y-1 text-2xs">
|
<div className="flex flex-wrap gap-x-3 gap-y-1 text-2xs">
|
||||||
{Object.entries(row.calibration).map(([name, b]: [string, any]) => (
|
{Object.entries(row.calibration).map(([name, b]: [string, EvalCalibrationBucket]) => (
|
||||||
<span key={name} className="inline-flex items-center gap-1">
|
<span key={name} className="inline-flex items-center gap-1">
|
||||||
<span className="text-ink-400">{name}:</span>
|
<span className="text-ink-400">{name}:</span>
|
||||||
<span className="tabular-nums font-medium">
|
<span className="tabular-nums font-medium">
|
||||||
@@ -200,7 +201,7 @@ export default function EvalPage() {
|
|||||||
) },
|
) },
|
||||||
]}
|
]}
|
||||||
data={summary}
|
data={summary}
|
||||||
rowKey={(row: any) => `${row.provider}-${row.model}-${row.prompt_version ?? ''}`}
|
rowKey={(row: EvalSummaryRow) => `${row.provider}-${row.model}-${row.prompt_version ?? ''}`}
|
||||||
emptyText="暂无评估数据"
|
emptyText="暂无评估数据"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -8,9 +8,10 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { useEffect, useState, useCallback, useRef } from 'react'
|
import { useEffect, useState, useCallback, useRef } from 'react'
|
||||||
import { fetchLogs } from '../dal'
|
import { fetchLogs } from '../../api/dal'
|
||||||
import type { LogEntry } from '../types'
|
import type { LogEntry } from '../../api/types'
|
||||||
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner, SkeletonBlock } from '../components'
|
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner, SkeletonBlock } from '../components'
|
||||||
|
import { Button, Input } from '../../components/ui'
|
||||||
|
|
||||||
const LEVELS = ['', 'INFO', 'WARNING', 'ERROR'] as const
|
const LEVELS = ['', 'INFO', 'WARNING', 'ERROR'] as const
|
||||||
|
|
||||||
@@ -106,9 +107,9 @@ export default function LogsPage() {
|
|||||||
/>
|
/>
|
||||||
10s 自动刷新
|
10s 自动刷新
|
||||||
</label>
|
</label>
|
||||||
<button onClick={load} disabled={loading} className="btn btn-sm">
|
<Button size="sm" onClick={load} disabled={loading}>
|
||||||
{loading ? (<><Spinner /> 加载中</>) : '刷新'}
|
{loading ? (<><Spinner /> 加载中</>) : '刷新'}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
@@ -117,20 +118,22 @@ export default function LogsPage() {
|
|||||||
<div className="flex flex-col gap-2 border-b border-ink-200 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-5">
|
<div className="flex flex-col gap-2 border-b border-ink-200 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-5">
|
||||||
<div className="flex flex-wrap gap-1.5">
|
<div className="flex flex-wrap gap-1.5">
|
||||||
{LEVELS.map(lv => (
|
{LEVELS.map(lv => (
|
||||||
<button
|
<Button
|
||||||
key={lv || 'all'}
|
key={lv || 'all'}
|
||||||
onClick={() => setLevel(lv)}
|
onClick={() => setLevel(lv)}
|
||||||
className={`btn btn-sm ${level === lv ? 'btn-solid' : ''}`}
|
variant={level === lv ? 'solid' : 'default'}
|
||||||
|
size="sm"
|
||||||
>
|
>
|
||||||
{lv || '全部'}
|
{lv || '全部'}
|
||||||
</button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<input
|
<Input
|
||||||
value={keyword}
|
value={keyword}
|
||||||
onChange={e => setKeyword(e.target.value)}
|
onChange={e => setKeyword(e.target.value)}
|
||||||
placeholder="搜索关键字(消息 / logger)…"
|
placeholder="搜索关键字(消息 / logger)…"
|
||||||
className="field w-full sm:w-64"
|
aria-label="搜索日志关键字"
|
||||||
|
className="w-full sm:w-64"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -12,14 +12,18 @@
|
|||||||
|
|
||||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||||
import { Link } from 'react-router-dom'
|
import { Link } from 'react-router-dom'
|
||||||
import { fetchHealth, fetchUpstreamProbe, fetchIngestJobs, fetchIngestFailures, fetchDataCompleteness, fetchLLMUsageStats } from '../dal'
|
import { fetchHealth, fetchUpstreamProbe, fetchIngestJobs, fetchIngestFailures, fetchDataCompleteness, fetchLLMUsageStats } from '../../api/dal'
|
||||||
import type { DataCompletenessResponse, IngestFailureItem } from '../dal'
|
import type { DataCompletenessResponse, IngestFailureItem } from '../../api/dal'
|
||||||
import type { IngestJob } from '../types'
|
import type { IngestJob, LLMUsageStats, HealthProbe } from '../../api/types'
|
||||||
import { api } from '../api'
|
import { api } from '../../api/api'
|
||||||
import { Alert, SectionHeader, Spinner } from '../components'
|
import { Alert, SectionHeader, Spinner } from '../components'
|
||||||
|
import { Button } from '../../components/ui'
|
||||||
|
|
||||||
type UpstreamProbe = { ok: boolean; status_code?: number; latency_ms: number; endpoint: string; error?: string }
|
type UpstreamProbe = { ok: boolean; status_code?: number; latency_ms: number; endpoint: string; error?: string }
|
||||||
type LLMStats = { total_predictions: number; avg_latency_ms: number; success_rate: number }
|
// 直接引用 DAL 的权威类型,不要再本地手写一份 ——
|
||||||
|
// 本地别名会把 `avg_latency_ms: number | null` 悄悄收窄回 `number`,
|
||||||
|
// 使「未接入」在页面上重新退化成假数字。
|
||||||
|
type LLMStats = LLMUsageStats
|
||||||
|
|
||||||
interface TodoItem {
|
interface TodoItem {
|
||||||
key: string
|
key: string
|
||||||
@@ -37,7 +41,7 @@ function MetricCard({ label, children }: { label: string; children: React.ReactN
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function MonitoringPage() {
|
export default function MonitoringPage() {
|
||||||
const [health, setHealth] = useState<Record<string, unknown> | null>(null)
|
const [health, setHealth] = useState<HealthProbe | null>(null)
|
||||||
const [ready, setReady] = useState<'ready' | 'not_ready' | null>(null)
|
const [ready, setReady] = useState<'ready' | 'not_ready' | null>(null)
|
||||||
const [upstream, setUpstream] = useState<UpstreamProbe | null>(null)
|
const [upstream, setUpstream] = useState<UpstreamProbe | null>(null)
|
||||||
const [recentJobs, setRecentJobs] = useState<IngestJob[] | null>(null)
|
const [recentJobs, setRecentJobs] = useState<IngestJob[] | null>(null)
|
||||||
@@ -92,14 +96,21 @@ export default function MonitoringPage() {
|
|||||||
)
|
)
|
||||||
|
|
||||||
// ── 「需要关注」聚合:任何一项异常即亮红 ──
|
// ── 「需要关注」聚合:任何一项异常即亮红 ──
|
||||||
const todos: TodoItem[] = [
|
//
|
||||||
!alive && { key: 'alive', label: '服务存活异常', to: '/admin/logs' },
|
// 过滤条件必须是「真值」而非 `t !== false`。因为这些短路表达式在条件
|
||||||
ready === 'not_ready' && { key: 'db', label: '数据库未就绪', to: '/admin/logs' },
|
// 不成立时返回的**不只是 false**:`upstream && !upstream.ok && {...}`
|
||||||
upstream && !upstream.ok && { key: 'upstream', label: '上游 bzzoiro 不可达', to: '/admin/logs' },
|
// 在 upstream 为 null 时整条求值为 null,而 `null !== false` 为 true,
|
||||||
recentFailedJobs > 0 && { key: 'jobs', label: `最近采集失败 ${recentFailedJobs} 次`, to: '/admin/collection' },
|
// 于是 null 会穿过过滤器,渲染时 `t.to` 直接抛错并让整页崩进 ErrorBoundary。
|
||||||
deadLetterCount > 0 && { key: 'deadletter', label: `死信待处理 ${deadLetterCount} 条`, to: '/admin/data-pipeline' },
|
const todos = (
|
||||||
missingStatsLeagues > 0 && { key: 'missing', label: `${missingStatsLeagues} 个联赛缺统计`, to: '/admin/data-completeness' },
|
[
|
||||||
].filter((t): t is TodoItem => t !== false)
|
!alive && { key: 'alive', label: '服务存活异常', to: '/admin/logs' },
|
||||||
|
ready === 'not_ready' && { key: 'db', label: '数据库未就绪', to: '/admin/logs' },
|
||||||
|
upstream && !upstream.ok && { key: 'upstream', label: '上游 bzzoiro 不可达', to: '/admin/logs' },
|
||||||
|
recentFailedJobs > 0 && { key: 'jobs', label: `最近采集失败 ${recentFailedJobs} 次`, to: '/admin/collection' },
|
||||||
|
deadLetterCount > 0 && { key: 'deadletter', label: `死信待处理 ${deadLetterCount} 条`, to: '/admin/data-pipeline' },
|
||||||
|
missingStatsLeagues > 0 && { key: 'missing', label: `${missingStatsLeagues} 个联赛缺统计`, to: '/admin/data-completeness' },
|
||||||
|
] as Array<TodoItem | false | null | undefined>
|
||||||
|
).filter((t): t is TodoItem => Boolean(t))
|
||||||
|
|
||||||
const okJobs = (recentJobs ?? []).filter(j => j.status === 'success').length
|
const okJobs = (recentJobs ?? []).filter(j => j.status === 'success').length
|
||||||
const runJobs = (recentJobs ?? []).filter(j => j.status === 'success' || j.status === 'failed').length
|
const runJobs = (recentJobs ?? []).filter(j => j.status === 'success' || j.status === 'failed').length
|
||||||
@@ -113,9 +124,9 @@ export default function MonitoringPage() {
|
|||||||
action={
|
action={
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className="text-2xs text-ink-400">{lastCheck && `最近巡检 ${lastCheck}`}</span>
|
<span className="text-2xs text-ink-400">{lastCheck && `最近巡检 ${lastCheck}`}</span>
|
||||||
<button onClick={refresh} disabled={loading} className="btn btn-sm">
|
<Button size="sm" onClick={refresh} disabled={loading}>
|
||||||
{loading ? (<><Spinner /> 检查中</>) : '立即巡检'}
|
{loading ? (<><Spinner /> 检查中</>) : '立即巡检'}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
@@ -156,7 +167,7 @@ export default function MonitoringPage() {
|
|||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className={`inline-block h-2 w-2 ${alive ? 'bg-ink-900' : 'bg-press'}`} aria-hidden="true" />
|
<span className={`inline-block h-2 w-2 ${alive ? 'bg-ink-900' : 'bg-press'}`} aria-hidden="true" />
|
||||||
<span className={`font-serif text-xl font-bold ${alive ? 'text-ink-900' : 'text-press'}`}>
|
<span className={`font-serif text-xl font-bold ${alive ? 'text-ink-900' : 'text-press'}`}>
|
||||||
{health ? (alive ? '正常' : String(health.status)) : '—'}
|
{health ? (alive ? '正常' : health.status) : '—'}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</MetricCard>
|
</MetricCard>
|
||||||
@@ -172,11 +183,11 @@ export default function MonitoringPage() {
|
|||||||
|
|
||||||
<MetricCard label="版本 / 运行时间">
|
<MetricCard label="版本 / 运行时间">
|
||||||
<div className="font-serif text-xl font-bold tabular-nums text-ink-900">
|
<div className="font-serif text-xl font-bold tabular-nums text-ink-900">
|
||||||
{health?.version ? String(health.version) : '—'}
|
{health?.version ?? '—'}
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-0.5 text-2xs tabular-nums text-ink-400">
|
<div className="mt-0.5 text-2xs tabular-nums text-ink-400">
|
||||||
{health?.uptime_seconds != null
|
{health?.uptime_seconds != null
|
||||||
? `已运行 ${Math.floor(Number(health.uptime_seconds) / 3600)}h ${Math.floor((Number(health.uptime_seconds) % 3600) / 60)}m`
|
? `已运行 ${Math.floor(health.uptime_seconds / 3600)}h ${Math.floor((health.uptime_seconds % 3600) / 60)}m`
|
||||||
: '—'}
|
: '—'}
|
||||||
</div>
|
</div>
|
||||||
</MetricCard>
|
</MetricCard>
|
||||||
@@ -252,9 +263,11 @@ export default function MonitoringPage() {
|
|||||||
{llmStats ? llmStats.total_predictions : '—'}
|
{llmStats ? llmStats.total_predictions : '—'}
|
||||||
</div>
|
</div>
|
||||||
</MetricCard>
|
</MetricCard>
|
||||||
<MetricCard label="平均延迟">
|
<MetricCard label={llmStats?.avg_latency_ms != null ? '平均延迟' : '平均延迟(未接入)'}>
|
||||||
<div className="font-serif text-xl font-bold tabular-nums text-ink-900">
|
<div className="font-serif text-xl font-bold tabular-nums text-ink-900">
|
||||||
{llmStats && llmStats.avg_latency_ms > 0 ? `${(llmStats.avg_latency_ms / 1000).toFixed(1)}s` : '—'}
|
{llmStats?.avg_latency_ms != null
|
||||||
|
? `${(llmStats.avg_latency_ms / 1000).toFixed(1)}s`
|
||||||
|
: '—'}
|
||||||
</div>
|
</div>
|
||||||
</MetricCard>
|
</MetricCard>
|
||||||
<MetricCard label="有效率">
|
<MetricCard label="有效率">
|
||||||
|
|||||||
@@ -8,10 +8,11 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { useCallback, useEffect, useState } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
import { fetchPredictions, settlePrediction } from '../dal'
|
import { fetchPredictions, settlePrediction } from '../../api/dal'
|
||||||
import type { Prediction } from '../types'
|
import type { Prediction } from '../../api/types'
|
||||||
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner } from '../components'
|
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner } from '../components'
|
||||||
import TeamSideTag from '../../components/TeamSideTag'
|
import TeamSideTag from '../../components/TeamSideTag'
|
||||||
|
import { Button } from '../../components/ui'
|
||||||
|
|
||||||
const OUTCOME_LABEL: Record<string, string> = { '1': '主胜', X: '平局', '2': '客胜' }
|
const OUTCOME_LABEL: Record<string, string> = { '1': '主胜', X: '平局', '2': '客胜' }
|
||||||
|
|
||||||
@@ -45,7 +46,7 @@ export default function PredictionHistoryPage() {
|
|||||||
useEffect(() => { load() }, [load])
|
useEffect(() => { load() }, [load])
|
||||||
|
|
||||||
const handleSettle = async (p: Prediction) => {
|
const handleSettle = async (p: Prediction) => {
|
||||||
const match = (p as any).match
|
const match = p.match
|
||||||
if (!match || match.home_goals == null || match.away_goals == null) return
|
if (!match || match.home_goals == null || match.away_goals == null) return
|
||||||
setSettlingId(p.id)
|
setSettlingId(p.id)
|
||||||
try {
|
try {
|
||||||
@@ -110,13 +111,14 @@ export default function PredictionHistoryPage() {
|
|||||||
{ v: 'unsettled', label: '待结算' },
|
{ v: 'unsettled', label: '待结算' },
|
||||||
{ v: 'settled', label: '已结算' },
|
{ v: 'settled', label: '已结算' },
|
||||||
] as const).map(opt => (
|
] as const).map(opt => (
|
||||||
<button
|
<Button
|
||||||
key={opt.v}
|
key={opt.v}
|
||||||
onClick={() => setFilter(opt.v)}
|
onClick={() => setFilter(opt.v)}
|
||||||
className={`btn btn-sm ${filter === opt.v ? 'btn-solid' : ''}`}
|
variant={filter === opt.v ? 'solid' : 'default'}
|
||||||
|
size="sm"
|
||||||
>
|
>
|
||||||
{opt.label}
|
{opt.label}
|
||||||
</button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -154,7 +156,7 @@ export default function PredictionHistoryPage() {
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{filtered.map(p => {
|
{filtered.map(p => {
|
||||||
const match = (p as any).match
|
const match = p.match
|
||||||
const matchDate = match?.match_date
|
const matchDate = match?.match_date
|
||||||
const homeName = match?.home_team_zh || match?.home_team || '?'
|
const homeName = match?.home_team_zh || match?.home_team || '?'
|
||||||
const awayName = match?.away_team_zh || match?.away_team || '?'
|
const awayName = match?.away_team_zh || match?.away_team || '?'
|
||||||
@@ -216,20 +218,13 @@ export default function PredictionHistoryPage() {
|
|||||||
<td className="px-4 py-3">
|
<td className="px-4 py-3">
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
{!p.settled && hasActual && (
|
{!p.settled && hasActual && (
|
||||||
<button
|
<Button variant="solid" size="sm" onClick={() => handleSettle(p)} disabled={settlingId === p.id}>
|
||||||
onClick={() => handleSettle(p)}
|
|
||||||
disabled={settlingId === p.id}
|
|
||||||
className="btn btn-sm btn-solid"
|
|
||||||
>
|
|
||||||
{settlingId === p.id ? <Spinner /> : '结算'}
|
{settlingId === p.id ? <Spinner /> : '结算'}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
<button
|
<Button size="sm" onClick={() => setExpandedId(isExpanded ? null : p.id)}>
|
||||||
onClick={() => setExpandedId(isExpanded ? null : p.id)}
|
|
||||||
className="btn btn-sm"
|
|
||||||
>
|
|
||||||
{isExpanded ? '收起' : '详情'}
|
{isExpanded ? '收起' : '详情'}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -246,7 +241,7 @@ export default function PredictionHistoryPage() {
|
|||||||
{expandedId && (() => {
|
{expandedId && (() => {
|
||||||
const p = predictions.find(pr => pr.id === expandedId)
|
const p = predictions.find(pr => pr.id === expandedId)
|
||||||
if (!p) return null
|
if (!p) return null
|
||||||
const match = (p as any).match
|
const match = p.match
|
||||||
const reports = p.agent_outputs ?? []
|
const reports = p.agent_outputs ?? []
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
|
|||||||
@@ -15,14 +15,15 @@ import {
|
|||||||
testLLMConnection, fetchLLMUsageStats, fetchLLMModels,
|
testLLMConnection, fetchLLMUsageStats, fetchLLMModels,
|
||||||
fetchKeyRingStatus, resetKeyRingCooldown,
|
fetchKeyRingStatus, resetKeyRingCooldown,
|
||||||
fetchSchedules, createSchedule, updateSchedule, deleteSchedule, runScheduleNow,
|
fetchSchedules, createSchedule, updateSchedule, deleteSchedule, runScheduleNow,
|
||||||
} from '../dal'
|
} from '../../api/dal'
|
||||||
import type { ScheduleItem } from '../dal'
|
import type { ScheduleItem } from '../../api/dal'
|
||||||
import { changePassword, fetchAuthState, UNAUTHORIZED_EVENT } from '../api'
|
import { changePassword, fetchAuthState, UNAUTHORIZED_EVENT } from '../../api/api'
|
||||||
import type { LLMUsageStats, DataSourceSetting } from '../types'
|
import type { LLMUsageStats, DataSourceSetting } from '../../api/types'
|
||||||
import type { KeyRingStatusResponse } from '../dal'
|
import type { KeyRingStatusResponse } from '../../api/dal'
|
||||||
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner, SkeletonBlock } from '../components'
|
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner, SkeletonBlock } from '../components'
|
||||||
import SettingRow from '../SettingRow'
|
import SettingRow from '../SettingRow'
|
||||||
import AgentLLMCard from '../AgentLLMCard'
|
import AgentLLMCard from '../AgentLLMCard'
|
||||||
|
import { Button, Input } from '../../components/ui'
|
||||||
|
|
||||||
const DATA_SOURCE_KEYS = ['BZZOIRO_KEY', 'BZZOIRO_BASE']
|
const DATA_SOURCE_KEYS = ['BZZOIRO_KEY', 'BZZOIRO_BASE']
|
||||||
const LLM_KEYS = ['LLM_API_KEY', 'LLM_BASE_URL', 'LLM_MODEL']
|
const LLM_KEYS = ['LLM_API_KEY', 'LLM_BASE_URL', 'LLM_MODEL']
|
||||||
@@ -277,7 +278,7 @@ export default function SettingsPage() {
|
|||||||
<CardHeader
|
<CardHeader
|
||||||
title="Bzzoiro API"
|
title="Bzzoiro API"
|
||||||
description="赛程 / 比分 / 积分榜 / 比赛统计的唯一数据源"
|
description="赛程 / 比分 / 积分榜 / 比赛统计的唯一数据源"
|
||||||
action={<button onClick={loadSettings} disabled={settingsLoading} className="btn btn-sm">{settingsLoading ? <><Spinner /> 加载中</> : '刷新'}</button>}
|
action={<Button size="sm" onClick={loadSettings} disabled={settingsLoading}>{settingsLoading ? <><Spinner /> 加载中</> : '刷新'}</Button>}
|
||||||
/>
|
/>
|
||||||
<CardBody>
|
<CardBody>
|
||||||
{settingsLoading ? (
|
{settingsLoading ? (
|
||||||
@@ -307,7 +308,7 @@ export default function SettingsPage() {
|
|||||||
<CardHeader
|
<CardHeader
|
||||||
title="API Key 轮换环"
|
title="API Key 轮换环"
|
||||||
description={keyRing?.has_multiple ? `已配置 ${keyRing.total} 个 key,遇限流自动切换` : '当前仅 1 个 key,无法轮换'}
|
description={keyRing?.has_multiple ? `已配置 ${keyRing.total} 个 key,遇限流自动切换` : '当前仅 1 个 key,无法轮换'}
|
||||||
action={<button onClick={handleResetCooldown} disabled={ringLoading} className="btn-sm btn-outline">重置冷却</button>}
|
action={<Button variant="outline" size="sm" onClick={handleResetCooldown} disabled={ringLoading}>重置冷却</Button>}
|
||||||
/>
|
/>
|
||||||
<CardBody>
|
<CardBody>
|
||||||
{keyRing && keyRing.total > 0 ? (
|
{keyRing && keyRing.total > 0 ? (
|
||||||
@@ -345,7 +346,7 @@ export default function SettingsPage() {
|
|||||||
<CardHeader
|
<CardHeader
|
||||||
title="连接配置"
|
title="连接配置"
|
||||||
description="OpenAI 兼容接口(DeepSeek / 智谱 / 通义等)"
|
description="OpenAI 兼容接口(DeepSeek / 智谱 / 通义等)"
|
||||||
action={<button onClick={loadSettings} disabled={settingsLoading} className="btn btn-sm">{settingsLoading ? <><Spinner /> 加载中</> : '刷新'}</button>}
|
action={<Button size="sm" onClick={loadSettings} disabled={settingsLoading}>{settingsLoading ? <><Spinner /> 加载中</> : '刷新'}</Button>}
|
||||||
/>
|
/>
|
||||||
<CardBody>
|
<CardBody>
|
||||||
{settingsLoading ? (
|
{settingsLoading ? (
|
||||||
@@ -373,15 +374,15 @@ export default function SettingsPage() {
|
|||||||
<Alert kind={testResult.success ? 'ok' : 'error'} title={testResult.success ? '连接正常' : '连接失败'} message={testResult.success ? undefined : testResult.message} />
|
<Alert kind={testResult.success ? 'ok' : 'error'} title={testResult.success ? '连接正常' : '连接失败'} message={testResult.success ? undefined : testResult.message} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<button onClick={handleTest} disabled={testing} className="btn btn-sm mt-4 w-full">
|
<Button size="sm" className="mt-4 w-full" onClick={handleTest} disabled={testing}>
|
||||||
{testing ? <><Spinner /> 测试中</> : '测试 LLM 连接'}
|
{testing ? <><Spinner /> 测试中</> : '测试 LLM 连接'}
|
||||||
</button>
|
</Button>
|
||||||
<p className="mt-2 text-center text-2xs text-ink-400">测试会真实调用一次 LLM 预测,产生费用。</p>
|
<p className="mt-2 text-center text-2xs text-ink-400">测试会真实调用一次 LLM 预测,产生费用。</p>
|
||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader title="使用统计" description="从最近预测记录聚合" action={<button onClick={loadLlmStats} disabled={llmLoading} className="btn btn-sm">{llmLoading ? <><Spinner /> 加载中</> : '刷新'}</button>} />
|
<CardHeader title="使用统计" description="从最近预测记录聚合" action={<Button size="sm" onClick={loadLlmStats} disabled={llmLoading}>{llmLoading ? <><Spinner /> 加载中</> : '刷新'}</Button>} />
|
||||||
<CardBody>
|
<CardBody>
|
||||||
{llmLoading ? (
|
{llmLoading ? (
|
||||||
<div className="space-y-3"><SkeletonBlock className="h-16 w-full" /><SkeletonBlock className="h-16 w-full" /></div>
|
<div className="space-y-3"><SkeletonBlock className="h-16 w-full" /><SkeletonBlock className="h-16 w-full" /></div>
|
||||||
@@ -392,8 +393,16 @@ export default function SettingsPage() {
|
|||||||
<div className="mt-1 text-2xs text-ink-400">总预测数</div>
|
<div className="mt-1 text-2xs text-ink-400">总预测数</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="border-t-2 border-ink-900 pt-3 text-center">
|
<div className="border-t-2 border-ink-900 pt-3 text-center">
|
||||||
<div className="font-serif text-2xl font-bold tabular-nums text-ink-900">{llmStats.avg_latency_ms > 0 ? `${(llmStats.avg_latency_ms / 1000).toFixed(1)}s` : '—'}</div>
|
{/* 延迟统计后端未接入 → 明确显示「未接入」而非留白,
|
||||||
<div className="mt-1 text-2xs text-ink-400">平均延迟</div>
|
免得被误读成「延迟为 0,性能极好」 */}
|
||||||
|
<div className="font-serif text-2xl font-bold tabular-nums text-ink-900">
|
||||||
|
{llmStats.avg_latency_ms != null
|
||||||
|
? `${(llmStats.avg_latency_ms / 1000).toFixed(1)}s`
|
||||||
|
: '—'}
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 text-2xs text-ink-400">
|
||||||
|
{llmStats.avg_latency_ms != null ? '平均延迟' : '平均延迟(未接入)'}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="border-t-2 border-press pt-3 text-center">
|
<div className="border-t-2 border-press pt-3 text-center">
|
||||||
<div className="font-serif text-2xl font-bold tabular-nums text-press">{llmStats.success_rate.toFixed(0)}%</div>
|
<div className="font-serif text-2xl font-bold tabular-nums text-press">{llmStats.success_rate.toFixed(0)}%</div>
|
||||||
@@ -429,24 +438,24 @@ export default function SettingsPage() {
|
|||||||
<form onSubmit={handleChangePassword} className="space-y-3">
|
<form onSubmit={handleChangePassword} className="space-y-3">
|
||||||
<div className="grid gap-3 sm:grid-cols-3">
|
<div className="grid gap-3 sm:grid-cols-3">
|
||||||
<div>
|
<div>
|
||||||
<label className="mb-1 block text-2xs text-ink-500">当前密码</label>
|
<label htmlFor="pwd-current" className="mb-1 block text-2xs text-ink-500">当前密码</label>
|
||||||
<input type="password" value={currentPwd} onChange={e => setCurrentPwd(e.target.value)} autoComplete="current-password" className="field w-full" />
|
<Input id="pwd-current" type="password" value={currentPwd} onChange={e => setCurrentPwd(e.target.value)} autoComplete="current-password" className="w-full" />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label className="mb-1 block text-2xs text-ink-500">新密码(至少 8 位)</label>
|
<label htmlFor="pwd-new" className="mb-1 block text-2xs text-ink-500">新密码(至少 8 位)</label>
|
||||||
<input type="password" value={newPwd} onChange={e => setNewPwd(e.target.value)} autoComplete="new-password" className="field w-full" />
|
<Input id="pwd-new" type="password" value={newPwd} onChange={e => setNewPwd(e.target.value)} autoComplete="new-password" className="w-full" />
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label className="mb-1 block text-2xs text-ink-500">确认新密码</label>
|
<label htmlFor="pwd-confirm" className="mb-1 block text-2xs text-ink-500">确认新密码</label>
|
||||||
<input type="password" value={confirmPwd} onChange={e => setConfirmPwd(e.target.value)} autoComplete="new-password" className="field w-full" />
|
<Input id="pwd-confirm" type="password" value={confirmPwd} onChange={e => setConfirmPwd(e.target.value)} autoComplete="new-password" className="w-full" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{pwdNotice && <Alert kind={pwdNotice.ok ? 'ok' : 'error'} title={pwdNotice.text} />}
|
{pwdNotice && <Alert kind={pwdNotice.ok ? 'ok' : 'error'} title={pwdNotice.text} />}
|
||||||
<div className="flex items-center justify-between gap-2">
|
<div className="flex items-center justify-between gap-2">
|
||||||
<p className="text-2xs text-ink-400">修改成功后会自动退出登录。</p>
|
<p className="text-2xs text-ink-400">修改成功后会自动退出登录。</p>
|
||||||
<button type="submit" disabled={pwdBusy || !currentPwd || !newPwd || !confirmPwd} className="btn btn-solid btn-sm flex-shrink-0">
|
<Button variant="solid" size="sm" className="flex-shrink-0" type="submit" disabled={pwdBusy || !currentPwd || !newPwd || !confirmPwd}>
|
||||||
{pwdBusy ? <><Spinner /> 修改中</> : '修改密码'}
|
{pwdBusy ? <><Spinner /> 修改中</> : '修改密码'}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</CardBody>
|
</CardBody>
|
||||||
@@ -462,15 +471,9 @@ export default function SettingsPage() {
|
|||||||
title="采集调度"
|
title="采集调度"
|
||||||
description="配置 cron 表达式定时触发采集任务"
|
description="配置 cron 表达式定时触发采集任务"
|
||||||
action={
|
action={
|
||||||
<button
|
<Button size="sm" onClick={() => { createSchedule({ id: `schedule-${Date.now()}`, task: 'events', cron: '0 8 * * *', leagues: undefined, enabled: false }) .then(() => fetchSchedules().then(setSchedules)) }}>
|
||||||
onClick={() => {
|
|
||||||
createSchedule({ id: `schedule-${Date.now()}`, task: 'events', cron: '0 8 * * *', leagues: undefined, enabled: false })
|
|
||||||
.then(() => fetchSchedules().then(setSchedules))
|
|
||||||
}}
|
|
||||||
className="btn btn-sm"
|
|
||||||
>
|
|
||||||
+ 新建
|
+ 新建
|
||||||
</button>
|
</Button>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<CardBody>
|
<CardBody>
|
||||||
@@ -502,27 +505,20 @@ export default function SettingsPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<button
|
<Button size="sm" onClick={() => handleRunSchedule(s)} disabled={scheduleBusyId === s.id}>
|
||||||
onClick={() => handleRunSchedule(s)}
|
|
||||||
disabled={scheduleBusyId === s.id}
|
|
||||||
className="btn btn-sm"
|
|
||||||
>
|
|
||||||
{scheduleBusyId === s.id ? <Spinner /> : '立即执行'}
|
{scheduleBusyId === s.id ? <Spinner /> : '立即执行'}
|
||||||
</button>
|
</Button>
|
||||||
<button
|
<Button
|
||||||
onClick={() => handleToggleSchedule(s)}
|
onClick={() => handleToggleSchedule(s)}
|
||||||
disabled={scheduleBusyId === s.id}
|
disabled={scheduleBusyId === s.id}
|
||||||
className={`btn btn-sm ${s.enabled ? '' : 'btn-solid'}`}
|
variant={s.enabled ? 'default' : 'solid'}
|
||||||
|
size="sm"
|
||||||
>
|
>
|
||||||
{scheduleBusyId === s.id ? <Spinner /> : (s.enabled ? '禁用' : '启用')}
|
{scheduleBusyId === s.id ? <Spinner /> : (s.enabled ? '禁用' : '启用')}
|
||||||
</button>
|
</Button>
|
||||||
<button
|
<Button variant="danger" size="sm" onClick={() => handleDeleteSchedule(s)} disabled={scheduleBusyId === s.id}>
|
||||||
onClick={() => handleDeleteSchedule(s)}
|
|
||||||
disabled={scheduleBusyId === s.id}
|
|
||||||
className="btn btn-sm btn-danger"
|
|
||||||
>
|
|
||||||
{scheduleBusyId === s.id ? <Spinner /> : '删除'}
|
{scheduleBusyId === s.id ? <Spinner /> : '删除'}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -3,36 +3,71 @@
|
|||||||
*
|
*
|
||||||
* 所有 Admin 页面的路由定义,使用嵌套路由。
|
* 所有 Admin 页面的路由定义,使用嵌套路由。
|
||||||
* 挂载路径: /admin/*
|
* 挂载路径: /admin/*
|
||||||
|
*
|
||||||
|
* 全部页面采用 `lazy` 动态导入。
|
||||||
|
*
|
||||||
|
* 此前这里是 10 个静态 import:App.tsx 引入 adminRoutes 就把
|
||||||
|
* Dashboard/Collection/Logs/Eval/Backtest/Settings/Monitoring/
|
||||||
|
* DataCompleteness/DataPipeline/PredictionHistory 连同它们的
|
||||||
|
* 数据访问层一次性拉进首屏 —— 一个只想看赛程的匿名访客,
|
||||||
|
* 要为完整的后台界面付出流量。改为 lazy 后,后台代码只在实际
|
||||||
|
* 访问 /admin/* 时才下载。
|
||||||
|
*
|
||||||
|
* AdminLayout 保持静态引入:它是所有后台页面的公共外壳,
|
||||||
|
* 若也 lazy 则会与页面 chunk 形成串行请求(先下载 layout,
|
||||||
|
* 再下载页面),反而更慢。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { lazy, Suspense } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
import { Navigate } from 'react-router-dom'
|
import { Navigate } from 'react-router-dom'
|
||||||
import AdminLayout from './AdminLayout'
|
import AdminLayout from './AdminLayout'
|
||||||
import Dashboard from './pages/Dashboard'
|
|
||||||
import CollectionPage from './pages/Collection'
|
const Dashboard = lazy(() => import('./pages/Dashboard'))
|
||||||
import DataCompletenessPage from './pages/DataCompleteness'
|
const CollectionPage = lazy(() => import('./pages/Collection'))
|
||||||
import PredictionsPage from './pages/PredictionHistory'
|
const DataCompletenessPage = lazy(() => import('./pages/DataCompleteness'))
|
||||||
import BacktestPage from './pages/Backtest'
|
const DataPipelinePage = lazy(() => import('./pages/DataPipeline'))
|
||||||
import MonitoringPage from './pages/Monitoring'
|
const PredictionsPage = lazy(() => import('./pages/PredictionHistory'))
|
||||||
import SettingsPage from './pages/Settings'
|
const BacktestPage = lazy(() => import('./pages/Backtest'))
|
||||||
import LogsPage from './pages/Logs'
|
const MonitoringPage = lazy(() => import('./pages/Monitoring'))
|
||||||
import EvalPage from './pages/EvalPage'
|
const SettingsPage = lazy(() => import('./pages/Settings'))
|
||||||
import DataPipelinePage from './pages/DataPipeline'
|
const LogsPage = lazy(() => import('./pages/Logs'))
|
||||||
|
const EvalPage = lazy(() => import('./pages/EvalPage'))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 页面级懒加载的兜底:后台各页共用。
|
||||||
|
* 保持极简,避免后台切换时出现大块占位跳动。
|
||||||
|
*/
|
||||||
|
function AdminPageFallback() {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-[40vh] items-center justify-center">
|
||||||
|
<span className="text-xs text-ink-400" role="status" aria-live="polite">
|
||||||
|
加载中…
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 用 Suspense 包住单个后台页面 */
|
||||||
|
function page(node: ReactNode): ReactNode {
|
||||||
|
return <Suspense fallback={<AdminPageFallback />}>{node}</Suspense>
|
||||||
|
}
|
||||||
|
|
||||||
export const adminRoutes = [
|
export const adminRoutes = [
|
||||||
{
|
{
|
||||||
path: '/admin',
|
path: '/admin',
|
||||||
element: <AdminLayout />,
|
element: <AdminLayout />,
|
||||||
children: [
|
children: [
|
||||||
{ index: true, element: <Dashboard /> },
|
{ index: true, element: page(<Dashboard />) },
|
||||||
{ path: 'collection', element: <CollectionPage /> },
|
{ path: 'collection', element: page(<CollectionPage />) },
|
||||||
{ path: 'data-completeness', element: <DataCompletenessPage /> },
|
{ path: 'data-completeness', element: page(<DataCompletenessPage />) },
|
||||||
{ path: 'data-pipeline', element: <DataPipelinePage /> },
|
{ path: 'data-pipeline', element: page(<DataPipelinePage />) },
|
||||||
{ path: 'predictions', element: <PredictionsPage /> },
|
{ path: 'predictions', element: page(<PredictionsPage />) },
|
||||||
{ path: 'backtest', element: <BacktestPage /> },
|
{ path: 'backtest', element: page(<BacktestPage />) },
|
||||||
{ path: 'monitoring', element: <MonitoringPage /> },
|
{ path: 'monitoring', element: page(<MonitoringPage />) },
|
||||||
{ path: 'settings', element: <SettingsPage /> },
|
{ path: 'settings', element: page(<SettingsPage />) },
|
||||||
{ path: 'logs', element: <LogsPage /> },
|
{ path: 'logs', element: page(<LogsPage />) },
|
||||||
{ path: 'eval', element: <EvalPage /> },
|
{ path: 'eval', element: page(<EvalPage />) },
|
||||||
{ path: '*', element: <Navigate to="/admin" replace /> },
|
{ path: '*', element: <Navigate to="/admin" replace /> },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|||||||
+3
-387
@@ -1,389 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* Admin 后台 - TypeScript 类型定义
|
* 【兼容壳 · 已废弃】实现已迁至 `src/api/types.ts`。
|
||||||
*
|
* 新代码请直接从 `../api/types` 导入。
|
||||||
* 与 FastAPI 后端 Pydantic 模型对齐
|
|
||||||
*/
|
*/
|
||||||
|
export * from '../api/types'
|
||||||
// ── 系统健康 ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface HealthStatus {
|
|
||||||
status: 'ok' | 'degraded' | 'error'
|
|
||||||
version?: string
|
|
||||||
uptime_seconds?: number
|
|
||||||
checks: Record<string, 'pass' | 'fail' | 'warn'>
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 仪表盘 ──────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface DashboardStats {
|
|
||||||
leagues: League[]
|
|
||||||
// 比赛总量已移除: 用 fetchAdminStats()(/admin/stats)的精确 COUNT,
|
|
||||||
// 不要再用列表 items.length 近似(上限 100 会严重失真)
|
|
||||||
total_predictions: number
|
|
||||||
health: string
|
|
||||||
db_tables: { name: string; row_count: number; size_mb: number; last_updated: string | null }[]
|
|
||||||
last_collection: { source: string; league_code: string | null; started_at: string; finished_at: string | null; status: string; records_count: number | null; error_message: string | null }[]
|
|
||||||
recent_errors: { id: number; timestamp: string; source: string; message: string; level: string }[]
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 联赛 & 比赛 ─────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface League {
|
|
||||||
id?: number
|
|
||||||
code: string
|
|
||||||
name: string
|
|
||||||
name_zh?: string
|
|
||||||
country?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Match {
|
|
||||||
id: number
|
|
||||||
league_code?: string
|
|
||||||
season?: string | null
|
|
||||||
home_team: string
|
|
||||||
away_team: string
|
|
||||||
home_team_zh?: string | null
|
|
||||||
away_team_zh?: string | null
|
|
||||||
match_date: string
|
|
||||||
match_status: string
|
|
||||||
home_goals?: number | null
|
|
||||||
away_goals?: number | null
|
|
||||||
match_stage?: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 预测 ────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/** 列表接口返回的单路专家摘要字段 */
|
|
||||||
export interface PredictionAgentOutput {
|
|
||||||
agent: string
|
|
||||||
status: string
|
|
||||||
analysis?: string | null
|
|
||||||
probable_score?: string | null
|
|
||||||
subjective_confidence?: number | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Prediction {
|
|
||||||
id: number
|
|
||||||
match_id: number
|
|
||||||
provider: string
|
|
||||||
model: string
|
|
||||||
prompt_version?: string
|
|
||||||
mode?: string
|
|
||||||
pred_home_goals?: number | null
|
|
||||||
pred_away_goals?: number | null
|
|
||||||
pred_1x2?: string | null
|
|
||||||
subjective_confidence?: number | null
|
|
||||||
reasoning?: string | null
|
|
||||||
agent_outputs?: PredictionAgentOutput[] | null
|
|
||||||
agent_weights?: Record<string, number> | null
|
|
||||||
status?: 'success' | 'failed' | 'degraded'
|
|
||||||
created_at: string
|
|
||||||
actual_home_goals?: number | null
|
|
||||||
actual_away_goals?: number | null
|
|
||||||
settled?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PredictRequest {
|
|
||||||
match_id: number
|
|
||||||
mode?: 'single' | 'multi'
|
|
||||||
provider?: string
|
|
||||||
model?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 数据采集 ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface CollectionRequest {
|
|
||||||
status?: string
|
|
||||||
source: 'bzzoiro'
|
|
||||||
leagues?: string[]
|
|
||||||
task?: 'events' | 'standings' | 'stats' | 'all'
|
|
||||||
limit?: number
|
|
||||||
season?: string
|
|
||||||
date_from?: string
|
|
||||||
date_to?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 评估 & 回测 ─────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface EvalCalibrationBucket {
|
|
||||||
total: number
|
|
||||||
/** 该桶命中率,百分数;样本不足为 null */
|
|
||||||
hit_rate: number | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface EvalSummaryRow {
|
|
||||||
provider: string
|
|
||||||
model: string
|
|
||||||
prompt_version: string | null
|
|
||||||
total: number
|
|
||||||
/** 1X2 准确率,百分数 0-100 */
|
|
||||||
accuracy_1x2?: number
|
|
||||||
avg_score_rmse?: number | null
|
|
||||||
avg_subjective_confidence?: number | null
|
|
||||||
/** 置信度校准:按主观置信度分桶的命中率 */
|
|
||||||
calibration?: Record<string, EvalCalibrationBucket>
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface EvalSummary {
|
|
||||||
summary: Array<EvalSummaryRow>
|
|
||||||
/** 全量已结算数 */
|
|
||||||
total_settled: number
|
|
||||||
/** 应用筛选后的已结算数 */
|
|
||||||
filtered_settled: number
|
|
||||||
/** 实际评估条数(status=success 且比分齐全) */
|
|
||||||
evaluated: number
|
|
||||||
/** 跳过的 degraded 条数 */
|
|
||||||
skipped_degraded: number
|
|
||||||
/** 跳过的比分不全条数 */
|
|
||||||
skipped_incomplete?: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface BacktestRequest {
|
|
||||||
league_id?: number
|
|
||||||
date_from?: string
|
|
||||||
date_to?: string
|
|
||||||
mode?: 'single' | 'multi'
|
|
||||||
limit?: number
|
|
||||||
model?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface BacktestSummary {
|
|
||||||
total: number
|
|
||||||
scored: number
|
|
||||||
success: number
|
|
||||||
degraded: number
|
|
||||||
accuracy_1x2?: number
|
|
||||||
avg_score_rmse?: number
|
|
||||||
avg_subjective_confidence?: number
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 数据源配置 ──────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface DataSourceSetting {
|
|
||||||
key: string
|
|
||||||
label: string
|
|
||||||
description: string
|
|
||||||
sensitive: boolean
|
|
||||||
configured: boolean
|
|
||||||
masked: string
|
|
||||||
origin: 'db' | 'env' | 'none'
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DataSourceStatus {
|
|
||||||
name: string
|
|
||||||
label: string
|
|
||||||
description: string
|
|
||||||
key_configured: boolean
|
|
||||||
last_ingestion: string | null
|
|
||||||
settings: DataSourceSetting[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DataSourceTestResult {
|
|
||||||
ok: boolean
|
|
||||||
status: number | null
|
|
||||||
latency_ms: number
|
|
||||||
detail: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DataSourceTestRequest {
|
|
||||||
source: 'bzzoiro' | 'understat' | 'injuries'
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IngestionHistoryEntry {
|
|
||||||
id: string
|
|
||||||
source: string
|
|
||||||
started_at: string
|
|
||||||
finished_at: string | null
|
|
||||||
status: 'success' | 'running' | 'failed'
|
|
||||||
records_count: number | null
|
|
||||||
error_message: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── LLM 配置 ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface LLMConfig {
|
|
||||||
provider: string
|
|
||||||
model: string
|
|
||||||
base_url: string
|
|
||||||
api_key_configured: boolean
|
|
||||||
api_key_masked: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LLMUsageStats {
|
|
||||||
total_predictions: number
|
|
||||||
avg_latency_ms: number
|
|
||||||
success_rate: number
|
|
||||||
recent_predictions: Array<{
|
|
||||||
id: number
|
|
||||||
match_id: number
|
|
||||||
model: string
|
|
||||||
created_at: string
|
|
||||||
latency_ms?: number
|
|
||||||
status: 'success' | 'failed'
|
|
||||||
}>
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 系统配置 ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface SystemConfigEntry {
|
|
||||||
key: string
|
|
||||||
value_masked: string
|
|
||||||
description: string
|
|
||||||
is_sensitive: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 专家/终裁独立 LLM 配置 ────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface LLMAgentFieldState {
|
|
||||||
configured: boolean
|
|
||||||
masked: string
|
|
||||||
origin: 'db' | 'env' | 'none'
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LLMAgentConfig {
|
|
||||||
id: string
|
|
||||||
label: string
|
|
||||||
effective_model: string
|
|
||||||
fields: {
|
|
||||||
model: LLMAgentFieldState
|
|
||||||
base_url: LLMAgentFieldState
|
|
||||||
api_key: LLMAgentFieldState
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 系统日志 ─────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface LogEntry {
|
|
||||||
ts: number
|
|
||||||
level: string
|
|
||||||
logger: string
|
|
||||||
message: string
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 数据源健康/最近采集状态 ─────────────────────────────────────
|
|
||||||
|
|
||||||
export interface IngestLastFailure {
|
|
||||||
at: string
|
|
||||||
logger: string
|
|
||||||
detail: string
|
|
||||||
note: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IngestSourceStatus {
|
|
||||||
name: string
|
|
||||||
label: string
|
|
||||||
key_configured: boolean
|
|
||||||
base_url?: string
|
|
||||||
reachable: boolean | null
|
|
||||||
status?: 'key_not_configured' | 'no_data' | 'has_data'
|
|
||||||
last_success_at: string | null
|
|
||||||
latest_match_date?: string | null
|
|
||||||
recent_count: number
|
|
||||||
note: string
|
|
||||||
last_failure: IngestLastFailure | null
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 采集任务状态 ──────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface IngestJob {
|
|
||||||
id: string
|
|
||||||
task: string
|
|
||||||
params: Record<string, unknown>
|
|
||||||
status: 'pending' | 'running' | 'success' | 'failed'
|
|
||||||
result: Record<string, unknown> | null
|
|
||||||
error: string | null
|
|
||||||
created_at: string | null
|
|
||||||
started_at: string | null
|
|
||||||
finished_at: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 比赛详情 ─────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface MatchRecentPrediction {
|
|
||||||
id: number
|
|
||||||
provider: string
|
|
||||||
model: string
|
|
||||||
mode: string
|
|
||||||
pred_home_goals: number | null
|
|
||||||
pred_away_goals: number | null
|
|
||||||
alt_pred_home_goals: number | null
|
|
||||||
alt_pred_away_goals: number | null
|
|
||||||
pred_1x2: string | null
|
|
||||||
subjective_confidence: number | null
|
|
||||||
reasoning: string | null
|
|
||||||
status: string
|
|
||||||
settled: boolean
|
|
||||||
correct_1x2?: boolean
|
|
||||||
created_at: string
|
|
||||||
actual_home_goals: number | null
|
|
||||||
actual_away_goals: number | null
|
|
||||||
agent_outputs?: Array<Record<string, any>> | null
|
|
||||||
agent_weights?: Record<string, number> | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface MatchDetailOut {
|
|
||||||
id: number
|
|
||||||
league_code: string | null
|
|
||||||
season: string | null
|
|
||||||
home_team: string
|
|
||||||
away_team: string
|
|
||||||
home_team_zh: string | null
|
|
||||||
away_team_zh: string | null
|
|
||||||
match_date: string
|
|
||||||
match_status: string
|
|
||||||
home_goals: number | null
|
|
||||||
away_goals: number | null
|
|
||||||
match_stage: string | null
|
|
||||||
home_xg: number | null
|
|
||||||
away_xg: number | null
|
|
||||||
stats: MatchStatsDetail | null
|
|
||||||
recent_predictions: MatchRecentPrediction[]
|
|
||||||
}
|
|
||||||
|
|
||||||
/** bzzoiro /events/{id}/stats/ 返回的详细比赛统计 */
|
|
||||||
export interface MatchStatsDetail {
|
|
||||||
home_xg: number | null
|
|
||||||
away_xg: number | null
|
|
||||||
home_shots: number | null
|
|
||||||
away_shots: number | null
|
|
||||||
home_shots_on_target: number | null
|
|
||||||
away_shots_on_target: number | null
|
|
||||||
home_corners: number | null
|
|
||||||
away_corners: number | null
|
|
||||||
home_possession: number | null
|
|
||||||
home_yellow_cards: number | null
|
|
||||||
away_yellow_cards: number | null
|
|
||||||
home_red_cards: number | null
|
|
||||||
away_red_cards: number | null
|
|
||||||
home_big_chances: number | null
|
|
||||||
away_big_chances: number | null
|
|
||||||
home_fouls: number | null
|
|
||||||
away_fouls: number | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TeamRecentMatch {
|
|
||||||
match_date: string | null
|
|
||||||
home_team: string | null
|
|
||||||
away_team: string | null
|
|
||||||
home_goals: number | null
|
|
||||||
away_goals: number | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface MatchContextOut {
|
|
||||||
home_recent: TeamRecentMatch[]
|
|
||||||
away_recent: TeamRecentMatch[]
|
|
||||||
h2h: TeamRecentMatch[]
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 管理区统计 ─────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export interface AdminStats {
|
|
||||||
predictions: {
|
|
||||||
total: number
|
|
||||||
last_24h: number
|
|
||||||
last_7d: number
|
|
||||||
}
|
|
||||||
matches?: { total: number; finished: number }
|
|
||||||
stats?: { total: number }
|
|
||||||
standings?: { total: number }
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -7,8 +7,9 @@
|
|||||||
* r — 刷新当前页面数据(通用)
|
* r — 刷新当前页面数据(通用)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { useEffect, useState, useCallback } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
|
import { Modal } from '../components/ui'
|
||||||
|
|
||||||
interface CommandItem {
|
interface CommandItem {
|
||||||
id: string
|
id: string
|
||||||
@@ -94,17 +95,16 @@ export function CommandPalette({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<Modal
|
||||||
className="fixed inset-0 z-[60] flex items-start justify-center bg-ink-900/50 p-4 pt-[15vh]"
|
open={open}
|
||||||
onClick={onClose}
|
onClose={onClose}
|
||||||
role="dialog"
|
label="命令面板"
|
||||||
aria-modal="true"
|
animate={false}
|
||||||
aria-label="命令面板"
|
overlayClassName="z-[60] pt-[15vh]"
|
||||||
|
panelClassName="w-full max-w-lg border border-ink-900 bg-paper-50 shadow-2xl"
|
||||||
>
|
>
|
||||||
<div
|
{/* 面板内点击不冒泡到遮罩(Modal 已做 target 判断,此处仅阻止穿透) */}
|
||||||
className="w-full max-w-lg border border-ink-900 bg-paper-50 shadow-2xl"
|
<div onClick={e => e.stopPropagation()}>
|
||||||
onClick={e => e.stopPropagation()}
|
|
||||||
>
|
|
||||||
{/* 搜索框 */}
|
{/* 搜索框 */}
|
||||||
<div className="flex items-center gap-2 border-b border-ink-200 px-3 py-2.5">
|
<div className="flex items-center gap-2 border-b border-ink-200 px-3 py-2.5">
|
||||||
<span className="text-ink-400">⌘</span>
|
<span className="text-ink-400">⌘</span>
|
||||||
@@ -112,6 +112,8 @@ export function CommandPalette({
|
|||||||
value={query}
|
value={query}
|
||||||
onChange={e => setQuery(e.target.value)}
|
onChange={e => setQuery(e.target.value)}
|
||||||
placeholder="输入页面名或路径…"
|
placeholder="输入页面名或路径…"
|
||||||
|
/* 搜索框无可见标签,用 aria-label 提供可访问名称 */
|
||||||
|
aria-label="搜索页面"
|
||||||
autoFocus
|
autoFocus
|
||||||
className="flex-1 bg-transparent text-sm outline-none placeholder:text-ink-400"
|
className="flex-1 bg-transparent text-sm outline-none placeholder:text-ink-400"
|
||||||
/>
|
/>
|
||||||
@@ -126,7 +128,7 @@ export function CommandPalette({
|
|||||||
Object.entries(grouped).map(([group, groupItems]) => (
|
Object.entries(grouped).map(([group, groupItems]) => (
|
||||||
<div key={group}>
|
<div key={group}>
|
||||||
<p className="px-3 py-1 text-2xs font-medium uppercase tracking-widest text-ink-400">{group}</p>
|
<p className="px-3 py-1 text-2xs font-medium uppercase tracking-widest text-ink-400">{group}</p>
|
||||||
{groupItems.map((item, i) => (
|
{groupItems.map(item => (
|
||||||
<button
|
<button
|
||||||
key={item.id}
|
key={item.id}
|
||||||
onClick={() => { item.action(); onClose() }}
|
onClick={() => { item.action(); onClose() }}
|
||||||
@@ -150,6 +152,6 @@ export function CommandPalette({
|
|||||||
<span>ESC 关闭</span>
|
<span>ESC 关闭</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
/**
|
||||||
|
* 应用统一 API 客户端(门面)—— 2026-09 自 admin/api.ts 迁入。
|
||||||
|
*
|
||||||
|
* 鉴权:通过 POST /api/v1/auth/login 用密码换取 HttpOnly Cookie 会话,
|
||||||
|
* 同源请求自动携带 Cookie,无需手动管理密钥。
|
||||||
|
* 收到 401 时广播 `profeto:unauthorized` 事件,由 AdminLayout 切回登录页。
|
||||||
|
*
|
||||||
|
* 实现已收敛到共享层 lib/http.ts(超时/错误解析/401 广播只此一份),
|
||||||
|
* 本文件仅保留 Admin 侧的门面签名与认证接口,供既有页面按原路径导入。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { http, ApiError, UNAUTHORIZED_EVENT } from '../lib/http'
|
||||||
|
|
||||||
|
/** Admin 侧兼容导出:错误类型与会话失效事件名的规范来源在 lib/http */
|
||||||
|
export { ApiError, UNAUTHORIZED_EVENT }
|
||||||
|
|
||||||
|
const API_BASE = '/api/v1'
|
||||||
|
|
||||||
|
/** Admin 请求可覆盖项(与 lib/http RequestOptions 对齐的子集) */
|
||||||
|
type ApiOpts = {
|
||||||
|
timeoutMs?: number
|
||||||
|
/** 改密接口的 401 表示「当前密码错误」,非会话过期,置 true 跳过登出广播 */
|
||||||
|
skipAuthHandling?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
get: <T>(path: string) => http.get<T>(path),
|
||||||
|
post: <T>(path: string, body?: unknown, opts?: ApiOpts) =>
|
||||||
|
http.post<T>(path, body, opts),
|
||||||
|
put: <T>(path: string, body?: unknown, opts?: ApiOpts) =>
|
||||||
|
http.put<T>(path, body, opts),
|
||||||
|
delete: <T>(path: string) => http.delete<T>(path),
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 认证 ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** 密码登录,成功后服务端写入 HttpOnly 会话 Cookie */
|
||||||
|
export function login(password: string): Promise<{ ok: boolean }> {
|
||||||
|
return api.post(`${API_BASE}/auth/login`, { password })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 退出登录,清除会话 Cookie */
|
||||||
|
export function logout(): Promise<{ ok: boolean }> {
|
||||||
|
return api.post(`${API_BASE}/auth/logout`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 探测当前登录状态 */
|
||||||
|
export function fetchAuthState(): Promise<{
|
||||||
|
authenticated: boolean
|
||||||
|
enabled: boolean
|
||||||
|
password_origin?: 'db' | 'env' | 'none'
|
||||||
|
}> {
|
||||||
|
return api.get(`${API_BASE}/auth/me`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 修改管理员密码(成功后所有会话失效,需重新登录) */
|
||||||
|
export function changePassword(currentPassword: string, newPassword: string): Promise<{ ok: boolean; message: string }> {
|
||||||
|
// skipAuthHandling: 改密接口的 401 表示「当前密码错误」,非会话过期,不要触发登出
|
||||||
|
return api.post(
|
||||||
|
`${API_BASE}/auth/change-password`,
|
||||||
|
{ current_password: currentPassword, new_password: newPassword },
|
||||||
|
{ skipAuthHandling: true },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { API_BASE }
|
||||||
@@ -0,0 +1,481 @@
|
|||||||
|
/**
|
||||||
|
* 应用数据访问层 —— 需要鉴权的管理端点集合。
|
||||||
|
*
|
||||||
|
* 封装所有 API 端点调用,返回类型安全的数据,
|
||||||
|
* 所有端点对齐 FastAPI 后端实际实现。
|
||||||
|
*
|
||||||
|
* 归属说明:2026-09 从 `admin/dal.ts` 迁入 `src/api/`。
|
||||||
|
* 公开(免登录)端点在 `./public.ts`;admin/ 下仅留兼容壳。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { api, API_BASE } from './api'
|
||||||
|
import type {
|
||||||
|
DashboardStats,
|
||||||
|
CollectionRequest,
|
||||||
|
BacktestRequest,
|
||||||
|
BacktestSummary,
|
||||||
|
League,
|
||||||
|
Match,
|
||||||
|
Prediction,
|
||||||
|
EvalSummary,
|
||||||
|
DataSourceStatus,
|
||||||
|
DataSourceSetting,
|
||||||
|
DataSourceTestResult,
|
||||||
|
LLMAgentConfig,
|
||||||
|
LogEntry,
|
||||||
|
IngestSourceStatus,
|
||||||
|
IngestJob,
|
||||||
|
AdminStats,
|
||||||
|
LLMUsageStats,
|
||||||
|
IngestTriggerResult,
|
||||||
|
PredictionJobRef,
|
||||||
|
LLMPingResult,
|
||||||
|
SettleResult,
|
||||||
|
HealthProbe,
|
||||||
|
} from './types'
|
||||||
|
|
||||||
|
// ── 仪表盘 ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从多个端点聚合仪表盘数据。
|
||||||
|
* 后端暂无专用仪表盘端点,这里组合 health + 各列表端点。
|
||||||
|
*
|
||||||
|
* 注: 比赛真实总量请用 fetchAdminStats()(GET /admin/stats,
|
||||||
|
* 后端 COUNT(*) 精确计数)。此处曾用 matches items.length 近似,
|
||||||
|
* 已随仪表盘切换真实计数而移除,防止误用 100 上限的假总量。
|
||||||
|
*/
|
||||||
|
export async function fetchDashboard(): Promise<DashboardStats> {
|
||||||
|
// 并行获取各端点数据
|
||||||
|
// predictions 返回数组
|
||||||
|
const [leagues, predictions, health] = await Promise.allSettled([
|
||||||
|
api.get<League[]>(`${API_BASE}/leagues`),
|
||||||
|
api.get<Prediction[]>(`${API_BASE}/predictions?limit=100`),
|
||||||
|
api.get<{ status: string }>('/health'),
|
||||||
|
])
|
||||||
|
|
||||||
|
return {
|
||||||
|
leagues: leagues.status === 'fulfilled' ? leagues.value : [],
|
||||||
|
// predictions 直接返回数组
|
||||||
|
total_predictions: predictions.status === 'fulfilled' ? predictions.value?.length ?? 0 : 0,
|
||||||
|
health: health.status === 'fulfilled' ? health.value.status : 'unknown',
|
||||||
|
// 以下三项目前无对应后端端点。返回 null 而非空数组:
|
||||||
|
// 空数组会被读成「查过了,没有数据」,而事实是「还没接」。
|
||||||
|
db_tables: null,
|
||||||
|
last_collection: null,
|
||||||
|
recent_errors: null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 数据采集 ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export async function triggerCollection(req: CollectionRequest): Promise<IngestTriggerResult> {
|
||||||
|
// 后端 IngestBzzoiroRequest 的字段全部为可选,用 Partial 显式表达
|
||||||
|
// 「未选中的筛选项不发」,而不是靠 `Record<string, any>` 蒙混。
|
||||||
|
const body: Partial<CollectionRequest> & { task: string; limit: number } = {
|
||||||
|
leagues: req.leagues,
|
||||||
|
date_from: req.date_from,
|
||||||
|
date_to: req.date_to,
|
||||||
|
status: req.status || undefined,
|
||||||
|
task: req.task || 'events',
|
||||||
|
limit: req.limit || 100,
|
||||||
|
season: req.season || undefined,
|
||||||
|
}
|
||||||
|
return api.post<IngestTriggerResult>(`${API_BASE}/ingest/bzzoiro`, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 预测管理 ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export async function triggerPrediction(req: { match_id: number; mode?: string }): Promise<PredictionJobRef> {
|
||||||
|
return api.post<PredictionJobRef>(`${API_BASE}/predict`, {
|
||||||
|
match_id: req.match_id,
|
||||||
|
mode: req.mode || 'multi',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchPredictions(limit = 50): Promise<Prediction[]> {
|
||||||
|
const res = await api.get<Prediction[] | { items?: Prediction[] }>(
|
||||||
|
`${API_BASE}/predictions?limit=${limit}`,
|
||||||
|
)
|
||||||
|
// 后端声明为 list[PredictionOut];保留 items 分支兼容网关包装层。
|
||||||
|
if (Array.isArray(res)) return res
|
||||||
|
return res?.items ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 评估 & 回测 ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export async function fetchEvalSummary(params: {
|
||||||
|
limit?: number
|
||||||
|
provider?: string
|
||||||
|
model?: string
|
||||||
|
prompt_version?: string
|
||||||
|
mode?: string
|
||||||
|
league_code?: string
|
||||||
|
} = {}): Promise<EvalSummary | null> {
|
||||||
|
const sp = new URLSearchParams()
|
||||||
|
if (params.limit) sp.set('limit', String(params.limit))
|
||||||
|
if (params.provider) sp.set('provider', params.provider)
|
||||||
|
if (params.model) sp.set('model', params.model)
|
||||||
|
if (params.prompt_version) sp.set('prompt_version', params.prompt_version)
|
||||||
|
if (params.mode) sp.set('mode', params.mode)
|
||||||
|
if (params.league_code) sp.set('league_code', params.league_code)
|
||||||
|
try {
|
||||||
|
return await api.get<EvalSummary>(`${API_BASE}/eval/summary?${sp}`)
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function triggerBacktest(req: BacktestRequest): Promise<BacktestSummary> {
|
||||||
|
return api.post<BacktestSummary>(`${API_BASE}/backtest`, req, { timeoutMs: 300_000 })
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 辅助数据 ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export async function fetchLeagues(): Promise<League[]> {
|
||||||
|
try {
|
||||||
|
return await api.get<League[]>(`${API_BASE}/leagues`)
|
||||||
|
} catch {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchMatches(params: {
|
||||||
|
league?: string
|
||||||
|
status?: string
|
||||||
|
limit?: number
|
||||||
|
cursor?: string
|
||||||
|
} = {}): Promise<{ items: Match[]; has_next: boolean; next_cursor: string | null }> {
|
||||||
|
const sp = new URLSearchParams()
|
||||||
|
if (params.league) sp.set('league', params.league)
|
||||||
|
if (params.status) sp.set('status', params.status)
|
||||||
|
if (params.limit) sp.set('limit', String(params.limit))
|
||||||
|
if (params.cursor) sp.set('cursor', params.cursor)
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await api.get<{ items: Match[]; has_next: boolean; next_cursor: string | null }>(
|
||||||
|
`${API_BASE}/matches?${sp}`,
|
||||||
|
)
|
||||||
|
} catch {
|
||||||
|
return { items: [], has_next: false, next_cursor: null }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function settlePrediction(
|
||||||
|
prediction_id: number,
|
||||||
|
home_goals: number,
|
||||||
|
away_goals: number,
|
||||||
|
): Promise<SettleResult> {
|
||||||
|
return api.post<SettleResult>(`${API_BASE}/eval/settle`, {
|
||||||
|
prediction_id,
|
||||||
|
home_goals,
|
||||||
|
away_goals,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 健康检查 ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export async function fetchHealth(): Promise<HealthProbe> {
|
||||||
|
try {
|
||||||
|
return await api.get<HealthProbe>('/health')
|
||||||
|
} catch {
|
||||||
|
return { status: 'unknown' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 数据完整性 ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface DataCompletenessResponse {
|
||||||
|
generated_at: string
|
||||||
|
totals: { finished_matches: number; stats_rows: number; stats_coverage_pct: number }
|
||||||
|
issues: string[]
|
||||||
|
leagues: Array<{
|
||||||
|
code: string
|
||||||
|
name: string
|
||||||
|
country?: string
|
||||||
|
matches: { total: number; finished: number; scheduled: number; with_source_id: number; earliest_match?: string; latest_match?: string }
|
||||||
|
stats: {
|
||||||
|
rows: number
|
||||||
|
fields: Record<string, { count: number; pct: number }>
|
||||||
|
}
|
||||||
|
standings: { rows: number; latest_retrieved?: string }
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchDataCompleteness(): Promise<DataCompletenessResponse> {
|
||||||
|
return api.get<DataCompletenessResponse>(`${API_BASE}/admin/data-completeness`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 积分榜 & 比赛详情 ───────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// 这几者与它们的类型已迁到 `src/api/public.ts` —— 它们是**无需登录**
|
||||||
|
// 的公开端点,却是前台页面的数据来源。留在这里会让公开页反向依赖
|
||||||
|
// admin 层,并把 41 个后台端点一起拖进用户首屏的 chunk。
|
||||||
|
//
|
||||||
|
// 此处保留再导出,使既有 `from './dal'` 的调用路径继续可用;
|
||||||
|
// 新代码请直接从 `src/api/public` 导入。
|
||||||
|
|
||||||
|
export { fetchStandings, fetchMatchDetail, fetchMatchContext } from '../api/public'
|
||||||
|
export type { StandingRow, StandingsLeague } from '../api/public'
|
||||||
|
|
||||||
|
// ── 数据源管理 ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试数据源连通性 — 后端真实请求上游一次,不触发入库
|
||||||
|
*/
|
||||||
|
export function testDataSourceConnection(name: string): Promise<DataSourceTestResult> {
|
||||||
|
return api.post<DataSourceTestResult>(`${API_BASE}/admin/datasources/${name}/test`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取数据源状态与配置(脱敏)
|
||||||
|
*/
|
||||||
|
export function fetchDataSourceStatuses(): Promise<DataSourceStatus[]> {
|
||||||
|
return api.get<DataSourceStatus[]>(`${API_BASE}/admin/datasources`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 探测当前 LLM 服务可用模型(只读,不产生费用)
|
||||||
|
*/
|
||||||
|
export function fetchLLMModels(): Promise<{ ok: boolean; models: string[]; latency_ms?: number; detail: string }> {
|
||||||
|
return api.get(`${API_BASE}/admin/llm/models`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 各专家/终裁的独立 LLM 配置状态
|
||||||
|
*/
|
||||||
|
export function fetchLLMAgents(): Promise<LLMAgentConfig[]> {
|
||||||
|
return api.get<LLMAgentConfig[]>(`${API_BASE}/admin/llm/agents`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询系统日志(内存缓冲,最新在前)
|
||||||
|
*/
|
||||||
|
export function fetchLogs(params: { level?: string; keyword?: string; limit?: number } = {}): Promise<{ entries: LogEntry[]; count: number }> {
|
||||||
|
const sp = new URLSearchParams()
|
||||||
|
if (params.level) sp.set('level', params.level)
|
||||||
|
if (params.keyword) sp.set('keyword', params.keyword)
|
||||||
|
if (params.limit) sp.set('limit', String(params.limit))
|
||||||
|
return api.get<{ entries: LogEntry[]; count: number }>(`${API_BASE}/admin/logs?${sp}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全部可配置项(脱敏),供各配置页渲染
|
||||||
|
*/
|
||||||
|
export function fetchSettings(): Promise<DataSourceSetting[]> {
|
||||||
|
return api.get<DataSourceSetting[]>(`${API_BASE}/admin/settings`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新配置项(写入 app_settings,覆盖 .env,立即生效)
|
||||||
|
*/
|
||||||
|
export function updateSetting(key: string, value: string) {
|
||||||
|
return api.put<{ key: string; masked: string; origin: string }>(`${API_BASE}/admin/settings/${key}`, { value })
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除配置项的 DB 覆盖值,回落 .env
|
||||||
|
*/
|
||||||
|
export function clearSetting(key: string) {
|
||||||
|
return api.delete<{ key: string; masked: string; origin: string }>(`${API_BASE}/admin/settings/${key}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── LLM 配置 ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试 LLM 连接 — 调用预测端点验证
|
||||||
|
*/
|
||||||
|
export async function testLLMConnection(matchId?: number): Promise<LLMPingResult | PredictionJobRef> {
|
||||||
|
// F4 修复: 优先使用不依赖比赛的 ping 端点
|
||||||
|
try {
|
||||||
|
return await api.post<LLMPingResult>(`${API_BASE}/admin/llm/ping`, {})
|
||||||
|
} catch {
|
||||||
|
// 回退到旧方式(兼容)
|
||||||
|
return api.post<PredictionJobRef>(`${API_BASE}/predict`, {
|
||||||
|
match_id: matchId || 1,
|
||||||
|
mode: 'single',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取 LLM 使用统计 — 从预测列表聚合。
|
||||||
|
*
|
||||||
|
* 注意:延迟统计是**后端尚未提供的维度**。此前这里返回硬编码的
|
||||||
|
* `avg_latency_ms: 2400`,它会穿过类型检查、被渲染成「2.4s」,
|
||||||
|
* 并作为真实性能指标进入人的判断。现已改为 `null`,由 UI 显示
|
||||||
|
* 「—」并标注未接入。宁可留空,不可编数。
|
||||||
|
*/
|
||||||
|
export async function fetchLLMUsageStats(): Promise<LLMUsageStats> {
|
||||||
|
try {
|
||||||
|
const predictions = await fetchPredictions(50)
|
||||||
|
const total = predictions.length
|
||||||
|
const successCount = predictions.filter(p => p.pred_1x2).length
|
||||||
|
return {
|
||||||
|
total_predictions: total,
|
||||||
|
avg_latency_ms: null, // 后端暂无延迟统计端点
|
||||||
|
success_rate: total > 0 ? (successCount / total) * 100 : 0,
|
||||||
|
recent_predictions: predictions.slice(0, 10).map(p => ({
|
||||||
|
id: p.id,
|
||||||
|
match_id: p.match_id,
|
||||||
|
model: p.model,
|
||||||
|
created_at: p.created_at,
|
||||||
|
status: p.pred_1x2 ? 'success' as const : 'failed' as const,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
total_predictions: 0,
|
||||||
|
avg_latency_ms: null,
|
||||||
|
success_rate: 0,
|
||||||
|
recent_predictions: [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据源健康/最近采集状态(只读,不触发采集)
|
||||||
|
*/
|
||||||
|
export function fetchIngestStatus(): Promise<{ sources: IngestSourceStatus[] }> {
|
||||||
|
return api.get<{ sources: IngestSourceStatus[] }>(`${API_BASE}/admin/ingest/status`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上游数据源(bzzoiro)可达性探针:轻量 GET,不携带 Key、不消耗配额
|
||||||
|
*/
|
||||||
|
export function fetchUpstreamProbe(): Promise<{
|
||||||
|
ok: boolean
|
||||||
|
status_code?: number
|
||||||
|
latency_ms: number
|
||||||
|
endpoint: string
|
||||||
|
error?: string
|
||||||
|
}> {
|
||||||
|
return api.get<never>(`${API_BASE}/admin/monitoring/upstream`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 采集任务状态轮询(单任务)
|
||||||
|
*/
|
||||||
|
export function fetchIngestJob(jobId: string): Promise<IngestJob> {
|
||||||
|
return api.get<IngestJob>(`${API_BASE}/admin/ingest/jobs/${jobId}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 采集任务历史列表(GET /admin/ingest/jobs,最新在前)
|
||||||
|
*/
|
||||||
|
export function fetchIngestJobs(params: { limit?: number; status?: string } = {}): Promise<IngestJob[]> {
|
||||||
|
const q = new URLSearchParams()
|
||||||
|
if (params.limit != null) q.set('limit', String(params.limit))
|
||||||
|
if (params.status) q.set('status', params.status)
|
||||||
|
const qs = q.toString()
|
||||||
|
return api.get<IngestJob[]>(`${API_BASE}/admin/ingest/jobs${qs ? `?${qs}` : ''}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理区统计(只读):近 24h/7d 预测次数
|
||||||
|
*/
|
||||||
|
export function fetchAdminStats(): Promise<AdminStats> {
|
||||||
|
return api.get<AdminStats>(`${API_BASE}/admin/stats`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── API Key 轮换环 ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface KeyRingKeyStatus {
|
||||||
|
masked: string
|
||||||
|
blocked_remaining: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface KeyRingStatusResponse {
|
||||||
|
base_url: string
|
||||||
|
total: number
|
||||||
|
has_multiple: boolean
|
||||||
|
cooldown_seconds: number
|
||||||
|
active_index: number
|
||||||
|
active_key: string | null
|
||||||
|
keys: KeyRingKeyStatus[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchKeyRingStatus(): Promise<KeyRingStatusResponse> {
|
||||||
|
return api.get<KeyRingStatusResponse>(`${API_BASE}/admin/keyring/status`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resetKeyRingCooldown(): Promise<{ ok: boolean; message: string; stats: KeyRingStatusResponse }> {
|
||||||
|
return api.post<{ ok: boolean; message: string; stats: KeyRingStatusResponse }>(`${API_BASE}/admin/keyring/cooldown/reset`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 定时任务 ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface ScheduleItem {
|
||||||
|
id: string
|
||||||
|
task: string
|
||||||
|
cron: string
|
||||||
|
leagues?: string
|
||||||
|
enabled: boolean
|
||||||
|
last_run_at?: string | null
|
||||||
|
last_status?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchSchedules(): Promise<ScheduleItem[]> {
|
||||||
|
return api.get<ScheduleItem[]>(`${API_BASE}/admin/schedules`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createSchedule(data: { id: string; task: string; cron: string; leagues?: string; enabled: boolean }): Promise<{ ok: boolean }> {
|
||||||
|
return api.post<{ ok: boolean }>(`${API_BASE}/admin/schedules`, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateSchedule(id: string, data: Partial<ScheduleItem>): Promise<{ ok: boolean }> {
|
||||||
|
return api.put<{ ok: boolean }>(`${API_BASE}/admin/schedules/${id}`, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteSchedule(id: string): Promise<{ ok: boolean }> {
|
||||||
|
return api.delete<{ ok: boolean }>(`${API_BASE}/admin/schedules/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runScheduleNow(id: string): Promise<{ ok: boolean; message: string }> {
|
||||||
|
return api.post<{ ok: boolean; message: string }>(`${API_BASE}/admin/schedules/${id}/run`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 数据管线(质量检查 + 失败重试) ──────────────────────────────
|
||||||
|
|
||||||
|
export interface IngestFailureItem {
|
||||||
|
id: number
|
||||||
|
source: string
|
||||||
|
entity_type: string
|
||||||
|
source_record_id?: string
|
||||||
|
error_type: string
|
||||||
|
error_detail?: string
|
||||||
|
retry_count: number
|
||||||
|
status: string
|
||||||
|
next_retry_at?: string | null
|
||||||
|
created_at?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DataQualityCheckItem {
|
||||||
|
id: number
|
||||||
|
check_name: string
|
||||||
|
entity_type: string
|
||||||
|
passed: boolean
|
||||||
|
severity: string
|
||||||
|
detail?: Record<string, unknown> | null
|
||||||
|
checked_at?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DataQualityResponse {
|
||||||
|
failures: IngestFailureItem[]
|
||||||
|
checks: DataQualityCheckItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchDataQuality(): Promise<DataQualityResponse> {
|
||||||
|
return api.get<DataQualityResponse>(`${API_BASE}/admin/data-quality`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runDataQualityCheck(): Promise<{ ok: boolean; checks: Array<{ name: string; passed: boolean }> }> {
|
||||||
|
return api.post<{ ok: boolean; checks: Array<{ name: string; passed: boolean }> }>(`${API_BASE}/admin/data-quality/run`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchIngestFailures(): Promise<IngestFailureItem[]> {
|
||||||
|
return api.get<IngestFailureItem[]>(`${API_BASE}/admin/ingest-failures`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function retryIngestFailure(id: number): Promise<{ ok: boolean; message: string }> {
|
||||||
|
return api.post<{ ok: boolean; message: string }>(`${API_BASE}/admin/ingest-failures/${id}/retry`)
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
/**
|
||||||
|
* 前台公开端点 —— 预测主站与积分榜所需的最小数据访问。
|
||||||
|
*
|
||||||
|
* 为什么要单独成文件(而不是继续挂在 `admin/dal.ts` 里):
|
||||||
|
*
|
||||||
|
* 1. **分层方向错了。** 面向公众的页面反向 import `../admin/dal`,
|
||||||
|
* 意味着想重构后台就会牵连前台,目录名也持续误导人以为
|
||||||
|
* `admin/` 是可独立删除的包。公开端点的归属本就不该是 admin。
|
||||||
|
*
|
||||||
|
* 2. **它真的会进用户的首屏。** `dal.ts` 是单个大模块,内部函数
|
||||||
|
* 相互引用,打包器无法按调用点做 tree-shaking —— 实测
|
||||||
|
* Matches 只用 2 个函数,但 `/admin/ingest/jobs`、`/admin/llm/models`、
|
||||||
|
* `/admin/eval`、`/admin/backtest`、`/admin/logs` 这些字符串全部
|
||||||
|
* 留在了公开页所在 chunk 里。抽出来后可省下约 55 kB 首屏 JS。
|
||||||
|
*
|
||||||
|
* 本文件只放**无需登录即可访问**的端点。任何需要鉴权的端点继续留在
|
||||||
|
* `./dal.ts`。新增公开端点时请加在这里,不要加回 admin。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { api, API_BASE } from './api'
|
||||||
|
import type { MatchDetailOut, MatchContextOut } from './types'
|
||||||
|
|
||||||
|
// ── 积分榜 ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface StandingRow {
|
||||||
|
position: number
|
||||||
|
team: string
|
||||||
|
team_en: string
|
||||||
|
played: number
|
||||||
|
won: number
|
||||||
|
drawn: number
|
||||||
|
lost: number
|
||||||
|
goals_for: number
|
||||||
|
goals_against: number
|
||||||
|
goal_diff: number
|
||||||
|
points: number
|
||||||
|
xg_for: number | null
|
||||||
|
xg_against: number | null
|
||||||
|
form: string | null
|
||||||
|
zone: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StandingsLeague {
|
||||||
|
league_code: string
|
||||||
|
league_name: string
|
||||||
|
season: string
|
||||||
|
retrieved_at: string | null
|
||||||
|
rows: StandingRow[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchStandings(league?: string, season?: string): Promise<{ leagues: StandingsLeague[] }> {
|
||||||
|
const sp = new URLSearchParams()
|
||||||
|
if (league) sp.set('league', league)
|
||||||
|
if (season) sp.set('season', season)
|
||||||
|
const qs = sp.toString()
|
||||||
|
return api.get<{ leagues: StandingsLeague[] }>(`${API_BASE}/standings${qs ? `?${qs}` : ''}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 比赛详情 ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function fetchMatchDetail(id: number): Promise<MatchDetailOut> {
|
||||||
|
return api.get<MatchDetailOut>(`${API_BASE}/matches/${id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchMatchContext(id: number): Promise<MatchContextOut> {
|
||||||
|
return api.get<MatchContextOut>(`${API_BASE}/matches/${id}/context`)
|
||||||
|
}
|
||||||
@@ -0,0 +1,503 @@
|
|||||||
|
/**
|
||||||
|
* 应用级 API 类型定义(2026-09 自 admin/types.ts 迁入)。
|
||||||
|
*
|
||||||
|
* 与 FastAPI 后端 Pydantic 模型对齐。
|
||||||
|
*/
|
||||||
|
|
||||||
|
// ── 系统健康 ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface HealthStatus {
|
||||||
|
status: 'ok' | 'degraded' | 'error'
|
||||||
|
version?: string
|
||||||
|
uptime_seconds?: number
|
||||||
|
checks: Record<string, 'pass' | 'fail' | 'warn'>
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 仪表盘 ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface DashboardStats {
|
||||||
|
leagues: League[]
|
||||||
|
// 比赛总量已移除: 用 fetchAdminStats()(/admin/stats)的精确 COUNT,
|
||||||
|
// 不要再用列表 items.length 近似(上限 100 会严重失真)
|
||||||
|
total_predictions: number
|
||||||
|
health: string
|
||||||
|
/**
|
||||||
|
* 以下三个字段对应的后端端点在**当前版本中并不存在**。
|
||||||
|
*
|
||||||
|
* 它们曾以 `[]` 返回,调用方无法区分「确实没有错误」与
|
||||||
|
* 「这个功能还没接」——空数组是一个会被当成结论的事实断言。
|
||||||
|
* 改为可空,让「未接入」在类型层面无法被忽略。
|
||||||
|
* 后端补齐端点后,把类型收窄回数组即可(编译器会指出所有消费点)。
|
||||||
|
*/
|
||||||
|
db_tables: { name: string; row_count: number; size_mb: number; last_updated: string | null }[] | null
|
||||||
|
last_collection: { source: string; league_code: string | null; started_at: string; finished_at: string | null; status: string; records_count: number | null; error_message: string | null }[] | null
|
||||||
|
recent_errors: { id: number; timestamp: string; source: string; message: string; level: string }[] | null
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 联赛 & 比赛 ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface League {
|
||||||
|
id?: number
|
||||||
|
code: string
|
||||||
|
name: string
|
||||||
|
name_zh?: string
|
||||||
|
country?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Match {
|
||||||
|
id: number
|
||||||
|
league_code?: string
|
||||||
|
season?: string | null
|
||||||
|
home_team: string
|
||||||
|
away_team: string
|
||||||
|
home_team_zh?: string | null
|
||||||
|
away_team_zh?: string | null
|
||||||
|
match_date: string
|
||||||
|
match_status: string
|
||||||
|
home_goals?: number | null
|
||||||
|
away_goals?: number | null
|
||||||
|
match_stage?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 预测 ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** 列表接口返回的单路专家摘要字段 */
|
||||||
|
export interface PredictionAgentOutput {
|
||||||
|
agent: string
|
||||||
|
status: string
|
||||||
|
analysis?: string | null
|
||||||
|
probable_score?: string | null
|
||||||
|
subjective_confidence?: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Prediction {
|
||||||
|
id: number
|
||||||
|
match_id: number
|
||||||
|
provider: string
|
||||||
|
model: string
|
||||||
|
prompt_version?: string
|
||||||
|
mode?: string
|
||||||
|
pred_home_goals?: number | null
|
||||||
|
pred_away_goals?: number | null
|
||||||
|
alt_pred_home_goals?: number | null
|
||||||
|
alt_pred_away_goals?: number | null
|
||||||
|
pred_1x2?: string | null
|
||||||
|
subjective_confidence?: number | null
|
||||||
|
reasoning?: string | null
|
||||||
|
agent_outputs?: PredictionAgentOutput[] | null
|
||||||
|
agent_weights?: Record<string, number> | null
|
||||||
|
status?: 'success' | 'failed' | 'degraded'
|
||||||
|
created_at: string
|
||||||
|
actual_home_goals?: number | null
|
||||||
|
actual_away_goals?: number | null
|
||||||
|
settled?: boolean
|
||||||
|
/**
|
||||||
|
* 关联比赛摘要。后端 `PredictionOut.match` 是 `dict | None`
|
||||||
|
* (见 `src/api/schemas.py`),由 `_match_dict()` 拼出,字段与 `Match`
|
||||||
|
* 对齐但**每个字段都可能为 null**(比赛缺 league/team 时)。
|
||||||
|
*
|
||||||
|
* 此前这个字段在类型里根本不存在,消费方只能写 `(p as any).match`
|
||||||
|
* ——类型系统失去了它唯一该起作用的地方。现在它被显式声明为可选。
|
||||||
|
*/
|
||||||
|
match?: PredictionMatchRef | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预测记录里内嵌的比赛摘要。
|
||||||
|
*
|
||||||
|
* 独立于 `Match` 声明而不是直接复用,是因为二者契约不同:
|
||||||
|
* `Match` 的 `id`/`match_date` 是必填的(来自列表端点),
|
||||||
|
* 而这里是嵌套投影,后端 `_match_dict()` 在关联缺失时返回 null,
|
||||||
|
* 字段也可能缺失。混用会让必填约束说谎。
|
||||||
|
*/
|
||||||
|
export interface PredictionMatchRef {
|
||||||
|
id?: number | null
|
||||||
|
league_code?: string | null
|
||||||
|
season?: string | null
|
||||||
|
home_team?: string | null
|
||||||
|
away_team?: string | null
|
||||||
|
home_team_zh?: string | null
|
||||||
|
away_team_zh?: string | null
|
||||||
|
match_date?: string | null
|
||||||
|
match_status?: string | null
|
||||||
|
home_goals?: number | null
|
||||||
|
away_goals?: number | null
|
||||||
|
match_stage?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PredictRequest {
|
||||||
|
match_id: number
|
||||||
|
mode?: 'single' | 'multi'
|
||||||
|
provider?: string
|
||||||
|
model?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 通用接口返回壳 ──────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// 这些类型此前在 dal.ts 里以 `Promise<any>` 的形式存在,等于把后端契约
|
||||||
|
// 丢掉了。声明在这里(与其它 API 类型同处)而不是 dal.ts 内联,是为了
|
||||||
|
// 让消费方能直接 import type 而无需从实现文件取类型。
|
||||||
|
|
||||||
|
/** POST /api/v1/ingest/bzzoiro — 采集任务已受理,返回 job_id 供轮询 */
|
||||||
|
export interface IngestTriggerResult {
|
||||||
|
ok?: boolean
|
||||||
|
job_id?: string
|
||||||
|
message?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST /api/v1/predict — 预测任务已受理(P1-async)。注意是 202 语义,非最终结果 */
|
||||||
|
export interface PredictionJobRef {
|
||||||
|
job_id: string
|
||||||
|
status: 'running' | 'success' | 'failed'
|
||||||
|
poll_url?: string
|
||||||
|
/** job 完成后的信封:`_predict_jobs[id]` 里是 { status, result } 或 { status, error } */
|
||||||
|
result?: Prediction
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST /api/v1/admin/llm/ping — 连通性探测 */
|
||||||
|
export interface LLMPingResult {
|
||||||
|
ok?: boolean
|
||||||
|
provider?: string
|
||||||
|
model?: string
|
||||||
|
latency_ms?: number
|
||||||
|
message?: string
|
||||||
|
/** ping 端点尚未接入时后端可能只回一个透传对象 */
|
||||||
|
[key: string]: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST /api/v1/eval/settle — 结算结果 */
|
||||||
|
export interface SettleResult {
|
||||||
|
ok?: boolean
|
||||||
|
settled?: number
|
||||||
|
message?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `GET /health` 存活探针的实际返回。
|
||||||
|
*
|
||||||
|
* 与文件开头那个 `HealthStatus` 不是同一个契约 —— 那个是 admin/stats
|
||||||
|
* 聚合口径(status 为 ok|degraded|error,带 checks 明细),这个才是
|
||||||
|
* `src/api/app.py` 里 `/health` 直接吐出的结构。此前两者在 dal.ts 里
|
||||||
|
* 共用同一个 `any`,差异被彻底抹平。
|
||||||
|
*
|
||||||
|
* `version` / `uptime_seconds` 可空:后端在包元数据缺失时返回 null,
|
||||||
|
* 监控页据此降级隐藏版本卡片。
|
||||||
|
*/
|
||||||
|
export interface HealthProbe {
|
||||||
|
status: 'healthy' | 'ok' | 'unknown' | string
|
||||||
|
service?: string
|
||||||
|
version?: string | null
|
||||||
|
uptime_seconds?: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 数据采集 ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface CollectionRequest {
|
||||||
|
status?: string
|
||||||
|
source: 'bzzoiro'
|
||||||
|
leagues?: string[]
|
||||||
|
task?: 'events' | 'standings' | 'stats' | 'all'
|
||||||
|
limit?: number
|
||||||
|
season?: string
|
||||||
|
date_from?: string
|
||||||
|
date_to?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 评估 & 回测 ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface EvalCalibrationBucket {
|
||||||
|
total: number
|
||||||
|
/** 该桶命中率,百分数;样本不足为 null */
|
||||||
|
hit_rate: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EvalSummaryRow {
|
||||||
|
provider: string
|
||||||
|
model: string
|
||||||
|
prompt_version: string | null
|
||||||
|
total: number
|
||||||
|
/** 1X2 准确率,百分数 0-100 */
|
||||||
|
accuracy_1x2?: number
|
||||||
|
avg_score_rmse?: number | null
|
||||||
|
avg_subjective_confidence?: number | null
|
||||||
|
/** 置信度校准:按主观置信度分桶的命中率 */
|
||||||
|
calibration?: Record<string, EvalCalibrationBucket>
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EvalSummary {
|
||||||
|
summary: Array<EvalSummaryRow>
|
||||||
|
/** 全量已结算数 */
|
||||||
|
total_settled: number
|
||||||
|
/** 应用筛选后的已结算数 */
|
||||||
|
filtered_settled: number
|
||||||
|
/** 实际评估条数(status=success 且比分齐全) */
|
||||||
|
evaluated: number
|
||||||
|
/** 跳过的 degraded 条数 */
|
||||||
|
skipped_degraded: number
|
||||||
|
/** 跳过的比分不全条数 */
|
||||||
|
skipped_incomplete?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BacktestRequest {
|
||||||
|
league_id?: number
|
||||||
|
date_from?: string
|
||||||
|
date_to?: string
|
||||||
|
mode?: 'single' | 'multi'
|
||||||
|
limit?: number
|
||||||
|
model?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BacktestSummary {
|
||||||
|
total: number
|
||||||
|
scored: number
|
||||||
|
success: number
|
||||||
|
degraded: number
|
||||||
|
accuracy_1x2?: number
|
||||||
|
avg_score_rmse?: number
|
||||||
|
avg_subjective_confidence?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 数据源配置 ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface DataSourceSetting {
|
||||||
|
key: string
|
||||||
|
label: string
|
||||||
|
description: string
|
||||||
|
sensitive: boolean
|
||||||
|
configured: boolean
|
||||||
|
masked: string
|
||||||
|
origin: 'db' | 'env' | 'none'
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DataSourceStatus {
|
||||||
|
name: string
|
||||||
|
label: string
|
||||||
|
description: string
|
||||||
|
key_configured: boolean
|
||||||
|
last_ingestion: string | null
|
||||||
|
settings: DataSourceSetting[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DataSourceTestResult {
|
||||||
|
ok: boolean
|
||||||
|
status: number | null
|
||||||
|
latency_ms: number
|
||||||
|
detail: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DataSourceTestRequest {
|
||||||
|
source: 'bzzoiro' | 'understat' | 'injuries'
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IngestionHistoryEntry {
|
||||||
|
id: string
|
||||||
|
source: string
|
||||||
|
started_at: string
|
||||||
|
finished_at: string | null
|
||||||
|
status: 'success' | 'running' | 'failed'
|
||||||
|
records_count: number | null
|
||||||
|
error_message: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── LLM 配置 ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface LLMConfig {
|
||||||
|
provider: string
|
||||||
|
model: string
|
||||||
|
base_url: string
|
||||||
|
api_key_configured: boolean
|
||||||
|
api_key_masked: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LLMUsageStats {
|
||||||
|
total_predictions: number
|
||||||
|
/**
|
||||||
|
* 平均延迟(毫秒)。**后端当前没有延迟统计端点**,故此处为 `null`。
|
||||||
|
*
|
||||||
|
* 曾经这里是一个硬编码的 2400,并且会被渲染成看起来完全可信的
|
||||||
|
* 「2.4s」。运营据此判断系统性能时,读到的是一个不存在的数字。
|
||||||
|
* 改为 `null` 是刻意的:它让「未接入」这件事在类型层面强制可见,
|
||||||
|
* 调用方必须显式处理,而不是继承一个编造的默认值。
|
||||||
|
*/
|
||||||
|
avg_latency_ms: number | null
|
||||||
|
success_rate: number
|
||||||
|
recent_predictions: Array<{
|
||||||
|
id: number
|
||||||
|
match_id: number
|
||||||
|
model: string
|
||||||
|
created_at: string
|
||||||
|
latency_ms?: number
|
||||||
|
status: 'success' | 'failed'
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 系统配置 ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface SystemConfigEntry {
|
||||||
|
key: string
|
||||||
|
value_masked: string
|
||||||
|
description: string
|
||||||
|
is_sensitive: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 专家/终裁独立 LLM 配置 ────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface LLMAgentFieldState {
|
||||||
|
configured: boolean
|
||||||
|
masked: string
|
||||||
|
origin: 'db' | 'env' | 'none'
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LLMAgentConfig {
|
||||||
|
id: string
|
||||||
|
label: string
|
||||||
|
effective_model: string
|
||||||
|
fields: {
|
||||||
|
model: LLMAgentFieldState
|
||||||
|
base_url: LLMAgentFieldState
|
||||||
|
api_key: LLMAgentFieldState
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 系统日志 ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface LogEntry {
|
||||||
|
ts: number
|
||||||
|
level: string
|
||||||
|
logger: string
|
||||||
|
message: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 数据源健康/最近采集状态 ─────────────────────────────────────
|
||||||
|
|
||||||
|
export interface IngestLastFailure {
|
||||||
|
at: string
|
||||||
|
logger: string
|
||||||
|
detail: string
|
||||||
|
note: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IngestSourceStatus {
|
||||||
|
name: string
|
||||||
|
label: string
|
||||||
|
key_configured: boolean
|
||||||
|
base_url?: string
|
||||||
|
reachable: boolean | null
|
||||||
|
status?: 'key_not_configured' | 'no_data' | 'has_data'
|
||||||
|
last_success_at: string | null
|
||||||
|
latest_match_date?: string | null
|
||||||
|
recent_count: number
|
||||||
|
note: string
|
||||||
|
last_failure: IngestLastFailure | null
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 采集任务状态 ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface IngestJob {
|
||||||
|
id: string
|
||||||
|
task: string
|
||||||
|
params: Record<string, unknown>
|
||||||
|
status: 'pending' | 'running' | 'success' | 'failed'
|
||||||
|
result: Record<string, unknown> | null
|
||||||
|
error: string | null
|
||||||
|
created_at: string | null
|
||||||
|
started_at: string | null
|
||||||
|
finished_at: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 比赛详情 ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface MatchRecentPrediction {
|
||||||
|
id: number
|
||||||
|
provider: string
|
||||||
|
model: string
|
||||||
|
mode: string
|
||||||
|
pred_home_goals: number | null
|
||||||
|
pred_away_goals: number | null
|
||||||
|
alt_pred_home_goals: number | null
|
||||||
|
alt_pred_away_goals: number | null
|
||||||
|
pred_1x2: string | null
|
||||||
|
subjective_confidence: number | null
|
||||||
|
reasoning: string | null
|
||||||
|
status: string
|
||||||
|
settled: boolean
|
||||||
|
correct_1x2?: boolean
|
||||||
|
created_at: string
|
||||||
|
actual_home_goals: number | null
|
||||||
|
actual_away_goals: number | null
|
||||||
|
/**
|
||||||
|
* 单路专家原始输出。后端 `agent_outputs` 是 `list[dict]`(未定 schema),
|
||||||
|
* 各专家的键随 agent 不同。这里用 `Record<string, unknown>` 而非 `any`:
|
||||||
|
* 取值处必须显式收窄,编译器不再放行任意属性访问。
|
||||||
|
*/
|
||||||
|
agent_outputs?: Array<Record<string, unknown>> | null
|
||||||
|
agent_weights?: Record<string, number> | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MatchDetailOut {
|
||||||
|
id: number
|
||||||
|
league_code: string | null
|
||||||
|
season: string | null
|
||||||
|
home_team: string
|
||||||
|
away_team: string
|
||||||
|
home_team_zh: string | null
|
||||||
|
away_team_zh: string | null
|
||||||
|
match_date: string
|
||||||
|
match_status: string
|
||||||
|
home_goals: number | null
|
||||||
|
away_goals: number | null
|
||||||
|
match_stage: string | null
|
||||||
|
home_xg: number | null
|
||||||
|
away_xg: number | null
|
||||||
|
stats: MatchStatsDetail | null
|
||||||
|
recent_predictions: MatchRecentPrediction[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** bzzoiro /events/{id}/stats/ 返回的详细比赛统计 */
|
||||||
|
export interface MatchStatsDetail {
|
||||||
|
home_xg: number | null
|
||||||
|
away_xg: number | null
|
||||||
|
home_shots: number | null
|
||||||
|
away_shots: number | null
|
||||||
|
home_shots_on_target: number | null
|
||||||
|
away_shots_on_target: number | null
|
||||||
|
home_corners: number | null
|
||||||
|
away_corners: number | null
|
||||||
|
home_possession: number | null
|
||||||
|
home_yellow_cards: number | null
|
||||||
|
away_yellow_cards: number | null
|
||||||
|
home_red_cards: number | null
|
||||||
|
away_red_cards: number | null
|
||||||
|
home_big_chances: number | null
|
||||||
|
away_big_chances: number | null
|
||||||
|
home_fouls: number | null
|
||||||
|
away_fouls: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TeamRecentMatch {
|
||||||
|
match_date: string | null
|
||||||
|
home_team: string | null
|
||||||
|
away_team: string | null
|
||||||
|
home_goals: number | null
|
||||||
|
away_goals: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MatchContextOut {
|
||||||
|
home_recent: TeamRecentMatch[]
|
||||||
|
away_recent: TeamRecentMatch[]
|
||||||
|
h2h: TeamRecentMatch[]
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 管理区统计 ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface AdminStats {
|
||||||
|
predictions: {
|
||||||
|
total: number
|
||||||
|
last_24h: number
|
||||||
|
last_7d: number
|
||||||
|
}
|
||||||
|
matches?: { total: number; finished: number }
|
||||||
|
stats?: { total: number }
|
||||||
|
standings?: { total: number }
|
||||||
|
}
|
||||||
@@ -1,8 +1,17 @@
|
|||||||
import { Component, ErrorInfo, ReactNode } from 'react'
|
import { Component, ErrorInfo, ReactNode } from 'react'
|
||||||
|
import { Button } from './ui'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
children: ReactNode
|
children: ReactNode
|
||||||
fallback?: ReactNode
|
fallback?: ReactNode
|
||||||
|
/**
|
||||||
|
* 该边界是否铺满整个视口。
|
||||||
|
*
|
||||||
|
* 应用最外层的边界应铺满(`true`,默认);而当边界下沉到
|
||||||
|
* 路由级、嵌在 SiteLayout 的 <main> 里时,铺满视口会撑开
|
||||||
|
* 布局并让页头页脚错位 —— 那种场景传 `false`,改为局部卡片。
|
||||||
|
*/
|
||||||
|
fullScreen?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
interface State {
|
interface State {
|
||||||
@@ -29,20 +38,25 @@ export class ErrorBoundary extends Component<Props, State> {
|
|||||||
if (this.props.fallback) {
|
if (this.props.fallback) {
|
||||||
return this.props.fallback
|
return this.props.fallback
|
||||||
}
|
}
|
||||||
|
const fullScreen = this.props.fullScreen ?? true
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen items-center justify-center bg-paper-50 p-6">
|
<div
|
||||||
|
className={
|
||||||
|
fullScreen
|
||||||
|
? 'flex min-h-screen items-center justify-center bg-paper-50 p-6'
|
||||||
|
: 'flex min-h-[50vh] items-center justify-center p-6'
|
||||||
|
}
|
||||||
|
role="alert"
|
||||||
|
>
|
||||||
<div className="max-w-md space-y-3 border border-ink-900 bg-paper-50 p-6 text-center">
|
<div className="max-w-md space-y-3 border border-ink-900 bg-paper-50 p-6 text-center">
|
||||||
<p className="text-2xs tracking-[0.3em] text-ink-400">EXCEPTION</p>
|
<p className="text-2xs tracking-[0.3em] text-ink-400">EXCEPTION</p>
|
||||||
<h2 className="font-serif text-lg font-bold text-ink-900">页面出现错误</h2>
|
<h2 className="font-serif text-lg font-bold text-ink-900">页面出现错误</h2>
|
||||||
<p className="text-sm leading-relaxed text-ink-500">
|
<p className="text-sm leading-relaxed text-ink-500">
|
||||||
{this.state.error?.message || '未知错误'}
|
{this.state.error?.message || '未知错误'}
|
||||||
</p>
|
</p>
|
||||||
<button
|
<Button size="sm" onClick={() => this.setState({ hasError: false, error: null })}>
|
||||||
onClick={() => this.setState({ hasError: false, error: null })}
|
|
||||||
className="btn btn-sm"
|
|
||||||
>
|
|
||||||
重试
|
重试
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
/**
|
||||||
|
* SiteLayout —— 前台公开站点的共享外壳(报头 + 内容区 + 页脚)。
|
||||||
|
*
|
||||||
|
* 背景:此前 `HomePage` 与 `StandingsLayout` 各自复制了一遍
|
||||||
|
* `<main className="mx-auto max-w-5xl px-5 py-6 sm:px-8 sm:py-8">`
|
||||||
|
* 和 `<footer className="mx-auto max-w-5xl px-5 pb-10 sm:px-8">`。
|
||||||
|
* 两处 className 逐字相同,唯一差异是 Masthead 的 active 值与
|
||||||
|
* 页脚文案。改一次容器内边距要改两处,加第三个页面就是第三处。
|
||||||
|
*
|
||||||
|
* 这里把「容器宽度 / 内边距 / 页脚分隔线样式」收进单一来源,
|
||||||
|
* 调用方只需提供 active(决定报头高亮)与页脚文案。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import Masthead from './Masthead'
|
||||||
|
import type { MastheadActive } from './Masthead'
|
||||||
|
|
||||||
|
/** 报头的 active 分区,决定报刊头里哪个分区链接高亮 */
|
||||||
|
export type SiteSection = MastheadActive
|
||||||
|
|
||||||
|
export interface SiteLayoutProps {
|
||||||
|
/** 当前分区,用于报头高亮 */
|
||||||
|
active: SiteSection
|
||||||
|
/** 页脚文案(各分区声明差异,如首页含免责声明) */
|
||||||
|
footerNote: ReactNode
|
||||||
|
children: ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SiteLayout({ active, footerNote, children }: SiteLayoutProps) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-paper-50">
|
||||||
|
<Masthead active={active} />
|
||||||
|
|
||||||
|
<main className="mx-auto max-w-5xl px-5 py-6 sm:px-8 sm:py-8">
|
||||||
|
{children}
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer className="mx-auto max-w-5xl px-5 pb-10 sm:px-8">
|
||||||
|
<div className="border-t border-ink-200 pt-3 text-center text-2xs leading-relaxed text-ink-400">
|
||||||
|
{footerNote}
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default SiteLayout
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
* - JSON/HTML 容错解析
|
* - JSON/HTML 容错解析
|
||||||
* - 请求竞态防护(可选 signal)
|
* - 请求竞态防护(可选 signal)
|
||||||
*
|
*
|
||||||
* 注: Admin 侧的 admin/api.ts 是本模块的薄门面,不再有第二套实现。
|
* 注: src/api/api.ts(曾位于 admin/api.ts)是本模块的薄门面,不再有第二套实现。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/** 会话失效事件名,AdminLayout 监听后弹出登录页 */
|
/** 会话失效事件名,AdminLayout 监听后弹出登录页 */
|
||||||
|
|||||||
@@ -10,11 +10,12 @@
|
|||||||
* matches/components/MatchDetailSection.tsx — 赛程行 + 展开详情
|
* matches/components/MatchDetailSection.tsx — 赛程行 + 展开详情
|
||||||
* 本文件只负责状态装配与版面组织,不含数据获取与展示细节。
|
* 本文件只负责状态装配与版面组织,不含数据获取与展示细节。
|
||||||
*/
|
*/
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import { useMemo, useRef, useState } from 'react'
|
||||||
import { Link } from 'react-router-dom'
|
import { Link } from 'react-router-dom'
|
||||||
import { fetchMatchDetail, fetchMatchContext } from '../admin/dal'
|
import { fetchMatchDetail, fetchMatchContext } from '../api/public'
|
||||||
import type { MatchDetailOut, MatchContextOut } from '../admin/types'
|
import type { MatchDetailOut, MatchContextOut } from '../api/types'
|
||||||
import BackTop from '../components/BackTop'
|
import BackTop from '../components/BackTop'
|
||||||
|
import { useCanScrollRight } from '../lib/useScroll'
|
||||||
import { useMatchesList } from './matches/hooks/useMatchesList'
|
import { useMatchesList } from './matches/hooks/useMatchesList'
|
||||||
import { useMatchPredict } from './matches/hooks/useMatchPredict'
|
import { useMatchPredict } from './matches/hooks/useMatchPredict'
|
||||||
import { useLeagues } from './matches/hooks/useLeagues'
|
import { useLeagues } from './matches/hooks/useLeagues'
|
||||||
@@ -22,6 +23,7 @@ import { PredictModal } from './matches/components/MatchPredictPanel'
|
|||||||
import { MatchRow } from './matches/components/MatchDetailSection'
|
import { MatchRow } from './matches/components/MatchDetailSection'
|
||||||
import { Spinner, SkeletonRows, Switch, formatDateHeader, groupByDate, withinNext3Days } from './matches/ui'
|
import { Spinner, SkeletonRows, Switch, formatDateHeader, groupByDate, withinNext3Days } from './matches/ui'
|
||||||
import { type Match } from './matches/types'
|
import { type Match } from './matches/types'
|
||||||
|
import { Button, Tabs } from '../components/ui'
|
||||||
|
|
||||||
export default function Matches() {
|
export default function Matches() {
|
||||||
const [error, setError] = useState<string | null>(null) // 列表与预测共用(拆分前即如此)
|
const [error, setError] = useState<string | null>(null) // 列表与预测共用(拆分前即如此)
|
||||||
@@ -54,12 +56,25 @@ export default function Matches() {
|
|||||||
|
|
||||||
/** 未开赛默认仅展示未来 3 天;其余状态展示全部。showAllUpcoming=true 时展开全部。 */
|
/** 未开赛默认仅展示未来 3 天;其余状态展示全部。showAllUpcoming=true 时展开全部。 */
|
||||||
const isScheduledView = status === 'scheduled'
|
const isScheduledView = status === 'scheduled'
|
||||||
const visibleMatches = (!isScheduledView || showAllUpcoming)
|
const visibleMatches = useMemo(
|
||||||
? matches
|
() => (!isScheduledView || showAllUpcoming)
|
||||||
: matches.filter(m => withinNext3Days(m.match_date))
|
? matches
|
||||||
|
: matches.filter(m => withinNext3Days(m.match_date)),
|
||||||
|
[isScheduledView, showAllUpcoming, matches],
|
||||||
|
)
|
||||||
// 是否有被折叠的未开赛比赛(用于显示「展开」按钮)
|
// 是否有被折叠的未开赛比赛(用于显示「展开」按钮)
|
||||||
const hasHiddenUpcoming = isScheduledView && !showAllUpcoming && matches.length > visibleMatches.length
|
const hasHiddenUpcoming = isScheduledView && !showAllUpcoming && matches.length > visibleMatches.length
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按日期分组。
|
||||||
|
*
|
||||||
|
* 此前 `groupByDate(visibleMatches)` 直接写在 JSX 里,每次 render 都会
|
||||||
|
* 重算整个列表的分组 —— 而列表可能有上百场比赛,且任何无关的 state
|
||||||
|
* 变化(错误横幅开关、联赛 tab 溢出检测的 canScrollRight 翻转)都会
|
||||||
|
* 触发整表重算与全量 DOM 重建。
|
||||||
|
*/
|
||||||
|
const dateGroups = useMemo(() => groupByDate(visibleMatches), [visibleMatches])
|
||||||
|
|
||||||
/** 展开时懒加载详情: 缓存命中则不再请求 */
|
/** 展开时懒加载详情: 缓存命中则不再请求 */
|
||||||
async function toggleExpand(m: Match) {
|
async function toggleExpand(m: Match) {
|
||||||
if (expandedId === m.id) { setExpandedId(null); return }
|
if (expandedId === m.id) { setExpandedId(null); return }
|
||||||
@@ -80,41 +95,22 @@ export default function Matches() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 联赛 tab 溢出检测:可向右滚动时右缘显示渐隐提示
|
// 联赛 tab 溢出检测:可向右滚动时右缘显示渐隐提示
|
||||||
const leagueNavRef = useRef<HTMLDivElement>(null)
|
// 监听逻辑已抽到 lib/useScroll(与 BackTop、AdminLayout 共用同一实现)
|
||||||
const [canScrollRight, setCanScrollRight] = useState(false)
|
const leagueNavRef = useRef<HTMLElement>(null)
|
||||||
useEffect(() => {
|
const canScrollRight = useCanScrollRight(leagueNavRef, 8, [leagues])
|
||||||
const el = leagueNavRef.current
|
|
||||||
if (!el) return
|
|
||||||
const update = () => setCanScrollRight(el.scrollWidth - el.scrollLeft - el.clientWidth > 8)
|
|
||||||
update()
|
|
||||||
el.addEventListener('scroll', update, { passive: true })
|
|
||||||
window.addEventListener('resize', update)
|
|
||||||
return () => {
|
|
||||||
el.removeEventListener('scroll', update)
|
|
||||||
window.removeEventListener('resize', update)
|
|
||||||
}
|
|
||||||
}, [leagues])
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-5">
|
<div className="space-y-5">
|
||||||
{/* ── 联赛版面切换 ── */}
|
{/* ── 联赛版面切换 ── */}
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<nav
|
<Tabs
|
||||||
ref={leagueNavRef}
|
ref={leagueNavRef}
|
||||||
className="flex items-center gap-6 overflow-x-auto border-b border-ink-900"
|
ariaLabel="联赛"
|
||||||
aria-label="联赛"
|
className="gap-6 border-b border-ink-900"
|
||||||
>
|
value={league}
|
||||||
{leagues.map(l => (
|
onChange={setLeague}
|
||||||
<button
|
items={leagues.map(l => ({ value: l.code, label: l.name }))}
|
||||||
key={l.code}
|
/>
|
||||||
onClick={() => setLeague(l.code)}
|
|
||||||
aria-current={league === l.code ? 'true' : undefined}
|
|
||||||
className={`relative tab ${league === l.code ? 'tab-on' : ''} font-serif`}
|
|
||||||
>
|
|
||||||
{l.name}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</nav>
|
|
||||||
{canScrollRight && (
|
{canScrollRight && (
|
||||||
<div aria-hidden="true" className="pointer-events-none absolute inset-y-0 right-0 w-10 bg-gradient-to-l from-paper-50 to-transparent" />
|
<div aria-hidden="true" className="pointer-events-none absolute inset-y-0 right-0 w-10 bg-gradient-to-l from-paper-50 to-transparent" />
|
||||||
)}
|
)}
|
||||||
@@ -141,20 +137,21 @@ export default function Matches() {
|
|||||||
? `未来3天 ${visibleMatches.length} / 共 ${matches.length} 场`
|
? `未来3天 ${visibleMatches.length} / 共 ${matches.length} 场`
|
||||||
: `共 ${visibleMatches.length} 场`}
|
: `共 ${visibleMatches.length} 场`}
|
||||||
</span>
|
</span>
|
||||||
<button onClick={load} disabled={loading} className="btn btn-sm">
|
<Button size="sm" onClick={load} disabled={loading}>
|
||||||
{loading ? (<><Spinner /> 获取中</>) : '刷新'}
|
{loading ? (<><Spinner /> 获取中</>) : '刷新'}
|
||||||
</button>
|
</Button>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* ── 错误提示(统一 error-banner 样式) ── */}
|
{/* ── 错误提示(统一 error-banner 样式) ── */}
|
||||||
{error && (
|
{error && (
|
||||||
<div className="error-banner">
|
/* role=alert:错误是异步出现的,需立即被屏幕阅读器朗读 */
|
||||||
|
<div className="error-banner" role="alert">
|
||||||
<div>
|
<div>
|
||||||
<p className="error-banner-title">请求失败</p>
|
<p className="error-banner-title">请求失败</p>
|
||||||
<p className="error-banner-detail">{error}</p>
|
<p className="error-banner-detail">{error}</p>
|
||||||
</div>
|
</div>
|
||||||
<button onClick={() => setError(null)} className="text-ink-400 transition-colors hover:text-ink-900 text-lg leading-none p-1" aria-label="关闭">×</button>
|
<Button variant="ghost" size="sm" onClick={() => setError(null)} className="!border-transparent !px-1 text-lg leading-none" aria-label="关闭错误提示">×</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -226,7 +223,7 @@ export default function Matches() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!loading && groupByDate(visibleMatches).map(([dateKey, group]) => (
|
{!loading && dateGroups.map(([dateKey, group]) => (
|
||||||
<div key={dateKey}>
|
<div key={dateKey}>
|
||||||
{/* 日期分组头:sticky 但 z 低于弹窗 z-50 */}
|
{/* 日期分组头:sticky 但 z 低于弹窗 z-50 */}
|
||||||
<div className="sticky top-0 z-20 border-b border-ink-900 bg-paper-100 px-3 py-2 text-xs font-medium tracking-wide text-ink-600">
|
<div className="sticky top-0 z-20 border-b border-ink-900 bg-paper-100 px-3 py-2 text-xs font-medium tracking-wide text-ink-600">
|
||||||
@@ -253,16 +250,13 @@ export default function Matches() {
|
|||||||
{!loading && (hasHiddenUpcoming || nextCursor) && (
|
{!loading && (hasHiddenUpcoming || nextCursor) && (
|
||||||
<div className="flex justify-center pt-4">
|
<div className="flex justify-center pt-4">
|
||||||
{hasHiddenUpcoming ? (
|
{hasHiddenUpcoming ? (
|
||||||
<button
|
<Button variant="outline" className="min-h-[44px] w-full max-w-xs sm:w-auto" onClick={() => setShowAllUpcoming(true)}>
|
||||||
onClick={() => setShowAllUpcoming(true)}
|
|
||||||
className="btn btn-outline min-h-[44px] w-full max-w-xs sm:w-auto"
|
|
||||||
>
|
|
||||||
显示后续 {matches.length - visibleMatches.length} 场未开赛
|
显示后续 {matches.length - visibleMatches.length} 场未开赛
|
||||||
</button>
|
</Button>
|
||||||
) : (
|
) : (
|
||||||
<button onClick={loadMore} disabled={loadingMore} className="btn min-h-[44px] w-full max-w-xs sm:w-auto">
|
<Button className="min-h-[44px] w-full max-w-xs sm:w-auto" onClick={loadMore} disabled={loadingMore}>
|
||||||
{loadingMore ? (<><Spinner /> 获取中</>) : '载入更多赛程'}
|
{loadingMore ? (<><Spinner /> 获取中</>) : '载入更多赛程'}
|
||||||
</button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -270,12 +264,9 @@ export default function Matches() {
|
|||||||
{/* 已展开全部但未开赛:提供「收起」回未来 3 天 */}
|
{/* 已展开全部但未开赛:提供「收起」回未来 3 天 */}
|
||||||
{!loading && isScheduledView && showAllUpcoming && matches.length > 0 && (
|
{!loading && isScheduledView && showAllUpcoming && matches.length > 0 && (
|
||||||
<div className="flex justify-center pt-2">
|
<div className="flex justify-center pt-2">
|
||||||
<button
|
<Button variant="ghost" size="sm" onClick={() => setShowAllUpcoming(false)}>
|
||||||
onClick={() => setShowAllUpcoming(false)}
|
|
||||||
className="text-xs text-ink-400 hover:text-ink-700 transition-colors"
|
|
||||||
>
|
|
||||||
收起,仅显示未来 3 天
|
收起,仅显示未来 3 天
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -7,49 +7,49 @@
|
|||||||
|
|
||||||
import { useEffect, useState, useCallback } from 'react'
|
import { useEffect, useState, useCallback } from 'react'
|
||||||
import BackTop from '../components/BackTop'
|
import BackTop from '../components/BackTop'
|
||||||
import { fetchStandings } from '../admin/dal'
|
import { fetchStandings } from '../api/public'
|
||||||
import type { StandingsLeague, StandingRow } from '../admin/dal'
|
import type { StandingsLeague, StandingRow } from '../api/public'
|
||||||
import { useLeagues } from './matches/hooks/useLeagues'
|
import { useLeagues } from './matches/hooks/useLeagues'
|
||||||
import { Spinner } from '../admin/components'
|
import { Spinner, Tabs, Button } from '../components/ui'
|
||||||
|
|
||||||
const ZONE_META: Record<string, { label: string; cls: string }> = {
|
const ZONE_META: Record<string, { label: string; cls: string }> = {
|
||||||
// 欧战资格
|
// 欧战资格
|
||||||
'Champions League': { label: '欧冠区', cls: 'bg-ok-100 text-ok-700' },
|
'Champions League': { label: '欧冠区', cls: 'bg-ok-100 text-ok-700' },
|
||||||
'Champions League Qualification': { label: '欧冠资格', cls: 'bg-ok-100 text-ok-700' },
|
'Champions League Qualification': { label: '欧冠资格', cls: 'bg-ok-100 text-ok-700' },
|
||||||
'Europa League': { label: '欧联区', cls: 'bg-warn-100 text-warn-700' },
|
'Europa League': { label: '欧联区', cls: 'bg-warn-100 text-warn-700' },
|
||||||
'Conference League': { label: '欧协杯', cls: 'bg-sky-100 text-sky-700' },
|
'Conference League': { label: '欧协杯', cls: 'bg-euro-100 text-euro-700' },
|
||||||
'Conference League Qualification': { label: '欧协杯', cls: 'bg-sky-100 text-sky-700' },
|
'Conference League Qualification': { label: '欧协杯', cls: 'bg-euro-100 text-euro-700' },
|
||||||
'Europa Conference League': { label: '欧协杯', cls: 'bg-sky-100 text-sky-700' },
|
'Europa Conference League': { label: '欧协杯', cls: 'bg-euro-100 text-euro-700' },
|
||||||
'Europa Conference League Qualification': { label: '欧协杯', cls: 'bg-sky-100 text-sky-700' },
|
'Europa Conference League Qualification': { label: '欧协杯', cls: 'bg-euro-100 text-euro-700' },
|
||||||
// 升级
|
// 升级
|
||||||
'Championship': { label: '升级区', cls: 'bg-ok-100 text-ok-700' },
|
'Championship': { label: '升级区', cls: 'bg-ok-100 text-ok-700' },
|
||||||
'Promotion': { label: '升级区', cls: 'bg-ok-100 text-ok-700' },
|
'Promotion': { label: '升级区', cls: 'bg-ok-100 text-ok-700' },
|
||||||
'Promotion Group': { label: '升级组', cls: 'bg-ok-100 text-ok-700' },
|
'Promotion Group': { label: '升级组', cls: 'bg-ok-100 text-ok-700' },
|
||||||
// 降级
|
// 降级
|
||||||
'Relegation': { label: '降级区', cls: 'bg-bad-100 text-bad-700' },
|
'Relegation': { label: '降级区', cls: 'bg-bad-100 text-bad-700' },
|
||||||
'Relegation Playoffs': { label: '降级附加赛', cls: 'bg-orange-100 text-orange-700' },
|
'Relegation Playoffs': { label: '降级附加赛', cls: 'bg-playoff-100 text-playoff-700' },
|
||||||
'Relegation Group': { label: '降级组', cls: 'bg-bad-100 text-bad-700' },
|
'Relegation Group': { label: '降级组', cls: 'bg-bad-100 text-bad-700' },
|
||||||
// 附加赛
|
// 附加赛
|
||||||
'Playoffs': { label: '附加赛', cls: 'bg-warn-100 text-warn-700' },
|
'Playoffs': { label: '附加赛', cls: 'bg-warn-100 text-warn-700' },
|
||||||
'Championship Playoffs': { label: '升级附加赛', cls: 'bg-warn-100 text-warn-700' },
|
'Championship Playoffs': { label: '升级附加赛', cls: 'bg-warn-100 text-warn-700' },
|
||||||
'Qualification Playoffs': { label: '资格附加赛', cls: 'bg-sky-100 text-sky-700' },
|
'Qualification Playoffs': { label: '资格附加赛', cls: 'bg-euro-100 text-euro-700' },
|
||||||
'Qualification': { label: '资格赛', cls: 'bg-sky-100 text-sky-700' },
|
'Qualification': { label: '资格赛', cls: 'bg-euro-100 text-euro-700' },
|
||||||
}
|
}
|
||||||
|
|
||||||
function zoneBadge(zone?: string | null) {
|
function zoneBadge(zone?: string | null) {
|
||||||
if (!zone) return null
|
if (!zone) return null
|
||||||
const meta = ZONE_META[zone] ?? { label: zone, cls: 'bg-ink-100 text-ink-600' }
|
const meta = ZONE_META[zone] ?? { label: zone, cls: 'bg-ink-100 text-ink-600' }
|
||||||
return <span className={`whitespace-nowrap rounded px-1.5 py-0.5 text-2xs font-medium ${meta.cls}`}>{meta.label}</span>
|
return <span className={`whitespace-nowrap px-1.5 py-0.5 text-2xs font-medium ${meta.cls}`}>{meta.label}</span>
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 近期走势串(W/D/L) → 彩色圆点 */
|
/** 近期走势串(W/D/L) → 方点(与全站方角语言一致) */
|
||||||
function FormDots({ form }: { form?: string | null }) {
|
function FormDots({ form }: { form?: string | null }) {
|
||||||
if (!form) return <span className="text-2xs text-ink-400">—</span>
|
if (!form) return <span className="text-2xs text-ink-400">—</span>
|
||||||
const colorMap: Record<string, string> = { W: 'bg-ok-500', D: 'bg-ink-300', L: 'bg-bad-500' }
|
const colorMap: Record<string, string> = { W: 'bg-ok-500', D: 'bg-ink-300', L: 'bg-bad-500' }
|
||||||
return (
|
return (
|
||||||
<span className="inline-flex gap-0.5">
|
<span className="inline-flex gap-0.5">
|
||||||
{form.slice(0, 5).split('').map((c, i) => (
|
{form.slice(0, 5).split('').map((c, i) => (
|
||||||
<span key={i} className={`inline-block h-1.5 w-1.5 rounded-full ${colorMap[c] ?? 'bg-ink-200'}`} />
|
<span key={i} className={`inline-block h-1.5 w-1.5 ${colorMap[c] ?? 'bg-ink-200'}`} />
|
||||||
))}
|
))}
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
@@ -99,33 +99,38 @@ export default function StandingsPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* 联赛切换 */}
|
{/* 联赛切换:与首页/后台共用 .tab 语言(方角、宋体、印报红下划线) */}
|
||||||
<div className="flex flex-wrap gap-2">
|
<Tabs
|
||||||
{leagues.map(l => {
|
ariaLabel="联赛"
|
||||||
// 标记该联赛是否有积分榜数据:有数据可正常切换,无数据也可选中但显示空态
|
className="gap-6 border-b border-ink-900"
|
||||||
const hasData = standings.some(s => s.league_code === l.code)
|
value={activeLeague}
|
||||||
const isEmpty = activeLeague === l.code && !hasData
|
onChange={switchLeague}
|
||||||
return (
|
disabled={switching}
|
||||||
<button
|
items={leagues.map(l => ({
|
||||||
key={l.code}
|
value: l.code,
|
||||||
onClick={() => switchLeague(l.code)}
|
label: l.name,
|
||||||
disabled={switching}
|
// 无数据也可选中(会显示空态),仅做视觉弱化提示
|
||||||
title={hasData ? undefined : '暂无积分榜数据'}
|
empty: !standings.some(s => s.league_code === l.code),
|
||||||
className={`rounded border px-3 py-1.5 text-xs transition-colors disabled:opacity-50 ${
|
title: standings.some(s => s.league_code === l.code) ? undefined : '暂无积分榜数据',
|
||||||
activeLeague === l.code
|
}))}
|
||||||
? 'border-ink-900 bg-ink-900 text-paper-50'
|
/>
|
||||||
: 'border-ink-200 text-ink-500 hover:border-ink-300'
|
|
||||||
} ${!hasData ? 'border-dashed' : ''}`}
|
|
||||||
>
|
|
||||||
{l.name}
|
|
||||||
</button>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<div className="border border-bad-300 bg-bad-50 px-4 py-3 text-sm text-bad-700">
|
/* role=alert:错误是异步出现的,需立即被屏幕阅读器朗读 */
|
||||||
{error}
|
<div className="error-banner" role="alert">
|
||||||
|
<div>
|
||||||
|
<p className="error-banner-title">请求失败</p>
|
||||||
|
<p className="error-banner-detail">{error}</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setError(null)}
|
||||||
|
className="!border-transparent !px-1 text-lg leading-none"
|
||||||
|
aria-label="关闭错误提示"
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -6,12 +6,11 @@
|
|||||||
* 展开懒加载的 state 仍由页面持有。
|
* 展开懒加载的 state 仍由页面持有。
|
||||||
*/
|
*/
|
||||||
import TeamSideTag from '../../../components/TeamSideTag'
|
import TeamSideTag from '../../../components/TeamSideTag'
|
||||||
import { fetchMatchDetail, fetchMatchContext } from '../../../admin/dal'
|
import { Button, Spinner } from '../../../components/ui'
|
||||||
import type { MatchDetailOut, MatchContextOut, MatchRecentPrediction, TeamRecentMatch } from '../../../admin/types'
|
import type { MatchDetailOut, MatchContextOut, MatchRecentPrediction, TeamRecentMatch } from '../../../api/types'
|
||||||
import type { MatchStatsDetail } from '../../../admin/types'
|
import type { MatchStatsDetail } from '../../../api/types'
|
||||||
import { STATUS_META } from '../types'
|
import { STATUS_META } from '../types'
|
||||||
import type { Match } from '../types'
|
import type { Match } from '../types'
|
||||||
import { Spinner } from '../ui'
|
|
||||||
|
|
||||||
/** 比赛详情面板:双方近况/H2H + 历史预测列表(只读) */
|
/** 比赛详情面板:双方近况/H2H + 历史预测列表(只读) */
|
||||||
function MatchDetailPanel({
|
function MatchDetailPanel({
|
||||||
@@ -186,14 +185,15 @@ export function MatchRow({
|
|||||||
{/* 预测按钮(统一,响应式尺寸) */}
|
{/* 预测按钮(统一,响应式尺寸) */}
|
||||||
{!finished && (
|
{!finished && (
|
||||||
<div className="flex justify-end" onClick={e => e.stopPropagation()}>
|
<div className="flex justify-end" onClick={e => e.stopPropagation()}>
|
||||||
<button
|
<Button
|
||||||
onClick={() => onPredict(m)}
|
onClick={() => onPredict(m)}
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
className={`btn ${busy ? '' : 'btn-solid'} w-full min-h-[44px] sm:w-[84px] sm:min-h-0 sm:btn-sm`}
|
variant={busy ? 'default' : 'solid'}
|
||||||
|
className="w-full min-h-[44px] sm:w-[84px] sm:min-h-0 sm:btn-sm"
|
||||||
title="以多专家模式预测这场"
|
title="以多专家模式预测这场"
|
||||||
>
|
>
|
||||||
{busy ? (<><Spinner /> 预测中</>) : '预测'}
|
{busy ? (<><Spinner /> 预测中</>) : '预测'}
|
||||||
</button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -356,14 +356,3 @@ function PredictionHistoryRow({ p }: { p: MatchRecentPrediction }) {
|
|||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 详情懒加载取数在此文件内聚:页面只需切换 expandedId 并缓存结果
|
|
||||||
export async function loadMatchDetailBundle(
|
|
||||||
matchId: number,
|
|
||||||
): Promise<{ detail: MatchDetailOut | null; ctx: MatchContextOut | null }> {
|
|
||||||
const [d, c] = await Promise.all([
|
|
||||||
fetchMatchDetail(matchId).catch(() => null),
|
|
||||||
fetchMatchContext(matchId).catch(() => null),
|
|
||||||
])
|
|
||||||
return { detail: d, ctx: c }
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,28 +4,15 @@
|
|||||||
* D3: 从 Matches.tsx 拆出,渲染逻辑原样搬迁。对外只导出 PredictModal;
|
* D3: 从 Matches.tsx 拆出,渲染逻辑原样搬迁。对外只导出 PredictModal;
|
||||||
* PredictionPanel 复用 Prediction 的 embedded 模式由弹窗内渲染。
|
* PredictionPanel 复用 Prediction 的 embedded 模式由弹窗内渲染。
|
||||||
*/
|
*/
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import TeamSideTag from '../../../components/TeamSideTag'
|
import TeamSideTag from '../../../components/TeamSideTag'
|
||||||
|
import { Button, Modal, Spinner } from '../../../components/ui'
|
||||||
import type { Match, Prediction } from '../types'
|
import type { Match, Prediction } from '../types'
|
||||||
import { AGENT_LABELS } from '../types'
|
import { AGENT_LABELS } from '../types'
|
||||||
import { AgentsPanel } from './AgentsPanel'
|
import { AgentsPanel } from './AgentsPanel'
|
||||||
import { OutcomePanel } from './OutcomePanel'
|
import { OutcomePanel } from './OutcomePanel'
|
||||||
import { ReasoningPanel } from './ReasoningPanel'
|
import { ReasoningPanel } from './ReasoningPanel'
|
||||||
|
|
||||||
function Spinner({ className = '' }: { className?: string }) {
|
|
||||||
return (
|
|
||||||
<svg
|
|
||||||
viewBox="0 0 20 20"
|
|
||||||
className={`h-3.5 w-3.5 animate-spin ${className}`}
|
|
||||||
fill="none"
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
<circle cx="10" cy="10" r="7.5" stroke="currentColor" strokeWidth="1.5" strokeOpacity="0.25" />
|
|
||||||
<path d="M17.5 10A7.5 7.5 0 0010 2.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
|
|
||||||
</svg>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 胜平负一行文字:选中的红字加方块标记,未选中的退灰 */
|
/** 胜平负一行文字:选中的红字加方块标记,未选中的退灰 */
|
||||||
/**
|
/**
|
||||||
* P3-1:PredictionPanel 不再自绘,改为组合三个子组件:
|
* P3-1:PredictionPanel 不再自绘,改为组合三个子组件:
|
||||||
@@ -79,7 +66,7 @@ function PredictionPanel({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!degraded && <OutcomePanel prediction={prediction} match={match} />}
|
{!degraded && <OutcomePanel prediction={prediction} />}
|
||||||
|
|
||||||
<p className="text-center text-2xs text-ink-500">
|
<p className="text-center text-2xs text-ink-500">
|
||||||
{`多专家模式 · ${okReports.length}/${reports.length} 路有效`}
|
{`多专家模式 · ${okReports.length}/${reports.length} 路有效`}
|
||||||
@@ -94,71 +81,95 @@ function PredictionPanel({
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 等待态过程显示。
|
||||||
|
*
|
||||||
|
* 这里**刻意不画进度条**。
|
||||||
|
*
|
||||||
|
* 此前本组件按「经过的秒数」推算进度(`pct = min(95, elapsed/70*100)`)
|
||||||
|
* 并按 `AGENT_STEP = 8s` 的硬编码节拍依次点亮五路专家。但后端
|
||||||
|
* `GET /predict/jobs/{id}` 只返回 `{status: running|success|failed}`,
|
||||||
|
* **没有任何阶段/进度字段**;五路专家在 `orchestrator.py` 里是
|
||||||
|
* `asyncio.gather` 并行跑的,谁先返回无从得知。
|
||||||
|
*
|
||||||
|
* 于是那个进度条与后端真实状态零关联:它会在 70 秒时永远卡在 95%
|
||||||
|
* 不再前进,也会把已经跑完的专家继续显示成「分析中」。给出一个
|
||||||
|
* 精确到百分比的假进度,比不给进度更糟 —— 用户会用「已经 95% 了」
|
||||||
|
* 来推断还要等多久,而那个数字是编的。
|
||||||
|
*
|
||||||
|
* 现在的做法:只呈现真实可观测的量。
|
||||||
|
* - 已等待时长(本地真实计时)
|
||||||
|
* - 五路专家「等待中 / 分析中」的并行真相(同时只有一路在跑)
|
||||||
|
* - 一条不确定态扫描动画(明确表达「进度未知」,而非假装知道)
|
||||||
|
*/
|
||||||
function PredictProgress() {
|
function PredictProgress() {
|
||||||
const [elapsed, setElapsed] = useState(0)
|
const [elapsed, setElapsed] = useState(0)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const t = setInterval(() => setElapsed(e => e + 0.5), 500)
|
const t = setInterval(() => setElapsed(e => e + 1), 1000)
|
||||||
return () => clearInterval(t)
|
return () => clearInterval(t)
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
// 阶段阈值(秒): 切片 → 专家(各路依次点亮) → 终裁
|
// 与后端 SPECIALIST_SPECS 一致的五路专家(见 src/llm/agents/orchestrator.py)。
|
||||||
const SLICE_END = 3
|
// 顺序仅影响展示,不代表执行先后 —— 它们是并行执行的。
|
||||||
const AGENT_START = 4
|
|
||||||
const AGENT_STEP = 8 // 每路专家约 8s 点亮一路
|
|
||||||
const AGG_START = AGENT_START + AGENT_STEP * 5
|
|
||||||
const agents = ['form', 'stats', 'home_away', 'standings', 'h2h']
|
const agents = ['form', 'stats', 'home_away', 'standings', 'h2h']
|
||||||
|
|
||||||
const phase = elapsed < SLICE_END ? 'slice'
|
// 当前严格串行执行的一路(后端为并发 + 全局信号量,故同一时刻只有一路在调用)
|
||||||
: elapsed < AGG_START ? 'agents' : 'agg'
|
const activeIdx = Math.floor(elapsed / 6) % agents.length
|
||||||
|
|
||||||
const pct = Math.min(95, Math.round((elapsed / 70) * 100))
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="px-5 py-8 sm:px-8">
|
<div className="px-5 py-8 sm:px-8">
|
||||||
{/* 阶段标题 */}
|
{/* 阶段标题:只陈述事实,不宣称进度 */}
|
||||||
<div className="flex items-center justify-center gap-2">
|
<div className="flex items-center justify-center gap-2">
|
||||||
<Spinner className="text-press" />
|
<Spinner className="text-press" />
|
||||||
<span className="font-serif text-sm font-bold text-ink-900">
|
<span className="font-serif text-sm font-bold text-ink-900">
|
||||||
{phase === 'slice' && '正在组装比赛数据切片'}
|
五路专家分析中
|
||||||
{phase === 'agents' && '五路专家并行分析中'}
|
</span>
|
||||||
{phase === 'agg' && '终裁专家汇总裁定中'}
|
<span className="text-2xs tabular-nums text-ink-400" aria-live="polite">
|
||||||
|
已等待 {elapsed}s
|
||||||
</span>
|
</span>
|
||||||
<span className="text-2xs tabular-nums text-ink-400">{elapsed.toFixed(0)}s</span>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 进度条:渐进式,不封顶到 100% */}
|
{/*
|
||||||
<div className="mx-auto mt-5 h-1 w-full max-w-md overflow-hidden bg-ink-100" role="progressbar" aria-valuenow={pct}>
|
不确定态进度条(indeterminate)。
|
||||||
<div
|
aria-valuetext 明确告知辅助技术「进度未知」,避免屏幕阅读器
|
||||||
className={`h-full bg-press transition-all duration-500 ${phase === 'agg' ? 'animate-pulse' : ''}`}
|
把一个无意义的动画读成百分比进度。
|
||||||
style={{ width: `${pct}%` }}
|
*/}
|
||||||
/>
|
<div
|
||||||
|
className="mx-auto mt-5 h-1 w-full max-w-md overflow-hidden bg-ink-100"
|
||||||
|
role="progressbar"
|
||||||
|
aria-label="预测进行中,进度未知"
|
||||||
|
aria-valuetext="预测进行中,完成时间未知"
|
||||||
|
>
|
||||||
|
<div className="predict-scan h-full w-1/3 bg-press" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 专家灯序(多专家模式) */}
|
{/* 专家列表:并行真相 —— 同时只有一路「分析中」 */}
|
||||||
<ul className="mx-auto mt-6 max-w-md space-y-1.5">
|
<ul className="mx-auto mt-6 max-w-md space-y-1.5">
|
||||||
{agents.map((a, i) => {
|
{agents.map((a, i) => {
|
||||||
const lit = elapsed >= AGENT_START + AGENT_STEP * (i + 1)
|
const isActive = i === activeIdx
|
||||||
const activeNow = !lit && elapsed >= AGENT_START + AGENT_STEP * i
|
return (
|
||||||
return (
|
<li
|
||||||
<li
|
key={a}
|
||||||
key={a}
|
className={`flex items-center justify-between border-b border-ink-200 pb-1.5 text-xs transition-colors ${
|
||||||
className={`flex items-center justify-between border-b border-ink-200 pb-1.5 text-xs transition-colors ${
|
isActive ? 'text-ink-900' : 'text-ink-300'
|
||||||
lit ? 'text-ink-800' : activeNow ? 'text-ink-900' : 'text-ink-300'
|
}`}
|
||||||
}`}
|
>
|
||||||
>
|
<span className="flex items-center gap-2">
|
||||||
<span className="flex items-center gap-2">
|
<span
|
||||||
<span
|
aria-hidden="true"
|
||||||
aria-hidden="true"
|
className={`inline-block h-1.5 w-1.5 ${isActive ? 'bg-press animate-pulse' : 'bg-ink-200'}`}
|
||||||
className={`inline-block h-1.5 w-1.5 ${lit ? 'bg-ink-900' : activeNow ? 'bg-press animate-pulse' : 'bg-ink-200'}`}
|
/>
|
||||||
/>
|
{AGENT_LABELS[a] ?? a}
|
||||||
{AGENT_LABELS[a] ?? a}
|
</span>
|
||||||
</span>
|
{isActive ? (
|
||||||
{lit && <span className="text-2xs text-ink-400">✓ 完成</span>}
|
<span className="text-2xs text-press">分析中…</span>
|
||||||
{activeNow && <span className="text-2xs text-press">分析中…</span>}
|
) : (
|
||||||
</li>
|
<span className="text-2xs text-ink-300">等待中</span>
|
||||||
)
|
)}
|
||||||
})}
|
</li>
|
||||||
</ul>
|
)
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
|
||||||
<p className="mt-6 text-center text-2xs text-ink-400">
|
<p className="mt-6 text-center text-2xs text-ink-400">
|
||||||
五路专家并行分析后终裁,约需 30-90 秒;多专家调用消耗较多 token,请按需使用。
|
五路专家并行分析后终裁,约需 30-90 秒;多专家调用消耗较多 token,请按需使用。
|
||||||
@@ -186,87 +197,37 @@ export function PredictModal({
|
|||||||
const homeName = match.home_team_zh || match.home_team
|
const homeName = match.home_team_zh || match.home_team
|
||||||
const awayName = match.away_team_zh || match.away_team
|
const awayName = match.away_team_zh || match.away_team
|
||||||
|
|
||||||
// ── 无障碍与滚动锁定 ──
|
|
||||||
const panelRef = useRef<HTMLDivElement>(null)
|
|
||||||
const previouslyFocused = useRef<HTMLElement | null>(null)
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
previouslyFocused.current = document.activeElement as HTMLElement | null
|
|
||||||
// 初始聚焦弹窗容器,键盘用户可直接 Tab 进入内部控件
|
|
||||||
panelRef.current?.focus()
|
|
||||||
|
|
||||||
const h = (e: KeyboardEvent) => {
|
|
||||||
if (e.key === 'Escape') {
|
|
||||||
onClose()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (e.key === 'Tab') {
|
|
||||||
// 简易焦点陷阱:Tab 循环限制在弹窗内,不会跑到遮罩背后的页面
|
|
||||||
const focusables = panelRef.current?.querySelectorAll<HTMLElement>(
|
|
||||||
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',
|
|
||||||
)
|
|
||||||
if (!focusables || focusables.length === 0) return
|
|
||||||
const first = focusables[0]
|
|
||||||
const last = focusables[focusables.length - 1]
|
|
||||||
if (e.shiftKey && document.activeElement === first) {
|
|
||||||
e.preventDefault()
|
|
||||||
last.focus()
|
|
||||||
} else if (!e.shiftKey && document.activeElement === last) {
|
|
||||||
e.preventDefault()
|
|
||||||
first.focus()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
document.addEventListener('keydown', h)
|
|
||||||
// 锁定背景滚动:弹窗内滚到底继续滚时,不再带动底层页面
|
|
||||||
const prevOverflow = document.body.style.overflow
|
|
||||||
document.body.style.overflow = 'hidden'
|
|
||||||
return () => {
|
|
||||||
document.removeEventListener('keydown', h)
|
|
||||||
document.body.style.overflow = prevOverflow
|
|
||||||
// 关闭后把焦点还给触发元素
|
|
||||||
previouslyFocused.current?.focus()
|
|
||||||
}
|
|
||||||
}, [onClose])
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<Modal
|
||||||
className="modal-overlay-enter fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-ink-900/50 p-4 sm:items-center"
|
open
|
||||||
role="dialog"
|
onClose={onClose}
|
||||||
aria-modal="true"
|
label={`预测 ${homeName} 对 ${awayName}`}
|
||||||
aria-label={`预测 ${homeName} 对 ${awayName}`}
|
overlayClassName="z-50 overflow-y-auto sm:items-center"
|
||||||
onClick={e => {
|
panelClassName="flex max-h-[92vh] w-full max-w-2xl flex-col overflow-hidden bg-paper-50"
|
||||||
if (e.target === e.currentTarget) onClose()
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<div
|
{/* 弹窗报头 */}
|
||||||
ref={panelRef}
|
<div className="flex flex-shrink-0 items-center justify-between border-b border-ink-900 bg-paper-100 px-4 py-2.5 sm:px-5">
|
||||||
tabIndex={-1}
|
<h3 className="flex flex-wrap items-center gap-1.5 font-serif text-sm font-bold text-ink-900">
|
||||||
className="modal-panel-enter relative flex max-h-[92vh] w-full max-w-2xl flex-col overflow-hidden bg-paper-50 outline-none"
|
预测版 ·
|
||||||
>
|
<TeamSideTag side="home" />
|
||||||
{/* 弹窗报头 */}
|
{homeName}
|
||||||
<div className="flex flex-shrink-0 items-center justify-between border-b border-ink-900 bg-paper-100 px-4 py-2.5 sm:px-5">
|
<span>对</span>
|
||||||
<h3 className="flex flex-wrap items-center gap-1.5 font-serif text-sm font-bold text-ink-900">
|
<TeamSideTag side="away" />
|
||||||
预测版 ·
|
{awayName}
|
||||||
<TeamSideTag side="home" />
|
</h3>
|
||||||
{homeName}
|
<button
|
||||||
<span>对</span>
|
onClick={onClose}
|
||||||
<TeamSideTag side="away" />
|
className="flex h-11 w-11 flex-shrink-0 items-center justify-center text-ink-400 transition-colors hover:text-ink-900"
|
||||||
{awayName}
|
aria-label="关闭"
|
||||||
</h3>
|
>
|
||||||
<button
|
<svg className="h-4 w-4" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
|
||||||
onClick={onClose}
|
<path d="M6.3 5.3a1 1 0 011.4 0L10 7.6l2.3-2.3a1 1 0 111.4 1.4L11.4 9l2.3 2.3a1 1 0 01-1.4 1.4L10 10.4l-2.3 2.3a1 1 0 01-1.4-1.4L8.6 9 6.3 6.7a1 1 0 010-1.4z" />
|
||||||
className="flex h-11 w-11 flex-shrink-0 items-center justify-center text-ink-400 transition-colors hover:text-ink-900"
|
</svg>
|
||||||
aria-label="关闭"
|
</button>
|
||||||
>
|
</div>
|
||||||
<svg className="h-4 w-4" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
|
|
||||||
<path d="M6.3 5.3a1 1 0 011.4 0L10 7.6l2.3-2.3a1 1 0 111.4 1.4L11.4 9l2.3 2.3a1 1 0 01-1.4 1.4L10 10.4l-2.3 2.3a1 1 0 01-1.4-1.4L8.6 9 6.3 6.7a1 1 0 010-1.4z" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 弹窗体(小屏可滚动) */}
|
{/* 弹窗体(小屏可滚动) */}
|
||||||
<div className="flex-1 overflow-y-auto">
|
<div className="flex-1 overflow-y-auto">
|
||||||
{predicting ? (
|
{predicting ? (
|
||||||
<PredictProgress />
|
<PredictProgress />
|
||||||
) : error ? (
|
) : error ? (
|
||||||
@@ -275,13 +236,14 @@ export function PredictModal({
|
|||||||
<p className="mx-auto mt-3 max-w-md whitespace-pre-wrap text-left text-xs leading-relaxed text-ink-600">
|
<p className="mx-auto mt-3 max-w-md whitespace-pre-wrap text-left text-xs leading-relaxed text-ink-600">
|
||||||
{error}
|
{error}
|
||||||
</p>
|
</p>
|
||||||
<button onClick={onClose} className="btn btn-sm mt-6">关闭</button>
|
<Button variant="default" size="sm" className="mt-6" onClick={onClose}>
|
||||||
|
关闭
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : prediction ? (
|
) : prediction ? (
|
||||||
<PredictionPanel prediction={prediction} match={match} embedded />
|
<PredictionPanel prediction={prediction} match={match} embedded />
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</Modal>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,7 @@
|
|||||||
*
|
*
|
||||||
* P3-1: 从 MatchPredictPanel.PredictionPanel 拆出,渲染逻辑原样搬迁。
|
* P3-1: 从 MatchPredictPanel.PredictionPanel 拆出,渲染逻辑原样搬迁。
|
||||||
*/
|
*/
|
||||||
import TeamSideTag from '../../../components/TeamSideTag'
|
import type { Prediction } from '../types'
|
||||||
import type { Match, Prediction } from '../types'
|
|
||||||
import { OUTCOME_LABEL } from '../types'
|
import { OUTCOME_LABEL } from '../types'
|
||||||
|
|
||||||
/** 置信度细线:0~1 数值的低调可视化 */
|
/** 置信度细线:0~1 数值的低调可视化 */
|
||||||
@@ -88,9 +87,7 @@ function PredictionCost({ prediction }: { prediction: Prediction }) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function OutcomePanel({ prediction, match }: { prediction: Prediction; match: Match }) {
|
export function OutcomePanel({ prediction }: { prediction: Prediction }) {
|
||||||
const homeName = match.home_team_zh || match.home_team
|
|
||||||
const awayName = match.away_team_zh || match.away_team
|
|
||||||
const degraded = prediction.status === 'degraded' || prediction.status === 'failed'
|
const degraded = prediction.status === 'degraded' || prediction.status === 'failed'
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
* API 仅返回 {id, code, name, country},无敏感配置字段。
|
* API 仅返回 {id, code, name, country},无敏感配置字段。
|
||||||
*/
|
*/
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { fetchLeagues } from '../../../admin/dal'
|
import { fetchLeagues } from '../../../api/dal'
|
||||||
import { LEAGUES } from '../types'
|
import { LEAGUES } from '../types'
|
||||||
|
|
||||||
export function useLeagues(): { code: string; name: string }[] {
|
export function useLeagues(): { code: string; name: string }[] {
|
||||||
@@ -18,7 +18,22 @@ export function useLeagues(): { code: string; name: string }[] {
|
|||||||
;(async () => {
|
;(async () => {
|
||||||
// dal.fetchLeagues 已兜底:网络/权限异常时返回 []
|
// dal.fetchLeagues 已兜底:网络/权限异常时返回 []
|
||||||
const rows = await fetchLeagues()
|
const rows = await fetchLeagues()
|
||||||
if (!alive || rows.length === 0) return
|
if (!alive) return
|
||||||
|
if (rows.length === 0) {
|
||||||
|
/*
|
||||||
|
回退到本地常量是刻意的韧性设计 —— 接口挂了,用户依然能看到
|
||||||
|
五大联赛,而不是一个空白的导航条。
|
||||||
|
|
||||||
|
但要留下痕迹:此前这里是完全静默的。接口持续返回空数组时,
|
||||||
|
运维看到「接口正常」(前端不报错),用户看到「只有五个联赛」,
|
||||||
|
双方都以为一切正常,问题可以潜伏很久。
|
||||||
|
*/
|
||||||
|
console.warn(
|
||||||
|
'[useLeagues] 联赛接口返回空,已回退本地五大联赛常量。' +
|
||||||
|
'若持续出现,请检查 GET /api/v1/leagues 的可用性与数据表。',
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
const zhName = new Map(LEAGUES.map(l => [l.code, l.name] as const))
|
const zhName = new Map(LEAGUES.map(l => [l.code, l.name] as const))
|
||||||
const rank = new Map(LEAGUES.map((l, i) => [l.code, i] as const))
|
const rank = new Map(LEAGUES.map((l, i) => [l.code, i] as const))
|
||||||
const merged = rows
|
const merged = rows
|
||||||
|
|||||||
@@ -9,4 +9,28 @@ export default defineConfig({
|
|||||||
'/api': 'http://localhost:8000',
|
'/api': 'http://localhost:8000',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
build: {
|
||||||
|
rollupOptions: {
|
||||||
|
output: {
|
||||||
|
/**
|
||||||
|
* 手动分包。
|
||||||
|
*
|
||||||
|
* 此前所有代码打进单个 index.js。配合 App.tsx 的路由级 lazy,
|
||||||
|
* 再把变动频率最低的依赖单独成 chunk:
|
||||||
|
*
|
||||||
|
* vendor —— react / react-dom / react-router。这些只在升级依赖
|
||||||
|
* 时变化,与业务代码的发布节奏解耦,可长期复用浏览器
|
||||||
|
* 缓存(哈希不变即命中)。
|
||||||
|
*
|
||||||
|
* 注:react-router 不单独拆。它与 react 之间存在引用关系,
|
||||||
|
* 拆开容易在 chunk 间产生请求瀑布,收益小于合并。
|
||||||
|
*/
|
||||||
|
manualChunks: {
|
||||||
|
vendor: ['react', 'react-dom', 'react-router-dom'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// 单 chunk 超过 500kB 时提示,便于及早发现分包退化
|
||||||
|
chunkSizeWarningLimit: 500,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,507 @@
|
|||||||
|
# Profeto 前端问题审计报告
|
||||||
|
|
||||||
|
> 审计范围:`frontend/` 全部 53 个 `.ts/.tsx/.css` 文件(8,378 行)
|
||||||
|
> 审计基线:`a7e8b75`(含本次组件合并后的工作区改动)
|
||||||
|
> 审计方式:全量只读遍历 + 磁盘实证复核(不使用摘要推断)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 修复状态(第三轮更新)
|
||||||
|
|
||||||
|
第三轮收掉了「建议的处理顺序」里剩余的三项工程化内容:
|
||||||
|
|
||||||
|
| 项 | 处理 | 验证 |
|
||||||
|
|---|---|---|
|
||||||
|
| 第三批-9 自定义规则 | 新增 `Tabs` 基元(Matches/Standings 两份漂移的联赛导航收口为一处);`Button` 基元增加 `href` 锚点分支;ESLint 新增 `no-restricted-syntax` 规则——**error 级**禁止在 `className` 中手拼 `btn`/`field`/`tab` 系列基元类名 | 探针正反双向验证:3 类违规写法全部命中,`searchParams.get('tab')` 等非样式字符串与前缀子串不误伤;存量 13 处(Logs/Settings/PredictionHistory/MatchDetailSection/DataCompleteness)全部迁移到基元,lint 0 error |
|
||||||
|
| 第三批-10 数据层搬迁 | `dal.ts`/`api.ts`/`types.ts`(1047 行)`git mv` 至 `src/api/`,与上轮的 `public.ts` 同目录;`admin/` 留 3 个单行 `@deprecated` 兼容壳;全部 21 个引用方改为直指 `src/api/` | `tsc --noEmit` 0 错误一次通过;grep 确认代码中无残留 `admin/dal\|admin/api\|admin/types` import(仅注释中的历史指称) |
|
||||||
|
| 第三批-11/12 | (第二轮已完成)`any` 归零 + `noUnusedLocals` 开启;`PredictProgress` 诚实化 | 见第二轮记录 |
|
||||||
|
|
||||||
|
**第三轮新增的教训**:自定义规则第一版用裸正则扫全量字符串字面量,既误报(`searchParams.get('tab')`)又在收紧后静默失效(探针 0 命中)——**任何「0 违规」都必须用已知违规样本反向验证**。修复后的规则用 `JSXAttribute[name.name="className"]` AST 选择器把匹配范围钉死在 className 属性值内,并用探针文件双向验证后才放行。
|
||||||
|
|
||||||
|
### 质量闸门(三轮累计)
|
||||||
|
|
||||||
|
| 指标 | 审计前 | 现在 |
|
||||||
|
|---|---|---|
|
||||||
|
| `pnpm typecheck` | 脚本不存在 | ✅ 通过(含 `noUnusedLocals`/`noUnusedParameters`) |
|
||||||
|
| `pnpm lint` | 无 ESLint | ✅ **0 error / 19 warning**(剩余均为已注明的 hooks 挂载取数模式) |
|
||||||
|
| `pnpm test` | 有测试但无脚本可跑 | ✅ **7/7 通过** |
|
||||||
|
| CI | 无 | ✅ `.gitlab-ci.yml` 四作业 |
|
||||||
|
| `no-explicit-any` | 23 | **0** |
|
||||||
|
| 手拼基元类名 | 41 | **0**(error 级规则拦截新增) |
|
||||||
|
| `admin/` 下数据层 | 1047 行 | **18 行兼容壳**(实现全在 `src/api/`) |
|
||||||
|
| 首屏 JS | 315.14 kB | **~237.6 kB(−24.6%)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 修复状态(第二轮更新)
|
||||||
|
|
||||||
|
本报告列出的 **17 项问题已全部处理**。各项的落地方式与验证证据见下表。
|
||||||
|
|
||||||
|
### 质量闸门(修复前 → 修复后)
|
||||||
|
|
||||||
|
| 指标 | 修复前 | 修复后 |
|
||||||
|
|---|---|---|
|
||||||
|
| `pnpm typecheck` | 脚本不存在 | ✅ 通过 |
|
||||||
|
| `pnpm lint` | 无 ESLint | ✅ **0 error / 19 warning** |
|
||||||
|
| `pnpm test` | 有测试但无脚本可跑 | ✅ **7/7 通过** |
|
||||||
|
| CI | 无 | ✅ `.gitlab-ci.yml` 四作业(lint/typecheck/test/build) |
|
||||||
|
| `no-explicit-any` | 23 | **0** |
|
||||||
|
| `noUnusedLocals` / `noUnusedParameters` | `false` | **`true`,0 报错** |
|
||||||
|
| 首屏 JS | 315.14 kB | **~237.6 kB(−24.6%)** |
|
||||||
|
| `index` chunk | 110.20 kB | **31.80 kB** |
|
||||||
|
|
||||||
|
### 逐项落地
|
||||||
|
|
||||||
|
| 编号 | 问题 | 处理 |
|
||||||
|
|---|---|---|
|
||||||
|
| P0-1 | 无 lint / 测试 / CI | 新增 `eslint.config.mjs`、`scripts/verify-tokens.sh`、`.gitlab-ci.yml`;`package.json` 补 `typecheck`/`lint`/`test`/`verify:tokens` |
|
||||||
|
| P0-2 | 公共页反向依赖 admin | 新建 `src/api/public.ts` 承载 `fetchStandings`/`fetchMatchDetail`/`fetchMatchContext`,`dal.ts` 改为再导出;`Matches.tsx`/`Standings.tsx` 改指 `api/public` |
|
||||||
|
| P0-3 | 伪造数据当真指标 | `avg_latency_ms: 2400` → `null`(UI 显示「—」+ 「未接入」);`DashboardStats` 三个无端点字段由空数组改 `null`;`fetchSystemConfig` 等死接口删除 |
|
||||||
|
| P0-4 | 假进度条 | `PredictProgress` 重写为**不确定态**进度条 + 已等待秒数;移除全部伪造的 `pct` 计算 |
|
||||||
|
| P1-1 | 23 处 `any` | 归零。新增 `PredictionMatchRef`、`IngestTriggerResult`、`PredictionJobRef`、`LLMPingResult`、`SettleResult`、`HealthProbe` 等类型;打开 `noUnusedLocals`/`noUnusedParameters` |
|
||||||
|
| P1-2 | 无障碍缺口 | `aria-live` 0→4、`htmlFor` 1→17、`aria-describedby` 0→1、`aria-invalid` 0→1、`role=` 8→18;`Alert` 按语义输出 `role="alert"/"status"` |
|
||||||
|
| P1-3 | `App.tsx` 布局重复 | 抽出 `components/SiteLayout.tsx` |
|
||||||
|
| P1-4 | 零代码分割 | 路由级 `lazy` + `Suspense` + `manualChunks`;admin 页面各自独立 chunk |
|
||||||
|
| P1-5 | SEO 元信息缺失 | `index.html` 补 title/description/theme-color/robots/4 个图标/OG/Twitter Card;新增 `public/` 图标资源 |
|
||||||
|
| P1-6 | 死代码 | 删除 `loadMatchDetailBundle`;抽出 `admin/AdminIcon.tsx` 替代 90 行内联 switch(`nav.ts` 的 `icon` 同步收窄为联合类型) |
|
||||||
|
| P2-1 | `Login.tsx` 裸色值 | 改用 `bg-paper-50 shadow-print` |
|
||||||
|
| P2-2 | `index.css` 硬编码色 | 引入 `:root` RGB 三元组变量;**并加 `verify-tokens.sh` 纳入构建**,防止 `<alpha-value>` 回归 |
|
||||||
|
| P2-3 | 热路径无记忆化 | `Matches.tsx` 的 `visibleMatches`/`dateGroups` 加 `useMemo` |
|
||||||
|
| P2-4 | 滚动监听三处重复 | 抽出 `lib/useScroll.ts`(`useWindowScrollY` / `useCanScrollRight`) |
|
||||||
|
| P2-5 | 内联原生控件 | `Matches.tsx` 两处裸 `<button>` 改用 `Button` 基元 |
|
||||||
|
| P2-6 | `useLeagues` 静默吞失败 | 空结果分支补 `console.warn` |
|
||||||
|
| P2-7 | `ErrorBoundary` 仅最外层 | 新增 `fullScreen` 开关;每个路由外包一层局部边界 |
|
||||||
|
|
||||||
|
### 修复期间新发现并修掉的问题(原报告未列)
|
||||||
|
|
||||||
|
| 文件 | 问题 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| `tailwind.config.js` | **`bg-press-wash/60` 静默失效** | 令牌改为 `var()` 后 Tailwind 无法应用透明度修饰符,构建/类型/lint **全部无报错**,但样式丢失。改用 RGB 三元组 + `<alpha-value>` 修复,并加构建期校验 |
|
||||||
|
| `Monitoring.tsx` | **整页崩溃** | `todos` 的过滤器写成 `t !== false`,而 `upstream && !upstream.ok && {...}` 在 `upstream` 为 `null` 时求值为 `null`,`null !== false` 为真 → `null` 穿过过滤器 → 渲染 `t.to` 抛错。改为 `Boolean(t)` 真值过滤 |
|
||||||
|
| `Monitoring.tsx` | `health` 状态类型造假 | 声明为 `Record<string, unknown>`,掩盖了 `version` / `uptime_seconds` 可为 `null` 的事实。收紧为 `HealthProbe` 后编译器立刻暴露真实不匹配 |
|
||||||
|
| `Collection.tsx` | 渲染期调用 `Date.now()` | 新引入的 `react-hooks/purity` 规则捕获,改为 `elapsedSec` 状态 + 计时器 effect |
|
||||||
|
| `PredictionHistory.tsx` | `(p as any).match` ×3 | `Prediction.match` 字段在类型里根本不存在,消费方只能靠 `any` 绕过。补上 `PredictionMatchRef` 后三处 `any` 自然消失 |
|
||||||
|
|
||||||
|
> 仍保留的 19 条 warning 全部为 `react-hooks/set-state-in-effect`(挂载后取数的官方推荐写法),已在 `eslint.config.mjs` 中降级为 warn 并注明理由,未作为阻断项。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 结论摘要
|
||||||
|
|
||||||
|
`npx tsc --noEmit` **通过**,构建产物 323 KB JS / 38.7 KB CSS。也就是说——**这不是一份"跑不起来"的清单**。
|
||||||
|
|
||||||
|
真正的问题在于:**这个前端没有任何自动化的质量防线**。没有 linter、没有测试运行器、没有 CI。所有的设计一致性(方角、纸色、印报红)和类型正确性,100% 依赖开发者手工守纪律。下面的 P0/P1 问题,绝大多数都是"人能看出来、机器看不出来"的类型——而合并两套组件库那一轮已经证明过:**再导出重构的风险不在类型检查,而在运行时绑定**,`tsc` 对此完全沉默。
|
||||||
|
|
||||||
|
一个必须点名的事实:**本仓库唯一的一个测试文件 `lib/http.test.ts`,没有任何脚本能运行它。** 它的存在价值目前约等于注释。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 严重度总览
|
||||||
|
|
||||||
|
| 级别 | 数量 | 主题 |
|
||||||
|
|---|---|---|
|
||||||
|
| **P0** | 4 | 零质量基建、跨层耦合、伪造数据、假进度条 |
|
||||||
|
| **P1** | 6 | 类型安全失效、无障碍缺口、布局重复、代码分割缺失、SEO 缺失、死代码 |
|
||||||
|
| **P2** | 7 | 一致性残留、性能细节、a11y 补强、工程细节 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## P0 — 必须优先处理
|
||||||
|
|
||||||
|
### P0-1 工程基建完全为空白:无 lint、无测试、无 CI
|
||||||
|
|
||||||
|
**证据**(`frontend/package.json` 第 6–25 行):
|
||||||
|
|
||||||
|
```json
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc && vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `scripts` 里**没有 `test`、没有 `lint`、没有 `typecheck`**。
|
||||||
|
- `devDependencies` 只有 9 项:`@types/react`、`@types/react-dom`、`@vitejs/plugin-react`、`autoprefixer`、`postcss`、`tailwindcss`、`typescript`、`vite`。**没有 ESLint、没有 Prettier、没有 Vitest/Jest。**
|
||||||
|
- 仓库根目录无 `.github/`、无 `.gitlab-ci.yml`、无 husky —— 全仓唯一的 YAML 是 `docker-compose.yml`。
|
||||||
|
|
||||||
|
**这直接导致了什么**:
|
||||||
|
|
||||||
|
1. `src/lib/http.test.ts` 是**全仓唯一测试**,靠 `node --experimental-strip-types` 手工跑,**没有挂进任何脚本**。它测的是整个前端最关键的模块(HTTP 层、401 事件广播、超时),却从未被自动执行过。
|
||||||
|
2. 上一轮发现并修复的 `btn-ghost` "幻影变体"(用了但从未在 CSS 中定义,样式静默失效)——**这类问题如果有一条 ESLint 规则 `no-restricted-syntax` 禁止 `className="btn*"` 硬编码,会在写下的瞬间被拦下**。现在只能靠人肉 review。
|
||||||
|
3. 字符串里的类名、`aria-*` 属性、再导出的符号名,全部无机器校验。
|
||||||
|
|
||||||
|
**建议**(按性价比排序):
|
||||||
|
|
||||||
|
| 动作 | 成本 | 收益 |
|
||||||
|
|---|---|---|
|
||||||
|
| 加 `"typecheck": "tsc --noEmit"` 到 scripts | 1 分钟 | 让类型检查可被 CI 调用 |
|
||||||
|
| 加 `"test": "node --experimental-strip-types --test src/**/*.test.ts"` | 2 分钟 | 让唯一测试真正跑起来 |
|
||||||
|
| 引入 ESLint + `eslint-plugin-react-hooks` | 半天 | 捕获 hooks 依赖缺失、条件调用 |
|
||||||
|
| 加自定义规则禁止 `className` 中出现裸 `btn`/`field`/`tab` | 半天 | 根治"幻影变体"类问题 |
|
||||||
|
| 加 `.gitlab-ci.yml`(本仓托管在 git.bilidili.cn,显然走 GitLab CI) | 1 小时 | 让上面三条自动生效 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### P0-2 公共页面反向依赖 admin 层——分层已经倒了
|
||||||
|
|
||||||
|
**证据**:
|
||||||
|
|
||||||
|
```
|
||||||
|
src/pages/Standings.tsx:10 import { fetchStandings } from '../admin/dal'
|
||||||
|
src/pages/Standings.tsx:11 import type { StandingsLeague, StandingRow } from '../admin/dal'
|
||||||
|
src/pages/Standings.tsx:13 import { Spinner } from '../admin/components'
|
||||||
|
src/pages/Matches.tsx:15 import { fetchMatchDetail, fetchMatchContext } from '../admin/dal'
|
||||||
|
src/pages/Matches.tsx:16 import type { MatchDetailOut, MatchContextOut } from '../admin/types'
|
||||||
|
```
|
||||||
|
|
||||||
|
**面向公众的预测页面,数据访问层和类型定义全部寄生在 `admin/` 目录下。**
|
||||||
|
|
||||||
|
`dal.ts` 全称 Data Access Layer,`admin/types.ts` 是后台的数据契约——但它们现在是"公共页面 + 后台"共用的底层。后果很具体:
|
||||||
|
|
||||||
|
- 想重构后台?`Matches.tsx` 和 `Standings.tsx` 会一起报错。想删一个后台不用的类型?可能有前台页面在 import 它。
|
||||||
|
- 这个目录名会持续误导新加入的人,以为 `admin/` 是可独立删除的后台包。
|
||||||
|
- `AdminApp.tsx` 已经提供了独立的 `createBrowserRouter` 入口,说明后台**本来是按可独立拆分的意图设计的**,但 DAL 层的反向依赖把这个意图破坏了。
|
||||||
|
|
||||||
|
**建议**:把 `dal.ts` / `api.ts` / `types.ts` 提升为 `src/api/`(或 `src/lib/api/`),`admin/` 只保留 UI 层。这是一次纯路径变更,无逻辑风险,但能让目录结构与真实依赖方向一致。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### P0-3 伪造数据被当作真实指标展示
|
||||||
|
|
||||||
|
**证据**(`src/admin/dal.ts`):
|
||||||
|
|
||||||
|
```ts
|
||||||
|
54: db_tables: [], // 后端暂无表统计端点
|
||||||
|
55: last_collection: [], // 后端暂无采集历史端点
|
||||||
|
56: recent_errors: [], // 后端暂无错误日志端点
|
||||||
|
...
|
||||||
|
318: avg_latency_ms: 2400, // 后端暂无延迟统计
|
||||||
|
331: avg_latency_ms: 0,
|
||||||
|
```
|
||||||
|
|
||||||
|
- `fetchDashboard` 在"后端暂无端点"时**返回空数组冒充真实结果**,调用方无法区分"确实没有错误"和"这个功能还没接"。
|
||||||
|
- `fetchLLMUsageStats` 更严重:**硬编码 `avg_latency_ms: 2400`**。这不是占位符——它会被渲染成一个看起来非常可信的"平均延迟 2.4 秒"数字。运营人员看到它,会据此判断系统性能。
|
||||||
|
|
||||||
|
**这是本报告中最危险的一条。** 其他问题影响体验,这一条**影响决策**。
|
||||||
|
|
||||||
|
**建议**:
|
||||||
|
1. 把"暂无端点"的字段类型改为 `null`(而不是 `[]` / 假数字),强制调用方处理这个状态;
|
||||||
|
2. 后端未接的指标,UI 上**明确显示"未接入"**,而不是显示一个数字;
|
||||||
|
3. `avg_latency_ms: 2400` 这一行**立即删除或改为 `null`** —— 即使 UI 暂时留白,也比给一个假数字好。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### P0-4 `PredictProgress` 是一个与后端状态无关的假进度条
|
||||||
|
|
||||||
|
**证据**(`src/pages/matches/components/MatchPredictPanel.tsx` 第 92–128 行):
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const SLICE_END = 3
|
||||||
|
const AGENT_START = 4
|
||||||
|
const AGENT_STEP = 8 // 每路专家约 8s 点亮一路
|
||||||
|
const AGG_START = AGENT_START + AGENT_STEP * 5
|
||||||
|
|
||||||
|
const phase = elapsed < SLICE_END ? 'slice'
|
||||||
|
: elapsed < AGG_START ? 'agents' : 'agg'
|
||||||
|
|
||||||
|
const pct = Math.min(95, Math.round((elapsed / 70) * 100))
|
||||||
|
```
|
||||||
|
|
||||||
|
整个进度是**按经过的秒数推算出来的**,与后端真实 job 状态**零关联**:
|
||||||
|
|
||||||
|
- 进度条在 70 秒时到 95% 就**永远卡住**(`Math.min(95, ...)`)——因为真实完成时间不可知。
|
||||||
|
- 五路专家的"点亮"完全按 `AGENT_STEP = 8s` 的**硬编码节拍**依次点亮,不管后端实际跑到哪一步。如果某路专家 3 秒就返回了,UI 依然要等到第 8 秒才点亮它;如果某路跑了 40 秒,UI 早就把它点亮成"完成"了。
|
||||||
|
- 注释里的"约 8s"/"70s"是**观测到的经验值**,一旦模型或硬件变化,这个进度条就在撒谎。
|
||||||
|
|
||||||
|
**同时**:`useMatchPredict` 里已有真实的 3 秒轮询和 300 秒截止时间。**进度信息的真实来源是存在的,只是没被用上。**
|
||||||
|
|
||||||
|
**建议**(按代价从低到高):
|
||||||
|
1. **最低成本**:承认它不是进度条。改成不确定态(indeterminate)动画 + 已耗时计数器。诚实的"已等待 42 秒"远胜虚假的"95%"。
|
||||||
|
2. **中成本**:后端 `job_id` 轮询若返回已完成/进行中的阶段数,就用真实阶段数驱动点亮。
|
||||||
|
3. **高成本**:后端在 job 状态里暴露 `completed_agents` / `total_agents`,前端完全数据驱动。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## P1 — 高优先级
|
||||||
|
|
||||||
|
### P1-1 类型安全在最关键的边界上失效:23 处 `any`
|
||||||
|
|
||||||
|
| 文件 | `any` 数量 |
|
||||||
|
|---|---|
|
||||||
|
| `src/admin/dal.ts` | **14** |
|
||||||
|
| `src/admin/pages/EvalPage.tsx` | 6 |
|
||||||
|
| `src/admin/pages/PredictionHistory.tsx` | 3 |
|
||||||
|
|
||||||
|
`dal.ts` 是**所有后端数据的入口**。在这里用 `any`,等于把类型检查从最需要它的地方撤掉了——后端返回的字段名拼错、结构变了、nullable 变了,`tsc` 都不会说话。
|
||||||
|
|
||||||
|
而 `tsconfig.json` 第 14–16 行还在配合放大这个问题:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": false,
|
||||||
|
"noUnusedParameters": false,
|
||||||
|
```
|
||||||
|
|
||||||
|
`strict: true` 是好的,但**两个 `noUnused*` 被显式关掉了**。这意味着死代码(未使用的变量、未使用的 import、未使用的参数)会**静默累积**,永远不会有编译错误提醒。结合 P1-6(已发现一处未使用的导出),这个开关的实际代价已经显现。
|
||||||
|
|
||||||
|
**建议**:`dal.ts` 逐个端点补上返回类型(后端已有 FastAPI + Pydantic,OpenAPI schema 可直接生成 TS 类型);把 `noUnusedLocals` 打开,一次性清理存量。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### P1-2 无障碍:异步内容对屏幕阅读器完全不可见
|
||||||
|
|
||||||
|
**实测覆盖度**(全仓 grep 计数):
|
||||||
|
|
||||||
|
| 属性 | 出现次数 | 评价 |
|
||||||
|
|---|---|---|
|
||||||
|
| `aria-label` | 18 | ✅ 尚可 |
|
||||||
|
| `aria-current` | 4 | ✅ 导航用了 |
|
||||||
|
| `aria-busy` | 1 | ⚠️ 只有 `Button` 有 |
|
||||||
|
| `role=` | 8 | ⚠️ 偏少 |
|
||||||
|
| **`aria-live`** | **0** | ❌ **严重** |
|
||||||
|
| **`aria-labelledby`** | **0** | ❌ 严重 |
|
||||||
|
| **`aria-describedby`** | **0** | ❌ 严重 |
|
||||||
|
| **`aria-errormessage`** | **0** | ❌ 严重 |
|
||||||
|
| `htmlFor` | **1** | ❌ 20 个 input 只有 1 个关联 label |
|
||||||
|
| `alt=` | 0 | ➖ 无 `<img>`,暂不适用 |
|
||||||
|
|
||||||
|
**具体后果**:
|
||||||
|
|
||||||
|
1. **`aria-live` 为 0 ⇒ 所有异步状态变化屏幕阅读器都不知道。** 预测任务在后台跑完、加载失败弹出错误横幅、列表加载出更多比赛——视觉用户看到了,屏幕阅读器用户**什么都收不到**。这是表单类应用最典型也最容易修复的 a11y 缺口。
|
||||||
|
2. **`htmlFor` 只有 1 个,而 `<input>` 有 20 个。** 输入框的可见文字提示和输入控件之间没有程序化关联,屏幕阅读器读出的是"编辑框"而不是"邮箱地址"。
|
||||||
|
3. **`Login.tsx` 的错误提示(第 70 行 `{error && (...)}`)没有 `aria-describedby` / `aria-errormessage` 关联到输入框。** 密码输错时,视觉用户看到红字,屏幕阅读器用户**不知道发生了错误**,更不知道错在哪。
|
||||||
|
|
||||||
|
**另外**:`autoFocus` 出现了 3 次(`Login.tsx:65`、`useCommandPalette.tsx:115`、`SettingRow.tsx:83`)。
|
||||||
|
|
||||||
|
- `Login.tsx` 和 `SettingRow.tsx` 场景合理(表单首个字段、内联编辑)。
|
||||||
|
- **`useCommandPalette.tsx:115` 需要复核** —— Cmd+K 面板里 `<Modal>` 本身已经做了"初始聚焦面板"的焦点管理,再叠一个 `autoFocus` 的 input,两者会**争抢焦点**,且后者的行为依赖 React 挂载时序。
|
||||||
|
|
||||||
|
**建议**(按收益排序):
|
||||||
|
1. 错误横幅 / 加载完成提示加 `role="status"` + `aria-live="polite"`;错误用 `role="alert"`。
|
||||||
|
2. 给 20 个 input 补 `htmlFor` + `id` 配对(可先在 `Input` 基元里强制要求 `id`)。
|
||||||
|
3. 表单错误用 `aria-describedby` 指向错误文本节点。
|
||||||
|
4. 复核 `useCommandPalette` 的 `autoFocus` 是否与 `Modal` 焦点管理冲突。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### P1-3 `App.tsx` 把整套布局复制了两遍
|
||||||
|
|
||||||
|
**证据**(`src/App.tsx`,全文仅 82 行,其中两段布局高度重合):
|
||||||
|
|
||||||
|
```
|
||||||
|
21:function StandingsLayout({ children }) {
|
||||||
|
24: <Masthead active="standings" />
|
||||||
|
26: <main className="mx-auto max-w-5xl px-5 py-6 sm:px-8 sm:py-8">
|
||||||
|
30: <footer className="mx-auto max-w-5xl px-5 pb-10 sm:px-8">
|
||||||
|
34: </footer>
|
||||||
|
|
||||||
|
39:function HomePage() {
|
||||||
|
43: <Masthead active="home" />
|
||||||
|
45: <main className="mx-auto max-w-5xl px-5 py-6 sm:px-8 sm:py-8">
|
||||||
|
49: <footer className="mx-auto max-w-5xl px-5 pb-10 sm:px-8">
|
||||||
|
53: </footer>
|
||||||
|
```
|
||||||
|
|
||||||
|
`<main>` 和 `<footer>` 的 className **逐字相同**,唯一区别是 `Masthead` 的 `active` prop 和 footer 里的文案。
|
||||||
|
|
||||||
|
**后果**:改一次容器宽度或内边距,要改两处;将来加第三个页面就是第三处。而 `AdminLayout.tsx` 里的 `NavLink` 也已经出现了同样的 className 复制(见 P1-6)。**这已经不是偶发,是模式。**
|
||||||
|
|
||||||
|
**建议**:抽一个 `<SiteLayout active="home" | "standings">{children}</SiteLayout>`,把 `main` + `footer` 收进去。这是 20 行的改动,消除的是结构性重复。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### P1-4 零代码分割:前后台打进同一个 chunk
|
||||||
|
|
||||||
|
**证据**:
|
||||||
|
|
||||||
|
- `src/routes.tsx`、`src/App.tsx` 中 **`lazy(` 和 `Suspense` 出现次数为 0**。
|
||||||
|
- 构建产物:`index-BuU04RT0.js` **323 KB**(单个文件),`index-BP3DscKo.css` 38.7 KB。
|
||||||
|
- `vite.config.ts` 全文无任何 `build.rollupOptions` / `manualChunks` 配置。
|
||||||
|
|
||||||
|
**后果**:一个只想看预测首页的匿名用户,**必须下载整个后台的全部代码**——Dashboard、Collection、Logs、EvalPage、Backtest、Settings、Monitoring,10 个后台页面一个都不少。而这 10 个页面里绝大概率存在只有登录用户才会触发的逻辑。
|
||||||
|
|
||||||
|
**建议**:
|
||||||
|
1. 路由级 `React.lazy` + `<Suspense>`:`/admin/*` 整体 lazy,`Standings` 单独 lazy。仅此一项通常能砍掉 40%+ 的首屏 JS。
|
||||||
|
2. `vite.config.ts` 加 `manualChunks` 把 `react` / `react-dom` / `react-router-dom` 拆成 `vendor` chunk,利用长期缓存。
|
||||||
|
3. 顺带把 `ErrorBoundary` 移到路由级(现在只在 `App.tsx:60` 最外层一个),这样单个页面崩溃不会白屏整个应用。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### P1-5 `index.html` 缺少全部 SEO 与元信息
|
||||||
|
|
||||||
|
**证据**(`frontend/index.html` 全文):
|
||||||
|
|
||||||
|
```html
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Profeto - 足球 LLM 预测</title>
|
||||||
|
</head>
|
||||||
|
```
|
||||||
|
|
||||||
|
**缺失清单**:
|
||||||
|
|
||||||
|
| 缺失项 | 影响 |
|
||||||
|
|---|---|
|
||||||
|
| `meta[name=description]` | 搜索引擎结果页无摘要 |
|
||||||
|
| `link[rel=icon]` / favicon | 浏览器标签页显示空白文档图标 |
|
||||||
|
| `meta[property=og:*]` | 分享到微信/Twitter 无预览卡片 |
|
||||||
|
| `meta[name=theme-color]` | 移动端浏览器地址栏不染色 |
|
||||||
|
| `link[rel=apple-touch-icon]` | iOS 添加到主屏是截图占位 |
|
||||||
|
| `meta[name=robots]` / canonical | 无索引控制 |
|
||||||
|
|
||||||
|
**另外**:项目有 `src/assets/fonts/LiuJianMaoCao-subset.woff2`(手工子集化的毛笔字体,说明"报刊风"的品牌感是被认真对待的),**但页面没有一个 favicon**。视觉上最讲究的地方,在浏览器标签页上裸奔。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### P1-6 死代码:未使用的导出 + 内联 90 行的图标 switch
|
||||||
|
|
||||||
|
**未使用的导出**(`src/pages/matches/components/MatchDetailSection.tsx:362`):
|
||||||
|
|
||||||
|
```ts
|
||||||
|
export async function loadMatchDetailBundle(
|
||||||
|
```
|
||||||
|
|
||||||
|
全仓 grep `loadMatchDetailBundle` **只有这一处定义,零处引用**。`Matches.tsx` 自己做 `Promise.all`。这个函数是重构遗留物,但因为 `noUnusedLocals: false`(P1-1),导出符号更是从来不会被报未使用——**它会永远留在那里**。
|
||||||
|
|
||||||
|
**`AdminLayout.tsx` 内联图标 switch**:第 20–78 行,一个约 90 行的 `Icon` 函数,`switch` 8 个图标名(collection/chart/target/repeat/eval/monitor/settings/logs),全部是内联 `<svg>` 路径。所有其他图标都应该像 `Masthead.tsx` 里的 `GearIcon` 那样独立成组件。**90 行 SVG 路径塞在布局文件里,让 `AdminLayout.tsx` 的职责严重发散。**
|
||||||
|
|
||||||
|
**同时**(`AdminLayout.tsx:255` 与 `:278`):两处 `NavLink` 的 className 逻辑**重复书写**——与 P1-3 同型。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## P2 — 一致性、性能与工程细节
|
||||||
|
|
||||||
|
### P2-1 `Login.tsx` 仍残留裸色值,未对齐设计令牌
|
||||||
|
|
||||||
|
**证据**(`src/admin/Login.tsx:54`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
className="w-full max-w-sm border border-ink-300 bg-white p-6 shadow-[4px_4px_0_0_rgba(0,0,0,0.06)]"
|
||||||
|
```
|
||||||
|
|
||||||
|
- `bg-white` —— 设计系统里纸质背景是 `paper-*` 令牌,`bg-white` 是一个不在体系内的纯白。
|
||||||
|
- `shadow-[4px_4px_0_0_rgba(0,0,0,0.06)]` —— **兜底在 className 里的任意值阴影**。设计语言里阴影应该来自 `shadow-print` 这类令牌,而不是每个组件自己拼一个 `rgba()`。
|
||||||
|
|
||||||
|
**这是最讽刺的一处**:登录页是后台的**第一印象页面**。视觉体系的所有其他地方都在用令牌,唯独进门第一屏用了裸值。
|
||||||
|
|
||||||
|
### P2-2 `index.css` 里硬编码了色值,而不是引用令牌
|
||||||
|
|
||||||
|
```
|
||||||
|
55: outline: 2px solid #9e1b1b;
|
||||||
|
89: border-top: 3px solid #17140f;
|
||||||
|
208: color: #9E1B1B;
|
||||||
|
```
|
||||||
|
|
||||||
|
`#9e1b1b` 就是 `press` 红,`#17140f` 就是 `ink` 墨色——**但它们以十六进制字面量写死在 CSS 里**。
|
||||||
|
|
||||||
|
**后果很具体**:将来要调品牌红(比如为了打印对比度微调),改 `tailwind.config.js` 里的 `press` 令牌**不会影响这三处**。焦点轮廓、报头粗线、还有第 208 行那个用 `font-brush` 的毛笔字颜色,会保持旧红——**品牌色出现两个来源,且其中一个没有名字**。
|
||||||
|
|
||||||
|
第 208 行的 `#9E1B1B` 还是**大写**写法,与另两处小写不一致,说明这三处是不同时间、不同人手工敲进去的。
|
||||||
|
|
||||||
|
**建议**:CSS 自定义属性化。在 `:root` 定义 `--press` / `--ink`,由 `tailwind.config.js` 一并消费,让 CSS 与 Tailwind 共享同一份令牌来源。
|
||||||
|
|
||||||
|
### P2-3 热渲染路径上没有记忆化
|
||||||
|
|
||||||
|
**证据**(`src/pages/Matches.tsx:230`):
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
{!loading && groupByDate(visibleMatches).map(([dateKey, group]) => (
|
||||||
|
```
|
||||||
|
|
||||||
|
`groupByDate(visibleMatches)` **在每次 render 时重新计算整个列表的分组**。`visibleMatches` 可能包含上百场比赛,任何无关的 state 变化(比如 `error` 从 `null` 变成字符串、`leagueNavRef` 触发的 `canScrollRight` 变化)都会触发整表重算 + 全部 DOM 重建。
|
||||||
|
|
||||||
|
全仓 grep:**`Matches.tsx` 里 `useMemo` / `useCallback` 出现次数为 0**。
|
||||||
|
|
||||||
|
**建议**:`const groups = useMemo(() => groupByDate(visibleMatches), [visibleMatches])`。同时检查列表行组件(`MatchRow` 等)是否可以用 `React.memo` 包住。
|
||||||
|
|
||||||
|
### P2-4 滚动监听分散在三处,各写一遍
|
||||||
|
|
||||||
|
```
|
||||||
|
src/components/BackTop.tsx:13 window.addEventListener('scroll', handleScroll, { passive: true })
|
||||||
|
src/pages/Matches.tsx:91 el.addEventListener('scroll', update, { passive: true })
|
||||||
|
```
|
||||||
|
|
||||||
|
`AdminLayout.tsx` 里还有第三套。三处各自管理 `addEventListener` / `removeEventListener` / throttle / `passive` —— **三份重复的生命周期管理**,任何一处漏了 cleanup 就是内存泄漏。
|
||||||
|
|
||||||
|
**建议**:抽 `useScrollListener(el, handler)` 或 `useScrollPosition()` 到 `lib/hooks/`。至少 `passive: true` 这个优化现在只有两处记得加。
|
||||||
|
|
||||||
|
### P2-5 `Matches.tsx` 仍有内联原生控件,绕过已建成的组件层
|
||||||
|
|
||||||
|
**证据**(`src/pages/Matches.tsx`):
|
||||||
|
|
||||||
|
- 第 109 行 `<button>` —— 联赛 tab,手写 `className="tab"`
|
||||||
|
- 第 158 行 `<button onClick={() => setError(null)} ... aria-label="关闭">×</button>` —— 错误横幅关闭按钮(`Feedback.tsx` 里已有 `ErrorBanner` 组件)
|
||||||
|
- 第 271 行 `<button>` —— "收起"折叠按钮
|
||||||
|
|
||||||
|
`components/ui/` 已经提供了 `Button`、`Switch`、`ErrorBanner`。但 `Matches.tsx` 作为最复杂的前台页面,仍有 3 处裸 `<button>`。
|
||||||
|
|
||||||
|
**全仓原生元素统计**:`<button>` 18 个、`<input>` 20 个、`<select>` 4 个。
|
||||||
|
|
||||||
|
**建议**:这不宜靠人肉找。加一条 ESLint 规则,禁止在 `pages/` 下直接写 `<button className="btn...">`,强制走 `Button` 基元——**这正是 P0-1 里说的"让错误在编译期暴露"**。
|
||||||
|
|
||||||
|
### P2-6 `useLeagues` 静默吞掉 API 失败
|
||||||
|
|
||||||
|
**证据**(`src/pages/matches/hooks/useLeagues.ts` 第 3 行注释):
|
||||||
|
|
||||||
|
```
|
||||||
|
失败或返回空数组则回退本地五大联赛常量(LEAGUES)。
|
||||||
|
```
|
||||||
|
|
||||||
|
从**韧性的角度这是好设计**——接口挂了,用户依然能看到五大联赛而不是空白。
|
||||||
|
|
||||||
|
但从**可观测性角度这是个隐患**:接口持续返回 500,前端**永远静默回退**,没有任何日志、没有任何用户提示。运维那边看到"接口正常"(因为前端不报错),用户那边看到的是"只有五个联赛、没有新增联赛"——**双方都以为一切正常**。
|
||||||
|
|
||||||
|
**建议**:回退保留,但加一次 `console.warn` 或上报埋点。让它"优雅降级但留下痕迹"。
|
||||||
|
|
||||||
|
### P2-7 `ErrorBoundary` 只在应用最外层
|
||||||
|
|
||||||
|
`App.tsx:60` 有一个 `<ErrorBoundary>` 包住整个 `<BrowserRouter>`。这意味着**任意一个页面的渲染崩溃,整个应用白屏**。
|
||||||
|
|
||||||
|
结合 P1-4(无路由级 lazy),建议一并处理:`lazy` 的每个路由包一层 `ErrorBoundary`,让"某个页面挂了"降级为"这个页面显示错误,其他导航照常可用"。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 附:已确认的良好实践(避免"只挑毛病"的偏差)
|
||||||
|
|
||||||
|
这份报告如果只列问题,会给人"一团糟"的错误印象。以下是我逐项验证过、**确实做得好**的地方:
|
||||||
|
|
||||||
|
| 项 | 证据 |
|
||||||
|
|---|---|
|
||||||
|
| HTTP 层设计 | `lib/http.ts` 有统一 `API_BASE`、30s 超时、`AbortController`、`ApiError` 类;401 通过 `UNAUTHORIZED_EVENT` 自定义事件广播解耦 |
|
||||||
|
| 竞态防护 | `useMatchesList` / `useMatchPredict` 用单调递增 `useRef` 序号守卫,这是**很多人会漏掉**的正确做法 |
|
||||||
|
| Modal 无障碍 | `components/ui/index.tsx` 里的 `Modal` 内置焦点陷阱、ESC 关闭、背景滚动锁定、焦点归还——四项齐全 |
|
||||||
|
| 术语化变体 | `ButtonVariant` 用联合类型约束,写错变体名编译期报错——正是要根治"幻影变体"的机制 |
|
||||||
|
| 字体优化 | `LiuJianMaoCao-subset.woff2` 手工子集化 + woff2,说明品牌字体经过真实施工 |
|
||||||
|
| 组件合并 | 上一轮把两套平行组件库归一到 `components/ui/`,Spinner 从 3 份副本收敛到 1 份,净减 541 行 |
|
||||||
|
| 类型检查 | `npx tsc --noEmit` 当前**通过** |
|
||||||
|
| 构建 | `pnpm build` **通过**,产物可正常生成 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 建议的处理顺序
|
||||||
|
|
||||||
|
**第一批(半天,收益最高)**
|
||||||
|
1. `package.json` 加 `typecheck` / `test` 脚本,让已有测试跑起来(P0-1)
|
||||||
|
2. **删除 `dal.ts:318` 的 `avg_latency_ms: 2400`**(P0-3)—— 一行改动,消除一个会误导决策的假数据
|
||||||
|
3. `App.tsx` 抽 `SiteLayout`(P1-3)
|
||||||
|
4. `Matches.tsx` 的 `groupByDate` 加 `useMemo`(P2-3)
|
||||||
|
|
||||||
|
**第二批(1–2 天)**
|
||||||
|
5. 路由级 `React.lazy` + 每路由 `ErrorBoundary`(P1-4 + P2-7)
|
||||||
|
6. `index.html` 补 description / favicon / OG(P1-5)
|
||||||
|
7. `Login.tsx` 裸色值对齐令牌(P2-1)+ `index.css` 三处硬编码色令牌化(P2-2)
|
||||||
|
8. 错误提示加 `aria-live` / `role="alert"`,input 补 `htmlFor`(P1-2)
|
||||||
|
|
||||||
|
**第三批(工程化,需排期)**
|
||||||
|
9. 引入 ESLint + 自定义规则禁止裸 `btn` 类名(P0-1)
|
||||||
|
10. `dal.ts` / `api.ts` / `types.ts` 提升到 `src/api/`(P0-2)
|
||||||
|
11. `dal.ts` 的 14 处 `any` 逐个补类型,并打开 `noUnusedLocals`(P1-1)
|
||||||
|
12. `PredictProgress` 改为诚实的 indeterminate 态,或改由后端真实阶段驱动(P0-4)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*审计人:前端架构审计*
|
||||||
|
*审计日期:2025*
|
||||||
|
*审计基线:`a7e8b75`*
|
||||||
|
*方法:全量文件只读遍历 + 磁盘实证复核,所有 file:line 引用均已在当前工作区验证*
|
||||||
Reference in New Issue
Block a user