Files
monkey-ai-web/src/components/table/users/modals/EditUserModal.jsx
T
zhanjunhao 34e318454d fix(ui): 统一三中心表格交互并优化企业及配套页面
- 公共表格:统一分组标签、状态开关和危险操作确认,支持防重复提交和失败重试,修复浮层触发组件的 ref 转发。
- 控制台:统一用户和渠道编辑抽屉,修正分组回填与提交格式,对齐系统设置操作区和预约列表。
- 企业中心:调整技能中心页签和窄屏布局,优化质量监控提示栏、效能分析及成本对账,统一消耗明细和审计日志筛选。
- 用户中心及公共页面:优化密钥和消费记录展示,对齐模型超市筛选,统一公开与内嵌客户端下载页。
- 同步多语言文案、组件规范与移动端视口要求。
2026-11-24 15:00:30 +08:00

439 lines
15 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.
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useEffect, useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess, renderQuota } from '../../../../helpers';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import {
Button,
Modal,
SideSheet,
Spin,
Typography,
Card,
Form,
Avatar,
Row,
Col,
} from '@/components/ui';
import QuotaInput, { FormQuotaInput } from '../../../common/ui/QuotaInput';
import {
User as ActionUser,
Link as ActionLink,
Users as ActionUsers,
Plus as ActionPlus,
} from '@/components/common/icons/ActionIcons';
import { toGroupList } from '@/helpers/groupList';
const { Text } = Typography;
const EditUserModal = (props) => {
const { t } = useTranslation();
const userId = props.editingUser.id;
const [loading, setLoading] = useState(true);
const [loadedUserId, setLoadedUserId] = useState(null);
const [submitting, setSubmitting] = useState(false);
const pending = useRef(false);
const [addQuotaModalOpen, setIsModalOpen] = useState(false);
const [addQuotaLocal, setAddQuotaLocal] = useState('');
const isMobile = useIsMobile();
const [groupOptions, setGroupOptions] = useState([]);
const [levelOptions, setLevelOptions] = useState([]);
const formApiRef = useRef(null);
const isEdit = Boolean(userId);
const ready = loadedUserId === (userId ?? false);
const getInitValues = () => ({
username: '',
display_name: '',
password: '',
github_id: '',
oidc_id: '',
discord_id: '',
wechat_id: '',
telegram_id: '',
email: '',
quota: 0,
group: userId ? ['default'] : 'default',
level: '',
remark: '',
});
const fetchGroups = async () => {
try {
let res = await API.get(`/api/group/`);
setGroupOptions(res.data.data.map((g) => ({ label: g, value: g })));
} catch (e) {
showError(e.message);
}
};
const fetchLevels = async () => {
try {
// 个人等级下拉:选项取 personal 注册表。空选项 = 不受限(存量默认)。
// 走 /api/group/personal_levels(AdminAuth,仅返回 code+名称),普通管理员也能取到选项;
// /api/level 仍受 level_policy 权限控制,不在此使用。
// skipErrorHandler:失败时静默降级为仅「不限制」,不弹全局错误。
let res = await API.get(`/api/group/personal_levels`, {
skipErrorHandler: true,
});
if (res?.data?.success) {
const opts = (res.data.data?.levels || []).map((l) => ({
label: l.name ? `${l.name} (${l.code})` : l.code,
value: l.code,
}));
setLevelOptions([{ label: t('不限制(默认)'), value: '' }, ...opts]);
} else {
setLevelOptions([{ label: t('不限制(默认)'), value: '' }]);
}
} catch (e) {
// 请求失败或未配置:静默降级为仅「不限制」
setLevelOptions([{ label: t('不限制(默认)'), value: '' }]);
}
};
const handleCancel = () => {
if (pending.current) return;
setIsModalOpen(false);
setAddQuotaLocal('');
props.handleClose();
};
const onScopeChange = useEffectEvent(async (isCurrent) => {
setLoading(true);
setLoadedUserId(null);
const url = userId ? `/api/user/${userId}` : '/api/user/self';
if (userId) {
fetchGroups();
fetchLevels();
}
try {
const { data: response } = await API.get(url);
if (!isCurrent()) return;
if (response.success) {
formApiRef.current?.setValues({
...getInitValues(),
...response.data,
...(userId && {
group: toGroupList(response.data.group ?? 'default'),
}),
password: '',
});
setLoadedUserId(userId ?? false);
} else {
showError(response.message);
}
} catch {
// The API client reports request failures.
} finally {
if (isCurrent()) setLoading(false);
}
});
useEffect(() => {
if (!props.visible) return;
let current = true;
onScopeChange(() => current);
return () => {
current = false;
};
}, [onScopeChange, props.visible, userId]);
/* ----------------------- submit ----------------------- */
const submit = async (values) => {
if (!ready || pending.current) return;
pending.current = true;
setSubmitting(true);
try {
const payload = { ...values };
if (typeof payload.quota === 'string')
payload.quota = parseInt(payload.quota) || 0;
if (typeof payload.gift_quota === 'string')
payload.gift_quota = parseInt(payload.gift_quota) || 0;
if (userId) {
payload.id = parseInt(userId);
payload.group = toGroupList(values.group).join(',');
}
const url = userId ? '/api/user/' : '/api/user/self';
const { data } = await API.put(url, payload);
if (data.success) {
showSuccess(t('用户信息更新成功!'));
props.refresh();
props.handleClose();
} else {
showError(data.message);
}
} catch {
// The API client reports request failures.
} finally {
pending.current = false;
setSubmitting(false);
}
};
/* --------------------- quota helper -------------------- */
const addLocalQuota = () => {
const current = parseInt(formApiRef.current?.getValue('quota') || 0);
const delta = parseInt(addQuotaLocal) || 0;
formApiRef.current?.setValue('quota', current + delta);
};
/* --------------------------- UI --------------------------- */
return (
<>
<SideSheet
placement='right'
rootClassName='console-user-drawer'
classNames={{ header: 'console-user-editor-header' }}
title={isEdit ? t('编辑用户') : t('创建用户')}
bodyStyle={{ padding: 0 }}
visible={props.visible}
width={isMobile ? '100%' : 600}
footer={
<div className='console-user-footer'>
<Button onClick={handleCancel} disabled={submitting}>
{t('取消')}
</Button>
<Button
theme='solid'
type='primary'
disabled={!ready || loading}
loading={submitting}
onClick={() => formApiRef.current?.submitForm()}
>
{t('提交')}
</Button>
</div>
}
onCancel={handleCancel}
>
<Form
initValues={getInitValues()}
getFormApi={(api) => (formApiRef.current = api)}
onSubmit={submit}
>
{() => (
<Spin spinning={loading}>
<div className='console-user-sections p-2'>
{/* 基本信息 */}
<Card className='rounded-2xl shadow-sm'>
<div className='console-user-section'>
<Avatar size='small' color='blue'>
<ActionUser size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>
{t('基本信息')}
</Text>
<div className='console-user-section-description'>
{t('用户的基本账户信息')}
</div>
</div>
</div>
<Row gutter={12}>
<Col span={24}>
<Form.Input
field='username'
label={t('用户名')}
placeholder={t('请输入新的用户名')}
rules={[{ required: true, message: t('请输入用户名') }]}
showClear
/>
</Col>
<Col span={24}>
<Form.Input
field='password'
label={t('密码')}
placeholder={t('请输入新的密码,最短 8 位')}
mode='password'
showClear
/>
</Col>
<Col span={24}>
<Form.Input
field='display_name'
label={t('显示名称')}
placeholder={t('请输入新的显示名称')}
showClear
/>
</Col>
<Col span={24}>
<Form.Input
field='remark'
label={t('备注')}
placeholder={t('请输入备注(仅管理员可见)')}
showClear
/>
</Col>
</Row>
</Card>
{/* 权限设置 */}
{userId && (
<Card className='rounded-2xl shadow-sm'>
<div className='console-user-section'>
<Avatar size='small' color='green'>
<ActionUsers size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>
{t('权限设置')}
</Text>
<div className='console-user-section-description'>
{t('用户分组和额度管理')}
</div>
</div>
</div>
<Row gutter={12}>
<Col span={24}>
<Form.Select
field='group'
label={t('分组')}
placeholder={t('请选择分组')}
optionList={groupOptions}
allowAdditions
search
rules={[{ required: true, message: t('请选择分组') }]}
/>
</Col>
<Col span={24}>
<Form.Select
field='level'
label={t('等级(模型访问)')}
placeholder={t('不限制(默认)')}
optionList={levelOptions}
showClear
extraText={t(
'控制该用户可见/可调用的模型;留空表示不受限。修改会记录审计日志。',
)}
style={{ width: '100%' }}
/>
</Col>
<Col xs={24} sm={12}>
<FormQuotaInput
field='quota'
label={t('剩余额度')}
rules={[{ required: true, message: t('请输入额度') }]}
style={{ width: '100%' }}
/>
</Col>
<Col xs={24} sm={12}>
<FormQuotaInput
field='gift_quota'
label={t('赠送余额')}
extraText={t(
'赠送钱包余额(营销赠送性质,分佣净消耗剔除口径);调整此项即赠送/收回赠送额度',
)}
style={{ width: '100%' }}
/>
</Col>
<Col span={24}>
<Form.Slot label={t('添加额度')}>
<Button
icon={<ActionPlus size={16} />}
aria-label={t('添加额度')}
onClick={() => setIsModalOpen(true)}
/>
</Form.Slot>
</Col>
</Row>
</Card>
)}
{/* 绑定信息 */}
<Card className='rounded-2xl shadow-sm'>
<div className='console-user-section'>
<Avatar size='small' color='purple'>
<ActionLink size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>
{t('绑定信息')}
</Text>
<div className='console-user-section-description'>
{t('第三方账户绑定状态(只读)')}
</div>
</div>
</div>
<Row gutter={12}>
{[
'github_id',
'discord_id',
'oidc_id',
'wechat_id',
'email',
'telegram_id',
].map((field) => (
<Col span={24} key={field}>
<Form.Input
field={field}
label={t('已绑定的 {{provider}} 账户', {
provider: field.replace('_id', '').toUpperCase(),
})}
readonly
placeholder={t(
'此项只读,需要用户通过个人设置页面的相关绑定按钮进行绑定,不可直接修改',
)}
/>
</Col>
))}
</Row>
</Card>
</div>
</Spin>
)}
</Form>
</SideSheet>
{/* 添加额度模态框 */}
<Modal
centered
visible={addQuotaModalOpen}
onOk={() => {
addLocalQuota();
setIsModalOpen(false);
}}
onCancel={() => setIsModalOpen(false)}
closable={null}
title={
<div className='flex items-center'>
<ActionPlus size={16} className='mr-2' />
{t('添加额度')}
</div>
}
>
<div className='mb-4'>
{(() => {
const current = formApiRef.current?.getValue('quota') || 0;
return (
<Text type='secondary' className='block mb-2'>
{`${t('新额度:')}${renderQuota(current)} + ${renderQuota(addQuotaLocal || 0)} = ${renderQuota(current + parseInt(addQuotaLocal || 0))}`}
</Text>
);
})()}
</div>
<QuotaInput
placeholder={t('需要添加的金额(支持负数)')}
value={addQuotaLocal}
onChange={setAddQuotaLocal}
style={{ width: '100%' }}
showClear
/>
</Modal>
</>
);
};
export default EditUserModal;