Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
@@ -0,0 +1,646 @@
/*
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 React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Table,
Button,
Select,
Empty,
Spin,
Progress,
Typography,
} from '@douyinfe/semi-ui';
import OrgPanel from './OrgPanel';
import { VChart } from '@visactor/react-vchart';
import { initVChartSemiTheme } from '@visactor/vchart-semi-theme';
import {
RefreshCw,
PieChart,
TrendingUp,
BarChart3,
Crown,
} from 'lucide-react';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import { renderQuota } from '../../../helpers/render';
import { useActualTheme } from '../../../context/Theme';
const { Text } = Typography;
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 上期。增长绿、下降红;无上期数据时灰显。
// 状态色统一走 Semi 语义 token(与页面各处使用进度条同一套红绿,且随明暗主题自适应)。
const DeltaBadge = ({ cur, prev, t }) => {
if (!prev || prev <= 0) {
return <span className='text-xs text-gray-400'>{t('无上期对比')}</span>;
}
const pct = ((cur - prev) / prev) * 100;
const up = pct >= 0;
return (
<span
className='text-xs font-medium'
style={{
color: up ? 'var(--semi-color-success)' : 'var(--semi-color-danger)',
}}
>
{up ? '▲' : '▼'} {Math.abs(pct).toFixed(1)}%
<span className='text-gray-400 ml-1'>{t('较上期')}</span>
</span>
);
};
const KpiCard = ({ label, value, sub }) => (
<div className='px-4 py-3 rounded-xl bg-[var(--semi-color-fill-0)]'>
<div className='text-xs text-gray-500 mb-1'>{label}</div>
<div className='text-lg font-semibold text-gray-900 dark:text-white truncate'>
{value}
</div>
{sub ? <div className='mt-0.5'>{sub}</div> : null}
</div>
);
// 把 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('成员')}#${row.key}`;
} else if (dimension === 'token' && name === `令牌#${row.key}`) {
name = `${t('令牌')}#${row.key}`;
}
return name === row.name ? row : { ...row, name };
});
// 多维用量分析面板(§5.6):经营看板视角——KPI+环比、消耗趋势折线、维度分布柱状、明细表。
// 仅 admin + analytics 特性开启时挂载(前端门控),后端接口仍 admin+feature 鉴权。
const OrgAnalyticsPanel = ({ orgId }) => {
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(() => {
initVChartSemiTheme({ 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 },
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.brand2],
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: 200 },
{
title: t('消耗占比'),
render: (_, r) => {
const pct =
breakdownTotal > 0 ? ((r.quota || 0) / breakdownTotal) * 100 : 0;
return (
<div className='flex items-center gap-2'>
<Progress
percent={Math.round(pct)}
style={{ flex: 1 }}
stroke={brandColors.brand2}
showInfo={false}
/>
<span className='text-xs text-gray-500 whitespace-nowrap'>
{renderQuota(r.quota || 0, 2)} ({pct.toFixed(1)}%)
</span>
</div>
);
},
},
{ title: t('请求数'), dataIndex: 'request_count', width: 100 },
{
title: t('Token (入/出)'),
width: 160,
render: (_, r) =>
`${r.prompt_tokens || 0} / ${r.completion_tokens || 0}`,
},
],
[dimLabel, breakdownTotal, t, brandColors],
);
const rangeOptions = [
{ label: t('近 7 天'), value: 7 },
{ label: t('近 30 天'), value: 30 },
{ label: t('近 90 天'), value: 90 },
];
return (
<div className='space-y-4'>
{/* 控制区 */}
<OrgPanel>
<div className='flex flex-wrap items-center justify-between gap-3'>
<div className='flex items-center gap-2'>
<PieChart size={18} className='text-brand-deep' />
<Text strong>{t('企业用量分析')}</Text>
<Text type='tertiary' size='small'>
{t('趋势 · 结构 · 与消耗明细一致')}
</Text>
</div>
<div className='flex items-center gap-2'>
<Select
value={dimension}
onChange={setDimension}
optionList={dimensions}
style={{ width: 110 }}
/>
<Select
value={rangeDays}
onChange={setRangeDays}
optionList={rangeOptions}
style={{ width: 110 }}
/>
<Button
theme='light'
icon={<RefreshCw size={14} />}
loading={loading}
onClick={() => fetchAll(true)}
>
{t('刷新')}
</Button>
</div>
</div>
{/* KPI + 环比 */}
<div className='grid grid-cols-2 lg:grid-cols-4 gap-4 mt-4'>
<KpiCard
label={t('本期总消耗')}
value={renderQuota(curQuota, 2)}
sub={<DeltaBadge cur={curQuota} prev={prevQuota} t={t} />}
/>
<KpiCard
label={t('本期总请求')}
value={curReq.toLocaleString()}
sub={<DeltaBadge cur={curReq} prev={prevReq} t={t} />}
/>
<KpiCard
label={t('日均消耗')}
value={renderQuota(rangeDays > 0 ? curQuota / rangeDays : 0, 2)}
sub={
<span className='text-xs text-gray-400'>
{t('近 {{n}} 天均值', { n: rangeDays })}
</span>
}
/>
<KpiCard
label={t('消耗最高')}
value={topRow ? topRow.name : '-'}
sub={
topRow ? (
<span className='text-xs text-amber-500 inline-flex items-center gap-1'>
<Crown size={11} /> {renderQuota(topRow.quota || 0, 2)}
</span>
) : (
<span className='text-xs text-gray-400'>
{dimension === 'time' ? t('按时间维度无排名') : '-'}
</span>
)
}
/>
</div>
</OrgPanel>
{/* 消耗趋势折线 */}
<OrgPanel>
<div className='flex items-center justify-between mb-3'>
<div className='flex items-center gap-2'>
<TrendingUp size={16} className='text-brand-deep' />
<Text strong>{t('用量趋势')}</Text>
</div>
<Select
value={trendMetric}
onChange={setTrendMetric}
optionList={[
{ label: t('消耗'), value: 'quota' },
{ label: t('请求数'), value: 'requests' },
]}
style={{ width: 100 }}
size='small'
/>
</div>
{loading ? (
<div className='flex justify-center py-12'>
<Spin size='large' />
</div>
) : trendSpec ? (
<div className='rounded-2xl border border-gray-100/70 dark:border-white/5 bg-white/60 dark:bg-slate-950/25 p-2'>
<VChart
key={`trend-${actualTheme}`}
spec={trendSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: 280 }}
/>
</div>
) : (
<Empty
description={t('该时间范围暂无用量数据')}
style={{ padding: 40 }}
/>
)}
</OrgPanel>
{/* 维度分布柱状(time 维度不展示,趋势图已覆盖) */}
{dimension !== 'time' && (
<OrgPanel>
<div className='flex items-center gap-2 mb-3'>
<BarChart3 size={16} className='text-brand-deep' />
<Text strong>{t('{{dim}}消耗分布', { dim: dimLabel })}</Text>
<Text type='tertiary' size='small'>
{t('Top 10')}
</Text>
</div>
{loading ? (
<div className='flex justify-center py-12'>
<Spin size='large' />
</div>
) : barSpec ? (
<div className='rounded-2xl border border-gray-100/70 dark:border-white/5 bg-white/60 dark:bg-slate-950/25 p-2'>
<VChart
key={`bar-${actualTheme}`}
spec={barSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: Math.max(220, barData.length * 34 + 60) }}
/>
</div>
) : (
<Empty
description={t('该时间范围暂无用量数据')}
style={{ padding: 40 }}
/>
)}
</OrgPanel>
)}
{/* 明细表 */}
<OrgPanel>
<div className='flex items-center gap-2 mb-3'>
<Text strong>{t('{{dim}}明细', { dim: dimLabel })}</Text>
</div>
{loading ? (
<div className='flex justify-center py-12'>
<Spin size='large' />
</div>
) : breakdownRows.length === 0 ? (
<Empty
description={t('该时间范围暂无用量数据')}
style={{ padding: 40 }}
/>
) : (
<Table
columns={columns}
dataSource={breakdownRows}
rowKey='key'
pagination={
breakdownRows.length > 20
? { pageSize: 20, showSizeChanger: false }
: false
}
/>
)}
</OrgPanel>
</div>
);
};
export default OrgAnalyticsPanel;