Files
monkey-ai-web/src/components/quality/QualityOverview.jsx
T
zhanjunhao c492e2b7c0 fix(*): 全量 UI 审查与 undefined 展示异常修复
分析模块:补齐看板、排行、趋势及报表数值兜底
企业与用户中心:修复统计、成员、技能及资金字段展示
充值与交易:修复充值、发票、订单、订阅及支付字段拼接
平台页面:修复渠道、模型、服务监控与状态空值展示
通用能力:新增安全展示工具,补齐九语言文案与回归测试
文档记录:更新修复范围、影响及回滚说明
2026-11-20 10:18:17 +08:00

524 lines
15 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { Trans } from 'react-i18next';
import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import React, { useMemo } from 'react';
import { Button, Skeleton, Tooltip } from '@/components/ui';
import { useActualTheme } from '../../context/Theme';
import { formatPercent } from '../../helpers/safeDisplay';
import { VChart } from '@visactor/react-vchart';
import { Activity, AlertTriangle, Info, PieChart } from 'lucide-react';
import {
DEGRADE_TEXT,
FAULTS,
OUTCOMES,
fmtInt,
fmtMs,
fmtTs,
outcomeColors,
pct,
qualityErrorText,
readCssVar,
toneColor,
} from './qualityConstants';
const Delta = ({ current, previous, higherIsBetter = true, asRate, t }) => {
if (previous === undefined || previous === null) return null;
const diff = current - previous;
if (!Number.isFinite(diff) || Math.abs(diff) < (asRate ? 0.0005 : 0.5)) {
return <span>{t('与上一周期持平')}</span>;
}
const good = higherIsBetter ? diff > 0 : diff < 0;
const text = asRate
? `${diff > 0 ? '+' : ''}${(diff * 100).toFixed(1)}pp`
: `${diff > 0 ? '+' : ''}${fmtInt(Math.round(diff))}`;
return (
<span className={good ? 'quality-delta-up' : 'quality-delta-down'}>
{t('环比')} {text}
</span>
);
};
/** 数据来源 / 降级 / 完整度提示条 */
export const QualityMetaNotice = ({ meta, scope, t }) => {
if (!meta) return null;
const notes = [];
// 未知原因码不直显(避免英文内部标识出现在界面上)
const reasons = String(meta.degraded_reason || '')
.split(',')
.filter((r) => DEGRADE_TEXT[r])
.map((r) => t(DEGRADE_TEXT[r]));
if (reasons.length > 0 || meta.data_source === 'logs') {
notes.push({
tone: 'info',
text:
reasons.join(';') ||
t('当前条件下直接统计调用日志,时间范围最长 7 天'),
});
}
if (meta.narrowed) {
notes.push({
tone: 'info',
text: t(
'已按结局 / 责任方收窄:耗时分位与用量为收窄前的整体值,仅供参考',
),
});
}
const c = meta.completeness || {};
if (scope !== 'org' && c.enabled === false) {
notes.push({
tone: 'warn',
text: t(
'质量采集已关闭(MONITOR_QUALITY_ENABLED=false),新调用不会进入看板',
),
});
}
if (scope !== 'org' && (c.dropped_events > 0 || c.dropped_rows > 0)) {
notes.push({
tone: 'warn',
text: t(
'本节点自启动以来丢弃了 {{events}} 条事件 / {{rows}} 行聚合,统计可能偏低',
{
events: fmtInt(c.dropped_events),
rows: fmtInt(c.dropped_rows),
},
),
});
}
if (meta.detail_available === false) {
notes.push({
tone: 'warn',
text: t('日志表尚未完成质量字段升级,明细与按用户 / 密钥分析暂不可用'),
});
}
if (notes.length === 0) return null;
return (
<div className='flex flex-col gap-2'>
{notes.map((n, i) => (
<div key={i} className='quality-notice' data-tone={n.tone}>
{n.tone === 'warn' ? (
<AlertTriangle size={14} className='mt-0.5 flex-shrink-0' />
) : (
<Info size={14} className='mt-0.5 flex-shrink-0' />
)}
<span>{n.text}</span>
</div>
))}
</div>
);
};
export const QualityErrorState = ({ error, onRetry, t }) => (
<div className='quality-card'>
<div className='quality-empty flex flex-col items-center gap-3'>
<AlertTriangle size={22} className='text-[var(--ui-color-danger)]' />
<div>{qualityErrorText(t, error)}</div>
{onRetry && (
<Button size='small' onClick={onRetry}>
{t('重试')}
</Button>
)}
</div>
</div>
);
/** KPI 卡:点击结局类卡片直接下钻到对应明细 */
export const QualityKpiCards = ({ summary, loading, onDrillOutcome, t }) => {
if (loading && !summary) {
return (
<div className='quality-kpis'>
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className='quality-kpi'>
<Skeleton.Paragraph rows={2} />
</div>
))}
</div>
);
}
const cur = summary?.current || {};
// 直查日志时后端不计算上一周期,不能拿全 0 当环比基数
const prev = summary?.meta?.no_previous ? undefined : summary?.previous;
const cards = [
{
key: 'total',
label: t('请求总数'),
value: fmtInt(cur.total),
color: toneColor('primary'),
foot: (
<>
<Delta current={cur.total} previous={prev?.total} t={t} />
{cur.total_raw !== cur.total && (
<Tooltip content={t('含客户端中断与内容拦截的原始请求数')}>
<span>
{t('原始')} {fmtInt(cur.total_raw)}
</span>
</Tooltip>
)}
</>
),
},
{
key: 'success_rate',
label: t('成功率'),
value: pct(cur.success_rate, 2),
color: toneColor('success'),
foot: (
<>
<Delta
current={cur.success_rate}
previous={prev?.success_rate}
asRate
t={t}
/>
<span>
{t('直接成功率')} {pct(cur.direct_rate)}
</span>
</>
),
},
{
key: 'fallback_saved',
label: t('兜底成功'),
value: fmtInt(cur.fallback_saved),
color: toneColor('primary'),
outcome: '2',
foot: (
<>
<span>
{t('触发兜底')} {fmtInt(cur.fallback_triggered)}
</span>
<span>
{t('挽救率')} {pct(cur.fallback_save_rate)}
</span>
</>
),
},
{
key: 'fallback_failed',
label: t('兜底失败'),
value: fmtInt(cur.fallback_failed),
color: toneColor('danger'),
outcome: '3',
foot: (
<Delta
current={cur.fallback_failed}
previous={prev?.fallback_failed}
higherIsBetter={false}
t={t}
/>
),
},
{
key: 'failed_no_fallback',
label: t('失败(未兜底)'),
value: fmtInt(cur.failed_no_fallback),
color: toneColor('warning'),
outcome: '4',
foot: (
<span>
{t('上游故障率')} {pct(cur.upstream_fault_rate)}
</span>
),
},
{
key: 'p95',
label: t('P95 耗时'),
value: fmtMs(cur.p95_ms),
color: toneColor('tertiary'),
foot: (
<>
<span>
{I18N_TECHNICAL_TEXT.P50} {fmtMs(cur.p50_ms)}
</span>
<span>
{t('平均')} {fmtMs(cur.avg_ms)}
</span>
</>
),
},
{
key: 'abort',
label: t('客户端中断 / 内容拦截'),
value: `${fmtInt(cur.client_abort)} / ${fmtInt(cur.blocked)}`,
color: toneColor('purple'),
outcome: '5,6',
foot: (
<span>
{t('拦截率')} {pct(cur.block_rate)}
</span>
),
},
];
return (
<div className='quality-kpis'>
{cards.map((card) => {
const clickable = Boolean(card.outcome && onDrillOutcome);
return (
<div
key={card.key}
className='quality-kpi'
style={{ '--kpi-color': card.color }}
data-clickable={clickable}
role={clickable ? 'button' : undefined}
tabIndex={clickable ? 0 : undefined}
onClick={clickable ? () => onDrillOutcome(card.outcome) : undefined}
onKeyDown={
clickable
? (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
onDrillOutcome(card.outcome);
}
}
: undefined
}
>
<span className='quality-kpi-label'>{card.label}</span>
<span className='quality-kpi-value'>{card.value}</span>
<span className='quality-kpi-foot'>{card.foot}</span>
</div>
);
})}
</div>
);
};
/** 趋势:结局堆叠柱 + 成功率折线;点击柱子把时间范围放大到该桶 */
export const QualityTrendChart = ({ trend, loading, onZoom, t }) => {
const actualTheme = useActualTheme();
const points = useMemo(() => trend?.points || [], [trend]);
const gran = trend?.meta?.granularity || 3600;
const spec = useMemo(() => {
if (points.length === 0) return null;
const colors = outcomeColors();
const bars = [];
points.forEach((p) => {
OUTCOMES.forEach((o) => {
bars.push({
ts: p.ts,
time: fmtTs(p.ts),
outcome: t(o.label),
value: p[o.key] || 0,
});
});
});
const rateLabel = t('成功率');
const line = points.map((p) => ({
ts: p.ts,
time: fmtTs(p.ts),
series: rateLabel,
rate: p.total > 0 ? Number((p.success_rate * 100).toFixed(2)) : null,
}));
return {
type: 'common',
data: [
{ id: 'bars', values: bars },
{ id: 'line', values: line },
],
// 第 7 个颜色给成功率折线,图例色块与线色一致
color: [...colors, readCssVar('--ui-color-success', '#3bb346')],
series: [
{
type: 'bar',
id: 'outcomeBar',
dataIndex: 0,
xField: 'time',
yField: 'value',
seriesField: 'outcome',
stack: true,
},
{
type: 'line',
id: 'rateLine',
dataIndex: 1,
xField: 'time',
yField: 'rate',
seriesField: 'series',
line: {
style: {
stroke: readCssVar('--ui-color-success', '#3bb346'),
lineWidth: 2,
},
},
point: {
style: {
fill: readCssVar('--ui-color-success', '#3bb346'),
size: 4,
},
},
},
],
axes: [
{ orient: 'left', seriesId: ['outcomeBar'], title: { visible: false } },
{
orient: 'right',
seriesId: ['rateLine'],
min: 0,
max: 100,
grid: { visible: false },
label: { formatMethod: (v) => formatPercent(v, 0) },
},
{ orient: 'bottom', type: 'band' },
],
legends: { visible: true, orient: 'top', position: 'start' },
tooltip: {
dimension: {
content: [
{
seriesId: 'outcomeBar',
key: (d) => d?.outcome,
value: (d) => fmtInt(d?.value),
},
{
seriesId: 'rateLine',
key: t('成功率'),
value: (d) => formatPercent(d?.rate, 1),
},
],
},
},
};
// actualTheme:切换亮 / 暗色时重新读取主题色
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [points, t, actualTheme]);
return (
<div className='quality-card'>
<div className='quality-card-head'>
<span className='quality-card-title'>
<Activity size={16} />
{t('调用结局趋势')}
<span className='quality-card-sub'>
<Trans
t={t}
i18nKey='粒度 {{value}} · 点击柱子放大到该时段'
values={{
value:
gran >= 86400
? t('1 天')
: gran >= 3600
? t('1 小时')
: t('5 分钟'),
}}
/>
</span>
</span>
</div>
<div className='quality-card-body' style={{ height: 340 }}>
{loading && !spec ? (
<Skeleton.Image style={{ width: '100%', height: '100%' }} />
) : spec ? (
<VChart
spec={spec}
option={{ mode: 'desktop-browser' }}
onClick={(e) => {
const ts = e?.datum?.ts;
if (ts && onZoom) onZoom(ts, ts + gran);
}}
/>
) : (
<div className='quality-empty'>{t('所选时间范围内暂无调用')}</div>
)}
</div>
</div>
);
};
/** 责任方分布:点击扇区按责任方筛选 */
export const QualityFaultChart = ({
summary,
scope,
loading,
onDrillFault,
t,
}) => {
const actualTheme = useActualTheme();
const fault = summary?.current?.fault || {};
const isOrg = scope === 'org';
// 颜色按责任方固定,不随"哪些类别为 0 被过滤掉"而错位
const faultColor = {
upstream: ['--ui-color-danger', '#f93920'],
platform: ['--ui-color-warning', '#fc8800'],
client: ['--ui-color-primary', '#0064fa'],
quota: ['--ui-color-secondary', '#8b5cf6'],
abort: ['--ui-color-tertiary', '#6b7075'],
};
const data = FAULTS.filter((f) => !(isOrg && f.value === 2))
.map((f) => ({
value: f.value,
key: f.key,
name: t(isOrg ? f.orgLabel : f.label),
count: fault[f.key] || 0,
}))
.filter((d) => d.count > 0);
const spec = useMemo(
() =>
data.length === 0
? null
: {
type: 'pie',
data: [{ id: 'fault', values: data }],
valueField: 'count',
categoryField: 'name',
outerRadius: 0.8,
innerRadius: 0.55,
color: data.map((d) => readCssVar(...faultColor[d.key])),
legends: { visible: true, orient: 'bottom' },
label: { visible: true, formatMethod: (_t, d) => fmtInt(d?.count) },
tooltip: {
mark: {
content: [
{ key: (d) => d?.name, value: (d) => fmtInt(d?.count) },
],
},
},
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[JSON.stringify(data), actualTheme],
);
return (
<div className='quality-card'>
<div className='quality-card-head'>
<span className='quality-card-title'>
<PieChart size={16} />
{t('失败责任方')}
<span className='quality-card-sub'>{t('点击扇区筛选')}</span>
</span>
</div>
<div className='quality-card-body' style={{ height: 340 }}>
{loading && !summary ? (
<Skeleton.Image style={{ width: '100%', height: '100%' }} />
) : spec ? (
<VChart
spec={spec}
option={{ mode: 'desktop-browser' }}
onClick={(e) => {
const v = e?.datum?.value;
if (v && onDrillFault) onDrillFault(String(v));
}}
/>
) : (
<div className='quality-empty'>{t('所选范围内没有失败请求')}</div>
)}
</div>
</div>
);
};