Files
monkey-ai-web/src/components/analytics/OrgCacheHourlySheet.jsx
T
zhanjunhao 8a48765a46 chore(repo): 移除重复版权文件头并纳入共享单测
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
2026-11-20 11:23:49 +08:00

363 lines
12 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.
import React, { useMemo, useState, useEffect } from 'react';
import { Button, Empty, Segmented, Skeleton, theme } from 'antd';
import { VChart } from '@visactor/react-vchart';
import { Info } from 'lucide-react';
import { RefreshCw } from '@/components/common/icons/ActionIcons';
import { ConsoleDrawer } from '@/components/console/ConsolePrimitives';
import useOrgCacheHourly from '../../hooks/analytics/useOrgCacheHourly';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import { formatIdReference, formatPercent } from '../../helpers/safeDisplay';
// 图表序列色属于专用图表(VChart)配色,统计块沿用同色以便与图例对应。
// 千分位缩写。线上单小时 cache_read 能到十亿量级,不缩写轴标签会糊成一片。
const abbr = (n) => {
const v = Number(n) || 0;
const abs = Math.abs(v);
if (abs >= 1e9) return `${(v / 1e9).toFixed(2)}B`;
if (abs >= 1e6) return `${(v / 1e6).toFixed(2)}M`;
if (abs >= 1e3) return `${(v / 1e3).toFixed(2)}K`;
return `${v}`;
};
const money = (n) => {
const v = Number(n) || 0;
if (Math.abs(v) >= 1000) return `$${(v / 1000).toFixed(2)}K`;
return `$${v.toFixed(2)}`;
};
// unix 秒 → 本地「MM-DD HH:00」。后端返回的是小时桶起点,整点整分,不做四舍五入。
const hourLabel = (unixSec) => {
const d = new Date((Number(unixSec) || 0) * 1000);
const p = (x) => String(x).padStart(2, '0');
return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:00`;
};
const SERIES_COLORS = {
input: '#3b82f6',
output: '#10b981',
cacheCreation: '#f59e0b',
cacheRead: '#8b5cf6',
hitRate: '#ef4444',
};
const StatBlock = ({ label, value, sub, color }) => (
<div className='flex-1 min-w-[110px]'>
<div className='text-xs text-[var(--text-secondary)] mb-1'>{label}</div>
<div
className='text-lg font-semibold'
style={color ? { color } : undefined}
>
{value}
</div>
{sub ? (
<div className='text-xs text-[var(--text-secondary)] mt-0.5'>{sub}</div>
) : null}
</div>
);
/**
* 单企业逐小时缓存命中率报表抽屉。
*
* 数据源是企业小时聚合表,不是 logs —— 口径与成本理由见
* model/analytics_org_cache.go 顶部注释。
*/
const OrgCacheHourlySheet = ({ visible, org, onClose, t }) => {
const isMobile = useIsMobile();
const { token } = theme.useToken();
const [hours, setHours] = useState(24);
// 关闭后重开默认回到 24h:上次选了 7d 不该粘到下一家企业上。
useEffect(() => {
if (!visible) setHours(24);
}, [visible]);
const orgId = visible ? org?.org_id : null;
const { data, loading, error, refresh } = useOrgCacheHourly(orgId, hours);
const points = useMemo(() => data?.points || [], [data]);
const totals = data?.totals || null;
// 全窗口零流量:补出来的点都是 0,画出来是一条贴底的直线,不如直接给空态。
const hasTraffic = points.some((p) => (p.requests || 0) > 0);
const spec = useMemo(() => {
if (!points.length || !hasTraffic) return null;
const inputKey = t('输入');
const outputKey = t('输出');
const creationKey = t('写缓存');
const readKey = t('读缓存');
const stacked = [];
const rateRows = [];
points.forEach((p) => {
const label = hourLabel(p.hour);
stacked.push(
{ hour: label, kind: inputKey, value: p.input || 0 },
{ hour: label, kind: outputKey, value: p.output || 0 },
{ hour: label, kind: creationKey, value: p.cache_creation || 0 },
{ hour: label, kind: readKey, value: p.cache_read || 0 },
);
rateRows.push({
hour: label,
// 该小时无流量时后端给 null;这里原样传下去并让序列 invalidType='break',
// 折线在空洞处断开,而不是掉到 0% 被误读成命中率暴跌。
hit_rate:
p.hit_rate === null || p.hit_rate === undefined ? null : p.hit_rate,
actual_cost: p.actual_cost || 0,
requests: p.requests || 0,
});
});
const rateKey = t('缓存命中率');
return {
type: 'common',
data: [
{ id: 'tokens', values: stacked },
{ id: 'rate', values: rateRows },
],
series: [
{
type: 'bar',
id: 'tokens',
dataIndex: 0,
xField: 'hour',
yField: 'value',
seriesField: 'kind',
stack: true,
bar: { style: { cornerRadius: [0, 0, 0, 0] } },
tooltip: {
visible: true,
mark: {
content: [
{
key: (datum) => datum?.kind,
value: (datum) => `${abbr(datum?.value)} tokens`,
},
],
},
},
},
{
type: 'line',
id: 'rate',
name: rateKey,
dataIndex: 1,
xField: 'hour',
yField: 'hit_rate',
// 空洞断线,不要 connectNulls 把两段无关的曲线连起来
invalidType: 'break',
point: {
visible: true,
size: 3,
style: { fill: SERIES_COLORS.hitRate },
},
line: { style: { stroke: SERIES_COLORS.hitRate, lineWidth: 2 } },
tooltip: {
visible: true,
mark: {
content: [
{
key: () => rateKey,
value: (datum) =>
datum?.hit_rate === null || datum?.hit_rate === undefined
? t('无流量')
: formatPercent(datum.hit_rate, 1),
},
{
key: () => t('实际消费'),
value: (datum) => money(datum?.actual_cost),
},
{
key: () => t('请求数'),
value: (datum) => (datum?.requests || 0).toLocaleString(),
},
],
},
},
},
],
color: [
SERIES_COLORS.input,
SERIES_COLORS.output,
SERIES_COLORS.cacheCreation,
SERIES_COLORS.cacheRead,
],
legends: {
visible: true,
orient: 'top',
position: 'middle',
padding: { top: 0, bottom: 12, left: 0, right: 0 },
layoutType: 'normal',
},
tooltip: { visible: true, dimension: { visible: true } },
crosshair: { xField: { visible: true, line: { visible: true } } },
axes: [
{
orient: 'bottom',
// 7d = 168 个桶,标签必须自动抽稀,否则重叠成黑条
label: { style: { angle: -45 }, autoLimit: true, autoHide: true },
},
{
orient: 'left',
title: { visible: true, text: t('Token 数') },
label: { formatMethod: (v) => abbr(v) },
seriesIndex: [0],
},
{
orient: 'right',
title: { visible: true, text: t('命中率 (%)') },
// 固定 0~100:让曲线的高低在不同企业、不同窗口之间可比。
// 自适应量程会把 76%~87% 的波动拉成满屏振荡,像出了故障。
min: 0,
max: 100,
label: { formatMethod: (v) => formatPercent(v, 0) },
seriesIndex: [1],
},
],
};
}, [points, hasTraffic, t]);
const orgReference = formatIdReference(org?.org_id);
const orgTitle = org?.org_name || (org ? `${t('企业')} ${orgReference}` : '');
return (
<ConsoleDrawer
open={visible}
onClose={onClose}
size={isMobile ? '100%' : 820}
title={
<div className='flex items-center gap-2 flex-wrap'>
<span className='font-semibold'>{t('缓存命中率明细')}</span>
<span className='text-sm font-normal text-[var(--text-secondary)]'>
{orgTitle}
</span>
{org?.org_id ? (
<span className='text-xs font-normal text-[var(--text-secondary)]'>
{orgReference}
</span>
) : null}
</div>
}
>
<div className='flex items-center justify-between gap-3 flex-wrap mb-4'>
<Segmented
value={hours}
onChange={setHours}
options={[
{ label: t('近 24 小时'), value: 24 },
{ label: t('近 7 天'), value: 24 * 7 },
]}
/>
<Button
icon={<RefreshCw size={16} />}
onClick={refresh}
loading={loading}
>
{t('刷新')}
</Button>
</div>
{totals ? (
<div
className='flex flex-wrap gap-4 px-4 py-3 mb-4 rounded-lg'
style={{ background: token.colorFillAlter }}
>
<StatBlock
label={t('缓存命中率')}
value={
totals.hit_rate === null || totals.hit_rate === undefined
? '--'
: formatPercent(totals.hit_rate, 2)
}
sub={t('按 token 加权')}
color={SERIES_COLORS.hitRate}
/>
<StatBlock label={t('输入')} value={abbr(totals.input)} />
<StatBlock label={t('输出')} value={abbr(totals.output)} />
<StatBlock
label={t('写缓存')}
value={abbr(totals.cache_creation)}
color={SERIES_COLORS.cacheCreation}
/>
<StatBlock
label={t('读缓存')}
value={abbr(totals.cache_read)}
color={SERIES_COLORS.cacheRead}
/>
<StatBlock
label={t('实际消费')}
value={money(totals.actual_cost)}
sub={t('{{n}} 次请求', {
n: (totals.requests || 0).toLocaleString(),
})}
/>
</div>
) : null}
{loading && !points.length ? (
<Skeleton active title={false} paragraph={{ rows: 8 }} />
) : error ? (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
className='py-12'
description={
<>
<div className='text-[var(--text-primary)]'>{t('加载失败')}</div>
<div>{error}</div>
</>
}
/>
) : spec ? (
<VChart
spec={spec}
option={{ mode: 'desktop-browser' }}
style={{ height: 360 }}
/>
) : (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
className='py-12'
description={
<>
<div className='text-[var(--text-primary)]'>
{t('该时间段内没有流量')}
</div>
<div>{t('所选窗口内这家企业没有产生可统计的请求')}</div>
</>
}
/>
)}
{/* 口径脚注:不写清楚的话,运营会拿这张图去对账单,然后发现对不上。 */}
<div
className='mt-4 px-3 py-2.5 text-xs text-[var(--text-secondary)] leading-relaxed rounded-md'
style={{ background: token.colorFillAlter }}
>
<div className='flex items-start gap-1.5'>
<Info aria-hidden className='w-3.5 h-3.5 mt-0.5 flex-shrink-0' />
<div>
<div>
{t(
'命中率 = 读缓存 ÷(输入 + 写缓存 + 读缓存)。输出 token 与缓存无关,不计入分母。',
)}
</div>
<div>
{t(
'数据来自企业小时聚合表,按自然小时切桶;最后一个小时尚未走完,数字仍在累加。',
)}
</div>
<div>
{t(
'「实际消费」为本平台实际计费金额;标准价对比待官方价目表配置完成后再上。',
)}
</div>
</div>
</div>
</div>
</ConsoleDrawer>
);
};
export { abbr as formatTokenAbbr, money as formatUsd, hourLabel };
export default OrgCacheHourlySheet;