Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
@@ -0,0 +1,524 @@
/*
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 {
Button,
Empty,
Table,
TabPane,
Tabs,
Tag,
Typography,
} from '@douyinfe/semi-ui';
import { ClipboardList, Download } from 'lucide-react';
import { ChangeText, OrgNameCell, ReasonTags, SectionCard } from './shared';
import {
daysSince,
downloadCsv,
formatCny,
formatCst,
orgDisplayName,
quotaToCny,
REASONS,
} from './utils';
const { Text } = Typography;
export const ACTION_TABS = ['renewal', 'retention', 'growth', 'activation'];
const TAB_META = {
renewal: {
label: '续费跟进',
desc: '余额耗尽 / 即将不足 / 低于预警线,以及合同即将到期的企业;按紧急程度排序',
},
retention: {
label: '流失挽回',
desc: '本期停用、消耗下滑、近 7 日腰斩,以及 60 天内还在使用的沉睡企业;按消耗减少金额排序',
},
growth: {
label: '增长机会',
desc: '高速增长、新客起量、回流,以及成员活跃率低于 30% 的企业;按本期消耗排序',
},
activation: {
label: '激活跟进',
desc: '待激活或开通后从未使用的企业;按创建时间倒序',
},
};
const money = (cny) => (v) => (
<span className='tabular-nums'>{formatCny(v, cny)}</span>
);
const salesRepCol = (t) => ({
title: t('跟进人'),
dataIndex: 'sales_rep',
width: 100,
render: (v) =>
v ? (
<span className='truncate'>{v}</span>
) : (
<Text type='tertiary'>{t('未分配')}</Text>
),
});
const contactCol = (t) => ({
title: t('联系人'),
dataIndex: 'contact_name',
width: 150,
render: (v, r) =>
v || r.contact_phone ? (
<div className='min-w-0'>
<div className='truncate'>{v || '—'}</div>
{r.contact_phone ? (
<div className='text-xs text-gray-400 tabular-nums'>
{r.contact_phone}
</div>
) : null}
</div>
) : (
<Text type='tertiary'>—</Text>
),
});
const baseCols = (t) => [
{
title: t('企业'),
dataIndex: 'name',
width: 190,
fixed: 'left',
render: (_, r) => <OrgNameCell org={r} t={t} />,
},
salesRepCol(t),
{
title: t('原因'),
dataIndex: 'reasons',
width: 170,
render: (v) => <ReasonTags reasons={v} t={t} />,
},
];
const actionCol = (t) => ({
title: t('建议动作'),
dataIndex: 'action',
width: 190,
render: (v) => <span className='text-sm'>{t(v)}</span>,
});
const columnsFor = (tab, cny, t, atRisk) => {
const m = money(cny);
switch (tab) {
case 'renewal':
return [
...baseCols(t),
{
title: t('当前余额'),
dataIndex: 'balance',
width: 120,
align: 'right',
render: m,
},
{
title: t('日均消耗'),
dataIndex: 'daily_avg',
width: 110,
align: 'right',
render: (v) => (v > 0 ? m(v) : <Text type='tertiary'>—</Text>),
},
{
title: t('预计可用'),
dataIndex: 'days_left',
width: 100,
align: 'right',
render: (v, r) => {
if (v < 0) return <Text type='tertiary'>{t('近期无消耗')}</Text>;
return (
<span
className='tabular-nums font-medium'
style={{
color:
v <= 3
? 'var(--semi-color-danger)'
: 'var(--semi-color-warning)',
}}
>
{v < 1 ? t('不足 1 天') : `${v.toFixed(1)} ${t('天')}`}
</span>
);
},
},
{
title: t('建议充值'),
dataIndex: 'topup_suggest',
width: 120,
align: 'right',
render: (v) =>
v > 0 ? (
<span className='font-semibold'>{m(v)}</span>
) : (
<Text type='tertiary'>—</Text>
),
},
{
title: t('到期时间'),
dataIndex: 'expired_at',
width: 110,
render: (v) =>
v > 0 ? formatCst(v, false) : <Text type='tertiary'>—</Text>,
},
contactCol(t),
actionCol(t),
];
case 'retention':
return [
...baseCols(t),
{
title: t('对比期消耗'),
dataIndex: 'prev_quota',
width: 120,
align: 'right',
render: m,
},
{
title: t('本期消耗'),
dataIndex: 'quota',
width: 120,
align: 'right',
render: m,
},
{
title: t('变化'),
dataIndex: 'change',
width: 90,
align: 'right',
render: (_, r) => (
<ChangeText
cur={r.quota}
prev={r.prev_quota}
t={t}
showNew={false}
/>
),
},
{
title: t('消耗减少'),
dataIndex: 'at_risk',
width: 110,
align: 'right',
render: (_, r) => (
<span className='tabular-nums font-semibold'>
{formatCny(atRisk(r), cny)}
</span>
),
},
{
title: t('最近使用'),
dataIndex: 'last_active',
width: 110,
render: (v) => {
const d = daysSince(v);
return d === null ? (
<Text type='tertiary'>—</Text>
) : d === 0 ? (
t('今天')
) : (
t('{{days}} 天前', { days: d })
);
},
},
{
title: t('余额'),
dataIndex: 'balance',
width: 110,
align: 'right',
render: m,
},
contactCol(t),
actionCol(t),
];
case 'growth':
return [
...baseCols(t),
{
title: t('本期消耗'),
dataIndex: 'quota',
width: 120,
align: 'right',
render: m,
},
{
title: t('变化'),
dataIndex: 'change',
width: 100,
align: 'right',
render: (_, r) => (
<ChangeText cur={r.quota} prev={r.prev_quota} t={t} />
),
},
{
title: t('成员活跃'),
dataIndex: 'active_members',
width: 120,
align: 'right',
render: (v, r) => (
<span className='tabular-nums'>
{v}/{r.member_count}
{r.member_count > 0 ? (
<span className='text-xs text-gray-400 ml-1'>
{Math.min(100, (v / r.member_count) * 100).toFixed(0)}%
</span>
) : null}
</span>
),
},
{
title: t('层级'),
dataIndex: 'tier',
width: 70,
render: (v) =>
v ? <Tag size='small'>{v}</Tag> : <Text type='tertiary'>—</Text>,
},
{
title: t('余额'),
dataIndex: 'balance',
width: 110,
align: 'right',
render: m,
},
actionCol(t),
];
default:
return [
...baseCols(t),
{
title: t('创建时间'),
dataIndex: 'created_at',
width: 110,
render: (v) => formatCst(v, false),
},
{
title: t('已开通'),
dataIndex: 'age',
width: 90,
align: 'right',
render: (_, r) => {
const d = daysSince(r.created_at);
return d === null ? '—' : t('{{days}} 天', { days: d });
},
},
{
title: t('成员数'),
dataIndex: 'member_count',
width: 80,
align: 'right',
},
{
title: t('余额'),
dataIndex: 'balance',
width: 110,
align: 'right',
render: m,
},
contactCol(t),
actionCol(t),
];
}
};
const exportList = (tab, rows, cny, t, atRisk) => {
const yuan = (v) => quotaToCny(v, cny).toFixed(2);
const common = (o) => [
orgDisplayName(o, t),
o.code,
o.sales_rep || t('未分配'),
o.reasons.map((r) => t(REASONS[r]?.label || r)).join(' / '),
];
const head = [t('企业'), t('企业代码'), t('跟进人'), t('原因')];
let headers;
let body;
switch (tab) {
case 'renewal':
headers = [
...head,
t('当前余额'),
t('日均消耗'),
t('预计可用天数'),
t('建议充值'),
t('到期时间'),
t('联系人'),
t('联系电话'),
t('建议动作'),
];
body = rows.map((o) => [
...common(o),
yuan(o.balance),
yuan(o.daily_avg),
o.days_left < 0 ? '' : o.days_left.toFixed(1),
yuan(o.topup_suggest),
o.expired_at > 0 ? formatCst(o.expired_at, false) : '',
o.contact_name,
o.contact_phone,
t(o.action),
]);
break;
case 'retention':
headers = [
...head,
t('对比期消耗'),
t('本期消耗'),
t('消耗减少'),
t('最近使用'),
t('余额'),
t('联系人'),
t('联系电话'),
t('建议动作'),
];
body = rows.map((o) => [
...common(o),
yuan(o.prev_quota),
yuan(o.quota),
yuan(atRisk(o)),
formatCst(o.last_active),
yuan(o.balance),
o.contact_name,
o.contact_phone,
t(o.action),
]);
break;
case 'growth':
headers = [
...head,
t('本期消耗'),
t('对比期消耗'),
t('活跃成员'),
t('成员数'),
t('层级'),
t('余额'),
t('建议动作'),
];
body = rows.map((o) => [
...common(o),
yuan(o.quota),
yuan(o.prev_quota),
o.active_members,
o.member_count,
o.tier,
yuan(o.balance),
t(o.action),
]);
break;
default:
headers = [
...head,
t('创建时间'),
t('成员数'),
t('余额'),
t('联系人'),
t('联系电话'),
t('建议动作'),
];
body = rows.map((o) => [
...common(o),
formatCst(o.created_at, false),
o.member_count,
yuan(o.balance),
o.contact_name,
o.contact_phone,
t(o.action),
]);
}
downloadCsv(
`${t(TAB_META[tab].label)}-${formatCst(Date.now() / 1000, false)}.csv`,
headers,
body,
);
};
export const ActionCenter = ({ lists, activeTab, onTabChange, cny, t }) => (
<SectionCard
id='org-report-actions'
title={t('行动清单')}
icon={<ClipboardList className='w-5 h-5' />}
extra={
<span className='text-xs text-gray-400'>
{t('按跟进场景拆分的待办企业,可直接导出分派')}
</span>
}
bodyStyle={{ paddingTop: 4 }}
>
<Tabs
type='line'
activeKey={activeTab}
onChange={onTabChange}
tabBarExtraContent={
<Button
size='small'
icon={<Download className='w-3.5 h-3.5' />}
disabled={lists[activeTab].length === 0}
onClick={() =>
exportList(activeTab, lists[activeTab], cny, t, lists.atRisk)
}
>
{t('导出')}
</Button>
}
>
{ACTION_TABS.map((tab) => (
<TabPane
key={tab}
itemKey={tab}
tab={
<span className='flex items-center gap-1.5'>
{t(TAB_META[tab].label)}
<Tag
size='small'
color={
lists[tab].length > 0
? tab === 'growth'
? 'green'
: 'red'
: 'grey'
}
>
{lists[tab].length}
</Tag>
</span>
}
>
<div className='text-xs text-gray-500 dark:text-gray-400 my-2'>
{t(TAB_META[tab].desc)}
</div>
<Table
columns={columnsFor(tab, cny, t, lists.atRisk)}
dataSource={lists[tab]}
rowKey='org_id'
size='small'
scroll={{ x: 1200 }}
pagination={
lists[tab].length > 10
? { pageSize: 10, showSizeChanger: false }
: false
}
empty={<Empty description={t('暂无需要跟进的企业')} />}
/>
</TabPane>
))}
</Tabs>
</SectionCard>
);
Binary file not shown.
@@ -0,0 +1,360 @@
/*
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 '@douyinfe/semi-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(--semi-color-danger)' },
warning: { icon: AlertTriangle, color: 'var(--semi-color-warning)' },
success: { icon: CheckCircle2, color: 'var(--semi-color-success)' },
info: { icon: Info, color: 'var(--semi-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(--semi-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(--semi-color-danger)'
: 'var(--semi-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(--semi-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(--semi-color-success)'
: 'var(--semi-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(--semi-color-success)'
: 'var(--semi-color-danger)',
}}
>
{delta > 0 ? '+' : '-'}
{formatCny(Math.abs(delta), cny, 0)}
</span>
) : null}
</div>
</button>
</Tooltip>
);
})}
</div>
);
};
@@ -0,0 +1,522 @@
/*
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, { useMemo } from 'react';
import {
Button,
Empty,
Input,
Select,
Table,
Tag,
Typography,
} from '@douyinfe/semi-ui';
import { Download, Search, Table2, UserCog } from 'lucide-react';
import { ChangeText, OrgNameCell, SectionCard } from './shared';
import {
ALERT_LEVELS,
ORG_STATUS,
changeRate,
daysSince,
downloadCsv,
formatCny,
formatCst,
orgDisplayName,
quotaToCny,
SEGMENTS,
TIERS,
} from './utils';
const { Text } = Typography;
// ─── 跟进人视图 ───────────────────────────────────────────────────
export const SalesRepTable = ({ reps, cny, onSelect, t }) => {
const m = (v) => <span className='tabular-nums'>{formatCny(v, cny)}</span>;
const count = (color) => (v) =>
v > 0 ? (
<Tag size='small' color={color}>
{v}
</Tag>
) : (
<Text type='tertiary'>0</Text>
);
const columns = [
{
title: t('跟进人'),
dataIndex: 'sales_rep',
width: 120,
fixed: 'left',
render: (v) => (
<button
type='button'
className='text-left font-medium hover:text-brand focus-visible:outline focus-visible:outline-2'
onClick={() => onSelect(v || '__none__')}
>
{v || t('未分配')}
</button>
),
},
{ title: t('企业数'), dataIndex: 'orgs', width: 80, align: 'right' },
{ title: t('活跃企业'), dataIndex: 'active', width: 90, align: 'right' },
{
title: t('本期消耗'),
dataIndex: 'quota',
width: 130,
align: 'right',
render: m,
sorter: (a, b) => a.quota - b.quota,
},
{
title: t('变化'),
dataIndex: 'change',
width: 90,
align: 'right',
render: (_, r) => <ChangeText cur={r.quota} prev={r.prev_quota} t={t} />,
sorter: (a, b) =>
(changeRate(a.quota, a.prev_quota) ?? -Infinity) -
(changeRate(b.quota, b.prev_quota) ?? -Infinity),
},
{
title: t('企业余额'),
dataIndex: 'balance',
width: 130,
align: 'right',
render: m,
},
{
title: t('续费跟进'),
dataIndex: 'renewal',
width: 90,
align: 'center',
render: count('red'),
sorter: (a, b) => a.renewal - b.renewal,
},
{
title: t('流失挽回'),
dataIndex: 'retention',
width: 90,
align: 'center',
render: count('orange'),
sorter: (a, b) => a.retention - b.retention,
},
{
title: t('增长机会'),
dataIndex: 'growth',
width: 90,
align: 'center',
render: count('green'),
sorter: (a, b) => a.growth - b.growth,
},
];
return (
<SectionCard
title={t('跟进人视图')}
icon={<UserCog className='w-5 h-5' />}
extra={
<span className='text-xs text-gray-400'>
{t('点击跟进人筛选下方企业明细')}
</span>
}
>
<Table
columns={columns}
dataSource={reps}
rowKey={(r) => r.sales_rep || '__none__'}
size='small'
scroll={{ x: 920 }}
pagination={
reps.length > 8 ? { pageSize: 8, showSizeChanger: false } : false
}
empty={<Empty description={t('暂无数据')} />}
/>
</SectionCard>
);
};
// ─── 企业明细 ─────────────────────────────────────────────────────
export const EMPTY_DETAIL_FILTER = {
keyword: '',
segment: '',
tier: '',
alert: '',
salesRep: '',
};
const filterOrgs = (orgs, f) => {
const kw = f.keyword.trim().toLowerCase();
return orgs.filter((o) => {
if (kw && !`${o.name || ''} ${o.code || ''}`.toLowerCase().includes(kw))
return false;
if (f.segment && o.segment !== f.segment) return false;
if (f.tier && o.tier !== f.tier) return false;
if (
f.alert === '__any__'
? !o.alert_level
: f.alert && o.alert_level !== f.alert
)
return false;
if (f.salesRep && (o.sales_rep || '__none__') !== f.salesRep) return false;
return true;
});
};
export const OrgDetailTable = ({ report, filter, setFilter, cny, t }) => {
const orgs = useMemo(() => report.orgs || [], [report]);
const rows = useMemo(() => filterOrgs(orgs, filter), [orgs, filter]);
const reps = useMemo(
() =>
Array.from(new Set(orgs.map((o) => o.sales_rep || '__none__'))).sort(),
[orgs],
);
const set = (k) => (v) => setFilter({ ...filter, [k]: v || '' });
const filtered = Object.values(filter).some(Boolean);
const m = (v) => <span className='tabular-nums'>{formatCny(v, cny)}</span>;
const columns = [
{
title: t('企业'),
dataIndex: 'name',
width: 190,
fixed: 'left',
render: (_, r) => <OrgNameCell org={r} t={t} />,
},
{
title: t('跟进人'),
dataIndex: 'sales_rep',
width: 90,
render: (v) =>
v ? (
<span className='truncate'>{v}</span>
) : (
<Text type='tertiary'>—</Text>
),
},
{
title: t('层级'),
dataIndex: 'tier',
width: 64,
render: (v) =>
v ? (
<Tag size='small' color={TIERS[v].color}>
{v}
</Tag>
) : (
<Text type='tertiary'>—</Text>
),
},
{
title: t('健康'),
dataIndex: 'segment',
width: 96,
render: (v) =>
SEGMENTS[v] ? (
<Tag size='small' color={SEGMENTS[v].color}>
{t(SEGMENTS[v].label)}
</Tag>
) : null,
},
{
title: t('本期消耗'),
dataIndex: 'quota',
width: 120,
align: 'right',
render: m,
sorter: (a, b) => a.quota - b.quota,
defaultSortOrder: 'descend',
},
{
title: t('对比期'),
dataIndex: 'prev_quota',
width: 110,
align: 'right',
render: m,
sorter: (a, b) => a.prev_quota - b.prev_quota,
},
{
title: t('变化'),
dataIndex: 'change',
width: 90,
align: 'right',
render: (_, r) => (
<ChangeText cur={r.quota} prev={r.prev_quota} t={t} showNew={false} />
),
sorter: (a, b) => a.quota - a.prev_quota - (b.quota - b.prev_quota),
},
{
title: t('占比'),
dataIndex: 'share',
width: 70,
align: 'right',
render: (v) =>
v > 0 ? (
<span className='tabular-nums'>{v.toFixed(1)}%</span>
) : (
<Text type='tertiary'>—</Text>
),
},
{
title: t('请求数'),
dataIndex: 'requests',
width: 90,
align: 'right',
render: (v) => (v || 0).toLocaleString(),
sorter: (a, b) => a.requests - b.requests,
},
{
title: t('活跃/成员'),
dataIndex: 'active_members',
width: 90,
align: 'right',
render: (v, r) => (
<span className='tabular-nums'>
{v}/{r.member_count}
</span>
),
sorter: (a, b) => a.active_members - b.active_members,
},
{
title: t('余额'),
dataIndex: 'balance',
width: 120,
align: 'right',
render: m,
sorter: (a, b) => a.balance - b.balance,
},
{
title: t('预计可用'),
dataIndex: 'days_left',
width: 90,
align: 'right',
render: (v) =>
v < 0 ? (
<Text type='tertiary'>—</Text>
) : (
<span className='tabular-nums'>
{v < 1 ? t('不足 1 天') : `${v.toFixed(0)} ${t('天')}`}
</span>
),
sorter: (a, b) =>
(a.days_left < 0 ? Infinity : a.days_left) -
(b.days_left < 0 ? Infinity : b.days_left),
},
{
title: t('余额预警'),
dataIndex: 'alert_level',
width: 110,
render: (v) =>
ALERT_LEVELS[v] ? (
<Tag size='small' color={ALERT_LEVELS[v].color}>
{t(ALERT_LEVELS[v].label)}
</Tag>
) : null,
},
{
title: t('最近使用'),
dataIndex: 'last_active',
width: 100,
render: (v) => {
const d = daysSince(v);
return d === null ? (
<Text type='tertiary'>—</Text>
) : d === 0 ? (
t('今天')
) : (
t('{{days}} 天前', { days: d })
);
},
sorter: (a, b) => a.last_active - b.last_active,
},
];
const onExport = () => exportOrgDetail(rows, cny, t);
return (
<SectionCard
id='org-report-detail'
title={t('企业明细')}
icon={<Table2 className='w-5 h-5' />}
extra={
<span className='text-xs text-gray-400 tabular-nums'>
{filtered
? t('筛选 {{count}} / 共 {{total}} 家', {
count: rows.length,
total: orgs.length,
})
: t('共 {{total}} 家', { total: orgs.length })}
</span>
}
>
<div className='flex flex-wrap items-center gap-2 mb-3'>
<Input
prefix={<Search className='w-4 h-4 ml-2 text-gray-400' />}
placeholder={t('搜索企业名称或代码')}
value={filter.keyword}
onChange={set('keyword')}
showClear
style={{ width: 220 }}
/>
<Select
placeholder={t('健康分群')}
value={filter.segment || undefined}
onChange={set('segment')}
showClear
style={{ width: 130 }}
optionList={Object.entries(SEGMENTS).map(([k, v]) => ({
value: k,
label: t(v.label),
}))}
/>
<Select
placeholder={t('价值层级')}
value={filter.tier || undefined}
onChange={set('tier')}
showClear
style={{ width: 110 }}
optionList={Object.entries(TIERS).map(([k, v]) => ({
value: k,
label: t(v.label),
}))}
/>
<Select
placeholder={t('余额预警')}
value={filter.alert || undefined}
onChange={set('alert')}
showClear
style={{ width: 130 }}
optionList={[
{ value: '__any__', label: t('全部预警') },
...Object.entries(ALERT_LEVELS).map(([k, v]) => ({
value: k,
label: t(v.label),
})),
]}
/>
<Select
placeholder={t('跟进人')}
value={filter.salesRep || undefined}
onChange={set('salesRep')}
showClear
filter
style={{ width: 130 }}
optionList={reps.map((r) => ({
value: r,
label: r === '__none__' ? t('未分配') : r,
}))}
/>
{filtered ? (
<Button
type='tertiary'
onClick={() => setFilter(EMPTY_DETAIL_FILTER)}
>
{t('重置')}
</Button>
) : null}
<Button
className='ml-auto'
icon={<Download className='w-4 h-4' />}
onClick={onExport}
disabled={rows.length === 0}
>
{t('导出')}
</Button>
</div>
<Table
columns={columns}
dataSource={rows}
rowKey='org_id'
size='small'
scroll={{ x: 1480 }}
pagination={{
pageSize: 20,
showSizeChanger: true,
pageSizeOpts: [20, 50, 100],
}}
empty={
<Empty
description={filtered ? t('没有符合筛选条件的企业') : t('暂无企业')}
/>
}
/>
</SectionCard>
);
};
export const exportOrgDetail = (rows, cny, t) => {
const yuan = (v) => quotaToCny(v, cny).toFixed(2);
downloadCsv(
`${t('企业经营明细')}-${formatCst(Date.now() / 1000, false)}.csv`,
[
t('企业ID'),
t('企业'),
t('企业代码'),
t('状态'),
t('跟进人'),
t('层级'),
t('健康分群'),
t('本期消耗'),
t('对比期消耗'),
t('变化率'),
t('占比'),
t('请求数'),
t('活跃成员'),
t('成员数'),
t('余额'),
t('赠送余额'),
t('近7日日均消耗'),
t('预计可用天数'),
t('建议充值'),
t('余额预警'),
t('最近使用'),
t('创建时间'),
t('到期时间'),
t('联系人'),
t('联系电话'),
],
rows.map((o) => {
const rate = changeRate(o.quota, o.prev_quota);
return [
o.org_id,
orgDisplayName(o, t),
o.code,
ORG_STATUS[o.status] ? t(ORG_STATUS[o.status].label) : o.status,
o.sales_rep,
o.tier,
SEGMENTS[o.segment] ? t(SEGMENTS[o.segment].label) : '',
yuan(o.quota),
yuan(o.prev_quota),
rate === null ? '' : `${rate.toFixed(1)}%`,
o.share ? `${o.share.toFixed(2)}%` : '',
o.requests,
o.active_members,
o.member_count,
yuan(o.balance),
yuan(o.gift_quota),
yuan(o.daily_avg),
o.days_left < 0 ? '' : o.days_left.toFixed(1),
yuan(o.topup_suggest),
ALERT_LEVELS[o.alert_level] ? t(ALERT_LEVELS[o.alert_level].label) : '',
o.last_active ? formatCst(o.last_active) : '',
formatCst(o.created_at, false),
o.expired_at > 0 ? formatCst(o.expired_at, false) : '',
o.contact_name,
o.contact_phone,
];
}),
);
};
@@ -0,0 +1,213 @@
/*
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, { useCallback, useMemo, useState } from 'react';
import { Button, Card, Typography } from '@douyinfe/semi-ui';
import { ActionCenter, ACTION_TABS } from './ActionCenter';
import {
ChangeAttribution,
TiersAndRankings,
TopModels,
TrendChart,
} from './Analysis';
import { HealthSegments, KeyFindings, KpiGrid, ReportHeader } from './Overview';
import { SectionTitle } from './shared';
import {
EMPTY_DETAIL_FILTER,
exportOrgDetail,
OrgDetailTable,
SalesRepTable,
} from './Tables';
import {
deriveActionLists,
deriveFindings,
deriveSalesReps,
getCnyParams,
} from './utils';
const { Text } = Typography;
// 页签内锚点跳转:顶栏与跑马灯为 fixed,元素上已加 scroll-mt 让位
const scrollToId = (id) => {
const el = document.getElementById(id);
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
};
const ReportSkeleton = () => (
<div className='space-y-4'>
<div className='h-[92px] rounded-xl bg-gray-100 dark:bg-gray-800 animate-pulse' />
<div className='h-[160px] rounded-xl bg-gray-100 dark:bg-gray-800 animate-pulse' />
<div className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3'>
{Array.from({ length: 8 }).map((_, i) => (
<div
key={i}
className='h-[96px] rounded-xl bg-gray-100 dark:bg-gray-800 animate-pulse'
/>
))}
</div>
</div>
);
const OrgReportPanel = ({ report, loading, error, onRetry, t }) => {
const cny = useMemo(getCnyParams, []);
const [actionTab, setActionTab] = useState('renewal');
const [detailFilter, setDetailFilter] = useState(EMPTY_DETAIL_FILTER);
const lists = useMemo(
() => deriveActionLists(report?.orgs, report?.meta),
[report],
);
const findings = useMemo(
() => deriveFindings(report, lists, cny, t),
[report, lists, cny, t],
);
const reps = useMemo(
() => deriveSalesReps(report?.orgs, lists),
[report, lists],
);
const jump = useCallback((target) => {
if (ACTION_TABS.includes(target)) {
setActionTab(target);
scrollToId('org-report-actions');
return;
}
scrollToId(`org-report-${target}`);
}, []);
const filterDetail = useCallback((patch) => {
setDetailFilter({ ...EMPTY_DETAIL_FILTER, ...patch });
scrollToId('org-report-detail');
}, []);
if (!report) {
if (error) {
return (
<Card className='shadow-sm'>
<div className='py-12 flex flex-col items-center gap-3'>
<Text type='danger'>{t('企业经营报表加载失败,请稍后重试')}</Text>
<Button onClick={onRetry} loading={loading}>
{t('重试')}
</Button>
</div>
</Card>
);
}
return <ReportSkeleton />;
}
return (
<div
className={
loading
? 'opacity-60 transition-opacity pointer-events-none'
: 'transition-opacity'
}
>
<ReportHeader
report={report}
onExport={() => exportOrgDetail(report.orgs || [], cny, t)}
t={t}
/>
<KeyFindings findings={findings} onJump={jump} t={t} />
<SectionTitle
index={1}
title={t('核心指标')}
desc={t('本期对比等长对比期;点击卡片定位到相关分析')}
/>
<KpiGrid report={report} lists={lists} cny={cny} onJump={jump} t={t} />
<SectionTitle
index={2}
title={t('客户健康分群')}
desc={t('按本期与对比期的使用变化划分,点击分群筛选企业明细')}
/>
<HealthSegments
report={report}
cny={cny}
activeSegment={detailFilter.segment}
onSelect={(segment) =>
segment
? filterDetail({ segment })
: setDetailFilter(EMPTY_DETAIL_FILTER)
}
t={t}
/>
<SectionTitle
index={3}
title={t('行动清单')}
desc={t('续费、挽回、增长、激活四类待办,含建议动作与联系人')}
/>
<ActionCenter
lists={lists}
activeTab={actionTab}
onTabChange={setActionTab}
cny={cny}
t={t}
/>
<SectionTitle
index={4}
title={t('变化归因')}
desc={t('本期相对对比期的消耗变化由哪些企业、哪些分群贡献')}
/>
<ChangeAttribution report={report} cny={cny} t={t} />
<SectionTitle
index={5}
title={t('客户结构')}
desc={t('ABC 价值分层与头部企业')}
/>
<TiersAndRankings
report={report}
cny={cny}
onSelectTier={(tier) => filterDetail({ tier })}
t={t}
/>
<SectionTitle index={6} title={t('趋势与模型')} />
<div className='grid grid-cols-1 xl:grid-cols-2 gap-4'>
<TrendChart report={report} cny={cny} t={t} />
<TopModels report={report} cny={cny} t={t} />
</div>
<SectionTitle index={7} title={t('团队与明细')} />
<div className='space-y-4 mb-6'>
<SalesRepTable
reps={reps}
cny={cny}
onSelect={(salesRep) => filterDetail({ salesRep })}
t={t}
/>
<OrgDetailTable
report={report}
filter={detailFilter}
setFilter={setDetailFilter}
cny={cny}
t={t}
/>
</div>
</div>
);
};
export default OrgReportPanel;
@@ -0,0 +1,174 @@
/*
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 { Card, Tag, Tooltip } from '@douyinfe/semi-ui';
import { TrendingDown, TrendingUp } from 'lucide-react';
import { changeRate, ORG_STATUS, orgDisplayName, REASONS } from './utils';
export const SectionCard = ({
id,
title,
icon,
extra,
children,
bodyStyle,
}) => (
<Card
id={id}
className='shadow-sm h-full scroll-mt-24'
title={
<div className='flex items-center gap-2 flex-wrap min-w-0'>
<span className='text-brand flex-shrink-0'>{icon}</span>
<span className='font-semibold'>{title}</span>
{extra}
</div>
}
bodyStyle={{ padding: '16px', ...bodyStyle }}
>
{children}
</Card>
);
export const SectionTitle = ({ id, index, title, desc }) => (
<div
id={id}
className='flex items-baseline gap-2 mb-3 mt-8 flex-wrap scroll-mt-24'
>
{index ? (
<span className='text-xs font-semibold tracking-wider text-brand tabular-nums'>
{String(index).padStart(2, '0')}
</span>
) : null}
<h3 className='text-base font-semibold text-gray-800 dark:text-gray-100'>
{title}
</h3>
{desc ? (
<span className='text-xs text-gray-500 dark:text-gray-400'>{desc}</span>
) : null}
</div>
);
// 变化值:上升绿、下降红;对比期为 0 时无法计算
export const ChangeText = ({ cur, prev, t, size = 'xs', showNew = true }) => {
const rate = changeRate(cur, prev);
const sizeClass = size === 'sm' ? 'text-sm' : 'text-xs';
if (rate === null) {
return cur > 0 && showNew ? (
<span className={`${sizeClass} text-gray-400`}>{t('对比期无数据')}</span>
) : (
<span className={`${sizeClass} text-gray-400`}>—</span>
);
}
const up = rate >= 0;
return (
<span
className={`inline-flex items-center gap-0.5 ${sizeClass} font-medium tabular-nums`}
style={{
color: up ? 'var(--semi-color-success)' : 'var(--semi-color-danger)',
}}
>
{up ? (
<TrendingUp className='w-3 h-3' />
) : (
<TrendingDown className='w-3 h-3' />
)}
{up ? '+' : ''}
{rate.toFixed(1)}%
</span>
);
};
export const KpiCard = ({
title,
value,
sub,
compare,
tip,
accent,
onClick,
}) => (
<Card
className={`shadow-sm border-none transition-shadow ${onClick ? 'cursor-pointer hover:shadow-md' : ''}`}
bodyStyle={{ padding: '14px 16px' }}
onClick={onClick}
style={{
borderLeft: `3px solid ${accent || 'var(--semi-color-primary)'}`,
}}
>
<div className='flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 mb-1'>
<span className='truncate'>{title}</span>
{tip ? (
<Tooltip content={tip}>
<span className='cursor-help text-gray-400'>ⓘ</span>
</Tooltip>
) : null}
</div>
<div className='text-xl font-bold text-gray-800 dark:text-gray-100 tabular-nums truncate'>
{value}
</div>
<div className='flex items-center justify-between gap-2 mt-1 min-h-[18px]'>
<span className='text-xs text-gray-500 dark:text-gray-400 truncate'>
{sub}
</span>
{compare}
</div>
</Card>
);
export const OrgNameCell = ({ org, t, showCode = true }) => {
const name = orgDisplayName(org, t);
const status = ORG_STATUS[org.status];
return (
<div className='min-w-0'>
<div className='flex items-center gap-1.5 min-w-0'>
<span className='font-medium truncate' title={name}>
{name}
</span>
{!org.deleted && status && org.status !== 1 ? (
<Tag size='small' color={status.color} className='flex-shrink-0'>
{t(status.label)}
</Tag>
) : null}
</div>
{showCode && org.code ? (
<div className='text-xs text-gray-400 truncate'>{org.code}</div>
) : null}
</div>
);
};
export const ReasonTags = ({ reasons, t }) => (
<div className='flex flex-wrap gap-1'>
{(reasons || []).map((r) => (
<Tag key={r} size='small' color={REASONS[r]?.color || 'grey'}>
{t(REASONS[r]?.label || r)}
</Tag>
))}
</div>
);
export const EmptyBlock = ({ height = 240, text }) => (
<div
className='flex items-center justify-center text-gray-400 text-sm'
style={{ height }}
>
{text}
</div>
);
+470
View File
@@ -0,0 +1,470 @@
/*
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
*/
// 企业经营决策报表:口径常量、行动清单派生、要点生成、CSV 导出
// ─── 金额 ───────────────────────────────────────────────────────
// 货币统一显示人民币:额度 → CNY = quota / quota_per_unit × usd_exchange_rate
export const getCnyParams = () => {
let quotaPerUnit = parseFloat(localStorage.getItem('quota_per_unit'));
if (!quotaPerUnit || quotaPerUnit <= 0) quotaPerUnit = 500000;
let usdRate = 1;
try {
const s = JSON.parse(localStorage.getItem('status') || '{}');
usdRate = s?.usd_exchange_rate || 1;
} catch (e) {
usdRate = 1;
}
return { quotaPerUnit, usdRate };
};
export const quotaToCny = (quota, { quotaPerUnit, usdRate }) =>
((quota || 0) / quotaPerUnit) * usdRate;
export const formatCny = (quota, params, digits = 2) =>
`¥${quotaToCny(quota, params).toLocaleString(undefined, {
minimumFractionDigits: digits,
maximumFractionDigits: digits,
})}`;
// 环比(%);对比期为 0 时无法计算返回 null
export const changeRate = (cur, prev) =>
prev > 0 ? (((cur || 0) - prev) / prev) * 100 : null;
export const formatRate = (rate) =>
rate === null || rate === undefined
? '—'
: `${rate >= 0 ? '+' : ''}${rate.toFixed(1)}%`;
export const pct = (part, total) => (total > 0 ? (part / total) * 100 : 0);
// ─── 时间(报表口径统一为 UTC+8,与浏览器时区无关) ─────────────────
const pad = (n) => String(n).padStart(2, '0');
export const formatCst = (ts, withTime = true) => {
if (!ts) return '—';
const d = new Date((ts + 8 * 3600) * 1000);
const date = `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
return withTime
? `${date} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`
: date;
};
export const daysSince = (ts, now = Date.now() / 1000) =>
ts > 0 ? Math.max(0, Math.floor((now - ts) / 86400)) : null;
// ─── 标签字典 ────────────────────────────────────────────────────
export const ORG_STATUS = {
1: { label: '正常', color: 'green' },
2: { label: '冻结', color: 'grey' },
3: { label: '欠费', color: 'red' },
4: { label: '待激活', color: 'blue' },
};
export const SEGMENTS = {
new: { label: '新客起量', color: 'cyan', desc: '本期首次使用' },
growing: { label: '增长', color: 'green', desc: '消耗环比增长 ≥ 20%' },
stable: { label: '稳定', color: 'blue', desc: '消耗环比波动 < 20%' },
recovered: { label: '回流', color: 'teal', desc: '对比期无使用,本期恢复' },
declining: { label: '下滑', color: 'orange', desc: '消耗环比下降 ≥ 20%' },
stopped: { label: '停用', color: 'red', desc: '对比期有使用,本期无使用' },
dormant: { label: '沉睡', color: 'grey', desc: '两期均无使用,历史用过' },
never_used: {
label: '从未使用',
color: 'violet',
desc: '开通后从未产生调用',
},
pending: { label: '待激活', color: 'light-blue', desc: '等待平台激活' },
frozen: { label: '冻结', color: 'grey', desc: '已被冻结' },
};
export const ALERT_LEVELS = {
exhausted: { label: '余额耗尽', color: 'red', rank: 0 },
critical: { label: '3 天内耗尽', color: 'orange', rank: 1 },
threshold: { label: '低于预警线', color: 'amber', rank: 2 },
warning: { label: '即将不足', color: 'yellow', rank: 3 },
};
export const TIERS = {
A: { label: 'A 类', color: 'red', desc: '累计贡献前 80% 消耗' },
B: { label: 'B 类', color: 'orange', desc: '累计贡献 80%~95%' },
C: { label: 'C 类', color: 'grey', desc: '其余长尾企业' },
};
// 行动原因 → 标签与建议动作(顺序即优先级)
export const REASONS = {
exhausted: {
label: '余额耗尽',
color: 'red',
action: '立即联系充值,避免业务中断',
},
critical: { label: '3 天内耗尽', color: 'orange', action: '3 天内跟进续费' },
expired: { label: '合同已到期', color: 'red', action: '确认续约方案' },
threshold: {
label: '低于预警线',
color: 'amber',
action: '提醒企业补充余额',
},
warning: { label: '即将不足', color: 'yellow', action: '本周内沟通续费计划' },
expiring: { label: '30 天内到期', color: 'orange', action: '推进续约' },
stopped: { label: '本期停用', color: 'red', action: '回访了解停用原因' },
sharp_decline: {
label: '近 7 日腰斩',
color: 'red',
action: '回访排查使用下降原因',
},
declining: {
label: '消耗下滑',
color: 'orange',
action: '回访排查使用下降原因',
},
dormant: {
label: '近期沉睡',
color: 'grey',
action: '唤醒沟通,推送新模型与新功能',
},
fast_growth: {
label: '高速增长',
color: 'green',
action: '跟进扩容与年度方案',
},
growing: { label: '稳步增长', color: 'green', action: '跟进扩容与年度方案' },
new: { label: '新客起量', color: 'cyan', action: '新客关怀,确认使用顺畅' },
recovered: { label: '回流', color: 'teal', action: '回流客户关怀,巩固使用' },
low_penetration: {
label: '成员渗透低',
color: 'violet',
action: '推动内部推广、组织培训',
},
pending: { label: '待激活', color: 'light-blue', action: '协助完成企业激活' },
never_used: {
label: '开通未使用',
color: 'violet',
action: '引导创建令牌、完成首次调用',
},
};
const isServing = (o) => !o.deleted && (o.status === 1 || o.status === 3);
// ─── 行动清单 ────────────────────────────────────────────────────
const withReasons = (o, reasons) => ({
...o,
reasons,
action: reasons.length ? REASONS[reasons[0]].action : '',
});
export const deriveActionLists = (orgs, meta) => {
const renewal = [];
const retention = [];
const growth = [];
const activation = [];
// 沉睡只关注「最近 60 天内还用过」的,太久远的不值得逐个跟进
const dormantCutoff = (meta?.start || 0) - 60 * 86400;
(orgs || []).forEach((o) => {
if (o.deleted) return;
const flags = o.flags || [];
// 续费跟进
if (isServing(o)) {
const r = [];
if (o.alert_level) r.push(o.alert_level);
if (flags.includes('expired')) r.push('expired');
if (flags.includes('expiring')) r.push('expiring');
if (r.length) {
r.sort(
(a, b) =>
Object.keys(REASONS).indexOf(a) - Object.keys(REASONS).indexOf(b),
);
renewal.push(withReasons(o, r));
}
}
// 流失挽回
if (isServing(o)) {
const r = [];
if (o.segment === 'stopped') r.push('stopped');
if (flags.includes('sharp_decline')) r.push('sharp_decline');
if (o.segment === 'declining') r.push('declining');
if (
o.segment === 'dormant' &&
o.last_active >= dormantCutoff &&
o.last_active > 0
)
r.push('dormant');
if (r.length) retention.push(withReasons(o, r));
}
// 增长机会
if (isServing(o)) {
const r = [];
const rate = changeRate(o.quota, o.prev_quota);
if (o.segment === 'growing')
r.push(rate !== null && rate >= 50 ? 'fast_growth' : 'growing');
if (o.segment === 'new') r.push('new');
if (o.segment === 'recovered') r.push('recovered');
if (flags.includes('low_penetration')) r.push('low_penetration');
if (r.length) growth.push(withReasons(o, r));
}
// 激活跟进
if (
o.segment === 'pending' ||
(o.segment === 'never_used' && isServing(o))
) {
activation.push(withReasons(o, [o.segment]));
}
});
const reasonRank = (o) => Object.keys(REASONS).indexOf(o.reasons[0]);
renewal.sort(
(a, b) =>
reasonRank(a) - reasonRank(b) ||
(a.days_left < 0) - (b.days_left < 0) ||
a.days_left - b.days_left ||
b.daily_avg - a.daily_avg,
);
const atRisk = (o) =>
Math.max(
(o.prev_quota || 0) - (o.quota || 0),
(o.prior7_quota || 0) - (o.recent7_quota || 0),
);
retention.sort((a, b) => atRisk(b) - atRisk(a));
growth.sort((a, b) => (b.quota || 0) - (a.quota || 0));
activation.sort((a, b) => (b.created_at || 0) - (a.created_at || 0));
return { renewal, retention, growth, activation, atRisk };
};
// ─── 跟进人视图 ──────────────────────────────────────────────────
export const deriveSalesReps = (orgs, lists) => {
const idsOf = (list) => new Set(list.map((o) => o.org_id));
const renewalIds = idsOf(lists.renewal);
const retentionIds = idsOf(lists.retention);
const growthIds = idsOf(lists.growth);
const map = new Map();
(orgs || []).forEach((o) => {
if (o.deleted) return;
const key = o.sales_rep || '';
if (!map.has(key)) {
map.set(key, {
sales_rep: key,
orgs: 0,
active: 0,
quota: 0,
prev_quota: 0,
renewal: 0,
retention: 0,
growth: 0,
balance: 0,
});
}
const r = map.get(key);
r.orgs += 1;
if (o.requests > 0) r.active += 1;
r.quota += o.quota || 0;
r.prev_quota += o.prev_quota || 0;
r.balance += o.balance || 0;
if (renewalIds.has(o.org_id)) r.renewal += 1;
if (retentionIds.has(o.org_id)) r.retention += 1;
if (growthIds.has(o.org_id)) r.growth += 1;
});
return Array.from(map.values()).sort((a, b) => b.quota - a.quota);
};
// ─── 本期要点(结论先行) ────────────────────────────────────────
// 返回 [{ level: 'danger'|'warning'|'success'|'info', text, target }],text 已翻译
export const deriveFindings = (report, lists, cny, t) => {
if (!report) return [];
const k = report.kpi || {};
const orgs = report.orgs || [];
const out = [];
const money = (q) => formatCny(q, cny, 0);
// 1. 消耗变化与主要贡献者
const rate = changeRate(k.org_quota, k.prev_org_quota);
const deltas = orgs
.filter((o) => !o.deleted)
.map((o) => ({ name: o.name, d: (o.quota || 0) - (o.prev_quota || 0) }));
const up = deltas
.filter((x) => x.d > 0)
.sort((a, b) => b.d - a.d)
.slice(0, 2);
const down = deltas
.filter((x) => x.d < 0)
.sort((a, b) => a.d - b.d)
.slice(0, 2);
if (rate !== null) {
const drivers = (rate >= 0 ? up : down)
.map((x) => `${x.name} (${x.d > 0 ? '+' : '-'}${money(Math.abs(x.d))})`)
.join(', ');
const params = {
amount: money(k.org_quota),
rate: formatRate(rate),
drivers,
};
let text;
if (!drivers) {
text = t('企业消耗 {{amount}},较对比期 {{rate}}', params);
} else if (rate >= 0) {
text = t(
'企业消耗 {{amount}},较对比期 {{rate}},增长主要来自 {{drivers}}',
params,
);
} else {
text = t(
'企业消耗 {{amount}},较对比期 {{rate}},下滑主要来自 {{drivers}}',
params,
);
}
out.push({
level: rate >= 0 ? 'success' : 'warning',
text,
target: 'attribution',
});
} else if (k.org_quota > 0) {
out.push({
level: 'info',
text: t('企业消耗 {{amount}},对比期无消耗数据', {
amount: money(k.org_quota),
}),
target: 'attribution',
});
}
// 2. 续费风险
const urgent = lists.renewal.filter((o) =>
['exhausted', 'critical'].includes(o.alert_level),
).length;
if (lists.renewal.length > 0) {
out.push({
level: urgent > 0 ? 'danger' : 'warning',
text: t(
'{{count}} 家企业需续费跟进({{urgent}} 家已耗尽或 3 天内耗尽),未来 30 天充值缺口约 {{gap}}',
{ count: lists.renewal.length, urgent, gap: money(k.topup_gap_30d) },
),
target: 'renewal',
});
}
// 3. 流失风险
if (lists.retention.length > 0) {
const exposure = lists.retention.reduce((s, o) => s + lists.atRisk(o), 0);
out.push({
level: 'warning',
text: t(
'{{count}} 家企业存在流失风险(停用 / 下滑 / 沉睡),涉及消耗减少约 {{amount}}',
{
count: lists.retention.length,
amount: money(exposure),
},
),
target: 'retention',
});
}
// 4. 本月预测
if (k.month_to_date > 0 || k.last_month_quota > 0) {
const mRate = changeRate(k.month_forecast, k.last_month_quota);
out.push({
level: mRate !== null && mRate < 0 ? 'warning' : 'info',
text: t(
'按近 7 日日均 {{runRate}} 推算,本月企业消耗预计 {{forecast}},上月 {{last}}({{rate}})',
{
runRate: money(k.run_rate_daily),
forecast: money(k.month_forecast),
last: money(k.last_month_quota),
rate: formatRate(mRate),
},
),
target: 'kpi',
});
}
// 5. 集中度
if (k.org_quota > 0 && k.active_orgs >= 5) {
out.push({
level: k.top5_share >= 60 ? 'warning' : 'info',
text:
k.top5_share >= 60
? t(
'头部依赖较高:Top5 企业贡献 {{share}} 的企业消耗,需关注大客户稳定性',
{
share: `${k.top5_share.toFixed(1)}%`,
},
)
: t('客户结构较分散:Top5 企业贡献 {{share}} 的企业消耗', {
share: `${k.top5_share.toFixed(1)}%`,
}),
target: 'tiers',
});
}
// 6. 渗透与激活
const lowPen = lists.growth.filter((o) =>
o.reasons.includes('low_penetration'),
).length;
const penetration = pct(k.active_members, k.total_members);
if (k.total_members > 0 && (penetration < 50 || lowPen > 0)) {
out.push({
level: 'info',
text: t(
'企业成员渗透率 {{rate}},{{count}} 家企业成员活跃率低于 30%,存在增量空间',
{
rate: `${Math.min(100, penetration).toFixed(1)}%`,
count: lowPen,
},
),
target: 'growth',
});
}
if (lists.activation.length > 0) {
out.push({
level: 'info',
text: t('{{count}} 家企业待激活或开通后从未使用,建议安排激活跟进', {
count: lists.activation.length,
}),
target: 'activation',
});
}
return out;
};
// ─── CSV 导出(带 BOM,Excel 直接打开不乱码) ─────────────────────
export const downloadCsv = (filename, headers, rows) => {
const escape = (v) => {
const s = v === null || v === undefined ? '' : String(v);
return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
};
const lines = [headers.map(escape).join(',')];
rows.forEach((r) => lines.push(r.map(escape).join(',')));
const blob = new Blob(['' + lines.join('\r\n')], {
type: 'text/csv;charset=utf-8;',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
export const orgDisplayName = (o, t) =>
o.deleted ? `${t('已删除企业')} #${o.org_id}` : o.name || `#${o.org_id}`;