Files
monkey-ai-web/src/hooks/dashboard/useDashboardCharts.jsx
T
qiubaishen 61294dc597 merge: 合入总仓库 weiyuan(bfdfb339) web/ 新功能,保留 ui-optimization 的 UI 重构
来源:luoguang/monkey-ai weiyuan@bfdfb339 的 web/(经 sync/main-weiyuan-web-bfdfb339 同步)
同步基准:总仓库 a2ca13cb = 本仓库初始导入 d8f3aee2

冲突处理原则:保留 ui-optimization 的 UI(样式/结构/组件),嫁接 weiyuan 的功能逻辑。
- i18n:按键三方合并;ours 的「令牌→密钥」改名键上移植 theirs 的术语修订
- task-logs / OrgLogs:ours 已手工移植同一功能(6ad95e2),保留 ours
- 删除:OrgCreate(theirs 下线 /org/create)、旧 image 组件与 VideoRegenerateModal(theirs 体验中心重写)、
  OrgAvatarSection / PricingBentoPage / CommissionConsole(ours 重构中已移除)
- 测试:users-pagination 的 i18next mock 补 t();theirs 新增文件补 license header
2026-11-10 12:01:21 +08:00

907 lines
20 KiB
React

/*
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 { useState, useCallback, useEffect } from 'react';
import { initVChartTheme } from '@/components/ui/chartTheme';
import {
modelColorMap,
renderNumber,
renderQuota,
modelToColor,
getQuotaWithUnit,
} from '../../helpers';
import {
processRawData,
calculateTrendData,
aggregateDataByTimeAndModel,
generateChartTimePoints,
updateChartSpec,
updateMapValue,
initializeMaps,
} from '../../helpers/dashboard';
export const useDashboardCharts = (
dataExportDefaultTime,
setTrendData,
setConsumeQuota,
setTimes,
setConsumeTokens,
setPieData,
setLineData,
setModelColors,
t,
) => {
// ========== 图表规格状态 ==========
// 模型调用排行 - 水平柱状榜单(取代原 donut 饼图)
const [spec_pie, setSpecPie] = useState({
type: 'bar',
data: [
{
id: 'id0',
values: [],
},
],
xField: 'value',
yField: 'type',
seriesField: 'type',
direction: 'horizontal',
title: {
visible: true,
text: t('模型调用排行'),
subtext: t('总计:{{value}}', { value: renderNumber(0) }),
textStyle: {
fontSize: 14,
fontWeight: 600,
},
subtextStyle: {
fontSize: 11,
fontWeight: 400,
fill: '#888',
},
},
bar: {
style: {
cornerRadius: [0, 8, 8, 0],
fillOpacity: 0.9,
},
state: {
hover: {
fillOpacity: 1,
shadowBlur: 12,
shadowColor: 'rgba(0, 0, 0, 0.18)',
shadowOffsetX: 2,
shadowOffsetY: 0,
},
selected: {
fillOpacity: 1,
},
},
},
label: {
visible: true,
position: 'right',
style: {
fontSize: 11,
fontWeight: 600,
fill: '#666',
},
formatMethod: (text, datum) => renderNumber(datum?.value || 0),
},
axes: [
{
orient: 'left',
label: {
style: {
fontSize: 11,
fontWeight: 500,
fill: '#888',
},
},
tick: { visible: false },
domainLine: { visible: false },
},
{
orient: 'bottom',
visible: false,
},
],
legends: { visible: false },
tooltip: {
mark: {
title: {
visible: true,
value: (datum) => String(datum['type'] || ''),
},
content: [
{
key: (datum) => String(datum['type'] || ''),
value: (datum) => renderNumber(datum['value'] || 0),
},
],
},
style: {
panel: {
shadow: {
blur: 12,
color: 'rgba(0, 0, 0, 0.12)',
},
},
},
},
color: [
'#6366f1', // 靛蓝
'#8b5cf6', // 紫色
'#ec4899', // 粉色
'#f43f5e', // 玫瑰色
'#f97316', // 橙色
'#eab308', // 黄色
'#22c55e', // 绿色
'#14b8a6', // 青色
'#06b6d4', // 天蓝
'#3b82f6', // 蓝色
],
animation: true,
animationAppear: {
bar: {
duration: 700,
easing: 'cubicOut',
oneByOne: 30,
},
},
});
// 消费时段走势 - 堆叠面积图(取代原堆叠柱图)
const [spec_line, setSpecLine] = useState({
type: 'area',
data: [
{
id: 'barData',
values: [],
},
],
xField: 'Time',
yField: 'Usage',
seriesField: 'Model',
stack: true,
legends: {
visible: true,
selectMode: 'single',
orient: 'right',
position: 'middle',
padding: { left: 16 },
item: {
shape: {
style: {
symbolType: 'circle',
size: 8,
},
},
label: {
style: {
fontSize: 11,
fontWeight: 500,
},
},
},
},
title: {
visible: true,
text: t('消费时段走势'),
subtext: t('总计:{{value}}', { value: renderQuota(0, 2) }),
textStyle: {
fontSize: 14,
fontWeight: 600,
},
subtextStyle: {
fontSize: 11,
fontWeight: 400,
fill: '#888',
},
},
area: {
style: {
fillOpacity: 0.55,
curveType: 'monotone',
},
state: {
hover: {
fillOpacity: 0.85,
},
selected: {
fillOpacity: 0.95,
},
},
},
line: {
style: {
lineWidth: 2,
lineCap: 'round',
lineJoin: 'round',
curveType: 'monotone',
},
state: {
hover: {
lineWidth: 3,
},
},
},
// 平时隐藏数据点;保留 hover state 以便 VChart 在悬停时显示 symbol
point: {
visible: false,
},
axes: [
{
orient: 'bottom',
label: {
style: {
fontSize: 10,
fill: '#888',
},
},
tick: {
visible: false,
},
domainLine: {
visible: true,
style: {
stroke: '#e5e7eb',
lineWidth: 1,
},
},
grid: {
visible: false,
},
},
{
orient: 'left',
label: {
style: {
fontSize: 10,
fill: '#888',
},
},
tick: {
visible: false,
},
domainLine: {
visible: false,
},
grid: {
visible: true,
style: {
stroke: '#f0f0f0',
lineDash: [4, 4],
},
},
},
],
tooltip: {
mark: {
title: {
visible: true,
value: (datum) => String(datum['Model'] || ''),
style: {
fontWeight: 600,
},
},
content: [
{
key: (datum) => String(datum['Model'] || ''),
value: (datum) => renderQuota(datum['rawQuota'] || 0, 4),
},
],
},
dimension: {
content: [
{
key: (datum) => String(datum['Model'] || ''),
value: (datum) => datum['rawQuota'] || 0,
},
],
updateContent: (array) => {
array.sort((a, b) => b.value - a.value);
let sum = 0;
for (let i = 0; i < array.length; i++) {
// 注意:这里曾经有一条 `key == '其他' 就 continue` 的历史分支。
// dimension.content 的 value 取的是裸数字(rawQuota),格式化只发生在本循环里,
// 跳过就等于把该行渲染成未格式化的浮点数。移动端把长尾模型合并成「其他」系列后
// 这条分支会被真实命中(中文下 t('其他') 就是字面量 '其他'),故移除。
let value = parseFloat(array[i].value);
if (isNaN(value)) {
value = 0;
}
if (array[i].datum && array[i].datum.TimeSum) {
sum = array[i].datum.TimeSum;
}
array[i].value = renderQuota(value, 4);
}
array.unshift({
key: t('总计'),
value: renderQuota(sum, 4),
});
return array;
},
},
style: {
panel: {
shadow: {
blur: 12,
color: 'rgba(0, 0, 0, 0.12)',
},
},
},
},
// 使用更丰富的渐变调色板
color: [
'#6366f1', // 靛蓝
'#8b5cf6', // 紫色
'#ec4899', // 粉色
'#f43f5e', // 玫瑰色
'#f97316', // 橙色
'#eab308', // 黄色
'#22c55e', // 绿色
'#14b8a6', // 青色
'#06b6d4', // 天蓝
'#3b82f6', // 蓝色
'#a855f7', // 淡紫
'#d946ef', // 洋红
'#10b981', // 翠绿
'#84cc16', // 草绿
'#f59e0b', // 琥珀
'#ef4444', // 红色
],
// 动画配置
animation: true,
animationAppear: {
area: {
duration: 800,
easing: 'cubicOut',
},
line: {
duration: 800,
easing: 'cubicOut',
},
},
animationUpdate: {
area: {
duration: 400,
easing: 'linear',
},
line: {
duration: 400,
easing: 'linear',
},
},
});
// 模型消耗趋势折线图(已弃用,保留以兼容旧导出,UI 不再渲染)
const [spec_model_line, setSpecModelLine] = useState({
type: 'line',
data: [
{
id: 'lineData',
values: [],
},
],
xField: 'Time',
yField: 'Count',
seriesField: 'Model',
legends: {
visible: true,
selectMode: 'single',
orient: 'right',
position: 'middle',
padding: { left: 16 },
item: {
shape: {
style: {
symbolType: 'circle',
size: 10,
},
},
label: {
style: {
fontSize: 11,
fontWeight: 500,
},
},
},
},
title: {
visible: true,
text: t('模型消耗趋势'),
subtext: '',
textStyle: {
fontSize: 16,
fontWeight: 600,
},
subtextStyle: {
fontSize: 12,
fontWeight: 400,
fill: '#888',
},
},
line: {
style: {
lineWidth: 2.5,
lineCap: 'round',
lineJoin: 'round',
},
state: {
hover: {
lineWidth: 4,
},
},
},
point: {
visible: true,
style: {
size: 6,
fill: '#fff',
lineWidth: 2,
},
state: {
hover: {
size: 10,
lineWidth: 3,
},
},
},
axes: [
{
orient: 'bottom',
label: {
style: {
fontSize: 10,
fill: '#888',
},
},
tick: {
visible: false,
},
domainLine: {
visible: true,
style: {
stroke: '#e5e7eb',
lineWidth: 1,
},
},
grid: {
visible: false,
},
},
{
orient: 'left',
label: {
style: {
fontSize: 10,
fill: '#888',
},
},
tick: {
visible: false,
},
domainLine: {
visible: false,
},
grid: {
visible: true,
style: {
stroke: '#f0f0f0',
lineDash: [4, 4],
},
},
},
],
tooltip: {
mark: {
title: {
visible: true,
value: (datum) => String(datum['Model'] || ''),
},
content: [
{
key: (datum) => String(datum['Model'] || ''),
value: (datum) => renderNumber(datum['Count'] || 0),
},
],
},
style: {
panel: {
shadow: {
blur: 12,
color: 'rgba(0, 0, 0, 0.12)',
},
},
},
},
// 使用渐变色调色板
color: [
'#6366f1', // 靛蓝
'#8b5cf6', // 紫色
'#ec4899', // 粉色
'#f43f5e', // 玫瑰色
'#f97316', // 橙色
'#22c55e', // 绿色
'#06b6d4', // 天蓝
'#3b82f6', // 蓝色
],
// 动画配置
animation: true,
animationAppear: {
line: {
duration: 1000,
easing: 'cubicOut',
type: 'clipIn',
},
point: {
duration: 600,
easing: 'cubicOut',
delay: 400,
},
},
});
// 模型调用次数排行柱状图
const [spec_rank_bar, setSpecRankBar] = useState({
type: 'bar',
data: [
{
id: 'rankData',
values: [],
},
],
xField: 'Count',
yField: 'Model',
seriesField: 'Model',
direction: 'horizontal',
legends: {
visible: false,
},
title: {
visible: true,
text: t('模型调用次数排行'),
subtext: '',
textStyle: {
fontSize: 16,
fontWeight: 600,
},
subtextStyle: {
fontSize: 12,
fontWeight: 400,
fill: '#888',
},
},
bar: {
style: {
cornerRadius: [0, 6, 6, 0],
fillOpacity: 0.85,
},
state: {
hover: {
fillOpacity: 1,
stroke: 'rgba(255, 255, 255, 0.9)',
lineWidth: 2,
shadowBlur: 10,
shadowColor: 'rgba(0, 0, 0, 0.2)',
shadowOffsetX: 2,
shadowOffsetY: 2,
},
},
},
axes: [
{
orient: 'left',
type: 'band',
label: {
style: {
fontSize: 11,
fontWeight: 500,
fill: '#555',
},
},
tick: {
visible: false,
},
domainLine: {
visible: false,
},
grid: {
visible: false,
},
},
{
orient: 'bottom',
label: {
style: {
fontSize: 10,
fill: '#888',
},
},
tick: {
visible: false,
},
domainLine: {
visible: true,
style: {
stroke: '#e5e7eb',
lineWidth: 1,
},
},
grid: {
visible: true,
style: {
stroke: '#f5f5f5',
lineDash: [4, 4],
},
},
},
],
label: {
visible: true,
position: 'outside-right',
style: {
fontSize: 11,
fontWeight: 600,
fill: '#333',
},
formatter: (datum) => renderNumber(datum['Count'] || 0),
},
tooltip: {
mark: {
title: {
visible: true,
value: (datum) => String(datum['Model'] || ''),
},
content: [
{
key: (datum) => String(datum['Model'] || ''),
value: (datum) => renderNumber(datum['Count'] || 0),
},
],
},
style: {
panel: {
shadow: {
blur: 12,
color: 'rgba(0, 0, 0, 0.12)',
},
},
},
},
// 使用渐变色调色板
color: [
'#6366f1', // 靛蓝
'#8b5cf6', // 紫色
'#ec4899', // 粉色
'#f43f5e', // 玫瑰色
'#f97316', // 橙色
'#eab308', // 黄色
'#22c55e', // 绿色
'#14b8a6', // 青色
'#06b6d4', // 天蓝
'#3b82f6', // 蓝色
'#a855f7', // 淡紫
'#d946ef', // 洋红
],
// 动画配置
animation: true,
animationAppear: {
bar: {
duration: 600,
easing: 'cubicOut',
type: 'growWidthIn',
},
},
});
// ========== 数据处理函数 ==========
const generateModelColors = useCallback((uniqueModels, modelColors) => {
const newModelColors = {};
Array.from(uniqueModels).forEach((modelName) => {
if (!modelName) return; // 跳过 undefined/null
newModelColors[modelName] =
modelColorMap[modelName] ||
modelColors[modelName] ||
modelToColor(modelName);
});
return newModelColors;
}, []);
const updateChartData = useCallback(
(data) => {
const processedData = processRawData(
data,
dataExportDefaultTime,
initializeMaps,
updateMapValue,
);
const {
totalQuota,
totalTimes,
totalTokens,
uniqueModels,
timePoints,
timeQuotaMap,
timeTokensMap,
timeCountMap,
} = processedData;
const trendDataResult = calculateTrendData(
timePoints,
timeQuotaMap,
timeTokensMap,
timeCountMap,
dataExportDefaultTime,
);
setTrendData(trendDataResult);
const newModelColors = generateModelColors(uniqueModels, {});
setModelColors(newModelColors);
const aggregatedData = aggregateDataByTimeAndModel(
data,
dataExportDefaultTime,
);
const modelTotals = new Map();
for (let [_, value] of aggregatedData) {
updateMapValue(modelTotals, value.model, value.count);
}
const newPieData = Array.from(modelTotals)
.filter(([model]) => model) // 过滤掉 undefined/null
.map(([model, count]) => ({
type: String(model),
value: count,
}))
.sort((a, b) => b.value - a.value);
const chartTimePoints = generateChartTimePoints(
aggregatedData,
data,
dataExportDefaultTime,
);
let newLineData = [];
chartTimePoints.forEach((time) => {
let timeData = Array.from(uniqueModels)
.filter((model) => model) // 过滤掉 undefined/null
.map((model) => {
const key = `${time}-${model}`;
const aggregated = aggregatedData.get(key);
return {
Time: time,
Model: String(model),
rawQuota: aggregated?.quota || 0,
Usage: aggregated?.quota
? getQuotaWithUnit(aggregated.quota, 4)
: 0,
};
});
const timeSum = timeData.reduce((sum, item) => sum + item.rawQuota, 0);
timeData.sort((a, b) => b.rawQuota - a.rawQuota);
timeData = timeData.map((item) => ({ ...item, TimeSum: timeSum }));
newLineData.push(...timeData);
});
newLineData.sort((a, b) => a.Time.localeCompare(b.Time));
updateChartSpec(
setSpecPie,
newPieData,
t('总计:{{value}}', { value: renderNumber(totalTimes) }),
newModelColors,
'id0',
);
updateChartSpec(
setSpecLine,
newLineData,
t('总计:{{value}}', { value: renderQuota(totalQuota, 2) }),
newModelColors,
'barData',
);
// ===== 模型调用次数折线图 =====
let modelLineData = [];
chartTimePoints.forEach((time) => {
const timeData = Array.from(uniqueModels)
.filter((model) => model) // 过滤掉 undefined/null
.map((model) => {
const key = `${time}-${model}`;
const aggregated = aggregatedData.get(key);
return {
Time: time,
Model: String(model),
Count: aggregated?.count || 0,
};
});
modelLineData.push(...timeData);
});
modelLineData.sort((a, b) => a.Time.localeCompare(b.Time));
// ===== 模型调用次数排行柱状图 =====
const rankData = Array.from(modelTotals)
.filter(([model]) => model) // 过滤掉 undefined/null
.map(([model, count]) => ({
Model: String(model),
Count: count,
}))
.sort((a, b) => b.Count - a.Count);
updateChartSpec(
setSpecModelLine,
modelLineData,
t('总计:{{value}}', { value: renderNumber(totalTimes) }),
newModelColors,
'lineData',
);
updateChartSpec(
setSpecRankBar,
rankData,
t('总计:{{value}}', { value: renderNumber(totalTimes) }),
newModelColors,
'rankData',
);
setPieData(newPieData);
setLineData(newLineData);
setConsumeQuota(totalQuota);
setTimes(totalTimes);
setConsumeTokens(totalTokens);
},
[
dataExportDefaultTime,
setTrendData,
generateModelColors,
setModelColors,
setPieData,
setLineData,
setConsumeQuota,
setTimes,
setConsumeTokens,
t,
],
);
// ========== 初始化图表主题 ==========
useEffect(() => {
initVChartTheme({
isWatchingThemeSwitch: true,
});
}, []);
return {
// 图表规格
spec_pie,
spec_line,
spec_model_line,
spec_rank_bar,
// 函数
updateChartData,
generateModelColors,
};
};