Files
monkey-ai-web/src/components/table/tokens/modals/EditTokenModal.jsx
T
qiubaishen 870b51d054 feat: 同步权限管理、企业成员排行与消费计费明细
- 接入平台与企业角色权限,按权限展示菜单、页面及操作。
- 企业成员排行按需加载,翻页沿用同一榜单快照,保留连续名次与前三名样式。
- 更新消费日志的费用明细、超管指标和官方价格汇率设置,补齐翻译与回归测试。
2026-11-25 21:08:24 +08:00

759 lines
28 KiB
React

import {
X as ActionX,
Settings2 as ActionSettings2,
Check as ActionCheck,
} from '@/components/common/icons/ActionIcons';
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useEffect, useState, useContext, useRef } from 'react';
import {
API,
showError,
showSuccess,
renderGroupOption,
getModelCategories,
selectFilter,
} from '../../../../helpers';
import { FormQuotaInput } from '../../../common/ui/QuotaInput';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import {
Button,
Modal,
Spin,
Form,
Collapsible,
DatePicker,
} from '@/components/ui';
import { IconChevronDown } from '@/components/ui/icons';
import {
Key,
CreditCard,
Shield,
Calendar,
Hash,
Layers,
Infinity,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { StatusContext } from '../../../../context/Status';
import EditTokenDrawer from './EditTokenDrawer';
const EditTokenModal = (props) => {
const { t: originalT } = useTranslation();
const t = props.labelReplace
? (key, options) => {
const result = originalT(key, options);
return typeof result === 'string'
? result.replace(/密钥/g, props.labelReplace)
: result;
}
: originalT;
const [statusState] = useContext(StatusContext);
const [loading, setLoading] = useState(false);
const [advancedOpen, setAdvancedOpen] = useState(false);
const [neverExpire, setNeverExpire] = useState(true);
const [expireDate, setExpireDate] = useState(null);
const isMobile = useIsMobile();
const formApiRef = useRef(null);
const [models, setModels] = useState([]);
const [skillOptions, setSkillOptions] = useState([]);
const [groups, setGroups] = useState([]);
const isEdit = props.editingToken.id !== undefined;
// 默认分组配置
const DEFAULT_GROUP = 'claude专用分组';
// 生成默认名称:claude + 随机两位整数
const generateDefaultName = () => {
const randomNum = Math.floor(Math.random() * 100)
.toString()
.padStart(2, '0');
return `claude${randomNum}`;
};
const getInitValues = () => ({
name: generateDefaultName(),
remain_quota: 0,
unlimited_quota: true,
model_limits_enabled: false,
model_limits: [],
allow_ips: '',
group: '', // 分组在 loadGroups 后动态设置
tokenCount: 1,
// 技能注入:默认关闭,存量密钥零影响
skill_injection_enabled: false,
skill_ids: [],
});
const handleCancel = () => {
setAdvancedOpen(false);
setNeverExpire(true);
setExpireDate(null);
props.handleClose();
};
const setExpiredTime = (month, day, hour, minute) => {
if (month === 0 && day === 0 && hour === 0 && minute === 0) {
setNeverExpire(true);
setExpireDate(null);
return;
}
setNeverExpire(false);
let now = new Date();
let timestamp = now.getTime();
let ms = month * 30 * 24 * 60 * 60 * 1000;
ms += day * 24 * 60 * 60 * 1000;
ms += hour * 60 * 60 * 1000;
ms += minute * 60 * 1000;
setExpireDate(new Date(timestamp + ms));
};
// 设置默认分组:优先 claude专用分组,否则第一个分组
const setDefaultGroup = (groupOptions) => {
if (!formApiRef.current || groupOptions.length === 0) return;
const hasDefaultGroup = groupOptions.some((g) => g.value === DEFAULT_GROUP);
const defaultValue = hasDefaultGroup
? DEFAULT_GROUP
: groupOptions[0].value;
formApiRef.current.setValue('group', defaultValue);
};
// 绑定技能的候选集取自技能超市目录(平台已发布集)。
// 这里刻意不做治理判定:企业密钥即便勾了企业未启用的技能,
// 后端解析层也只会收窄不会扩权(skillinject.resolveOrganization),
// 前端再判一次只会产生两套口径。
const loadSkillOptions = async () => {
// 必须翻页取全,不能"取一页当全量":服务端单页上限 100,而平台已发布技能
// 有数百个,只取首页会让第 101 个之后的技能永远无法被绑定,且界面上毫无提示。
// 这与 R19 修掉的企业技能市场固定 200 一页是同一型缺陷。
const pageSize = 100;
const maxPages = 20; // 兜底,防止服务端 total 异常时无限翻页
try {
const collected = [];
let offset = 0;
for (let page = 0; page < maxPages; page += 1) {
const res = await API.get('/api/skills/market', {
params: { page_size: pageSize, offset },
});
if (!res.data?.success) break;
const batch = res.data.data || [];
collected.push(...batch);
offset += batch.length;
if (batch.length < pageSize || offset >= (res.data.total || 0)) break;
}
setSkillOptions(
collected.map((skill) => ({
label: skill.name || skill.canonical_id,
value: skill.id,
})),
);
} catch (_error) {
setSkillOptions([]);
}
};
const loadModels = async () => {
let res = await API.get(`/api/user/models`);
const { success, message, data } = res.data;
if (success) {
const categories = getModelCategories(t);
let localModelOptions = data.map((model) => {
let icon = null;
for (const [key, category] of Object.entries(categories)) {
if (key !== 'all' && category.filter({ model_name: model })) {
icon = category.icon;
break;
}
}
return {
label: (
<span className='flex items-center gap-1'>
{icon}
{model}
</span>
),
value: model,
};
});
setModels(localModelOptions);
} else {
showError(t(message));
}
};
const loadGroups = async () => {
let res = await API.get(`/api/user/self/groups`);
const { success, message, data } = res.data;
if (success) {
let localGroupOptions = Object.entries(data).map(([group, info]) => ({
label: group,
value: group,
ratio: info.ratio,
description: info.desc,
fullLabel: info.desc,
}));
if (statusState?.status?.default_use_auto_group) {
if (localGroupOptions.some((group) => group.value === 'auto')) {
localGroupOptions.sort((a, b) => (a.value === 'auto' ? -1 : 1));
}
}
setGroups(localGroupOptions);
// 新建模式下设置默认分组
if (!isEdit) {
setDefaultGroup(localGroupOptions);
}
} else {
showError(t(message));
}
};
const loadToken = async () => {
setLoading(true);
let res = await API.get(`/api/token/${props.editingToken.id}`);
const { success, message, data } = res.data;
if (success) {
// 处理过期时间
if (data.expired_time === -1) {
setNeverExpire(true);
setExpireDate(null);
} else {
setNeverExpire(false);
setExpireDate(new Date(data.expired_time * 1000));
}
if (data.model_limits !== '') {
data.model_limits = data.model_limits.split(',');
} else {
data.model_limits = [];
}
// tokens.skill_ids 存的是 JSON 数组文本,表单要的是数组。
// 解析失败退化为空数组(=跟随身份有效集),不因一条坏数据卡住整个编辑页。
if (typeof data.skill_ids === 'string') {
try {
const parsed = JSON.parse(data.skill_ids || '[]');
data.skill_ids = Array.isArray(parsed) ? parsed : [];
} catch (_error) {
data.skill_ids = [];
}
} else if (!Array.isArray(data.skill_ids)) {
data.skill_ids = [];
}
// 移除 expired_time,因为我们单独管理
const { expired_time, ...restData } = data;
if (formApiRef.current) {
formApiRef.current.setValues({ ...getInitValues(), ...restData });
}
if (
data.model_limits?.length > 0 ||
data.allow_ips ||
!data.unlimited_quota ||
data.skill_injection_enabled
) {
setAdvancedOpen(true);
}
} else {
showError(message);
}
setLoading(false);
};
const onVisibilityChange = useEffectEvent(() => {
if (props.visiable) {
loadModels();
loadGroups();
loadSkillOptions();
if (isEdit) {
loadToken();
} else {
formApiRef.current?.setValues(getInitValues());
setAdvancedOpen(false);
setNeverExpire(true);
setExpireDate(null);
// 如果 groups 已加载,设置默认分组
if (groups.length > 0) {
setDefaultGroup(groups);
}
}
} else {
formApiRef.current?.reset();
setAdvancedOpen(false);
setNeverExpire(true);
setExpireDate(null);
}
});
useEffect(
() => onVisibilityChange(),
[onVisibilityChange, props.visiable, props.editingToken.id],
);
const generateRandomSuffix = () => {
const characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < 6; i++) {
result += characters.charAt(
Math.floor(Math.random() * characters.length),
);
}
return result;
};
// 创建/编辑共用的载荷构造(R26 教训:双分支各自维护同构逻辑,漏一边就出
// skill_ids 未序列化这类漂移故障,统一出口杜绝分叉)。
// - remain_quota 表单值是字符串,落库要整数
// - model_limits 表单值是数组,接口契约是逗号分隔文本
// - skill_ids 表单值是数组,tokens.skill_ids 落库是 JSON 数组文本;
// 空数组语义是"跟随身份有效集",与"未开启注入"不是一回事,
// 因此关闭注入时也如实提交空数组。
const buildTokenPayload = (values, expired_time) => {
const { tokenCount: _tc, ...payload } = values;
payload.remain_quota = parseInt(payload.remain_quota);
payload.expired_time = expired_time;
payload.model_limits = payload.model_limits.join(',');
payload.model_limits_enabled = payload.model_limits.length > 0;
payload.skill_ids = JSON.stringify(payload.skill_ids || []);
return payload;
};
const submit = async (values) => {
// 验证过期时间
if (!neverExpire && !expireDate) {
showError(t('请选择过期时间'));
return;
}
if (!neverExpire && expireDate && expireDate.getTime() <= Date.now()) {
showError(t('过期时间不能早于当前时间'));
return;
}
setLoading(true);
// 计算过期时间
const expired_time = neverExpire
? -1
: Math.ceil(expireDate.getTime() / 1000);
try {
if (isEdit) {
const localInputs = buildTokenPayload(values, expired_time);
let res = await API.put(`/api/token/`, {
...localInputs,
id: parseInt(props.editingToken.id),
});
const { success, message } = res.data;
if (success) {
showSuccess(t('密钥更新成功!'));
props.refresh();
props.handleClose();
} else {
showError(t(message));
}
} else {
const count = parseInt(values.tokenCount, 10) || 1;
let successCount = 0;
for (let i = 0; i < count; i++) {
const localInputs = buildTokenPayload(values, expired_time);
const baseName =
values.name.trim() === '' ? 'default' : values.name.trim();
if (i !== 0 || values.name.trim() === '') {
localInputs.name = `${baseName}-${generateRandomSuffix()}`;
} else {
localInputs.name = baseName;
}
let res = await API.post(`/api/token/`, localInputs);
const { success, message } = res.data;
if (success) {
successCount++;
} else {
showError(t(message));
break;
}
}
if (successCount > 0) {
showSuccess(t('密钥创建成功,请在列表页面点击复制获取密钥!'));
props.onCreated?.(successCount);
props.refresh();
props.handleClose();
}
}
} catch {
// The API client reports request failures.
} finally {
setLoading(false);
}
};
// 自定义标签组件
const FieldLabel = ({ icon: Icon, iconColor, children, required }) => (
<div className='flex items-center gap-1.5 mb-1'>
<Icon size={14} className={iconColor} />
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
{children}
</span>
{required && <span className='text-red-500 text-sm'>*</span>}
</div>
);
// 密钥管理页使用抽屉形态(密钥管理页面.zip);状态、请求与载荷仍由本组件统一提供。
if (props.presentation === 'drawer') {
return (
<EditTokenDrawer
open={props.visiable}
isEdit={isEdit}
isMobile={isMobile}
loading={loading}
t={t}
groups={groups}
models={models}
skillOptions={skillOptions}
neverExpire={neverExpire}
setNeverExpire={setNeverExpire}
expireDate={expireDate}
setExpireDate={setExpireDate}
setExpiredTime={setExpiredTime}
advancedOpen={advancedOpen}
setAdvancedOpen={setAdvancedOpen}
initValues={getInitValues()}
formApiRef={formApiRef}
onSubmit={submit}
onCancel={handleCancel}
/>
);
}
return (
<Modal
title={null}
visible={props.visiable}
onCancel={handleCancel}
centered
width={isMobile ? '95%' : 480}
closeIcon={null}
header={null}
footer={null}
maskClosable={false}
className='edit-token-modal'
bodyStyle={{ padding: 0 }}
style={{ borderRadius: '16px', overflow: 'hidden' }}
>
<div className='bg-white dark:bg-neutral-900'>
{/* 头部 */}
<div className='flex items-center justify-between px-5 py-4 border-b border-gray-100 dark:border-neutral-800 bg-gradient-to-r from-brand/[0.06] to-transparent'>
<div className='flex items-center gap-3'>
<div className='p-2 rounded-xl bg-gradient-to-br from-brand-from to-brand-to shadow-lg shadow-brand/30'>
<Key size={18} className='text-white' />
</div>
<div>
<h2 className='text-base font-semibold text-gray-800 dark:text-gray-100'>
{isEdit ? t('编辑密钥') : t('创建密钥')}
</h2>
<p className='text-xs text-gray-500 dark:text-gray-400'>
{isEdit ? t('修改密钥配置') : t('快速创建访问密钥')}
</p>
</div>
</div>
<button
onClick={handleCancel}
className='app-action-button p-1.5 rounded-lg text-gray-400 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-neutral-800 transition-colors'
>
<ActionX size={18} />
</button>
</div>
{/* 表单内容 */}
<Spin spinning={loading}>
<Form
key={isEdit ? 'edit' : 'new'}
initValues={getInitValues()}
getFormApi={(api) => (formApiRef.current = api)}
onSubmit={submit}
>
{({ values }) => (
<div className='px-5 py-4 max-h-[65vh] overflow-y-auto space-y-4 modal-scrollbar'>
{/* 基础配置区块 */}
<div className='p-4 rounded-xl bg-white dark:bg-neutral-900 border border-gray-200/60 dark:border-neutral-700/60 space-y-4'>
<div className='flex items-center gap-2 pb-2 border-b border-gray-200/60 dark:border-neutral-700/60'>
<div className='w-1 h-4 rounded-full bg-gradient-to-b from-brand-from to-brand-to' />
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
{t('基础配置')}
</span>
</div>
{/* 名称 */}
<div>
<FieldLabel icon={Key} iconColor='text-brand' required>
{t('名称')}
</FieldLabel>
<Form.Input
field='name'
noLabel
placeholder={t('请输入密钥名称')}
rules={[{ required: true, message: t('请输入名称') }]}
showClear
/>
</div>
{/* 密钥分组 */}
<div>
<FieldLabel icon={Layers} iconColor='text-brand'>
{t('密钥分组')}
</FieldLabel>
{groups.length > 0 ? (
<Form.Select
field='group'
noLabel
placeholder={t('选择分组,默认为用户分组')}
optionList={groups}
renderOptionItem={renderGroupOption}
showClear
style={{ width: '100%' }}
/>
) : (
<Form.Select
field='group'
noLabel
placeholder={t('管理员未设置用户可选分组')}
disabled
style={{ width: '100%' }}
/>
)}
</div>
{/* 过期时间 */}
<div>
<FieldLabel icon={Calendar} iconColor='text-brand' required>
{t('过期时间')}
</FieldLabel>
{neverExpire ? (
<div
className='flex items-center gap-2 px-3 py-2.5 bg-brand/[0.08] border border-brand/20 rounded-lg cursor-pointer hover:bg-brand/[0.12] transition-colors'
onClick={() => {
setNeverExpire(false);
const oneMonthLater = new Date();
oneMonthLater.setMonth(oneMonthLater.getMonth() + 1);
setExpireDate(oneMonthLater);
}}
>
<Infinity size={16} className='text-brand' />
<span className='text-sm font-medium text-brand-deep'>
{t('永不过期')}
</span>
<span className='text-xs text-brand/70 ml-auto'>
{t('点击修改')}
</span>
</div>
) : (
<DatePicker
type='dateTime'
value={expireDate}
onChange={(date) => setExpireDate(date)}
placeholder={t('选择过期时间')}
showClear
style={{ width: '100%' }}
disabledDate={(date) =>
date &&
date < new Date(new Date().setHours(0, 0, 0, 0))
}
/>
)}
{/* 快捷按钮 */}
<div className='flex flex-wrap gap-1.5 mt-2'>
{[
{
label: t('永不过期'),
args: [0, 0, 0, 0],
active: neverExpire,
},
{ label: t('一个月'), args: [1, 0, 0, 0] },
{ label: t('一周'), args: [0, 7, 0, 0] },
{ label: t('一天'), args: [0, 1, 0, 0] },
].map((item, idx) => (
<button
key={idx}
type='button'
onClick={() => setExpiredTime(...item.args)}
className={`px-2.5 py-1 text-xs font-medium rounded-lg transition-all ${
item.active
? 'bg-brand text-white shadow-sm shadow-brand/30'
: 'bg-white dark:bg-neutral-700 text-gray-600 dark:text-gray-300 hover:bg-brand/[0.08] hover:text-brand-deep hover:border-brand/30 border border-gray-200 dark:border-neutral-600'
}`}
>
{item.label}
</button>
))}
</div>
</div>
{/* 新建数量 */}
{!isEdit && (
<div>
<FieldLabel icon={Hash} iconColor='text-brand'>
{t('新建数量')}
</FieldLabel>
<Form.InputNumber
field='tokenCount'
noLabel
min={1}
max={100}
rules={[
{ required: true, message: t('请输入新建数量') },
]}
style={{ width: '100%' }}
/>
<p className='text-[11px] text-gray-400 mt-1'>
{t('批量创建时会在名称后自动添加随机后缀')}
</p>
</div>
)}
</div>
{/* 高级设置区块 */}
<div className='rounded-xl border border-gray-200 dark:border-neutral-700 overflow-hidden'>
<button
type='button'
onClick={() => setAdvancedOpen(!advancedOpen)}
className='app-action-button w-full flex items-center justify-between px-4 py-3 bg-white dark:bg-neutral-900 hover:bg-gray-50 dark:hover:bg-neutral-800 transition-colors'
>
<div className='flex items-center gap-2'>
<ActionSettings2 size={15} className='text-brand' />
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
{t('高级设置')}
</span>
<span className='text-[11px] text-gray-400 dark:text-gray-500 ml-1'>
{t('额度、模型限制、IP白名单')}
</span>
</div>
<IconChevronDown
size={16}
className={`text-gray-400 transition-transform duration-200 ${advancedOpen ? 'rotate-180' : ''}`}
/>
</button>
<Collapsible isOpen={advancedOpen} keepDOM>
<div className='px-4 pb-4 pt-2 bg-white dark:bg-neutral-900 space-y-4'>
{/* 额度设置 */}
<div className='space-y-3'>
<div className='flex items-center gap-1.5'>
<CreditCard size={14} className='text-brand' />
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
{t('额度设置')}
</span>
</div>
<Form.Switch
field='unlimited_quota'
label={t('无限额度')}
extraText={t('开启后密钥不限制使用额度')}
/>
{!values.unlimited_quota && (
<FormQuotaInput
field='remain_quota'
label={t('额度上限')}
rules={[
{ required: true, message: t('请输入额度') },
]}
style={{ width: '100%' }}
/>
)}
</div>
<div className='h-px bg-brand/50 dark:bg-brand-deep/30' />
{/* 访问限制 */}
<div className='space-y-3'>
<div className='flex items-center gap-1.5'>
<Shield size={14} className='text-brand' />
<span className='text-sm font-medium text-gray-700 dark:text-gray-300'>
{t('访问限制')}
</span>
</div>
<Form.Select
field='model_limits'
label={t('模型限制')}
placeholder={t('留空则支持所有模型')}
multiple
optionList={models}
extraText={t('非必要不建议启用')}
filter={selectFilter}
autoClearSearchValue={false}
searchPosition='dropdown'
showClear
style={{ width: '100%' }}
/>
<Form.TextArea
field='allow_ips'
label={t('IP白名单')}
placeholder={t('允许的IP,一行一个')}
autosize
rows={2}
extraText={t('不填则不限制,IP可能被伪造')}
showClear
style={{ width: '100%' }}
/>
<Form.Switch
field='skill_injection_enabled'
label={t('技能注入')}
extraText={t(
'开启后,用该密钥调用对话类接口时会自动前置技能约束。注入文本按正常 prompt token 计费,归属本密钥所属方。',
)}
/>
<Form.Select
field='skill_ids'
label={t('绑定技能')}
placeholder={t('留空则跟随「我的技能」')}
multiple
optionList={skillOptions}
extraText={t(
'最多同时生效 5 个。注意:前置注入会改变 system 前缀,已使用 prompt 缓存的高频调用可能缓存失效、成本上升。',
)}
filter={selectFilter}
autoClearSearchValue={false}
searchPosition='dropdown'
showClear
style={{ width: '100%' }}
/>
</div>
</div>
</Collapsible>
</div>
</div>
)}
</Form>
</Spin>
{/* 底部按钮 */}
<div className='flex gap-3 px-5 py-4 border-t border-gray-100 dark:border-neutral-800 bg-white dark:bg-neutral-900'>
<Button
theme='solid'
className='flex-1 !h-10 !rounded-xl !font-medium !border-0 !text-white !bg-gradient-to-r !from-brand-from !via-brand !to-brand-to shadow-lg shadow-brand/30 hover:!opacity-90'
onClick={() => formApiRef.current?.submitForm()}
icon={<ActionCheck size={16} />}
loading={loading}
>
{isEdit ? t('保存修改') : t('创建密钥')}
</Button>
<Button
theme='light'
className='!h-10 !px-5 !rounded-xl'
onClick={handleCancel}
>
{t('取消')}
</Button>
</div>
</div>
</Modal>
);
};
export default EditTokenModal;