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,157 @@
/*
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, { useState } from 'react';
import { Card, Table, Progress } from '@douyinfe/semi-ui';
import { renderQuota } from '../../helpers';
const ChannelConsumption = ({ data, title, icon, t }) => {
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
if (!data || data.length === 0) {
return (
<Card
className='shadow-sm hover:shadow-md transition-shadow'
title={
<div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span>
</div>
}
bodyStyle={{ padding: '16px' }}
>
<div className='h-[300px] flex items-center justify-center text-gray-400'>
{t('暂无数据')}
</div>
</Card>
);
}
// 计算最大值用于进度条
const maxQuota = Math.max(...data.map((item) => item.quota || 0));
// 计算全局序号
const getGlobalIndex = (pageIndex) =>
(currentPage - 1) * pageSize + pageIndex;
const columns = [
{
title: '#',
dataIndex: 'index',
key: 'index',
width: 50,
render: (_, record, index) => {
const globalIndex = getGlobalIndex(index);
return (
<span
className={`font-medium ${globalIndex < 3 ? 'text-orange-500' : 'text-gray-500'}`}
>
{globalIndex + 1}
</span>
);
},
},
{
title: t('渠道名称'),
dataIndex: 'channel_name',
key: 'channel_name',
render: (text) => (
<span className='font-medium truncate' title={text}>
{text || t('未知渠道')}
</span>
),
},
{
title: t('消耗额度'),
dataIndex: 'quota',
key: 'quota',
width: 180,
render: (val, record) => (
<div className='flex items-center gap-2'>
<Progress
percent={(val / maxQuota) * 100}
showInfo={false}
size='small'
style={{ width: 80, height: 6 }}
stroke='#3b82f6'
/>
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
{renderQuota(val || 0)}
</span>
</div>
),
},
{
title: t('请求次数'),
dataIndex: 'count',
key: 'count',
width: 100,
align: 'right',
render: (val) => (
<span className='text-gray-600'>{(val || 0).toLocaleString()}</span>
),
},
{
title: t('占比'),
dataIndex: 'percent',
key: 'percent',
width: 80,
align: 'right',
render: (val) => (
<span className='text-gray-500'>{(val || 0).toFixed(1)}%</span>
),
},
];
return (
<Card
className='shadow-sm hover:shadow-md transition-shadow'
title={
<div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span>
<span className='text-xs text-gray-400 ml-2'>TOP {data.length}</span>
</div>
}
bodyStyle={{ padding: '0' }}
>
<Table
columns={columns}
dataSource={data}
pagination={{
currentPage,
pageSize,
showSizeChanger: true,
pageSizeOpts: [10, 20, 30],
showTotal: (total) => `${t('共')} ${total} ${t('条')}`,
onPageChange: (page) => setCurrentPage(page),
onPageSizeChange: (size) => {
setPageSize(size);
setCurrentPage(1);
},
}}
size='small'
rowKey={(record, index) => `${record.channel_name}-${index}`}
/>
</Card>
);
};
export default ChannelConsumption;
@@ -0,0 +1,202 @@
/*
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, Table, Button } from '@douyinfe/semi-ui';
import { IconDownload } from '@douyinfe/semi-icons';
import { renderQuota } from '../../helpers';
const DailyStatsTable = ({ data, title, icon, t }) => {
const columns = [
{
title: t('日期'),
dataIndex: 'date',
key: 'date',
width: 120,
fixed: 'left',
render: (text) => <span className='font-medium'>{text}</span>,
},
{
title: t('新增用户'),
dataIndex: 'new_users',
key: 'new_users',
width: 100,
align: 'right',
render: (val) => (
<span className='text-green-600'>{(val || 0).toLocaleString()}</span>
),
},
{
title: t('活跃用户'),
dataIndex: 'active_users',
key: 'active_users',
width: 100,
align: 'right',
render: (val) => (
<span className='text-blue-600'>{(val || 0).toLocaleString()}</span>
),
},
{
title: t('充值人数'),
dataIndex: 'topup_users',
key: 'topup_users',
width: 100,
align: 'right',
render: (val) => <span>{(val || 0).toLocaleString()}</span>,
},
{
title: t('充值金额'),
dataIndex: 'topup_amount',
key: 'topup_amount',
width: 120,
align: 'right',
render: (val) => (
<span className='text-yellow-600 font-medium'>
¥{(val || 0).toFixed(2)}
</span>
),
},
{
title: t('消耗额度'),
dataIndex: 'consume_quota',
key: 'consume_quota',
width: 120,
align: 'right',
render: (val) => (
<span className='text-brand-deep font-medium'>
{renderQuota(val || 0)}
</span>
),
},
{
title: t('请求次数'),
dataIndex: 'requests',
key: 'requests',
width: 120,
align: 'right',
render: (val) => <span>{(val || 0).toLocaleString()}</span>,
},
{
title: t('Token消耗'),
dataIndex: 'tokens',
key: 'tokens',
width: 120,
align: 'right',
render: (val) => {
const tokens = val || 0;
if (tokens >= 1000000) {
return <span>{(tokens / 1000000).toFixed(2)}M</span>;
} else if (tokens >= 1000) {
return <span>{(tokens / 1000).toFixed(1)}K</span>;
}
return <span>{tokens.toLocaleString()}</span>;
},
},
{
title: t('人均消耗'),
dataIndex: 'avg_consume',
key: 'avg_consume',
width: 120,
align: 'right',
render: (val) => (
<span className='text-gray-600'>{renderQuota(val || 0)}</span>
),
},
];
// 导出CSV
const handleExport = () => {
if (!data || data.length === 0) return;
const headers = [
t('日期'),
t('新增用户'),
t('活跃用户'),
t('充值人数'),
t('充值金额'),
t('消耗额度'),
t('请求次数'),
t('Token消耗'),
t('人均消耗'),
];
const rows = data.map((row) => [
row.date,
row.new_users || 0,
row.active_users || 0,
row.topup_users || 0,
row.topup_amount || 0,
row.consume_quota || 0,
row.requests || 0,
row.tokens || 0,
row.avg_consume || 0,
]);
const csvContent =
'\uFEFF' +
[headers.join(','), ...rows.map((row) => row.join(','))].join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = `analytics_${new Date().toISOString().split('T')[0]}.csv`;
link.click();
};
return (
<Card
className='shadow-sm hover:shadow-md transition-shadow'
title={
<div className='flex items-center justify-between w-full'>
<div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span>
</div>
<Button
icon={<IconDownload />}
size='small'
onClick={handleExport}
disabled={!data || data.length === 0}
>
{t('导出CSV')}
</Button>
</div>
}
bodyStyle={{ padding: '0' }}
>
<Table
columns={columns}
dataSource={data || []}
pagination={{
pageSize: 10,
showSizeChanger: true,
showTotal: (total) => `${t('共')} ${total} ${t('条')}`,
}}
scroll={{ x: 1100 }}
size='small'
rowKey='date'
empty={
<div className='py-8 text-center text-gray-400'>{t('暂无数据')}</div>
}
/>
</Card>
);
};
export default DailyStatsTable;
@@ -0,0 +1,377 @@
/*
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, useState } from 'react';
import {
Card,
Table,
Tag,
Button,
InputNumber,
Select,
Space,
Modal,
Input,
Typography,
} from '@douyinfe/semi-ui';
import {
IconRefresh,
IconAlertTriangle,
IconShieldStroked,
} from '@douyinfe/semi-icons';
import { renderQuota } from '../../helpers';
const { Text } = Typography;
const formatTime = (ts) => {
if (!ts) return '-';
const d = new Date(ts * 1000);
const pad = (n) => (n < 10 ? '0' + n : '' + n);
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
};
/**
* 高频低消耗用户监测组件
*
* 列:用户ID / 昵称 / 请求次数 / 总消耗 / 平均消耗 / 状态 / 最常用模型 / 最近IP / 最近活跃 / 操作
*/
const HighFreqLowCostUsers = ({
loading,
items,
windowRange,
filters,
setFilters,
fetchSuspects,
rules,
unbanUser,
onOpenRuleModal,
t,
}) => {
const [unbanModalVisible, setUnbanModalVisible] = useState(false);
const [unbanRow, setUnbanRow] = useState(null);
const [unbanReason, setUnbanReason] = useState('');
// 当前启用规则(仅取 enabled=true 的规则)—用于"是否命中封号阈值"标签
// 不回落到禁用规则:否则会显示"待自动封号"红色 tag 但实际永不封号,误导管理员
const activeRule = useMemo(
() => (rules || []).find((r) => r.enabled),
[rules],
);
const evalRowStatus = (row) => {
// 状态优先级:已自动封号 > 命中封号阈值(待下次扫描)> 命中预警 > 仅满足查询条件
if (row.user_status !== undefined && row.user_status === 2) {
return { level: 'banned', label: t('已封号'), color: 'red' };
}
if (!activeRule)
return { level: 'hit', label: t('命中筛选'), color: 'grey' };
// 仅当规则的"自动封号"总开关启用时,才判断是否命中封号阈值
const meetsBan =
activeRule.auto_ban_enabled &&
activeRule.ban_min_requests > 0 &&
row.request_count >= activeRule.ban_min_requests &&
(activeRule.ban_max_avg_quota <= 0 ||
row.avg_quota <= activeRule.ban_max_avg_quota) &&
(activeRule.ban_max_total_quota <= 0 ||
row.total_quota <= activeRule.ban_max_total_quota);
if (meetsBan) return { level: 'ban', label: t('待自动封号'), color: 'red' };
const meetsWarn =
activeRule.warn_min_requests > 0 &&
row.request_count >= activeRule.warn_min_requests &&
(activeRule.warn_max_avg_quota <= 0 ||
row.avg_quota <= activeRule.warn_max_avg_quota);
if (meetsWarn) return { level: 'warn', label: t('预警'), color: 'orange' };
return { level: 'hit', label: t('命中筛选'), color: 'grey' };
};
const columns = [
{
title: t('用户ID'),
dataIndex: 'user_id',
width: 100,
render: (v) => <Text>{v}</Text>,
},
{
title: t('昵称'),
dataIndex: 'display_name',
width: 160,
render: (v, row) => (
<div className='flex flex-col'>
<Text strong>{v || row.username || `user_${row.user_id}`}</Text>
{row.username && v && row.username !== v && (
<Text type='tertiary' size='small'>
@{row.username}
</Text>
)}
</div>
),
},
{
title: t('请求次数'),
dataIndex: 'request_count',
width: 110,
sorter: (a, b) => a.request_count - b.request_count,
defaultSortOrder: 'descend',
render: (v) => <Text strong>{v.toLocaleString()}</Text>,
},
{
title: t('总消耗'),
dataIndex: 'total_quota',
width: 120,
sorter: (a, b) => a.total_quota - b.total_quota,
render: (v) => <Text>{renderQuota(v, 4)}</Text>,
},
{
title: t('平均消耗'),
dataIndex: 'avg_quota',
width: 130,
sorter: (a, b) => a.avg_quota - b.avg_quota,
render: (v) => (
<Text type={v < 100 ? 'danger' : 'primary'}>{renderQuota(v, 6)}</Text>
),
},
{
title: t('状态'),
width: 110,
render: (_v, row) => {
const s = evalRowStatus(row);
return <Tag color={s.color}>{s.label}</Tag>;
},
},
{
title: t('最常用模型'),
dataIndex: 'top_model',
width: 160,
render: (v) =>
v ? <Tag color='blue'>{v}</Tag> : <Text type='tertiary'>-</Text>,
},
{
title: t('活跃 IP'),
dataIndex: 'last_ip',
width: 130,
render: (v) => (v ? <Text>{v}</Text> : <Text type='tertiary'>-</Text>),
},
{
title: t('最近活跃'),
dataIndex: 'last_active_at',
width: 150,
render: (v) => formatTime(v),
},
{
title: t('操作'),
width: 130,
render: (_v, row) => {
const isBanned = row.user_status === 2;
const isRiskBan = isBanned && row.ban_log_id > 0;
if (isRiskBan) {
return (
<Button
size='small'
type='primary'
theme='light'
onClick={() => {
setUnbanRow(row);
setUnbanReason('');
setUnbanModalVisible(true);
}}
>
{t('解封')}
</Button>
);
}
if (isBanned) {
return (
<Text type='tertiary' size='small'>
{t('已被手动封号')}
</Text>
);
}
return (
<Text type='tertiary' size='small'>
{t('监测中')}
</Text>
);
},
},
];
const windowOptions = [
{ value: 60, label: t('最近 1 小时') },
{ value: 360, label: t('最近 6 小时') },
{ value: 1440, label: t('最近 24 小时') },
{ value: 4320, label: t('最近 3 天') },
{ value: 10080, label: t('最近 7 天') },
];
return (
<Card
className='shadow-sm hover:shadow-md transition-shadow'
title={
<div className='flex items-center justify-between flex-wrap gap-2'>
<div className='flex items-center gap-2'>
<IconAlertTriangle className='text-orange-500' />
<span className='font-semibold'>{t('高频低消耗用户监测')}</span>
{windowRange && windowRange.start > 0 && (
<Text type='tertiary' size='small' className='ml-2'>
{formatTime(windowRange.start)} ~ {formatTime(windowRange.end)}
</Text>
)}
</div>
<Space>
<Button
icon={<IconShieldStroked />}
onClick={onOpenRuleModal}
type='tertiary'
>
{t('风控规则')}
</Button>
<Button
icon={<IconRefresh />}
onClick={() => fetchSuspects()}
loading={loading}
>
{t('刷新')}
</Button>
</Space>
</div>
}
bodyStyle={{ padding: '16px' }}
>
{/* 筛选区 */}
<div className='mb-4 grid grid-cols-2 sm:grid-cols-4 gap-3 items-end'>
<div>
<div className='text-xs text-gray-500 mb-1'>{t('时间窗')}</div>
<Select
value={filters.windowMinutes}
onChange={(v) => setFilters((f) => ({ ...f, windowMinutes: v }))}
optionList={windowOptions}
style={{ width: '100%' }}
/>
</div>
<div>
<div className='text-xs text-gray-500 mb-1'>{t('请求次数 ≥')}</div>
<InputNumber
value={filters.minRequests}
onChange={(v) => setFilters((f) => ({ ...f, minRequests: v || 0 }))}
min={1}
style={{ width: '100%' }}
/>
</div>
<div>
<div className='text-xs text-gray-500 mb-1'>
{t('平均消耗 ≤ (quota,0=不限)')}
</div>
<InputNumber
value={filters.maxAvgQuota}
onChange={(v) => setFilters((f) => ({ ...f, maxAvgQuota: v || 0 }))}
min={0}
style={{ width: '100%' }}
/>
</div>
<div className='flex gap-2'>
<Button
type='primary'
theme='solid'
onClick={() => fetchSuspects()}
loading={loading}
block
>
{t('查询')}
</Button>
</div>
</div>
{(filters.maxAvgQuota > 0 || filters.maxTotalQuota > 0) && (
<div className='mb-3 text-xs text-gray-500'>
{filters.maxAvgQuota > 0 && (
<span>
{t('平均消耗 ≤')} {renderQuota(filters.maxAvgQuota, 6)}
{' '}
</span>
)}
{filters.maxTotalQuota > 0 && (
<span>
{t('总消耗 ≤')} {renderQuota(filters.maxTotalQuota, 4)}
</span>
)}
</div>
)}
<Table
columns={columns}
dataSource={items}
rowKey='user_id'
loading={loading}
pagination={{ pageSize: 20, showTotal: true }}
empty={t('暂无数据')}
scroll={{ x: 1200 }}
/>
<Modal
title={t('解封用户')}
visible={unbanModalVisible}
onCancel={() => setUnbanModalVisible(false)}
onOk={async () => {
if (!unbanRow) return;
// unbanUser 内部会并发刷新 suspects + banLogs,无需在此重复 fetch
const ok = await unbanUser({
userId: unbanRow.user_id,
banLogId: unbanRow.ban_log_id,
reason: unbanReason,
});
if (ok) {
setUnbanModalVisible(false);
}
}}
okText={t('确认解封')}
cancelText={t('取消')}
>
{unbanRow && (
<div className='space-y-3'>
<div>
<Text type='tertiary'>{t('用户:')}</Text>
<Text strong>
{unbanRow.display_name || unbanRow.username}(ID:
{unbanRow.user_id})
</Text>
</div>
<div>
<Text type='tertiary'>
{t(
'解封后用户账号会恢复,但被禁用的 Token 不会自动启用,需手动开启。',
)}
</Text>
</div>
<div>
<div className='text-xs text-gray-500 mb-1'>{t('解封原因')}</div>
<Input.TextArea
value={unbanReason}
onChange={setUnbanReason}
placeholder={t('记录解封原因,便于审计')}
rows={3}
/>
</div>
</div>
)}
</Modal>
</Card>
);
};
export default HighFreqLowCostUsers;
@@ -0,0 +1,142 @@
/*
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 { Card } from '@douyinfe/semi-ui';
import { VChart } from '@visactor/react-vchart';
import { renderQuota } from '../../helpers';
const ModelDistribution = ({ data, title, icon, t }) => {
const pieSpec = useMemo(() => {
if (!data || data.length === 0) return null;
const chartData = data.slice(0, 8).map((item) => ({
name: item.model_name || t('未知'),
value: item.quota || 0,
}));
// 如果有更多数据,合并为"其他"
if (data.length > 8) {
const otherQuota = data
.slice(8)
.reduce((sum, item) => sum + (item.quota || 0), 0);
chartData.push({ name: t('其他'), value: otherQuota });
}
return {
type: 'pie',
data: [{ id: 'modelDist', values: chartData }],
valueField: 'value',
categoryField: 'name',
outerRadius: 0.8,
innerRadius: 0.5,
padAngle: 0.02,
pie: {
style: {
cornerRadius: 4,
},
},
tooltip: {
mark: {
content: [
{
key: (datum) => datum?.name,
value: (datum) => renderQuota(datum?.value || 0),
},
],
},
},
legends: {
visible: true,
position: 'right',
orient: 'vertical',
item: {
width: 100,
label: {
style: {
fontSize: 11,
},
},
},
},
label: {
visible: false,
},
color: [
'#3b82f6',
'#10b981',
'#f59e0b',
'#ef4444',
'#8b5cf6',
'#06b6d4',
'#f97316',
'#84cc16',
'#94a3b8',
],
};
}, [data, t]);
// 排行列表
const topModels = data?.slice(0, 5) || [];
return (
<Card
className='shadow-sm hover:shadow-md transition-shadow'
title={
<div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span>
</div>
}
bodyStyle={{ padding: '16px' }}
>
{pieSpec ? (
<div>
<VChart
spec={pieSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: 200 }}
/>
<div className='mt-4 space-y-2'>
{topModels.map((item, index) => (
<div key={index} className='flex items-center gap-2'>
<span className='text-xs text-gray-500 w-4'>{index + 1}</span>
<span
className='text-sm flex-1 truncate'
title={item.model_name}
>
{item.model_name}
</span>
<span className='text-xs text-gray-500'>
{item.percent?.toFixed(1)}%
</span>
</div>
))}
</div>
</div>
) : (
<div className='h-[300px] flex items-center justify-center text-gray-400'>
{t('暂无数据')}
</div>
)}
</Card>
);
};
export default ModelDistribution;
+156
View File
@@ -0,0 +1,156 @@
/*
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 } from '@douyinfe/semi-ui';
import {
Users,
UserPlus,
DollarSign,
Zap,
Activity,
Percent,
TrendingUp,
TrendingDown,
} from 'lucide-react';
import { renderQuota } from '../../helpers';
const OverviewCards = ({ overview, t }) => {
if (!overview) {
return (
<div className='grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-6'>
{[...Array(6)].map((_, i) => (
<Card key={i} className='animate-pulse'>
<div className='h-20 bg-gray-200 dark:bg-gray-700 rounded'></div>
</Card>
))}
</div>
);
}
const cards = [
{
title: t('今日活跃'),
value: overview.dau?.toLocaleString() || '0',
change: overview.dau_change,
icon: <Users className='w-5 h-5' />,
color: 'blue',
bgColor: 'bg-blue-50 dark:bg-blue-900/20',
iconBg: 'bg-blue-500',
},
{
title: t('今日新增'),
value: overview.new_users?.toLocaleString() || '0',
change: overview.new_users_change,
icon: <UserPlus className='w-5 h-5' />,
color: 'green',
bgColor: 'bg-green-50 dark:bg-green-900/20',
iconBg: 'bg-green-500',
},
{
title: t('今日充值'),
value: `¥${overview.today_topup?.toFixed(2) || '0.00'}`,
change: overview.today_topup_change,
icon: <DollarSign className='w-5 h-5' />,
color: 'yellow',
bgColor: 'bg-yellow-50 dark:bg-yellow-900/20',
iconBg: 'bg-yellow-500',
},
{
title: t('今日消耗'),
value: renderQuota(overview.today_consume || 0),
change: overview.today_consume_change,
icon: <Zap className='w-5 h-5' />,
color: 'purple',
bgColor: 'bg-brand/5 dark:bg-brand-deep/20',
iconBg: 'bg-brand',
},
{
title: t('请求次数'),
value: overview.today_requests?.toLocaleString() || '0',
change: null,
icon: <Activity className='w-5 h-5' />,
color: 'cyan',
bgColor: 'bg-cyan-50 dark:bg-cyan-900/20',
iconBg: 'bg-cyan-500',
},
{
title: t('付费率'),
value: `${overview.pay_rate?.toFixed(1) || '0.0'}%`,
change: null,
icon: <Percent className='w-5 h-5' />,
color: 'pink',
bgColor: 'bg-pink-50 dark:bg-pink-900/20',
iconBg: 'bg-pink-500',
},
];
const renderChange = (change) => {
if (change === null || change === undefined || isNaN(change)) return null;
const isPositive = change >= 0;
return (
<div
className={`flex items-center gap-1 text-xs font-medium ${
isPositive ? 'text-green-500' : 'text-red-500'
}`}
>
{isPositive ? (
<TrendingUp className='w-3 h-3' />
) : (
<TrendingDown className='w-3 h-3' />
)}
<span>
{isPositive ? '+' : ''}
{change.toFixed(1)}%
</span>
</div>
);
};
return (
<div className='grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-6'>
{cards.map((card, index) => (
<Card
key={index}
className={`${card.bgColor} border-none shadow-sm hover:shadow-md transition-shadow`}
bodyStyle={{ padding: '16px' }}
>
<div className='flex items-start justify-between'>
<div className='flex-1'>
<p className='text-xs text-gray-500 dark:text-gray-400 mb-1'>
{card.title}
</p>
<p className='text-xl font-bold text-gray-800 dark:text-gray-100'>
{card.value}
</p>
{renderChange(card.change)}
</div>
<div
className={`${card.iconBg} p-2 rounded-lg text-white shadow-sm`}
>
{card.icon}
</div>
</div>
</Card>
))}
</div>
);
};
export default OverviewCards;
@@ -0,0 +1,269 @@
/*
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, { useState } from 'react';
import {
Table,
Tag,
Button,
Modal,
Input,
Typography,
Space,
Select,
} from '@douyinfe/semi-ui';
import { IconRefresh } from '@douyinfe/semi-icons';
import { renderQuota } from '../../helpers';
const { Text } = Typography;
const formatTime = (ts) => {
if (!ts) return '-';
const d = new Date(ts * 1000);
const pad = (n) => (n < 10 ? '0' + n : '' + n);
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
};
/**
* 自动封号历史 / 解封操作中心
*
* 职责:
* - 持久查看所有由风控自动封号产生的记录(即使用户已经从疑似列表中消失)
* - 解封操作的主入口(疑似列表里的解封按钮只能覆盖"封号后还有活动"的边界场景)
*/
const RiskControlBanLogs = ({
loading,
banLogs,
banLogTotal,
banLogStatus,
setBanLogStatus,
banLogPage,
fetchBanLogs,
unbanUser,
t,
}) => {
const [unbanModalVisible, setUnbanModalVisible] = useState(false);
const [unbanRow, setUnbanRow] = useState(null);
const [unbanReason, setUnbanReason] = useState('');
const columns = [
{
title: t('封号时间'),
dataIndex: 'ban_at',
width: 150,
render: (v) => formatTime(v),
},
{
title: t('用户ID'),
dataIndex: 'user_id',
width: 100,
},
{
title: t('用户名(快照)'),
dataIndex: 'user_snapshot',
width: 140,
render: (v) => v || <Text type='tertiary'>-</Text>,
},
{
title: t('请求次数'),
dataIndex: 'request_count',
width: 100,
render: (v) => (v || 0).toLocaleString(),
},
{
title: t('总消耗'),
dataIndex: 'total_quota',
width: 110,
render: (v) => renderQuota(v || 0, 4),
},
{
title: t('平均消耗'),
dataIndex: 'avg_quota_x1000',
width: 120,
render: (v) => renderQuota((v || 0) / 1000, 6),
},
{
title: t('最常用模型'),
dataIndex: 'top_model',
width: 150,
render: (v) =>
v ? <Tag color='blue'>{v}</Tag> : <Text type='tertiary'>-</Text>,
},
{
title: t('活跃 IP'),
dataIndex: 'last_ip',
width: 130,
render: (v) => v || <Text type='tertiary'>-</Text>,
},
{
title: t('状态'),
dataIndex: 'status',
width: 100,
render: (v) =>
v === 1 ? (
<Tag color='red'>{t('已封号')}</Tag>
) : (
<Tag color='green'>{t('已解封')}</Tag>
),
},
{
title: t('解封时间'),
dataIndex: 'unban_at',
width: 150,
render: (v) => (v > 0 ? formatTime(v) : <Text type='tertiary'>-</Text>),
},
{
title: t('解封原因'),
dataIndex: 'unban_reason',
width: 180,
render: (v) => v || <Text type='tertiary'>-</Text>,
},
{
title: t('操作'),
width: 110,
fixed: 'right',
render: (_v, row) => {
if (row.status === 1) {
return (
<Button
size='small'
type='primary'
theme='light'
onClick={() => {
setUnbanRow(row);
setUnbanReason('');
setUnbanModalVisible(true);
}}
>
{t('解封')}
</Button>
);
}
return (
<Text type='tertiary' size='small'>
-
</Text>
);
},
},
];
const statusOptions = [
{ value: 0, label: t('全部') },
{ value: 1, label: t('已封号') },
{ value: 2, label: t('已解封') },
];
return (
<div>
<div className='mb-3 flex items-center justify-between flex-wrap gap-2'>
<Space>
<Text type='tertiary' size='small'>
{t('共')} {banLogTotal || 0} {t('条')}
</Text>
<Select
value={banLogStatus}
onChange={(v) => {
setBanLogStatus(v);
fetchBanLogs({ status: v, page: 1 });
}}
optionList={statusOptions}
style={{ width: 120 }}
size='small'
/>
</Space>
<Button
icon={<IconRefresh />}
size='small'
onClick={() => fetchBanLogs()}
loading={loading}
>
{t('刷新')}
</Button>
</div>
<Table
columns={columns}
dataSource={banLogs}
rowKey='id'
loading={loading}
pagination={{
pageSize: 20,
showTotal: true,
total: banLogTotal,
// 受控分页:避免切换状态筛选后 Semi 内部页码与 hook 不同步
currentPage: banLogPage,
onPageChange: (page) => fetchBanLogs({ page }),
}}
empty={t('暂无封号记录')}
scroll={{ x: 1400 }}
/>
<Modal
title={t('解封用户')}
visible={unbanModalVisible}
onCancel={() => setUnbanModalVisible(false)}
onOk={async () => {
if (!unbanRow) return;
// unbanUser 内部会并发刷新 suspects + banLogs,无需在此重复 fetch
const ok = await unbanUser({
userId: unbanRow.user_id,
banLogId: unbanRow.id,
reason: unbanReason,
});
if (ok) {
setUnbanModalVisible(false);
}
}}
okText={t('确认解封')}
cancelText={t('取消')}
>
{unbanRow && (
<div className='space-y-3'>
<div>
<Text type='tertiary'>{t('用户:')}</Text>
<Text strong>
{unbanRow.user_snapshot || `user_${unbanRow.user_id}`}(ID:
{unbanRow.user_id})
</Text>
</div>
<div>
<Text type='tertiary'>
{t(
'解封后用户账号会恢复,但被禁用的 Token 不会自动启用,需手动开启。',
)}
</Text>
</div>
<div>
<div className='text-xs text-gray-500 mb-1'>{t('解封原因')}</div>
<Input.TextArea
value={unbanReason}
onChange={setUnbanReason}
placeholder={t('记录解封原因,便于审计')}
rows={3}
/>
</div>
</div>
)}
</Modal>
</div>
);
};
export default RiskControlBanLogs;
@@ -0,0 +1,297 @@
/*
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, { useEffect, useRef, useState } from 'react';
import {
Modal,
Form,
Switch,
InputNumber,
Input,
Typography,
Banner,
Button,
Space,
} from '@douyinfe/semi-ui';
import { renderQuota } from '../../helpers';
const { Text } = Typography;
const defaultValues = {
id: 0,
name: '高频低消耗自动封号',
enabled: false,
window_minutes: 1440,
scan_interval_minutes: 10,
warn_min_requests: 500,
warn_max_avg_quota: 50,
auto_ban_enabled: true,
ban_min_requests: 1000,
ban_max_avg_quota: 5,
ban_max_total_quota: 5000,
notify_admin: true,
};
const RiskControlRulesModal = ({
visible,
onClose,
rules,
saveRule,
triggerScanNow,
t,
}) => {
const [form, setForm] = useState(defaultValues);
const [saving, setSaving] = useState(false);
// 仅在 Modal 由"关闭→打开"的瞬间同步表单,避免 rules 异步到达时覆盖用户正在编辑的值
const prevVisibleRef = useRef(false);
useEffect(() => {
if (visible && !prevVisibleRef.current) {
if (rules && rules.length > 0) {
setForm({ ...defaultValues, ...rules[0] });
} else {
setForm(defaultValues);
}
}
prevVisibleRef.current = visible;
}, [visible, rules]);
const setField = (k, v) => setForm((f) => ({ ...f, [k]: v }));
const handleSave = async (alsoScan) => {
// 仅在启用了自动封号时校验封号阈值
if (form.auto_ban_enabled) {
if (
form.ban_min_requests > 0 &&
form.ban_min_requests < form.warn_min_requests
) {
Modal.warning({
title: t('阈值不合法'),
content: t('封号最低请求数不能低于预警阈值'),
});
return;
}
if (
form.ban_max_avg_quota > 0 &&
form.warn_max_avg_quota > 0 &&
form.ban_max_avg_quota > form.warn_max_avg_quota
) {
Modal.warning({
title: t('阈值不合法'),
content: t('封号平均消耗上限不能高于预警阈值'),
});
return;
}
}
setSaving(true);
const ok = await saveRule(form);
setSaving(false);
if (!ok) return;
if (alsoScan) {
await triggerScanNow();
}
onClose();
};
return (
<Modal
title={t('风控规则配置')}
visible={visible}
onCancel={onClose}
footer={
<Space>
<Button onClick={onClose}>{t('取消')}</Button>
<Button onClick={() => handleSave(false)} loading={saving}>
{t('仅保存')}
</Button>
<Button
type='primary'
theme='solid'
onClick={() => handleSave(true)}
loading={saving}
>
{t('保存并立即扫描')}
</Button>
</Space>
}
width={620}
>
<Banner
type='info'
description={t(
'命中"预警阈值"仅通知管理员,不动账号;命中"封号阈值"会自动封号并禁用该用户全部 Token。',
)}
className='mb-4'
/>
<div className='space-y-4'>
<Form.Slot label={t('规则名称')}>
<Input value={form.name} onChange={(v) => setField('name', v)} />
</Form.Slot>
<div className='flex items-center gap-3'>
<Switch
checked={form.enabled}
onChange={(v) => setField('enabled', v)}
/>
<Text>{t('启用此规则')}</Text>
</div>
<div className='grid grid-cols-2 gap-4'>
<Form.Slot label={t('检测时间窗(分钟)')}>
<InputNumber
value={form.window_minutes}
onChange={(v) => setField('window_minutes', v || 1440)}
min={1}
style={{ width: '100%' }}
suffix={t('分钟')}
/>
</Form.Slot>
<Form.Slot label={t('扫描频率(分钟)')}>
<InputNumber
value={form.scan_interval_minutes}
onChange={(v) => setField('scan_interval_minutes', v || 10)}
min={1}
style={{ width: '100%' }}
suffix={t('分钟')}
/>
</Form.Slot>
</div>
<div className='border-l-4 border-orange-400 pl-3 py-1'>
<Text strong className='text-orange-600'>
⚠ {t('预警阈值(仅通知,不封号)')}
</Text>
</div>
<div className='grid grid-cols-2 gap-4'>
<Form.Slot label={t('最低请求数')}>
<InputNumber
value={form.warn_min_requests}
onChange={(v) => setField('warn_min_requests', v || 0)}
min={1}
style={{ width: '100%' }}
/>
</Form.Slot>
<Form.Slot
label={
<span>
{t('平均消耗 ≤')}{' '}
<Text type='tertiary' size='small'>
({t('quota')}, ≈ {renderQuota(form.warn_max_avg_quota, 6)})
</Text>
</span>
}
>
<InputNumber
value={form.warn_max_avg_quota}
onChange={(v) => setField('warn_max_avg_quota', v || 0)}
min={0}
style={{ width: '100%' }}
/>
</Form.Slot>
</div>
<div className='border-l-4 border-red-500 pl-3 py-1 flex items-center justify-between'>
<Text strong className='text-red-600'>
🚨 {t('封号阈值(自动封号 + 禁用所有 Token)')}
</Text>
<div className='flex items-center gap-2'>
<Text size='small' type='tertiary'>
{t('启用自动封号')}
</Text>
<Switch
size='small'
checked={form.auto_ban_enabled}
onChange={(v) => setField('auto_ban_enabled', v)}
/>
</div>
</div>
{!form.auto_ban_enabled && (
<Banner
type='warning'
description={t(
'已关闭自动封号:命中阈值的用户仅会收到管理员预警通知,不会被自动处置。',
)}
className='mb-2'
/>
)}
<div
className={`grid grid-cols-2 gap-4 ${form.auto_ban_enabled ? '' : 'opacity-50 pointer-events-none'}`}
>
<Form.Slot label={t('最低请求数')}>
<InputNumber
value={form.ban_min_requests}
onChange={(v) => setField('ban_min_requests', v == null ? 0 : v)}
min={0}
style={{ width: '100%' }}
disabled={!form.auto_ban_enabled}
/>
</Form.Slot>
<Form.Slot
label={
<span>
{t('平均消耗 ≤')}{' '}
<Text type='tertiary' size='small'>
({t('quota')}, ≈ {renderQuota(form.ban_max_avg_quota, 6)})
</Text>
</span>
}
>
<InputNumber
value={form.ban_max_avg_quota}
onChange={(v) => setField('ban_max_avg_quota', v || 0)}
min={0}
style={{ width: '100%' }}
disabled={!form.auto_ban_enabled}
/>
</Form.Slot>
</div>
<Form.Slot
label={
<span>
{t('总消耗 ≤')}{' '}
<Text type='tertiary' size='small'>
({t('quota')}, ≈ {renderQuota(form.ban_max_total_quota, 4)},{' '}
{t('防误伤大客户')})
</Text>
</span>
}
>
<InputNumber
value={form.ban_max_total_quota}
onChange={(v) => setField('ban_max_total_quota', v || 0)}
min={0}
style={{ width: '100%' }}
disabled={!form.auto_ban_enabled}
/>
</Form.Slot>
<div className='flex items-center gap-3 pt-2'>
<Switch
checked={form.notify_admin}
onChange={(v) => setField('notify_admin', v)}
/>
<Text>{t('触发时通知管理员(站内 / 邮件 / Webhook)')}</Text>
</div>
</div>
</Modal>
);
};
export default RiskControlRulesModal;
@@ -0,0 +1,161 @@
/*
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 { Card } from '@douyinfe/semi-ui';
import { VChart } from '@visactor/react-vchart';
// 支付渠道颜色映射:支付宝蓝色、微信绿色
const CHANNEL_COLORS = {
支付宝: '#3b82f6', // 蓝色
微信支付: '#10b981', // 绿色
Stripe: '#8b5cf6', // 紫色
PayPal: '#0070ba',
Creem: '#f59e0b', // 橙色
易支付: '#ef4444', // 红色
};
const DEFAULT_COLORS = [
'#3b82f6',
'#10b981',
'#8b5cf6',
'#f59e0b',
'#ef4444',
'#06b6d4',
'#f97316',
];
const TopupChannelChart = ({ data, title, icon, t }) => {
const pieSpec = useMemo(() => {
if (!data || data.length === 0) return null;
const chartData = data.map((item) => ({
name: item.payment_method || t('未知'),
value: item.amount || 0,
count: item.count || 0,
}));
// 根据支付渠道名称生成颜色数组
const colorList = chartData.map((item, index) => {
return (
CHANNEL_COLORS[item.name] ||
DEFAULT_COLORS[index % DEFAULT_COLORS.length]
);
});
return {
type: 'pie',
data: [{ id: 'topupChannel', values: chartData }],
valueField: 'value',
categoryField: 'name',
outerRadius: 0.8,
innerRadius: 0.5,
padAngle: 0.02,
pie: {
style: {
cornerRadius: 4,
},
},
tooltip: {
mark: {
content: [
{
key: (datum) => datum?.name,
value: (datum) => `¥${(datum?.value || 0).toFixed(2)}`,
},
{
key: () => t('笔数'),
value: (datum) => `${datum?.count || 0} ${t('笔')}`,
},
],
},
},
legends: {
visible: true,
position: 'bottom',
orient: 'horizontal',
},
label: {
visible: true,
position: 'outside',
content: '{name}: {value:.1%}',
},
color: colorList,
};
}, [data, t]);
// 统计列表
const channelList = data || [];
const totalAmount = channelList.reduce(
(sum, item) => sum + (item.amount || 0),
0,
);
return (
<Card
className='shadow-sm hover:shadow-md transition-shadow'
title={
<div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span>
</div>
}
bodyStyle={{ padding: '16px' }}
>
{pieSpec ? (
<div>
<VChart
spec={pieSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: 200 }}
/>
<div className='mt-4 space-y-2'>
{channelList.map((item, index) => (
<div
key={index}
className='flex items-center justify-between text-sm py-1 border-b border-gray-100 dark:border-gray-700 last:border-0'
>
<span className='text-gray-600 dark:text-gray-400'>
{item.payment_method}
</span>
<div className='text-right'>
<span className='font-medium'>
¥{(item.amount || 0).toFixed(2)}
</span>
<span className='text-gray-400 text-xs ml-2'>
({item.percent?.toFixed(1)}%)
</span>
</div>
</div>
))}
<div className='flex items-center justify-between text-sm pt-2 font-semibold'>
<span>{t('合计')}</span>
<span>¥{totalAmount.toFixed(2)}</span>
</div>
</div>
</div>
) : (
<div className='h-[300px] flex items-center justify-center text-gray-400'>
{t('暂无数据')}
</div>
)}
</Card>
);
};
export default TopupChannelChart;
+251
View File
@@ -0,0 +1,251 @@
/*
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 { Card } from '@douyinfe/semi-ui';
import { VChart } from '@visactor/react-vchart';
const TrendCharts = ({ title, icon, data, type, t }) => {
const spec = useMemo(() => {
if (!data || data.length === 0) {
return null;
}
if (type === 'user') {
// 用户趋势图
const chartData = data.flatMap((item) => [
{ date: item.date, type: t('新增用户'), value: item.new_users || 0 },
{ date: item.date, type: t('活跃用户'), value: item.active_users || 0 },
{ date: item.date, type: t('付费用户'), value: item.paid_users || 0 },
]);
return {
type: 'line',
data: [{ id: 'userTrend', values: chartData }],
xField: 'date',
yField: 'value',
seriesField: 'type',
point: {
visible: true,
size: 4,
},
line: {
style: {
lineWidth: 2,
},
},
legends: {
visible: true,
orient: 'top',
position: 'middle',
padding: { top: 0, bottom: 16, left: 0, right: 0 },
layoutType: 'normal',
},
tooltip: {
visible: true,
mark: {
visible: true,
content: [
{
key: (datum) => datum?.type,
value: (datum) =>
`${(datum?.value || 0).toLocaleString()} ${t('人')}`,
},
],
},
dimension: {
visible: true,
content: [
{
key: (datum) => datum?.type,
value: (datum) =>
`${(datum?.value || 0).toLocaleString()} ${t('人')}`,
},
],
},
},
color: ['#3b82f6', '#10b981', '#f59e0b'],
crosshair: {
xField: { visible: true, line: { visible: true } },
yField: { visible: false },
},
axes: [
{
orient: 'bottom',
label: {
style: {
angle: -45,
},
},
},
{
orient: 'left',
label: {
formatMethod: (v) => Math.round(v),
},
},
],
};
} else {
// 收支趋势图 - 双轴
const topupKey = t('充值金额');
const consumeKey = t('消耗额度');
const chartData = data.map((item) => ({
date: item.date,
[topupKey]: item.topup_amount || 0,
[consumeKey]: (item.consume_quota || 0) / 500000, // 转换为美元单位
rawConsume: item.consume_quota || 0, // 保留原始值用于 tooltip
}));
return {
type: 'common',
data: [{ id: 'financeTrend', values: chartData }],
series: [
{
type: 'bar',
id: 'topup',
name: topupKey,
dataIndex: 0,
xField: 'date',
yField: topupKey,
bar: {
style: {
fill: '#3b82f6',
cornerRadius: [4, 4, 0, 0],
},
},
tooltip: {
visible: true,
mark: {
content: [
{
key: () => topupKey,
value: (datum) => `¥${(datum?.[topupKey] || 0).toFixed(2)}`,
},
],
},
},
},
{
type: 'line',
id: 'consume',
name: consumeKey,
dataIndex: 0,
xField: 'date',
yField: consumeKey,
point: {
visible: true,
size: 4,
style: {
fill: '#f59e0b',
},
},
line: {
style: {
stroke: '#f59e0b',
lineWidth: 2,
},
},
tooltip: {
visible: true,
mark: {
content: [
{
key: () => consumeKey,
value: (datum) =>
`¥${(datum?.[consumeKey] || 0).toFixed(2)}`,
},
],
},
},
},
],
legends: {
visible: true,
orient: 'top',
position: 'middle',
padding: { top: 0, bottom: 16, left: 0, right: 0 },
layoutType: 'normal',
},
tooltip: {
visible: true,
dimension: {
visible: true,
},
},
crosshair: {
xField: { visible: true, line: { visible: true } },
},
axes: [
{
orient: 'bottom',
label: {
style: {
angle: -45,
},
},
},
{
orient: 'left',
title: {
visible: true,
text: t('充值金额 (¥)'),
},
seriesIndex: [0],
},
{
orient: 'right',
title: {
visible: true,
text: t('消耗额度 ($)'),
},
seriesIndex: [1],
},
],
};
}
}, [data, type, t]);
return (
<Card
className='shadow-sm hover:shadow-md transition-shadow'
title={
<div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span>
</div>
}
bodyStyle={{ padding: '16px' }}
>
{spec ? (
<VChart
spec={spec}
option={{ mode: 'desktop-browser' }}
style={{ height: 300 }}
/>
) : (
<div className='h-[300px] flex items-center justify-center text-gray-400'>
{t('暂无数据')}
</div>
)}
</Card>
);
};
export default TrendCharts;
+139
View File
@@ -0,0 +1,139 @@
/*
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, Avatar, Progress } from '@douyinfe/semi-ui';
import { renderQuota } from '../../helpers';
const UserRanking = ({ data, title, icon, t }) => {
if (!data || data.length === 0) {
return (
<Card
className='shadow-sm hover:shadow-md transition-shadow'
title={
<div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span>
</div>
}
bodyStyle={{ padding: '16px' }}
>
<div className='h-[300px] flex items-center justify-center text-gray-400'>
{t('暂无数据')}
</div>
</Card>
);
}
// 计算最大值用于进度条
const maxQuota = Math.max(...data.map((item) => item.quota || 0));
// 排名颜色
const getRankStyle = (index) => {
if (index === 0)
return 'bg-gradient-to-r from-yellow-400 to-yellow-500 text-white';
if (index === 1)
return 'bg-gradient-to-r from-gray-300 to-gray-400 text-white';
if (index === 2)
return 'bg-gradient-to-r from-orange-400 to-orange-500 text-white';
return 'bg-gray-200 text-gray-600';
};
// 进度条颜色
const getProgressColor = (index) => {
if (index === 0) return '#f59e0b';
if (index === 1) return '#9ca3af';
if (index === 2) return '#f97316';
return '#3b82f6';
};
return (
<Card
className='shadow-sm hover:shadow-md transition-shadow'
title={
<div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span>
<span className='text-xs text-gray-400 ml-2'>
{t('共')} {data.length} {t('人')}
</span>
</div>
}
bodyStyle={{ padding: '16px' }}
>
<div className='space-y-2 max-h-[450px] overflow-y-auto pr-1'>
{data.map((item, index) => (
<div
key={item.user_id}
className='flex items-center gap-3 p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors'
>
<div
className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0 ${getRankStyle(
index,
)}`}
>
{index + 1}
</div>
<Avatar size='small' color='blue' className='flex-shrink-0'>
{(item.display_name || item.username)?.charAt(0)?.toUpperCase() ||
'U'}
</Avatar>
<div className='flex-1 min-w-0'>
<div className='flex items-center justify-between'>
<span
className='text-sm font-medium truncate'
title={`${item.display_name || item.username || 'User'} (ID: ${item.user_id})`}
>
{item.display_name || item.username || `User ${item.user_id}`}
<span className='text-xs text-gray-400 ml-1'>
#{item.user_id}
</span>
</span>
<span className='text-sm font-semibold text-gray-700 dark:text-gray-300 ml-2'>
{renderQuota(item.quota || 0)}
</span>
</div>
<Progress
percent={(item.quota / maxQuota) * 100}
showInfo={false}
size='small'
style={{ height: 4 }}
stroke={getProgressColor(index)}
/>
<div className='flex justify-between text-xs text-gray-400 mt-1'>
<span>
{item.requests?.toLocaleString()} {t('次请求')}
</span>
<span>{(item.tokens || 0).toLocaleString()} tokens</span>
</div>
<div className='flex justify-between text-xs mt-1'>
<span className='text-gray-500'>{t('余额')}:</span>
<span className='font-medium text-green-600 dark:text-green-400'>
{renderQuota(item.balance || 0)}
</span>
</div>
</div>
</div>
))}
</div>
</Card>
);
};
export default UserRanking;
@@ -0,0 +1,585 @@
/*
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, useState, useEffect, useCallback } from 'react';
import { Card, Spin, Tag, Progress, Empty } from '@douyinfe/semi-ui';
import { VChart } from '@visactor/react-vchart';
import { API, showError } from '../../helpers';
import {
UserCheck,
Briefcase,
Cpu,
Users,
TrendingUp,
BarChart3,
PieChart,
ChevronDown,
ChevronUp,
} from 'lucide-react';
// 职业类型标签配置
const JOB_TYPE_CONFIG = {
1: { label: '技术岗位', color: 'blue', icon: '💻', desc: '开发/测试/运维等' },
2: {
label: '技术周边',
color: 'green',
icon: '🎨',
desc: '产品/设计/运营等',
},
3: { label: '其他行业', color: 'orange', icon: '🏢', desc: '非IT行业' },
};
// AI工具使用标签配置
const AI_TOOL_CONFIG = {
1: { label: '正在使用', color: 'green', icon: '🚀', desc: '活跃用户' },
2: { label: '了解/尝试过', color: 'blue', icon: '🔍', desc: '潜在用户' },
3: { label: '有兴趣', color: 'orange', icon: '✨', desc: '待转化' },
4: { label: '暂不需要', color: 'grey', icon: '💤', desc: '观望用户' },
};
const UserSurveyStats = ({ title, icon, t }) => {
const [loading, setLoading] = useState(false);
const [surveyStats, setSurveyStats] = useState(null);
const [surveyTrend, setSurveyTrend] = useState([]);
const [collapsed, setCollapsed] = useState(true); // 默认折叠
// 获取统计数据
const fetchSurveyStats = useCallback(async () => {
try {
const res = await API.get('/api/analytics/survey/stats');
if (res.data.success) {
setSurveyStats(res.data.data);
} else {
showError(res.data.message);
}
} catch (error) {
console.error('获取问卷统计失败:', error);
}
}, []);
// 获取趋势数据
const fetchSurveyTrend = useCallback(async () => {
try {
const res = await API.get('/api/analytics/survey/trend');
if (res.data.success) {
setSurveyTrend(res.data.data || []);
}
} catch (error) {
console.error('获取问卷趋势失败:', error);
}
}, []);
// 初始加载
useEffect(() => {
const loadData = async () => {
setLoading(true);
await Promise.all([fetchSurveyStats(), fetchSurveyTrend()]);
setLoading(false);
};
loadData();
}, [fetchSurveyStats, fetchSurveyTrend]);
// 职业分布饼图配置
const jobTypePieSpec = useMemo(() => {
if (!surveyStats?.job_type_stats || surveyStats.job_type_stats.length === 0)
return null;
const chartData = surveyStats.job_type_stats.map((item) => ({
name: JOB_TYPE_CONFIG[item.job_type]?.label || t('未知'),
value: item.count,
percentage: item.percentage,
}));
return {
type: 'pie',
data: [{ id: 'jobType', values: chartData }],
valueField: 'value',
categoryField: 'name',
outerRadius: 0.8,
innerRadius: 0.5,
padAngle: 0.02,
pie: {
style: {
cornerRadius: 4,
},
},
tooltip: {
mark: {
content: [
{
key: (datum) => datum?.name,
value: (datum) => `${datum?.value || 0} ${t('人')}`,
},
{
key: () => t('占比'),
value: (datum) => `${(datum?.percentage || 0).toFixed(1)}%`,
},
],
},
},
legends: {
visible: true,
position: 'bottom',
orient: 'horizontal',
},
label: {
visible: true,
position: 'outside',
content: '{name}',
},
color: ['#3b82f6', '#10b981', '#f59e0b'],
};
}, [surveyStats, t]);
// AI工具使用饼图配置
const aiToolPieSpec = useMemo(() => {
if (!surveyStats?.ai_tool_stats || surveyStats.ai_tool_stats.length === 0)
return null;
const chartData = surveyStats.ai_tool_stats.map((item) => ({
name: AI_TOOL_CONFIG[item.ai_tool_usage]?.label || t('未知'),
value: item.count,
percentage: item.percentage,
}));
return {
type: 'pie',
data: [{ id: 'aiTool', values: chartData }],
valueField: 'value',
categoryField: 'name',
outerRadius: 0.8,
innerRadius: 0.5,
padAngle: 0.02,
pie: {
style: {
cornerRadius: 4,
},
},
tooltip: {
mark: {
content: [
{
key: (datum) => datum?.name,
value: (datum) => `${datum?.value || 0} ${t('人')}`,
},
{
key: () => t('占比'),
value: (datum) => `${(datum?.percentage || 0).toFixed(1)}%`,
},
],
},
},
legends: {
visible: true,
position: 'bottom',
orient: 'horizontal',
},
label: {
visible: true,
position: 'outside',
content: '{name}',
},
color: ['#10b981', '#3b82f6', '#f59e0b', '#9ca3af'],
};
}, [surveyStats, t]);
// 趋势图配置
const trendSpec = useMemo(() => {
if (!surveyTrend || surveyTrend.length === 0) return null;
const chartData = [...surveyTrend].reverse().map((item) => ({
date: item.date,
count: item.count,
}));
return {
type: 'bar',
data: [{ id: 'trend', values: chartData }],
xField: 'date',
yField: 'count',
bar: {
style: {
cornerRadius: [4, 4, 0, 0],
fill: {
gradient: 'linear',
x0: 0,
y0: 0,
x1: 0,
y1: 1,
stops: [
{ offset: 0, color: '#8b5cf6' },
{ offset: 1, color: '#6366f1' },
],
},
},
},
tooltip: {
mark: {
content: [
{
key: () => t('日期'),
value: (datum) => datum?.date,
},
{
key: () => t('新增'),
value: (datum) => `${datum?.count || 0} ${t('人')}`,
},
],
},
},
axes: [
{
orient: 'bottom',
label: {
autoRotate: true,
autoRotateAngle: [0, 45],
},
},
{
orient: 'left',
label: {
formatMethod: (v) => Math.round(v),
},
},
],
};
}, [surveyTrend, t]);
// 计算统计数据
const totalUsers = surveyStats?.total || 0;
const techUsers =
surveyStats?.job_type_stats?.find((s) => s.job_type === 1)?.count || 0;
const activeAIUsers =
surveyStats?.ai_tool_stats?.find((s) => s.ai_tool_usage === 1)?.count || 0;
const interestedUsers =
surveyStats?.ai_tool_stats?.find((s) => s.ai_tool_usage === 3)?.count || 0;
return (
<Card
className='shadow-sm hover:shadow-md transition-shadow'
title={
<div className='flex items-center justify-between w-full'>
<div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span>
{totalUsers > 0 && (
<Tag color='purple' size='small'>
{totalUsers} {t('人已填写')}
</Tag>
)}
</div>
<button
onClick={() => setCollapsed(!collapsed)}
className='flex items-center gap-1 px-2 py-1 text-sm text-gray-500 hover:text-brand-deep hover:bg-brand/5 dark:hover:bg-brand-deep/20 rounded transition-colors'
>
<span className='text-xs'>{collapsed ? t('展开') : t('收起')}</span>
{collapsed ? <ChevronDown size={16} /> : <ChevronUp size={16} />}
</button>
</div>
}
bodyStyle={{ padding: collapsed ? '0' : '16px' }}
>
{!collapsed && (
<Spin spinning={loading}>
{totalUsers === 0 ? (
<Empty
image={<UserCheck className='w-16 h-16 text-gray-300' />}
description={t('暂无问卷数据')}
style={{ padding: '40px 0' }}
/>
) : (
<div className='space-y-6'>
{/* 概览统计卡片 */}
<div className='grid grid-cols-2 sm:grid-cols-4 gap-4'>
<div className='p-4 bg-gradient-to-br from-brand-from/5 to-brand-to/5 dark:from-brand-from/20 dark:to-brand-to/20 rounded-xl'>
<div className='flex items-center gap-2 mb-2'>
<Users className='w-4 h-4 text-brand' />
<span className='text-xs text-gray-500 dark:text-gray-400'>
{t('总填写')}
</span>
</div>
<div className='text-2xl font-bold text-brand-deep dark:text-brand-from'>
{totalUsers}
</div>
</div>
<div className='p-4 bg-gradient-to-br from-blue-50 to-cyan-50 dark:from-blue-900/20 dark:to-cyan-900/20 rounded-xl'>
<div className='flex items-center gap-2 mb-2'>
<Briefcase className='w-4 h-4 text-blue-500' />
<span className='text-xs text-gray-500 dark:text-gray-400'>
{t('技术岗位')}
</span>
</div>
<div className='text-2xl font-bold text-blue-600 dark:text-blue-400'>
{techUsers}
</div>
<div className='text-xs text-gray-400 mt-1'>
{totalUsers > 0
? ((techUsers / totalUsers) * 100).toFixed(1)
: 0}
%
</div>
</div>
<div className='p-4 bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-900/20 dark:to-emerald-900/20 rounded-xl'>
<div className='flex items-center gap-2 mb-2'>
<Cpu className='w-4 h-4 text-green-500' />
<span className='text-xs text-gray-500 dark:text-gray-400'>
{t('正在使用AI')}
</span>
</div>
<div className='text-2xl font-bold text-green-600 dark:text-green-400'>
{activeAIUsers}
</div>
<div className='text-xs text-gray-400 mt-1'>
{totalUsers > 0
? ((activeAIUsers / totalUsers) * 100).toFixed(1)
: 0}
%
</div>
</div>
<div className='p-4 bg-gradient-to-br from-orange-50 to-amber-50 dark:from-orange-900/20 dark:to-amber-900/20 rounded-xl'>
<div className='flex items-center gap-2 mb-2'>
<TrendingUp className='w-4 h-4 text-orange-500' />
<span className='text-xs text-gray-500 dark:text-gray-400'>
{t('有兴趣尝试')}
</span>
</div>
<div className='text-2xl font-bold text-orange-600 dark:text-orange-400'>
{interestedUsers}
</div>
<div className='text-xs text-gray-400 mt-1'>
{totalUsers > 0
? ((interestedUsers / totalUsers) * 100).toFixed(1)
: 0}
%
</div>
</div>
</div>
{/* 图表区域 */}
<div className='grid grid-cols-1 lg:grid-cols-2 gap-6'>
{/* 职业分布 */}
<div className='bg-gray-50 dark:bg-gray-800/50 rounded-xl p-4'>
<div className='flex items-center gap-2 mb-4'>
<PieChart className='w-4 h-4 text-blue-500' />
<span className='font-medium text-gray-700 dark:text-gray-300'>
{t('职业分布')}
</span>
</div>
{jobTypePieSpec ? (
<>
<VChart
spec={jobTypePieSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: 180 }}
/>
<div className='mt-3 space-y-2'>
{surveyStats?.job_type_stats?.map((item) => {
const config = JOB_TYPE_CONFIG[item.job_type];
return (
<div
key={item.job_type}
className='flex items-center justify-between'
>
<div className='flex items-center gap-2'>
<span className='text-lg'>{config?.icon}</span>
<span className='text-sm text-gray-600 dark:text-gray-400'>
{config?.label}
</span>
</div>
<div className='flex items-center gap-2'>
<Progress
percent={item.percentage}
size='small'
style={{ width: 60 }}
showInfo={false}
stroke={
config?.color === 'blue'
? '#3b82f6'
: config?.color === 'green'
? '#10b981'
: '#f59e0b'
}
/>
<span className='text-sm font-medium w-12 text-right'>
{item.count}
</span>
</div>
</div>
);
})}
</div>
</>
) : (
<div className='h-[200px] flex items-center justify-center text-gray-400'>
{t('暂无数据')}
</div>
)}
</div>
{/* AI工具使用情况 */}
<div className='bg-gray-50 dark:bg-gray-800/50 rounded-xl p-4'>
<div className='flex items-center gap-2 mb-4'>
<PieChart className='w-4 h-4 text-green-500' />
<span className='font-medium text-gray-700 dark:text-gray-300'>
{t('AI工具使用情况')}
</span>
</div>
{aiToolPieSpec ? (
<>
<VChart
spec={aiToolPieSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: 180 }}
/>
<div className='mt-3 space-y-2'>
{surveyStats?.ai_tool_stats?.map((item) => {
const config = AI_TOOL_CONFIG[item.ai_tool_usage];
const colors = {
green: '#10b981',
blue: '#3b82f6',
orange: '#f59e0b',
grey: '#9ca3af',
};
return (
<div
key={item.ai_tool_usage}
className='flex items-center justify-between'
>
<div className='flex items-center gap-2'>
<span className='text-lg'>{config?.icon}</span>
<span className='text-sm text-gray-600 dark:text-gray-400'>
{config?.label}
</span>
</div>
<div className='flex items-center gap-2'>
<Progress
percent={item.percentage}
size='small'
style={{ width: 60 }}
showInfo={false}
stroke={colors[config?.color] || '#9ca3af'}
/>
<span className='text-sm font-medium w-12 text-right'>
{item.count}
</span>
</div>
</div>
);
})}
</div>
</>
) : (
<div className='h-[200px] flex items-center justify-center text-gray-400'>
{t('暂无数据')}
</div>
)}
</div>
</div>
{/* 填写趋势 */}
<div className='bg-gray-50 dark:bg-gray-800/50 rounded-xl p-4'>
<div className='flex items-center gap-2 mb-4'>
<BarChart3 className='w-4 h-4 text-brand' />
<span className='font-medium text-gray-700 dark:text-gray-300'>
{t('近30天填写趋势')}
</span>
</div>
{trendSpec ? (
<VChart
spec={trendSpec}
option={{ mode: 'desktop-browser' }}
style={{ height: 200 }}
/>
) : (
<div className='h-[200px] flex items-center justify-center text-gray-400'>
{t('暂无数据')}
</div>
)}
</div>
{/* 交叉分析表格 */}
{surveyStats?.cross_analysis &&
surveyStats.cross_analysis.length > 0 && (
<div className='bg-gray-50 dark:bg-gray-800/50 rounded-xl p-4'>
<div className='flex items-center gap-2 mb-4'>
<BarChart3 className='w-4 h-4 text-brand' />
<span className='font-medium text-gray-700 dark:text-gray-300'>
{t('交叉分析')}
</span>
</div>
<div className='overflow-x-auto'>
<table className='w-full text-sm'>
<thead>
<tr className='border-b border-gray-200 dark:border-gray-700'>
<th className='text-left py-2 px-3 font-medium text-gray-600 dark:text-gray-400'>
{t('职业类型')}
</th>
<th className='text-left py-2 px-3 font-medium text-gray-600 dark:text-gray-400'>
{t('AI工具使用')}
</th>
<th className='text-right py-2 px-3 font-medium text-gray-600 dark:text-gray-400'>
{t('人数')}
</th>
</tr>
</thead>
<tbody>
{surveyStats.cross_analysis.map((item, index) => (
<tr
key={index}
className='border-b border-gray-100 dark:border-gray-700/50 last:border-0'
>
<td className='py-2 px-3'>
<div className='flex items-center gap-2'>
<span>
{JOB_TYPE_CONFIG[item.job_type]?.icon}
</span>
<span className='text-gray-700 dark:text-gray-300'>
{JOB_TYPE_CONFIG[item.job_type]?.label}
</span>
</div>
</td>
<td className='py-2 px-3'>
<Tag
color={
AI_TOOL_CONFIG[item.ai_tool_usage]?.color
}
size='small'
>
{AI_TOOL_CONFIG[item.ai_tool_usage]?.label}
</Tag>
</td>
<td className='py-2 px-3 text-right font-medium'>
{item.count}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
)}
</Spin>
)}
</Card>
);
};
export default UserSurveyStats;
@@ -0,0 +1,156 @@
/*
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, Table } from '@douyinfe/semi-ui';
import { renderQuota } from '../../helpers';
const UserTopupRanking = ({ data, title, icon, t }) => {
if (!data || data.length === 0) {
return (
<Card
className='shadow-sm hover:shadow-md transition-shadow'
title={
<div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span>
</div>
}
bodyStyle={{ padding: '16px' }}
>
<div className='h-[300px] flex items-center justify-center text-gray-400'>
{t('暂无数据')}
</div>
</Card>
);
}
// 预计算排名(后端已按充值总额降序排好,直接按顺序编号)
const dataWithRank = data.map((item, idx) => ({ ...item, _rank: idx + 1 }));
// 排名样式
const getRankBadge = (rank) => {
if (rank === 1)
return 'bg-gradient-to-r from-yellow-400 to-yellow-500 text-white';
if (rank === 2)
return 'bg-gradient-to-r from-gray-300 to-gray-400 text-white';
if (rank === 3)
return 'bg-gradient-to-r from-orange-400 to-orange-500 text-white';
return 'bg-gray-200 text-gray-600';
};
const columns = [
{
title: t('排名'),
dataIndex: '_rank',
width: 70,
render: (rank) => (
<div
className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold ${getRankBadge(rank)}`}
>
{rank}
</div>
),
},
{
title: t('用户昵称'),
dataIndex: 'display_name',
width: 160,
render: (text, record) => (
<div className='flex flex-col'>
<span
className='font-medium text-sm truncate'
title={text || `User ${record.user_id}`}
>
{text || `User ${record.user_id}`}
</span>
<span className='text-xs text-gray-400 truncate'>
ID: {record.user_id}
</span>
</div>
),
},
{
title: t('充值总额'),
dataIndex: 'total_topup',
width: 130,
sorter: (a, b) => a.total_topup - b.total_topup,
defaultSortOrder: 'descend',
render: (value) => (
<span className='font-semibold text-red-500'>
¥{(value || 0).toFixed(2)}
</span>
),
},
{
title: t('历史消耗'),
dataIndex: 'used_quota',
width: 130,
sorter: (a, b) => a.used_quota - b.used_quota,
render: (value) => (
<span className='text-orange-600 dark:text-orange-400'>
{renderQuota(value || 0)}
</span>
),
},
{
title: t('当前余额'),
dataIndex: 'balance',
width: 130,
sorter: (a, b) => a.balance - b.balance,
render: (value) => (
<span className='font-medium text-green-600 dark:text-green-400'>
{renderQuota(value || 0)}
</span>
),
},
];
return (
<Card
className='shadow-sm hover:shadow-md transition-shadow'
title={
<div className='flex items-center gap-2'>
<span className='text-brand'>{icon}</span>
<span className='font-semibold'>{title}</span>
<span className='text-xs text-gray-400 ml-2'>
{t('共')} {data.length} {t('人')}
</span>
</div>
}
bodyStyle={{ padding: '0' }}
>
<Table
// 列宽合计远超窄屏视口;没有 scroll 时表格会压缩到 min-content 硬塞进去,
// 末尾的操作列落在视口外,且 iOS 上滚动条不可见、毫无可拖动提示
scroll={{ x: 'max-content' }}
columns={columns}
dataSource={dataWithRank}
rowKey='user_id'
pagination={
data.length > 20 ? { pageSize: 20, showSizeChanger: true } : false
}
size='small'
bordered={false}
style={{ borderRadius: 0 }}
/>
</Card>
);
};
export default UserTopupRanking;
@@ -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}`;