/* 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 . 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 {t('无上期对比')}; } const pct = Number.isFinite(Number(cur)) ? ((Number(cur) - Number(prev)) / Number(prev)) * 100 : null; const up = pct !== null && pct >= 0; return ( {pct === null ? '-' : `${up ? '↑' : '↓'} ${formatPercent(Math.abs(pct), 1)}`} {t('较上期')} ); }; // 把 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) => {v}, }, { title: t('消费占比'), width: 300, render: (_, r) => { const pct = breakdownTotal > 0 ? ((Number(r.quota) || 0) / breakdownTotal) * 100 : null; return (
{renderQuota(r.quota || 0, 2)} {formatPercent(pct, 1)}
); }, }, { title: t('请求数'), dataIndex: 'request_count', width: 110, align: 'right', render: (v) => Number(v || 0).toLocaleString(), }, { title: t('Token(入 / 出)'), width: 240, align: 'right', render: (_, r) => ( {Number(r.prompt_tokens || 0).toLocaleString()} / {Number(r.completion_tokens || 0).toLocaleString()} ), }, ], [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 = (

{t('{{dim}}明细', { dim: dimLabel })}

{loading ? (
) : breakdownRows.length === 0 ? ( ) : ( )} ); return ( <> {/* 多维用量分析(原型 .ea-analysis):标题 + 维度 / 时间 / 刷新 */}

{t('多维用量分析')}

{t('趋势、结构与调用明细')}

} loading={loading} onClick={() => fetchAll(true)} />
{/* 汇总指标(原型 .ea-summary) */}
{t('本期总消费')} {renderQuota(curQuota, 2)}
{t('本期总请求')} {curReq.toLocaleString()}
{t('日均消费')} {renderQuota(rangeDays > 0 ? curQuota / rangeDays : 0, 2)} {t('近 {{n}} 天均值', { n: rangeDays })}
{t('消费最高')} {topRow ? topRow.name : '-'} {topRow ? renderQuota(topRow.quota || 0, 2) : dimension === 'time' ? t('按时间维度无排名') : '-'}
{/* 用量趋势 */}

{t('用量趋势')}

{rangeDays > 7 ? t('按天查看企业调用消耗') : t('逐小时查看企业调用消耗')}
{loading ? (
) : trendSpec ? ( ) : ( )}
{/* 维度分布柱状(time 维度不展示,趋势图已覆盖) */} {dimension !== 'time' && (

{t('{{dim}}消费分布', { dim: dimLabel })}

{t('Top 10')}
{t('按消费排序')}
{loading ? (
) : barSpec ? ( ) : ( )}
)}
{/* 明细(原型 .ea-details:维度明细 / 成员用量 页签) */}
); }; export default OrgAnalyticsPanel;