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

580 lines
19 KiB
React

import { I18N_TECHNICAL_TEXT } from '../../../i18n/technicalText.js';
import React, { useMemo, useState } from 'react';
import { Progress, Radio, RadioGroup, Tag } from '@/components/ui';
import { VChart } from '@visactor/react-vchart';
import {
BarChart3,
Cpu,
Crown,
GitCompareArrows,
LineChart,
Users,
} from 'lucide-react';
import { ChangeText, EmptyBlock, SectionCard } from './shared';
import {
formatCny,
orgDisplayName,
pct,
quotaToCny,
SEGMENTS,
TIERS,
} from './utils';
// VChart 配色必须是具体色值(图表在 canvas 上绘制,读取不到 CSS 变量);
// 与看板其余图表共用同一组色:个人蓝、企业紫、增长绿、下降红
const COLOR_PERSONAL = '#3b82f6';
const COLOR_ORG = '#8b5cf6';
const COLOR_ORG_MA = '#c4b5fd';
const COLOR_UP = '#10b981';
const COLOR_DOWN = '#ef4444';
const truncateLabel = (v, n = 14) =>
v && v.length > n ? `${v.slice(0, n - 1)}…` : v;
// ─── 变化归因:谁拉动了增长 / 下滑 ─────────────────────────────────
export const ChangeAttribution = ({ report, cny, t }) => {
const { chartSpec, segmentRows, netDelta } = useMemo(() => {
const orgs = (report.orgs || []).map((o) => ({
name: orgDisplayName(o, t),
delta: (o.quota || 0) - (o.prev_quota || 0),
}));
const up = orgs
.filter((o) => o.delta > 0)
.sort((a, b) => b.delta - a.delta)
.slice(0, 8);
const down = orgs
.filter((o) => o.delta < 0)
.sort((a, b) => a.delta - b.delta)
.slice(0, 8);
const values = [...up, ...down.reverse()]
.map((o, i) => ({
// 名称可能重复,用序号保证类目唯一,标签里再去掉
key: `${i}${o.name}`,
value: Number(quotaToCny(o.delta, cny).toFixed(2)),
sign: o.delta > 0 ? 'up' : 'down',
}))
.reverse();
const spec = values.length
? {
type: 'bar',
direction: 'horizontal',
data: [{ id: 'attr', values }],
xField: 'value',
yField: 'key',
seriesField: 'sign',
color: {
type: 'ordinal',
domain: ['up', 'down'],
range: [COLOR_UP, COLOR_DOWN],
},
legends: { visible: false },
bar: { style: { cornerRadius: 3 } },
label: {
visible: true,
position: 'outside',
formatMethod: (v) => `${v > 0 ? '+' : ''}¥${v}`,
},
tooltip: {
mark: {
title: { value: (d) => d?.key?.split('')[1] },
content: [
{
key: t('消耗变化'),
value: (d) => `${d?.value > 0 ? '+' : ''}¥${d?.value}`,
},
],
},
},
axes: [
{ orient: 'bottom', label: { formatMethod: (v) => `¥${v}` } },
{
orient: 'left',
label: {
formatMethod: (v) => truncateLabel(String(v).split('')[1]),
},
},
],
}
: null;
const bySeg = {};
(report.segments || []).forEach((s) => {
bySeg[s.key] = (s.quota || 0) - (s.prev_quota || 0);
});
const rows = Object.entries(bySeg)
.filter(([, d]) => d !== 0)
.sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]));
const net = Object.values(bySeg).reduce((s, d) => s + d, 0);
return { chartSpec: spec, segmentRows: rows, netDelta: net };
}, [report, cny, t]);
return (
<SectionCard
id='org-report-attribution'
title={t('消耗变化归因')}
icon={<GitCompareArrows className='w-5 h-5' />}
extra={
<span
className='text-xs font-medium tabular-nums'
style={{
color:
netDelta >= 0
? 'var(--ui-color-success)'
: 'var(--ui-color-danger)',
}}
>
{t('净变化')} {netDelta >= 0 ? '+' : '-'}
{formatCny(Math.abs(netDelta), cny)}
</span>
}
>
<div className='grid grid-cols-1 lg:grid-cols-3 gap-4'>
<div className='lg:col-span-2 min-w-0'>
<div className='text-xs text-gray-500 mb-1'>
{t('增长 / 下滑贡献最大的企业(本期 − 对比期)')}
</div>
{chartSpec ? (
<VChart
spec={chartSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: 380 }}
/>
) : (
<EmptyBlock height={380} text={t('两期消耗无变化')} />
)}
</div>
<div className='min-w-0'>
<div className='text-xs text-gray-500 mb-2'>
{t('按健康分群拆解')}
</div>
{segmentRows.length === 0 ? (
<EmptyBlock height={120} text={t('暂无数据')} />
) : (
<div className='space-y-2'>
{segmentRows.map(([key, d]) => {
const meta = SEGMENTS[key] || { label: key, color: 'grey' };
const maxAbs = Math.max(
...segmentRows.map(([, x]) => Math.abs(x)),
1,
);
return (
<div key={key}>
<div className='flex items-center justify-between text-xs mb-0.5'>
<Tag size='small' color={meta.color}>
{t(meta.label)}
</Tag>
<span
className='tabular-nums font-medium'
style={{
color:
d > 0
? 'var(--ui-color-success)'
: 'var(--ui-color-danger)',
}}
>
{d > 0 ? '+' : '-'}
{formatCny(Math.abs(d), cny)}
</span>
</div>
<Progress
percent={(Math.abs(d) / maxAbs) * 100}
showInfo={false}
size='small'
stroke={
d > 0
? 'var(--ui-color-success)'
: 'var(--ui-color-danger)'
}
style={{ height: 4 }}
/>
</div>
);
})}
</div>
)}
</div>
</div>
</SectionCard>
);
};
// ─── 价值分层 + 排行 ──────────────────────────────────────────────
const RankList = ({ items, valueOf, render, max }) => (
<div className='space-y-1 max-h-[420px] overflow-y-auto pr-1 app-scrollbar'>
{items.map((o, i) => (
<div
key={o.org_id}
className='p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors'
>
<div className='flex items-center gap-2'>
<span
className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0 ${
i < 3
? 'bg-brand text-white'
: 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300'
}`}
>
{i + 1}
</span>
<div className='flex-1 min-w-0'>{render(o)}</div>
</div>
<Progress
percent={max > 0 ? (valueOf(o) / max) * 100 : 0}
showInfo={false}
size='small'
style={{ height: 3, marginTop: 4, marginLeft: 32 }}
/>
</div>
))}
</div>
);
export const TiersAndRankings = ({ report, cny, onSelectTier, t }) => {
const k = report.kpi || {};
const consumers = (report.orgs || []).filter((o) => o.quota > 0).slice(0, 10);
const byActive = [...(report.orgs || [])]
.filter((o) => o.active_members > 0)
.sort((a, b) => b.active_members - a.active_members || b.quota - a.quota)
.slice(0, 10);
return (
<div
id='org-report-tiers'
className='grid grid-cols-1 lg:grid-cols-3 gap-4 scroll-mt-24'
>
<SectionCard
title={t('客户价值分层')}
icon={<BarChart3 className='w-5 h-5' />}
>
<div className='space-y-3'>
{(report.tiers || []).map((tier) => {
const meta = TIERS[tier.key];
const share = pct(tier.quota, k.org_quota);
return (
<button
key={tier.key}
type='button'
onClick={() => onSelectTier(tier.key)}
className='w-full text-left rounded-xl border border-gray-200 dark:border-gray-700 p-3 hover:border-brand/50 transition-colors focus-visible:outline focus-visible:outline-2'
>
<div className='flex items-center justify-between'>
<Tag color={meta.color}>{t(meta.label)}</Tag>
<span className='text-xs text-gray-400'>{t(meta.desc)}</span>
</div>
<div className='flex items-end justify-between mt-2'>
<span className='text-lg font-bold tabular-nums text-gray-800 dark:text-gray-100'>
{tier.count}{' '}
<span className='text-xs font-normal text-gray-500'>
{t('家')}
</span>
</span>
<span className='text-sm tabular-nums text-gray-600 dark:text-gray-300'>
{formatCny(tier.quota, cny, 0)} · {share.toFixed(1)}%
</span>
</div>
<Progress
percent={share}
showInfo={false}
size='small'
style={{ height: 4, marginTop: 6 }}
/>
</button>
);
})}
<div className='grid grid-cols-2 gap-2 pt-1'>
<div className='rounded-lg bg-gray-50 dark:bg-gray-800 p-2'>
<div className='text-xs text-gray-500'>{t('Top5 集中度')}</div>
<div className='text-base font-semibold tabular-nums'>
{(k.top5_share || 0).toFixed(1)}%
</div>
</div>
<div className='rounded-lg bg-gray-50 dark:bg-gray-800 p-2'>
<div className='text-xs text-gray-500'>{t('Top10 集中度')}</div>
<div className='text-base font-semibold tabular-nums'>
{(k.top10_share || 0).toFixed(1)}%
</div>
</div>
</div>
</div>
</SectionCard>
<SectionCard
title={t('企业消耗 Top10')}
icon={<Crown className='w-5 h-5' />}
>
{consumers.length === 0 ? (
<EmptyBlock text={t('暂无数据')} />
) : (
<RankList
items={consumers}
valueOf={(o) => o.quota}
max={consumers[0].quota}
render={(o) => (
<>
<div className='flex items-center justify-between gap-2'>
<span
className='text-sm font-medium truncate'
title={orgDisplayName(o, t)}
>
{orgDisplayName(o, t)}
</span>
<span className='text-sm font-semibold tabular-nums flex-shrink-0'>
{formatCny(o.quota, cny)}
</span>
</div>
<div className='flex items-center justify-between gap-2 text-xs text-gray-400 tabular-nums'>
<span className='truncate'>
{(o.share || 0).toFixed(1)}
{I18N_TECHNICAL_TEXT.PERCENT_SEPARATOR} {o.active_members}/
{o.member_count} {t('人活跃')}
</span>
<ChangeText cur={o.quota} prev={o.prev_quota} t={t} />
</div>
</>
)}
/>
)}
</SectionCard>
<SectionCard
title={t('企业活跃人数 Top10')}
icon={<Users className='w-5 h-5' />}
>
{byActive.length === 0 ? (
<EmptyBlock text={t('暂无数据')} />
) : (
<RankList
items={byActive}
valueOf={(o) => o.active_members}
max={byActive[0].active_members}
render={(o) => (
<>
<div className='flex items-center justify-between gap-2'>
<span
className='text-sm font-medium truncate'
title={orgDisplayName(o, t)}
>
{orgDisplayName(o, t)}
</span>
<span className='text-sm font-semibold tabular-nums flex-shrink-0'>
{o.active_members} {t('人')}
</span>
</div>
<div className='flex items-center justify-between gap-2 text-xs text-gray-400 tabular-nums'>
<span>
{t('活跃率')}{' '}
{o.member_count > 0
? `${Math.min(100, pct(o.active_members, o.member_count)).toFixed(0)}%`
: '—'}
</span>
<span>
{t('人均')}{' '}
{formatCny(
o.active_members > 0 ? o.quota / o.active_members : 0,
cny,
)}
</span>
</div>
</>
)}
/>
)}
</SectionCard>
</div>
);
};
// ─── 趋势 ─────────────────────────────────────────────────────────
const TREND_MODES = {
quota: {
label: '消耗金额',
fields: ['personal_quota', 'org_quota'],
money: true,
},
requests: {
label: '请求次数',
fields: ['personal_requests', 'org_requests'],
},
users: { label: '活跃人数', fields: ['personal_active', 'org_active'] },
orgs: { label: '活跃企业', fields: [null, 'active_orgs'] },
};
export const TrendChart = ({ report, cny, t }) => {
const [mode, setMode] = useState('quota');
const spec = useMemo(() => {
const data = report.trend || [];
if (!data.length) return null;
const cfg = TREND_MODES[mode];
const personalKey = t('个人');
const orgKey = t('企业');
const maKey = t('企业 7 日均线');
const conv = (v) =>
cfg.money ? Number(quotaToCny(v || 0, cny).toFixed(2)) : v || 0;
const values = [];
const colors = [];
const series = [];
if (cfg.fields[0]) {
series.push(personalKey);
colors.push(COLOR_PERSONAL);
}
series.push(orgKey);
colors.push(COLOR_ORG);
const withMa = mode === 'quota' && data.length >= 7;
if (withMa) {
series.push(maKey);
colors.push(COLOR_ORG_MA);
}
data.forEach((p, i) => {
if (cfg.fields[0])
values.push({
date: p.date,
type: personalKey,
value: conv(p[cfg.fields[0]]),
});
values.push({
date: p.date,
type: orgKey,
value: conv(p[cfg.fields[1]]),
});
if (withMa && i >= 6) {
const win = data.slice(i - 6, i + 1);
const avg = win.reduce((s, x) => s + (x[cfg.fields[1]] || 0), 0) / 7;
values.push({ date: p.date, type: maKey, value: conv(avg) });
}
});
const fmt = (v) => (cfg.money ? `¥${v}` : Number(v).toLocaleString());
return {
type: 'line',
data: [{ id: 'trend', values }],
xField: 'date',
yField: 'value',
seriesField: 'type',
color: { type: 'ordinal', domain: series, range: colors },
point: { visible: data.length <= 31, style: { size: 4 } },
line: {
style: {
lineWidth: 2,
lineDash: (d) => (d.type === maKey ? [4, 4] : [0]),
},
},
legends: { visible: true, orient: 'top', position: 'end' },
tooltip: {
dimension: {
content: [{ key: (d) => d?.type, value: (d) => fmt(d?.value) }],
},
},
crosshair: { xField: { visible: true } },
axes: [
{
orient: 'bottom',
label: { style: { angle: data.length > 14 ? -45 : 0 } },
},
{ orient: 'left', label: { formatMethod: fmt } },
],
};
}, [report, mode, cny, t]);
return (
<SectionCard
id='org-report-trend'
title={t('趋势')}
icon={<LineChart className='w-5 h-5' />}
extra={
<RadioGroup
type='button'
size='small'
value={mode}
onChange={(e) => setMode(e.target.value)}
className='ml-auto'
>
{Object.entries(TREND_MODES).map(([k, v]) => (
<Radio key={k} value={k}>
{t(v.label)}
</Radio>
))}
</RadioGroup>
}
>
{spec ? (
<VChart
spec={spec}
option={{ mode: 'desktop-browser' }}
style={{ height: 320 }}
/>
) : (
<EmptyBlock height={320} text={t('暂无数据')} />
)}
</SectionCard>
);
};
// ─── 企业热门模型 ─────────────────────────────────────────────────
export const TopModels = ({ report, cny, t }) => {
const spec = useMemo(() => {
const data = report.top_models || [];
if (!data.length) return null;
const values = data
.map((m) => ({
model: m.model_name || '-',
value: Number(quotaToCny(m.quota, cny).toFixed(2)),
requests: m.requests,
orgs: m.org_count,
share: m.share,
}))
.reverse();
return {
type: 'bar',
direction: 'horizontal',
data: [{ id: 'models', values }],
xField: 'value',
yField: 'model',
color: [COLOR_ORG],
bar: { style: { cornerRadius: [0, 4, 4, 0] } },
label: {
visible: true,
position: 'outside',
formatMethod: (v, d) => `¥${v} · ${(d?.share || 0).toFixed(1)}%`,
},
tooltip: {
mark: {
title: { value: (d) => d?.model },
content: [
{ key: t('消耗金额'), value: (d) => `¥${d?.value}` },
{
key: t('占企业消耗'),
value: (d) => `${(d?.share || 0).toFixed(1)}%`,
},
{
key: t('请求次数'),
value: (d) => (d?.requests || 0).toLocaleString(),
},
{ key: t('使用企业数'), value: (d) => d?.orgs },
],
},
},
axes: [
{ orient: 'bottom', label: { formatMethod: (v) => `¥${v}` } },
{
orient: 'left',
label: { formatMethod: (v) => truncateLabel(v, 22) },
},
],
};
}, [report, cny, t]);
return (
<SectionCard title={t('企业热门模型')} icon={<Cpu className='w-5 h-5' />}>
{spec ? (
<VChart
spec={spec}
option={{ mode: 'desktop-browser' }}
style={{ height: 320 }}
/>
) : (
<EmptyBlock height={320} text={t('暂无数据')} />
)}
</SectionCard>
);
};