feat: Add prefill group management system for models

- Add new PrefillGroup model with CRUD operations
  * Support for model, tag, and endpoint group types
  * JSON storage for group items with GORM datatypes
  * Automatic database migration support

- Implement backend API endpoints
  * GET /api/prefill_group - List groups by type with admin auth
  * POST /api/prefill_group - Create new groups
  * PUT /api/prefill_group - Update existing groups
  * DELETE /api/prefill_group/:id - Delete groups

- Add comprehensive frontend management interface
  * PrefillGroupManagement component for group listing
  * EditPrefillGroupModal for group creation/editing
  * Integration with EditModelModal for auto-filling
  * Responsive design with CardTable and SideSheet

- Enhance model editing workflow
  * Tag group selection with auto-fill functionality
  * Endpoint group selection with auto-fill functionality
  * Seamless integration with existing model forms

- Create reusable UI components
  * Extract common rendering utilities to models/ui/
  * Shared renderLimitedItems and renderDescription functions
  * Consistent styling across all model-related components

- Improve user experience
  * Empty state illustrations matching existing patterns
  * Fixed column positioning for operation buttons
  * Item content display with +x indicators for overflow
  * Tooltip support for long descriptions
This commit is contained in:
t0ng7u
2025-08-04 02:54:37 +08:00
parent b64c8ea56b
commit 9f6027325c
13 changed files with 803 additions and 45 deletions

View File

