Files
monkey-ai-web/src/pages/Organization/OrgAudit.jsx
T
qiubaishen db3dba1e96 sync: 同步 monkey-ai@weiyuan(ddc5b9443) 的 web/ 到 ui-optimization
- 合入 weiyuan 新功能前端:分佣 V2 / 伙伴工作台、智能路由、企业资金与分析、官网设置与预约演示等,
  semi-ui 已全部迁移到 antd 6 / @/components/ui,不重新引入 Semi
- 分佣二级菜单与页头去重、伙伴入口探测(企业伙伴走企业中心「企业分佣」)、超管侧栏入口恢复
- 适配层 DatePicker / TimePicker 统一 onChange(Date|Date[]|null, 文本) 契约;生产构建剔除调试日志
- 图片链接刷新:同任务请求复用、后台刷新不弹全局错误、离页停止批量请求
- 恢复 bun.lock(与 package-lock.json 共存);docs 规范与 CHANGELOG 更新
- 停止跟踪 .env.playwright.local(本地登录凭据,已加入 .gitignore)
2026-11-18 10:22:02 +08:00

499 lines
17 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import {
Search as ActionSearch,
RefreshCw as ActionRefreshCw,
} from '@/components/common/icons/ActionIcons';
import TableEmpty from '../../components/common/table/TableEmpty';
import React, { useEffect, useState } from 'react';
import { getQuotaPerUnit } from '../../helpers';
import { timestamp2string } from '../../helpers/utils';
import { useTranslation } from 'react-i18next';
import { Form as AntForm, Tabs as AntTabs } from 'antd';
import { Table, Select, Button, Tag, Tooltip } from '@/components/ui';
import { API } from '../../helpers/api';
import { useOrgAuditLogs } from '../../hooks/org/useOrgData';
import OrgPageHeader from './components/OrgPageHeader';
import { OrgFilterCard, OrgListCard } from './components/OrgListCard';
import OrgPromptRecords from './OrgPromptRecords';
import {
formatQuotaAsCNY,
isQuotaDetailValue,
isZeroUnlimitedQuotaKey,
} from './orgAuditFormat';
import { parseOrgFeatureFlag } from './orgFeatureFlags';
const tokenStatusMap = {
1: '已启用',
2: '已禁用',
3: '已过期',
4: '已耗尽',
};
const orgStatusMap = {
1: '正常',
2: '冻结',
3: '欠费',
};
const memberStatusMap = {
1: '正常',
2: '禁用',
};
const targetTypeLabels = {
token: '密钥',
member: '成员',
organization: '企业',
invitation: '邀请',
};
const targetTypeColors = {
token: 'purple',
member: 'blue',
organization: 'green',
invitation: 'orange',
};
// 操作分类:颜色 + 标签
const actionConfig = {
create_org: { label: '创建企业', color: 'green' },
update_settings: { label: '更新设置', color: 'blue' },
dissolve_org: { label: '解散企业', color: 'red' },
transfer_ownership: { label: '转让所有权', color: 'orange' },
join_org: { label: '加入企业', color: 'green' },
leave_org: { label: '退出企业', color: 'orange' },
update_quota_alert: { label: '更新配额预警', color: 'blue' },
invite_member: { label: '邀请成员', color: 'green' },
remove_member: { label: '移除成员', color: 'red' },
update_member_role: { label: '更新角色', color: 'blue' },
update_member_quota: { label: '更新配额', color: 'blue' },
update_member_status: { label: '更新状态', color: 'blue' },
update_member_model_limits: { label: '更新模型限制', color: 'blue' },
update_member_admin_permissions: { label: '更新管理员权限', color: 'blue' },
accept_invitation: { label: '接受邀请', color: 'green' },
cancel_invitation: { label: '取消邀请', color: 'grey' },
create_token: { label: '创建密钥', color: 'green' },
update_token: { label: '更新密钥', color: 'blue' },
delete_token: { label: '删除密钥', color: 'red' },
view_token_key: { label: '查看密钥', color: 'orange' },
admin_create_org: { label: '管理员创建企业', color: 'cyan' },
admin_update_org: { label: '管理员更新企业', color: 'cyan' },
admin_delete_org: { label: '管理员删除企业', color: 'red' },
// 注:建企业时配的初始额度也写这条 action(供预警取"加额时刻",detail.source=org_create_initial),
// 渲染时按 source 区分,避免审计阅读者把它误读成"建号当天有人又改了一次额度"
admin_adjust_quota: { label: '管理员调整额度', color: 'cyan' },
org_alert_mute: { label: '屏蔽预警通知', color: 'grey' },
org_alert_unmute: { label: '恢复预警通知', color: 'green' },
admin_update_status: { label: '管理员更新状态', color: 'cyan' },
};
const detailKeyLabels = {
name: '名称',
code: '邀请码',
status: '状态',
unlimited_quota: '无限额度',
remain_quota: '剩余额度',
quota_limit: '额度上限',
email: '邮箱',
role: '角色',
from: '原值',
to: '新值',
member_id: '成员ID',
method: '方式',
model_limits_enabled: '模型限制',
model_limits: '可用模型',
threshold: '预警阈值',
owner: '所有者',
amount: '调整额度',
org_name: '企业名称',
before_quota: '调整前额度',
expired_time: '过期时间',
allow_ips: 'IP白名单',
group: '分组',
max_members: '最大成员数',
max_tokens: '最大密钥数',
default_member_quota: '新成员默认额度上限',
cycle_quota: '周期额度',
cycle_quota_delta: '周期额度增量',
quota_period: '配额周期',
};
// 根据 action 上下文选择正确的 status 映射
function getStatusLabel(action, value) {
if (
action.startsWith('admin_') ||
action === 'create_org' ||
action === 'dissolve_org'
) {
return orgStatusMap[value];
}
if (action.includes('member')) {
return memberStatusMap[value];
}
return tokenStatusMap[value];
}
function formatDetailValue(action, key, value, t, quotaPerUnit) {
if (isQuotaDetailValue(action, key)) {
// 保留旧行为:空字符串表示「已清除」,不能落进 Number('')===0 → ¥0.00
if (typeof value === 'string' && value === '') {
return t('已清除');
}
// 上限类字段 0 = 不限制(后端 QuotaLimit <= 0 跳过限额),显示 ¥0.00 会误导为零额度
if (Number(value) === 0 && isZeroUnlimitedQuotaKey(key)) {
return t('不限制');
}
return formatQuotaAsCNY(value, quotaPerUnit);
}
if (key === 'status') {
const label = getStatusLabel(action, value);
return label ? t(label) : String(value);
}
if (key === 'unlimited_quota' || key === 'model_limits_enabled') {
return value ? t('是') : t('否');
}
if (key === 'expired_time') {
if (value === -1) return t('永不过期');
return timestamp2string(value);
}
if (typeof value === 'string' && value === '') {
return t('已清除');
}
return String(value);
}
function formatDetail(action, obj, t, quotaPerUnit) {
if (!obj) return '-';
const parts = [];
Object.entries(obj).forEach(([k, v]) => {
if (v === null || v === undefined) return;
const label = t(detailKeyLabels[k] || k);
parts.push(label + ': ' + formatDetailValue(action, k, v, t, quotaPerUnit));
});
return parts.length > 0 ? parts.join(', ') : '-';
}
function formatRelativeTime(timestamp, t) {
if (!timestamp) return '-';
const now = Date.now();
const diff = now - timestamp * 1000;
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (seconds < 60) return t('刚刚');
if (minutes < 60) return t('{{n}} 分钟前', { n: minutes });
if (hours < 24) return t('{{n}} 小时前', { n: hours });
if (days < 30) return t('{{n}} 天前', { n: days });
return new Date(timestamp * 1000).toLocaleDateString();
}
const OrgAudit = ({ orgId }) => {
const { t, i18n } = useTranslation();
const quotaPerUnit = getQuotaPerUnit();
const { logs, total, loading, fetch } = useOrgAuditLogs(orgId);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [actionFilter, setActionFilter] = useState('');
const [activeTab, setActiveTab] = useState('operations');
// 提示词记录 tab 由企业 feature flag(prompt_archive)控制显隐
const [promptArchiveEnabled, setPromptArchiveEnabled] = useState(false);
// 且需当前用户具备查看权限(owner 恒真;admin 需 owner 授予),与后端 RequireOrgAdminPermission 对齐
const [canViewPromptRecords, setCanViewPromptRecords] = useState(false);
useEffect(() => {
fetch(page, pageSize, actionFilter);
}, [fetch, page, pageSize, actionFilter]);
useEffect(() => {
if (!orgId) return;
let cancelled = false;
// 切换企业先隐藏,避免上一企业的 flag/权限残留
setPromptArchiveEnabled(false);
setCanViewPromptRecords(false);
// 两个判断相互独立:feature flag 与个人权限各自 try,一个失败不牵连另一个(避免整块 tab 误隐)
(async () => {
try {
const res = await API.get('/api/org/info', {
headers: { 'X-Org-Id': String(orgId) },
});
const flags = res.data?.data?.organization?.feature_flags;
// 解析语义必须与后端 RequireOrgFeature 一致,否则 tab 显隐与接口放行口径割裂
if (!cancelled)
setPromptArchiveEnabled(parseOrgFeatureFlag(flags, 'prompt_archive'));
} catch {
// 忽略:无 flag 时不展示提示词 tab
}
})();
(async () => {
try {
const res = await API.get('/api/org/me/summary', {
headers: { 'X-Org-Id': String(orgId) },
});
// 与后端 RequireOrgAdminPermission 对齐:owner 恒真,admin 依 owner 授予
if (!cancelled)
setCanViewPromptRecords(
!!res.data?.data?.member?.can_view_prompt_records,
);
} catch {
// 忽略:拉取失败时按无权限处理(fail-closed)
}
})();
return () => {
cancelled = true;
};
}, [orgId]);
const actionOptions = [
{ value: '', label: t('全部操作') },
// 企业操作
{ value: 'create_org', label: t('创建企业') },
{ value: 'update_settings', label: t('更新设置') },
{ value: 'transfer_ownership', label: t('转让所有权') },
{ value: 'update_quota_alert', label: t('更新配额预警') },
{ value: 'dissolve_org', label: t('解散企业') },
// 成员操作
{ value: 'invite_member', label: t('邀请成员') },
{ value: 'accept_invitation', label: t('接受邀请') },
{ value: 'cancel_invitation', label: t('取消邀请') },
{ value: 'join_org', label: t('加入企业') },
{ value: 'leave_org', label: t('退出企业') },
{ value: 'remove_member', label: t('移除成员') },
{ value: 'update_member_role', label: t('更新角色') },
{ value: 'update_member_quota', label: t('更新配额') },
{ value: 'update_member_status', label: t('更新状态') },
{ value: 'update_member_model_limits', label: t('更新模型限制') },
{ value: 'update_member_admin_permissions', label: t('更新管理员权限') },
// 密钥操作
{ value: 'create_token', label: t('创建密钥') },
{ value: 'update_token', label: t('更新密钥') },
{ value: 'delete_token', label: t('删除密钥') },
{ value: 'view_token_key', label: t('查看密钥') },
// 管理员操作
{ value: 'admin_create_org', label: t('管理员创建企业') },
{ value: 'admin_update_org', label: t('管理员更新企业') },
{ value: 'admin_delete_org', label: t('管理员删除企业') },
{ value: 'admin_adjust_quota', label: t('管理员调整额度') },
{ value: 'admin_update_status', label: t('管理员更新状态') },
];
// 列宽与渲染对齐原型 EnterpriseAudit(130/170/110/500/150,scroll.x 1140);标签为无边框 filled
const columns = [
{
title: t('操作者'),
dataIndex: 'operator_name',
width: 130,
render: (name, record) => name || `User#${record.operator_id}`,
},
{
title: t('操作类型'),
dataIndex: 'action',
width: 170,
render: (action, record) => {
const config = actionConfig[action];
if (!config) return <Tag bordered={false}>{action}</Tag>;
// 建企业时配的初始额度复用 admin_adjust_quota(供预警取"加额时刻"),
// 但它不是二次人工调额,按 detail.source 区分展示
let label = config.label;
if (action === 'admin_adjust_quota') {
try {
const detail = record?.detail ? JSON.parse(record.detail) : null;
if (detail?.source === 'org_create_initial') {
label = '建企业初始额度';
}
} catch {
// detail 非 JSON 时按默认标签展示
}
}
return (
<Tag color={config.color} bordered={false}>
{t(label)}
</Tag>
);
},
},
{
title: t('目标类型'),
dataIndex: 'target_type',
width: 110,
render: (type) => (
<Tag color={targetTypeColors[type] || 'grey'} bordered={false}>
{t(targetTypeLabels[type] || type)}
</Tag>
),
},
{
title: t('详情'),
dataIndex: 'detail',
width: 500,
render: (detail, record) => {
if (!detail) return <span className='oc-muted'>-</span>;
let text = detail;
try {
text = formatDetail(
record.action,
JSON.parse(detail),
t,
quotaPerUnit,
);
} catch {
// detail 非 JSON 时原样展示
}
return (
<Tooltip content={text} position='topLeft' style={{ maxWidth: 400 }}>
<span className='oc-audit-detail' tabIndex={0}>
{text}
</span>
</Tooltip>
);
},
},
{
title: t('时间'),
dataIndex: 'created_at',
width: 150,
render: (v) =>
v ? (
<Tooltip content={new Date(v * 1000).toLocaleString(i18n.language)}>
<time
className='oc-audit-time'
dateTime={new Date(v * 1000).toISOString()}
tabIndex={0}
>
{formatRelativeTime(v, t)}
</time>
</Tooltip>
) : (
'-'
),
},
];
const refresh = () => fetch(page, pageSize, actionFilter);
// 选择即筛选(原交互):与原页头 Select 的 onChange 相同
const applyAction = (v) => {
setActionFilter(v ?? '');
setPage(1);
};
const operations = (
<>
<OrgFilterCard
className='oc-audit-filter'
actions={
<>
{/* 重置 = 选择“全部操作”;搜索 = 以当前筛选重新查询(同“刷新”) */}
<Button onClick={() => applyAction('')}>{t('重置')}</Button>
<Button
type='primary'
icon={<ActionSearch size={16} />}
onClick={refresh}
>
{t('搜索')}
</Button>
</>
}
>
<AntForm layout='vertical' requiredMark={false} component='div'>
<AntForm.Item label={t('操作类型')}>
<Select
value={actionFilter}
onChange={applyAction}
optionList={actionOptions}
style={{ width: '100%' }}
placeholder={t('全部操作')}
filter
/>
</AntForm.Item>
</AntForm>
</OrgFilterCard>
<OrgListCard
title={t('操作记录')}
tools={
<Button
icon={<ActionRefreshCw size={16} />}
onClick={refresh}
loading={loading}
>
{t('刷新')}
</Button>
}
>
<Table
columns={columns}
dataSource={logs}
loading={loading}
rowKey='id'
scroll={{ x: 1140 }}
pagination={{
currentPage: page,
pageSize,
showSizeChanger: false,
total,
onPageChange: setPage,
onPageSizeChange: (size) => {
setPage(1);
setPageSize(size);
},
showTotal: (n) => t('共 {{total}} 条', { total: n }),
}}
empty={<TableEmpty />}
/>
</OrgListCard>
</>
);
return (
<div className='uc-page oc-page'>
<OrgPageHeader title={t('审计日志')} subtitle={t('查看企业操作记录')} />
{/* 原型 platform-list-tabs;“提示词记录”页签沿用原 feature flag + 权限显隐 */}
<AntTabs
className='oc-list-tabs'
activeKey={activeTab}
onChange={setActiveTab}
items={[
{ key: 'operations', label: t('操作审计'), children: operations },
...(promptArchiveEnabled && canViewPromptRecords
? [
{
key: 'prompt-records',
label: t('提示词记录'),
// 原 Tabs 预渲染全部页签(lazyRender=false),保持提示词记录随页面挂载、请求时机不变
forceRender: true,
children: <OrgPromptRecords key={orgId} orgId={orgId} />,
},
]
: []),
]}
/>
</div>
);
};
export default OrgAudit;