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

688 lines
22 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 { formatIdReference, formatPercent } from '../../../helpers/safeDisplay';
import { RefreshCw as ActionRefreshCw } from '@/components/common/icons/ActionIcons';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Button as AntButton,
Card as AntCard,
Segmented,
Select as AntSelect,
Tabs as AntTabs,
Tag as AntTag,
} from 'antd';
import { Table, Empty, Spin, Progress } from '@/components/ui';
import '../../../styles/org-center.css';
import { VChart } from '@visactor/react-vchart';
import { initVChartTheme } from '@/components/ui/chartTheme';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import { renderQuota } from '../../../helpers/render';
import { useActualTheme } from '../../../context/Theme';
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
/* 系列色运行时读取品牌 token(--brand-*),随主题预设整套切换。
* 不再硬编码(旧值 #14b8a6 在 azure 等预设下与全站主色打架)。 */
const readBrandColors = () => {
if (typeof window === 'undefined') {
return { brand: '#1668dc', brand2: '#13c2c2' };
}
const style = getComputedStyle(document.documentElement);
return {
brand: style.getPropertyValue('--brand-primary').trim() || '#1668dc',
brand2: style.getPropertyValue('--accent-teal').trim() || '#13c2c2',
};
};
const getChartTokens = (isDark) => ({
axisLabel: isDark ? '#94a3b8' : '#64748b',
axisLine: isDark ? 'rgba(148, 163, 184, 0.28)' : '#e5e7eb',
grid: isDark ? 'rgba(148, 163, 184, 0.14)' : '#edf2f7',
tooltipBg: isDark ? 'rgba(15, 23, 42, 0.96)' : 'rgba(255, 255, 255, 0.98)',
tooltipBorder: isDark ? 'rgba(148, 163, 184, 0.22)' : '#e5e7eb',
tooltipText: isDark ? '#e2e8f0' : '#0f172a',
tooltipMuted: isDark ? '#94a3b8' : '#64748b',
});
const chartTooltipStyle = (tokens) => ({
panel: {
backgroundColor: tokens.tooltipBg,
borderColor: tokens.tooltipBorder,
shadowBlur: 18,
shadowColor: 'rgba(15, 23, 42, 0.25)',
},
titleLabel: { fontColor: tokens.tooltipText },
keyLabel: { fontColor: tokens.tooltipMuted },
valueLabel: { fontColor: tokens.tooltipText },
});
const chartAxisLine = (tokens) => ({
visible: true,
style: { stroke: tokens.axisLine },
});
const chartTick = (tokens) => ({
visible: true,
style: { stroke: tokens.axisLine },
});
const chartGrid = (tokens) => ({
visible: true,
style: { stroke: tokens.grid, lineDash: [4, 4] },
});
// 环比徽标:本期 vs 上期。增长绿、下降红;无上期数据时灰显(语义色沿用原实现)。
const DeltaBadge = ({ cur, prev, t }) => {
if (!prev || prev <= 0) {
return <small>{t('无上期对比')}</small>;
}
const pct = Number.isFinite(Number(cur))
? ((Number(cur) - Number(prev)) / Number(prev)) * 100
: null;
const up = pct !== null && pct >= 0;
return (
<small className={up ? 'is-up' : 'is-down'}>
{pct === null
? '-'
: `${up ? '↑' : '↓'} ${formatPercent(Math.abs(pct), 1)}`}
<em>{t('较上期')}</em>
</small>
);
};
// 把 time 维度的小时行聚合成趋势序列:>7 天按天汇总,否则按小时。
const buildTrend = (rows, rangeDays, field) => {
if (!rows || rows.length === 0) return [];
if (rangeDays > 7) {
const map = new Map();
rows.forEach((r) => {
const day = (r.name || '').slice(0, 10);
if (!day) return;
map.set(day, (map.get(day) || 0) + (r[field] || 0));
});
return Array.from(map, ([date, value]) => ({ date, value })).sort((a, b) =>
a.date < b.date ? -1 : 1,
);
}
return rows
.map((r) => ({ date: r.name || String(r.key), value: r[field] || 0 }))
.sort((a, b) => (a.date < b.date ? -1 : 1));
};
const sumField = (rows, field) =>
(rows || []).reduce((s, r) => s + (r[field] || 0), 0);
const localizeAnalyticsRows = (rows, dimension, t) =>
(rows || []).map((row) => {
let name = row.name;
if (row.key === '0') {
const zeroName = {
department: t('未分配部门'),
project: t('未绑定项目'),
member: t('未归属成员'),
token: t('未绑定密钥'),
}[dimension];
if (zeroName) name = zeroName;
} else if (dimension === 'member' && name === `成员#${row.key}`) {
name = `${t('成员')}${formatIdReference(row.key, t('未知成员'))}`;
} else if (dimension === 'token' && name === `\u4ee4\u724c#${row.key}`) {
name = `${t('密钥')}${formatIdReference(row.key, t('未知密钥'))}`;
}
return name === row.name ? row : { ...row, name };
});
// 多维用量分析面板(§5.6):经营看板视角——KPI+环比、消耗趋势折线、维度分布柱状、明细表。
// 仅 admin + analytics 特性开启时挂载(前端门控),后端接口仍 admin+feature 鉴权。
// memberUsage:数据看板传入的“成员用量明细”卡,作为明细页签之一(原型 .ea-detail-tabs);
// detailTab / onDetailTabChange:明细页签受控(数据看板“成员用量”按钮切换并定位)。
const OrgAnalyticsPanel = ({
orgId,
memberUsage = null,
detailTab,
onDetailTabChange,
detailsRef,
}) => {
const { t } = useTranslation();
const actualTheme = useActualTheme();
const isDarkMode = actualTheme === 'dark';
const chartTokens = useMemo(() => getChartTokens(isDarkMode), [isDarkMode]);
// 系列色跟随品牌 token:明暗切换(isDarkMode)与预设注入(theme-tokens-applied 事件)都会刷新
const [brandColors, setBrandColors] = useState(readBrandColors);
useEffect(() => {
const refresh = () => setBrandColors(readBrandColors());
refresh();
window.addEventListener('theme-tokens-applied', refresh);
return () => window.removeEventListener('theme-tokens-applied', refresh);
}, [isDarkMode]);
const [dimension, setDimension] = useState('model');
const [rangeDays, setRangeDays] = useState(7);
const [trendMetric, setTrendMetric] = useState('quota');
const [breakdownRows, setBreakdownRows] = useState([]);
const [trendRows, setTrendRows] = useState([]);
const [prevRows, setPrevRows] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
initVChartTheme({ isWatchingThemeSwitch: true });
}, []);
const dimensions = useMemo(
() => [
{ label: t('模型'), value: 'model' },
{ label: t('项目'), value: 'project' },
{ label: t('部门'), value: 'department' },
{ label: t('成员'), value: 'member' },
{ label: t('密钥'), value: 'token' },
{ label: t('时间'), value: 'time' },
],
[t],
);
const dimLabel =
dimensions.find((d) => d.value === dimension)?.label || t('维度');
const fetchAll = useCallback(
async (fresh = false) => {
if (!orgId) return;
setLoading(true);
try {
// 按分钟归一化时间窗,保证 30s 缓存可命中,同时只遗漏当前未完成分钟。
const end = Math.floor(Date.now() / 60000) * 60;
const span = rangeDays * 86400;
const start = end - span;
const prevStart = start - span;
// 仅「刷新」按钮 fresh=true 时带 nocache 拿最新;维度/时间切换走 30s 缓存。
const nc = fresh ? '&nocache=1' : '';
const get = (dim, s, e) =>
API.get(
`/api/org/analytics?dimension=${dim}&start=${s}&end=${e}${nc}`,
{
headers: getOrgHeaders(orgId),
},
).then((r) => {
// 后端以 HTTP 200 返回 success:false(如特性关闭/越权)时,抛错让 catch 提示,
// 而非静默展示空图表,避免误以为「无数据」。
if (r.data && r.data.success === false) {
throw new Error(r.data.message || t('加载用量分析失败'));
}
return r.data?.data?.rows || [];
});
const reqs = [get('time', start, end), get('time', prevStart, start)];
if (dimension !== 'time') reqs.push(get(dimension, start, end));
const [timeRows, prevTimeRows, breakdown] = await Promise.all(reqs);
const localizedTimeRows = localizeAnalyticsRows(timeRows, 'time', t);
setTrendRows(localizedTimeRows);
setPrevRows(localizeAnalyticsRows(prevTimeRows, 'time', t));
setBreakdownRows(
dimension === 'time'
? localizedTimeRows
: localizeAnalyticsRows(breakdown || [], dimension, t),
);
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
},
[orgId, dimension, rangeDays, t],
);
useEffect(() => {
fetchAll(false);
}, [fetchAll]);
// KPI:本期/上期总量 + 环比;日均;Top1 消耗对象
const curQuota = useMemo(() => sumField(trendRows, 'quota'), [trendRows]);
const curReq = useMemo(
() => sumField(trendRows, 'request_count'),
[trendRows],
);
const prevQuota = useMemo(() => sumField(prevRows, 'quota'), [prevRows]);
const prevReq = useMemo(
() => sumField(prevRows, 'request_count'),
[prevRows],
);
const topRow = useMemo(() => {
if (dimension === 'time') return null;
return (
[...breakdownRows].sort((a, b) => (b.quota || 0) - (a.quota || 0))[0] ||
null
);
}, [breakdownRows, dimension]);
// 趋势折线 spec
const trendData = useMemo(
() =>
buildTrend(
trendRows,
rangeDays,
trendMetric === 'requests' ? 'request_count' : 'quota',
),
[trendRows, rangeDays, trendMetric],
);
const isMoney = trendMetric === 'quota';
const trendSpec = useMemo(() => {
if (!trendData.length) return null;
return {
type: 'area',
background: 'transparent',
data: [{ id: 'trend', values: trendData }],
xField: 'date',
yField: 'value',
point: {
visible: trendData.length <= 60,
size: 3,
style: { fill: brandColors.brand },
},
line: { style: { lineWidth: 2, stroke: brandColors.brand } },
area: {
style: {
fill: {
gradient: 'linear',
x0: 0,
y0: 0,
x1: 0,
y1: 1,
stops: [
{ offset: 0, color: brandColors.brand, opacity: 0.35 },
{ offset: 1, color: brandColors.brand, opacity: 0.02 },
],
},
},
},
tooltip: {
visible: true,
style: chartTooltipStyle(chartTokens),
dimension: {
visible: true,
content: [
{
key: () => (isMoney ? t('消耗') : t('请求数')),
value: (datum) =>
isMoney
? renderQuota(datum?.value || 0, 2)
: `${(datum?.value || 0).toLocaleString()} ${t('次')}`,
},
],
},
},
crosshair: {
xField: {
visible: true,
line: { visible: true, style: { stroke: chartTokens.axisLine } },
},
},
axes: [
{
orient: 'bottom',
label: { style: { angle: -45, fill: chartTokens.axisLabel } },
domainLine: chartAxisLine(chartTokens),
tick: chartTick(chartTokens),
},
{
orient: 'left',
grid: chartGrid(chartTokens),
domainLine: chartAxisLine(chartTokens),
tick: chartTick(chartTokens),
label: {
style: { fill: chartTokens.axisLabel },
formatMethod: (v) => (isMoney ? renderQuota(v, 0) : Math.round(v)),
},
},
],
};
}, [trendData, isMoney, t, chartTokens, brandColors]);
// 维度分布柱状 spec(Top 10,横向)
const barData = useMemo(() => {
if (dimension === 'time') return [];
return [...breakdownRows]
.sort((a, b) => (b.quota || 0) - (a.quota || 0))
.slice(0, 10)
.map((r) => ({ name: r.name || '-', value: r.quota || 0 }));
}, [breakdownRows, dimension]);
const barSpec = useMemo(() => {
if (!barData.length) return null;
return {
type: 'bar',
background: 'transparent',
data: [{ id: 'bar', values: barData }],
direction: 'horizontal',
xField: 'value',
yField: 'name',
color: [brandColors.brand],
barMaxWidth: 22,
label: {
visible: true,
position: 'right',
style: { fill: chartTokens.axisLabel },
formatMethod: (text, datum) =>
renderQuota(
datum && datum.value != null ? datum.value : Number(text) || 0,
2,
),
},
tooltip: {
visible: true,
style: chartTooltipStyle(chartTokens),
mark: {
content: [
{
key: (datum) => datum?.name,
value: (datum) => renderQuota(datum?.value || 0, 2),
},
],
},
},
axes: [
{
orient: 'left',
label: { style: { fill: chartTokens.axisLabel } },
domainLine: chartAxisLine(chartTokens),
tick: chartTick(chartTokens),
},
{
orient: 'bottom',
grid: chartGrid(chartTokens),
domainLine: chartAxisLine(chartTokens),
tick: chartTick(chartTokens),
label: {
style: { fill: chartTokens.axisLabel },
formatMethod: (v) => renderQuota(v, 0),
},
},
],
};
}, [barData, chartTokens, brandColors]);
// 明细表:占比分母用「当前维度行的合计」而非时间维度总量,
// 保证表内各行占比之和恒为 100%(两者数学上应相等,但用自身合计更稳健)。
const breakdownTotal = useMemo(
() => sumField(breakdownRows, 'quota'),
[breakdownRows],
);
const columns = useMemo(
() => [
{
title: dimLabel,
dataIndex: 'name',
width: 228,
render: (v) => <span className='oc-ea-model-name'>{v}</span>,
},
{
title: t('消费占比'),
width: 300,
render: (_, r) => {
const pct =
breakdownTotal > 0
? ((Number(r.quota) || 0) / breakdownTotal) * 100
: null;
return (
<div className='oc-ea-cost-share'>
<div>
<strong>{renderQuota(r.quota || 0, 2)}</strong>
<span>{formatPercent(pct, 1)}</span>
</div>
<Progress
percent={Math.round(pct)}
size='small'
stroke={brandColors.brand}
showInfo={false}
/>
</div>
);
},
},
{
title: t('请求数'),
dataIndex: 'request_count',
width: 110,
align: 'right',
render: (v) => Number(v || 0).toLocaleString(),
},
{
title: t('Token(入 / 出)'),
width: 240,
align: 'right',
render: (_, r) => (
<span className='oc-ea-token-pair'>
{Number(r.prompt_tokens || 0).toLocaleString()}
<small> / </small>
{Number(r.completion_tokens || 0).toLocaleString()}
</span>
),
},
],
[dimLabel, breakdownTotal, t, brandColors],
);
const rangeOptions = [
{ label: t('近 7 天'), value: 7 },
{ label: t('近 30 天'), value: 30 },
{ label: t('近 90 天'), value: 90 },
];
const [innerTab, setInnerTab] = useState('models');
const activeDetail = detailTab ?? innerTab;
const changeDetail = (key) => {
setInnerTab(key);
onDetailTabChange?.(key);
};
const detailCard = (
<AntCard className='oc-ea-detail-card'>
<div className='oc-ea-table-toolbar'>
<h2>{t('{{dim}}明细', { dim: dimLabel })}</h2>
</div>
{loading ? (
<div className='oc-ea-loading'>
<Spin size='large' />
</div>
) : breakdownRows.length === 0 ? (
<Empty
description={t('该时间范围暂无用量数据')}
style={{ padding: 40 }}
/>
) : (
<Table
columns={columns}
dataSource={breakdownRows}
rowKey='key'
scroll={{ x: 880 }}
pagination={{ resetOnDataChange: true }}
/>
)}
</AntCard>
);
return (
<>
{/* 多维用量分析(原型 .ea-analysis):标题 + 维度 / 时间 / 刷新 */}
<section className='oc-ea-analysis'>
<div className='oc-ea-analysis-heading'>
<div>
<h2>{t('多维用量分析')}</h2>
<p>{t('趋势、结构与调用明细')}</p>
</div>
<div className='oc-ea-filters'>
<AntSelect
className='oc-ea-dimension-select'
aria-label={t('维度')}
value={dimension}
onChange={setDimension}
options={dimensions}
/>
<AntSelect
className='oc-ea-range-select'
aria-label={t('时间范围')}
value={rangeDays}
onChange={setRangeDays}
options={rangeOptions}
/>
<AntButton
className='oc-ea-refresh'
aria-label={t('刷新分析')}
icon={<ActionRefreshCw size={16} />}
loading={loading}
onClick={() => fetchAll(true)}
/>
</div>
</div>
{/* 汇总指标(原型 .ea-summary) */}
<div className='oc-ea-summary'>
<div>
<span>{t('本期总消费')}</span>
<strong>{renderQuota(curQuota, 2)}</strong>
<DeltaBadge cur={curQuota} prev={prevQuota} t={t} />
</div>
<div>
<span>{t('本期总请求')}</span>
<strong>{curReq.toLocaleString()}</strong>
<DeltaBadge cur={curReq} prev={prevReq} t={t} />
</div>
<div>
<span>{t('日均消费')}</span>
<strong>
{renderQuota(rangeDays > 0 ? curQuota / rangeDays : 0, 2)}
</strong>
<small>{t('近 {{n}} 天均值', { n: rangeDays })}</small>
</div>
<div>
<span>{t('消费最高')}</span>
<strong className='oc-ea-top'>{topRow ? topRow.name : '-'}</strong>
<small>
{topRow
? renderQuota(topRow.quota || 0, 2)
: dimension === 'time'
? t('按时间维度无排名')
: '-'}
</small>
</div>
</div>
<div
className={`oc-ea-charts${dimension === 'time' ? ' is-single' : ''}`}
>
{/* 用量趋势 */}
<AntCard className='oc-ea-trend'>
<div className='oc-ea-panel-heading'>
<div>
<h2>{t('用量趋势')}</h2>
<span>
{rangeDays > 7
? t('按天查看企业调用消耗')
: t('逐小时查看企业调用消耗')}
</span>
</div>
<Segmented
size='small'
value={trendMetric}
onChange={setTrendMetric}
options={[
{ label: t('消费'), value: 'quota' },
{ label: t('请求数'), value: 'requests' },
]}
/>
</div>
{loading ? (
<div className='oc-ea-loading'>
<Spin size='large' />
</div>
) : trendSpec ? (
<VChart
key={`trend-${actualTheme}`}
spec={trendSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: 306 }}
/>
) : (
<Empty
description={t('该时间范围暂无用量数据')}
style={{ padding: 40 }}
/>
)}
</AntCard>
{/* 维度分布柱状(time 维度不展示,趋势图已覆盖) */}
{dimension !== 'time' && (
<AntCard className='oc-ea-rank'>
<div className='oc-ea-panel-heading'>
<div>
<h2>{t('{{dim}}消费分布', { dim: dimLabel })}</h2>
<span>{t('Top 10')}</span>
</div>
<AntTag variant='filled'>{t('按消费排序')}</AntTag>
</div>
{loading ? (
<div className='oc-ea-loading'>
<Spin size='large' />
</div>
) : barSpec ? (
<VChart
key={`bar-${actualTheme}`}
spec={barSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: Math.max(306, barData.length * 34 + 60) }}
/>
) : (
<Empty
description={t('该时间范围暂无用量数据')}
style={{ padding: 40 }}
/>
)}
</AntCard>
)}
</div>
</section>
{/* 明细(原型 .ea-details:维度明细 / 成员用量 页签) */}
<section className='oc-ea-details' ref={detailsRef}>
<AntTabs
className='oc-ea-detail-tabs'
activeKey={memberUsage ? activeDetail : 'models'}
onChange={changeDetail}
items={[
{
key: 'models',
label: t('{{dim}}明细', { dim: dimLabel }),
children: detailCard,
},
...(memberUsage
? [
{
key: 'members',
label: t('成员用量'),
forceRender: true,
children: memberUsage,
},
]
: []),
]}
/>
</section>
</>
);
};
export default OrgAnalyticsPanel;