@@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
import React, { useState } from 'react';
import MissingModelsModal from './modals/MissingModelsModal.jsx';
import PrefillGroupManagement from './modals/PrefillGroupManagement.jsx';
import { Button, Space, Modal } from '@douyinfe/semi-ui';
import CompactModeToggle from '../../common/ui/CompactModeToggle';
import { showError } from '../../../helpers';
@@ -35,6 +36,7 @@ const ModelsActions = ({
// Modal states
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [showMissingModal, setShowMissingModal] = useState(false);
const [showGroupManagement, setShowGroupManagement] = useState(false);
// Handle delete selected models with confirmation
const handleDeleteSelectedModels = () => {
@@ -86,6 +88,15 @@ const ModelsActions = ({
{t('未配置模型')}
</Button>
<Button
type="secondary"
className="flex-1 md:flex-initial"
size="small"
onClick={() => setShowGroupManagement(true)}
>
{t('预填组管理')}
</Button>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
@@ -115,6 +126,11 @@ const ModelsActions = ({
}}
t={t}
/>
<PrefillGroupManagement
visible={showGroupManagement}
onClose={() => setShowGroupManagement(false)}
/>
</>
);
};

View File

@@ -23,14 +23,14 @@ import {
Space,
Tag,
Typography,
Modal,
Popover
Modal
} from '@douyinfe/semi-ui';
import {
timestamp2string,
getLobeHubIcon,
stringToColor
} from '../../../helpers';
import { renderLimitedItems, renderDescription } from './ui/RenderUtils.jsx';
const { Text } = Typography;
@@ -39,34 +39,6 @@ function renderTimestamp(timestamp) {
return <>{timestamp2string(timestamp)}</>;
}
// Generic renderer for list-style tags with limit and popover
function renderLimitedItems({ items, renderItem, maxDisplay = 3 }) {
if (!items || items.length === 0) return '-';
const displayItems = items.slice(0, maxDisplay);
const remainingItems = items.slice(maxDisplay);
return (
<Space spacing={1} wrap>
{displayItems.map((item, idx) => renderItem(item, idx))}
{remainingItems.length > 0 && (
<Popover
content={
<div className='p-2'>
<Space spacing={1} wrap>
{remainingItems.map((item, idx) => renderItem(item, idx))}
</Space>
</div>
}
position='top'
>
<Tag size='small' shape='circle' color='grey'>
+{remainingItems.length}
</Tag>
</Popover>
)}
</Space>
);
}
// Render vendor column with icon
const renderVendorTag = (vendorId, vendorMap, t) => {
if (!vendorId || !vendorMap[vendorId]) return '-';
@@ -82,15 +54,6 @@ const renderVendorTag = (vendorId, vendorMap, t) => {
);
};
// Render description with ellipsis
const renderDescription = (text) => {
return (
<Text ellipsis={{ showTooltip: true }} style={{ maxWidth: 200 }}>
{text || '-'}
</Text>
);
};
// Render groups (enable_groups)
const renderGroups = (groups) => {
if (!groups || groups.length === 0) return '-';
@@ -223,7 +186,7 @@ export const getModelsColumns = ({
{
title: t('描述'),
dataIndex: 'description',
render: renderDescription,
render: (text) => renderDescription(text, 200),
},
{
title: t('供应商'),

View File

@@ -61,6 +61,10 @@ const EditModelModal = (props) => {
// 供应商列表
const [vendors, setVendors] = useState([]);
// 预填组(标签、端点)
const [tagGroups, setTagGroups] = useState([]);
const [endpointGroups, setEndpointGroups] = useState([]);
// 获取供应商列表
const fetchVendors = async () => {
try {
@@ -74,9 +78,28 @@ const EditModelModal = (props) => {
}
};
// 获取预填组(标签、端点)
const fetchPrefillGroups = async () => {
try {
const [tagRes, endpointRes] = await Promise.all([
API.get('/api/prefill_group?type=tag'),
API.get('/api/prefill_group?type=endpoint'),
]);
if (tagRes?.data?.success) {
setTagGroups(tagRes.data.data || []);
}
if (endpointRes?.data?.success) {
setEndpointGroups(endpointRes.data.data || []);
}
} catch (error) {
// ignore
}
};
useEffect(() => {
if (props.visiable) {
fetchVendors();
fetchPrefillGroups();
}
}, [props.visiable]);
@@ -287,6 +310,23 @@ const EditModelModal = (props) => {
showClear
/>
</Col>
<Col span={24}>
<Form.Select
field='tag_group'
label={t('标签组')}
placeholder={t('选择标签组后将自动填充标签')}
optionList={tagGroups.map(g => ({ label: g.name, value: g.id }))}
showClear
style={{ width: '100%' }}
onChange={(value) => {
const g = tagGroups.find(item => item.id === value);
if (g && formApiRef.current) {
formApiRef.current.setValue('tags', g.items || []);
}
}}
/>
</Col>
<Col span={24}>
<Form.TagInput
field='tags'
@@ -353,6 +393,23 @@ const EditModelModal = (props) => {
</div>
</div>
<Row gutter={12}>
<Col span={24}>
<Form.Select
field='endpoint_group'
label={t('端点组')}
placeholder={t('选择端点组后将自动填充端点')}
optionList={endpointGroups.map(g => ({ label: g.name, value: g.id }))}
showClear
style={{ width: '100%' }}
onChange={(value) => {
const g = endpointGroups.find(item => item.id === value);
if (g && formApiRef.current) {
formApiRef.current.setValue('endpoints', g.items || []);
}
}}
/>
</Col>
<Col span={24}>
<Form.Select
field='endpoints'

View File

@@ -0,0 +1,234 @@
/*
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, { useState, useRef } from 'react';
import {
SideSheet,
Button,
Form,
Typography,
Space,
Tag,
Row,
Col,
Card,
Avatar,
Spin,
} from '@douyinfe/semi-ui';
import {
IconLayers,
IconSave,
IconClose,
} from '@douyinfe/semi-icons';
import { API, showError, showSuccess } from '../../../../helpers';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const { Text, Title } = Typography;
const EditPrefillGroupModal = ({ visible, onClose, editingGroup, onSuccess }) => {
const { t } = useTranslation();
const isMobile = useIsMobile();
const [loading, setLoading] = useState(false);
const formRef = useRef(null);
const isEdit = editingGroup && editingGroup.id !== undefined;
const typeOptions = [
{ label: t('模型组'), value: 'model' },
{ label: t('标签组'), value: 'tag' },
{ label: t('端点组'), value: 'endpoint' },
];
// 提交表单
const handleSubmit = async (values) => {
setLoading(true);
try {
const submitData = {
...values,
items: Array.isArray(values.items) ? values.items : [],
};
if (editingGroup.id) {
submitData.id = editingGroup.id;
const res = await API.put('/api/prefill_group', submitData);
if (res.data.success) {
showSuccess(t('更新成功'));
onSuccess();
} else {
showError(res.data.message || t('更新失败'));
}
} else {
const res = await API.post('/api/prefill_group', submitData);
if (res.data.success) {
showSuccess(t('创建成功'));
onSuccess();
} else {
showError(res.data.message || t('创建失败'));
}
}
} catch (error) {
showError(t('操作失败'));
}
setLoading(false);
};
return (
<SideSheet
placement="left"
title={
<Space>
{isEdit ? (
<Tag color='blue' shape='circle'>
{t('更新')}
</Tag>
) : (
<Tag color='green' shape='circle'>
{t('新建')}
</Tag>
)}
<Title heading={4} className='m-0'>
{isEdit ? t('更新预填组') : t('创建新的预填组')}
</Title>
</Space>
}
visible={visible}
onCancel={onClose}
width={isMobile ? '100%' : 600}
bodyStyle={{ padding: '0' }}
footer={
<div className='flex justify-end bg-white'>
<Space>
<Button
theme='solid'
className='!rounded-lg'
onClick={() => formRef.current?.submitForm()}
icon={<IconSave />}
loading={loading}
>
{t('提交')}
</Button>
<Button
theme='light'
className='!rounded-lg'
type='primary'
onClick={onClose}
icon={<IconClose />}
>
{t('取消')}
</Button>
</Space>
</div>
}
closeIcon={null}
>
<Spin spinning={loading}>
<Form
getFormApi={(api) => (formRef.current = api)}
initValues={{
name: editingGroup?.name || '',
type: editingGroup?.type || 'tag',
description: editingGroup?.description || '',
items: (() => {
try {
return typeof editingGroup?.items === 'string'
? JSON.parse(editingGroup.items)
: editingGroup?.items || [];
} catch {
return [];
}
})(),
}}
onSubmit={handleSubmit}
>
<div className='p-2'>
{/* 基本信息 */}
<Card className='!rounded-2xl shadow-sm border-0'>
<div className='flex items-center mb-2'>
<Avatar size='small' color='green' className='mr-2 shadow-md'>
<IconLayers size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('基本信息')}</Text>
<div className='text-xs text-gray-600'>{t('设置预填组的基本信息')}</div>
</div>
</div>
<Row gutter={12}>
<Col span={24}>
<Form.Input
field="name"
label={t('组名')}
placeholder={t('请输入组名')}
rules={[{ required: true, message: t('请输入组名') }]}
showClear
/>
</Col>
<Col span={24}>
<Form.Select
field="type"
label={t('类型')}
placeholder={t('选择组类型')}
optionList={typeOptions}
rules={[{ required: true, message: t('请选择组类型') }]}
style={{ width: '100%' }}
/>
</Col>
<Col span={24}>
<Form.TextArea
field="description"
label={t('描述')}
placeholder={t('请输入组描述')}
rows={3}
showClear
/>
</Col>
</Row>
</Card>
{/* 内容配置 */}
<Card className='!rounded-2xl shadow-sm border-0'>
<div className='flex items-center mb-2'>
<Avatar size='small' color='purple' className='mr-2 shadow-md'>
<IconLayers size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('内容配置')}</Text>
<div className='text-xs text-gray-600'>{t('配置组内包含的项目')}</div>
</div>
</div>
<Row gutter={12}>
<Col span={24}>
<Form.TagInput
field="items"
label={t('项目')}
placeholder={t('输入项目名称,按回车添加')}
addOnBlur
showClear
style={{ width: '100%' }}
/>
</Col>
</Row>
</Card>
</div>
</Form>
</Spin>
</SideSheet>
);
};
export default EditPrefillGroupModal;

View File

@@ -22,7 +22,8 @@ import { Modal, Table, Spin, Button, Typography, Empty, Input } from '@douyinfe/
import { IllustrationNoResult, IllustrationNoResultDark } from '@douyinfe/semi-illustrations';
import { IconSearch } from '@douyinfe/semi-icons';
import { API, showError } from '../../../../helpers';
import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants/index.js';
import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
const MissingModelsModal = ({
visible,
@@ -34,6 +35,7 @@ const MissingModelsModal = ({
const [missingModels, setMissingModels] = useState([]);
const [searchKeyword, setSearchKeyword] = useState('');
const [currentPage, setCurrentPage] = useState(1);
const isMobile = useIsMobile();
const fetchMissing = async () => {
setLoading(true);
@@ -87,6 +89,8 @@ const MissingModelsModal = ({
{
title: '',
dataIndex: 'operate',
fixed: 'right',
width: 100,
render: (text, record) => (
<Button
type="primary"
@@ -116,7 +120,7 @@ const MissingModelsModal = ({
visible={visible}
onCancel={onClose}
footer={null}
width={700}
size={isMobile ? 'full-width' : 'medium'}
className="!rounded-lg"
>
<Spin spinning={loading}>

View File

@@ -0,0 +1,271 @@
/*
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, { useState, useEffect } from 'react';
import {
SideSheet,
Button,
Typography,
Space,
Tag,
Popconfirm,
Card,
Avatar,
Spin,
Empty,
} from '@douyinfe/semi-ui';
import {
IconPlus,
IconLayers,
} from '@douyinfe/semi-icons';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '@douyinfe/semi-illustrations';
import { API, showError, showSuccess, stringToColor } from '../../../../helpers';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import CardTable from '../../../common/ui/CardTable.js';
import EditPrefillGroupModal from './EditPrefillGroupModal.jsx';
import { renderLimitedItems, renderDescription } from '../ui/RenderUtils.jsx';
const { Text, Title } = Typography;
const PrefillGroupManagement = ({ visible, onClose }) => {
const { t } = useTranslation();
const isMobile = useIsMobile();
const [loading, setLoading] = useState(false);
const [groups, setGroups] = useState([]);
const [showEdit, setShowEdit] = useState(false);
const [editingGroup, setEditingGroup] = useState({ id: undefined });
const typeOptions = [
{ label: t('模型组'), value: 'model' },
{ label: t('标签组'), value: 'tag' },
{ label: t('端点组'), value: 'endpoint' },
];
// 加载组列表
const loadGroups = async () => {
setLoading(true);
try {
const res = await API.get('/api/prefill_group');
if (res.data.success) {
setGroups(res.data.data || []);
} else {
showError(res.data.message || t('获取组列表失败'));
}
} catch (error) {
showError(t('获取组列表失败'));
}
setLoading(false);
};
// 删除组
const deleteGroup = async (id) => {
try {
const res = await API.delete(`/api/prefill_group/${id}`);
if (res.data.success) {
showSuccess(t('删除成功'));
loadGroups();
} else {
showError(res.data.message || t('删除失败'));
}
} catch (error) {
showError(t('删除失败'));
}
};
// 编辑组
const handleEdit = (group = {}) => {
setEditingGroup(group);
setShowEdit(true);
};
// 关闭编辑
const closeEdit = () => {
setShowEdit(false);
setTimeout(() => {
setEditingGroup({ id: undefined });
}, 300);
};
// 编辑成功回调
const handleEditSuccess = () => {
closeEdit();
loadGroups();
};
// 表格列定义
const columns = [
{
title: t('组名'),
dataIndex: 'name',
key: 'name',
render: (text, record) => (
<Space>
<Text strong>{text}</Text>
<Tag color="white" shape="circle" size="small">
{typeOptions.find(opt => opt.value === record.type)?.label || record.type}
</Tag>
</Space>
),
},
{
title: t('描述'),
dataIndex: 'description',
key: 'description',
render: (text) => renderDescription(text, 150),
},
{
title: t('项目内容'),
dataIndex: 'items',
key: 'items',
render: (items) => {
try {
const itemsArray = typeof items === 'string' ? JSON.parse(items) : items;
if (!Array.isArray(itemsArray) || itemsArray.length === 0) {
return <Text type="tertiary">{t('暂无项目')}</Text>;
}
return renderLimitedItems({
items: itemsArray,
renderItem: (item, idx) => (
<Tag key={idx} size="small" shape='circle' color={stringToColor(item)}>
{item}
</Tag>
),
maxDisplay: 3,
});
} catch {
return <Text type="tertiary">{t('数据格式错误')}</Text>;
}
},
},
{
title: '',
key: 'action',
fixed: 'right',
width: 140,
render: (_, record) => (
<Space>
<Button
size="small"
onClick={() => handleEdit(record)}
>
{t('编辑')}
</Button>
<Popconfirm
title={t('确定删除此组?')}
onConfirm={() => deleteGroup(record.id)}
>
<Button
size="small"
type="danger"
>
{t('删除')}
</Button>
</Popconfirm>
</Space>
),
},
];
useEffect(() => {
if (visible) {
loadGroups();
}
}, [visible]);
return (
<>
<SideSheet
placement="left"
title={
<Space>
<Tag color='blue' shape='circle'>
{t('管理')}
</Tag>
<Title heading={4} className='m-0'>
{t('预填组管理')}
</Title>
</Space>
}
visible={visible}
onCancel={onClose}
width={isMobile ? '100%' : 800}
bodyStyle={{ padding: '0' }}
closeIcon={null}
>
<Spin spinning={loading}>
<div className='p-2'>
<Card className='!rounded-2xl shadow-sm border-0'>
<div className='flex items-center mb-2'>
<Avatar size='small' color='blue' className='mr-2 shadow-md'>
<IconLayers size={16} />
</Avatar>
<div>
<Text className='text-lg font-medium'>{t('组列表')}</Text>
<div className='text-xs text-gray-600'>{t('管理模型、标签、端点等预填组')}</div>
</div>
</div>
<div className="flex justify-end mb-4">
<Button
type="primary"
theme='solid'
size="small"
icon={<IconPlus />}
onClick={() => handleEdit()}
>
{t('新建组')}
</Button>
</div>
{groups.length > 0 ? (
<CardTable
columns={columns}
dataSource={groups}
rowKey="id"
hidePagination={true}
size="small"
scroll={{ x: 'max-content' }}
/>
) : (
<Empty
image={<IllustrationNoResult style={{ width: 150, height: 150 }} />}
darkModeImage={<IllustrationNoResultDark style={{ width: 150, height: 150 }} />}
description={t('暂无预填组')}
style={{ padding: 30 }}
/>
)}
</Card>
</div>
</Spin>
</SideSheet>
{/* 编辑组件 */}
<EditPrefillGroupModal
visible={showEdit}
onClose={closeEdit}
editingGroup={editingGroup}
onSuccess={handleEditSuccess}
/>
</>
);
};
export default PrefillGroupManagement;

View File

@@ -0,0 +1,60 @@
/*
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 from 'react';
import { Space, Tag, Typography, Popover } from '@douyinfe/semi-ui';
const { Text } = Typography;
// 通用渲染函数限制项目数量显示支持popover展开
export function renderLimitedItems({ items, renderItem, maxDisplay = 3 }) {
if (!items || items.length === 0) return '-';
const displayItems = items.slice(0, maxDisplay);
const remainingItems = items.slice(maxDisplay);
return (
<Space spacing={1} wrap>
{displayItems.map((item, idx) => renderItem(item, idx))}
{remainingItems.length > 0 && (
<Popover
content={
<div className='p-2'>
<Space spacing={1} wrap>
{remainingItems.map((item, idx) => renderItem(item, idx))}
</Space>
</div>
}
position='top'
>
<Tag size='small' shape='circle' color='grey'>
+{remainingItems.length}
</Tag>
</Popover>
)}
</Space>
);
}
// 渲染描述字段长文本支持tooltip
export const renderDescription = (text, maxWidth = 200) => {
return (
<Text ellipsis={{ showTooltip: true }} style={{ maxWidth }}>
{text || '-'}
</Text>
);
};