chore(admin): 删除合并后遗留的 4 个死代码页面(~1280 行)
DataSources/LLMConfig/Config 已合并进统一 Settings 页, Predictions 已被 PredictionHistory 取代,均无任何路由或 import 引用。
This commit is contained in:
@@ -1,267 +0,0 @@
|
|||||||
/**
|
|
||||||
* Admin 后台 - 系统配置管理页面(报刊风)
|
|
||||||
*
|
|
||||||
* 功能:
|
|
||||||
* - 登录与鉴权说明(ADMIN_PASSWORD,HttpOnly 会话 Cookie)
|
|
||||||
* - 显示当前 .env 配置(脱敏;后端暂无配置端点,为静态说明)
|
|
||||||
* - 配置修改指南
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { useEffect, useState, useCallback } from 'react'
|
|
||||||
import { fetchSystemConfig } from '../dal'
|
|
||||||
import { changePassword, fetchAuthState, UNAUTHORIZED_EVENT } from '../api'
|
|
||||||
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner, SkeletonBlock } from '../components'
|
|
||||||
|
|
||||||
export default function ConfigPage() {
|
|
||||||
const [config, setConfig] = useState<any[]>([])
|
|
||||||
const [loading, setLoading] = useState(true)
|
|
||||||
const [passwordOrigin, setPasswordOrigin] = useState<'db' | 'env' | 'none' | null>(null)
|
|
||||||
|
|
||||||
// 修改密码表单
|
|
||||||
const [currentPwd, setCurrentPwd] = useState('')
|
|
||||||
const [newPwd, setNewPwd] = useState('')
|
|
||||||
const [confirmPwd, setConfirmPwd] = useState('')
|
|
||||||
const [pwdBusy, setPwdBusy] = useState(false)
|
|
||||||
const [pwdNotice, setPwdNotice] = useState<{ ok: boolean; text: string } | null>(null)
|
|
||||||
|
|
||||||
const loadConfig = useCallback(async () => {
|
|
||||||
setLoading(true)
|
|
||||||
try {
|
|
||||||
const data = await fetchSystemConfig()
|
|
||||||
setConfig(data)
|
|
||||||
} catch {
|
|
||||||
setConfig([])
|
|
||||||
} finally {
|
|
||||||
setLoading(false)
|
|
||||||
}
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
loadConfig()
|
|
||||||
fetchAuthState()
|
|
||||||
.then(s => setPasswordOrigin(s.password_origin ?? null))
|
|
||||||
.catch(() => setPasswordOrigin(null))
|
|
||||||
}, [loadConfig])
|
|
||||||
|
|
||||||
async function handleChangePassword(e: React.FormEvent) {
|
|
||||||
e.preventDefault()
|
|
||||||
setPwdNotice(null)
|
|
||||||
if (newPwd !== confirmPwd) {
|
|
||||||
setPwdNotice({ ok: false, text: '两次输入的新密码不一致' })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setPwdBusy(true)
|
|
||||||
try {
|
|
||||||
const res = await changePassword(currentPwd, newPwd)
|
|
||||||
setPwdNotice({ ok: true, text: res.message })
|
|
||||||
// 密码即会话密钥,修改后所有会话失效:主动切回登录页
|
|
||||||
setTimeout(() => window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT)), 1500)
|
|
||||||
} catch (err) {
|
|
||||||
setPwdNotice({ ok: false, text: err instanceof Error ? err.message.split('\n')[0] : '修改失败' })
|
|
||||||
} finally {
|
|
||||||
setPwdBusy(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<SectionHeader
|
|
||||||
title="系统配置"
|
|
||||||
description="登录鉴权说明与系统参数查看。敏感配置一律通过服务器 .env 文件管理。"
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* 登录与鉴权 */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader
|
|
||||||
title="登录与鉴权"
|
|
||||||
description="本后台通过密码登录保护,会话以 HttpOnly Cookie 保存,有效期默认 7 天"
|
|
||||||
/>
|
|
||||||
<CardBody>
|
|
||||||
<Alert kind="ok" title="已通过密码登录" />
|
|
||||||
<p className="mt-3 text-2xs leading-relaxed text-ink-500">
|
|
||||||
密码初始来自服务器 <code className="font-mono">.env</code> 的{' '}
|
|
||||||
<code className="font-mono">ADMIN_PASSWORD</code>(启动时自动转为哈希),在下方修改后以{' '}
|
|
||||||
<code className="font-mono">scrypt</code> 哈希安全存入数据库并立即生效,明文不再留存。
|
|
||||||
密码即会话签名密钥,修改后所有已登录会话失效,需用新密码重新登录。
|
|
||||||
脚本直连接口可改用 <code className="font-mono">ADMIN_API_KEY</code>(请求头 X-API-Key)。
|
|
||||||
</p>
|
|
||||||
{passwordOrigin && (
|
|
||||||
<p className="mt-2 flex items-center gap-2 text-2xs text-ink-500">
|
|
||||||
当前密码来源:
|
|
||||||
{passwordOrigin === 'db' ? (
|
|
||||||
<Badge status="success">数据库(scrypt 哈希)</Badge>
|
|
||||||
) : passwordOrigin === 'env' ? (
|
|
||||||
<Badge status="info">.env 初始值</Badge>
|
|
||||||
) : (
|
|
||||||
<Badge status="error">未配置</Badge>
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* 修改密码表单 */}
|
|
||||||
<form onSubmit={handleChangePassword} className="mt-5 space-y-3 border-t border-ink-200 pt-4">
|
|
||||||
<div className="grid gap-3 sm:grid-cols-3">
|
|
||||||
<div>
|
|
||||||
<label 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"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label 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"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label 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"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{pwdNotice && (
|
|
||||||
<Alert kind={pwdNotice.ok ? 'ok' : 'error'} title={pwdNotice.text} />
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex items-center justify-between gap-2">
|
|
||||||
<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"
|
|
||||||
>
|
|
||||||
{pwdBusy ? (<><Spinner /> 修改中</>) : '修改密码'}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</CardBody>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* 快速导航 */}
|
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
|
||||||
<a
|
|
||||||
href="/admin/data-sources"
|
|
||||||
className="group flex items-center justify-between border border-ink-300 p-4 transition-colors hover:border-ink-900 hover:bg-paper-100"
|
|
||||||
>
|
|
||||||
<div>
|
|
||||||
<div className="font-serif text-sm font-bold text-ink-900">数据源配置</div>
|
|
||||||
<div className="mt-0.5 text-2xs text-ink-500">管理采集源 API Key</div>
|
|
||||||
</div>
|
|
||||||
<span className="text-ink-300 transition-colors group-hover:text-press" aria-hidden="true">→</span>
|
|
||||||
</a>
|
|
||||||
<a
|
|
||||||
href="/admin/llm-config"
|
|
||||||
className="group flex items-center justify-between border border-ink-300 p-4 transition-colors hover:border-ink-900 hover:bg-paper-100"
|
|
||||||
>
|
|
||||||
<div>
|
|
||||||
<div className="font-serif text-sm font-bold text-ink-900">LLM 配置</div>
|
|
||||||
<div className="mt-0.5 text-2xs text-ink-500">管理模型连接与统计</div>
|
|
||||||
</div>
|
|
||||||
<span className="text-ink-300 transition-colors group-hover:text-press" aria-hidden="true">→</span>
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 配置列表 */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader
|
|
||||||
title="当前配置"
|
|
||||||
description="脱敏展示,实际值在服务器 .env 文件中"
|
|
||||||
action={
|
|
||||||
<button onClick={loadConfig} disabled={loading} className="btn btn-sm">
|
|
||||||
{loading ? (<><Spinner /> 加载中</>) : '刷新'}
|
|
||||||
</button>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<CardBody className="px-0 sm:px-0">
|
|
||||||
{loading ? (
|
|
||||||
<div className="space-y-3 px-4 sm:px-5">
|
|
||||||
{[1, 2, 3, 4, 5].map(i => (
|
|
||||||
<SkeletonBlock key={i} className="h-9 w-full" />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : config.length > 0 ? (
|
|
||||||
<div>
|
|
||||||
{config.map(item => (
|
|
||||||
<div
|
|
||||||
key={item.key}
|
|
||||||
className="flex flex-col gap-1 border-b border-ink-200 px-4 py-2.5 last:border-b-0 sm:grid sm:grid-cols-[minmax(0,2fr)_minmax(0,3fr)_minmax(0,2fr)] sm:items-baseline sm:gap-4 sm:px-5"
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="font-mono text-xs text-ink-800">{item.key}</span>
|
|
||||||
{item.is_sensitive && <Badge status="warning">敏感</Badge>}
|
|
||||||
</div>
|
|
||||||
<div className="break-all font-mono text-2xs text-ink-500">{item.value_masked}</div>
|
|
||||||
<div className="text-2xs text-ink-400">{item.description}</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<p className="py-8 text-center text-xs text-ink-400">无法加载配置信息</p>
|
|
||||||
)}
|
|
||||||
</CardBody>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* 修改指南 */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader title="修改配置指南" />
|
|
||||||
<CardBody className="space-y-5">
|
|
||||||
<div>
|
|
||||||
<h4 className="mb-2 font-serif text-sm font-bold text-ink-900">通过 SSH 修改 .env</h4>
|
|
||||||
<pre className="overflow-x-auto border border-ink-200 bg-paper-100 p-3 font-mono text-2xs leading-relaxed text-ink-700">
|
|
||||||
{`# 连接到部署主机
|
|
||||||
ssh user@your-server-ip
|
|
||||||
|
|
||||||
# 进入项目目录
|
|
||||||
cd /vol2/1000/Docker/Profeto
|
|
||||||
|
|
||||||
# 编辑 .env 文件
|
|
||||||
nano .env
|
|
||||||
|
|
||||||
# 修改后重启后端服务
|
|
||||||
docker compose restart api
|
|
||||||
|
|
||||||
# 查看日志确认生效
|
|
||||||
docker compose logs -f api`}
|
|
||||||
</pre>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<h4 className="mb-2 font-serif text-sm font-bold text-ink-900">常用配置项说明</h4>
|
|
||||||
<div className="space-y-2">
|
|
||||||
{[
|
|
||||||
['LLM_API_KEY', 'LLM 服务商的 API 密钥,用于调用大模型'],
|
|
||||||
['LLM_MODEL', '使用的模型名称,如 gpt-4o、claude-3-5-sonnet'],
|
|
||||||
['LLM_BASE_URL', 'API 基础地址,支持兼容 OpenAI 协议的服务商'],
|
|
||||||
['ADMIN_PASSWORD', '管理后台登录密码,修改后重启 api 容器生效'],
|
|
||||||
['ADMIN_API_KEY', '脚本直连接口的鉴权密钥(请求头 X-API-Key)'],
|
|
||||||
['BZZOIRO_KEY', 'Bzzoiro 数据源 API 密钥'],
|
|
||||||
['DATABASE_URL', 'PostgreSQL 数据库连接字符串'],
|
|
||||||
].map(([key, desc]) => (
|
|
||||||
<div key={key} className="flex items-start gap-2.5">
|
|
||||||
<code className="flex-shrink-0 border border-ink-200 bg-paper-100 px-1.5 py-0.5 font-mono text-2xs text-ink-800">
|
|
||||||
{key}
|
|
||||||
</code>
|
|
||||||
<span className="text-xs leading-relaxed text-ink-600">{desc}</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardBody>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,376 +0,0 @@
|
|||||||
import { useEffect, useState, useCallback } from 'react'
|
|
||||||
import {
|
|
||||||
fetchDataSourceStatuses,
|
|
||||||
fetchIngestStatus,
|
|
||||||
fetchAdminStats,
|
|
||||||
fetchKeyRingStatus,
|
|
||||||
resetKeyRingCooldown,
|
|
||||||
updateSetting,
|
|
||||||
clearSetting,
|
|
||||||
testDataSourceConnection,
|
|
||||||
} from '../dal'
|
|
||||||
import type { DataSourceStatus, DataSourceTestResult, IngestSourceStatus, AdminStats } from '../types'
|
|
||||||
import type { KeyRingStatusResponse } from '../dal'
|
|
||||||
import SettingRow from '../SettingRow'
|
|
||||||
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner, SkeletonBlock } from '../components'
|
|
||||||
|
|
||||||
function formatTime(iso: string | null): string {
|
|
||||||
if (!iso) return '暂无记录'
|
|
||||||
try {
|
|
||||||
return new Date(iso).toLocaleString('zh-CN', { hour12: false })
|
|
||||||
} catch {
|
|
||||||
return iso
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function DataSourcesPage() {
|
|
||||||
const [sources, setSources] = useState<DataSourceStatus[]>([])
|
|
||||||
const [loading, setLoading] = useState(true)
|
|
||||||
const [loadError, setLoadError] = useState('')
|
|
||||||
const [ingestStats, setIngestStats] = useState<Record<string, IngestSourceStatus>>({})
|
|
||||||
const [ingestLoading, setIngestLoading] = useState(true)
|
|
||||||
const [stats, setStats] = useState<AdminStats | null>(null)
|
|
||||||
|
|
||||||
const [testingSource, setTestingSource] = useState<string | null>(null)
|
|
||||||
const [testResults, setTestResults] = useState<Record<string, DataSourceTestResult>>({})
|
|
||||||
|
|
||||||
const [editingKey, setEditingKey] = useState<string | null>(null)
|
|
||||||
const [busyKey, setBusyKey] = useState<string | null>(null)
|
|
||||||
const [rowNotice, setRowNotice] = useState<{ key: string; ok: boolean; text: string } | null>(null)
|
|
||||||
const [keyRing, setKeyRing] = useState<KeyRingStatusResponse | null>(null)
|
|
||||||
const [ringLoading, setRingLoading] = useState(false)
|
|
||||||
|
|
||||||
const loadSources = useCallback(async () => {
|
|
||||||
setLoading(true)
|
|
||||||
setLoadError('')
|
|
||||||
try {
|
|
||||||
setSources(await fetchDataSourceStatuses())
|
|
||||||
} catch (err) {
|
|
||||||
setLoadError(err instanceof Error ? err.message.split('\n')[0] : '加载失败')
|
|
||||||
setSources([])
|
|
||||||
} finally {
|
|
||||||
setLoading(false)
|
|
||||||
}
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
// 健康状态(只读,与配置加载并行;失败不阻塞配置页)
|
|
||||||
const loadIngest = useCallback(async () => {
|
|
||||||
setIngestLoading(true)
|
|
||||||
try {
|
|
||||||
const { sources } = await fetchIngestStatus()
|
|
||||||
setIngestStats(Object.fromEntries(sources.map(x => [x.name, x])))
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
} finally {
|
|
||||||
setIngestLoading(false)
|
|
||||||
}
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
// 管理区统计(只读)
|
|
||||||
const loadStats = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
setStats(await fetchAdminStats())
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
}
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
// Key Ring 状态(只读)
|
|
||||||
const loadKeyRing = useCallback(async () => {
|
|
||||||
setRingLoading(true)
|
|
||||||
try {
|
|
||||||
setKeyRing(await fetchKeyRingStatus())
|
|
||||||
} catch {
|
|
||||||
/* ignore */
|
|
||||||
} finally {
|
|
||||||
setRingLoading(false)
|
|
||||||
}
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
loadSources()
|
|
||||||
loadIngest()
|
|
||||||
loadStats()
|
|
||||||
loadKeyRing()
|
|
||||||
}, [loadSources, loadIngest, loadStats, loadKeyRing])
|
|
||||||
|
|
||||||
async function handleTest(sourceName: string) {
|
|
||||||
setTestingSource(sourceName)
|
|
||||||
setTestResults(prev => ({ ...prev, [sourceName]: { ok: false, status: null, latency_ms: 0, detail: '测试中...' } }))
|
|
||||||
try {
|
|
||||||
const result = await testDataSourceConnection(sourceName)
|
|
||||||
setTestResults(prev => ({ ...prev, [sourceName]: result }))
|
|
||||||
} catch (err: unknown) {
|
|
||||||
const msg = err instanceof Error ? err.message.split('\n')[0] : '连接失败'
|
|
||||||
setTestResults(prev => ({ ...prev, [sourceName]: { ok: false, status: null, latency_ms: 0, detail: msg } }))
|
|
||||||
} finally {
|
|
||||||
setTestingSource(null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 渲染数据源健康块(最近采集 + 异常提示)
|
|
||||||
function renderHealth(sourceName: string) {
|
|
||||||
const st = ingestStats[sourceName]
|
|
||||||
if (!st) {
|
|
||||||
return (
|
|
||||||
<div className="flex items-center justify-between text-xs">
|
|
||||||
<span className="text-ink-400">最近成功采集</span>
|
|
||||||
<span className="text-ink-400">{ingestLoading ? '加载中...' : '暂无数据'}</span>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
const ago = st.last_success_at ? formatTime(st.last_success_at) : '暂无记录'
|
|
||||||
const issues: string[] = []
|
|
||||||
if (st.status === 'key_not_configured') issues.push('未配置 API Key')
|
|
||||||
else if (st.status === 'no_data') issues.push('本地无数据,建议补采')
|
|
||||||
if (st.last_failure) issues.push('近期有采集失败')
|
|
||||||
return (
|
|
||||||
<div className="space-y-1.5 border-t border-ink-200 pt-3">
|
|
||||||
<div className="flex items-center justify-between text-xs">
|
|
||||||
<span className="text-ink-400">最近成功采集</span>
|
|
||||||
<span className="text-ink-600">{ago}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between text-xs">
|
|
||||||
<span className="text-ink-400">已入库(近期)</span>
|
|
||||||
<span className="text-ink-600">{st.recent_count.toLocaleString()} 条</span>
|
|
||||||
</div>
|
|
||||||
{st.note && <p className="text-2xs leading-relaxed text-ink-400">{st.note}</p>}
|
|
||||||
{issues.length > 0 && (
|
|
||||||
<p className="border-l-2 border-press bg-press-wash/40 px-2 py-1 text-2xs leading-relaxed text-press-dark">
|
|
||||||
{issues.join(' / ')} — 请前往「数据采集」补采
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{st.last_failure && (
|
|
||||||
<p className="truncate text-2xs text-ink-400" title={st.last_failure.detail}>
|
|
||||||
最近失败: {st.last_failure.detail.slice(0, 60)}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleSave(key: string, value: string) {
|
|
||||||
setBusyKey(key)
|
|
||||||
setRowNotice(null)
|
|
||||||
try {
|
|
||||||
await updateSetting(key, value)
|
|
||||||
setRowNotice({ key, ok: true, text: '已保存,立即生效' })
|
|
||||||
setEditingKey(null)
|
|
||||||
await loadSources()
|
|
||||||
} catch (err) {
|
|
||||||
setRowNotice({ key, ok: false, text: err instanceof Error ? err.message.split('\n')[0] : '保存失败' })
|
|
||||||
} finally {
|
|
||||||
setBusyKey(null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleClear(key: string) {
|
|
||||||
setBusyKey(key)
|
|
||||||
setRowNotice(null)
|
|
||||||
try {
|
|
||||||
await clearSetting(key)
|
|
||||||
setRowNotice({ key, ok: true, text: '已清除数据库覆盖,回落 .env 默认值' })
|
|
||||||
await loadSources()
|
|
||||||
} catch (err) {
|
|
||||||
setRowNotice({ key, ok: false, text: err instanceof Error ? err.message.split('\n')[0] : '清除失败' })
|
|
||||||
} finally {
|
|
||||||
setBusyKey(null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleResetCooldown() {
|
|
||||||
if (!window.confirm('确定重置所有 key 的冷却状态?这可能使被限流的 key 立即恢复请求。')) return
|
|
||||||
try {
|
|
||||||
const res = await resetKeyRingCooldown()
|
|
||||||
setKeyRing(res.stats)
|
|
||||||
setRowNotice({ key: "__ring", ok: true, text: res.message })
|
|
||||||
} catch (err) {
|
|
||||||
setRowNotice({ key: "__ring", ok: false, text: err instanceof Error ? err.message.split('\n')[0] : '重置失败' })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<SectionHeader
|
|
||||||
title="数据源管理"
|
|
||||||
description="数据采集源的 API 配置、健康状态与连通性测试。"
|
|
||||||
/>
|
|
||||||
|
|
||||||
{loadError && (
|
|
||||||
<Alert kind="error" title="无法加载数据源配置" message={loadError} />
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* 数据源卡片 */}
|
|
||||||
{loading ? (
|
|
||||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
|
||||||
{[1, 2, 3].map(i => (
|
|
||||||
<Card key={i}>
|
|
||||||
<CardBody>
|
|
||||||
<div className="space-y-3">
|
|
||||||
<SkeletonBlock className="h-4 w-24" />
|
|
||||||
<SkeletonBlock className="h-3 w-32" />
|
|
||||||
<SkeletonBlock className="h-8 w-full" />
|
|
||||||
</div>
|
|
||||||
</CardBody>
|
|
||||||
</Card>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
|
||||||
{sources.map(source => {
|
|
||||||
const result = testResults[source.name]
|
|
||||||
const cardKeys = source.settings.map(s => s.key)
|
|
||||||
return (
|
|
||||||
<Card key={source.name}>
|
|
||||||
<CardBody className="space-y-4">
|
|
||||||
<div className="flex flex-wrap items-center justify-between gap-x-2 gap-y-1 border-b border-ink-200 pb-3">
|
|
||||||
<h3 className="font-serif text-sm font-bold text-ink-900">{source.label}</h3>
|
|
||||||
<Badge status={source.key_configured ? 'success' : 'error'}>
|
|
||||||
{source.key_configured ? '已就绪' : '缺配置'}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<p className="text-2xs leading-relaxed text-ink-500">{source.description}</p>
|
|
||||||
|
|
||||||
{source.settings.length > 0 ? (
|
|
||||||
<div>
|
|
||||||
{source.settings.map(setting => (
|
|
||||||
<SettingRow
|
|
||||||
key={setting.key}
|
|
||||||
setting={setting}
|
|
||||||
editing={editingKey === setting.key}
|
|
||||||
busy={busyKey === setting.key}
|
|
||||||
onEdit={() => { setEditingKey(setting.key); setRowNotice(null) }}
|
|
||||||
onCancel={() => setEditingKey(null)}
|
|
||||||
onSave={v => handleSave(setting.key, v)}
|
|
||||||
onClear={() => handleClear(setting.key)}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<p className="text-2xs text-ink-400">无需 API Key</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{rowNotice && cardKeys.includes(rowNotice.key) && (
|
|
||||||
<Alert kind={rowNotice.ok ? 'ok' : 'error'} title={rowNotice.text} />
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* 数据源健康:最近采集 + 异常提示 */}
|
|
||||||
{renderHealth(source.name)}
|
|
||||||
|
|
||||||
{result && testingSource !== source.name && (
|
|
||||||
<Alert
|
|
||||||
kind={result.ok ? 'ok' : 'error'}
|
|
||||||
title={result.ok ? `连接成功(${result.latency_ms}ms)` : result.status ? `HTTP ${result.status}` : '连接失败'}
|
|
||||||
message={result.ok ? undefined : result.detail}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<button
|
|
||||||
onClick={() => handleTest(source.name)}
|
|
||||||
disabled={testingSource === source.name}
|
|
||||||
className="btn btn-sm w-full"
|
|
||||||
>
|
|
||||||
{testingSource === source.name ? (<><Spinner /> 测试中</>) : '测试连接'}
|
|
||||||
</button>
|
|
||||||
</CardBody>
|
|
||||||
</Card>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* API Key 轮换环状态 */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader
|
|
||||||
title="API Key 轮换环"
|
|
||||||
description={keyRing?.has_multiple
|
|
||||||
? `已配置 ${keyRing.total} 个 key,遇到限流(429)自动切换;冷却 ${keyRing.cooldown_seconds}s`
|
|
||||||
: '当前仅 1 个 key,无法轮换。建议配置多个 key 以提高限流容忍度'
|
|
||||||
}
|
|
||||||
action={
|
|
||||||
<button
|
|
||||||
onClick={handleResetCooldown}
|
|
||||||
disabled={ringLoading}
|
|
||||||
className="btn-sm btn-outline"
|
|
||||||
>
|
|
||||||
重置冷却
|
|
||||||
</button>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<CardBody>
|
|
||||||
{ringLoading && !keyRing ? (
|
|
||||||
<SkeletonBlock className="h-10 w-full" />
|
|
||||||
) : keyRing && keyRing.total > 0 ? (
|
|
||||||
<div className="space-y-2">
|
|
||||||
{keyRing.keys.map((k, i) => {
|
|
||||||
const isBlocked = k.blocked_remaining > 0
|
|
||||||
return (
|
|
||||||
<div key={i} className={`flex items-center justify-between gap-3 border-b border-ink-100 py-2 last:border-b-0 ${isBlocked ? 'opacity-70' : ''}`}>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className={`inline-block h-2 w-2 rounded-full ${isBlocked ? 'bg-amber-500' : 'bg-emerald-500'}`} />
|
|
||||||
<span className="font-mono text-xs text-ink-700">{k.masked}</span>
|
|
||||||
{i === keyRing.active_index && (
|
|
||||||
<span className="rounded bg-ink-900 px-1.5 py-0.5 text-2xs text-paper-500">当前</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<span className={`text-2xs tabular-nums ${isBlocked ? 'text-amber-600' : 'text-ink-400'}`}>
|
|
||||||
{isBlocked ? `冷却中 ${k.blocked_remaining.toFixed(0)}s` : '可用'}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<p className="text-xs text-ink-400">暂无 key 配置</p>
|
|
||||||
)}
|
|
||||||
<p className="mt-3 border-l-2 border-ink-300 pl-3 text-2xs leading-relaxed text-ink-500">
|
|
||||||
在「Bzzoiro」配置项中用<b>逗号 / 分号 / 换行</b>分隔多个 key 即可启用轮换。遇到 429 自动标记当前 key 为冷却并立即切换到下一个 key;
|
|
||||||
全部 key 冷却时等待最早恢复的 key。「重置冷却」可紧急恢复所有 key。
|
|
||||||
</p>
|
|
||||||
</CardBody>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* 近期活动统计(只读) */}
|
|
||||||
{stats && stats.predictions && (
|
|
||||||
<Card>
|
|
||||||
<CardHeader title="近期预测活动" description="过去 24 小时 / 7 天的预测次数" />
|
|
||||||
<CardBody>
|
|
||||||
<div className="grid grid-cols-3 gap-4 text-center">
|
|
||||||
<div>
|
|
||||||
<div className="font-serif text-2xl font-bold tabular-nums text-ink-900">{stats.predictions.last_24h}</div>
|
|
||||||
<div className="mt-1 text-2xs text-ink-400">近 24 小时</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<div className="font-serif text-2xl font-bold tabular-nums text-ink-900">{stats.predictions.last_7d}</div>
|
|
||||||
<div className="mt-1 text-2xs text-ink-400">近 7 天</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<div className="font-serif text-2xl font-bold tabular-nums text-ink-900">{stats.predictions.total}</div>
|
|
||||||
<div className="mt-1 text-2xs text-ink-400">总计</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardBody>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardHeader title="配置说明" />
|
|
||||||
<CardBody>
|
|
||||||
<div className="space-y-3 text-xs leading-relaxed text-ink-600">
|
|
||||||
<p className="border-l-2 border-ink-300 pl-3">
|
|
||||||
保存的配置存于数据库 <code className="font-mono">app_settings</code> 并<b>立即生效</b>,优先于 <code className="font-mono">.env</code>;「回落 .env」删除覆盖值。
|
|
||||||
</p>
|
|
||||||
<p className="border-l-2 border-ink-300 pl-3">
|
|
||||||
「最近成功采集」为只读健康快照(不触发采集);近似数据已在行内标注。伤停源会区分「未配置 Key / 无数据 / 有数据」。
|
|
||||||
</p>
|
|
||||||
<p className="border-l-2 border-ink-300 pl-3">
|
|
||||||
「测试连接」真实请求上游一次;异常提示会引导前往「数据采集」补采,避免在空数据上误操作。
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</CardBody>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,275 +0,0 @@
|
|||||||
/**
|
|
||||||
* Admin 后台 - LLM 配置管理页面(报刊风)
|
|
||||||
*
|
|
||||||
* 功能:
|
|
||||||
* - 显示当前 LLM 配置(provider, model, base_url;后端暂无配置端点,当前值取自 .env 约定)
|
|
||||||
* - 测试 LLM 连接(会真实调用一次 /predict,产生 LLM 调用费用)
|
|
||||||
* - 显示 LLM 使用统计(从预测记录聚合)
|
|
||||||
* - 可用模型列表
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { useEffect, useState, useCallback } from 'react'
|
|
||||||
import { testLLMConnection, fetchLLMUsageStats, fetchSettings, fetchLLMModels, updateSetting, clearSetting } from '../dal'
|
|
||||||
import type { LLMUsageStats } from '../types'
|
|
||||||
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner, SkeletonBlock } from '../components'
|
|
||||||
import SettingRow from '../SettingRow'
|
|
||||||
import AgentLLMCard from '../AgentLLMCard'
|
|
||||||
import type { DataSourceSetting } from '../types'
|
|
||||||
|
|
||||||
const LLM_SETTING_KEYS = ['LLM_API_KEY', 'LLM_BASE_URL', 'LLM_MODEL']
|
|
||||||
|
|
||||||
export default function LLMConfigPage() {
|
|
||||||
const [stats, setStats] = useState<LLMUsageStats | null>(null)
|
|
||||||
const [loading, setLoading] = useState(true)
|
|
||||||
const [testing, setTesting] = useState(false)
|
|
||||||
const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null)
|
|
||||||
|
|
||||||
// LLM 连接配置(运行时配置,DB 覆盖 .env)
|
|
||||||
const [llmSettings, setLlmSettings] = useState<DataSourceSetting[]>([])
|
|
||||||
const [settingsLoading, setSettingsLoading] = useState(true)
|
|
||||||
const [editingKey, setEditingKey] = useState<string | null>(null)
|
|
||||||
const [busyKey, setBusyKey] = useState<string | null>(null)
|
|
||||||
const [rowNotice, setRowNotice] = useState<{ key: string; ok: boolean; text: string } | null>(null)
|
|
||||||
|
|
||||||
const loadStats = useCallback(async () => {
|
|
||||||
setLoading(true)
|
|
||||||
try {
|
|
||||||
const data = await fetchLLMUsageStats()
|
|
||||||
setStats(data)
|
|
||||||
} catch {
|
|
||||||
setStats(null)
|
|
||||||
} finally {
|
|
||||||
setLoading(false)
|
|
||||||
}
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
const loadSettings = useCallback(async () => {
|
|
||||||
setSettingsLoading(true)
|
|
||||||
try {
|
|
||||||
const all = await fetchSettings()
|
|
||||||
setLlmSettings(all.filter(x => LLM_SETTING_KEYS.includes(x.key)))
|
|
||||||
} catch {
|
|
||||||
setLlmSettings([])
|
|
||||||
} finally {
|
|
||||||
setSettingsLoading(false)
|
|
||||||
}
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
loadStats()
|
|
||||||
loadSettings()
|
|
||||||
}, [loadStats, loadSettings])
|
|
||||||
|
|
||||||
/** 供 LLM_MODEL 行内检测:探测当前服务可用模型,失败抛错由行内展示 */
|
|
||||||
const detectLLMModels = useCallback(async (): Promise<string[]> => {
|
|
||||||
const r = await fetchLLMModels()
|
|
||||||
if (!r.ok) throw new Error(r.detail)
|
|
||||||
return r.models
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
async function handleSave(key: string, value: string) {
|
|
||||||
setBusyKey(key)
|
|
||||||
setRowNotice(null)
|
|
||||||
try {
|
|
||||||
await updateSetting(key, value)
|
|
||||||
setRowNotice({ key, ok: true, text: '已保存,立即生效' })
|
|
||||||
setEditingKey(null)
|
|
||||||
await loadSettings()
|
|
||||||
} catch (err) {
|
|
||||||
setRowNotice({ key, ok: false, text: err instanceof Error ? err.message.split('\n')[0] : '保存失败' })
|
|
||||||
} finally {
|
|
||||||
setBusyKey(null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleClear(key: string) {
|
|
||||||
setBusyKey(key)
|
|
||||||
setRowNotice(null)
|
|
||||||
try {
|
|
||||||
await clearSetting(key)
|
|
||||||
setRowNotice({ key, ok: true, text: '已清除数据库覆盖,回落 .env 默认值' })
|
|
||||||
await loadSettings()
|
|
||||||
} catch (err) {
|
|
||||||
setRowNotice({ key, ok: false, text: err instanceof Error ? err.message.split('\n')[0] : '清除失败' })
|
|
||||||
} finally {
|
|
||||||
setBusyKey(null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleTest() {
|
|
||||||
setTesting(true)
|
|
||||||
setTestResult(null)
|
|
||||||
try {
|
|
||||||
await testLLMConnection()
|
|
||||||
setTestResult({ success: true, message: 'LLM 连接测试成功' })
|
|
||||||
} catch (err: unknown) {
|
|
||||||
const msg = err instanceof Error ? err.message : 'LLM 连接测试失败'
|
|
||||||
setTestResult({ success: false, message: msg })
|
|
||||||
} finally {
|
|
||||||
setTesting(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<SectionHeader
|
|
||||||
title="LLM 配置"
|
|
||||||
description="大语言模型连接状态与使用统计。模型切换通过修改 .env 并重启服务完成。"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className="grid gap-6 lg:grid-cols-2">
|
|
||||||
{/* LLM 连接配置 */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader
|
|
||||||
title="连接配置"
|
|
||||||
description="保存到数据库并立即生效,优先于服务器 .env"
|
|
||||||
action={
|
|
||||||
<button onClick={loadSettings} disabled={settingsLoading} className="btn btn-sm">
|
|
||||||
{settingsLoading ? (<><Spinner /> 加载中</>) : '刷新'}
|
|
||||||
</button>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<CardBody>
|
|
||||||
{settingsLoading ? (
|
|
||||||
<div className="space-y-3">
|
|
||||||
{[1, 2, 3].map(i => <SkeletonBlock key={i} className="h-9 w-full" />)}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div>
|
|
||||||
{llmSettings.map(setting => (
|
|
||||||
<SettingRow
|
|
||||||
key={setting.key}
|
|
||||||
setting={setting}
|
|
||||||
editing={editingKey === setting.key}
|
|
||||||
busy={busyKey === setting.key}
|
|
||||||
onEdit={() => {
|
|
||||||
setEditingKey(setting.key)
|
|
||||||
setRowNotice(null)
|
|
||||||
}}
|
|
||||||
onCancel={() => setEditingKey(null)}
|
|
||||||
onSave={v => handleSave(setting.key, v)}
|
|
||||||
onClear={() => handleClear(setting.key)}
|
|
||||||
detectModels={setting.key === 'LLM_MODEL' ? detectLLMModels : undefined}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{rowNotice && (
|
|
||||||
<div className="mt-3">
|
|
||||||
<Alert kind={rowNotice.ok ? 'ok' : 'error'} title={rowNotice.text} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<p className="mt-3 border-l-2 border-ink-300 pl-3 text-2xs leading-relaxed text-ink-500">
|
|
||||||
模式: 多专家 (5 路 + 终裁)。填入可连通的 OpenAI 兼容服务(如 DeepSeek、
|
|
||||||
智谱、通义或任意网关)后点下方「测试 LLM 连接」验证。
|
|
||||||
</p>
|
|
||||||
|
|
||||||
{/* 测试连接 */}
|
|
||||||
{testResult && (
|
|
||||||
<div className="mt-4">
|
|
||||||
<Alert
|
|
||||||
kind={testResult.success ? 'ok' : 'error'}
|
|
||||||
title={testResult.success ? '连接正常' : '连接失败'}
|
|
||||||
message={testResult.success ? undefined : testResult.message}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<button onClick={handleTest} disabled={testing} className="btn btn-sm mt-4 w-full">
|
|
||||||
{testing ? (<><Spinner /> 测试中</>) : '测试 LLM 连接'}
|
|
||||||
</button>
|
|
||||||
<p className="mt-2 text-center text-2xs text-ink-400">
|
|
||||||
测试会真实调用一次 LLM 预测,产生费用。
|
|
||||||
</p>
|
|
||||||
</CardBody>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* 使用统计 */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader
|
|
||||||
title="使用统计"
|
|
||||||
description="从最近预测记录聚合"
|
|
||||||
action={
|
|
||||||
<button onClick={loadStats} disabled={loading} className="btn btn-sm">
|
|
||||||
{loading ? (<><Spinner /> 加载中</>) : '刷新'}
|
|
||||||
</button>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<CardBody>
|
|
||||||
{loading ? (
|
|
||||||
<div className="space-y-3">
|
|
||||||
<SkeletonBlock className="h-16 w-full" />
|
|
||||||
<SkeletonBlock className="h-16 w-full" />
|
|
||||||
</div>
|
|
||||||
) : stats ? (
|
|
||||||
<div className="grid grid-cols-3 gap-4">
|
|
||||||
<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">
|
|
||||||
{stats.total_predictions}
|
|
||||||
</div>
|
|
||||||
<div className="mt-1 text-2xs text-ink-400">总预测数</div>
|
|
||||||
</div>
|
|
||||||
<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">
|
|
||||||
{stats.avg_latency_ms > 0 ? `${(stats.avg_latency_ms / 1000).toFixed(1)}s` : '—'}
|
|
||||||
</div>
|
|
||||||
<div className="mt-1 text-2xs text-ink-400">平均延迟</div>
|
|
||||||
</div>
|
|
||||||
<div className="border-t-2 border-press pt-3 text-center">
|
|
||||||
<div className="font-serif text-2xl font-bold tabular-nums text-press">
|
|
||||||
{stats.success_rate.toFixed(0)}%
|
|
||||||
</div>
|
|
||||||
<div className="mt-1 text-2xs text-ink-400">有效率</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<p className="py-6 text-center text-xs text-ink-400">暂无使用统计数据</p>
|
|
||||||
)}
|
|
||||||
</CardBody>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 专家与终裁独立配置 */}
|
|
||||||
<AgentLLMCard />
|
|
||||||
|
|
||||||
{/* 最近预测 */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader title="最近预测记录" />
|
|
||||||
<CardBody className="px-0 sm:px-0">
|
|
||||||
{loading ? (
|
|
||||||
<div className="space-y-2 px-4 sm:px-5">
|
|
||||||
{[1, 2, 3].map(i => (
|
|
||||||
<SkeletonBlock key={i} className="h-10 w-full" />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : stats && stats.recent_predictions.length > 0 ? (
|
|
||||||
<div>
|
|
||||||
{stats.recent_predictions.map(p => (
|
|
||||||
<div
|
|
||||||
key={p.id}
|
|
||||||
className="flex flex-col gap-1.5 border-b border-ink-200 px-4 py-2.5 last:border-b-0 sm:flex-row sm:items-center sm:justify-between sm:px-5"
|
|
||||||
>
|
|
||||||
<div className="flex items-baseline gap-3">
|
|
||||||
<span className="text-2xs tabular-nums text-ink-400">#{p.id}</span>
|
|
||||||
<span className="text-xs text-ink-800">比赛 #{p.match_id}</span>
|
|
||||||
<span className="font-mono text-2xs text-ink-500">{p.model}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<span className="text-2xs tabular-nums text-ink-400">
|
|
||||||
{p.created_at ? new Date(p.created_at).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }) : '—'}
|
|
||||||
</span>
|
|
||||||
{p.status === 'success' ? <Badge status="success">成功</Badge> : <Badge status="error">失败</Badge>}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<p className="py-8 text-center text-xs text-ink-400">暂无预测记录</p>
|
|
||||||
)}
|
|
||||||
</CardBody>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,363 +0,0 @@
|
|||||||
/**
|
|
||||||
* Admin 后台 - 预测管理页面(报刊风)
|
|
||||||
*
|
|
||||||
* 功能:
|
|
||||||
* - 触发预测(选择比赛 + 模式)
|
|
||||||
* - 结算:录入实际比分,写入评估(接 /eval/settle)
|
|
||||||
* - 预测记录列表:可展开查看终裁理由与专家摘要
|
|
||||||
*
|
|
||||||
* 响应式布局: 移动端单列,桌面端双列
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
|
||||||
import { triggerPrediction, fetchPredictions, fetchMatches, settlePrediction } from '../dal'
|
|
||||||
import type { Match, Prediction } from '../types'
|
|
||||||
import { Card, CardBody, CardHeader, Badge, SectionHeader, Alert, Spinner } from '../components'
|
|
||||||
import { teamSidePrefix } from '../../components/TeamSideTag'
|
|
||||||
import { AgentWeightsBar } from '../components'
|
|
||||||
|
|
||||||
const AGENT_LABELS: Record<string, string> = {
|
|
||||||
h2h: '历史交锋分析专家',
|
|
||||||
form: '近期状态分析专家',
|
|
||||||
stats: '攻防数据分析专家',
|
|
||||||
home_away: '主客因素分析专家',
|
|
||||||
injuries: '阵容完整性分析专家',
|
|
||||||
}
|
|
||||||
|
|
||||||
const OUTCOME_LABEL: Record<string, string> = { '1': '主胜', X: '平局', '2': '客胜' }
|
|
||||||
|
|
||||||
function fmtTime(s?: string | null): string {
|
|
||||||
if (!s) return '—'
|
|
||||||
const d = new Date(s)
|
|
||||||
return isNaN(d.getTime())
|
|
||||||
? s
|
|
||||||
: d.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function PredictionsPage() {
|
|
||||||
const [matches, setMatches] = useState<Match[]>([])
|
|
||||||
const [predictions, setPredictions] = useState<Prediction[]>([])
|
|
||||||
const [matchId, setMatchId] = useState('')
|
|
||||||
const [mode, setMode] = useState<'single' | 'multi'>('multi')
|
|
||||||
const [loading, setLoading] = useState(false)
|
|
||||||
const [error, setError] = useState<string | null>(null)
|
|
||||||
const [successMsg, setSuccessMsg] = useState<string | null>(null)
|
|
||||||
|
|
||||||
// 结算表单
|
|
||||||
const [settleId, setSettleId] = useState('')
|
|
||||||
const [homeGoals, setHomeGoals] = useState('')
|
|
||||||
const [awayGoals, setAwayGoals] = useState('')
|
|
||||||
const [settling, setSettling] = useState(false)
|
|
||||||
const [settleMsg, setSettleMsg] = useState<{ kind: 'error' | 'ok'; text: string } | null>(null)
|
|
||||||
|
|
||||||
const refreshPredictions = useCallback(async () => {
|
|
||||||
const list = await fetchPredictions(50)
|
|
||||||
setPredictions(list)
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
refreshPredictions()
|
|
||||||
fetchMatches({ limit: 100 }).then(d => setMatches(d.items))
|
|
||||||
}, [refreshPredictions])
|
|
||||||
|
|
||||||
/** match_id → 中文名对阵 */
|
|
||||||
const matchName = useMemo(() => {
|
|
||||||
const map = new Map<number, string>()
|
|
||||||
for (const m of matches) {
|
|
||||||
const home = m.home_team_zh || m.home_team
|
|
||||||
const away = m.away_team_zh || m.away_team
|
|
||||||
map.set(m.id, `${teamSidePrefix('home')}${home} vs ${teamSidePrefix('away')}${away}`)
|
|
||||||
}
|
|
||||||
return map
|
|
||||||
}, [matches])
|
|
||||||
|
|
||||||
const nameOf = (id: number) => matchName.get(id) ?? `比赛 #${id}`
|
|
||||||
|
|
||||||
async function handlePredict(e: React.FormEvent) {
|
|
||||||
e.preventDefault()
|
|
||||||
if (!matchId) return
|
|
||||||
setLoading(true)
|
|
||||||
setError(null)
|
|
||||||
setSuccessMsg(null)
|
|
||||||
try {
|
|
||||||
await triggerPrediction({ match_id: parseInt(matchId), mode })
|
|
||||||
setSuccessMsg('预测任务已完成,记录已更新')
|
|
||||||
await refreshPredictions()
|
|
||||||
} catch (err: unknown) {
|
|
||||||
setError(err instanceof Error ? err.message : '预测失败')
|
|
||||||
} finally {
|
|
||||||
setLoading(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const unsettled = predictions.filter(p => !p.settled)
|
|
||||||
|
|
||||||
async function handleSettle(e: React.FormEvent) {
|
|
||||||
e.preventDefault()
|
|
||||||
const pid = parseInt(settleId)
|
|
||||||
const hg = parseInt(homeGoals)
|
|
||||||
const ag = parseInt(awayGoals)
|
|
||||||
if (!pid || isNaN(hg) || isNaN(ag)) return
|
|
||||||
setSettling(true)
|
|
||||||
setSettleMsg(null)
|
|
||||||
try {
|
|
||||||
await settlePrediction(pid, hg, ag)
|
|
||||||
setSettleMsg({ kind: 'ok', text: '结算完成,准确率统计已更新' })
|
|
||||||
setSettleId('')
|
|
||||||
setHomeGoals('')
|
|
||||||
setAwayGoals('')
|
|
||||||
await refreshPredictions()
|
|
||||||
} catch (err: unknown) {
|
|
||||||
setSettleMsg({
|
|
||||||
kind: 'error',
|
|
||||||
text: err instanceof Error ? err.message : '结算失败',
|
|
||||||
})
|
|
||||||
} finally {
|
|
||||||
setSettling(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const settleTarget = predictions.find(p => p.id === parseInt(settleId))
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<SectionHeader
|
|
||||||
title="预测管理"
|
|
||||||
description="触发 LLM 预测;赛后录入实际比分完成结算,供准确率统计使用。"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className="grid gap-6 lg:grid-cols-2">
|
|
||||||
{/* 新建预测 */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader title="新建预测" />
|
|
||||||
<CardBody>
|
|
||||||
<form onSubmit={handlePredict} className="space-y-4">
|
|
||||||
<div>
|
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">比赛</label>
|
|
||||||
<select
|
|
||||||
value={matchId}
|
|
||||||
onChange={e => setMatchId(e.target.value)}
|
|
||||||
className="field w-full"
|
|
||||||
>
|
|
||||||
<option value="">选择比赛</option>
|
|
||||||
{matches.map(m => (
|
|
||||||
<option key={m.id} value={m.id}>
|
|
||||||
{teamSidePrefix('home')}{(m.home_team_zh || m.home_team)} vs {teamSidePrefix('away')}{(m.away_team_zh || m.away_team)}
|
|
||||||
({m.match_date?.slice(5, 10)})
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">模式</label>
|
|
||||||
<select
|
|
||||||
value={mode}
|
|
||||||
onChange={e => setMode(e.target.value as 'single' | 'multi')}
|
|
||||||
className="field w-full"
|
|
||||||
>
|
|
||||||
<option value="multi">多专家 (5 路 + 终裁,慢而稳)</option>
|
|
||||||
<option value="single">单次调用 (快)</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{error && <Alert kind="error" title="预测失败" message={error} onClose={() => setError(null)} />}
|
|
||||||
{successMsg && (
|
|
||||||
<Alert kind="ok" title={successMsg} onClose={() => setSuccessMsg(null)} />
|
|
||||||
)}
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={loading || !matchId}
|
|
||||||
className="btn btn-solid w-full"
|
|
||||||
>
|
|
||||||
{loading ? (<><Spinner /> 预测中,多专家模式约需 20-60 秒</>) : '触发预测'}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
</CardBody>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* 结算 */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader
|
|
||||||
title="预测结算"
|
|
||||||
description="录入实际比分,系统据此统计 1X2 准确率与比分 RMSE"
|
|
||||||
/>
|
|
||||||
<CardBody>
|
|
||||||
{unsettled.length === 0 ? (
|
|
||||||
<p className="py-6 text-center text-xs text-ink-400">
|
|
||||||
没有待结算的预测记录。预测完成后可在此录入实际比分。
|
|
||||||
</p>
|
|
||||||
) : (
|
|
||||||
<form onSubmit={handleSettle} className="space-y-4">
|
|
||||||
<div>
|
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">预测记录</label>
|
|
||||||
<select
|
|
||||||
value={settleId}
|
|
||||||
onChange={e => setSettleId(e.target.value)}
|
|
||||||
className="field w-full"
|
|
||||||
>
|
|
||||||
<option value="">选择待结算预测({unsettled.length} 条)</option>
|
|
||||||
{unsettled.map(p => (
|
|
||||||
<option key={p.id} value={p.id}>
|
|
||||||
#{p.id} {nameOf(p.match_id)} · 预测 {p.pred_home_goals ?? '-'}:{p.pred_away_goals ?? '-'}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{settleTarget && (
|
|
||||||
<p className="border-l-2 border-ink-300 pl-3 text-2xs text-ink-500">
|
|
||||||
预测:{settleTarget.pred_home_goals ?? '-'} : {settleTarget.pred_away_goals ?? '-'}
|
|
||||||
({OUTCOME_LABEL[settleTarget.pred_1x2 ?? ''] ?? '?'})
|
|
||||||
<span className="ml-2">{fmtTime(settleTarget.created_at)}</span>
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-3">
|
|
||||||
<div>
|
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">主队实际进球</label>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
min={0}
|
|
||||||
max={30}
|
|
||||||
value={homeGoals}
|
|
||||||
onChange={e => setHomeGoals(e.target.value)}
|
|
||||||
className="field w-full"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label className="mb-1.5 block text-xs text-ink-500">客队实际进球</label>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
min={0}
|
|
||||||
max={30}
|
|
||||||
value={awayGoals}
|
|
||||||
onChange={e => setAwayGoals(e.target.value)}
|
|
||||||
className="field w-full"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{settleMsg && (
|
|
||||||
<Alert
|
|
||||||
kind={settleMsg.kind}
|
|
||||||
title={settleMsg.kind === 'ok' ? '结算完成' : '结算失败'}
|
|
||||||
message={settleMsg.kind === 'error' ? settleMsg.text : undefined}
|
|
||||||
onClose={() => setSettleMsg(null)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={settling || !settleId || homeGoals === '' || awayGoals === ''}
|
|
||||||
className="btn btn-solid w-full"
|
|
||||||
>
|
|
||||||
{settling ? (<><Spinner /> 结算中</>) : '提交结算'}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
)}
|
|
||||||
</CardBody>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* 最近预测 */}
|
|
||||||
<Card>
|
|
||||||
<CardHeader title="预测记录" description="点击行可展开终裁理由与专家摘要" />
|
|
||||||
<CardBody className="px-0 sm:px-0">
|
|
||||||
{predictions.length === 0 ? (
|
|
||||||
<p className="py-10 text-center text-xs text-ink-400">
|
|
||||||
暂无预测记录,触发预测后将在此显示
|
|
||||||
</p>
|
|
||||||
) : (
|
|
||||||
<div>
|
|
||||||
{predictions.map(p => {
|
|
||||||
const okAgents = (p.agent_outputs ?? []).filter(a => a.status === 'ok')
|
|
||||||
return (
|
|
||||||
<details key={p.id} className="group border-b border-ink-200 last:border-b-0">
|
|
||||||
<summary className="flex cursor-pointer list-none flex-wrap items-baseline gap-x-3 gap-y-1 px-4 py-3 transition-colors hover:bg-paper-100 sm:px-5">
|
|
||||||
<span className="text-2xs tabular-nums text-ink-400">#{p.id}</span>
|
|
||||||
<span className="text-sm font-medium text-ink-900">{nameOf(p.match_id)}</span>
|
|
||||||
<span className="font-serif text-sm font-bold tabular-nums text-ink-900">
|
|
||||||
{p.pred_home_goals ?? '-'}<span className="mx-0.5 font-normal text-ink-300">:</span>{p.pred_away_goals ?? '-'}
|
|
||||||
</span>
|
|
||||||
<span className="text-2xs text-ink-500">
|
|
||||||
{OUTCOME_LABEL[p.pred_1x2 ?? ''] ?? '—'}
|
|
||||||
{p.subjective_confidence !== null && p.subjective_confidence !== undefined &&
|
|
||||||
` · ${Math.round(p.subjective_confidence * 100)}%`}
|
|
||||||
</span>
|
|
||||||
<span className="ml-auto flex items-baseline gap-3">
|
|
||||||
{p.settled ? (
|
|
||||||
<Badge status="success">已结算</Badge>
|
|
||||||
) : (
|
|
||||||
<Badge status="pending">未结算</Badge>
|
|
||||||
)}
|
|
||||||
{p.status === 'degraded' && (
|
|
||||||
<Badge status="error">降级·仅供参考</Badge>
|
|
||||||
)}
|
|
||||||
{p.status === 'failed' && (
|
|
||||||
<Badge status="error">预测失败</Badge>
|
|
||||||
)}
|
|
||||||
<span className="text-2xs tabular-nums text-ink-400">{fmtTime(p.created_at)}</span>
|
|
||||||
<svg
|
|
||||||
viewBox="0 0 20 20"
|
|
||||||
className="h-3 w-3 self-center text-ink-300 transition-transform group-open:rotate-90"
|
|
||||||
fill="currentColor"
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
<path d="M7.3 5.3a1 1 0 011.4 0l4 4a1 1 0 010 1.4l-4 4a1 1 0 01-1.4-1.4L10.6 10 7.3 6.7a1 1 0 010-1.4z" />
|
|
||||||
</svg>
|
|
||||||
</span>
|
|
||||||
</summary>
|
|
||||||
|
|
||||||
<div className="space-y-3 px-4 pb-4 pl-8 sm:px-6 sm:pl-9">
|
|
||||||
<p className="text-2xs text-ink-500">
|
|
||||||
{p.mode === 'multi' ? `多专家 · ${okAgents.length}/${p.agent_outputs?.length ?? 0} 路有效` : '单次模式'}
|
|
||||||
{p.model && <span className="ml-2 font-mono">{p.model}</span>}
|
|
||||||
</p>
|
|
||||||
|
|
||||||
{p.reasoning && (
|
|
||||||
<blockquote className="border-l-2 border-press pl-4">
|
|
||||||
<p className="whitespace-pre-wrap font-serif text-sm leading-loose text-ink-700">
|
|
||||||
{p.reasoning}
|
|
||||||
</p>
|
|
||||||
</blockquote>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{p.agent_weights && Object.keys(p.agent_weights).length > 0 && (
|
|
||||||
<AgentWeightsBar weights={p.agent_weights} okCount={okAgents.length} />
|
|
||||||
)}
|
|
||||||
|
|
||||||
{p.agent_outputs && p.agent_outputs.length > 0 && (
|
|
||||||
<ul className="space-y-1">
|
|
||||||
{p.agent_outputs.map((a, i) => (
|
|
||||||
<li key={i} className="flex items-baseline gap-2.5 text-xs">
|
|
||||||
<span className={`inline-block h-1.5 w-1.5 flex-shrink-0 self-center ${a.status === 'ok' ? 'bg-ink-900' : 'bg-ink-300'}`} aria-hidden="true" />
|
|
||||||
<span className="text-ink-800">{AGENT_LABELS[a.agent] ?? a.agent}</span>
|
|
||||||
{a.probable_score && (
|
|
||||||
<span className="font-serif font-bold tabular-nums text-ink-800">{a.probable_score}</span>
|
|
||||||
)}
|
|
||||||
<span className="text-2xs text-ink-400">
|
|
||||||
{a.status === 'ok' ? '' : a.status === 'no_data' ? '无数据' : '失败'}
|
|
||||||
</span>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{p.settled && (
|
|
||||||
<p className="border-t border-ink-100 pt-2.5 text-2xs text-ink-500">
|
|
||||||
实际比分 {p.actual_home_goals ?? '-'} : {p.actual_away_goals ?? '-'}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</details>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CardBody>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user