From 88325a0ba9cb4d92346dd38f014911e11dd329fa Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Mon, 29 Dec 2025 14:19:26 +0800 Subject: [PATCH 01/16] 1. Users can view transaction data on the client side. 2. The MCP service list supports tag filtering. --- .../admin_service/controllers/mcp_manager.py | 16 ++++- services/admin_service/controllers/order.py | 63 ++++++++++++++++++ services/admin_service/controllers/user.py | 66 ++++++++++++++++++- services/admin_service/controllers/web.py | 10 ++- .../repositories/mcp_service_repository.py | 15 ++++- .../user_wallet_history_repository.py | 24 ++++++- .../services/mcp_manager_service.py | 29 +++++++- .../services/user_wallet_history_service.py | 3 + services/common/config.py | 1 + 9 files changed, 218 insertions(+), 9 deletions(-) diff --git a/services/admin_service/controllers/mcp_manager.py b/services/admin_service/controllers/mcp_manager.py index fff8d1b..b413122 100644 --- a/services/admin_service/controllers/mcp_manager.py +++ b/services/admin_service/controllers/mcp_manager.py @@ -270,6 +270,20 @@ def get_mcp_service_simple_list( logger.error(f"Failed to get service simple list: {str(e)}") return ResponseUtils.error(error_msg=error_msg.INTERNAL_ERROR) +@router.get("/service/tags", summary="Get MCP service tags") +def get_mcp_service_tags( + request: Request, + mcp_manager_service: McpManagerService = Depends(get_mcp_manager), +): + if not UserUtils.is_admin(request): + return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION) + try: + tags = mcp_manager_service.get_tags_list(enabled_only=False) + return ResponseUtils.success(data=tags) + except Exception as e: + logger.error(f"Failed to get service tags: {str(e)}") + return ResponseUtils.error(error_msg=error_msg.INTERNAL_ERROR) + @router.get("/service/resource_group/list", summary="Get MCP service's resource group list") def get_mcp_service_resource_group_list( request: Request, @@ -360,4 +374,4 @@ def unbind_group( return ResponseUtils.success() except Exception as e: logger.error(f"Failed to unbind resource groups: {str(e)}") - return ResponseUtils.error(error_msg=error_msg.INTERNAL_ERROR) \ No newline at end of file + return ResponseUtils.error(error_msg=error_msg.INTERNAL_ERROR) diff --git a/services/admin_service/controllers/order.py b/services/admin_service/controllers/order.py index 34d8821..fe900b9 100644 --- a/services/admin_service/controllers/order.py +++ b/services/admin_service/controllers/order.py @@ -1,4 +1,7 @@ +from os import stat +from typing import Optional, List from fastapi import APIRouter, Depends, Query +from services.common.models.user_wallet_history import TransactionType from sqlalchemy import table from sqlalchemy.orm import Session from services.common.database import get_db @@ -52,3 +55,63 @@ def get_user_order_list( ) return ResponseUtils.success_page(data=result, total=total, page_num=page, page_size=page_size) + +@router.get("/list/by_user", summary="Get user order list by user id") +def get_user_order_list_by_user_id( + user_id: str = Query(..., description="User ID"), + page: int = Query(1, description="Current page number"), + page_size: int = Query(15, description="Number of items per page"), + order_type: Optional[str] = Query(None, description="Order type"), + status: Optional[str] = Query(None, description="Order status"), + user_service: UserService = Depends(get_user_service), + user_wallet_history_service: UserWalletHistoryService = Depends(get_user_wallet_history_service), +): + """Get paginated list of user order history by user id.""" + user = user_service.get_by_id(user_id) + if not user: + return ResponseUtils.error(message="not found user", code=404) + offset = (page - 1) * page_size + order_type_list = [] + if order_type: + # 将字符串转成列表,中间使用逗号分隔 + ots = order_type.split(",") + for ot in ots: + ot = ot.strip() + if ot == "purchase": + order_type_list.append("api_call") + elif ot == "recharge": + order_type_list.append("deposit") + else: + order_type_list.append(ot) + status_list: Optional[List[int]] = [] + if status: + sl = status.split(",") + for s in sl: + status_list.append(int(s.strip())) + total, orders = user_wallet_history_service.success_order_list_by_user(user_id, offset, page_size, order_type_list, status_list) + if not orders: + return ResponseUtils.success_page(data=[], total=total, page_num=page, page_size=page_size) + result = [] + for order in orders: + confirm_at = "" + if order.status == 1: + confirm_at = order.updated_at + for order in orders: + info = { + "id": order.id, + "user_id": order.user_id, + "order_id": order.transaction_id, + "payment_type": order.payment_method, + "payment_state": order.status, + "amount": order.amount, + "create_at": order.created_at, + "confirm_at": confirm_at, + } + if order.type == TransactionType.API_CALL: + info["order_type"] = "purchase" + elif order.type == TransactionType.DEPOSIT: + info["order_type"] = "recharge" + else: + info["order_type"] = order.type + result.append(info) + return ResponseUtils.success_page(data=result, total=total, page_num=page, page_size=page_size) \ No newline at end of file diff --git a/services/admin_service/controllers/user.py b/services/admin_service/controllers/user.py index 12a1004..73e102b 100644 --- a/services/admin_service/controllers/user.py +++ b/services/admin_service/controllers/user.py @@ -1,4 +1,4 @@ -from fastapi import APIRouter, Depends, Request,Body +from fastapi import APIRouter, Depends, Request,Body,Query from sqlalchemy.orm import Session from services.common.database import get_db from services.admin_service.constants.user_task import user_task_ids @@ -10,6 +10,9 @@ from services.admin_service.services.user_wallet_service import UserWalletServic from services.admin_service.services.user_task_service import UserTaskService from services.admin_service.services.auth_service import AuthService from services.admin_service.services.resource_group_service import ResourceGroupService +from services.admin_service.services.user_wallet_history_service import UserWalletHistoryService +from services.common.models.user_wallet_history import TransactionType +from typing import Optional,List router = APIRouter() @@ -27,6 +30,9 @@ def get_user_task_service(db: Session = Depends(get_db)) -> UserTaskService: def get_resource_group_service(db: Session = Depends(get_db)) -> ResourceGroupService: return ResourceGroupService(db) +def get_order_service(db: Session = Depends(get_db)) -> UserWalletHistoryService: + return UserWalletHistoryService(db) + @router.get("/info", response_model=dict) def get_user(request: Request, user_wallet: UserWalletService = Depends(get_user_wallet), user_task: UserTaskService = Depends(get_user_task_service), resource_group_service: ResourceGroupService = Depends(get_resource_group_service)): """Get current user information and wallet balance.""" @@ -87,3 +93,61 @@ def update_password( return ResponseUtils.error(message="not found user", code=404) +@router.get("/order/list", summary="Get order list") +def get_order_list( + request: Request, + page: int = Query(1, description="Current page number"), + page_size: int = Query(15, description="Number of items per page"), + order_type: Optional[str] = Query(None, description="Order type"), + status: Optional[str] = Query(None, description="Order status"), + user_wallet_history_service: UserWalletHistoryService = Depends(get_order_service), +): + """Get order list.""" + user = UserUtils.get_request_user(request) + if not user: + return ResponseUtils.error(message="not found user", code=404) + offset = (page - 1) * page_size + order_type_list = [] + if order_type: + # 将字符串转成列表,中间使用逗号分隔 + ots = order_type.split(",") + for ot in ots: + ot = ot.strip() + if ot == "purchase": + order_type_list.append("api_call") + elif ot == "recharge": + order_type_list.append("deposit") + else: + order_type_list.append(ot) + status_list: Optional[List[int]] = [] + if status: + sl = status.split(",") + for s in sl: + status_list.append(int(s.strip())) + total, orders = user_wallet_history_service.success_order_list_by_user(user.id, offset, page_size, order_type_list, status_list) + if not orders: + return ResponseUtils.success_page(data=[], total=total, page_num=page, page_size=page_size) + result = [] + for order in orders: + confirm_at = "" + if order.status == 1: + confirm_at = order.updated_at + for order in orders: + info = { + "id": order.id, + "user_id": order.user_id, + "order_id": order.transaction_id, + "payment_type": order.payment_method, + "payment_state": order.status, + "amount": order.amount, + "create_at": order.created_at, + "confirm_at": confirm_at, + } + if order.type == TransactionType.API_CALL: + info["order_type"] = "purchase" + elif order.type == TransactionType.DEPOSIT: + info["order_type"] = "recharge" + else: + info["order_type"] = order.type + result.append(info) + return ResponseUtils.success_page(data=result, total=total, page_num=page, page_size=page_size) \ No newline at end of file diff --git a/services/admin_service/controllers/web.py b/services/admin_service/controllers/web.py index a5f8b47..36e48e4 100644 --- a/services/admin_service/controllers/web.py +++ b/services/admin_service/controllers/web.py @@ -29,6 +29,7 @@ def get_public_mcp_services( keyword: Optional[str] = Query(None, description="Search keyword"), page: Optional[int] = Query(1, description="Page number (starts from 1)"), page_size: Optional[int] = Query(10, description="Page size (default 10)"), + tag: Optional[str] = Query(None, description="Filter by tag"), mcp_manager_service: McpManagerService = Depends(get_mcp_manager), ): """Get paginated list of public MCP services with keyword search.""" @@ -43,12 +44,19 @@ def get_public_mcp_services( # Get service list - let any exception bubble up to middleware service_list, total = mcp_manager_service.get_public_services_paginated( - keyword=search_keyword, page=validated_page, page_size=validated_page_size + keyword=search_keyword, page=validated_page, page_size=validated_page_size, tag=tag ) logger.info(f"Successfully retrieved {len(service_list)} services") return ResponseUtils.success_page(data=service_list, page_num=validated_page, page_size=validated_page_size, total=total) +@router.get("/mcp_tags", summary="Get public MCP tags list") +def get_public_mcp_tags( + mcp_manager_service: McpManagerService = Depends(get_mcp_manager), +): + tags = mcp_manager_service.get_tags_list(enabled_only=True) + return ResponseUtils.success(data=tags) + @router.get("/mcp_service_info", summary="Get public MCP service information") def get_public_mcp_service_info( diff --git a/services/admin_service/repositories/mcp_service_repository.py b/services/admin_service/repositories/mcp_service_repository.py index 98c33eb..3a8e713 100644 --- a/services/admin_service/repositories/mcp_service_repository.py +++ b/services/admin_service/repositories/mcp_service_repository.py @@ -1,4 +1,5 @@ from datetime import datetime, timezone +from sqlalchemy import func from sqlalchemy.orm import Session from services.common.models.mcp_service import McpService from typing import Optional, Tuple, List @@ -103,7 +104,7 @@ class McpServiceRepository: self.db.refresh(mcp_service) return mcp_service - def get_public_services_paginated(self, keyword: str, page: int = 1, page_size: int = 10) -> Tuple[List[McpService], int]: + def get_public_services_paginated(self, keyword: str, page: int = 1, page_size: int = 10, tag: Optional[str] = None) -> Tuple[List[McpService], int]: """Get public service list with pagination, supports keyword search""" offset = (page - 1) * page_size @@ -112,9 +113,21 @@ class McpServiceRepository: if keyword: keyword = f"%{keyword}%" query = query.filter((McpService.name.like(keyword)) | (McpService.short_description.like(keyword))) + if tag: + normalized_tag = tag.strip() + if normalized_tag: + normalized_tags = func.replace(func.replace(McpService.tags, ", ", ","), " ,", ",") + query = query.filter(func.find_in_set(normalized_tag, normalized_tags) > 0) + total = query.count() services = query.order_by(McpService.created_at.desc()).offset(offset).limit(page_size).all() return services, total + + def get_tags_strings(self, enabled_only: bool = False) -> List[str]: + query = self.db.query(McpService.tags).filter(McpService.tags.isnot(None)).filter(McpService.tags != "") + if enabled_only: + query = query.filter(McpService.enabled == 1) + return [row[0] for row in query.all() if row and row[0]] diff --git a/services/admin_service/repositories/user_wallet_history_repository.py b/services/admin_service/repositories/user_wallet_history_repository.py index d47cc95..0da9b47 100644 --- a/services/admin_service/repositories/user_wallet_history_repository.py +++ b/services/admin_service/repositories/user_wallet_history_repository.py @@ -242,8 +242,8 @@ class UserWalletHistoryRepository: .all() ) return total, history - - def get_by_id(self, history_id: str) -> Optional[UserWalletHistory]: + + def success_order_list_by_user(self, user_id: str, offset: int, limit: int, order_type: Optional[List[str]] = None, status: Optional[List[int]] = None) -> Tuple[int, List[UserWalletHistory]]: """ Get user wallet history record by ID. @@ -253,7 +253,25 @@ class UserWalletHistoryRepository: Returns: Optional[UserWalletHistory]: UserWalletHistory object or None """ - return self.db.query(UserWalletHistory).filter(UserWalletHistory.id == history_id).first() + + query = self.db.query(UserWalletHistory).filter( + UserWalletHistory.user_id == user_id, + ) + if order_type and len(order_type) > 0: + query = query.filter(UserWalletHistory.type.in_(order_type)) + if status and len(status) > 0: + query = query.filter(UserWalletHistory.status.in_(status)) + total = query.count() + if total < offset: + return total, [] + history = ( + query + .order_by(UserWalletHistory.created_at.desc()) + .offset(offset) + .limit(limit) + .all() + ) + return total, history def add_consume_record(self, wallet_history: UserWalletHistory) -> Optional[UserWalletHistory]: """ diff --git a/services/admin_service/services/mcp_manager_service.py b/services/admin_service/services/mcp_manager_service.py index 67655ff..e40f654 100644 --- a/services/admin_service/services/mcp_manager_service.py +++ b/services/admin_service/services/mcp_manager_service.py @@ -329,6 +329,31 @@ class McpManagerService: """Get service list with pagination""" return self.mcp_service_repository.get_all_paginated(page=page, page_size=page_size) + def get_tags_list(self, enabled_only: bool = False) -> List[str]: + tags_strings = self.mcp_service_repository.get_tags_strings(enabled_only=enabled_only) + tag_counts: dict[str, int] = {} + canonical: dict[str, str] = {} + + for tags_str in tags_strings: + normalized_in_service: set[str] = set() + for tag in parse_tags_to_array(tags_str): + normalized = tag.casefold() + if not normalized: + continue + if normalized in normalized_in_service: + continue + normalized_in_service.add(normalized) + canonical.setdefault(normalized, tag) + + for normalized in normalized_in_service: + tag_counts[normalized] = tag_counts.get(normalized, 0) + 1 + + sorted_normalized = sorted( + tag_counts.keys(), + key=lambda normalized: (-tag_counts[normalized], canonical[normalized].casefold()), + ) + return [canonical[normalized] for normalized in sorted_normalized] + def create_service_from_openapi(self, openapi_data: OpenApiForAI) -> str: # Convert OpenApiForAI info to McpService object and McpToolApi object list, return service ID or exception. try: @@ -488,9 +513,9 @@ class McpManagerService: logger.error(f"Failed to update service from OpenAPI: {str(e)}") raise ValueError(f"Failed to update service from OpenAPI.") - def get_public_services_paginated(self, keyword: str, page: int = 1, page_size: int = 10) -> Tuple[List[dict], int]: + def get_public_services_paginated(self, keyword: str, page: int = 1, page_size: int = 10, tag: Optional[str] = None) -> Tuple[List[dict], int]: """Get public services list with pagination, returns formatted data with API info""" - services, total = self.mcp_service_repository.get_public_services_paginated(keyword, page, page_size) + services, total = self.mcp_service_repository.get_public_services_paginated(keyword, page, page_size, tag) service_list = [] for service in services: diff --git a/services/admin_service/services/user_wallet_history_service.py b/services/admin_service/services/user_wallet_history_service.py index caf9a31..85f2556 100644 --- a/services/admin_service/services/user_wallet_history_service.py +++ b/services/admin_service/services/user_wallet_history_service.py @@ -18,6 +18,9 @@ class UserWalletHistoryService: def success_deposit_order_list(self, offset: int, limit: int) -> Tuple[int, List[UserWalletHistory]]: return self.user_wallet_history_repository.success_deposit_order_list(offset, limit) + def success_order_list_by_user(self, user_id: str, offset: int, limit: int, order_type: Optional[List[str]] = None, status: Optional[List[int]] = None) -> Tuple[int, List[UserWalletHistory]]: + return self.user_wallet_history_repository.success_order_list_by_user(user_id, offset, limit, order_type, status) + def order_list(self, payment_method: str, status: int, start: Optional[datetime] = None, end: Optional[datetime] = None) -> List[UserWalletHistory]: return self.user_wallet_history_repository.order_list(payment_method, status, start, end) diff --git a/services/common/config.py b/services/common/config.py index ff8b7ae..6dc19e6 100644 --- a/services/common/config.py +++ b/services/common/config.py @@ -58,6 +58,7 @@ class Config: "/api/auth/account/sign", "/api/auth/email/send_captcha", "/api/auth/google/sign", + "/api/web/mcp_tags", "/api/web/mcp_services", "/api/web/mcp_service_info", "/api/payment/callback_stripe", From 77ca12045da40e6e420856b80c56ba4a0228c07f Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Mon, 29 Dec 2025 15:43:10 +0800 Subject: [PATCH 02/16] The system settings support setting the tag_bar_display variable. --- scripts/resource/sql/version-1.3.0.sql | 8 ++++++++ services/admin_service/constants/sys_config_key.py | 1 + services/admin_service/controllers/init_config.py | 1 + services/admin_service/controllers/sys_config.py | 6 ++++++ 4 files changed, 16 insertions(+) create mode 100644 scripts/resource/sql/version-1.3.0.sql diff --git a/scripts/resource/sql/version-1.3.0.sql b/scripts/resource/sql/version-1.3.0.sql new file mode 100644 index 0000000..01477b5 --- /dev/null +++ b/scripts/resource/sql/version-1.3.0.sql @@ -0,0 +1,8 @@ +INSERT INTO `sys_config` (`id`,`key`, `value`,`description`,`created_at`,`updated_at`) +VALUES ('xpack-tag-bar-display','tag_bar_display', 'true', 'Display tag bar on the top of the page', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) + ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), `description` = VALUES(`description`), `updated_at` = CURRENT_TIMESTAMP; + + +INSERT INTO `sys_config` (`id`,`key`, `value`,`description`,`created_at`,`updated_at`) +VALUES ('xpack-version','version', '1.3.0', 'The user interface supports viewing the transaction list.', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) + ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), `description` = VALUES(`description`), `updated_at` = CURRENT_TIMESTAMP; diff --git a/services/admin_service/constants/sys_config_key.py b/services/admin_service/constants/sys_config_key.py index 4e0205e..2dd145d 100644 --- a/services/admin_service/constants/sys_config_key.py +++ b/services/admin_service/constants/sys_config_key.py @@ -7,6 +7,7 @@ KEY_SUBHEADLINE = "subheadline" KEY_LANGUAGE = "language" KEY_THEME = "theme" KEY_ABOUT_PAGE = "about_page" +KEY_TAG_BAR_DISPLAY = "tag_bar_display" KEY_ADMIN_USERNAME = "admin_username" KEY_ADMIN_PASSWORD = "admin_password" KEY_LOGIN_GOOGLE_CLIENT = "login_google_client_id" diff --git a/services/admin_service/controllers/init_config.py b/services/admin_service/controllers/init_config.py index e138335..54b276c 100644 --- a/services/admin_service/controllers/init_config.py +++ b/services/admin_service/controllers/init_config.py @@ -67,6 +67,7 @@ def get_config( "facebook_image_url": values.get(KEY_FACEBOOK_IMAGE_URL, ""), "social_account_facebook_url": values.get(KEY_SOCIAL_ACCOUNT_FACEBOOK_URL, ""), "social_account_x_url": values.get(KEY_SOCIAL_ACCOUNT_X_URL, ""), + "tag_bar_display": values.get(KEY_TAG_BAR_DISPLAY, "false").lower() in ("true", "t", "yes", "y", "1"), }, "faq": faq, "embeded_html": embeded_html, diff --git a/services/admin_service/controllers/sys_config.py b/services/admin_service/controllers/sys_config.py index d2ac13d..6c7a1a3 100644 --- a/services/admin_service/controllers/sys_config.py +++ b/services/admin_service/controllers/sys_config.py @@ -144,6 +144,7 @@ def get_sysconfig( "social_account_facebook_url": small_values.get(sys_config_key.KEY_SOCIAL_ACCOUNT_FACEBOOK_URL, ""), "social_account_x_url": small_values.get(sys_config_key.KEY_SOCIAL_ACCOUNT_X_URL, ""), "cname_a_ip": cname_a_ip, + "tag_bar_display": small_values.get(sys_config_key.KEY_TAG_BAR_DISPLAY, "").lower() in ("true", "t", "yes", "y", "1"), }, "account": { "username": admin_username, @@ -219,6 +220,9 @@ def set_sysconfig( facebook_image_url = platform.get("facebook_image_url") social_account_facebook_url = platform.get("social_account_facebook_url") social_account_x_url = platform.get("social_account_x_url") + tag_bar_display = platform.get("tag_bar_display") + + account = body.get("account", {}) admin_username = account.get("username") @@ -270,6 +274,7 @@ def set_sysconfig( (sys_config_key.KEY_FACEBOOK_IMAGE_URL, facebook_image_url, "Facebook image URL"), (sys_config_key.KEY_SOCIAL_ACCOUNT_FACEBOOK_URL, social_account_facebook_url, "Facebook URL"), (sys_config_key.KEY_SOCIAL_ACCOUNT_X_URL, social_account_x_url, "X URL"), + (sys_config_key.KEY_TAG_BAR_DISPLAY, tag_bar_display, "Tag bar display"), (sys_config_key.KEY_LOGIN_GOOGLE_CLIENT, login_google_client, "Google login client ID"), (sys_config_key.KEY_LOGIN_GOOGLE_SECRET, login_google_secret, "Google login client secret"), (sys_config_key.KEY_LOGIN_GOOGLE_ENABLE, login_google_enable, "Google login enabled"), @@ -318,6 +323,7 @@ def set_sysconfig( "facebook_image_url": facebook_image_url, "social_account_facebook_url": social_account_facebook_url, "social_account_x_url": social_account_x_url, + "tag_bar_display": tag_bar_display, } # Use background reporting to avoid blocking the main configuration update From 915a2bcf9e0b76a3578d6a05ace6c4ade131b3f6 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Tue, 30 Dec 2025 15:08:19 +0800 Subject: [PATCH 03/16] The transaction list now includes "balance" and "description" fields. --- services/admin_service/controllers/order.py | 28 +---------- services/admin_service/controllers/user.py | 31 ++---------- .../user_wallet_history_repository.py | 20 ++++++-- .../admin_service/services/payment_service.py | 14 +++++- .../services/user_wallet_history_service.py | 48 ++++++++++++++++++- 5 files changed, 80 insertions(+), 61 deletions(-) diff --git a/services/admin_service/controllers/order.py b/services/admin_service/controllers/order.py index fe900b9..05257e7 100644 --- a/services/admin_service/controllers/order.py +++ b/services/admin_service/controllers/order.py @@ -89,29 +89,5 @@ def get_user_order_list_by_user_id( for s in sl: status_list.append(int(s.strip())) total, orders = user_wallet_history_service.success_order_list_by_user(user_id, offset, page_size, order_type_list, status_list) - if not orders: - return ResponseUtils.success_page(data=[], total=total, page_num=page, page_size=page_size) - result = [] - for order in orders: - confirm_at = "" - if order.status == 1: - confirm_at = order.updated_at - for order in orders: - info = { - "id": order.id, - "user_id": order.user_id, - "order_id": order.transaction_id, - "payment_type": order.payment_method, - "payment_state": order.status, - "amount": order.amount, - "create_at": order.created_at, - "confirm_at": confirm_at, - } - if order.type == TransactionType.API_CALL: - info["order_type"] = "purchase" - elif order.type == TransactionType.DEPOSIT: - info["order_type"] = "recharge" - else: - info["order_type"] = order.type - result.append(info) - return ResponseUtils.success_page(data=result, total=total, page_num=page, page_size=page_size) \ No newline at end of file + + return ResponseUtils.success_page(data=orders, total=total, page_num=page, page_size=page_size) \ No newline at end of file diff --git a/services/admin_service/controllers/user.py b/services/admin_service/controllers/user.py index 73e102b..daa3104 100644 --- a/services/admin_service/controllers/user.py +++ b/services/admin_service/controllers/user.py @@ -11,7 +11,7 @@ from services.admin_service.services.user_task_service import UserTaskService from services.admin_service.services.auth_service import AuthService from services.admin_service.services.resource_group_service import ResourceGroupService from services.admin_service.services.user_wallet_history_service import UserWalletHistoryService -from services.common.models.user_wallet_history import TransactionType + from typing import Optional,List router = APIRouter() @@ -33,6 +33,7 @@ def get_resource_group_service(db: Session = Depends(get_db)) -> ResourceGroupSe def get_order_service(db: Session = Depends(get_db)) -> UserWalletHistoryService: return UserWalletHistoryService(db) + @router.get("/info", response_model=dict) def get_user(request: Request, user_wallet: UserWalletService = Depends(get_user_wallet), user_task: UserTaskService = Depends(get_user_task_service), resource_group_service: ResourceGroupService = Depends(get_resource_group_service)): """Get current user information and wallet balance.""" @@ -125,29 +126,5 @@ def get_order_list( for s in sl: status_list.append(int(s.strip())) total, orders = user_wallet_history_service.success_order_list_by_user(user.id, offset, page_size, order_type_list, status_list) - if not orders: - return ResponseUtils.success_page(data=[], total=total, page_num=page, page_size=page_size) - result = [] - for order in orders: - confirm_at = "" - if order.status == 1: - confirm_at = order.updated_at - for order in orders: - info = { - "id": order.id, - "user_id": order.user_id, - "order_id": order.transaction_id, - "payment_type": order.payment_method, - "payment_state": order.status, - "amount": order.amount, - "create_at": order.created_at, - "confirm_at": confirm_at, - } - if order.type == TransactionType.API_CALL: - info["order_type"] = "purchase" - elif order.type == TransactionType.DEPOSIT: - info["order_type"] = "recharge" - else: - info["order_type"] = order.type - result.append(info) - return ResponseUtils.success_page(data=result, total=total, page_num=page, page_size=page_size) \ No newline at end of file + + return ResponseUtils.success_page(data=orders, total=total, page_num=page, page_size=page_size) \ No newline at end of file diff --git a/services/admin_service/repositories/user_wallet_history_repository.py b/services/admin_service/repositories/user_wallet_history_repository.py index 0da9b47..a161d70 100644 --- a/services/admin_service/repositories/user_wallet_history_repository.py +++ b/services/admin_service/repositories/user_wallet_history_repository.py @@ -18,8 +18,20 @@ class UserWalletHistoryRepository: def __init__(self, db: Session): self.db = db + + def get_by_id(self, transaction_id: str) -> Optional[UserWalletHistory]: + """ + Get a user wallet history record by ID. - def add_deposit(self, user_id: str, amount: float, payment_method: str, transaction_id: str = "", status: int = 0) -> UserWalletHistory: + Args: + transaction_id: Transaction ID + + Returns: + Optional[UserWalletHistory]: Found record or None + """ + return self.db.query(UserWalletHistory).filter(UserWalletHistory.id == transaction_id).first() + + def add_deposit(self, user_id: str, amount: float, payment_method: str, transaction_id: str = "", status: int = 0, balance_after: float = 0.00) -> UserWalletHistory: """ Create a new deposit record. @@ -40,7 +52,7 @@ class UserWalletHistoryRepository: user_id=user_id, payment_method=PaymentMethod(payment_method), amount=amount, - balance_after=0.00, + balance_after=balance_after, type=TransactionType.DEPOSIT, transaction_id=transaction_id, status=status, @@ -81,7 +93,7 @@ class UserWalletHistoryRepository: self.db.refresh(history) return history - def set_balance(self,user_id: str,amount:float, payment_method: str, transaction_id: str = "", status: int = 0) -> UserWalletHistory: + def set_balance(self,user_id: str,amount:float, payment_method: str, transaction_id: str = "", status: int = 0, balance_after: float = 0.00) -> UserWalletHistory: """ Create a new balance record. @@ -102,7 +114,7 @@ class UserWalletHistoryRepository: user_id=user_id, payment_method=PaymentMethod(payment_method), amount=amount, - balance_after=0.00, + balance_after=balance_after, type=TransactionType.RESET, status=status, # 0=new, 1=completed, 2=refunded created_at=now, diff --git a/services/admin_service/services/payment_service.py b/services/admin_service/services/payment_service.py index 566abcb..7026f4a 100644 --- a/services/admin_service/services/payment_service.py +++ b/services/admin_service/services/payment_service.py @@ -403,11 +403,21 @@ class PaymentService: try: if typ == "incr": self.user_wallet_history_repository.add_deposit( - user_id=user_id, amount=amount, payment_method=payment_method, transaction_id=transaction_id,status=1 + user_id=user_id, + amount=amount, + payment_method=payment_method, + transaction_id=transaction_id, + status=1, + balance_after=new_balance, ) elif typ == "set": self.user_wallet_history_repository.set_balance( - user_id=user_id, amount=amount, payment_method=payment_method, transaction_id=transaction_id,status=1 + user_id=user_id, + amount=amount, + payment_method=payment_method, + transaction_id=transaction_id, + status=1, + balance_after=new_balance, ) self._delete_wallet_cache(user_id) logger.info(f"Successfully updated balance for user_id {user_id}: {current_wallet.balance} -> {new_balance}") diff --git a/services/admin_service/services/user_wallet_history_service.py b/services/admin_service/services/user_wallet_history_service.py index 85f2556..87052a0 100644 --- a/services/admin_service/services/user_wallet_history_service.py +++ b/services/admin_service/services/user_wallet_history_service.py @@ -3,11 +3,16 @@ from services.common.models.user_wallet_history import UserWalletHistory from services.admin_service.repositories.user_wallet_history_repository import UserWalletHistoryRepository from typing import Optional, Dict, Any, List, Tuple from datetime import datetime +from services.common.models.user_wallet_history import TransactionType +from services.admin_service.repositories.mcp_service_repository import McpServiceRepository +import json + class UserWalletHistoryService: def __init__(self, db: Session): self.user_wallet_history_repository = UserWalletHistoryRepository(db) + self.mcp_service_repository = McpServiceRepository(db) def add_deposit(self, user_id: str, amount: float, payment_method: str) -> UserWalletHistory: return self.user_wallet_history_repository.add_deposit(user_id, amount, payment_method) @@ -18,8 +23,47 @@ class UserWalletHistoryService: def success_deposit_order_list(self, offset: int, limit: int) -> Tuple[int, List[UserWalletHistory]]: return self.user_wallet_history_repository.success_deposit_order_list(offset, limit) - def success_order_list_by_user(self, user_id: str, offset: int, limit: int, order_type: Optional[List[str]] = None, status: Optional[List[int]] = None) -> Tuple[int, List[UserWalletHistory]]: - return self.user_wallet_history_repository.success_order_list_by_user(user_id, offset, limit, order_type, status) + def success_order_list_by_user(self, user_id: str, offset: int, limit: int, order_type: Optional[List[str]] = None, status: Optional[List[int]] = None) -> Tuple[int, List[dict]]: + total, orders = self.user_wallet_history_repository.success_order_list_by_user(user_id, offset, limit, order_type, status) + if total == 0: + return total, [] + result = [] + for order in orders: + confirm_at = "" + if order.status == 1: + confirm_at = order.updated_at + info = { + "id": order.id, + "user_id": order.user_id, + "order_id": order.transaction_id, + "payment_type": order.payment_method, + "payment_state": order.status, + "amount": order.amount, + "create_at": order.created_at, + "confirm_at": confirm_at, + } + if order.type == TransactionType.API_CALL: + info["order_type"] = "purchase" + try: + callback_data = json.loads(order.callback_data) + service = self.mcp_service_repository.get_by_id(callback_data["service_id"]) + if service: + info["description"] = service.name + except: + info["description"] = "-" + info["balance_after"] = order.balance_after + elif order.type == TransactionType.DEPOSIT: + info["order_type"] = "recharge" + if order.status == 1: + info["balance_after"] = order.balance_after + else: + info["balance_after"] = "-" + info["description"] = order.payment_method + else: + info["order_type"] = order.type + result.append(info) + return total, result + return total, orders def order_list(self, payment_method: str, status: int, start: Optional[datetime] = None, end: Optional[datetime] = None) -> List[UserWalletHistory]: return self.user_wallet_history_repository.order_list(payment_method, status, start, end) From d6dea1f1e80fa53a19e2d14ba9a671c2a0783bca Mon Sep 17 00:00:00 2001 From: lcx <1793599591@qq.com> Date: Tue, 30 Dec 2025 18:28:25 +0800 Subject: [PATCH 04/16] feat: add MCP service tag filtering, transaction record viewing, and various optimizations --- .../public/locales/zh-CN/translation.json | 14 +- .../console/SystemSettingsModal.tsx | 8 + .../console/SystemSettingsRightContent.tsx | 8 + .../src/components/console/console.type.ts | 1 + .../dashboard/AccountBalanceTable.tsx | 368 ++++++++++++++++++ .../dashboard/DashboardOverview.tsx | 4 + frontend/src/components/dashboard/Main.tsx | 17 +- .../dashboard/UserAccountBalance.tsx | 23 ++ frontend/src/components/marketplace/Main.tsx | 45 ++- .../system-setting/TagsBarSetting.tsx | 51 +++ .../src/components/theme/ThemeSelector.tsx | 53 ++- .../src/components/theme/classic/Home.tsx | 39 +- .../components/theme/classic/Navigation.tsx | 34 +- .../src/components/theme/creative/Home.tsx | 39 +- .../components/theme/creative/Navigation.tsx | 28 +- frontend/src/components/theme/modern/Home.tsx | 39 +- .../components/theme/modern/Navigation.tsx | 26 +- frontend/src/components/theme/temu/Home.tsx | 37 +- .../src/components/theme/temu/Navigation.tsx | 28 +- .../user-management/UserBalanceDetail.tsx | 48 +++ .../user-management/UserManagement.tsx | 31 ++ .../components/user-management/UserTable.tsx | 14 +- frontend/src/services/marketplaceService.ts | 27 +- frontend/src/shared/components/Navigation.tsx | 30 +- .../components/marketplace/HeroSection.tsx | 4 +- .../components/marketplace/ServerConfig.tsx | 127 +++++- .../components/marketplace/TagFilter.tsx | 309 +++++++++++++++ frontend/src/shared/types/dashboard.ts | 1 + frontend/src/shared/types/system.ts | 1 + 29 files changed, 1367 insertions(+), 87 deletions(-) create mode 100644 frontend/src/components/dashboard/AccountBalanceTable.tsx create mode 100644 frontend/src/components/dashboard/UserAccountBalance.tsx create mode 100644 frontend/src/components/system-setting/TagsBarSetting.tsx create mode 100644 frontend/src/components/user-management/UserBalanceDetail.tsx create mode 100644 frontend/src/shared/components/marketplace/TagFilter.tsx diff --git a/frontend/public/locales/zh-CN/translation.json b/frontend/public/locales/zh-CN/translation.json index e61aab6..b15b361 100644 --- a/frontend/public/locales/zh-CN/translation.json +++ b/frontend/public/locales/zh-CN/translation.json @@ -937,5 +937,17 @@ "Failed to load resource group detail": "获取资源组详情失败", "Resource Group Detail": "资源组详情", "Current display time is UTC time": "当前显示时间为UTC时间", - "View Resource Group Detail": "查看资源组详情" + "View Resource Group Detail": "查看资源组详情", + "Configure tags bar display": "配置标签栏显示", + "Failed to load orders": "加载订单失败", + "Transaction Time": "交易时间", + "All": "全部", + "Purchase": "消费", + "No orders found": "无订单", + "Account Balance": "账户余额", + "View your balance and transaction history": "查看您的余额和交易历史", + "Display tags bar": "显示标签栏", + "Front end displays tags bar and allows users to filter products based on tags.": "前端显示标签栏,允许用户根据标签过滤产品。", + "Tags Bar": "标签栏", + "Auth Key Name": "认证密钥名称" } diff --git a/frontend/src/components/console/SystemSettingsModal.tsx b/frontend/src/components/console/SystemSettingsModal.tsx index 5d4dd30..6d25629 100644 --- a/frontend/src/components/console/SystemSettingsModal.tsx +++ b/frontend/src/components/console/SystemSettingsModal.tsx @@ -34,6 +34,7 @@ import { Palette, SquareMenu, TableOfContents, + Tags, Trello, XIcon, } from "lucide-react"; @@ -161,6 +162,12 @@ const SystemSettingsModal: React.FC = ({ icon: , description: "Configure site navigation and menus", }, + { + key: SettingModalTab.TAGS_BAR, + label: "Tags Bar", + icon: , + description: "Configure tags bar display", + }, { key: SettingModalTab.FAQ, label: "FAQ", @@ -240,6 +247,7 @@ const SystemSettingsModal: React.FC = ({ items: groupItems([ SettingModalTab.THEME, SettingModalTab.NAVIGATION, + SettingModalTab.TAGS_BAR, SettingModalTab.FAQ, ]), }, diff --git a/frontend/src/components/console/SystemSettingsRightContent.tsx b/frontend/src/components/console/SystemSettingsRightContent.tsx index bc7fa4d..948dc08 100644 --- a/frontend/src/components/console/SystemSettingsRightContent.tsx +++ b/frontend/src/components/console/SystemSettingsRightContent.tsx @@ -31,6 +31,7 @@ import { AdminConfig, EmailConfig } from "@/types/system"; import { LoginSettingsContent } from "./LoginSettingsContent"; import { EmailConfigForm } from "@/components/system-setting/EmailConfigForm"; import { LanguageSetting } from "@/components/system-setting/LanguageSetting"; +import { TagsBarSetting } from "../system-setting/TagsBarSetting"; interface SystemSettingsRightContentProps { filteredKeys: string[]; @@ -201,6 +202,13 @@ const SystemSettingsRightContent: React.FC = ({ /> )} + {section.key === "tagsBar" && ( + + )} + {section.key === "faq" && ( = ({ userId }) => { + const { t } = useTranslation(); + + const [items, setItems] = useState([]); + const [loading, setLoading] = useState(false); + const [pagination, setPagination] = useState({ + page: 1, + pageSize: 10, + total: 0, + }); + const [selectedType, setSelectedType] = useState("all"); + const [selectedStatus, setSelectedStatus] = useState("all"); + const resourceGroupsParams = useRef({ + page: 1, + pageSize: 10, + keyword: "", + orderType: "", + status: "", + }); + + const pages = Math.ceil(pagination.total / pagination.pageSize); + const currentPage = Number(pagination.page); + + const fetchOrders = useCallback( + async ( + page: number, + page_size: number, + order_type?: string, + status?: string + ): Promise<{ data: OrderItem[]; total: number; page: number; page_size: number }> => { + try { + const params = new URLSearchParams({ + page: page.toString(), + page_size: page_size.toString(), + }); + if (order_type) params.append("order_type", order_type); + if (status) params.append("status", status); + if (userId) params.append("user_id", userId); + + // 根据是否有 userId 来决定使用哪个 API + const apiUrl = userId + ? `/api/order/list/by_user?${params.toString()}` + : `/api/user/order/list?${params.toString()}`; + + const response = await fetchAPI(apiUrl); + if (!response.success) { + toast.error(response.error_message || i18n.t("Failed to load orders")); + 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 orders:", error); + return { + data: [], + total: 0, + page, + page_size, + }; + } + }, + [userId] + ); + + const loadOrders = useCallback( + async ( + page: number = 1, + pageSize: number = 10, + keyword: string = "", + orderType: string = "", + status: string = "" + ) => { + setLoading(true); + try { + const response = await fetchOrders( + page, + pageSize, + orderType || undefined, + status || undefined + ); + setItems(response.data); + setPagination({ + page: response.page, + pageSize: response.page_size, + total: response.total, + }); + resourceGroupsParams.current = { + page: response.page, + pageSize: response.page_size, + keyword, + orderType, + status, + }; + } catch (error) { + console.error(t("Failed to load orders"), error); + } finally { + setLoading(false); + } + }, + [fetchOrders] + ); + + const formatDate = (dateString: string) => { + return ( +
+ + + {new Date(dateString).toLocaleString()} + +
+ ); + }; + + const getStatusColor = (status: number) => { + switch (status) { + case 1: + return "success"; + case 2: + return "danger"; + default: + return "warning"; + } + }; + + const onPageChange = (page: number) => { + const { pageSize, orderType, status } = resourceGroupsParams.current; + loadOrders(page, pageSize, "", orderType, status); + }; + + const handleTypeChange = (value: string) => { + setSelectedType(value); + const orderType = value === "all" ? "" : value; + const { status } = resourceGroupsParams.current; + loadOrders(1, pagination.pageSize, "", orderType, status); + }; + + const handleStatusChange = (value: string) => { + setSelectedStatus(value); + const status = value === "all" ? "" : value; + const { orderType } = resourceGroupsParams.current; + loadOrders(1, pagination.pageSize, "", orderType, status); + }; + + useEffect(() => { + loadOrders(1, 10, ""); + }, [loadOrders]); + + return ( +
+ + + +
+ {t("Transaction Time")} +
+
+ +
+ {t("Type")} + + + + + { + const selected = Array.from(keys)[0] as string; + handleTypeChange(selected); + }} + > + {t("All")} + {t("Recharge")} + {t("Purchase")} + + +
+
+ {t("Description")} + {t("Amount")} + {t("Balance")} + +
+ {t("Status")} + + + + + { + const selected = Array.from(keys)[0] as string; + handleStatusChange(selected); + }} + > + {t("All")} + {t("Pending")} + {t("Completed")} + {t("Failed")} + + +
+
+
+ } + emptyContent={t("No orders found")} + > + {(order) => ( + + {formatDate(order.confirm_at)} + + + { + order.order_type === "recharge" ? t("Recharge") : t("Purchase") + } + + + {order.description} + + + + {order.order_type === "recharge" ? "+" : ""} + + {order.amount} + + + {order.balance} + + + {t( + order.payment_state === 1 + ? "Completed" + : order.payment_state === 2 + ? "Failed" + : "Pending" + )} + + + + )} + +
+ + {pages > 1 && ( +
+ +
+ )} +
+ ); +}; + +export default AccountBalanceTable; diff --git a/frontend/src/components/dashboard/DashboardOverview.tsx b/frontend/src/components/dashboard/DashboardOverview.tsx index c1dd643..7050823 100644 --- a/frontend/src/components/dashboard/DashboardOverview.tsx +++ b/frontend/src/components/dashboard/DashboardOverview.tsx @@ -53,6 +53,10 @@ const OverviewPage: React.FC = () => { useEffect(() => { fetchApiKeys(); + if (sessionStorage.getItem('create_new_authorization')) { + handleNewKey(); + sessionStorage.removeItem('create_new_authorization'); + } }, []); // create new auth key diff --git a/frontend/src/components/dashboard/Main.tsx b/frontend/src/components/dashboard/Main.tsx index 0704888..fb1cfb9 100644 --- a/frontend/src/components/dashboard/Main.tsx +++ b/frontend/src/components/dashboard/Main.tsx @@ -11,8 +11,9 @@ import { formatCurrency } from "@/shared/utils/currency"; // Import dashboard content components import DashboardOverview from "@/components/dashboard/DashboardOverview"; import WalletManagement from "@/components/wallet/WalletManagement"; +import UserAccountBalance from "@/components/dashboard/UserAccountBalance"; import { Home, Key, Wallet } from "lucide-react"; -import { Avatar, Card, CardBody, Button, Divider } from "@nextui-org/react"; +import { Avatar, Card, CardBody, Button, Divider, Link } from "@nextui-org/react"; import { RechargeModal } from "@/shared/components/modal/RechargeModal"; import { useTranslation } from "@/shared/lib/useTranslation"; import { ChangePasswordModal } from "@/components/common/ChangePasswordModal"; @@ -41,7 +42,7 @@ const DashboardContent: React.FC = () => { const [isRechargeModalOpen, setIsRechargeModalOpen] = useState(false); const getInitialTab = (): TabKey => { const tabFromUrl = searchParams.get("tab") as TabKey; - if (tabFromUrl && [TabKey.OVERVIEW, TabKey.WALLET].includes(tabFromUrl)) { + if (tabFromUrl && [TabKey.OVERVIEW, TabKey.WALLET, TabKey.USER_ACCOUNT].includes(tabFromUrl)) { return tabFromUrl; } return TabKey.OVERVIEW; @@ -158,8 +159,15 @@ const DashboardContent: React.FC = () => { {t("Balance: {{amount}}", { - amount: formatCurrency(user?.wallet?.balance || 0), - })} + amount: "", + }).replace("{{amount}}", "")} + handleTabNavigate(TabKey.USER_ACCOUNT)} + > + {formatCurrency(user?.wallet?.balance || 0)} + @@ -187,6 +195,7 @@ const DashboardContent: React.FC = () => { {activeTab === TabKey.WALLET && ( setIsRechargeModalOpen(true)} /> )} + {activeTab === TabKey.USER_ACCOUNT && } diff --git a/frontend/src/components/dashboard/UserAccountBalance.tsx b/frontend/src/components/dashboard/UserAccountBalance.tsx new file mode 100644 index 0000000..a4240aa --- /dev/null +++ b/frontend/src/components/dashboard/UserAccountBalance.tsx @@ -0,0 +1,23 @@ +"use client"; + +import React from "react"; +import { useTranslation } from "@/shared/lib/useTranslation"; +import DashboardDemoContent from "@/shared/components/DashboardDemoContent"; +import AccountBalanceTable from "./AccountBalanceTable"; + +const UserAccountBalance: React.FC = () => { + const { t } = useTranslation(); + + return ( + +
+ +
+
+ ); +}; + +export default UserAccountBalance; diff --git a/frontend/src/components/marketplace/Main.tsx b/frontend/src/components/marketplace/Main.tsx index 449c853..4ecad29 100644 --- a/frontend/src/components/marketplace/Main.tsx +++ b/frontend/src/components/marketplace/Main.tsx @@ -4,12 +4,19 @@ import React, { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import { HeroSection } from "../../shared/components/marketplace/HeroSection"; import { ServiceListSection } from "@/shared/components/marketplace/ServiceListSection"; +import { TagFilter } from "@/shared/components/marketplace/TagFilter"; import { ServiceData } from "@/shared/types/marketplace"; import { fetchServices } from "@/services/marketplaceService"; import { Spinner } from "@nextui-org/react"; +import { ThemeType } from "@/shared/types/system"; interface MarketplaceMainProps { initialServices: ServiceData[]; + availableTags: string[]; + isTagBarDisplay: boolean; + selectedTag: string; + setSelectedTag: (tag: string) => void; + currentTheme: ThemeType; initialTotal: number; initialPage: number; initialSearch: string; @@ -19,6 +26,11 @@ interface MarketplaceMainProps { export const MarketplaceMain: React.FC = ({ initialServices, + availableTags, + isTagBarDisplay, + selectedTag, + setSelectedTag, + currentTheme, initialTotal, initialPage, initialSearch, @@ -33,16 +45,18 @@ export const MarketplaceMain: React.FC = ({ const [total, setTotal] = useState(initialTotal); const [loading, setLoading] = useState(false); + // load services data - const loadServices = async (page: number, search: string) => { + const loadServices = async (page: number, search: string, tag: string = "ALL") => { try { setLoading(true); const result = await fetchServices({ page, page_size: pageSize, keyword: search, + // 如果需要,可以在这里添加tag参数传递给API + tag: tag !== "ALL" ? tag : undefined, }); - setServices(result.data.services); setTotal(result.page.total); setCurrentPage(page); @@ -79,13 +93,20 @@ export const MarketplaceMain: React.FC = ({ // when page number changes, reload const handlePageChange = (page: number) => { updateURL(page, searchQuery); - loadServices(page, searchQuery); + loadServices(page, searchQuery, selectedTag); }; // handle search submit const handleSearch = () => { updateURL(1, searchQuery); - loadServices(1, searchQuery); + loadServices(1, searchQuery, selectedTag); + }; + + // handle tag change + const handleTagChange = (tag: string) => { + setSelectedTag(tag); + setCurrentPage(1); + loadServices(1, searchQuery, tag); }; // if there is an error, show error message @@ -102,9 +123,25 @@ export const MarketplaceMain: React.FC = ({ {/* Hero Section */} + + {/* filter section */} + { + isTagBarDisplay && ( + <> + + + ) + } {/* Server List Section */} {loading ? ( diff --git a/frontend/src/components/system-setting/TagsBarSetting.tsx b/frontend/src/components/system-setting/TagsBarSetting.tsx new file mode 100644 index 0000000..8d478fe --- /dev/null +++ b/frontend/src/components/system-setting/TagsBarSetting.tsx @@ -0,0 +1,51 @@ +"use client"; + +import React from "react"; +import { Switch } from "@nextui-org/react"; +import { useTranslation } from "@/shared/lib/useTranslation"; + +export type TagsBarSettingConfig = { + tag_bar_display: boolean; +}; + +interface TagsBarSettingProps { + isEnabled: boolean; + onSave: (config: TagsBarSettingConfig) => void; +} + +export const TagsBarSetting: React.FC = ({ + isEnabled, + onSave, +}) => { + const { t } = useTranslation(); + + return ( +
+
+ {/* showcase in xpack */} +
+
+ + {t("Display tags bar")} + + + {t( + "Front end displays tags bar and allows users to filter products based on tags." + )} + +
+ { + onSave({ + tag_bar_display: value + }); + }} + color="primary" + size="sm" + /> +
+
+
+ ); +}; diff --git a/frontend/src/components/theme/ThemeSelector.tsx b/frontend/src/components/theme/ThemeSelector.tsx index c6ccb45..d6ad09c 100644 --- a/frontend/src/components/theme/ThemeSelector.tsx +++ b/frontend/src/components/theme/ThemeSelector.tsx @@ -9,7 +9,7 @@ import { Home as ClassicHome } from "./classic/Home"; import { Home as CreativeHome } from "./creative/Home"; import { Home as TemuHome } from "./temu/Home"; import { ServiceData } from "@/shared/types/marketplace"; -import { fetchServices } from "@/services/marketplaceService"; +import { fetchServices, fetchTagsList } from "@/services/marketplaceService"; import { Navigation } from "@/shared/components/Navigation"; import { MarketplaceMain } from "../marketplace/Main"; import { Footer } from "@/shared/components/Footer"; @@ -53,18 +53,36 @@ export const ThemeSelector: React.FC = ({ const [currentPage, setCurrentPage] = useState(initialPage); const [total, setTotal] = useState(initialTotal); const [loading, setLoading] = useState(false); - + const isTagBarDisplay = platformConfig.tag_bar_display || false; + // 可用的标签列表(这里可以从API获取或配置) + const [availableTags, setAvailableTags] = useState([]); + const [selectedTag, setSelectedTag] = useState("ALL"); // search suggestion const searchSuggestions = ["Search MCP servers"]; + useEffect(() => { + const loadTagsList = async () => { + const tags = await fetchTagsList(); + setAvailableTags(tags); + }; + loadTagsList(); + }, []); + + // handle tag change + const handleTagChange = (tag: string) => { + setSelectedTag(tag); + setCurrentPage(1); + loadServices(1, searchQuery, tag); + }; // loading service data - const loadServices = async (page: number, search: string) => { + const loadServices = async (page: number, search: string, tag: string = "ALL") => { try { setLoading(true); const result = await fetchServices({ page, page_size: pageSize, keyword: search, + tag: tag !== "ALL" ? tag : undefined, }); setServices(result.data.services); @@ -103,13 +121,13 @@ export const ThemeSelector: React.FC = ({ // page change handler const handlePageChange = (page: number) => { updateURL(page, searchQuery); - loadServices(page, searchQuery); + loadServices(page, searchQuery, selectedTag); }; // search submit handler const handleSearch = () => { updateURL(1, searchQuery); - loadServices(1, searchQuery); + loadServices(1, searchQuery, selectedTag); }; // search input change handler @@ -122,6 +140,11 @@ export const ThemeSelector: React.FC = ({ case Theme.MODERN: return ( = ({ case Theme.CLASSIC: return ( = ({ case Theme.CREATIVE: return ( = ({ case Theme.TEMU: return ( = ({
void; + currentTheme: ThemeType; currentPage: number; total: number; pageSize: number; @@ -50,6 +57,11 @@ interface HomeProps { export const Home: React.FC = ({ searchQuery, services, + isTagBarDisplay, + availableTags, + selectedTag, + handleTagChange, + currentTheme, currentPage, total, pageSize, @@ -83,9 +95,9 @@ export const Home: React.FC = ({

{t( platformConfig.headline || - platformConfig.name || - _DefaultPlatformConfig.headline || - "" + platformConfig.name || + _DefaultPlatformConfig.headline || + "" )}

@@ -93,8 +105,8 @@ export const Home: React.FC = ({

{t( platformConfig.subheadline || - _DefaultPlatformConfig.subheadline || - "" + _DefaultPlatformConfig.subheadline || + "" )}

@@ -140,6 +152,21 @@ export const Home: React.FC = ({ + {/* filter section */} + { + isTagBarDisplay && ( +
+ +
+ ) + } + {/* Server List Section */} {loading ? (
@@ -148,7 +175,7 @@ export const Home: React.FC = ({
) : ( -
+
{/* Server Grid */}
diff --git a/frontend/src/components/theme/classic/Navigation.tsx b/frontend/src/components/theme/classic/Navigation.tsx index e13fcc3..bd1ade4 100644 --- a/frontend/src/components/theme/classic/Navigation.tsx +++ b/frontend/src/components/theme/classic/Navigation.tsx @@ -1,6 +1,6 @@ "use client"; -import React from "react"; +import React, { useState, useEffect } from "react"; import { Button } from "@nextui-org/react"; import { useTranslation } from "react-i18next"; @@ -8,6 +8,7 @@ import { DynamicLogo } from "@/shared/components/DynamicLogo"; import { useAuth } from "@/shared/lib/useAuth"; import { NavigationItem } from "@/shared/components/Navigation"; import Link from "next/link"; +import { useSharedStore } from "@/shared/store/share"; interface NavigationProps { items?: NavigationItem[]; @@ -17,6 +18,13 @@ export const Navigation: React.FC = ({ items }) => { const { t } = useTranslation(); const { handleLogin } = useAuth(); + const [userToken, setUserToken] = useState(null); + + useEffect(() => { + const userToken = useSharedStore?.getState?.().user_token + setUserToken(userToken); + }, []); + return (
{/* Classic Header */} @@ -26,21 +34,27 @@ export const Navigation: React.FC = ({ items }) => {
- + { + !userToken && ( + <> + + + ) + }
diff --git a/frontend/src/components/theme/creative/Home.tsx b/frontend/src/components/theme/creative/Home.tsx index ba23651..ae6f164 100644 --- a/frontend/src/components/theme/creative/Home.tsx +++ b/frontend/src/components/theme/creative/Home.tsx @@ -24,11 +24,18 @@ import { Footer } from "./Footer"; import { Navigation } from "./Navigation"; import { NavigationItem } from "@/shared/components/Navigation"; import { Faq } from "@/components/marketplace/Faq"; +import { TagFilter } from "@/shared/components/marketplace/TagFilter"; +import { ThemeType } from "@/shared/types/system"; interface HomeProps { // 状态 searchQuery: string; services: ServiceData[]; + isTagBarDisplay: boolean; + availableTags: string[]; + selectedTag: string; + handleTagChange: (tag: string) => void; + currentTheme: ThemeType; currentPage: number; total: number; pageSize: number; @@ -50,6 +57,11 @@ interface HomeProps { export const Home: React.FC = ({ searchQuery, services, + isTagBarDisplay, + availableTags, + selectedTag, + handleTagChange, + currentTheme, currentPage, total, pageSize, @@ -102,9 +114,9 @@ export const Home: React.FC = ({ {t( platformConfig.headline || - platformConfig.name || - _DefaultPlatformConfig.headline || - "" + platformConfig.name || + _DefaultPlatformConfig.headline || + "" )} @@ -113,8 +125,8 @@ export const Home: React.FC = ({

{t( platformConfig.subheadline || - _DefaultPlatformConfig.subheadline || - "" + _DefaultPlatformConfig.subheadline || + "" )}

@@ -166,6 +178,21 @@ export const Home: React.FC = ({
+ {/* filter section */} + { + isTagBarDisplay && ( + <> + + + ) + } + {/* Creative Server List Section */} {loading ? (
@@ -177,7 +204,7 @@ export const Home: React.FC = ({
) : (
-
+
{/* Creative Server Grid */}
{services.map((service, index) => { diff --git a/frontend/src/components/theme/creative/Navigation.tsx b/frontend/src/components/theme/creative/Navigation.tsx index a94709f..b030ddc 100644 --- a/frontend/src/components/theme/creative/Navigation.tsx +++ b/frontend/src/components/theme/creative/Navigation.tsx @@ -1,6 +1,6 @@ "use client"; -import React from "react"; +import React, { useEffect } from "react"; import { Button } from "@nextui-org/react"; import { useTranslation } from "react-i18next"; import Link from "next/link"; @@ -16,6 +16,7 @@ import { ArrowRightIcon } from "lucide-react"; import { DynamicLogo } from "@/shared/components/DynamicLogo"; import { useAuth } from "@/shared/lib/useAuth"; import { NavigationItem } from "@/shared/components/Navigation"; +import { useSharedStore } from "@/shared/store/share"; interface NavigationProps { items?: NavigationItem[]; @@ -26,6 +27,13 @@ export const Navigation: React.FC = ({ items }) => { const { handleLogin } = useAuth(); const [isMenuOpen, setIsMenuOpen] = useState(false); + const [userToken, setUserToken] = useState(null); + + useEffect(() => { + const userToken = useSharedStore?.getState?.().user_token + setUserToken(userToken); + }, []); + return ( <> {/* Creative Navigation */} @@ -65,16 +73,22 @@ export const Navigation: React.FC = ({ items }) => {
- + { + !userToken && ( + <> + + + ) + }
@@ -101,7 +115,7 @@ export const Navigation: React.FC = ({ items }) => { radius="full" onPress={handleLogin} > - {t("Get Started")} + {userToken ? t("Dashboard") : t("Get Started")}
void; + currentTheme: ThemeType; currentPage: number; total: number; pageSize: number; @@ -52,6 +59,11 @@ interface HomeProps { export const Home: React.FC = ({ searchQuery, services, + isTagBarDisplay, + availableTags, + selectedTag, + handleTagChange, + currentTheme, currentPage, total, pageSize, @@ -78,7 +90,7 @@ export const Home: React.FC = ({ {/* Modern Hero Section */}
-
+
{/* Modern Icon */}
@@ -91,9 +103,9 @@ export const Home: React.FC = ({

{t( platformConfig.headline || - platformConfig.name || - _DefaultPlatformConfig.headline || - "" + platformConfig.name || + _DefaultPlatformConfig.headline || + "" )}

@@ -101,8 +113,8 @@ export const Home: React.FC = ({

{t( platformConfig.subheadline || - _DefaultPlatformConfig.subheadline || - "" + _DefaultPlatformConfig.subheadline || + "" )}

@@ -145,6 +157,21 @@ export const Home: React.FC = ({
+ {/* filter section */} + { + isTagBarDisplay && ( + <> + + + ) + } +
{/* Server List Section */} {loading ? ( diff --git a/frontend/src/components/theme/modern/Navigation.tsx b/frontend/src/components/theme/modern/Navigation.tsx index 31ce596..6201db1 100644 --- a/frontend/src/components/theme/modern/Navigation.tsx +++ b/frontend/src/components/theme/modern/Navigation.tsx @@ -1,6 +1,6 @@ "use client"; -import React from "react"; +import React, { useEffect } from "react"; import { Button } from "@nextui-org/react"; import { useTranslation } from "react-i18next"; import Link from "next/link"; @@ -16,6 +16,7 @@ import { ArrowRightIcon } from "lucide-react"; import { DynamicLogo } from "@/shared/components/DynamicLogo"; import { useAuth } from "@/shared/lib/useAuth"; import { NavigationItem } from "@/shared/components/Navigation"; +import { useSharedStore } from "@/shared/store/share"; interface NavigationProps { items?: NavigationItem[]; @@ -25,7 +26,12 @@ export const Navigation: React.FC = ({ items }) => { const { t } = useTranslation(); const { handleLogin } = useAuth(); const [isMenuOpen, setIsMenuOpen] = useState(false); + const [userToken, setUserToken] = useState(null); + useEffect(() => { + const userToken = useSharedStore?.getState?.().user_token + setUserToken(userToken); + }, []); return ( <> {/* Modern Navigation */} @@ -61,16 +67,22 @@ export const Navigation: React.FC = ({ items }) => {
- + { + !userToken && ( + <> + + + ) + }
@@ -97,7 +109,7 @@ export const Navigation: React.FC = ({ items }) => { radius="full" onPress={handleLogin} > - {t("Get Started")} + {userToken ? t("Dashboard") : t("Get Started")}
void; + currentTheme: ThemeType; currentPage: number; total: number; pageSize: number; @@ -49,6 +56,11 @@ interface HomeProps { export const Home: React.FC = ({ searchQuery, services, + isTagBarDisplay, + availableTags, + selectedTag, + handleTagChange, + currentTheme, currentPage, total, pageSize, @@ -95,9 +107,9 @@ export const Home: React.FC = ({

{t( platformConfig.headline || - platformConfig.name || - _DefaultPlatformConfig.headline || - "" + platformConfig.name || + _DefaultPlatformConfig.headline || + "" )}

@@ -105,8 +117,8 @@ export const Home: React.FC = ({

{t( platformConfig.subheadline || - _DefaultPlatformConfig.subheadline || - "" + _DefaultPlatformConfig.subheadline || + "" )}

@@ -139,6 +151,21 @@ export const Home: React.FC = ({
+ {/* filter section */} + { + isTagBarDisplay && ( +
+ +
+ ) + } + {/* Products Section */}
{/* Section Header */} diff --git a/frontend/src/components/theme/temu/Navigation.tsx b/frontend/src/components/theme/temu/Navigation.tsx index 7833eed..16e6686 100644 --- a/frontend/src/components/theme/temu/Navigation.tsx +++ b/frontend/src/components/theme/temu/Navigation.tsx @@ -1,6 +1,6 @@ "use client"; -import React from "react"; +import React, { useEffect } from "react"; import { Button } from "@nextui-org/react"; import { useTranslation } from "react-i18next"; import Link from "next/link"; @@ -16,6 +16,7 @@ import { DynamicLogo } from "@/shared/components/DynamicLogo"; import { useAuth } from "@/shared/lib/useAuth"; import { NavigationItem } from "@/shared/components/Navigation"; import { ArrowRightIcon } from "lucide-react"; +import { useSharedStore } from "@/shared/store/share"; interface NavigationProps { items?: NavigationItem[]; @@ -26,6 +27,13 @@ export const Navigation: React.FC = ({ items }) => { const { handleLogin } = useAuth(); const [isMenuOpen, setIsMenuOpen] = useState(false); + const [userToken, setUserToken] = useState(null); + + useEffect(() => { + const userToken = useSharedStore?.getState?.().user_token + setUserToken(userToken); + }, []); + return ( <> {/* Temu Style Navigation */} @@ -64,15 +72,21 @@ export const Navigation: React.FC = ({ items }) => {
- + { + !userToken && ( + <> + + + ) + }
@@ -81,7 +95,7 @@ export const Navigation: React.FC = ({ items }) => { onPress={handleLogin} size="sm" > - {t("Sign In")} + {userToken ? t("Dashboard") : t("Sign In")}
@@ -100,7 +114,7 @@ export const Navigation: React.FC = ({ items }) => { radius="md" onPress={handleLogin} > - {t("Sign In")} + {userToken ? t("Dashboard") : t("Sign In")} diff --git a/frontend/src/components/user-management/UserBalanceDetail.tsx b/frontend/src/components/user-management/UserBalanceDetail.tsx new file mode 100644 index 0000000..17df963 --- /dev/null +++ b/frontend/src/components/user-management/UserBalanceDetail.tsx @@ -0,0 +1,48 @@ +"use client"; + +import React from "react"; +import { Button} from "@nextui-org/react"; +import { ChevronLeftIcon } from "lucide-react"; +import { useTranslation } from "@/shared/lib/useTranslation"; +import { withComponentInjection } from "@/shared/hooks/useComponentInjection"; +import AccountBalanceTable from "../dashboard/AccountBalanceTable"; + +interface UserBalanceDetailProps { + userId: string; + userEmail: string; + onCancel: () => void; +} + +const BaseUserBalanceDetail: React.FC = ({ + userId, + userEmail, + onCancel, +}) => { + const { t } = useTranslation(); + + return ( +
+ {/* page title */} +
+
+ +

+ {t("Account Balance")} +

+
+
+ {t("Email")}: {userEmail || '-'} +
+
+
+ +
+
+ ); +}; +export const UserBalanceDetail = withComponentInjection( + "components/user-management/UserBalanceDetail", + BaseUserBalanceDetail +); diff --git a/frontend/src/components/user-management/UserManagement.tsx b/frontend/src/components/user-management/UserManagement.tsx index 40359b1..c2f4c23 100644 --- a/frontend/src/components/user-management/UserManagement.tsx +++ b/frontend/src/components/user-management/UserManagement.tsx @@ -7,6 +7,9 @@ import { UserTable } from "./UserTable"; import { DeleteConfirmModal } from "@/shared/components/modal/DeleteConfirmModal"; import DashboardDemoContent from "@/shared/components/DashboardDemoContent"; import { useUserManagement } from "@/hooks/useUserManagement"; +import { UserBalanceDetail } from "./UserBalanceDetail"; + +type ViewMode = "list" | "detail"; const UserManagement: React.FC = () => { const { t } = useTranslation(); @@ -28,6 +31,11 @@ const UserManagement: React.FC = () => { user: null as User | null, }); + const [viewMode, setViewMode] = useState('list'); + const [selectedUserId, setSelectedUserId] = useState(null); + const [selectedUserEmail, setSelectedUserEmail] = useState(null); + + const handleDeleteUserClick = useCallback((user: User) => { setDeleteModal({ isOpen: true, @@ -35,6 +43,18 @@ const UserManagement: React.FC = () => { }); }, []); + const handleViewUserBalanceDetail = useCallback((user: User) => { + setSelectedUserId(user.id); + setSelectedUserEmail(user.email); + setViewMode('detail'); + }, []); + + const handleCloseUserBalanceDetail = useCallback(() => { + setSelectedUserId(null); + setSelectedUserEmail(null); + setViewMode('list'); + }, []); + const handleConfirmDelete = useCallback(async () => { if (deleteModal.user) { try { @@ -61,6 +81,16 @@ const UserManagement: React.FC = () => { [handleRechargeUser] ); + if (viewMode === "detail" ) { + return ( + + ); + } + return ( { fetchUsers={fetchUsers} loading={loading} onDelete={handleDeleteUserClick} + viewUserBalanceDetail={handleViewUserBalanceDetail} onRecharge={handleRecharge} pagination={pagination} onPageChange={setPage} diff --git a/frontend/src/components/user-management/UserTable.tsx b/frontend/src/components/user-management/UserTable.tsx index b512f1d..900f7af 100644 --- a/frontend/src/components/user-management/UserTable.tsx +++ b/frontend/src/components/user-management/UserTable.tsx @@ -14,10 +14,12 @@ import { Spinner, Select, SelectItem, + Link } from "@nextui-org/react"; import { useTranslation } from "@/shared/lib/useTranslation"; import { User } from "@/types/user"; import { Trash2, CreditCard, Calendar, HelpCircle } from "lucide-react"; + import { AdminRechargeModal } from "@/components/user-management/AdminRechargeModal"; import { fetchSimpleResourceGroups, updateUserResourceGroup } from "@/api/resourceGroup.api"; import toast from "react-hot-toast"; @@ -27,6 +29,7 @@ interface UserTableProps { fetchUsers: () => void; loading?: boolean; onDelete: (user: User) => void; + viewUserBalanceDetail: (userId: User) => void; onRecharge: (id: string, amount: number) => Promise; pagination: { page: number; @@ -40,6 +43,7 @@ export const UserTable: React.FC = ({ users, fetchUsers, loading = false, + viewUserBalanceDetail, onDelete, onRecharge, pagination, @@ -185,7 +189,15 @@ export const UserTable: React.FC = ({ {formatDate(user.created_at)} - {user.balance.toFixed(2) || "-"} + + viewUserBalanceDetail(user)} + > + {user.balance.toFixed(2) || "-"} + +
diff --git a/frontend/src/services/marketplaceService.ts b/frontend/src/services/marketplaceService.ts index 4b0eefe..84192b8 100644 --- a/frontend/src/services/marketplaceService.ts +++ b/frontend/src/services/marketplaceService.ts @@ -17,6 +17,7 @@ interface FetchServicesParams { page?: number; page_size?: number; keyword?: string; + tag?: string; } interface ServicesResponseData { services: ServiceData[]; @@ -42,6 +43,7 @@ export async function fetchServices( page_size: _BasePageDetail.page_size, page: _BasePageDetail.page, keyword: "", + tag: "", } ): Promise { // Build query parameters @@ -50,7 +52,7 @@ export async function fetchServices( if (params.page_size) queryParams.append("page_size", params.page_size.toString()); if (params.keyword) queryParams.append("keyword", params.keyword); - + if (params.tag) queryParams.append("tag", params.tag); const response = await fetchAPI( `/api/web/mcp_services${queryParams.toString() ? "?" + queryParams.toString() : ""}` ); @@ -99,3 +101,26 @@ export async function fetchServiceById( return convertMcpService([response.data])[0]; } + + +/** + * Fetch tags list + */ +export async function fetchTagsList( +): Promise { + const response = await fetchAPI( + `/api/web/mcp_tags`, + { + method: "GET", + headers: { + "Content-Type": "application/json", + }, + } + ); + + if (!response.success) { + return []; + } + + return response.data || [] +} diff --git a/frontend/src/shared/components/Navigation.tsx b/frontend/src/shared/components/Navigation.tsx index 9ce4634..c04c65e 100644 --- a/frontend/src/shared/components/Navigation.tsx +++ b/frontend/src/shared/components/Navigation.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { useState } from "react"; +import React, { useEffect, useState } from "react"; import { Navbar, NavbarContent, @@ -15,6 +15,7 @@ import { useAuth } from "@/shared/lib/useAuth"; import { ArrowRightIcon } from "lucide-react"; import { DynamicLogo } from "@/shared/components/DynamicLogo"; import Link from "next/link"; +import { useSharedStore } from "../store/share"; export type NavigationItem = { label: string; href: string; @@ -45,6 +46,13 @@ function NavigationClient({ const { t } = useTranslation(); const { handleLogin } = useAuth(); + const [userToken, setUserToken] = useState(null); + + useEffect(() => { + const userToken = useSharedStore?.getState?.().user_token + setUserToken(userToken); + }, []); + return ( <> {/* Main Navigation */} @@ -97,9 +105,17 @@ function NavigationClient({ {langNode ? ( langNode ) : ( - + <> + { + !userToken && ( + <> + + + ) + } + )} {/* Desktop Auth Button */} @@ -110,7 +126,7 @@ function NavigationClient({ radius="full" onPress={onLogin || handleLogin} > - {t(signinText)} + {userToken ? t("Dashboard") : t(signinText) }
- {t(signinText)} + {userToken ? t("Dashboard") : t(signinText) }
)} @@ -156,7 +172,7 @@ function NavigationClient({ radius="full" onPress={onLogin || handleLogin} > - {t(signinText)} + {userToken ? t("Dashboard") : t(signinText) }
void; onSearch?: () => void; searchSuggestions?: string[]; @@ -16,6 +17,7 @@ interface HeroSectionProps { export const HeroSection: React.FC = ({ searchQuery, + isTagBarDisplay, onSearchChange, onSearch, searchSuggestions = [], @@ -77,7 +79,7 @@ export const HeroSection: React.FC = ({ }; return ( -
+

{t( diff --git a/frontend/src/shared/components/marketplace/ServerConfig.tsx b/frontend/src/shared/components/marketplace/ServerConfig.tsx index 7bd6f90..6fab403 100644 --- a/frontend/src/shared/components/marketplace/ServerConfig.tsx +++ b/frontend/src/shared/components/marketplace/ServerConfig.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { useState } from "react"; +import React, { useCallback, useEffect, useState } from "react"; import { Card, Chip, Button, Select, SelectItem } from "@nextui-org/react"; import { FlipButton } from "@/shared/components/FlipButton"; import { useAuth } from "@/shared/lib/useAuth"; @@ -9,7 +9,16 @@ import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext"; import { Copy } from "lucide-react"; import { copyToClipboard } from "@/shared/utils/clipboard"; import toast from "react-hot-toast"; +import { useSharedStore } from "@/shared/store/share"; +import { fetchAPI } from "@/shared/rpc/common-function"; +import i18n from "@/shared/lib/i18n"; +type apiKeyList = { + name: string; + apikey: string; + create_time: string; + apikey_id: number; +} interface ServerConfigProps { mcpName?: string; url?: string; @@ -20,6 +29,18 @@ interface ServerConfigProps { type McpType = "sse" | "streamable-http"; +// 辅助函数:将 API Key 掩码显示,只保留前2位和后4位 +const maskApiKey = (apiKey: string): string => { + if (!apiKey || apiKey.length <= 6) { + return apiKey; // 如果太短就直接返回 + } + const prefix = apiKey.slice(0, 2); + const suffix = apiKey.slice(-4); + const maskedLength = apiKey.length - 6; + const masked = '*'.repeat(maskedLength); + return `${prefix}${masked}${suffix}`; +}; + export const ServerConfig: React.FC = ({ mcpName, url = process.env.NEXT_PUBLIC_MCP_URL, @@ -31,6 +52,48 @@ export const ServerConfig: React.FC = ({ const { handleLogin } = useAuth(); const { platformConfig } = usePlatformConfig(); const [mcpType, setMcpType] = useState("sse"); + // API Key List + const [apiKeys, setApiKeys] = useState<{ key: string, label: string }[]>([]); + // Selected API Key + const [selectedApiKey, setSelectedApiKey] = useState(null); + // User Token + const [userToken, setUserToken] = useState(null); + + useEffect(() => { + const fetchData = async () => { + const userToken = useSharedStore?.getState?.().user_token + setUserToken(userToken); + if (userToken) { + const data = await fetchApiKeys() + if (data.length > 0) { + setApiKeys(data.map((item) => ({ + key: item.apikey, + label: item.name, + }))); + } + } + } + fetchData(); + }, []); + + const fetchApiKeys = useCallback( + async ( + ): Promise => { + try { + + const response = await fetchAPI('/api/apikey/list'); + if (!response.success) { + toast.error(response.error_message || i18n.t("Failed to load api keys")); + return [] + } + return response.data || [] + } catch (error) { + console.error("Error fetching api keys:", error); + return [] + } + }, + [] + ); const mcpTypeOptions = [ { key: "sse", label: "SSE (Server-Sent Events)" }, @@ -40,8 +103,8 @@ export const ServerConfig: React.FC = ({ const getCodeContent = () => { const serverUrl = mcpType === "streamable-http" - ? `${url}/streamable-http?authkey={Your-${platformConfig?.name}-Auth-Key}` - : `${url}?authkey={Your-${platformConfig?.name}-Auth-Key}`; + ? `${url}/streamable-http?authkey=${selectedApiKey ? selectedApiKey : `{Your-${platformConfig?.name}-Auth-Key}`}` + : `${url}?authkey=${selectedApiKey ? selectedApiKey : `{Your-${platformConfig?.name}-Auth-Key}`}`; return `{ "mcpServers": { @@ -63,16 +126,62 @@ export const ServerConfig: React.FC = ({ } }; + const handleCreateNewAuthorization = () => { + sessionStorage.setItem('create_new_authorization', 'true'); + handleLogin() + } + return (
{ visitor || can_invoke ? <> - + { + !userToken ? <> + + : <> + { + apiKeys.length ? + <> + + + : + <> + + + } + + } : <>

@@ -140,7 +249,7 @@ export const ServerConfig: React.FC = ({ {mcpType === "streamable-http" ? `${url}/streamable-http?authkey=` : `${url}?authkey=`} - {`{Your-${platformConfig?.name}-Auth-Key}`} + {selectedApiKey ? maskApiKey(selectedApiKey) : `{Your-${platformConfig?.name}-Auth-Key}`} {`" } } diff --git a/frontend/src/shared/components/marketplace/TagFilter.tsx b/frontend/src/shared/components/marketplace/TagFilter.tsx new file mode 100644 index 0000000..ed6dd1d --- /dev/null +++ b/frontend/src/shared/components/marketplace/TagFilter.tsx @@ -0,0 +1,309 @@ +"use client"; + +import React, { useState, useEffect, useRef } from "react"; +import { + Modal, + ModalContent, + ModalHeader, + ModalBody, + ModalFooter, + Button, +} from "@nextui-org/react"; +import { Theme, ThemeType } from "@/shared/types/system"; +import { useTranslation } from "react-i18next"; + +interface TagFilterProps { + tags: string[]; + theme: ThemeType; + selectedTag: string; + onTagChange: (tag: string) => void; + maxWidthPercent?: number; // 最大宽度百分比,默认80% +} + +export const TagFilter: React.FC = ({ + tags, + theme, + selectedTag, + onTagChange, + maxWidthPercent = 80, +}) => { + const { t } = useTranslation(); + // 是否打开标签筛选弹窗 + const [isModalOpen, setIsModalOpen] = useState(false); + // 临时选中的标签 + const [tempSelectedTag, setTempSelectedTag] = useState(null); + // 可见的标签 + const [visibleTags, setVisibleTags] = useState(["ALL", ...tags]); + // 是否显示更多按钮 + const [showMore, setShowMore] = useState(false); + // 从弹窗选择的额外标签 + const [extraTag, setExtraTag] = useState(null); + // 容器引用 + const containerRef = useRef(null); + // 标签容器引用 + const tagsContainerRef = useRef(null); + + + // 根据主题获取颜色配置 + const getThemeColors = () => { + switch (theme) { + case Theme.DEFAULT: + case Theme.MODERN: + return { + selected: "bg-[#C8DCFF] text-[#1E40AF]", + unselected: "text-gray-700 hover:bg-gray-200", + shadow: "shadow-lg shadow-[#C8DCFF]/50", + }; + case Theme.CLASSIC: + return { + selected: "bg-[#475569] text-white", + unselected: "text-gray-700 hover:bg-gray-200", + shadow: "shadow-lg shadow-[#475569]/50", + }; + case Theme.TEMU: + return { + selected: "bg-[#F97316] text-white", + unselected: "text-gray-700 hover:bg-gray-200", + shadow: "shadow-lg shadow-[#F97316]/50", + }; + case Theme.CREATIVE: + return { + selected: "to-orange-500 via-red-500 from-pink-500 bg-gradient-to-r text-white", + unselected: "text-gray-700 hover:bg-gray-200", + shadow: "shadow-lg shadow-[#EF5082]/50", + }; + default: + return { + selected: "bg-[#C8DCFF] text-[#1E40AF]", + unselected: "text-gray-700 hover:bg-gray-200", + shadow: "shadow-lg shadow-[#C8DCFF]/50", + }; + } + }; + + const themeColors = getThemeColors(); + + // 计算哪些标签可以显示 + useEffect(() => { + const calculateVisibleTags = () => { + if (!containerRef.current) return; + + const containerWidth = containerRef.current.offsetWidth; + const maxWidth = (containerWidth * maxWidthPercent) / 100; + + // More按钮的宽度(估算) + const moreButtonWidth = 80; + + // 创建临时元素来测量标签宽度 + const tempDiv = document.createElement("div"); + tempDiv.style.position = "absolute"; + tempDiv.style.visibility = "hidden"; + tempDiv.style.whiteSpace = "nowrap"; + tempDiv.className = "px-6 py-2 rounded-full text-sm font-medium"; + document.body.appendChild(tempDiv); + + let currentWidth = 0; + const visible: string[] = ["ALL"]; + let needsMore = false; + + // 先计算常规标签 + for (const tag of tags) { + if (tag === extraTag) continue; // 跳过额外标签,稍后处理 + + tempDiv.textContent = tag; + const tagWidth = tempDiv.offsetWidth; // 不加间距 + + if (currentWidth + tagWidth + moreButtonWidth > maxWidth) { + needsMore = true; + break; + } + + currentWidth += tagWidth; + visible.push(tag); + } + + // 处理额外标签或当前选中的标签 + // 如果当前选中的标签不在可见列表中(除了ALL),需要作为额外标签显示 + const tagToShow = extraTag || (selectedTag !== "ALL" && !visible.includes(selectedTag) ? selectedTag : null); + + if (tagToShow && tagToShow !== "ALL" && !visible.includes(tagToShow)) { + tempDiv.textContent = tagToShow; + const tagWidth = tempDiv.offsetWidth; // 不加间距 + + // 检查是否还有空间显示额外标签 + if (currentWidth + tagWidth + moreButtonWidth <= maxWidth) { + // 空间足够,直接添加 + currentWidth += tagWidth; + visible.push(tagToShow); + } else { + // 空间不够,替换掉最后一个常规标签(保留 ALL) + if (visible.length > 1) { + visible.pop(); // 移除最后一个标签 + visible.push(tagToShow); // 添加额外标签 + needsMore = true; // 确保显示 More 按钮 + } + } + } + + document.body.removeChild(tempDiv); + + setVisibleTags(visible); + setShowMore(needsMore); + }; + + // 延迟执行以确保DOM已渲染 + setTimeout(calculateVisibleTags, 0); + + // 监听窗口大小变化 + window.addEventListener("resize", calculateVisibleTags); + return () => window.removeEventListener("resize", calculateVisibleTags); + }, [tags, extraTag, selectedTag, maxWidthPercent]); + + const handleTagClick = (tag: string) => { + // 如果点击的是额外标签以外的标签,清除额外标签 + if (extraTag && tag !== extraTag) { + setExtraTag(null); + } + onTagChange(tag); + }; + + const handleModalOpen = () => { + // 打开弹窗时,初始化临时选中的标签为当前选中的标签 + setTempSelectedTag(selectedTag); + setIsModalOpen(true); + }; + + const handleModalConfirm = () => { + if (tempSelectedTag) { + // 如果选择的是 ALL 或者已经在可见标签中的标签,不设置为额外标签 + if (tempSelectedTag === "ALL" || visibleTags.includes(tempSelectedTag)) { + setExtraTag(null); + } else { + // 否则设置为额外标签 + setExtraTag(tempSelectedTag); + } + onTagChange(tempSelectedTag); + } + setIsModalOpen(false); + }; + + const handleModalCancel = () => { + setTempSelectedTag(null); + setIsModalOpen(false); + }; + + const handleModalTagClick = (tag: string) => { + setTempSelectedTag(tag); + }; + + return ( + <> +

+
+
+ {visibleTags.map((tag) => { + const isSelected = selectedTag === tag; + return ( + + ); + })} + + {showMore && ( + + )} +
+
+
+ + {/* More Modal */} + + + + Tag Filter + + +
+ + + {tags.map((tag) => { + const isSelected = tempSelectedTag === tag; + return ( + + ); + })} +
+
+ + + + +
+
+ + ); +}; + diff --git a/frontend/src/shared/types/dashboard.ts b/frontend/src/shared/types/dashboard.ts index 15f313d..610215f 100644 --- a/frontend/src/shared/types/dashboard.ts +++ b/frontend/src/shared/types/dashboard.ts @@ -10,6 +10,7 @@ export enum TabKey { OVERVIEW = "overview", WALLET = "wallet", ACCOUNT = "account", + USER_ACCOUNT = "user-account", } export interface SidebarSubItem { diff --git a/frontend/src/shared/types/system.ts b/frontend/src/shared/types/system.ts index 6cee532..12c6c81 100644 --- a/frontend/src/shared/types/system.ts +++ b/frontend/src/shared/types/system.ts @@ -31,6 +31,7 @@ export interface PlatformConfig { facebook_description?: string; // facebook description facebook_image_url?: string; // facebook image url meta_description?: string; // meta description + tag_bar_display?: boolean; // whether to display tags bar [key: string]: any; } From fa23805b5c26761aa3bdb256e7868688771aa2ed Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Tue, 30 Dec 2025 18:41:18 +0800 Subject: [PATCH 05/16] Change the balance_after field to balance --- .../admin_service/services/user_wallet_history_service.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/admin_service/services/user_wallet_history_service.py b/services/admin_service/services/user_wallet_history_service.py index 87052a0..7d6df60 100644 --- a/services/admin_service/services/user_wallet_history_service.py +++ b/services/admin_service/services/user_wallet_history_service.py @@ -51,13 +51,13 @@ class UserWalletHistoryService: info["description"] = service.name except: info["description"] = "-" - info["balance_after"] = order.balance_after + info["balance"] = order.balance_after elif order.type == TransactionType.DEPOSIT: info["order_type"] = "recharge" if order.status == 1: info["balance_after"] = order.balance_after else: - info["balance_after"] = "-" + info["balance"] = "-" info["description"] = order.payment_method else: info["order_type"] = order.type From 50637087ae421fba4836fa98946e4844f5b337e8 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Tue, 30 Dec 2025 18:43:35 +0800 Subject: [PATCH 06/16] Change the balance_after field to balance --- services/admin_service/services/user_wallet_history_service.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/admin_service/services/user_wallet_history_service.py b/services/admin_service/services/user_wallet_history_service.py index 7d6df60..905b671 100644 --- a/services/admin_service/services/user_wallet_history_service.py +++ b/services/admin_service/services/user_wallet_history_service.py @@ -55,7 +55,7 @@ class UserWalletHistoryService: elif order.type == TransactionType.DEPOSIT: info["order_type"] = "recharge" if order.status == 1: - info["balance_after"] = order.balance_after + info["balance"] = order.balance_after else: info["balance"] = "-" info["description"] = order.payment_method From 714e19a4fcd2b7a61d554cee89da8e84fa043054 Mon Sep 17 00:00:00 2001 From: lcx <1793599591@qq.com> Date: Wed, 31 Dec 2025 11:36:57 +0800 Subject: [PATCH 07/16] feat: add MCP service tag filtering, transaction record viewing, and various optimizations --- frontend/src/shared/components/marketplace/ServerConfig.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/frontend/src/shared/components/marketplace/ServerConfig.tsx b/frontend/src/shared/components/marketplace/ServerConfig.tsx index 6fab403..59e6cde 100644 --- a/frontend/src/shared/components/marketplace/ServerConfig.tsx +++ b/frontend/src/shared/components/marketplace/ServerConfig.tsx @@ -70,6 +70,7 @@ export const ServerConfig: React.FC = ({ key: item.apikey, label: item.name, }))); + setSelectedApiKey(data[0].apikey) } } } From cbfc4310b599af87ab5a77afa3d29ee4a43c10c2 Mon Sep 17 00:00:00 2001 From: lcx <1793599591@qq.com> Date: Sun, 4 Jan 2026 19:02:42 +0800 Subject: [PATCH 08/16] feat: add MCP service tag filtering, transaction record viewing, and various optimizations --- .../dashboard/AccountBalanceTable.tsx | 34 +++++++++++++++---- .../dashboard/UserAccountBalance.tsx | 2 +- .../user-management/UserBalanceDetail.tsx | 2 +- .../components/user-management/UserTable.tsx | 6 ++-- 4 files changed, 32 insertions(+), 12 deletions(-) diff --git a/frontend/src/components/dashboard/AccountBalanceTable.tsx b/frontend/src/components/dashboard/AccountBalanceTable.tsx index 72edd5a..c3253d0 100644 --- a/frontend/src/components/dashboard/AccountBalanceTable.tsx +++ b/frontend/src/components/dashboard/AccountBalanceTable.tsx @@ -23,6 +23,7 @@ import { Calendar, HelpCircle, Filter } from "lucide-react"; import { fetchAPI } from "@/shared/rpc/common-function"; import i18n from "@/shared/lib/i18n"; import { toast } from "react-hot-toast"; +import { fetchAdminAPI } from "@/rpc/admin-api"; export interface OrderItem { id: string; @@ -44,9 +45,10 @@ export interface OrderItem { interface AccountBalanceTableProps { userId?: string; + source?: "client" | "admin"; } -const AccountBalanceTable: React.FC = ({ userId }) => { +const AccountBalanceTable: React.FC = ({ userId, source }) => { const { t } = useTranslation(); const [items, setItems] = useState([]); @@ -90,7 +92,7 @@ const AccountBalanceTable: React.FC = ({ userId }) => ? `/api/order/list/by_user?${params.toString()}` : `/api/user/order/list?${params.toString()}`; - const response = await fetchAPI(apiUrl); + const response = source === "client" ? await fetchAPI(apiUrl) : await fetchAdminAPI(apiUrl); if (!response.success) { toast.error(response.error_message || i18n.t("Failed to load orders")); return { @@ -168,6 +170,27 @@ const AccountBalanceTable: React.FC = ({ userId }) => ); }; + // 格式化金额,带正负号和美元符号 + const formatAmount = (amount: string | number): string => { + const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount; + if (isNaN(numAmount)) return '$0.00'; + const absAmount = Math.abs(numAmount).toFixed(2); + if (numAmount > 0) { + return `+$${absAmount}`; + } else if (numAmount < 0) { + return `-$${absAmount}`; + } + return `$${absAmount}`; + }; + + // 格式化余额,只显示美元符号,不带正负号 + const formatBalance = (balance: string | number): string => { + const numBalance = typeof balance === 'string' ? parseFloat(balance) : balance; + if (isNaN(numBalance)) return '$0.00'; + + return `$${Math.abs(numBalance).toFixed(2)}`; + }; + const getStatusColor = (status: number) => { switch (status) { case 1: @@ -321,13 +344,10 @@ const AccountBalanceTable: React.FC = ({ userId }) => : "text-red-500" } > - - {order.order_type === "recharge" ? "+" : ""} - - {order.amount} + {formatAmount(order.amount)} - {order.balance} + {formatBalance(order.balance)} { description={t("View your balance and transaction history")} >
- +
); diff --git a/frontend/src/components/user-management/UserBalanceDetail.tsx b/frontend/src/components/user-management/UserBalanceDetail.tsx index 17df963..61c42d3 100644 --- a/frontend/src/components/user-management/UserBalanceDetail.tsx +++ b/frontend/src/components/user-management/UserBalanceDetail.tsx @@ -37,7 +37,7 @@ const BaseUserBalanceDetail: React.FC = ({
- +
); diff --git a/frontend/src/components/user-management/UserTable.tsx b/frontend/src/components/user-management/UserTable.tsx index 900f7af..46c3008 100644 --- a/frontend/src/components/user-management/UserTable.tsx +++ b/frontend/src/components/user-management/UserTable.tsx @@ -139,7 +139,7 @@ export const UserTable: React.FC = ({ {t("Email")} {t("Resource Group")} - +
{t("Register Date")} = ({
- {t("Balance")} - {t("Actions")} + {t("Balance")} + {t("Actions")}
Date: Mon, 5 Jan 2026 11:52:27 +0800 Subject: [PATCH 09/16] feat: add MCP service tag filtering, transaction record viewing, and various optimizations --- frontend/src/components/dashboard/AccountBalanceTable.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/components/dashboard/AccountBalanceTable.tsx b/frontend/src/components/dashboard/AccountBalanceTable.tsx index c3253d0..5aeabb1 100644 --- a/frontend/src/components/dashboard/AccountBalanceTable.tsx +++ b/frontend/src/components/dashboard/AccountBalanceTable.tsx @@ -321,7 +321,7 @@ const AccountBalanceTable: React.FC = ({ userId, sourc > {(order) => ( - {formatDate(order.confirm_at)} + {formatDate(order.payment_state === 0 ? order.create_at : order.confirm_at)} Date: Wed, 7 Jan 2026 16:49:59 +0800 Subject: [PATCH 10/16] fix: prevent "Allow All" resource group from being set as default --- .../resource-group/AddServerModal.tsx | 24 ++++++++++++------- .../resource-group/GroupServiceTable.tsx | 12 ++++++++-- .../resource-group/resourceGroup.tsx | 1 + 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/frontend/src/components/resource-group/AddServerModal.tsx b/frontend/src/components/resource-group/AddServerModal.tsx index 228c1c0..92874b7 100644 --- a/frontend/src/components/resource-group/AddServerModal.tsx +++ b/frontend/src/components/resource-group/AddServerModal.tsx @@ -5,6 +5,7 @@ interface AddServerModalProps { isOpen: boolean; onClose: () => void; name: string; + id: string; onSaveServer: (name: string, isDefault: boolean) => Promise; type: "add" | "edit"; isDefault: boolean; @@ -13,6 +14,7 @@ export const AddServerModal: React.FC = ({ isOpen, onClose, name, + id, onSaveServer, type, isDefault, @@ -49,12 +51,16 @@ export const AddServerModal: React.FC = ({ {type === "add" ? t("Create New Resource Group") : t("Edit Resource Group")} - setServerName(e.target.value)} - /> + { + id !== 'allow-all' && <> + setServerName(e.target.value)} + /> + + }
@@ -73,9 +79,9 @@ export const AddServerModal: React.FC = ({
-

- {showOptions && currentGroupId && <> + {showEditOptions && currentGroupId && <> + + } + {showOptions && currentGroupId && <>