Files
monkey-ai-web/src/components/analytics/orgReport/Overview.jsx
T

361 lines
14 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.
/*
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 from 'react';
import { Banner, Button, Card, Tag, Tooltip } from '@/components/ui';
import {
AlertOctagon,
AlertTriangle,
CheckCircle2,
Download,
Info,
Lightbulb,
} from 'lucide-react';
import { ChangeText, KpiCard, SectionCard } from './shared';
import { formatCny, formatCst, pct, SEGMENTS } from './utils';
// ─── 报表抬头:统计口径 + 数据状态 ─────────────────────────────────
export const ReportHeader = ({ report, onExport, t }) => {
const m = report.meta || {};
const now = Date.now() / 1000;
const stale = m.rollup_ready && now - m.data_as_of > 2 * 3600;
const beyondFloor =
m.rollup_ready && m.history_floor > 0 && m.prev_start < m.history_floor;
return (
<>
<Card className='shadow-sm mb-4' bodyStyle={{ padding: '16px 20px' }}>
<div className='flex flex-col md:flex-row md:items-center md:justify-between gap-3'>
<div className='min-w-0'>
<div className='text-xs font-semibold tracking-wider text-brand mb-1'>
{t('企业经营决策报表')}
</div>
<div className='text-sm text-gray-700 dark:text-gray-200 tabular-nums'>
{t('本期')}:{formatCst(m.start)} ~ {formatCst(m.effective_end)}
<span className='mx-2 text-gray-300'>|</span>
{t('对比期')}:{formatCst(m.prev_start)} ~ {formatCst(m.prev_end)}
</div>
<div className='text-xs text-gray-500 dark:text-gray-400 mt-1'>
{t('数据截至 {{time}},按整点统计;对比期与本期按相同时长对齐', {
time: formatCst(m.data_as_of),
})}
</div>
</div>
<Button
icon={<Download className='w-4 h-4' />}
onClick={onExport}
disabled={!report.orgs?.length}
>
{t('导出企业明细')}
</Button>
</div>
</Card>
{!m.rollup_ready ? (
<Banner
className='mb-4'
type='warning'
fullMode={false}
closeIcon={null}
title={t('报表数据正在初始化')}
description={t(
'后台正在首次汇总消耗日志,通常 1~2 分钟后可用。若长时间无数据,请确认至少有一个 master 节点(NODE_TYPE 不为 slave),且未设置 ANALYTICS_ROLLUP_ENABLED=false。',
)}
/>
) : null}
{m.rollup_ready && !m.history_ready ? (
<Banner
className='mb-4'
type='info'
fullMode={false}
closeIcon={null}
description={t(
'历史数据回填中(已完成至 {{time}}),该时间之前的对比期数据暂不完整,环比与分群仅供参考。',
{ time: formatCst(m.backfill_cursor) },
)}
/>
) : null}
{beyondFloor ? (
<Banner
className='mb-4'
type='info'
fullMode={false}
closeIcon={null}
description={t(
'对比期早于汇总保留范围({{time}} 起),环比可能偏高。',
{
time: formatCst(m.history_floor, false),
},
)}
/>
) : null}
{stale ? (
<Banner
className='mb-4'
type='warning'
fullMode={false}
closeIcon={null}
description={t(
'数据同步延迟:最近一次同步于 {{time}},请检查 master 节点运行状态。',
{
time: formatCst(m.data_as_of),
},
)}
/>
) : null}
</>
);
};
// ─── 本期要点 ─────────────────────────────────────────────────────
const FINDING_STYLE = {
danger: { icon: AlertOctagon, color: 'var(--ui-color-danger)' },
warning: { icon: AlertTriangle, color: 'var(--ui-color-warning)' },
success: { icon: CheckCircle2, color: 'var(--ui-color-success)' },
info: { icon: Info, color: 'var(--ui-color-primary)' },
};
export const KeyFindings = ({ findings, onJump, t }) => (
<SectionCard
id='org-report-findings'
title={t('本期要点')}
icon={<Lightbulb className='w-5 h-5' />}
extra={
<span className='text-xs text-gray-400'>
{t('根据本期数据自动生成,点击可定位到明细')}
</span>
}
>
{findings.length === 0 ? (
<div className='text-sm text-gray-400 py-4'>
{t('本期暂无需要关注的变化')}
</div>
) : (
<ul className='space-y-2'>
{findings.map((f, i) => {
const style = FINDING_STYLE[f.level] || FINDING_STYLE.info;
const Icon = style.icon;
return (
<li key={i}>
<button
type='button'
onClick={() => onJump(f.target)}
className='w-full text-left flex items-start gap-2 p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors focus-visible:outline focus-visible:outline-2'
>
<Icon
className='w-4 h-4 mt-0.5 flex-shrink-0'
style={{ color: style.color }}
/>
<span className='text-sm text-gray-700 dark:text-gray-200 leading-relaxed'>
{f.text}
</span>
</button>
</li>
);
})}
</ul>
)}
</SectionCard>
);
// ─── 核心指标 ─────────────────────────────────────────────────────
export const KpiGrid = ({ report, lists, cny, onJump, t }) => {
const k = report.kpi || {};
const servingOrgs = (k.normal_orgs || 0) + (k.arrears_orgs || 0);
const avgPerOrg = k.active_orgs > 0 ? k.org_quota / k.active_orgs : 0;
const prevAvgPerOrg =
k.prev_active_orgs > 0 ? k.prev_org_quota / k.prev_active_orgs : 0;
const platform = (k.org_quota || 0) + (k.personal_quota || 0);
const prevPlatform = (k.prev_org_quota || 0) + (k.prev_personal_quota || 0);
const share = pct(k.org_quota, platform);
const prevShare =
prevPlatform > 0 ? pct(k.prev_org_quota, prevPlatform) : null;
const shareDelta = prevShare === null ? null : share - prevShare;
const coverDays =
k.run_rate_daily > 0 ? k.total_balance / k.run_rate_daily : null;
const cards = [
{
title: t('企业消耗'),
value: formatCny(k.org_quota, cny),
sub: `${t('对比期')} ${formatCny(k.prev_org_quota, cny)}`,
compare: <ChangeText cur={k.org_quota} prev={k.prev_org_quota} t={t} />,
onClick: () => onJump('attribution'),
},
{
title: t('活跃企业'),
value: `${(k.active_orgs || 0).toLocaleString()} ${t('家')}`,
sub: `${t('活跃率')} ${pct(k.active_orgs, servingOrgs).toFixed(1)}% · ${t('新增')} ${k.new_orgs || 0}`,
compare: (
<ChangeText cur={k.active_orgs} prev={k.prev_active_orgs} t={t} />
),
tip: t('本期有调用的企业数;活跃率 = 活跃企业 / 正常与欠费企业'),
onClick: () => onJump('segments'),
},
{
title: t('家均消耗'),
value: formatCny(avgPerOrg, cny),
sub: `${t('人均')} ${formatCny(k.active_members > 0 ? k.org_quota / k.active_members : 0, cny)}`,
compare: <ChangeText cur={avgPerOrg} prev={prevAvgPerOrg} t={t} />,
tip: t('企业消耗 / 活跃企业数;人均 = 企业消耗 / 活跃成员数'),
},
{
title: t('企业活跃成员'),
value: `${(k.active_members || 0).toLocaleString()} ${t('人')}`,
sub: `${t('渗透率')} ${Math.min(100, pct(k.active_members, k.total_members)).toFixed(1)}% · ${t('成员')} ${(k.total_members || 0).toLocaleString()}`,
tip: t('本期通过企业密钥产生调用的去重成员数(按自然日统计)'),
onClick: () => onJump('growth'),
},
{
title: t('本月预计企业消耗'),
value: formatCny(k.month_forecast, cny),
sub: `${t('本月至今')} ${formatCny(k.month_to_date, cny)}`,
compare: (
<Tooltip content={`${t('上月')} ${formatCny(k.last_month_quota, cny)}`}>
<span>
<ChangeText
cur={k.month_forecast}
prev={k.last_month_quota}
t={t}
/>
</span>
</Tooltip>
),
tip: t('本月至今 + 近 7 个完整日的日均消耗 × 本月剩余天数;对比上月全月'),
accent: 'var(--ui-color-tertiary)',
},
{
title: t('未来 30 天充值缺口'),
value: formatCny(k.topup_gap_30d, cny),
sub: `${lists.renewal.length} ${t('家需续费跟进')}`,
tip: t('按各企业近 7 日日均消耗覆盖 30 天所需金额,减去当前余额后累加'),
accent:
k.topup_gap_30d > 0
? 'var(--ui-color-danger)'
: 'var(--ui-color-success)',
onClick: () => onJump('renewal'),
},
{
title: t('企业总余额'),
value: formatCny(k.total_balance, cny),
sub:
coverDays === null
? t('近 7 日无消耗')
: t('按当前速度可支撑 {{days}} 天', { days: coverDays.toFixed(0) }),
tip: t('全部企业主余额 + 赠送余额'),
accent: 'var(--ui-color-success)',
},
{
title: t('企业消耗占平台'),
value: `${share.toFixed(1)}%`,
sub: `${t('个人消耗')} ${formatCny(k.personal_quota, cny)}`,
compare:
shareDelta === null ? null : (
<span
className='text-xs font-medium tabular-nums'
style={{
color:
shareDelta >= 0
? 'var(--ui-color-success)'
: 'var(--ui-color-danger)',
}}
>
{shareDelta >= 0 ? '+' : ''}
{shareDelta.toFixed(1)}pp
</span>
),
tip: t('企业消耗 /(企业 + 个人消耗);pp 为百分点变化'),
onClick: () => onJump('trend'),
},
];
return (
<div
id='org-report-kpi'
className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 scroll-mt-24'
>
{cards.map((c) => (
<KpiCard key={c.title} {...c} />
))}
</div>
);
};
// ─── 客户健康分群 ─────────────────────────────────────────────────
export const HealthSegments = ({ report, cny, activeSegment, onSelect, t }) => {
const segs = report.segments || [];
const totalCount = segs.reduce((s, x) => s + x.count, 0);
return (
<div
id='org-report-segments'
className='grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 scroll-mt-24'
>
{segs.map((s) => {
const meta = SEGMENTS[s.key] || { label: s.key, color: 'grey' };
const active = activeSegment === s.key;
const delta = (s.quota || 0) - (s.prev_quota || 0);
return (
<Tooltip key={s.key} content={t(meta.desc)}>
<button
type='button'
onClick={() => onSelect(active ? '' : s.key)}
className={`text-left rounded-xl border p-3 transition-all focus-visible:outline focus-visible:outline-2 ${
active
? 'border-brand bg-brand/5 shadow-sm'
: 'border-gray-200 dark:border-gray-700 hover:border-brand/50 hover:shadow-sm'
} ${s.count === 0 ? 'opacity-60' : ''}`}
>
<div className='flex items-center justify-between gap-2'>
<Tag size='small' color={meta.color}>
{t(meta.label)}
</Tag>
<span className='text-xs text-gray-400 tabular-nums'>
{pct(s.count, totalCount).toFixed(0)}%
</span>
</div>
<div className='mt-2 text-lg font-bold text-gray-800 dark:text-gray-100 tabular-nums'>
{s.count.toLocaleString()}{' '}
<span className='text-xs font-normal text-gray-500'>
{t('家')}
</span>
</div>
<div className='text-xs text-gray-500 dark:text-gray-400 tabular-nums truncate'>
{formatCny(s.quota, cny, 0)}
{delta !== 0 ? (
<span
className='ml-1'
style={{
color:
delta > 0
? 'var(--ui-color-success)'
: 'var(--ui-color-danger)',
}}
>
{delta > 0 ? '+' : '-'}
{formatCny(Math.abs(delta), cny, 0)}
</span>
) : null}
</div>
</button>
</Tooltip>
);
})}
</div>
);
};