Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
+75
View File
@@ -0,0 +1,75 @@
/*
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 { useState, useEffect } from 'react';
import { API, showError } from '../../helpers';
import { MODEL_CATEGORY_NAMES } from '../../constants';
/**
* 加载模型分类数据的 Hook
* @returns {Object} 分类数据和映射
*/
export const useModelCategories = () => {
const [categories, setCategories] = useState([]);
const [categoryNames, setCategoryNames] = useState({
...MODEL_CATEGORY_NAMES,
});
const [loading, setLoading] = useState(false);
// 加载分类数据
const loadCategories = async () => {
setLoading(true);
try {
const res = await API.get('/api/model_categories/flat');
const { success, data, message } = res.data;
if (success) {
const categoriesData = data || [];
setCategories(categoriesData);
// 构建 category_key -> category_name 的映射
const nameMap = { ...MODEL_CATEGORY_NAMES };
categoriesData.forEach((cat) => {
if (cat.category_key && cat.category_name) {
nameMap[cat.category_key] = cat.category_name;
}
});
setCategoryNames(nameMap);
} else {
showError(message || '加载分类失败');
}
} catch (error) {
console.error('Failed to load categories:', error);
// 失败时使用默认映射
} finally {
setLoading(false);
}
};
useEffect(() => {
loadCategories();
}, []);
return {
categories,
categoryNames,
loading,
refresh: loadCategories,
};
};
+262
View File
@@ -0,0 +1,262 @@
/*
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 { useState, useEffect, useCallback } from 'react';
import { API, showError } from '../../helpers';
import {
MODEL_CATEGORY,
inferModelCategory,
getModelsByCategory,
} from '../../constants/model-category.constant';
/**
* 模型选择Hook
* @param {string} category - 模型分类(可选,如果指定则只获取该分类的模型)
*/
export const useModelSelector = (category = null) => {
const [models, setModels] = useState([]);
const [filteredModels, setFilteredModels] = useState([]);
const [loading, setLoading] = useState(false);
const [selectedModel, setSelectedModel] = useState(null);
// 根据前端分类映射到后端 category 参数
const getCategoryParam = useCallback((frontendCategory) => {
if (!frontendCategory) return '';
// 图片相关分类
if (
[
MODEL_CATEGORY.IMAGE_GENERATION,
MODEL_CATEGORY.TEXT_TO_IMAGE,
MODEL_CATEGORY.IMAGE_TO_IMAGE,
].includes(frontendCategory)
) {
return 'image';
}
// 视频相关分类
if (
[
MODEL_CATEGORY.VIDEO_GENERATION,
MODEL_CATEGORY.TEXT_TO_VIDEO,
MODEL_CATEGORY.IMAGE_TO_VIDEO,
].includes(frontendCategory)
) {
return 'video';
}
// 默认返回空(使用文本模型配置)
return '';
}, []);
// 加载模型列表
const loadModels = useCallback(async () => {
setLoading(true);
try {
// 根据分类确定 category 参数
const categoryParam = getCategoryParam(category);
const categoryQuery = categoryParam ? `&category=${categoryParam}` : '';
// 并行获取模型列表和价格信息
// 使用 /api/user/models 接口,普通用户可访问
const [modelsRes, pricingRes] = await Promise.all([
API.get(`/api/user/models/?page_size=1000${categoryQuery}`),
// discount_scope=personal:体验中心/模型选择器的调用恒按个人等级计费,
// 企业 web 会话下若跟随会话作用域会把企业折扣价标给个人计费的调用
API.get('/api/pricing?discount_scope=personal').catch(() => ({
data: { success: true, data: [] },
})), // 如果pricing接口失败,使用空数组
]);
const { success, message, data } = modelsRes.data;
if (success) {
const allModels = data?.items || data || [];
// 等级锁态元数据(§6.2):后端已剔除 hidden,剩余仅 callable/visible;
// visible 表示「仅可见、不可调用」,前端展示锁态并禁止选中提交(最终仍以调用闸门为准)。
const levelStates = data?.level_states || {};
const pricingData = pricingRes.data?.data || [];
const groupRatioMap = pricingRes.data?.group_ratio || {};
// 模型级等级折扣修正系数(四期):{分组: {模型: 系数}},乘在分组倍率之上
const groupModelDiscountMap =
pricingRes.data?.group_model_discount || {};
// 当前登录用户分组(用于计算实际价格 = model_price * 分组倍率)
let userGroup = '';
try {
userGroup =
JSON.parse(localStorage.getItem('user') || '{}')?.group || '';
} catch {
userGroup = '';
}
const userGroupRatio =
typeof groupRatioMap[userGroup] === 'number'
? groupRatioMap[userGroup]
: 1;
// 创建pricing映射表,以模型名称为key
const pricingMap = {};
pricingData.forEach((pricing) => {
pricingMap[pricing.model_name] = pricing;
});
// 为每个模型推断分类(如果没有 categories 字段)并添加价格信息
const modelsWithCategory = allModels.map((model) => {
// 添加价格信息
const pricing = pricingMap[model.model_name] || {};
let modelWithCategory = { ...model };
// 如果后端返回了 categories 数组,直接使用
if (Array.isArray(model.categories) && model.categories.length > 0) {
modelWithCategory = model;
}
// 如果有 category 单个字段,转换为 categories 数组
else if (model.category) {
modelWithCategory = {
...model,
categories: [model.category],
};
}
// 否则通过模型名称推断分类
else {
const inferredCategory = inferModelCategory(
model.model_name,
model.endpoint_type,
);
modelWithCategory = {
...model,
categories: [inferredCategory],
};
}
// 合并价格信息(group_ratio 为当前用户所在分组的有效倍率,已含该模型的等级折扣修正)
return {
...modelWithCategory,
model_ratio: pricing.model_ratio,
model_price: pricing.model_price,
quota_type: pricing.quota_type,
completion_ratio: pricing.completion_ratio,
// 浮点乘积收敛 4 位小数,避免展示 0.7200000000000001 类脏数字
group_ratio: parseFloat(
(
userGroupRatio *
(groupModelDiscountMap?.[userGroup]?.[model.model_name] ?? 1)
).toFixed(4),
),
// callable(默认)/ visible(锁定,不可调用)
level_state: levelStates[model.model_name] || 'callable',
level_locked: levelStates[model.model_name] === 'visible',
};
});
setModels(modelsWithCategory);
// 如果指定了分类,进行筛选
if (category) {
const filtered = getModelsByCategory(modelsWithCategory, category);
setFilteredModels(filtered);
// 自动选择第一个「可调用」模型(避免默认选中锁定模型导致提交即 403)
if (filtered.length > 0) {
const firstCallable = filtered.find((m) => !m.level_locked);
setSelectedModel((prev) =>
prev && filtered.some((m) => m.id === prev.id && !m.level_locked)
? prev
: firstCallable || null,
);
} else {
setSelectedModel(null);
}
} else {
setFilteredModels(modelsWithCategory);
}
} else {
showError(message || '获取模型列表失败');
}
} catch (error) {
console.error('加载模型失败:', error);
showError('加载模型失败: ' + error.message);
} finally {
setLoading(false);
}
}, [category, getCategoryParam]);
// 切换模型分类
const filterByCategory = useCallback(
(newCategory) => {
if (newCategory) {
const filtered = getModelsByCategory(models, newCategory);
setFilteredModels(filtered);
// 自动选择第一个「可调用」模型
if (filtered.length > 0) {
setSelectedModel(filtered.find((m) => !m.level_locked) || null);
} else {
setSelectedModel(null);
}
} else {
setFilteredModels(models);
}
},
[models],
);
// 根据ID选择模型
const selectModelById = useCallback(
(modelId) => {
const model = filteredModels.find((m) => m.id === modelId);
if (model && !model.level_locked) {
setSelectedModel(model);
}
},
[filteredModels],
);
// 根据模型名称选择模型
const selectModelByName = useCallback(
(modelName) => {
const model = filteredModels.find((m) => m.model_name === modelName);
if (model && !model.level_locked) {
setSelectedModel(model);
}
},
[filteredModels],
);
// 初始加载和category变化时重新加载
useEffect(() => {
loadModels();
}, [loadModels]);
return {
// 数据
allModels: models,
models: filteredModels,
selectedModel,
loading,
// 操作方法
loadModels,
filterByCategory,
selectModelById,
selectModelByName,
setSelectedModel,
};
};
+534
View File
@@ -0,0 +1,534 @@
/*
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 { useState, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess } from '../../helpers';
import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode';
export const useModelsData = () => {
const { t } = useTranslation();
const [compactMode, setCompactMode] = useTableCompactMode('models');
// State management
const [models, setModels] = useState([]);
const [loading, setLoading] = useState(true);
const [activePage, setActivePage] = useState(1);
const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
const [searching, setSearching] = useState(false);
const [modelCount, setModelCount] = useState(0);
// Modal states
const [showEdit, setShowEdit] = useState(false);
const [editingModel, setEditingModel] = useState({
id: undefined,
});
// Row selection
const [selectedKeys, setSelectedKeys] = useState([]);
const rowSelection = {
getCheckboxProps: (record) => ({
name: record.model_name,
}),
selectedRowKeys: selectedKeys.map((model) => model.id),
onChange: (selectedRowKeys, selectedRows) => {
setSelectedKeys(selectedRows);
},
};
// Form initial values
const formInitValues = {
searchKeyword: '',
searchVendor: '',
searchCategory: '',
};
// ---------- helpers ----------
// Safely extract array items from API payload
const extractItems = (payload) => {
const items = payload?.items || payload || [];
return Array.isArray(items) ? items : [];
};
// Form API reference
const [formApi, setFormApi] = useState(null);
// Get form values helper function
const getFormValues = () => formApi?.getValues() || formInitValues;
// Close edit modal
const closeEdit = () => {
setShowEdit(false);
setTimeout(() => {
setEditingModel({ id: undefined });
}, 500);
};
// Set model format with key field
const setModelFormat = (models) => {
for (let i = 0; i < models.length; i++) {
models[i].key = models[i].id;
}
setModels(models);
};
// Vendor list
const [vendors, setVendors] = useState([]);
const [vendorCounts, setVendorCounts] = useState({});
const [activeVendorKey, setActiveVendorKey] = useState('all');
const [showAddVendor, setShowAddVendor] = useState(false);
const [showEditVendor, setShowEditVendor] = useState(false);
const [editingVendor, setEditingVendor] = useState({ id: undefined });
const [syncing, setSyncing] = useState(false);
const [previewing, setPreviewing] = useState(false);
const vendorMap = useMemo(() => {
const map = {};
vendors.forEach((v) => {
map[v.id] = v;
});
return map;
}, [vendors]);
// Load vendor list
const loadVendors = async () => {
try {
const res = await API.get('/api/vendors/?page_size=1000');
if (res.data.success) {
const items = res.data.data.items || res.data.data || [];
setVendors(Array.isArray(items) ? items : []);
}
} catch (_) {
// ignore
}
};
// Load models data
const loadModels = async (
page = 1,
size = pageSize,
vendorKey = activeVendorKey,
) => {
setLoading(true);
try {
let url = `/api/models/?p=${page}&page_size=${size}`;
if (vendorKey && vendorKey !== 'all') {
// Filter by vendor ID
url = `/api/models/search?vendor=${vendorKey}&p=${page}&page_size=${size}`;
}
const res = await API.get(url);
const { success, message, data } = res.data;
if (success) {
const newPageData = extractItems(data);
setActivePage(data.page || page);
setModelCount(data.total || newPageData.length);
setModelFormat(newPageData);
if (data.vendor_counts) {
const sumAll = Object.values(data.vendor_counts).reduce(
(acc, v) => acc + v,
0,
);
setVendorCounts({ ...data.vendor_counts, all: sumAll });
}
} else {
showError(message);
setModels([]);
}
} catch (error) {
console.error(error);
showError(t('获取模型列表失败'));
setModels([]);
}
setLoading(false);
};
// Refresh data
const refresh = async (page = activePage) => {
await loadModels(page, pageSize);
};
// Sync upstream models/vendors for missing models only
const syncUpstream = async (opts = {}) => {
const locale = opts?.locale;
setSyncing(true);
try {
const body = {};
if (locale) body.locale = locale;
const res = await API.post('/api/models/sync_upstream', body);
const { success, message, data } = res.data || {};
if (success) {
const createdModels = data?.created_models || 0;
const createdVendors = data?.created_vendors || 0;
const skipped = (data?.skipped_models || []).length || 0;
showSuccess(
t(
'已同步:新增 {{createdModels}} 模型,新增 {{createdVendors}} 供应商,跳过 {{skipped}} 项',
{ createdModels, createdVendors, skipped },
),
);
await loadVendors();
await refresh();
} else {
showError(message || t('同步失败'));
}
} catch (e) {
showError(t('同步失败'));
}
setSyncing(false);
};
// Preview upstream differences
const previewUpstreamDiff = async (opts = {}) => {
const locale = opts?.locale;
setPreviewing(true);
try {
const url = `/api/models/sync_upstream/preview${locale ? `?locale=${locale}` : ''}`;
const res = await API.get(url);
const { success, message, data } = res.data || {};
if (success) {
return data || { missing: [], conflicts: [] };
}
showError(message || t('预览失败'));
return { missing: [], conflicts: [] };
} catch (e) {
showError(t('预览失败'));
return { missing: [], conflicts: [] };
} finally {
setPreviewing(false);
}
};
// Apply selected overwrite
const applyUpstreamOverwrite = async (payloadOrArray = []) => {
const isArray = Array.isArray(payloadOrArray);
const overwrite = isArray ? payloadOrArray : payloadOrArray.overwrite || [];
const locale = isArray ? undefined : payloadOrArray.locale;
setSyncing(true);
try {
const body = { overwrite };
if (locale) body.locale = locale;
const res = await API.post('/api/models/sync_upstream', body);
const { success, message, data } = res.data || {};
if (success) {
const createdModels = data?.created_models || 0;
const updatedModels = data?.updated_models || 0;
const createdVendors = data?.created_vendors || 0;
const skipped = (data?.skipped_models || []).length || 0;
showSuccess(
t(
'完成:新增 {{createdModels}} 模型,更新 {{updatedModels}} 模型,新增 {{createdVendors}} 供应商,跳过 {{skipped}} 项',
{ createdModels, updatedModels, createdVendors, skipped },
),
);
await loadVendors();
await refresh();
return true;
}
showError(message || t('同步失败'));
return false;
} catch (e) {
showError(t('同步失败'));
return false;
} finally {
setSyncing(false);
}
};
// Search models with keyword and vendor
const searchModels = async () => {
const {
searchKeyword = '',
searchVendor = '',
searchCategory = '',
} = getFormValues();
if (searchKeyword === '' && searchVendor === '' && searchCategory === '') {
// If all filters are blank, load models instead
await loadModels(1, pageSize);
return;
}
setSearching(true);
try {
const res = await API.get(
`/api/models/search?keyword=${searchKeyword}&vendor=${searchVendor}&category=${searchCategory}&p=1&page_size=${pageSize}`,
);
const { success, message, data } = res.data;
if (success) {
const newPageData = extractItems(data);
setActivePage(data.page || 1);
setModelCount(data.total || newPageData.length);
setModelFormat(newPageData);
if (data.vendor_counts) {
const sumAll = Object.values(data.vendor_counts).reduce(
(acc, v) => acc + v,
0,
);
setVendorCounts({ ...data.vendor_counts, all: sumAll });
}
} else {
showError(message);
setModels([]);
}
} catch (error) {
console.error(error);
showError(t('搜索模型失败'));
setModels([]);
}
setSearching(false);
};
// Manage model (enable/disable/delete)
const manageModel = async (id, action, record) => {
let res;
switch (action) {
case 'delete':
res = await API.delete(`/api/models/${id}`);
break;
case 'enable':
res = await API.put('/api/models/?status_only=true', { id, status: 1 });
break;
case 'disable':
res = await API.put('/api/models/?status_only=true', { id, status: 0 });
break;
default:
return;
}
const { success, message } = res.data;
if (success) {
showSuccess(t('操作成功完成!'));
if (action === 'delete') {
await refresh();
} else {
// Update local state for enable/disable
setModels((prevModels) =>
prevModels.map((model) =>
model.id === id
? { ...model, status: action === 'enable' ? 1 : 0 }
: model,
),
);
}
} else {
showError(message);
}
};
// Handle page change
const handlePageChange = (page) => {
setActivePage(page);
loadModels(page, pageSize, activeVendorKey);
};
// Reload models when activeVendorKey changes
useEffect(() => {
loadModels(1, pageSize, activeVendorKey);
}, [activeVendorKey]);
// Handle page size change
const handlePageSizeChange = async (size) => {
setPageSize(size);
setActivePage(1);
await loadModels(1, size, activeVendorKey);
};
// Handle row click and styling
const handleRow = (record, index) => {
const rowStyle =
record.status !== 1
? {
style: {
background: 'var(--semi-color-disabled-border)',
},
}
: {};
return {
...rowStyle,
onClick: (event) => {
// Don't trigger row selection when clicking on buttons
if (event.target.closest('button, .semi-button')) {
return;
}
const newSelectedKeys = selectedKeys.some(
(item) => item.id === record.id,
)
? selectedKeys.filter((item) => item.id !== record.id)
: [...selectedKeys, record];
setSelectedKeys(newSelectedKeys);
},
};
};
// Batch delete models
const batchDeleteModels = async () => {
if (selectedKeys.length === 0) {
showError(t('请至少选择一个模型'));
return;
}
try {
const deletePromises = selectedKeys.map((model) =>
API.delete(`/api/models/${model.id}`),
);
const results = await Promise.all(deletePromises);
let successCount = 0;
results.forEach((res, index) => {
if (res.data.success) {
successCount++;
} else {
showError(`删除模型 ${selectedKeys[index].model_name} 失败: ${res.data.message}`,
);
}
});
if (successCount > 0) {
showSuccess(t('成功删除 {{successCount}} 个模型', { successCount }));
setSelectedKeys([]);
await refresh();
}
} catch (error) {
showError(t('批量删除失败'));
}
};
// Batch update model categories
const batchUpdateCategory = async (categories) => {
if (selectedKeys.length === 0) {
showError(t('请至少选择一个模型'));
return;
}
try {
const ids = selectedKeys.map((model) => model.id);
const res = await API.put('/api/models/batch-category', {
ids,
categories,
});
const { success, message, data } = res.data;
if (success) {
showSuccess(
t('成功更新 {{updated}} 个模型的分类', { updated: data.updated }),
);
setSelectedKeys([]);
await refresh();
} else {
showError(message || t('批量更新分类失败'));
}
} catch (error) {
console.error('Batch update category failed:', error);
showError(t('批量更新分类失败'));
}
};
// Copy text helper
const copyText = async (text) => {
try {
await navigator.clipboard.writeText(text);
showSuccess(t('复制成功'));
} catch (error) {
console.error('Copy failed:', error);
showError(t('复制失败'));
}
};
// Initial load
useEffect(() => {
(async () => {
await loadVendors();
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return {
// Data state
models,
loading,
searching,
activePage,
pageSize,
modelCount,
// Selection state
selectedKeys,
rowSelection,
handleRow,
setSelectedKeys,
// Modal state
showEdit,
editingModel,
setEditingModel,
setShowEdit,
closeEdit,
// Form state
formInitValues,
setFormApi,
// Actions
loadModels,
searchModels,
refresh,
manageModel,
batchDeleteModels,
batchUpdateCategory,
copyText,
// Pagination
setActivePage,
handlePageChange,
handlePageSizeChange,
// UI state
compactMode,
setCompactMode,
// Vendor data
vendors,
vendorMap,
vendorCounts,
activeVendorKey,
setActiveVendorKey,
showAddVendor,
setShowAddVendor,
showEditVendor,
setShowEditVendor,
editingVendor,
setEditingVendor,
loadVendors,
// Translation
t,
// Upstream sync
syncing,
previewing,
syncUpstream,
previewUpstreamDiff,
applyUpstreamOverwrite,
};
};