/*
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 .
For commercial licensing, please contact support@quantumnous.com
*/
import { formatUserReference } from '../../helpers/safeDisplay';
import React, { useMemo, useState } from 'react';
import {
Card,
Table,
Tag,
Button,
InputNumber,
Select,
Space,
Modal,
Input,
Typography,
} from '@/components/ui';
import {
IconRefresh,
IconAlertTriangle,
IconShieldStroked,
} from '@/components/ui/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) => {v},
},
{
title: t('昵称'),
dataIndex: 'display_name',
width: 160,
render: (v, row) => (
{formatUserReference(v || row.username, row.user_id, t('未知用户'))}
{row.username && v && row.username !== v && (
@{row.username}
)}
),
},
{
title: t('请求次数'),
dataIndex: 'request_count',
width: 110,
sorter: (a, b) => a.request_count - b.request_count,
defaultSortOrder: 'descend',
render: (v) => {v.toLocaleString()},
},
{
title: t('总消耗'),
dataIndex: 'total_quota',
width: 120,
sorter: (a, b) => a.total_quota - b.total_quota,
render: (v) => {renderQuota(v, 4)},
},
{
title: t('平均消耗'),
dataIndex: 'avg_quota',
width: 130,
sorter: (a, b) => a.avg_quota - b.avg_quota,
render: (v) => (
{renderQuota(v, 6)}
),
},
{
title: t('状态'),
width: 110,
render: (_v, row) => {
const s = evalRowStatus(row);
return {s.label};
},
},
{
title: t('最常用模型'),
dataIndex: 'top_model',
width: 160,
render: (v) =>
v ? {v} : -,
},
{
title: t('活跃 IP'),
dataIndex: 'last_ip',
width: 130,
render: (v) => (v ? {v} : -),
},
{
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 (
);
}
if (isBanned) {
return (
{t('已被手动封号')}
);
}
return (
{t('监测中')}
);
},
},
];
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 (
{t('高频低消耗用户监测')}
{windowRange && windowRange.start > 0 && (
{formatTime(windowRange.start)} ~ {formatTime(windowRange.end)}
)}
}
onClick={onOpenRuleModal}
type='tertiary'
>
{t('风控规则')}
}
onClick={() => fetchSuspects()}
loading={loading}
>
{t('刷新')}
}
styles={{ body: { padding: '16px' } }}
>
{/* 筛选区 */}
{t('时间窗')}
{t('请求次数 ≥')}
setFilters((f) => ({ ...f, minRequests: v || 0 }))}
min={1}
style={{ width: '100%' }}
/>
{t('平均消耗 ≤ (quota,0=不限)')}
setFilters((f) => ({ ...f, maxAvgQuota: v || 0 }))}
min={0}
style={{ width: '100%' }}
/>
{(filters.maxAvgQuota > 0 || filters.maxTotalQuota > 0) && (
{filters.maxAvgQuota > 0 && (
{t('平均消耗 ≤')} {renderQuota(filters.maxAvgQuota, 6)}
{' '}
)}
{filters.maxTotalQuota > 0 && (
{t('总消耗 ≤')} {renderQuota(filters.maxTotalQuota, 4)}
)}
)}
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 && (
{t('用户:')}
{unbanRow.display_name || unbanRow.username}(ID:
{unbanRow.user_id})
{t(
'解封后用户账号会恢复,但被禁用的 Token 不会自动启用,需手动开启。',
)}
)}
);
};
export default HighFreqLowCostUsers;