Files
monkey-ai-web/src/pages/Organization/components/OrgScopedLimitButtons.jsx
T
qiubaishen 635351f539 merge: 合入总仓库 weiyuan(bfdfb339) web/ 新功能,保留 ui-optimization 的 UI 重构
来源:luoguang/monkey-ai weiyuan@bfdfb339 的 web/(经 sync/main-weiyuan-web-bfdfb339 同步)
同步基准:总仓库 a2ca13cb = 本仓库初始导入 d8f3aee2

冲突处理原则:保留 ui-optimization 的 UI(样式/结构/组件),嫁接 weiyuan 的功能逻辑。
- i18n:按键三方合并;ours 的「令牌→密钥」改名键上移植 theirs 的术语修订
- task-logs / OrgLogs:ours 已手工移植同一功能(6ad95e2),保留 ours
- 删除:OrgCreate(theirs 下线 /org/create)、旧 image 组件与 VideoRegenerateModal(theirs 体验中心重写)、
  OrgAvatarSection / PricingBentoPage / CommissionConsole(ours 重构中已移除)
- 测试:users-pagination 的 i18next mock 补 t();theirs 新增文件补 license header
2026-11-10 12:01:21 +08:00

282 lines
9.6 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 React, { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Select, Toast, Tooltip } from '@/components/ui';
import { Layers } from 'lucide-react';
import { API } from '../../../helpers/api';
import { showError } from '../../../helpers';
import OrgModal from './OrgModal';
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
// 解析分组字段:兼容 JSON 字符串/数组;为空表示该维度未配置分组。
const parseGroups = (raw) => {
if (Array.isArray(raw)) return raw;
if (typeof raw === 'string' && raw.trim()) {
try {
const arr = JSON.parse(raw);
if (Array.isArray(arr)) return arr;
} catch {
/* ignore */
}
}
return [];
};
/**
* 部门/项目「模型 / 分组」限制配置入口(操作列复用组件)。
* 生效规则:成员个人、项目、部门按维度取交集,由后端鉴权链路裁决。
*
* props:
* - orgId
* - record: 行数据(含 model_limits_enabled / model_limits / groups)
* - apiBase: '/api/org/dept' 或 '/api/org/project'
* - scopeLabel: '部门' | '项目'(用于弹窗标题与文案)
* - onSaved: 保存成功后回调(刷新列表)
*/
// variant='link':企业中心已按原型对齐的列表页使用 link 按钮(无图标、13px);默认保持原描边按钮
const OrgScopedLimitButtons = ({
orgId,
record,
apiBase,
scopeLabel,
onSaved,
variant = 'default',
}) => {
const { t } = useTranslation();
const [modelModalVisible, setModelModalVisible] = useState(false);
const [orgModels, setOrgModels] = useState([]);
const [loadingModels, setLoadingModels] = useState(false);
const [selectedModels, setSelectedModels] = useState([]);
const [groupsModalVisible, setGroupsModalVisible] = useState(false);
const [orgGroups, setOrgGroups] = useState([]);
const [selectedGroups, setSelectedGroups] = useState([]);
const scopeName = record?.name || '';
const openModelModal = useCallback(async () => {
setSelectedModels(
record.model_limits_enabled && record.model_limits
? record.model_limits.split(',').filter(Boolean)
: [],
);
setModelModalVisible(true);
setLoadingModels(true);
try {
const res = await API.get('/api/org/models', { headers: getOrgHeaders(orgId) });
if (res.data.success) {
setOrgModels((res.data.data || []).map((m) => ({ label: m, value: m })));
}
} catch {
/* ignore */
}
setLoadingModels(false);
}, [orgId, record]);
const openGroupsModal = useCallback(async () => {
setSelectedGroups(parseGroups(record?.groups));
setGroupsModalVisible(true);
try {
const res = await API.get('/api/org/info', { headers: getOrgHeaders(orgId) });
if (res.data.success) {
const org = res.data.data?.organization || {};
let groups = [];
if (Array.isArray(org.groups)) {
groups = org.groups;
} else if (typeof org.groups === 'string' && org.groups.trim()) {
try {
groups = JSON.parse(org.groups);
} catch {
groups = [];
}
}
if (!groups.length && org.group) groups = [org.group];
setOrgGroups(groups.map((g) => ({ label: g, value: g })));
}
} catch {
/* ignore */
}
}, [orgId, record]);
const handleModelSave = useCallback(async () => {
const enabled = selectedModels.length > 0;
try {
const res = await API.put(
`${apiBase}/${record.id}/models`,
{ model_limits_enabled: enabled, model_limits: selectedModels.join(',') },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(t('模型限制已更新'));
setModelModalVisible(false);
onSaved && onSaved();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
}, [apiBase, record, orgId, selectedModels, onSaved, t]);
const handleGroupsSave = useCallback(async () => {
try {
const res = await API.put(
`${apiBase}/${record.id}/groups`,
{ groups: selectedGroups },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
Toast.success(t('分组已更新'));
setGroupsModalVisible(false);
onSaved && onSaved();
} else {
showError(res.data.message);
}
} catch (err) {
showError(err.message);
}
}, [apiBase, record, orgId, selectedGroups, onSaved, t]);
const modelConfigured = record.model_limits_enabled;
const groupConfigured = parseGroups(record?.groups).length > 0;
return (
<>
<Tooltip content={t('设置该{{scope}}成员默认可用的模型范围(与成员/项目/部门限制取交集)', { scope: t(scopeLabel) })}>
<Button
{...(variant === 'link'
? { type: 'link' }
: {
size: 'small',
theme: 'light',
type: modelConfigured ? 'primary' : 'tertiary',
icon: <Layers size={14} />,
})}
onClick={openModelModal}
>
{t('模型')}
</Button>
</Tooltip>
<Tooltip content={t('设置该{{scope}}成员默认可调用的分组(与成员/项目/部门限制取交集)', { scope: t(scopeLabel) })}>
<Button
{...(variant === 'link'
? { type: 'link' }
: {
size: 'small',
theme: 'light',
type: groupConfigured ? 'primary' : 'tertiary',
icon: <Layers size={14} />,
})}
onClick={openGroupsModal}
>
{t('分组')}
</Button>
</Tooltip>
{/* 模型限制 Modal */}
<OrgModal
title={`${t('{{scope}}模型限制', { scope: t(scopeLabel) })}${scopeName ? ` - ${scopeName}` : ''}`}
visible={modelModalVisible}
onOk={handleModelSave}
onCancel={() => setModelModalVisible(false)}
okText={t('保存')}
cancelText={t('取消')}
width={520}
>
<div className='space-y-3'>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t(
'限制该{{scope}}成员默认可使用的模型。留空则该维度不限制;若成员个人、项目、部门同时配置,最终可用模型取交集。',
{ scope: t(scopeLabel) },
)}
</p>
<div>
<label className='flex items-center gap-1.5 text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
<Layers size={14} className='text-brand' />
{t('可用模型')}
<span className='text-xs text-gray-400 font-normal ml-1'>
({t('留空则不限制')})
</span>
</label>
<Select
multiple
value={selectedModels}
onChange={setSelectedModels}
optionList={orgModels}
loading={loadingModels}
placeholder={t('选择可用模型,留空则支持所有模型')}
filter
autoClearSearchValue={false}
searchPosition='dropdown'
showClear
style={{ width: '100%' }}
/>
</div>
</div>
</OrgModal>
{/* 可调用分组 Modal */}
<OrgModal
title={`${t('{{scope}}可调用分组', { scope: t(scopeLabel) })}${scopeName ? ` - ${scopeName}` : ''}`}
visible={groupsModalVisible}
onOk={handleGroupsSave}
onCancel={() => setGroupsModalVisible(false)}
okText={t('保存')}
cancelText={t('取消')}
width={520}
>
<div className='space-y-3'>
<p className='text-sm text-gray-500 dark:text-gray-400'>
{t(
'设置该{{scope}}成员默认可调用的分组,只能从企业已配置的可用分组中选择。留空则该维度不限制;若成员个人、项目、部门同时配置,最终可用分组取交集。',
{ scope: t(scopeLabel) },
)}
</p>
<div>
<label className='flex items-center gap-1.5 text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
<Layers size={14} className='text-brand' />
{t('可调用分组')}
<span className='text-xs text-gray-400 font-normal ml-1'>
({t('留空则不限制')})
</span>
</label>
<Select
multiple
value={selectedGroups}
onChange={setSelectedGroups}
optionList={orgGroups}
placeholder={t('选择可调用的分组')}
filter
autoClearSearchValue={false}
searchPosition='dropdown'
showClear
style={{ width: '100%' }}
/>
</div>
</div>
</OrgModal>
</>
);
};
export default OrgScopedLimitButtons;