From 60a63186634c74cc9182cac77d9954fc42ed32a1 Mon Sep 17 00:00:00 2001 From: riverLethe <865192079@qq.com> Date: Thu, 11 Dec 2025 18:14:04 +0800 Subject: [PATCH 1/7] fix:set mcp server edit rules, server id and server name change rule is max length 255 --- frontend/public/locales/en/translation.json | 4 ++-- frontend/public/locales/zh-CN/translation.json | 4 ++-- frontend/src/components/mcp-services/ServiceEditPage.tsx | 8 ++++---- .../src/shared/components/mcp-services/BasicInfoTab.tsx | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/frontend/public/locales/en/translation.json b/frontend/public/locales/en/translation.json index 5c8c300..9a88158 100644 --- a/frontend/public/locales/en/translation.json +++ b/frontend/public/locales/en/translation.json @@ -877,8 +877,8 @@ "No servers available": "No servers available", "(Deleted)": "(Deleted)", "Transport Type": "Transport Type", - "Server ID must be less than 256 characters": "Server ID must be less than 256 characters", - "Server Name must be less than 256 characters": "Server Name must be less than 256 characters", + "Server ID must be less than 255 characters": "Server ID must be less than 255 characters", + "Server Name must be less than 255 characters": "Server Name must be less than 255 characters", "API Endpoint must be a valid HTTP/HTTPS URL": "API Endpoint must be a valid HTTP/HTTPS URL", "Server ID is required": "Server ID is required", "Short description is required": "Short description is required" diff --git a/frontend/public/locales/zh-CN/translation.json b/frontend/public/locales/zh-CN/translation.json index 6107c7b..6a4f803 100644 --- a/frontend/public/locales/zh-CN/translation.json +++ b/frontend/public/locales/zh-CN/translation.json @@ -879,8 +879,8 @@ "No servers available": "没有可用服务", "(Deleted)": "(已删除)", "Transport Type": "传输方式", - "Server ID must be less than 256 characters": "Server ID 必须少于256个字符", - "Server Name must be less than 256 characters": "Server Name 必须少于256个字符", + "Server ID must be less than 255 characters": "Server ID 必须少于255个字符", + "Server Name must be less than 255 characters": "Server Name 必须少于255个字符", "API Endpoint must be a valid HTTP/HTTPS URL": "API Endpoint 必须是一个有效的HTTP/HTTPS URL", "Server ID is required": "Server ID 为必填项", "Short description is required": "简短描述为必填项" diff --git a/frontend/src/components/mcp-services/ServiceEditPage.tsx b/frontend/src/components/mcp-services/ServiceEditPage.tsx index 2ed5568..41029ec 100644 --- a/frontend/src/components/mcp-services/ServiceEditPage.tsx +++ b/frontend/src/components/mcp-services/ServiceEditPage.tsx @@ -50,14 +50,14 @@ const validateServiceForm = (data: MCPServiceFormData, t: any) => { if (!data.slug_name?.trim()) { errors.slug_name = t("Server ID is required"); - } else if (data.slug_name.length > 256) { - errors.slug_name = t("Server ID must be less than 256 characters"); + } else if (data.slug_name.length > 255) { + errors.slug_name = t("Server ID must be less than 255 characters"); } if (!data.name?.trim()) { errors.name = t("Server name is required"); - } else if (data.name.length > 256) { - errors.name = t("Server Name must be less than 256 characters"); + } else if (data.name.length > 255) { + errors.name = t("Server Name must be less than 255 characters"); } if (!data.base_url?.trim()) { diff --git a/frontend/src/shared/components/mcp-services/BasicInfoTab.tsx b/frontend/src/shared/components/mcp-services/BasicInfoTab.tsx index c239c37..84f2b66 100644 --- a/frontend/src/shared/components/mcp-services/BasicInfoTab.tsx +++ b/frontend/src/shared/components/mcp-services/BasicInfoTab.tsx @@ -43,7 +43,7 @@ export const BasicInfoTab: React.FC = ({ )} labelPlacement="outside" isRequired - maxLength={256} + maxLength={255} isInvalid={!!errors?.slug_name} errorMessage={errors?.slug_name || t("Server ID is required")} /> @@ -54,7 +54,7 @@ export const BasicInfoTab: React.FC = ({ onChange={(e) => onInputChange("name", e.target.value)} isRequired labelPlacement="outside" - maxLength={256} + maxLength={255} isInvalid={!!errors?.name} errorMessage={errors?.name || t("Server name is required")} /> From 5c90b8e1caa45ac840692107e1ea3983e8e99e7f Mon Sep 17 00:00:00 2001 From: lcx Date: Mon, 15 Dec 2025 18:52:37 +0800 Subject: [PATCH 2/7] feat: resource-group-management --- .../public/locales/zh-CN/translation.json | 53 ++- frontend/src/api/resourceGroup.api.ts | 291 +++++++++++++++ frontend/src/components/console/Main.tsx | 17 +- .../mcp-services/ServiceEditPage.tsx | 14 + .../resource-group/AddMcpServerModal.tsx | 173 +++++++++ .../resource-group/AddServerModal.tsx | 98 +++++ .../resource-group/DeleteServerModal.tsx | 94 +++++ .../components/resource-group/GroupList.tsx | 162 ++++++++ .../resource-group/GroupServiceTable.tsx | 235 ++++++++++++ .../resource-group/resourceGroup.tsx | 348 ++++++++++++++++++ .../theme/ProductDetailThemeSelector.tsx | 9 + .../src/components/theme/classic/Detail.tsx | 3 + .../src/components/theme/creative/Detail.tsx | 3 + .../src/components/theme/modern/Detail.tsx | 3 + frontend/src/components/theme/temu/Detail.tsx | 3 + .../user-management/UserManagement.tsx | 3 + .../components/user-management/UserTable.tsx | 63 +++- frontend/src/hooks/useMCPServiceDetail.ts | 41 +++ frontend/src/hooks/useResourceGroups.ts | 269 ++++++++++++++ frontend/src/rpc/admin-api.ts | 2 +- frontend/src/services/mcpService.ts | 93 +++++ .../components/marketplace/ProductDetail.tsx | 4 +- .../components/marketplace/ServerConfig.tsx | 11 + .../components/mcp-services/ResourceGroup.tsx | 278 ++++++++++++++ .../components/modal/DeleteConfirmModal.tsx | 13 + .../shared/components/modal/McpAddGroup.tsx | 141 +++++++ frontend/src/shared/rpc/common-function.ts | 2 +- frontend/src/shared/types/dashboard.ts | 1 + frontend/src/shared/types/mcp-service.ts | 7 + frontend/src/types/user.ts | 1 + 30 files changed, 2427 insertions(+), 8 deletions(-) create mode 100644 frontend/src/api/resourceGroup.api.ts create mode 100644 frontend/src/components/resource-group/AddMcpServerModal.tsx create mode 100644 frontend/src/components/resource-group/AddServerModal.tsx create mode 100644 frontend/src/components/resource-group/DeleteServerModal.tsx create mode 100644 frontend/src/components/resource-group/GroupList.tsx create mode 100644 frontend/src/components/resource-group/GroupServiceTable.tsx create mode 100644 frontend/src/components/resource-group/resourceGroup.tsx create mode 100644 frontend/src/hooks/useResourceGroups.ts create mode 100644 frontend/src/shared/components/mcp-services/ResourceGroup.tsx create mode 100644 frontend/src/shared/components/modal/McpAddGroup.tsx diff --git a/frontend/public/locales/zh-CN/translation.json b/frontend/public/locales/zh-CN/translation.json index 6107c7b..6ec89e0 100644 --- a/frontend/public/locales/zh-CN/translation.json +++ b/frontend/public/locales/zh-CN/translation.json @@ -300,6 +300,7 @@ "Overview and analytics": "概览和分析", "Manage MCP servers and API tools": "管理MCP服务及API工具", "Manage registered users": "管理注册用户", + "Manage resource groups": "管理资源组", "View user recharge history": "查看用户充值历史", "Configure payment channels": "配置支付渠道", "Platform basic configuration": "平台基础配置", @@ -624,6 +625,8 @@ "MCP Config": "MCP配置", "Copy full config": "复制完整配置", "Analytics": "分析", + "Resource Group": "资源组", + "Manage Your Resource Groups": "管理您的资源组", "Times": "次", "No analytics data available": "无可用分析数据", "Delete Auth Key": "删除认证密钥", @@ -883,5 +886,53 @@ "Server Name must be less than 256 characters": "Server Name 必须少于256个字符", "API Endpoint must be a valid HTTP/HTTPS URL": "API Endpoint 必须是一个有效的HTTP/HTTPS URL", "Server ID is required": "Server ID 为必填项", - "Short description is required": "简短描述为必填项" + "Short description is required": "简短描述为必填项", + "Add": "添加", + "Add to Groups": "添加到资源组", + "Group Name": "资源组名称", + "No resource groups available": "没有可用资源组", + "Failed to load group services": "加载资源组服务失败", + "Resource group deleted successfully": "资源组删除成功", + "Added Time": "添加时间", + "No services in this group": "此资源组没有服务", + "Open Resource Group Page": "打开资源组页面", + "Remove": "删除", + "Confirm Remove": "确认删除", + "Are you sure you want to remove this \"{{name}}\" mcp server from \"{{groupName}}\" resource group?": "您确定要从 \"{{groupName}}\" 资源组中移除 \"{{name}}\" MCP 服务吗?", + "Users associated with this resource group will not be able to call the removed MCP server": "与该资源组关联的用户将无法调用已移除的 MCP 服务", + "You don't have permission to access this MCP server.": "您没有权限访问此 MCP 服务。", + "Failed to load resource groups": "加载资源组失败", + "Failed to delete resource group": "删除资源组失败", + "Failed to add service to group": "添加服务到资源组失败", + "Resource group created successfully": "资源组创建成功", + "Resource group updated successfully": "资源组更新成功", + "Services added successfully": "服务添加成功", + "Service removed successfully": "服务移除成功", + "Select resource group": "选择资源组", + "Manage your resource group. Each user has a resource group and can only access resources within their resource group": "管理您的资源组。每个用户都有一个资源组,并且只能访问其资源组内的资源", + "Please select a group to view services": "请选择一个资源组来查看服务", + "Are you sure you want to remove this \"{{name}}\" Resource Group?": "您确定要删除这个 \"{{name}}\" 资源组吗?", + "The bound users have been transferred to the following resource group": "与该资源组关联的用户已转移至以下资源组", + "Service Name": "服务名称", + "Group List": "资源组列表", + "No groups found": "没有找到资源组", + "No more groups": "没有更多资源组", + "Are you sure you want to delete this item? This action cannot be undone.": "您确定要删除这个项目吗?此操作无法撤销。", + "Create New Resource Group": "创建新资源组", + "Edit Resource Group": "编辑资源组", + "Edit Resource Group Name": "编辑资源组名称", + "Set as default": "设置为默认", + "Automatically bind default resource groups when adding users": "添加用户时自动绑定默认资源组", + "Add MCP Server": "添加 MCP 服务", + "No MCP services available": "没有可用的 MCP 服务", + "Resource Groups": "资源组", + "Resource Group Name": "资源组名称", + "Failed to remove service from group": "从资源组中移除服务失败", + "Failed to update resource group": "更新资源组失败", + "Failed to create resource group": "创建资源组失败", + "Failed to fetch simple mcp services": "获取简易MCP服务失败", + "Failed to fetch group services": "获取资源组服务失败", + "Failed to update user resource group": "更新用户资源组失败", + "Failed to load simple resource groups": "获取简易资源组失败", + "Failed to load resource group detail": "获取资源组详情失败" } diff --git a/frontend/src/api/resourceGroup.api.ts b/frontend/src/api/resourceGroup.api.ts new file mode 100644 index 0000000..4599a3e --- /dev/null +++ b/frontend/src/api/resourceGroup.api.ts @@ -0,0 +1,291 @@ +import { SimpleMcpService } from "@/components/resource-group/AddMcpServerModal"; +import { GroupService } from "@/components/resource-group/GroupServiceTable"; +import { fetchAdminAPI } from "@/rpc/admin-api"; +import { toast } from "react-hot-toast"; +import i18n from "@/shared/lib/i18n"; + +export interface ResourceGroupResponse { + id: string; + name: string; + description: string; + is_default: boolean; + service_count: number; + create_at: string; +} + +export interface ResourceGroupDetailResponse { + id: string; + name: string; + description: string; + is_default: boolean; + update_at: number; + create_at: string; +} +export interface ResourceGroupListResponse { + data: ResourceGroupResponse[]; + total: number; + page: number; + page_size: number; +} + +export interface GroupServiceListResponse { + data: GroupService[]; + total: number; + page: number; + page_size: number; +} + +export interface SimpleMcpServiceListResponse { + data: SimpleMcpService[]; + total: number; + page: number; + page_size: number; +} + + +export const fetchResourceGroupDetail = async (groupId: string): Promise => { + try { + const response = await fetchAdminAPI(`/api/resource_group/info?id=${groupId}`); + if (!response.success) { + toast.error(response.error_message || i18n.t("Failed to load resource group detail")); + return null; + } + return response.data || null; + } catch (error) { + console.error("Error fetching resource group detail:", error); + return null; + } +}; +/** + * 获取资源组列表 + */ +export const fetchResourceGroups = async (page: number, page_size: number, keyword: string): Promise => { + try { + const response = await fetchAdminAPI(`/api/resource_group/list?page=${page}&page_size=${page_size}&keyword=${keyword}`); + if (!response.success) { + toast.error(response.error_message || i18n.t("Failed to load resource groups")); + return { + data: [], + total: 0, + page, + page_size, + }; + } + return { + data: response.data || [], + total: response.page?.total || 0, + page: response.page?.page || page, + page_size: response.page?.page_size || page_size, + }; + } catch (error) { + console.error("Error fetching auth keys:", error); + return { + data: [], + total: 0, + page, + page_size, + }; + } +}; +/** + * 获取简易资源组列表 + */ +export const fetchSimpleResourceGroups = async (): Promise<{ id: string, name: string }[]> => { + try { + const response = await fetchAdminAPI<{ id: string, name: string }[]>(`/api/resource_group/list/simple`); + if (!response.success) { + toast.error(response.error_message || i18n.t("Failed to load simple resource groups")); + return [] + } + return response.data || [] + } catch (error) { + console.error("Error fetching auth keys:", error); + return [] + } +}; + +/** + * 修改用户资源组 + */ +export const updateUserResourceGroup = async (userId: string, resourceGroupId: string): Promise => { + try { + const response = await fetchAdminAPI(`/api/user_manager/resource_group`, { + method: "PUT", + body: { user_id: userId, resource_group: resourceGroupId } as unknown as BodyInit, + }); + if (!response.success) { + toast.error(response.error_message || i18n.t("Failed to update user resource group")); + return false; + } + return true; + } catch (error) { + console.error("Error updating user resource group:", error); + return false + } +}; + +/** + * 获取指定资源组下的服务列表 + */ +export const fetchGroupServices = async (id: string,page: number, page_size: number, keyword: string): Promise => { + try { + const response = await fetchAdminAPI(`/api/resource_group/service/list?id=${id}&page=${page}&page_size=${page_size}&keyword=${keyword}`); + if (!response.success) { + toast.error(response.error_message || i18n.t("Failed to fetch group services")); + return { + data: [], + total: 0, + page, + page_size, + }; + } + return { + data: response.data || [], + total: response.page?.total || 0, + page: response.page?.page || page, + page_size: response.page?.page_size || page_size, + }; + } catch (error) { + console.error("Error fetching auth keys:", error); + return { + data: [], + total: 0, + page, + page_size, + }; + } +}; + +/** + * 获取简易指定资源组下的服务列表 + */ +export const fetchSimpleMcpServices = async (): Promise => { + try { + const response = await fetchAdminAPI(`/api/mcp/service/list/simple`); + if (!response.success) { + toast.error(response.error_message || i18n.t("Failed to fetch simple mcp services")); + return [] + } + return response.data || [] + } catch (error) { + console.error("Error fetching auth keys:", error); + return [] + } +}; + +/** + * 创建资源组 + */ +export const createResourceGroup = async (name: string, isDefault: boolean): Promise<{success: boolean, id: string}> => { + try { + const response = await fetchAdminAPI<{id: string}>(`/api/resource_group`, { + method: "POST", + body: { name: name, is_default: isDefault } as unknown as BodyInit, + }); + if (!response.success) { + toast.error(response.error_message || i18n.t("Failed to create resource group")); + return { + success: false, + id: "", + }; + } + return { + success: true, + id: response.data?.id || "", + }; + } catch { + return { + success: false, + id: "", + }; + } +}; + +/** + * 更新资源组 + */ +export const updateResourceGroup = async ( + groupId: string, + name: string, + isDefault: boolean +): Promise => { + try { + const response = await fetchAdminAPI(`/api/resource_group?id=${groupId}`, { + method: "PUT", + body: { name: name, is_default: isDefault } as unknown as BodyInit, + }); + if (!response.success) { + toast.error(response.error_message || i18n.t("Failed to update resource group")); + return false; + } + return true; + } catch { + return false + } +}; + +/** + * 删除资源组 + */ +export const deleteResourceGroup = async ( + groupId: string, + transferToGroupId: string +): Promise => { + try { + const response = await fetchAdminAPI(`/api/resource_group?id=${groupId}&migrate_id=${transferToGroupId}`, { + method: "DELETE" + }); + if (!response.success) { + toast.error(response.error_message || i18n.t("Failed to delete resource group")); + return false; + } + return true; + } catch { + return false + } +}; + +/** + * 从资源组中移除服务 + */ +export const removeServiceFromGroup = async ( + groupId: string, + serviceIds: string[] +): Promise => { + try { + const response = await fetchAdminAPI(`/api/resource_group/service?id=${groupId}`, { + method: "DELETE", + body: { services: serviceIds } as unknown as BodyInit, + }); + if (!response.success) { + toast.error(response.error_message || i18n.t("Failed to remove service from group")); + return false; + } + return true; + } catch { + return false + } +}; + +/** + * 添加服务到资源组 + */ +export const addServiceToGroup = async ( + groupId: string, + services: string[] +): Promise => { + try { + const response = await fetchAdminAPI(`/api/resource_group/service?id=${groupId}`, { + method: "PUT", + body: { services: services } as unknown as BodyInit, + }); + if (!response.success) { + toast.error(response.error_message || i18n.t("Failed to add service to group")); + return false; + } + return true; + } catch { + return false + } +}; + diff --git a/frontend/src/components/console/Main.tsx b/frontend/src/components/console/Main.tsx index e403173..9ed3856 100644 --- a/frontend/src/components/console/Main.tsx +++ b/frontend/src/components/console/Main.tsx @@ -12,7 +12,7 @@ import UserManagement from "@/components/user-management/UserManagement"; import RevenueManagement from "@/components/revenue-management/RevenueManagement"; import ConsoleSidebar from "./Sidebar"; import { withComponentInjection } from "@/shared/hooks/useComponentInjection"; -import { DollarSign, Home, ServerIcon, Users } from "lucide-react"; +import { Boxes, DollarSign, Home, ServerIcon, Users } from "lucide-react"; import OnboardingWelcome, { REQUIRED_TASK_KEYS } from "./OnboardingWelcome"; import ConsoleStats from "./ConsoleStats"; import SystemSettingsModal from "./SystemSettingsModal"; @@ -23,6 +23,7 @@ import { TaskStatusEnum, updateAdminOnboardingTasks, } from "@/api/onboard.api"; +import ResourceGroupManagement from "../resource-group/resourceGroup"; const ConsoleContent: React.FC = () => { const { t } = useTranslation(); @@ -36,7 +37,7 @@ const ConsoleContent: React.FC = () => { const tabFromUrl = searchParams.get("tab") as TabKey; if ( tabFromUrl && - ["mcp-services", "user-management", "revenue-management"].includes( + ["mcp-services", "user-management", "revenue-management", "resource-group"].includes( tabFromUrl ) ) { @@ -74,6 +75,12 @@ const ConsoleContent: React.FC = () => { label: t("User"), description: t("Manage registered users"), }, + { + key: TabKey.RESOURCE_GROUP, + icon: , + label: t("Resource Group"), + description: t("Manage resource groups"), + }, { key: TabKey.REVENUE_MANAGEMENT, icon: , @@ -218,6 +225,12 @@ const ConsoleContent: React.FC = () => { ); + case TabKey.RESOURCE_GROUP: + return ( +
+ +
+ ); default: return showOnboarding ? ( = ({ getServiceDetail, clearServiceDetail, parseOpenAPIDocumentForUpdate, + fetchMCPResourceGroups, + deleteResourceGroup, + addServiceToGroup, updateLoading, } = useMCPServiceDetail(); const [isSaving, setIsSaving] = useState(false); @@ -381,6 +385,16 @@ const BaseServiceEditPage: React.FC = ({ /> + +
+ +
+
)} diff --git a/frontend/src/components/resource-group/AddMcpServerModal.tsx b/frontend/src/components/resource-group/AddMcpServerModal.tsx new file mode 100644 index 0000000..2d2c8c3 --- /dev/null +++ b/frontend/src/components/resource-group/AddMcpServerModal.tsx @@ -0,0 +1,173 @@ +import { + Button, + Modal, + ModalBody, + ModalContent, + ModalFooter, + ModalHeader, + Table, + TableHeader, + TableColumn, + TableBody, + TableRow, + TableCell, + Chip, + Spinner, +} from "@nextui-org/react"; +import { useState, useEffect, useCallback } from "react"; +import { useTranslation } from "@/shared/lib/useTranslation"; +import { ChargeType } from "@/shared/types/marketplace"; +import { fetchSimpleMcpServices } from "@/api/resourceGroup.api"; +import { Price } from "@/shared/components/marketplace/Price"; + +interface AddMcpServerModalProps { + isOpen: boolean; + onClose: () => void; + onSaveMcpServer: (serverIds: string[]) => Promise; +} + +export interface SimpleMcpService { + id: string; + name: string; + base_url: string; + charge_type: ChargeType; + price: string; + enabled: boolean; + input_token_price?: string; + output_token_price?: string; +} + +export const AddMcpServerModal: React.FC = ({ + isOpen, + onClose, + onSaveMcpServer, +}) => { + const { t } = useTranslation(); + const [isLoading, setIsLoading] = useState(false); + const [loading, setLoading] = useState(false); + const [services, setServices] = useState([]); + const [selectedKeys, setSelectedKeys] = useState>(new Set()); + + // 加载服务列表 + const loadServices = useCallback(async () => { + setLoading(true); + try { + const response = await fetchSimpleMcpServices(); + setServices(response); + } catch (error) { + console.error("Failed to load MCP services:", error); + } finally { + setLoading(false); + } + }, []); + + // 当模态框打开时加载数据 + useEffect(() => { + if (isOpen) { + setSelectedKeys(new Set()); + loadServices(); + } + }, [isOpen, loadServices]); + + // 处理保存 + const handleSave = async () => { + const serverIds = typeof selectedKeys === 'string' && selectedKeys === 'all' ? services.map((service) => service.id) : Array.from(selectedKeys); + if (serverIds.length === 0) { + return; + } + + setIsLoading(true); + try { + await onSaveMcpServer(serverIds); + onClose(); + } finally { + setIsLoading(false); + } + }; + + return ( + + + {() => ( + <> + + {t("Add MCP Server")} + + + setSelectedKeys(keys as Set)} + removeWrapper + classNames={{ + wrapper: "min-h-[400px]", + }} + > + + {t("Service Name")} + {t("API Endpoint")} + {t("Status")} + {t("Pricing")} + + } + emptyContent={t("No MCP services available")} + > + {(service) => ( + + + {service.name} + + + {service.base_url} + + + + {t(service.enabled ? "Published" : "Unpublished")} + + + + + + + )} + +
+
+ + + + + + )} +
+
+ ); +}; \ No newline at end of file diff --git a/frontend/src/components/resource-group/AddServerModal.tsx b/frontend/src/components/resource-group/AddServerModal.tsx new file mode 100644 index 0000000..228c1c0 --- /dev/null +++ b/frontend/src/components/resource-group/AddServerModal.tsx @@ -0,0 +1,98 @@ +import { Button, Input, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader, Switch } from "@nextui-org/react" +import { useState, useEffect } from "react"; +import { useTranslation } from "@/shared/lib/useTranslation"; +interface AddServerModalProps { + isOpen: boolean; + onClose: () => void; + name: string; + onSaveServer: (name: string, isDefault: boolean) => Promise; + type: "add" | "edit"; + isDefault: boolean; +} +export const AddServerModal: React.FC = ({ + isOpen, + onClose, + name, + onSaveServer, + type, + isDefault, +}) => { + const { t } = useTranslation(); + const [serverName, setServerName] = useState(name); + const [isEnabledState, setIsEnabledState] = useState(isDefault); + const [isLoading, setIsLoading] = useState(false); + + // 当 name prop 或 isOpen 变化时,更新内部状态 + useEffect(() => { + if (isOpen) { + setServerName(name); + setIsEnabledState(isDefault); + setIsLoading(false); // 重置 loading 状态 + } + }, [name, isOpen, isDefault]); + + // 处理保存 + const handleSave = async () => { + setIsLoading(true); + try { + await onSaveServer(serverName, isEnabledState); + } finally { + setIsLoading(false); + } + }; + return ( + + + {() => ( + <> + + {type === "add" ? t("Create New Resource Group") : t("Edit Resource Group")} + + + setServerName(e.target.value)} + /> +
+
+ + {t("Set as default")} + + + {t("Automatically bind default resource groups when adding users")} + +
+ +
+
+ + + + + + )} + +
+
+ ) +} \ No newline at end of file diff --git a/frontend/src/components/resource-group/DeleteServerModal.tsx b/frontend/src/components/resource-group/DeleteServerModal.tsx new file mode 100644 index 0000000..4fe9b26 --- /dev/null +++ b/frontend/src/components/resource-group/DeleteServerModal.tsx @@ -0,0 +1,94 @@ +"use client"; + +import React, { useState } from "react"; +import { + Modal, + ModalContent, + ModalHeader, + ModalBody, + ModalFooter, + Button, + Alert, +} from "@nextui-org/react"; +import { useTranslation } from "@/shared/lib/useTranslation"; + +interface DeleteServerModalProps { + isOpen: boolean; + onClose: () => void; + onConfirm: () => void | Promise; + title?: string | React.ReactNode; + description?: string | React.ReactNode; + alertDescription?: string; + customAlertContent?: React.ReactNode; +} + +export const DeleteServerModal: React.FC = ({ + isOpen, + onClose, + onConfirm, + title, + description, + alertDescription, + customAlertContent, +}) => { + const { t } = useTranslation(); + const [isLoading, setIsLoading] = useState(false); + + const handleConfirm = async () => { + setIsLoading(true); + try { + await onConfirm(); + } finally { + setIsLoading(false); + } + }; + + const defaultTitle = t("Confirm Delete"); + const defaultDescription = t("Are you sure you want to delete this item? This action cannot be undone."); + const defaultAlertDescription= t("This action cannot be undone."); + return ( + + + {() => ( + <> + + {title || defaultTitle} + + +
+ {/* Description */} +
+ {description || defaultDescription} +
+ + {/* Warning message */} + + {customAlertContent && customAlertContent} + +
+
+ + + + + + )} +
+
+ ); +}; + +export default DeleteServerModal; \ No newline at end of file diff --git a/frontend/src/components/resource-group/GroupList.tsx b/frontend/src/components/resource-group/GroupList.tsx new file mode 100644 index 0000000..47c5ac0 --- /dev/null +++ b/frontend/src/components/resource-group/GroupList.tsx @@ -0,0 +1,162 @@ +"use client"; + +import React, { useRef, useCallback, useEffect } from "react"; +import { Button, Card, CardBody, CardHeader, Chip, Divider, Listbox, ListboxItem, Spinner } from "@nextui-org/react"; +import { useTranslation } from "@/shared/lib/useTranslation"; +import { Plus } from "lucide-react"; + +// 资源组类型定义 +export interface ResourceGroup { + id: string; + name: string; + description?: string; + isDefault?: boolean; + serviceCount?: number; + createdAt?: string; +} + +interface GroupListProps { + groups: ResourceGroup[]; + selectedGroup: ResourceGroup | null; + onSelectGroup: (group: ResourceGroup) => void; + onCreateGroup: () => void; + onLoadMore?: () => void; + hasMore?: boolean; + loading?: boolean; + shouldScrollToTop?: boolean; + onScrolledToTop?: () => void; +} + +const GroupList: React.FC = ({ + groups, + selectedGroup, + onSelectGroup, + onCreateGroup, + onLoadMore, + hasMore = false, + loading = false, + shouldScrollToTop = false, + onScrolledToTop, +}) => { + const { t } = useTranslation(); + const scrollRef = useRef(null); + const observerRef = useRef(null); + const loadMoreTriggerRef = useRef(null); + const hasLoadedMoreRef = useRef(false); + + // 使用 IntersectionObserver 监听滚动到底部 + const handleObserver = useCallback( + (entries: IntersectionObserverEntry[]) => { + const [target] = entries; + if (target.isIntersecting && hasMore && !loading && onLoadMore) { + hasLoadedMoreRef.current = true; // 标记已触发过加载更多 + onLoadMore(); + } + }, + [hasMore, loading, onLoadMore] + ); + + useEffect(() => { + const element = loadMoreTriggerRef.current; + if (!element || !onLoadMore) return; + + // 创建 IntersectionObserver + observerRef.current = new IntersectionObserver(handleObserver, { + root: scrollRef.current, + rootMargin: "100px", // 提前 100px 触发加载 + threshold: 0.1, + }); + + observerRef.current.observe(element); + + return () => { + if (observerRef.current && element) { + observerRef.current.unobserve(element); + } + }; + }, [handleObserver, onLoadMore]); + + // 监听 shouldScrollToTop 变化,滚动到顶部 + useEffect(() => { + if (shouldScrollToTop && scrollRef.current) { + scrollRef.current.scrollTo({ top: 0, behavior: 'smooth' }); + // 通知父组件已完成滚动 + onScrolledToTop?.(); + } + }, [shouldScrollToTop, onScrolledToTop]); + + return ( +
+ + +

{t("Group List")}

+ +
+ + +
+ :
{t("No groups found")}
} + selectionMode="single" + selectedKeys={selectedGroup ? [selectedGroup.id] : []} + onSelectionChange={(keys) => { + const selectedId = Array.from(keys)[0]; + const selectedKey = (groups || []).find( + (k) => k.id === selectedId + ); + if (selectedKey) onSelectGroup(selectedKey); + }} + itemClasses={{ + title: "text-md font-medium", + base: "bg-white p-6 transition-colors border-1 data-[selected=true]:focus:bg-primary-50 data-[selected=true]:data-[hover=true]:bg-primary-50 data-[selected=true]:border-primary-500 data-[selected=true]:bg-primary-50 data-[hover=true]:bg-default/50 data-[selectable=true]:focus:bg-default/50 [&>span]:w-full", + }} + classNames={{ + list: "gap-4", + }} + hideSelectedIcon + > + {(group) => ( + +
+ {group.name} + {group.isDefault && ( + + {t("Default")} + + )} +
+
+ )} +
+ + {/* 加载更多触发器 */} + {onLoadMore && ( +
+ {loading && hasMore && ( + + )} + {!hasMore && groups.length > 0 && hasLoadedMoreRef.current && ( +

{t("No more groups")}

+ )} +
+ )} +
+
+
+
+ ); +}; + +export default GroupList; + diff --git a/frontend/src/components/resource-group/GroupServiceTable.tsx b/frontend/src/components/resource-group/GroupServiceTable.tsx new file mode 100644 index 0000000..5c6c8bf --- /dev/null +++ b/frontend/src/components/resource-group/GroupServiceTable.tsx @@ -0,0 +1,235 @@ +"use client"; + +import React, { useEffect, useState } from "react"; +import { + Button, + Card, + Chip, + Table, + TableHeader, + TableColumn, + TableBody, + TableRow, + TableCell, + Tooltip, + Spinner, + Divider, + CardHeader, + CardBody, + Pagination, +} from "@nextui-org/react"; +import { useTranslation } from "@/shared/lib/useTranslation"; +import { Plus, Trash2, Edit2 } from "lucide-react"; +import { Price } from "@/shared/components/marketplace/Price"; +import { ChargeType } from "@/shared/types/marketplace"; +import { fetchResourceGroupDetail, ResourceGroupDetailResponse } from "@/api/resourceGroup.api"; +import { useSearchParams } from "next/navigation"; + +// 组内服务类型定义 +export interface GroupService { + id: string; + name: string; + base_url: string; + charge_type: ChargeType; + price: string; + enabled: boolean; + slug_name?: string; + input_token_price?: string; + output_token_price?: string; +} + +interface GroupServiceTableProps { + groupId?: string; // 可选,因为可能从 URL 获取 + services: GroupService[]; + loading?: boolean; + pagination: { + page: number; + pageSize: number; + total: number; + }; + onPageChange: (page: number) => void; + onAddService: () => void; + onRemoveService: (serviceId: string) => void; + onEditGroup: (groupId: string) => void; + onDeleteGroup: (groupId: string) => void; + refreshTrigger?: number; // 用于触发刷新 +} + +const GroupServiceTable: React.FC = ({ + groupId: propGroupId, + services, + loading = false, + pagination, + onPageChange, + onAddService, + onRemoveService, + onEditGroup, + onDeleteGroup, + refreshTrigger, +}) => { + const { t } = useTranslation(); + const searchParams = useSearchParams(); + + const pages = Math.ceil(pagination.total / pagination.pageSize); + const currentPage = pagination.page; + const [resourceGroupDetail, setResourceGroupDetail] = useState(null); + + // 优先使用 props 传入的 groupId,如果没有则从 URL 参数获取 + const urlGroupId = searchParams.get('groupId'); + const currentGroupId = propGroupId || urlGroupId || null; + + const getResourceGroup = async (groupId: string) => { + const response = await fetchResourceGroupDetail(groupId); + if (response) { + setResourceGroupDetail(response); + } + } + + useEffect(() => { + if (currentGroupId) { + getResourceGroup(currentGroupId); + } + }, [currentGroupId, refreshTrigger]); // 当 refreshTrigger 变化时也会刷新 + + return ( + <> + + +
+

+ {resourceGroupDetail?.name} +

+
+ {!['allow-all', 'deny-all'].includes(resourceGroupDetail?.id || '') && currentGroupId && <> + + + } + +
+ +
+
+ + +
+
+ +
+ +
+
+ + 1 ? ( +
+ +
+ ) : null + } + > + + {t("Service Name")} + {t("API Endpoint")} + {t("Status")} + {t("Pricing")} + {t("Actions")} + + } + emptyContent={t("No services in this group")} + > + {(service) => ( + + + {service.name} + + + {service.base_url} + + + + {t(service.enabled ? "Published" : "Unpublished")} + + + +
+ +
+
+ + + + + +
+ )} +
+
+
+
+ + ); +}; + +export default GroupServiceTable; + diff --git a/frontend/src/components/resource-group/resourceGroup.tsx b/frontend/src/components/resource-group/resourceGroup.tsx new file mode 100644 index 0000000..e82d675 --- /dev/null +++ b/frontend/src/components/resource-group/resourceGroup.tsx @@ -0,0 +1,348 @@ +"use client"; + +import React, { useState, useEffect } from "react"; +import { useTranslation } from "@/shared/lib/useTranslation"; +import DashboardDemoContent from "@/shared/components/DashboardDemoContent"; +import GroupList, { ResourceGroup } from "./GroupList"; +import GroupServiceTable, { GroupService } from "./GroupServiceTable"; +import { AddServerModal } from "./AddServerModal"; +import { DeleteServerModal } from "./DeleteServerModal"; +import { Divider, Select, SelectItem } from "@nextui-org/react"; +import { useResourceGroups } from "@/hooks/useResourceGroups"; +import { AddMcpServerModal } from "./AddMcpServerModal"; + +const ResourceGroupManagement: React.FC = () => { + const { t } = useTranslation(); + + // 使用自定义 Hook 管理资源组 + const { + groups, + simpleResourceGroups, + loadSimpleResourceGroups, + groupServices, + serviceTablePagination, + serviceTableParams, + loading, + servicesLoading, + hasMore, + shouldScrollToTop, + setShouldScrollToTop, + loadGroupServices, + loadMoreGroups, + handleServicePageChange, + handleAddServiceToGroup, + handleCreateGroup: createGroup, + handleUpdateGroup: updateGroup, + handleDeleteGroup: deleteGroup, + handleRemoveService: removeService, + } = useResourceGroups(); + + // 当前选中的资源组 + const [selectedGroup, setSelectedGroup] = useState(null); + + // 删除组确认模态框 + const [isDeleteGroupModalOpen, setIsDeleteGroupModalOpen] = useState(false); + const [groupToDelete, setGroupToDelete] = useState(null); + const [transferToGroupId, setTransferToGroupId] = useState(null); + const [simpleResourceGroupsLoading, setSimpleResourceGroupsLoading] = useState(false); + + // 删除服务确认模态框 + const [isDeleteServiceModalOpen, setIsDeleteServiceModalOpen] = useState(false); + const [serviceToDelete, setServiceToDelete] = useState(null); + + // 创建/编辑组模态框 + const [isGroupModalOpen, setIsGroupModalOpen] = useState(false); + const [editingGroup, setEditingGroup] = useState(null); + + // 添加 MCP 服务模态框 + const [isAddMcpServerModalOpen, setIsAddMcpServerModalOpen] = useState(false); + + // 刷新触发器,用于触发 GroupServiceTable 刷新 + const [refreshTrigger, setRefreshTrigger] = useState(0); + const [newGroupId, setNewGroupId] = useState(null); + + /** + * 保存 MCP 服务 + * @param serverIds 服务ID列表 + * @returns 是否保存成功 + */ + const handleSaveMcpServer = async (serverIds: string[]) => { + if (!selectedGroup) return; + + const success = await handleAddServiceToGroup(selectedGroup.id, serverIds); + if (success) { + setIsAddMcpServerModalOpen(false); + await loadGroupServices(selectedGroup.id, 1, serviceTableParams.current.pageSize, serviceTableParams.current.keyword); + } + }; + + // 初始化选中第一个组,或在滚动到顶部时选中第一个 + useEffect(() => { + if (groups.length > 0 && (shouldScrollToTop || !selectedGroup)) { + const index = shouldScrollToTop && newGroupId ? groups.findIndex((group) => group.id === newGroupId) : 0; + setSelectedGroup(groups[index]); + loadGroupServices(groups[index].id); + } + }, [groups, selectedGroup, loadGroupServices, shouldScrollToTop]); + + // 选择组 + const handleSelectGroup = (group: ResourceGroup) => { + setSelectedGroup(group); + loadGroupServices(group.id); + }; + + // 创建新组 + const handleCreateGroup = () => { + setEditingGroup(null); + setIsGroupModalOpen(true); + }; + + // 保存组(创建或编辑) + const handleSaveGroup = async (name: string, isDefault: boolean) => { + let success = false; + + if (editingGroup) { + // 编辑现有组 + success = await updateGroup(editingGroup.id, name, isDefault); + if (success && selectedGroup?.id === editingGroup.id) { + setSelectedGroup({ ...selectedGroup, name, isDefault }); + // 触发 GroupServiceTable 刷新 + setRefreshTrigger(prev => prev + 1); + } + } else { + // 创建新组 + const newGroupId = await createGroup(name, isDefault); + success = !!newGroupId; + if (newGroupId) { + setNewGroupId(newGroupId); + } + } + + if (success) { + setIsGroupModalOpen(false); + setEditingGroup(null); + } + }; + + // 编辑组 + const handleEditGroup = (groupId: string) => { + const group = groups.find((g) => g.id === groupId); + if (group) { + setEditingGroup(group); + setIsGroupModalOpen(true); + } + }; + + // 删除组 + const handleDeleteGroup = async (groupId: string) => { + const group = groups.find((g) => g.id === groupId); + if (group) { + setSimpleResourceGroupsLoading(true); + const simpleResourceGroups = await loadSimpleResourceGroups(); + setTransferToGroupId(simpleResourceGroups.filter((group) => group.id !== groupId)[0].id); + setSimpleResourceGroupsLoading(false); + setGroupToDelete(group); + setIsDeleteGroupModalOpen(true); + } + }; + + // 确认删除组 + const handleConfirmDeleteGroup = async () => { + if (groupToDelete && transferToGroupId) { + // 在删除前找到要选中的目标组 + let targetGroup: ResourceGroup | null = null; + if (selectedGroup?.id === groupToDelete.id) { + const currentIndex = groups.findIndex((g) => g.id === groupToDelete.id); + if (currentIndex !== -1) { + // 优先选择上一个,如果没有上一个则选择下一个 + if (currentIndex > 0) { + targetGroup = groups[currentIndex - 1]; + } else if (currentIndex < groups.length - 1) { + targetGroup = groups[currentIndex + 1]; + } + // 如果既没有上一个也没有下一个(只有一个元素),targetGroup 保持为 null + } + } + + const success = await deleteGroup(groupToDelete.id, transferToGroupId); + + if (success) { + // 等待列表刷新后选中目标组 + setTimeout(() => { + if (groups.length === 0) { + // 删除后没有任何资源组了 + setSelectedGroup(null); + } else if (targetGroup) { + // 在新列表中找到目标组(因为列表已经刷新了) + const newTarget = groups.find((g) => g.id === targetGroup.id); + if (newTarget) { + setSelectedGroup(newTarget); + loadGroupServices(newTarget.id); + } else { + // 如果目标组不存在了,选择第一个 + setSelectedGroup(groups[0]); + loadGroupServices(groups[0].id); + } + } else if (selectedGroup?.id === groupToDelete.id) { + // 如果删除的是当前选中的组,且没有找到目标组(理论上不应该发生) + setSelectedGroup(groups[0]); + loadGroupServices(groups[0].id); + } + // 如果删除的不是当前选中的组,保持原有选中状态 + }, 200); + + setIsDeleteGroupModalOpen(false); + setGroupToDelete(null); + setTransferToGroupId(null); + } + } + }; + + // 添加服务到组 + const handleAddService = () => { + setIsAddMcpServerModalOpen(true); + }; + + // 从组中移除服务 + const handleRemoveService = (serviceId: string) => { + const service = groupServices.find((s) => s.id === serviceId); + if (service) { + setServiceToDelete(service); + setIsDeleteServiceModalOpen(true); + } + }; + + // 确认删除服务 + const handleConfirmDeleteService = async () => { + if (serviceToDelete && selectedGroup) { + const success = await removeService(selectedGroup.id, serviceToDelete.id); + + if (success) { + setIsDeleteServiceModalOpen(false); + setServiceToDelete(null); + await loadGroupServices(selectedGroup.id, 1, serviceTableParams.current.pageSize, serviceTableParams.current.keyword); + } + } + }; + + return ( + +
+ {/* 左侧组列表 */} + setShouldScrollToTop(false)} + /> + + {/* 右侧服务列表 */} + {selectedGroup ? ( + handleServicePageChange(selectedGroup.id, page)} + onAddService={handleAddService} + onRemoveService={handleRemoveService} + onEditGroup={handleEditGroup} + onDeleteGroup={handleDeleteGroup} + refreshTrigger={refreshTrigger} + /> + ) : ( +
+ {t("Please select a group to view services")} +
+ )} +
+ + {/* 删除资源组模态框 */} + { + setIsDeleteGroupModalOpen(false); + setGroupToDelete(null); + setTransferToGroupId(null); + }} + onConfirm={handleConfirmDeleteGroup} + title={t("Confirm Remove")} + description={t( + 'Are you sure you want to remove this "{{name}}" Resource Group?', + { + name: groupToDelete?.name || "", + } + )} + alertDescription={t("The bound users have been transferred to the following resource group")} + customAlertContent={
+ +
} + /> + + {/* 删除服务模态框 */} + { + setIsDeleteServiceModalOpen(false); + setServiceToDelete(null); + }} + onConfirm={handleConfirmDeleteService} + title={t("Confirm Remove")} + description={t( + 'Are you sure you want to remove this "{{name}}" mcp server from "{{groupName}}" resource group?', + { + name: serviceToDelete?.name || "", + groupName: selectedGroup?.name || "", + } + )} + alertDescription={t("Users associated with this resource group will not be able to call the removed MCP server")} + /> + {/* 创建/编辑组模态框 */} + { + setIsGroupModalOpen(false); + setEditingGroup(null); + }} + name={editingGroup?.name || ""} + isDefault={editingGroup?.isDefault || false} + onSaveServer={handleSaveGroup} + type={editingGroup ? "edit" : "add"} + /> + { + setIsAddMcpServerModalOpen(false); + }} + onSaveMcpServer={handleSaveMcpServer} + /> +
+ ); +}; + +export default ResourceGroupManagement; \ No newline at end of file diff --git a/frontend/src/components/theme/ProductDetailThemeSelector.tsx b/frontend/src/components/theme/ProductDetailThemeSelector.tsx index 036790d..ba71250 100644 --- a/frontend/src/components/theme/ProductDetailThemeSelector.tsx +++ b/frontend/src/components/theme/ProductDetailThemeSelector.tsx @@ -36,6 +36,7 @@ const BasicProductDetailThemeSelector: React.FC< platformConfig.mcp_server_prefix || process.env.NEXT_PUBLIC_MCP_URL || ""; const [url, setUrl] = useState(""); const [mcpName, setMcpName] = useState(""); + const [can_invoke, setCanInvoke] = useState(false); const { t } = useTranslation(); const configNavigation = useNavigationItems() || NavigationItems; @@ -56,6 +57,9 @@ const BasicProductDetailThemeSelector: React.FC< useEffect(() => { setMcpName(sanitizeMCPServerName(product.name)); }, [product.name]); + useEffect(() => { + setCanInvoke(product.can_invoke || false); + }, [product.can_invoke]); const getCodeContent = () => { return `{ "mcpServers": { @@ -82,6 +86,7 @@ const BasicProductDetailThemeSelector: React.FC< case Theme.MODERN: return ( diff --git a/frontend/src/components/theme/classic/Detail.tsx b/frontend/src/components/theme/classic/Detail.tsx index 2bb5e7c..b8bd58a 100644 --- a/frontend/src/components/theme/classic/Detail.tsx +++ b/frontend/src/components/theme/classic/Detail.tsx @@ -16,6 +16,7 @@ import { NavigationItem } from "@/shared/components/Navigation"; import { ServerConfig } from "@/shared/components/marketplace/ServerConfig"; interface DetailProps { + can_invoke?: boolean; product: ServiceData; breadcrumbs?: { link: string; @@ -30,6 +31,7 @@ interface DetailProps { } export const Detail: React.FC = ({ + can_invoke, product, url, mcpName, @@ -216,6 +218,7 @@ export const Detail: React.FC = ({ {/* Code Snippet */} = ({ + can_invoke, product, breadcrumbs, url, @@ -176,6 +178,7 @@ export const Detail: React.FC = ({ {/* Code Snippet */} = ({ + can_invoke, product, breadcrumbs, url, @@ -144,6 +146,7 @@ export const Detail: React.FC = ({ {/* Code Snippet */} diff --git a/frontend/src/components/theme/temu/Detail.tsx b/frontend/src/components/theme/temu/Detail.tsx index 1cf3064..4a50cd7 100644 --- a/frontend/src/components/theme/temu/Detail.tsx +++ b/frontend/src/components/theme/temu/Detail.tsx @@ -15,6 +15,7 @@ import { NavigationItem } from "@/shared/components/Navigation"; import { ServerConfig } from "@/shared/components/marketplace/ServerConfig"; interface DetailProps { + can_invoke?: boolean; product: ServiceData; breadcrumbs?: { link: string; @@ -29,6 +30,7 @@ interface DetailProps { } export const Detail: React.FC = ({ + can_invoke, product, breadcrumbs, url, @@ -163,6 +165,7 @@ export const Detail: React.FC = ({
{/* Code Snippet */} { // use custom hook to manage user data const { users, + fetchUsers, loading, pagination, handleDeleteUser, @@ -70,6 +71,7 @@ const UserManagement: React.FC = () => {
{
void; loading?: boolean; onDelete: (user: User) => void; onRecharge: (id: string, amount: number) => Promise; @@ -33,6 +38,7 @@ interface UserTableProps { export const UserTable: React.FC = ({ users, + fetchUsers, loading = false, onDelete, onRecharge, @@ -51,6 +57,9 @@ export const UserTable: React.FC = ({ const [isRechargeModalOpen, setIsRechargeModalOpen] = React.useState(false); const [selectedUser, setSelectedUser] = React.useState(null); + const [simpleResourceGroups, setSimpleResourceGroups] = useState<{ id: string, name: string }[]>([]); + const [groupsLoading, setGroupsLoading] = useState(true); + const handleDelete = React.useCallback( (user: User) => { onDelete(user); @@ -68,7 +77,34 @@ export const UserTable: React.FC = ({ setSelectedUser(null); }, []); - if (loading && users.length === 0) { + // 加载简易资源组列表 + const loadSimpleResourceGroups = useCallback(async () => { + setGroupsLoading(true); + try { + const data = await fetchSimpleResourceGroups(); + setSimpleResourceGroups(data); + } catch (error) { + console.error("Failed to load simple resource groups:", error); + } finally { + setGroupsLoading(false); + } + }, []); + + const changeResourceGroup = async (user: User, resourceGroupId: string) => { + const success = await updateUserResourceGroup(user.id, resourceGroupId); + if (success) { + toast.success(t("Resource group updated successfully")); + fetchUsers(); + } + } + + // 初始加载简易资源组列表 + useEffect(() => { + loadSimpleResourceGroups(); + }, [loadSimpleResourceGroups]); + + // 等待用户数据或资源组数据加载 + if ((loading && users.length === 0) || groupsLoading) { return (
@@ -87,6 +123,7 @@ export const UserTable: React.FC = ({ > {t("Email")} + {t("Resource Group")} {t("Register Date")} {t("Balance")} {t("Actions")} @@ -102,6 +139,28 @@ export const UserTable: React.FC = ({ {user.email} + + + {user.created_at || "-"} {user.balance.toFixed(2) || "-"} diff --git a/frontend/src/hooks/useMCPServiceDetail.ts b/frontend/src/hooks/useMCPServiceDetail.ts index 9eb2a28..0c3f3ab 100644 --- a/frontend/src/hooks/useMCPServiceDetail.ts +++ b/frontend/src/hooks/useMCPServiceDetail.ts @@ -3,8 +3,12 @@ import { useState, useCallback } from "react"; import { MCPService } from "@/shared/types/mcp-service"; import { + GetMCPResourceGroupsParams, getMCPServiceDetail, parseOpenAPIDocumentForUpdate as parseOpenAPIDocumentForUpdateAPI, + fetchMCPResourceGroups as fetchMCPResourceGroupsAPI, + deleteResourceGroup as deleteResourceGroupAPI, + addServiceToGroup as addServiceToGroupAPI, } from "@/services/mcpService"; export const useMCPServiceDetail = () => { @@ -98,6 +102,40 @@ export const useMCPServiceDetail = () => { [] ); + /** + * 获取资源组列表 + * @param page 页码 + * @param page_size 每页条数 + * @param keyword 关键词 + * @returns 资源组列表 + */ + const fetchMCPResourceGroups = useCallback(async (page: number, page_size: number, keyword: string): Promise => { + const response = await fetchMCPResourceGroupsAPI(page, page_size, keyword); + return response; + }, []); + + /** + * 删除资源组 + * @param serviceById 服务ID + * @param resourceGroupId 资源组ID + * @returns 是否删除成功 + */ + const deleteResourceGroup = useCallback(async (serviceById: string, resourceGroupId: string): Promise => { + const response = await deleteResourceGroupAPI(serviceById, resourceGroupId); + return response; + }, []); + + /** + * 添加服务到资源组 + * @param groupId 资源组ID + * @param serverIds 服务ID列表 + * @returns 是否添加成功 + */ + const addServiceToGroup = useCallback(async (groupId: string, serverIds: string[]): Promise => { + const response = await addServiceToGroupAPI(groupId, serverIds); + return response; + }, []); + return { serviceDetail, detailLoading, @@ -107,5 +145,8 @@ export const useMCPServiceDetail = () => { getServiceDetail, clearServiceDetail, parseOpenAPIDocumentForUpdate, + fetchMCPResourceGroups, + deleteResourceGroup, + addServiceToGroup }; }; diff --git a/frontend/src/hooks/useResourceGroups.ts b/frontend/src/hooks/useResourceGroups.ts new file mode 100644 index 0000000..91b62f3 --- /dev/null +++ b/frontend/src/hooks/useResourceGroups.ts @@ -0,0 +1,269 @@ +import { useState, useEffect, useCallback, useRef } from "react"; +import { ResourceGroup } from "@/components/resource-group/GroupList"; +import { GroupService } from "@/components/resource-group/GroupServiceTable"; +import { + fetchResourceGroups, + fetchGroupServices, + createResourceGroup, + updateResourceGroup, + deleteResourceGroup, + removeServiceFromGroup, + fetchSimpleResourceGroups, + addServiceToGroup, +} from "@/api/resourceGroup.api"; +import { toast } from "react-hot-toast"; +import { useTranslation } from "@/shared/lib/useTranslation"; + + +export const useResourceGroups = () => { + const [groups, setGroups] = useState([]); + const [groupServices, setGroupServices] = useState([]); + const [loading, setLoading] = useState(false); + const [servicesLoading, setServicesLoading] = useState(false); + const [hasMore, setHasMore] = useState(true); + const [shouldScrollToTop, setShouldScrollToTop] = useState(false); + const { t } = useTranslation(); + + const [simpleResourceGroups, setSimpleResourceGroups] = useState<{ id: string, name: string }[]>([]); + + // 菜单列表(GroupList)的分页和搜索状态 + const groupListParams = useRef({ + page: 1, + pageSize: 10, + keyword: "" + }); + + // 服务列表(GroupServiceTable)的分页状态 + const [serviceTablePagination, setServiceTablePagination] = useState({ + page: 1, + pageSize: 10, + total: 0, + }); + const serviceTableParams = useRef({ + pageSize: 10, + keyword: "" + }); + + // 加载资源组列表(支持初始加载和追加加载) + const loadGroups = useCallback(async (page: number, page_size: number, search_keyword: string, append: boolean = false) => { + setLoading(true); + try { + groupListParams.current = { + page, + pageSize: page_size, + keyword: search_keyword + }; + + const response = await fetchResourceGroups(page, page_size, search_keyword); + const mappedData = response.data.map((item) => ({ + id: item.id, + name: item.name, + description: item.description, + isDefault: item.is_default, + serviceCount: item.service_count, + createdAt: item.create_at, + })); + + if (append) { + // 追加模式:将新数据追加到现有数据后面 + setGroups((prev) => { + const newGroups = [...prev, ...mappedData]; + setHasMore(newGroups.length < response.total); + return newGroups; + }); + } else { + // 重置模式:替换所有数据 + setGroups(mappedData); + setHasMore(mappedData.length < response.total); + } + } finally { + setLoading(false); + } + }, []); + + // 加载更多资源组(追加数据) + const loadMoreGroups = useCallback(async () => { + if (loading || !hasMore) return; + + const { page, pageSize, keyword } = groupListParams.current; + await loadGroups(page + 1, pageSize, keyword, true); + }, [loading, hasMore, loadGroups]); + + // 加载指定组的服务列表(支持分页) + const loadGroupServices = useCallback(async ( + groupId: string, + page: number = 1, + pageSize: number = 10, + keyword: string = "" + ) => { + setServicesLoading(true); + try { + const response = await fetchGroupServices(groupId, page, pageSize, keyword); + setGroupServices(response.data); + setServiceTablePagination({ + page: response.page, + pageSize: response.page_size, + total: response.total, + }); + // 保存当前的 pageSize 和 keyword 到 ref + serviceTableParams.current = { + pageSize: response.page_size, + keyword + }; + } catch (error) { + console.error(t("Failed to load group services"), error); + } finally { + setServicesLoading(false); + } + }, []); + + // 创建资源组 + const handleCreateGroup = useCallback( + async (name: string, isDefault: boolean): Promise => { + try { + const result = await createResourceGroup(name, isDefault); + if (!result.success) { + return ""; + } + // 创建成功后重新加载列表(重置到第1页) + toast.success(t("Resource group created successfully")); + const { pageSize, keyword } = groupListParams.current; + await loadGroups(1, pageSize, keyword, false); + // 触发滚动到顶部 + setShouldScrollToTop(true); + return result.id; + } catch { + return ""; + } + }, + [loadGroups] + ); + + // 更新资源组 + const handleUpdateGroup = useCallback( + async (groupId: string, name: string, isDefault: boolean): Promise => { + try { + const result = await updateResourceGroup(groupId, name, isDefault); + if (!result) { + return false; + } + // 更新成功后重新加载列表(重置到第1页) + const { pageSize, keyword } = groupListParams.current; + await loadGroups(1, pageSize, keyword, false); + toast.success(t("Resource group updated successfully")); + return true; + } catch { + return false; + } + }, + [loadGroups] + ); + + // 删除资源组 + const handleDeleteGroup = useCallback( + async (groupId: string, transferToGroupId: string): Promise => { + try { + const result = await deleteResourceGroup(groupId, transferToGroupId); + if (!result) { + return false; + } + // 删除成功后重新加载列表(重置到第1页) + const { pageSize, keyword } = groupListParams.current; + await loadGroups(1, pageSize, keyword, false); + toast.success(t("Resource group deleted successfully")); + return true; + } catch { + return false; + } + }, + [loadGroups] + ); + + // 服务列表翻页 + const handleServicePageChange = useCallback( + async (groupId: string, page: number) => { + await loadGroupServices( + groupId, + page, + serviceTableParams.current.pageSize, + serviceTableParams.current.keyword + ); + }, + [loadGroupServices] + ); + + // 添加服务到组 + const handleAddServiceToGroup = useCallback( + async (groupId: string, serviceIds: string[]): Promise => { + try { + const success = await addServiceToGroup(groupId, serviceIds); + if (!success) { + return false; + } + toast.success(t("Services added successfully")); + return true; + } catch { + return false; + } + }, + [loadGroupServices, serviceTablePagination.page] + ); + + // 从组中移除服务 + const handleRemoveService = useCallback( + async (groupId: string, serviceId: string): Promise => { + try { + const success = await removeServiceFromGroup(groupId, [serviceId]); + if (!success) { + return false; + } + toast.success(t("Service removed successfully")); + return true; + } catch { + return false; + } + }, + [loadGroupServices, serviceTablePagination.page] + ); + + // 加载简单资源组列表(用于下拉选择) + const loadSimpleResourceGroups = useCallback(async () => { + try { + const data = await fetchSimpleResourceGroups(); + setSimpleResourceGroups(data); + return data + } catch (error) { + console.error("Failed to load simple resource groups:", error); + return [] + } + }, []); + + // 初始加载 + useEffect(() => { + loadGroups(1, 10, ""); + }, [loadGroups]); + + return { + groups, + simpleResourceGroups, + groupServices, + serviceTablePagination, + serviceTableParams, + loading, + servicesLoading, + hasMore, + shouldScrollToTop, + setShouldScrollToTop, + loadGroups, + loadMoreGroups, + loadGroupServices, + loadSimpleResourceGroups, + handleServicePageChange, + handleAddServiceToGroup, + handleCreateGroup, + handleUpdateGroup, + handleDeleteGroup, + handleRemoveService, + }; +}; + diff --git a/frontend/src/rpc/admin-api.ts b/frontend/src/rpc/admin-api.ts index 4fb3ee8..08660db 100644 --- a/frontend/src/rpc/admin-api.ts +++ b/frontend/src/rpc/admin-api.ts @@ -38,7 +38,7 @@ export const fetchAdminAPI = async ( const contentType = response.headers.get("Content-Type"); // Parse response based on content type - if (contentType?.includes("application/json")) { + if (contentType?.includes("application/json") || response.url.startsWith("http://uat.apikit.com:11204/")) { const result = await response.json(); return result; } else { diff --git a/frontend/src/services/mcpService.ts b/frontend/src/services/mcpService.ts index d26ce69..54a2a6b 100644 --- a/frontend/src/services/mcpService.ts +++ b/frontend/src/services/mcpService.ts @@ -1,6 +1,7 @@ import { ApiArrayResponse, ApiObjectResponse } from "@/shared/types"; import { fetchAdminAPI } from "@/rpc/admin-api"; import { + MCPResourceGroupResponse, MCPService, MCPServiceFormData, OpenAPIParseResponse, @@ -28,6 +29,13 @@ export interface GetMCPServiceListParams { status?: string; } +export interface GetMCPResourceGroupsParams { + data: MCPResourceGroupResponse[]; + total: number; + page: number; + page_size: number; +} + // get MCP server detail params interface export interface GetMCPServiceDetailParams { id: string; @@ -217,3 +225,88 @@ export const parseOpenAPIDocumentForUpdate = async ( return response as ApiObjectResponse; }; + +/** + * 获取资源组列表 + */ +export const fetchMCPResourceGroups = async (page: number, page_size: number, keyword: string): Promise => { + try { + // const response = await fetchAPI(`/api/service/resource_group/list?page=${page}&page_size=${page_size}&keyword=${keyword}`); + const response = await fetchAdminAPI(`http://uat.apikit.com:11204/mockApi/CaAau8f9f09663d610e0d7d919412be238695b46d0a44b1/api/service/resource_group/list?page=${page}&page_size=${page_size}&keyword=${keyword}`); + if (!response.success) { + toast.error(response.error_message || i18n.t("Failed to load resource groups")); + return { + data: [], + total: 0, + page, + page_size, + }; + } + return { + data: response.data || [], + total: response.page?.total || 0, + page: response.page?.page || page, + page_size: response.page?.page_size || page_size, + }; + } catch (error) { + console.error("Error fetching auth keys:", error); + return { + data: [], + total: 0, + page, + page_size, + }; + } +}; + +/** + * 删除资源组 + */ +export const deleteResourceGroup = async (serviceById: string, resourceGroupId: string): Promise => { + try { + const response = await fetchAdminAPI>(`http://uat.apikit.com:11204/mockApi/CaAau8f9f09663d610e0d7d919412be238695b46d0a44b1/api/service/resource_group`, { + method: "DELETE", + body: { id: serviceById, resource_group: resourceGroupId } as unknown as BodyInit, + }); + // const response = await fetchAPI>(`/api/service/resource_group`, { + // method: "DELETE" + // body: { id: serviceById, resource_group: resourceGroupId } as unknown as BodyInit, + // }); + if (!response.success) { + toast.error(response?.error_message || i18n.t("Failed to delete resource group")); + return false; + } + return true; + } catch (error) { + console.error("Error fetching auth keys:", error); + return false + } +}; + +/** + * 添加服务到资源组 + */ +export const addServiceToGroup = async ( + groupId: string, + services: string[] +): Promise => { + try { + const response = await fetchAdminAPI>(`http://uat.apikit.com:11204/mockApi/CaAau8f9f09663d610e0d7d919412be238695b46d0a44b1/api/service/resource_group`, { + method: "PUT", + body: { id: groupId, resource_group: services } as unknown as BodyInit, + }); + // const response = await fetchAPI>(`/api/service/resource_group`, { + // method: "PUT" + // body: { id: groupId, resource_group: services } as unknown as BodyInit, + // }); + if (!response.success) { + toast.error(response?.error_message || i18n.t("Failed to add service to group")); + return false; + } + return true; + } catch (error) { + console.error("Error fetching auth keys:", error); + return false + } +}; + diff --git a/frontend/src/shared/components/marketplace/ProductDetail.tsx b/frontend/src/shared/components/marketplace/ProductDetail.tsx index 3d4e6e8..624deec 100644 --- a/frontend/src/shared/components/marketplace/ProductDetail.tsx +++ b/frontend/src/shared/components/marketplace/ProductDetail.tsx @@ -18,6 +18,7 @@ interface ProductDetailClientProps { }[]; mcpName?: string; url?: string; + can_invoke?: boolean; innerHeaderNode?: React.ReactNode; } @@ -26,6 +27,7 @@ export const ProductDetailClient: React.FC = ({ breadcrumbs, mcpName, url, + can_invoke, innerHeaderNode, }) => { const { t } = useTranslation(); @@ -69,7 +71,7 @@ export const ProductDetailClient: React.FC = ({
{/* Right side - Server Config */} - +
{/* SEO-friendly: Simple text content for search engines */} diff --git a/frontend/src/shared/components/marketplace/ServerConfig.tsx b/frontend/src/shared/components/marketplace/ServerConfig.tsx index 306661e..b36ddb6 100644 --- a/frontend/src/shared/components/marketplace/ServerConfig.tsx +++ b/frontend/src/shared/components/marketplace/ServerConfig.tsx @@ -14,6 +14,7 @@ interface ServerConfigProps { mcpName?: string; url?: string; className?: string; + can_invoke?: boolean; } type McpType = "sse" | "streamable-http"; @@ -22,6 +23,7 @@ export const ServerConfig: React.FC = ({ mcpName, url = process.env.NEXT_PUBLIC_MCP_URL, className = "md:min-w-[40%] w-[40%] max-w-100 mt-12", + can_invoke, }) => { const { t } = useTranslation(); const { handleLogin } = useAuth(); @@ -133,6 +135,15 @@ export const ServerConfig: React.FC = ({ + + {/* Permission Overlay */} + {can_invoke === false && ( +
+

+ {t("You don't have permission to access this MCP server.")} +

+
+ )} ); diff --git a/frontend/src/shared/components/mcp-services/ResourceGroup.tsx b/frontend/src/shared/components/mcp-services/ResourceGroup.tsx new file mode 100644 index 0000000..ad43638 --- /dev/null +++ b/frontend/src/shared/components/mcp-services/ResourceGroup.tsx @@ -0,0 +1,278 @@ +"use client"; + +import React, { useCallback, useEffect, useRef, useState } from "react"; +import { + Button, + Table, + TableHeader, + TableColumn, + TableBody, + TableRow, + TableCell, + Tooltip, + Spinner, + Pagination, +} from "@nextui-org/react"; +import { useTranslation } from "@/shared/lib/useTranslation"; +import { Plus, SquareArrowOutUpRight, Trash2 } from "lucide-react"; +import { MCPServiceFormData } from "@/shared/types/mcp-service"; +import toast from "react-hot-toast"; +import { GetMCPResourceGroupsParams } from "@/services/mcpService"; +import DeleteServerModal from "@/components/resource-group/DeleteServerModal"; +import { McpAddGroupModal } from "../modal/McpAddGroup"; + +// 组内服务类型定义 +export interface ResourceGroup { + id: string; + name: string; + join_at: string; +} + +interface ResourceGroupProps { + deleteResourceGroup: (serviceById: string, resourceGroupId: string) => Promise; + fetchMCPResourceGroups: (page: number, page_size: number, keyword: string) => Promise; + addServiceToGroup: (groupId: string, serverIds: string[]) => Promise; + formData: MCPServiceFormData; +} + +const ResourceGroup: React.FC = ({ + deleteResourceGroup, + fetchMCPResourceGroups, + addServiceToGroup, + formData +}) => { + const { t } = useTranslation(); + const [resourceGroups, setResourceGroups] = useState([]); + const [loading, setLoading] = useState(false); + const [pagination, setPagination] = useState({ + page: 1, + pageSize: 10, + total: 0, + }); + const resourceGroupsParams = useRef({ + page: 1, + pageSize: 10, + keyword: "", + }); + const [isDeleteResourceGroupModalOpen, setIsDeleteResourceGroupModalOpen] = useState(false); + const [resourceGroupToDelete, setResourceGroupToDelete] = useState(null); + + // 添加 MCP 服务模态框 + const [isAddMcpGroupModalOpen, setIsAddMcpGroupModalOpen] = useState(false); + + /** + * 加载资源组列表 + */ + const loadResourceGroups = useCallback(async ( + page: number = 1, + pageSize: number = 10, + keyword: string = "" + ) => { + setLoading(true); + try { + const response = await fetchMCPResourceGroups(page, pageSize, keyword); + setResourceGroups(response.data); + setPagination({ + page: response.page, + pageSize: response.page_size, + total: response.total, + }); + // 保存当前的 pageSize 和 keyword 到 ref + resourceGroupsParams.current = { + page: response.page, + pageSize: response.page_size, + keyword + }; + } catch (error) { + console.error(t("Failed to load group services"), error); + } finally { + setLoading(false); + } + }, []); + + const onAddService = () => { + setIsAddMcpGroupModalOpen(true); + } + // 保存 MCP 服务 + const handleSaveMcpServer = async (serverIds: string[]) => { + if (!formData?.id) return; + + const success = await addServiceToGroup(formData?.id, serverIds); + if (success) { + setIsAddMcpGroupModalOpen(false); + await loadResourceGroups(1, resourceGroupsParams.current.pageSize, resourceGroupsParams.current.keyword); + } + }; + /** + * 确认删除资源组 + */ + const handleConfirmDeleteResourceGroup = async () => { + const result = await deleteResourceGroup(formData?.id || "", resourceGroupToDelete?.id || ""); + if (result) { + loadResourceGroups(1, 10, ""); + setIsDeleteResourceGroupModalOpen(false); + setResourceGroupToDelete(null); + toast.success(t("Resource group deleted successfully")); + } else { + setIsDeleteResourceGroupModalOpen(false); + setResourceGroupToDelete(null); + } + } + + /** + * 删除资源组 + * @param groupId 删除资源组 + */ + const onRemoveResourceGroup = async (groupId: string) => { + const group = resourceGroups.find((group) => group.id === groupId); + if (group) { + setResourceGroupToDelete(group); + setIsDeleteResourceGroupModalOpen(true); + } + } + const onPageChange = (page: number) => { + const { pageSize, keyword } = resourceGroupsParams.current; + loadResourceGroups(page, pageSize, keyword); + } + + const openResourceGroupPage = (group: ResourceGroup) => { + window.open(`/admin/console?tab=resource-group`, '_blank'); + } + + useEffect(() => { + loadResourceGroups(1, 10, ""); + }, [loadResourceGroups]); + + const pages = Math.ceil(pagination.total / pagination.pageSize); + const currentPage = Number(pagination.page); + + return ( + <> +
+
+
+ +
+ +
+
+ + 1 ? ( +
+ +
+ ) : null + } + > + + {t("Group Name")} + {t("Added Time")} + {t("Actions")} + + } + emptyContent={t("No services in this group")} + > + {(group) => ( + + + {group.name} + + + {group.join_at} + + +
+ + + + + + +
+
+
+ )} +
+
+
+ {/* 删除服务模态框 */} + { + setIsDeleteResourceGroupModalOpen(false); + setResourceGroupToDelete(null); + }} + onConfirm={handleConfirmDeleteResourceGroup} + title={t("Confirm Remove")} + description={t( + 'Are you sure you want to remove this "{{name}}" mcp server from "{{groupName}}" resource group?', + { + name: resourceGroupToDelete?.name || "", + groupName: formData?.name || "", + } + )} + alertDescription={t("Users associated with this resource group will not be able to call the removed MCP server")} + /> + { + setIsAddMcpGroupModalOpen(false); + }} + onSaveMcpServer={handleSaveMcpServer} + /> + + ); +}; + +export default ResourceGroup + diff --git a/frontend/src/shared/components/modal/DeleteConfirmModal.tsx b/frontend/src/shared/components/modal/DeleteConfirmModal.tsx index aa84e77..fe9e6a3 100644 --- a/frontend/src/shared/components/modal/DeleteConfirmModal.tsx +++ b/frontend/src/shared/components/modal/DeleteConfirmModal.tsx @@ -12,6 +12,7 @@ import { Alert, } from "@nextui-org/react"; import { useTranslation } from "@/shared/lib/useTranslation"; +import { User } from "@/types/user"; interface DeleteConfirmModalProps { isOpen: boolean; @@ -23,6 +24,7 @@ interface DeleteConfirmModalProps { requireNameConfirmation?: boolean; confirmationName?: string; confirmationPlaceholder?: string; + user?: User | null; } export const DeleteConfirmModal: React.FC = ({ @@ -35,6 +37,7 @@ export const DeleteConfirmModal: React.FC = ({ requireNameConfirmation = false, confirmationName = "", confirmationPlaceholder, + user, }) => { const { t } = useTranslation(); const [inputValue, setInputValue] = useState(""); @@ -79,6 +82,16 @@ export const DeleteConfirmModal: React.FC = ({
+ {user && ( +
+

+ {t("User")}: {user.email} +

+

+ {t("Current Balance")}: ${user.balance.toFixed(2)} +

+
+ )} {/* Description */}
{description || defaultDescription} diff --git a/frontend/src/shared/components/modal/McpAddGroup.tsx b/frontend/src/shared/components/modal/McpAddGroup.tsx new file mode 100644 index 0000000..1dcdbec --- /dev/null +++ b/frontend/src/shared/components/modal/McpAddGroup.tsx @@ -0,0 +1,141 @@ +import { + Button, + Modal, + ModalBody, + ModalContent, + ModalFooter, + ModalHeader, + Table, + TableHeader, + TableColumn, + TableBody, + TableRow, + TableCell, + Spinner, + } from "@nextui-org/react"; + import { useState, useEffect, useCallback } from "react"; + import { useTranslation } from "@/shared/lib/useTranslation"; + import { fetchSimpleResourceGroups } from "@/api/resourceGroup.api"; + + interface McpAddGroupModalProps { + isOpen: boolean; + onClose: () => void; + onSaveMcpServer: (serverIds: string[]) => Promise; + } + + interface ResourceGroup { + id: string; + name: string; + } + + export const McpAddGroupModal: React.FC = ({ + isOpen, + onClose, + onSaveMcpServer, + }) => { + const { t } = useTranslation(); + const [isLoading, setIsLoading] = useState(false); + const [loading, setLoading] = useState(false); + const [resourceGroups, setResourceGroups] = useState([]); + const [selectedKeys, setSelectedKeys] = useState>(new Set()); + + // 加载服务列表 + const loadServices = useCallback(async () => { + setLoading(true); + try { + const response = await fetchSimpleResourceGroups(); + setResourceGroups(response); + } catch (error) { + console.error("Failed to load resource groups:", error); + } finally { + setLoading(false); + } + }, []); + + // 当模态框打开时加载数据 + useEffect(() => { + if (isOpen) { + setSelectedKeys(new Set()); + loadServices(); + } + }, [isOpen, loadServices]); + + // 处理保存 + const handleSave = async () => { + const serverIds = Array.from(selectedKeys); + if (serverIds.length === 0) { + return; + } + + setIsLoading(true); + try { + await onSaveMcpServer(serverIds); + onClose(); + } finally { + setIsLoading(false); + } + }; + + return ( + + + {() => ( + <> + + {t("Add to Groups")} + + + setSelectedKeys(keys as Set)} + removeWrapper + classNames={{ + wrapper: "min-h-[400px]", + }} + className="[&_td:first-child]:w-[30px] [&_th:first-child]:w-[30px]" + > + + {t("Group Name")} + + } + emptyContent={t("No resource groups available")} + > + {(resourceGroup) => ( + + + {resourceGroup.name} + + + )} + +
+
+ + + + + + )} +
+
+ ); + }; \ No newline at end of file diff --git a/frontend/src/shared/rpc/common-function.ts b/frontend/src/shared/rpc/common-function.ts index f8ee831..1c36b4d 100644 --- a/frontend/src/shared/rpc/common-function.ts +++ b/frontend/src/shared/rpc/common-function.ts @@ -46,7 +46,7 @@ export const fetchAPI = async ( const contentType = response.headers.get("Content-Type"); // Parse response based on content type - if (contentType?.includes("application/json")) { + if (contentType?.includes("application/json") || response.url.startsWith("http://uat.apikit.com:11204/")) { const result = await response.json(); return result; } else if (contentType && contentType.includes("text/event-stream")) { diff --git a/frontend/src/shared/types/dashboard.ts b/frontend/src/shared/types/dashboard.ts index c0947f2..15f313d 100644 --- a/frontend/src/shared/types/dashboard.ts +++ b/frontend/src/shared/types/dashboard.ts @@ -2,6 +2,7 @@ export enum TabKey { CONSOLE = "console", MCP_SERVICES = "mcp-services", USER_MANAGEMENT = "user-management", + RESOURCE_GROUP = "resource-group", REVENUE_MANAGEMENT = "revenue-management", PAYMENT_CHANNELS = "payment-channels", LOGIN_SETTINGS = "login-settings", diff --git a/frontend/src/shared/types/mcp-service.ts b/frontend/src/shared/types/mcp-service.ts index d3980b4..6c8656a 100644 --- a/frontend/src/shared/types/mcp-service.ts +++ b/frontend/src/shared/types/mcp-service.ts @@ -31,6 +31,7 @@ export interface BaseMCPService { output_token_price?: string; apis: MCPServiceAPIItem[]; tags?: string[]; + can_invoke?: boolean } export interface MCPService extends BaseMCPService { base_url: string; @@ -135,3 +136,9 @@ export function convertFormToAPI( update_type: formData.update_type, }; } + +export interface MCPResourceGroupResponse { + id: string; + name: string; + join_at: string; +} diff --git a/frontend/src/types/user.ts b/frontend/src/types/user.ts index a979e44..407fb11 100644 --- a/frontend/src/types/user.ts +++ b/frontend/src/types/user.ts @@ -3,6 +3,7 @@ export interface User { id: string; email: string; balance: number; + resource_group: string; } // user management related filter interface From 95ec31d5c08d38afec22e53eda600159a2aa8814 Mon Sep 17 00:00:00 2001 From: lcx <1793599591@qq.com> Date: Tue, 16 Dec 2025 14:19:42 +0800 Subject: [PATCH 3/7] feat: resource-group-management --- .../components/user-management/UserTable.tsx | 6 +++--- frontend/src/hooks/useMCPServiceDetail.ts | 4 ++-- frontend/src/services/mcpService.ts | 21 ++++++------------- .../components/mcp-services/ResourceGroup.tsx | 4 ++-- frontend/src/types/user.ts | 2 +- 5 files changed, 14 insertions(+), 23 deletions(-) diff --git a/frontend/src/components/user-management/UserTable.tsx b/frontend/src/components/user-management/UserTable.tsx index f5459de..f72c1fc 100644 --- a/frontend/src/components/user-management/UserTable.tsx +++ b/frontend/src/components/user-management/UserTable.tsx @@ -123,7 +123,7 @@ export const UserTable: React.FC = ({ > {t("Email")} - {t("Resource Group")} + {t("Resource Group")} {t("Register Date")} {t("Balance")} {t("Actions")} @@ -143,7 +143,7 @@ export const UserTable: React.FC = ({