Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c7462f3ed | ||
|
|
4c03a25f9b | ||
|
|
cc2d66be11 | ||
|
|
754d8e596e | ||
|
|
97fdd892ed | ||
|
|
fc46e7b354 | ||
|
|
02fd02ceef | ||
|
|
ed1391fc84 | ||
|
|
4e57c9d0b1 | ||
|
|
a37d13604d | ||
|
|
19267e14c2 | ||
|
|
660c83e0c7 | ||
|
|
ea3174e0fe | ||
|
|
e01a0cb249 | ||
|
|
890d1d8bf3 | ||
|
|
b7197fb35d | ||
|
|
8751aa9ef6 | ||
|
|
35cb02a035 | ||
|
|
beba80a14c | ||
|
|
2c1b17a947 | ||
|
|
71322c2d9d | ||
|
|
d93a3f9af3 | ||
|
|
55457532cc | ||
|
|
9b953048b3 | ||
|
|
913006ba02 | ||
|
|
3a38426b13 | ||
|
|
e42e5ad752 | ||
|
|
c69ed103dc | ||
|
|
6cd52f0d92 | ||
|
|
be7033e9a2 | ||
|
|
8946be619d | ||
|
|
2262a7f49a | ||
|
|
11264d302d | ||
|
|
6a18812572 | ||
|
|
401b35cd10 | ||
|
|
f44102bdb7 | ||
|
|
29a779648d | ||
|
|
20eabea48f | ||
|
|
919285e716 | ||
|
|
01d1411d49 | ||
|
|
6cb7ca9902 | ||
|
|
3012d27aae | ||
|
|
dd3a784cb5 | ||
|
|
518d5f55c5 | ||
|
|
923496735e | ||
|
|
20903eeab5 | ||
|
|
4016bb9d52 | ||
|
|
bf9071122b | ||
|
|
3ff0b743a6 | ||
|
|
360e2cd20d | ||
|
|
e12f6c0db5 | ||
|
|
ec96465a96 | ||
|
|
920eb9154e | ||
|
|
a224445038 | ||
|
|
1c3e40d337 | ||
|
|
44d0768296 | ||
|
|
e9ae97762b | ||
|
|
26b8147f94 | ||
|
|
e4f97e1014 | ||
|
|
d3efa08da2 | ||
|
|
ede3d5c2a3 | ||
|
|
42665d13a7 | ||
|
|
c4bbf09a19 | ||
|
|
ba3a4fe2a2 | ||
|
|
496b9fa380 | ||
|
|
80b3118f3a | ||
|
|
c4f56df03b | ||
|
|
4d26a793a3 | ||
|
|
ac849ce4dd | ||
|
|
a9a83fa187 | ||
|
|
c2738813eb | ||
|
|
883ada7aac | ||
|
|
ad574f0162 | ||
|
|
5cc9e9910e | ||
|
|
d91c1c5369 | ||
|
|
f108551780 | ||
|
|
be19df6273 | ||
|
|
2eb02bb70f | ||
|
|
b548f2494d | ||
|
|
e1fdbdd026 | ||
|
|
7985c6ae2b | ||
|
|
fdfe2c63bc |
No files matched your search
+1
-1
@@ -11,7 +11,7 @@ ADMIN_PORT=8001
|
||||
|
||||
# 调试配置
|
||||
DEBUG=false
|
||||
LOG_LEVEL=INFO
|
||||
LOG_LEVEL=DEBUG
|
||||
|
||||
# Redis 配置
|
||||
REDIS_HOST=xpack-redis
|
||||
|
||||
@@ -1,36 +1,37 @@
|
||||
# XPack 开源版本 - Copilot 编程指导
|
||||
# XPack Open Source Edition - Copilot Programming Guidelines
|
||||
|
||||
## 项目架构
|
||||
## Project Architecture
|
||||
|
||||
### 服务依赖
|
||||
- `admin_service` 和 `api_service` 相互独立,都依赖 `common`
|
||||
- 遵循分层架构:Controller → Service → Repository
|
||||
### Service Dependencies
|
||||
- `admin_service` and `api_service` are independent of each other, both depend on `common`
|
||||
- Follow layered architecture: Controller → Service → Repository
|
||||
|
||||
### 目录结构
|
||||
### Directory Structure
|
||||
```
|
||||
services/
|
||||
├── admin_service/ # 管理端服务
|
||||
├── api_service/ # API服务
|
||||
└── common/ # 公共模块
|
||||
├── admin_service/ # Admin service
|
||||
├── api_service/ # API service
|
||||
└── common/ # Common modules
|
||||
```
|
||||
|
||||
## 编码规范
|
||||
## Coding Standards
|
||||
|
||||
### 代码风格
|
||||
- 遵循 PEP 8,使用类型注解和 docstring
|
||||
- 命名:函数/变量用 `snake_case`,类用 `PascalCase`
|
||||
- 导入:优先使用 `services/common`,避免跨服务导入
|
||||
### Code Style
|
||||
- Follow PEP 8, use type annotations and docstrings
|
||||
- Naming: use `snake_case` for functions/variables, `PascalCase` for classes
|
||||
- Imports: prioritize `services/common`, avoid cross-service imports
|
||||
|
||||
### 日志要求
|
||||
- **必须使用英文**,使用 `services/common/logging_config.py`
|
||||
- 格式:`logger.info("Action completed: {context}")`
|
||||
- 避免敏感信息,包含必要上下文
|
||||
### Logging Requirements
|
||||
- **Must use English**, use `services/common/logging_config.py`
|
||||
- Format: `logger.info("Action completed: {context}")`
|
||||
- Avoid sensitive information, include necessary context
|
||||
|
||||
### 错误处理
|
||||
- 使用 `services/common/error_msg.py` 定义的错误消息
|
||||
- 统一异常处理和日志记录
|
||||
### Error Handling
|
||||
- Use error messages defined in `services/common/error_msg.py`
|
||||
- Unified exception handling and logging
|
||||
|
||||
## 开发建议
|
||||
- 有适当的日志记录(英文格式,统一格式)
|
||||
- 添加方法级别英文注释,需要简洁
|
||||
- 添加的注释一律使用英文
|
||||
## Development Guidelines
|
||||
- Think and analyze requirements first, wait for user confirmation before writing code
|
||||
- Include appropriate logging (English format, consistent style)
|
||||
- Add method-level English comments, keep them concise
|
||||
- All comments must be written in English
|
||||
@@ -32,7 +32,7 @@ jobs:
|
||||
- name: Setup qshell
|
||||
uses: foxundermoon/setup-qshell@v5
|
||||
with:
|
||||
version: '2.9.0'
|
||||
version: '2.13.0'
|
||||
- name: build
|
||||
run: |
|
||||
cd scripts && ./docker_build.sh ${{ secrets.DOCKER_USERNAME }}
|
||||
|
||||
@@ -41,3 +41,4 @@ htmlcov/
|
||||
local_settings.py
|
||||
/.secrets
|
||||
/uploads/
|
||||
/.vercel/
|
||||
+11
-11
@@ -8,18 +8,18 @@
|
||||
<a href="/README-zh-cn.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
**XPack** 是一款轻量级、开源的 MCP(Model Context Protocol)服务市场框架。
|
||||
它可以将任何符合 OpenAPI 规范的接口快速转换为 MCP 服务,并帮助你在数分钟内搭建自己的 API 商店。
|
||||
**XPack** 是全球首个开源 MCP 交易平台,帮助你在10分钟内快速搭建自己的 MCP 商店并立刻开始销售 MCP 服务。
|
||||
|
||||
<br>
|
||||
|
||||
✨ 使用 XPack,你可以:
|
||||
- ✅ **一键将 OpenAPI 转换为 MCP 服务配置**
|
||||
- 🧾 **自动生成 SEO 友好的主页和服务页**
|
||||
- 💳 **内置调用计费功能(支持按次收费)**
|
||||
- 👥 **用户账户体系与管理后台**
|
||||
- 🛠 **内置 Stripe 支付集成**
|
||||
- 🔐 **支持邮箱 & Google 登录认证**
|
||||
- ✅ 一键将 OpenAPI 转换为 MCP 服务并且为 MCP 定价
|
||||
- 🧾 自动生成 SEO 友好的主页和服务页
|
||||
- 💳 内置计费功能(支持按次、按Token收费)
|
||||
- 👥 管理注册用户、充值、交易记录等
|
||||
- 🛠 集成 Stripe 支付
|
||||
- 🔐 邮箱 & Google 登录认证
|
||||
- 📊 用户调用统计
|
||||
|
||||
本项目基于 **Apache 2.0 协议开源**,可放心用于商业用途。
|
||||
|
||||
@@ -27,10 +27,10 @@
|
||||
|
||||
# ✨ 快速开始
|
||||
|
||||
😍 只需一行命令,即可在 10 分钟内部署你的 MCP 服务市场:
|
||||
😍 只需一行命令,即可在 10 分钟内部署你的 MCP 交易平台:
|
||||
|
||||
```bash
|
||||
curl -sSO http://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
该脚本会自动安装 MySQL、Redis、RabbitMQ,并启动 XPack 服务。
|
||||
@@ -83,7 +83,7 @@ XPack-MCP-Market 依赖以下服务(可容器化或自行安装):
|
||||
### 🟢 快速部署命令
|
||||
|
||||
```bash
|
||||
curl -sSO http://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
支持系统包括:
|
||||
|
||||
@@ -7,15 +7,14 @@
|
||||
<a href="/README-zh-cn.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
**XPack** is a lightweight, open-source marketplace framework for MCP (Model Context Protocol) services.
|
||||
It allows you to transform any OpenAPI into a monetizable MCP service and build your own API store in just minutes.
|
||||
**XPack** is the world’s first open-source MCP marketplace, to quickly create and sell your own MCP services in just minutes.
|
||||
|
||||
<br>
|
||||
|
||||
✨ With XPack, you can:
|
||||
- ✅ **One-click OpenAPI → MCP service config**
|
||||
- 🧾 **SEO-friendly homepage + mcp service page**
|
||||
- 💳 **Built-in billing (per-call)**
|
||||
- 💳 **Built-in billing (per-call or token usage)**
|
||||
- 👥 **User account management**
|
||||
- 🛠 **Support Stripe Payment**
|
||||
- 🔐 **Support Email & Google OAuth Sign in**
|
||||
@@ -29,9 +28,12 @@ Everything is open-source and licensed under **Apache 2.0** — ready for commer
|
||||
😍 Deploying XPack is incredibly simple. With just one command line, you can deploy your MCP Market in 10 minutes.
|
||||
|
||||
```bash
|
||||
curl -sSO http://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
[](https://www.youtube.com/watch?v=Ut4mbFXWbFs)
|
||||
|
||||
|
||||
<br>
|
||||
|
||||
|
||||
@@ -83,7 +85,7 @@ Ensure these services are available and properly configured before running the b
|
||||
😍 Deploying XPack is incredibly simple. With just one command line, you can deploy your MCP Market in 10 minutes.
|
||||
|
||||
```bash
|
||||
curl -sSO http://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
curl -sSO https://xpack.ai/install/quick-start.sh; bash quick-start.sh
|
||||
```
|
||||
|
||||
<details>
|
||||
|
||||
@@ -42,10 +42,6 @@ const nextConfig = {
|
||||
key: "X-Content-Type-Options",
|
||||
value: "nosniff",
|
||||
},
|
||||
{
|
||||
key: "X-Frame-Options",
|
||||
value: "DENY",
|
||||
},
|
||||
{
|
||||
key: "X-XSS-Protection",
|
||||
value: "1; mode=block",
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"Featured Packages": "Featured Packages",
|
||||
"Individual Tools": "Individual Tools",
|
||||
"Details": "Details",
|
||||
"Copy code": "Copy code",
|
||||
"excel": "Excel",
|
||||
"data": "Data",
|
||||
"analysis": "Analysis",
|
||||
@@ -198,6 +199,27 @@
|
||||
"Tool name": "Tool name",
|
||||
"Tool description": "Tool description",
|
||||
"Take Offline": "Take Offline",
|
||||
"Platform Domain": "Platform Domain",
|
||||
"Enter platform domain (e.g., example.com)": "Enter platform domain (e.g., example.com)",
|
||||
"The domain name of your platform": "The domain name of your platform",
|
||||
"MCP Server Domain": "MCP Server Domain",
|
||||
"Enter MCP server domain (e.g., api.example.com)": "Enter MCP server domain (e.g., api.example.com)",
|
||||
"The domain for MCP server API calls": "The domain for MCP server API calls",
|
||||
"Featured in the XPack showcase": "Featured in the XPack showcase",
|
||||
"Enable this option to feature your site in the XPack global showcase and reach users worldwide.": "Enable this option to feature your site in the XPack global showcase and reach users worldwide.",
|
||||
"Please enter a platform domain before enabling showcase": "Please enter a platform domain before enabling showcase",
|
||||
"FAQ Management": "FAQ Management",
|
||||
"Configure frequently asked questions for your users": "Configure frequently asked questions for your users",
|
||||
"FAQ List": "FAQ List",
|
||||
"Edit questions and answers directly in the table below": "Edit questions and answers directly in the table below",
|
||||
"Save All": "Save All",
|
||||
"Order": "Order",
|
||||
"Question": "Question",
|
||||
"Answer": "Answer",
|
||||
"No FAQ items available.": "No FAQ items available.",
|
||||
"Enter question": "Enter question",
|
||||
"Enter answer": "Enter answer",
|
||||
"Insert below": "Insert below",
|
||||
"Bring Online": "Bring Online",
|
||||
"Short Description": "Short Description",
|
||||
"Long Description": "Long Description",
|
||||
@@ -234,6 +256,8 @@
|
||||
"Failed to parse OpenAPI document": "Failed to parse OpenAPI document",
|
||||
"OpenAPI document parsed successfully": "OpenAPI document parsed successfully",
|
||||
"Please enter a valid URL": "Please enter a valid URL",
|
||||
"Please enter a valid URL with http:// or https://": "Please enter a valid URL with http:// or https://",
|
||||
"Please fix validation errors before saving": "Please fix validation errors before saving",
|
||||
"Please select a file": "Please select a file",
|
||||
"File uploaded successfully": "File uploaded successfully",
|
||||
"Failed to upload file": "Failed to upload file",
|
||||
@@ -306,6 +330,14 @@
|
||||
"All Roles": "All Roles",
|
||||
"Ban User": "Ban User",
|
||||
"Unban User": "Unban User",
|
||||
"Recharge User": "Recharge User",
|
||||
"Current Balance": "Current Balance",
|
||||
"User recharged successfully": "User recharged successfully",
|
||||
"Please enter a valid amount": "Please enter a valid amount",
|
||||
"Minimum recharge amount is $1": "Minimum recharge amount is $1",
|
||||
"User not selected": "User not selected",
|
||||
"Recharge failed": "Recharge failed",
|
||||
"Network error, please try again": "Network error, please try again",
|
||||
"Delete User": "Delete User",
|
||||
"View Profile": "View Profile",
|
||||
"Edit User": "Edit User",
|
||||
@@ -386,12 +418,20 @@
|
||||
"Failed to test Google auth": "Failed to test Google auth",
|
||||
"Failed to fetch Stripe config": "Failed to fetch Stripe config",
|
||||
"Failed to save Stripe config": "Failed to save Stripe config",
|
||||
"Failed to save Alipay config": "Failed to save Alipay config",
|
||||
"Failed to save WeChat config": "Failed to save WeChat config",
|
||||
"Stripe connection test failed": "Stripe connection test failed",
|
||||
"Stripe connection test successful": "Stripe connection test successful",
|
||||
"Alipay connection test successful": "Alipay connection test successful",
|
||||
"Alipay connection test failed": "Alipay connection test failed",
|
||||
"WeChat connection test successful": "WeChat connection test successful",
|
||||
"WeChat connection test failed": "WeChat connection test failed",
|
||||
"Connection test failed": "Connection test failed",
|
||||
"Unknown error": "Unknown error",
|
||||
"Secret Key cannot be empty": "Secret Key cannot be empty",
|
||||
"Stripe Configuration": "Stripe Configuration",
|
||||
"Alipay Configuration": "Alipay Configuration",
|
||||
"WeChat Configuration": "WeChat Configuration",
|
||||
"Google Login Settings": "Google Login Settings",
|
||||
"Enable Google Login": "Enable Google Login",
|
||||
"Administrator Account": "Administrator Account",
|
||||
@@ -533,8 +573,19 @@
|
||||
"Billing Mode": "Billing Mode",
|
||||
"Enable free quota": "Enable free quota",
|
||||
"Configure Stripe payment interface": "Configure Stripe payment interface",
|
||||
"Configure Alipay payment interface": "Configure Alipay payment interface",
|
||||
"Configure WeChat payment interface": "Configure WeChat payment interface",
|
||||
"Secret Key": "Secret Key",
|
||||
"Stripe secret key for server-side API calls": "Stripe secret key for server-side API calls",
|
||||
"App ID": "App ID",
|
||||
"Alipay App ID": "Alipay App ID",
|
||||
"App Private Key": "App Private Key",
|
||||
"Alipay App Private Key": "Alipay App Private Key",
|
||||
"Alipay Public Key": "Alipay Public Key",
|
||||
"Alipay public key for verification": "Alipay public key for verification",
|
||||
"WeChat App ID": "WeChat App ID",
|
||||
"Merchant ID": "Merchant ID",
|
||||
"WeChat Merchant ID": "WeChat Merchant ID",
|
||||
"Webhook Secret": "Webhook Secret",
|
||||
"Test Connection": "Test Connection",
|
||||
"Monitor platform revenue and view user recharge history": "Monitor platform revenue and view user recharge history",
|
||||
@@ -593,6 +644,7 @@
|
||||
"Confirm": "Confirm",
|
||||
"Recharge Account": "Recharge Account",
|
||||
"Funds will be added to your account balance": "Funds will be added to your account balance",
|
||||
"Please select a payment method": "Please select a payment method",
|
||||
"Manage your balance and recharge history": "Manage your balance and recharge history",
|
||||
"Build incredible AI agents together": "Build incredible AI agents together",
|
||||
"Balance: {{amount}}": "Balance: {{amount}}",
|
||||
@@ -633,6 +685,12 @@
|
||||
"Total Revenue": "Total Revenue",
|
||||
"Failed to save stripe config": "Failed to save stripe config",
|
||||
"Stripe config saved successfully": "Stripe config saved successfully",
|
||||
"Alipay config saved successfully": "Alipay config saved successfully",
|
||||
"WeChat config saved successfully": "WeChat config saved successfully",
|
||||
"Failed to save {{channelName}} config": "Failed to save {{channelName}} config",
|
||||
"{{channelName}} config saved successfully": "{{channelName}} config saved successfully",
|
||||
"{{channelName}} connection test failed": "{{channelName}} connection test failed",
|
||||
"{{channelName}} connection test successful": "{{channelName}} connection test successful",
|
||||
"Login successful": "Login successful",
|
||||
"Logged out successfully": "Logged out successfully",
|
||||
"Configure email settings": "Configure email settings",
|
||||
@@ -727,5 +785,91 @@
|
||||
"Theme changed successfully": "Theme changed successfully",
|
||||
"Failed to change theme": "Failed to change theme",
|
||||
"About page saved successfully": "About page saved successfully",
|
||||
"Failed to save about page": "Failed to save about page"
|
||||
"Failed to save about page": "Failed to save about page",
|
||||
"General": "General",
|
||||
"Homepage": "Homepage",
|
||||
"Homepage content and theme settings": "Homepage content and theme settings",
|
||||
"About Page": "About Page",
|
||||
"About page content configuration": "About page content configuration",
|
||||
"Email & Admin": "Email & Admin",
|
||||
"Email and administrator settings": "Email and administrator settings",
|
||||
"Embedded HTML": "Embedded HTML",
|
||||
"Configure custom HTML content for global injection": "Configure custom HTML content for global injection",
|
||||
"Enable Custom HTML": "Enable Custom HTML",
|
||||
"Toggle to enable or disable custom HTML injection": "Toggle to enable or disable custom HTML injection",
|
||||
"Show Preview": "Show Preview",
|
||||
"Hide Preview": "Hide Preview",
|
||||
"Enter your custom HTML, CSS, or JavaScript code here...\n\nExample:\n<script>\n // Google Analytics\n gtag('config', 'GA_MEASUREMENT_ID');\n</script>\n\n<style>\n .custom-style {\n color: #333;\n }\n</style>": "Enter your custom HTML, CSS, or JavaScript code here...\n\nExample:\n<script>\n // Google Analytics\n gtag('config', 'GA_MEASUREMENT_ID');\n</script>\n\n<style>\n .custom-style {\n color: #333;\n }\n</style>",
|
||||
"This HTML will be injected globally into the application. You can include script tags, CSS styles, or any valid HTML.": "This HTML will be injected globally into the application. You can include script tags, CSS styles, or any valid HTML.",
|
||||
"Preview": "Preview",
|
||||
"Note: This is a text preview. The actual HTML will be rendered when saved and enabled.": "Note: This is a text preview. The actual HTML will be rendered when saved and enabled.",
|
||||
"Usage Instructions": "Usage Instructions",
|
||||
"You can include Google Analytics, custom CSS, or any tracking scripts": "You can include Google Analytics, custom CSS, or any tracking scripts",
|
||||
"The HTML will be injected into the document head section": "The HTML will be injected into the document head section",
|
||||
"Make sure your code is valid to avoid breaking the application": "Make sure your code is valid to avoid breaking the application",
|
||||
"Changes take effect immediately after saving and enabling": "Changes take effect immediately after saving and enabling",
|
||||
"Welcome to Your Platform": "Welcome to Your Platform",
|
||||
"Let's set up your platform with some basic information": "Let's set up your platform with some basic information",
|
||||
"Information needed": "Information needed",
|
||||
"Fields marked with * are required": "Fields marked with * are required",
|
||||
"Website title is required": "Website title is required",
|
||||
"Headline is required": "Headline is required",
|
||||
"Subheadline is required": "Subheadline is required",
|
||||
"Please fill in all required fields": "Please fill in all required fields",
|
||||
"Setup failed. Please try again.": "Setup failed. Please try again.",
|
||||
"Complete Setup": "Complete Setup",
|
||||
"Platform setup completed successfully!": "Platform setup completed successfully!",
|
||||
"Welcome to the famous five-minute platform setup process! Just fill in the information below and you'll be on your way to using the most extendable and powerful platform.": "Welcome to the famous five-minute platform setup process! Just fill in the information below and you'll be on your way to using the most extendable and powerful platform.",
|
||||
"Please provide the following information. Do not worry, you can always change these settings later in the admin panel.": "Please provide the following information. Do not worry, you can always change these settings later in the admin panel.",
|
||||
"Failed to update homepage config": "Failed to update homepage config",
|
||||
"Homepage config updated successfully": "Homepage config updated successfully",
|
||||
"Failed to load homepage config": "Failed to load homepage config",
|
||||
"FAQ updated successfully": "FAQ updated successfully",
|
||||
"Navigation updated successfully": "Navigation updated successfully",
|
||||
"Embedded HTML updated successfully": "Embedded HTML updated successfully",
|
||||
"Payment channels updated successfully": "Payment channels updated successfully",
|
||||
"Manage frequently asked questions": "Manage frequently asked questions",
|
||||
"Add FAQ Item": "Add FAQ Item",
|
||||
"Remove FAQ Item": "Remove FAQ Item",
|
||||
"Top Navigation": "Top Navigation",
|
||||
"Manage top navigation links": "Manage top navigation links",
|
||||
"Title": "Title",
|
||||
"Link": "Link",
|
||||
"Target": "Target",
|
||||
"Add Navigation Item": "Add Navigation Item",
|
||||
"Remove Navigation Item": "Remove Navigation Item",
|
||||
"Enter title": "Enter title",
|
||||
"Enter link URL": "Enter link URL",
|
||||
"Same window": "Same window",
|
||||
"New window": "New window",
|
||||
"Custom HTML injection": "Custom HTML injection",
|
||||
"Enable embedded HTML": "Enable embedded HTML",
|
||||
"HTML Content": "HTML Content",
|
||||
"Enter custom HTML code": "Enter custom HTML code",
|
||||
"Manage payment methods": "Manage payment methods",
|
||||
"Channel ID": "Channel ID",
|
||||
"Display Name": "Display Name",
|
||||
"Add Payment Channel": "Add Payment Channel",
|
||||
"Remove Payment Channel": "Remove Payment Channel",
|
||||
"Enter channel ID": "Enter channel ID",
|
||||
"Enter display name": "Enter display name",
|
||||
"Installation Status": "Installation Status",
|
||||
"First time installation": "First time installation",
|
||||
"System installed": "System installed",
|
||||
"Configure top navigation menu items and links": "Configure top navigation menu items and links",
|
||||
"Per Million Tokens": "Per Million Tokens",
|
||||
"Price per million tokens consumed": "Price per million tokens consumed",
|
||||
"Price per million tokens": "Price per million tokens",
|
||||
"Price per API call": "Price per API call",
|
||||
"Payment channel disabled successfully": "Payment channel disabled successfully",
|
||||
"Failed to disable payment channel": "Failed to disable payment channel",
|
||||
"Payment channel enabled successfully": "Payment channel enabled successfully",
|
||||
"Failed to enable payment channel": "Failed to enable payment channel",
|
||||
"Input Token Price": "Input Token Price",
|
||||
"Output Token Price": "Output Token Price",
|
||||
"Price per million input tokens": "Price per million input tokens",
|
||||
"Price per million output tokens": "Price per million output tokens",
|
||||
"Input": "Input",
|
||||
"Output": "Output",
|
||||
"1M tokens": "1M tokens"
|
||||
}
|
||||
@@ -40,6 +40,7 @@
|
||||
"Featured Packages": "精选工具包",
|
||||
"Individual Tools": "单个工具",
|
||||
"Details": "详情",
|
||||
"Copy code": "复制代码",
|
||||
"excel": "Excel",
|
||||
"data": "数据",
|
||||
"analysis": "分析",
|
||||
@@ -199,6 +200,27 @@
|
||||
"Tool name": "工具名称",
|
||||
"Tool description": "工具描述",
|
||||
"Take Offline": "下线",
|
||||
"Platform Domain": "平台域名",
|
||||
"Enter platform domain (e.g., example.com)": "输入平台域名(例如:example.com)",
|
||||
"The domain name of your platform": "您平台的域名",
|
||||
"MCP Server Domain": "MCP 服务器域名",
|
||||
"Enter MCP server domain (e.g., api.example.com)": "输入 MCP 服务器域名(例如:api.example.com)",
|
||||
"The domain for MCP server API calls": "用于 MCP 服务器 API 调用的域名",
|
||||
"Featured in the XPack showcase": "展示在 XPack 的全球案例榜单",
|
||||
"Enable this option to feature your site in the XPack global showcase and reach users worldwide.": "当开启选项,你的网站会展示在 XPack 的全球案例榜单来获得全球用户的关注。",
|
||||
"Please enter a platform domain before enabling showcase": "启用展示功能前请先输入平台域名",
|
||||
"FAQ Management": "FAQ管理",
|
||||
"Configure frequently asked questions for your users": "为您的用户配置常见问题",
|
||||
"FAQ List": "FAQ列表",
|
||||
"Edit questions and answers directly in the table below": "在下方表格中直接编辑问题和答案",
|
||||
"Save All": "保存全部",
|
||||
"Order": "排序",
|
||||
"Question": "问题",
|
||||
"Answer": "答案",
|
||||
"No FAQ items available.": "暂无FAQ项目。",
|
||||
"Enter question": "输入问题",
|
||||
"Enter answer": "输入答案",
|
||||
"Insert below": "在下方插入",
|
||||
"Bring Online": "上线",
|
||||
"Short Description": "简短描述",
|
||||
"Long Description": "详细描述",
|
||||
@@ -235,6 +257,8 @@
|
||||
"Failed to parse OpenAPI document": "解析 OpenAPI 文档失败",
|
||||
"OpenAPI document parsed successfully": "OpenAPI 文档解析成功",
|
||||
"Please enter a valid URL": "请输入有效的 URL",
|
||||
"Please enter a valid URL with http:// or https://": "请输入有效的 URL,需要包含 http:// 或 https://",
|
||||
"Please fix validation errors before saving": "请修复验证错误后再保存",
|
||||
"Please select a file": "请选择文件",
|
||||
"File uploaded successfully": "文件上传成功",
|
||||
"Failed to upload file": "文件上传失败",
|
||||
@@ -307,6 +331,14 @@
|
||||
"All Roles": "所有角色",
|
||||
"Ban User": "封禁用户",
|
||||
"Unban User": "解封用户",
|
||||
"Recharge User": "为用户充值",
|
||||
"Current Balance": "当前余额",
|
||||
"User recharged successfully": "用户充值成功",
|
||||
"Please enter a valid amount": "请输入有效金额",
|
||||
"Minimum recharge amount is $1": "最低充值金额为 $1",
|
||||
"User not selected": "未选择用户",
|
||||
"Recharge failed": "充值失败",
|
||||
"Network error, please try again": "网络错误,请重试",
|
||||
"Delete User": "删除用户",
|
||||
"View Profile": "查看资料",
|
||||
"Edit User": "编辑用户",
|
||||
@@ -387,12 +419,20 @@
|
||||
"Failed to test Google auth": "测试Google认证失败",
|
||||
"Failed to fetch Stripe config": "获取Stripe配置失败",
|
||||
"Failed to save Stripe config": "保存Stripe配置失败",
|
||||
"Failed to save Alipay config": "保存支付宝配置失败",
|
||||
"Failed to save WeChat config": "保存微信配置失败",
|
||||
"Stripe connection test failed": "Stripe连接测试失败",
|
||||
"Stripe connection test successful": "Stripe连接测试成功",
|
||||
"Alipay connection test successful": "支付宝连接测试成功",
|
||||
"Alipay connection test failed": "支付宝连接测试失败",
|
||||
"WeChat connection test successful": "微信连接测试成功",
|
||||
"WeChat connection test failed": "微信连接测试失败",
|
||||
"Connection test failed": "连接测试失败",
|
||||
"Unknown error": "未知错误",
|
||||
"Secret Key cannot be empty": "密钥不能为空",
|
||||
"Stripe Configuration": "Stripe配置",
|
||||
"Alipay Configuration": "支付宝配置",
|
||||
"WeChat Configuration": "微信配置",
|
||||
"Google Login Settings": "Google登录设置",
|
||||
"Enable Google Login": "启用Google登录",
|
||||
"Administrator Account": "管理员账户",
|
||||
@@ -535,6 +575,17 @@
|
||||
"Billing Mode": "计费模式",
|
||||
"Enable free quota": "启用免费配额",
|
||||
"Configure Stripe payment interface": "配置Stripe支付接口",
|
||||
"Configure Alipay payment interface": "配置支付宝支付接口",
|
||||
"Configure WeChat payment interface": "配置微信支付接口",
|
||||
"App ID": "应用ID",
|
||||
"Alipay App ID": "支付宝应用ID",
|
||||
"App Private Key": "应用私钥",
|
||||
"Alipay App Private Key": "支付宝应用私钥",
|
||||
"Alipay Public Key": "支付宝公钥",
|
||||
"Alipay public key for verification": "支付宝公钥用于验证",
|
||||
"WeChat App ID": "微信应用ID",
|
||||
"Merchant ID": "商户号",
|
||||
"WeChat Merchant ID": "微信商户号",
|
||||
"Secret Key": "密钥",
|
||||
"Stripe secret key for server-side API calls": "用于服务端API调用的Stripe密钥",
|
||||
"Webhook Secret": "Webhook密钥",
|
||||
@@ -594,7 +645,8 @@
|
||||
"WeChat Pay": "微信支付",
|
||||
"Confirm": "确认",
|
||||
"Recharge Account": "充值账户",
|
||||
"Funds will be added to your account balance": "资金将添加到您的账户余额",
|
||||
"Funds will be added to your account balance": "资金将添加到您的账户余额中",
|
||||
"Please select a payment method": "请选择支付方式",
|
||||
"Manage your balance and recharge history": "管理您的余额和充值历史",
|
||||
"Build incredible AI agents together": "一起构建强大的 AI 代理",
|
||||
"Balance: {{amount}}": "余额: {{amount}}",
|
||||
@@ -609,6 +661,10 @@
|
||||
"Failed to toggle service status": "切换服务状态失败",
|
||||
"Stripe configuration saved successfully": "Stripe 配置保存成功",
|
||||
"Failed to save Stripe configuration": "保存 Stripe 配置失败",
|
||||
"Failed to save {{channelName}} config": "保存{{channelName}}配置失败",
|
||||
"{{channelName}} config saved successfully": "{{channelName}}配置保存成功",
|
||||
"{{channelName}} connection test failed": "{{channelName}}连接测试失败",
|
||||
"{{channelName}} connection test successful": "{{channelName}}连接测试成功",
|
||||
"System config updated successfully": "系统配置更新成功",
|
||||
"Failed to update system config": "更新系统配置失败",
|
||||
"Confirm Purchase": "确认购买",
|
||||
@@ -635,6 +691,8 @@
|
||||
"Total Revenue": "总收入",
|
||||
"Failed to save stripe config": "保存 Stripe 配置失败",
|
||||
"Stripe config saved successfully": "Stripe 配置保存成功",
|
||||
"Alipay config saved successfully": "支付宝配置保存成功",
|
||||
"WeChat config saved successfully": "微信配置保存成功",
|
||||
"Login successful": "登录成功",
|
||||
"Logged out successfully": "退出登录成功",
|
||||
"Configure email settings": "配置邮箱设置",
|
||||
@@ -729,5 +787,91 @@
|
||||
"Theme changed successfully": "主题切换成功",
|
||||
"Failed to change theme": "主题切换失败",
|
||||
"About page saved successfully": "关于页面保存成功",
|
||||
"Failed to save about page": "关于页面保存失败"
|
||||
"Failed to save about page": "关于页面保存失败",
|
||||
"General": "常规设置",
|
||||
"Homepage": "首页设置",
|
||||
"Homepage content and theme settings": "首页内容和主题设置",
|
||||
"About Page": "关于页面",
|
||||
"About page content configuration": "关于页面内容配置",
|
||||
"Email & Admin": "邮箱与管理员",
|
||||
"Email and administrator settings": "邮箱和管理员设置",
|
||||
"Embedded HTML": "嵌入式HTML",
|
||||
"Configure custom HTML content for global injection": "配置自定义HTML内容进行全局注入",
|
||||
"Enable Custom HTML": "启用自定义HTML",
|
||||
"Toggle to enable or disable custom HTML injection": "切换启用或禁用自定义HTML注入",
|
||||
"Show Preview": "显示预览",
|
||||
"Hide Preview": "隐藏预览",
|
||||
"Enter your custom HTML, CSS, or JavaScript code here...\n\nExample:\n<script>\n // Google Analytics\n gtag('config', 'GA_MEASUREMENT_ID');\n</script>\n\n<style>\n .custom-style {\n color: #333;\n }\n</style>": "在此输入您的自定义HTML、CSS或JavaScript代码...\n\n示例:\n<script>\n // Google Analytics\n gtag('config', 'GA_MEASUREMENT_ID');\n</script>\n\n<style>\n .custom-style {\n color: #333;\n }\n</style>",
|
||||
"This HTML will be injected globally into the application. You can include script tags, CSS styles, or any valid HTML.": "此HTML将全局注入到应用程序中。您可以包含脚本标签、CSS样式或任何有效的HTML。",
|
||||
"Preview": "预览",
|
||||
"Note: This is a text preview. The actual HTML will be rendered when saved and enabled.": "注意:这是文本预览。实际的HTML将在保存并启用后渲染。",
|
||||
"Usage Instructions": "使用说明",
|
||||
"You can include Google Analytics, custom CSS, or any tracking scripts": "您可以包含Google Analytics、自定义CSS或任何跟踪脚本",
|
||||
"The HTML will be injected into the document head section": "HTML将注入到文档头部分",
|
||||
"Make sure your code is valid to avoid breaking the application": "确保您的代码有效,以避免破坏应用程序",
|
||||
"Changes take effect immediately after saving and enabling": "更改在保存并启用后立即生效",
|
||||
"Welcome to Your Platform": "欢迎使用您的平台",
|
||||
"Let's set up your platform with some basic information": "让我们用一些基本信息来设置您的平台",
|
||||
"Fields marked with * are required": "标有 * 的字段为必填项",
|
||||
"Website title is required": "网站标题为必填项",
|
||||
"Headline is required": "标题为必填项",
|
||||
"Subheadline is required": "副标题为必填项",
|
||||
"Please fill in all required fields": "请填写所有必填字段",
|
||||
"Setup failed. Please try again.": "设置失败,请重试。",
|
||||
"Complete Setup": "完成设置",
|
||||
"Platform setup completed successfully!": "平台设置成功完成!",
|
||||
"Welcome to the famous five-minute platform setup process! Just fill in the information below and you'll be on your way to using the most extendable and powerful platform.": "欢迎使用著名的五分钟平台设置流程!只需填写下面的信息,您就可以开始使用最具扩展性和功能强大的平台了。",
|
||||
"Information needed": "所需信息",
|
||||
"Please provide the following information. Do not worry, you can always change these settings later in the admin panel.": "请提供以下信息。不用担心,您随时可以在管理面板中更改这些设置。",
|
||||
"Failed to update homepage config": "更新主页配置失败",
|
||||
"Homepage config updated successfully": "主页配置更新成功",
|
||||
"Failed to load homepage config": "加载主页配置失败",
|
||||
"FAQ updated successfully": "常见问题更新成功",
|
||||
"Navigation updated successfully": "导航更新成功",
|
||||
"Embedded HTML updated successfully": "嵌入HTML更新成功",
|
||||
"Payment channels updated successfully": "支付渠道更新成功",
|
||||
"Manage frequently asked questions": "管理常见问题",
|
||||
"Add FAQ Item": "添加常见问题",
|
||||
"Remove FAQ Item": "删除常见问题",
|
||||
"Top Navigation": "顶部导航",
|
||||
"Manage top navigation links": "管理顶部导航链接",
|
||||
"Title": "标题",
|
||||
"Link": "链接",
|
||||
"Target": "目标",
|
||||
"Add Navigation Item": "添加导航项",
|
||||
"Remove Navigation Item": "删除导航项",
|
||||
"Enter title": "输入标题",
|
||||
"Enter link URL": "输入链接地址",
|
||||
"Same window": "当前窗口",
|
||||
"New window": "新窗口",
|
||||
"Custom HTML injection": "自定义HTML注入",
|
||||
"Enable embedded HTML": "启用嵌入HTML",
|
||||
"HTML Content": "HTML内容",
|
||||
"Enter custom HTML code": "输入自定义HTML代码",
|
||||
"Manage payment methods": "管理支付方式",
|
||||
"Channel ID": "渠道ID",
|
||||
"Display Name": "显示名称",
|
||||
"Add Payment Channel": "添加支付渠道",
|
||||
"Remove Payment Channel": "删除支付渠道",
|
||||
"Enter channel ID": "输入渠道ID",
|
||||
"Enter display name": "输入显示名称",
|
||||
"Installation Status": "安装状态",
|
||||
"First time installation": "首次安装",
|
||||
"System installed": "系统已安装",
|
||||
"Configure top navigation menu items and links": "配置顶部导航菜单项和链接",
|
||||
"Per Million Tokens": "每百万Token",
|
||||
"Price per million tokens consumed": "每百万Token消耗的价格",
|
||||
"Price per million tokens": "每百万Token价格",
|
||||
"Price per API call": "每次API调用价格",
|
||||
"Payment channel disabled successfully": "支付渠道禁用成功",
|
||||
"Failed to disable payment channel": "禁用支付渠道失败",
|
||||
"Payment channel enabled successfully": "支付渠道启用成功",
|
||||
"Failed to enable payment channel": "启用支付渠道失败",
|
||||
"Input Token Price": "输入Token价格",
|
||||
"Output Token Price": "输出Token价格",
|
||||
"Price per million input tokens": "每百万输入Token价格",
|
||||
"Price per million output tokens": "每百万输出Token价格",
|
||||
"Input": "输入",
|
||||
"Output": "输出",
|
||||
"1M tokens": "1M tokens"
|
||||
}
|
||||
@@ -32,6 +32,13 @@ export default async function RootLayout({
|
||||
`,
|
||||
}}
|
||||
/>
|
||||
{platformConfig?.embeded_html?.is_enabled && platformConfig?.embeded_html?.html && (
|
||||
<div
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: platformConfig.embeded_html.html,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</head>
|
||||
<body className={redHatDisplay.className} suppressHydrationWarning>
|
||||
<ClientRootProviders initConfig={platformConfig}>
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import React, { Suspense } from "react";
|
||||
import { MarketplaceMain } from "@/components/marketplace/Main";
|
||||
import React from "react";
|
||||
import type { Metadata } from "next";
|
||||
import { createBaseMetadata, getDynamicTitle } from "@/shared/utils/metadata";
|
||||
import { Navigation } from "@/shared/components/Navigation";
|
||||
import { Footer } from "@/shared/components/Footer";
|
||||
import { fetchServices } from "@/services/marketplaceService";
|
||||
import type { ServiceData } from "@/shared/types/marketplace";
|
||||
import { ThemeSelector } from "@/components/theme/ThemeSelector";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const title = await getDynamicTitle("Marketplace");
|
||||
const title = await getDynamicTitle();
|
||||
return createBaseMetadata(title);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,42 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import React, { useState } from "react";
|
||||
import { EmailConfigForm } from "@/components/login-setting/EmailConfigForm";
|
||||
import { GoogleAuthConfigForm } from "@/components/login-setting/GoogleAuthConfigForm";
|
||||
import { useSystemConfigManagement } from "@/hooks/useSystemConfigManagement";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
import { LoginConfig, GoogleAuthConfig } from "@/shared/types/system";
|
||||
import { TabKey } from "@/shared/types/dashboard";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { EmailConfig } from "@/types/system";
|
||||
|
||||
interface LoginSettingsContentProps {
|
||||
onTabNavigate?: (tab: TabKey) => void;
|
||||
loginConfig: LoginConfig;
|
||||
saveLoginConfig: (config: LoginConfig) => Promise<boolean>;
|
||||
emailConfig: EmailConfig;
|
||||
}
|
||||
|
||||
export const LoginSettingsContent: React.FC<LoginSettingsContentProps> = ({
|
||||
onTabNavigate,
|
||||
loginConfig,
|
||||
saveLoginConfig,
|
||||
emailConfig,
|
||||
}) => {
|
||||
const [googleSubmitLoading, setGoogleSubmitLoading] = useState(false);
|
||||
const [emailSubmitLoading, setEmailSubmitLoading] = useState(false);
|
||||
const { t } = useTranslation();
|
||||
const { updateClientConfig } = usePlatformConfig();
|
||||
|
||||
const {
|
||||
// login config
|
||||
loginConfig,
|
||||
loginLoading,
|
||||
saveLoginConfig,
|
||||
|
||||
// email config
|
||||
emailConfig,
|
||||
|
||||
// platform config
|
||||
platformConfig,
|
||||
} = useSystemConfigManagement();
|
||||
|
||||
// 验证至少有一种登录方式启用
|
||||
// check if at least one login method is enabled
|
||||
const validateLoginMethods = (config: LoginConfig): boolean => {
|
||||
const isGoogleEnabled =
|
||||
config.google?.is_enabled && config.google?.client_id;
|
||||
const isGoogleEnabled = config.google?.is_enabled;
|
||||
const isEmailEnabled = config.email?.is_enabled;
|
||||
|
||||
const enabledCount = [isGoogleEnabled, isEmailEnabled].filter(
|
||||
@@ -57,12 +51,13 @@ export const LoginSettingsContent: React.FC<LoginSettingsContentProps> = ({
|
||||
return;
|
||||
}
|
||||
|
||||
setEmailSubmitLoading(true);
|
||||
const result = await saveLoginConfig(config);
|
||||
if (!result) return;
|
||||
updateClientConfig({
|
||||
platform: platformConfig,
|
||||
login: config,
|
||||
});
|
||||
setEmailSubmitLoading(false);
|
||||
};
|
||||
|
||||
// save google auth config
|
||||
@@ -76,22 +71,23 @@ export const LoginSettingsContent: React.FC<LoginSettingsContentProps> = ({
|
||||
return;
|
||||
}
|
||||
|
||||
setGoogleSubmitLoading(true);
|
||||
const result = await saveLoginConfig(updatedLoginConfig);
|
||||
if (!result) return;
|
||||
updateClientConfig({
|
||||
platform: platformConfig,
|
||||
login: updatedLoginConfig,
|
||||
});
|
||||
setGoogleSubmitLoading(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 w-full">
|
||||
<div className="space-y-4 w-full">
|
||||
{/* email config */}
|
||||
<EmailConfigForm
|
||||
config={loginConfig}
|
||||
emailConfig={emailConfig}
|
||||
onSave={handleSaveLoginConfig}
|
||||
isLoading={loginLoading}
|
||||
isLoading={emailSubmitLoading}
|
||||
onTabNavigate={onTabNavigate}
|
||||
/>
|
||||
|
||||
@@ -99,7 +95,7 @@ export const LoginSettingsContent: React.FC<LoginSettingsContentProps> = ({
|
||||
<GoogleAuthConfigForm
|
||||
config={loginConfig.google}
|
||||
onSave={handleSaveGoogleAuthConfig}
|
||||
isLoading={loginLoading}
|
||||
isLoading={googleSubmitLoading}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -4,7 +4,6 @@ import React, { useEffect, useState, Suspense } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useAdminStore } from "@/store/admin";
|
||||
import DashboardSidebar from "@/shared/components/DashboardSidebar";
|
||||
import DashboardDemoContent from "@/shared/components/DashboardDemoContent";
|
||||
import ConsoleStats from "@/components/console/ConsoleStats";
|
||||
import PaymentChannelsContent from "@/components/console/PaymentChannelsContent";
|
||||
@@ -15,17 +14,14 @@ import { MCPServicesManagement } from "@/components/mcp-services/MCPServicesMana
|
||||
import UserManagement from "@/components/user-management/UserManagement";
|
||||
import RevenueManagement from "@/components/revenue-management/RevenueManagement";
|
||||
import {
|
||||
Cog,
|
||||
CreditCard,
|
||||
DollarSign,
|
||||
Home,
|
||||
Settings,
|
||||
Users,
|
||||
LogIn,
|
||||
ServerIcon,
|
||||
} from "lucide-react";
|
||||
import { LoginSettingsContent } from "@/components/console/LoginSettingsContent";
|
||||
import { Button } from "@nextui-org/react";
|
||||
import { FaDiscord } from "react-icons/fa";
|
||||
import ConsoleSidebar from "./Sidebar";
|
||||
|
||||
const ConsoleContent: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
@@ -33,6 +29,8 @@ const ConsoleContent: React.FC = () => {
|
||||
const searchParams = useSearchParams();
|
||||
const [admin_token] = useAdminStore((state) => [state.admin_token]);
|
||||
|
||||
const _DefaultSubTab = "general";
|
||||
|
||||
const getInitialTab = (): TabKey => {
|
||||
const tabFromUrl = searchParams.get("tab") as TabKey;
|
||||
if (
|
||||
@@ -51,49 +49,79 @@ const ConsoleContent: React.FC = () => {
|
||||
return TabKey.CONSOLE;
|
||||
};
|
||||
|
||||
const getInitialSubTab = (): string | undefined => {
|
||||
const subTabFromUrl = searchParams.get("subtab");
|
||||
return subTabFromUrl || _DefaultSubTab;
|
||||
};
|
||||
|
||||
const [activeTab, setActiveTab] = useState<TabKey>(getInitialTab);
|
||||
const [activeSubTab, setActiveSubTab] = useState<string | undefined>(
|
||||
getInitialSubTab
|
||||
);
|
||||
const sidebarItems: SidebarItem[] = [
|
||||
{
|
||||
key: TabKey.CONSOLE,
|
||||
icon: <Home className="w-5 h-5" />,
|
||||
icon: <Home size={18} />,
|
||||
label: t("Dashboard"),
|
||||
description: t("Overview and analytics"),
|
||||
},
|
||||
{
|
||||
key: TabKey.MCP_SERVICES,
|
||||
icon: <Settings className="w-5 h-5" />,
|
||||
icon: <ServerIcon size={18} />,
|
||||
label: t("MCP Services"),
|
||||
description: t("Manage MCP services and API tools"),
|
||||
},
|
||||
{
|
||||
key: TabKey.USER_MANAGEMENT,
|
||||
icon: <Users className="w-5 h-5" />,
|
||||
icon: <Users size={18} />,
|
||||
label: t("User Management"),
|
||||
description: t("Manage registered users"),
|
||||
},
|
||||
{
|
||||
key: TabKey.REVENUE_MANAGEMENT,
|
||||
icon: <DollarSign className="w-5 h-5" />,
|
||||
icon: <DollarSign size={18} />,
|
||||
label: t("Revenue Management"),
|
||||
description: t("View user recharge history"),
|
||||
},
|
||||
{
|
||||
key: TabKey.PAYMENT_CHANNELS,
|
||||
icon: <CreditCard className="w-5 h-5" />,
|
||||
icon: <CreditCard size={18} />,
|
||||
label: t("Payment Channels"),
|
||||
description: t("Configure payment channels"),
|
||||
},
|
||||
{
|
||||
key: TabKey.LOGIN_SETTINGS,
|
||||
icon: <LogIn className="w-5 h-5" />,
|
||||
label: t("Login Settings"),
|
||||
description: t("Configure authentication methods"),
|
||||
},
|
||||
{
|
||||
key: TabKey.SYSTEM_SETTINGS,
|
||||
icon: <Cog className="w-5 h-5" />,
|
||||
icon: <Settings size={18} />,
|
||||
label: t("System Settings"),
|
||||
description: t("Platform basic configuration"),
|
||||
// Sub-menu items for System Settings
|
||||
subItems: [
|
||||
{
|
||||
key: "general",
|
||||
label: "General",
|
||||
description: "Platform basic configuration",
|
||||
},
|
||||
{
|
||||
key: "login-settings",
|
||||
label: "Login Settings",
|
||||
description: "Configure authentication methods",
|
||||
},
|
||||
{
|
||||
key: "homepage",
|
||||
label: "Homepage",
|
||||
description: "Homepage content and theme settings",
|
||||
},
|
||||
{
|
||||
key: "about-page",
|
||||
label: "About Page",
|
||||
description: "About page content configuration",
|
||||
},
|
||||
{
|
||||
key: "email-admin",
|
||||
label: "Email & Admin",
|
||||
description: "Email and administrator settings",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -104,8 +132,10 @@ const ConsoleContent: React.FC = () => {
|
||||
}
|
||||
}, [admin_token, router]);
|
||||
|
||||
const handleTabNavigate = (tab: TabKey) => {
|
||||
const handleTabNavigate = (tab: TabKey, subTab?: string) => {
|
||||
setActiveTab(tab);
|
||||
setActiveSubTab(subTab || _DefaultSubTab);
|
||||
|
||||
// update url params
|
||||
if (tab === TabKey.CONSOLE) {
|
||||
// when switch to dashboard, clear all query params, only keep base path
|
||||
@@ -114,6 +144,12 @@ const ConsoleContent: React.FC = () => {
|
||||
// other tabs set corresponding tab params
|
||||
const params = new URLSearchParams();
|
||||
params.set("tab", tab);
|
||||
|
||||
// add subtab parameter if provided
|
||||
if (subTab) {
|
||||
params.set("subtab", subTab);
|
||||
}
|
||||
|
||||
router.push(`/console?${params.toString()}`, { scroll: false });
|
||||
}
|
||||
};
|
||||
@@ -151,23 +187,15 @@ const ConsoleContent: React.FC = () => {
|
||||
<PaymentChannelsContent />
|
||||
</DashboardDemoContent>
|
||||
);
|
||||
case "login-settings":
|
||||
return (
|
||||
<DashboardDemoContent
|
||||
title={t("Login Settings")}
|
||||
description={t("Configure authentication methods")}
|
||||
>
|
||||
<LoginSettingsContent onTabNavigate={handleTabNavigate} />
|
||||
</DashboardDemoContent>
|
||||
);
|
||||
case "system-settings":
|
||||
return (
|
||||
<DashboardDemoContent
|
||||
title={t("System Settings")}
|
||||
description={t("Platform basic configuration")}
|
||||
>
|
||||
<SystemSettingsContent />
|
||||
</DashboardDemoContent>
|
||||
<SystemSettingsContent
|
||||
activeSubTab={activeSubTab}
|
||||
subTab={sidebarItems
|
||||
.find((item) => item.key === activeTab)
|
||||
?.subItems?.find((item) => item.key === activeSubTab)}
|
||||
onTabNavigate={handleTabNavigate}
|
||||
/>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
@@ -185,25 +213,12 @@ const ConsoleContent: React.FC = () => {
|
||||
<div className="min-h-screen bg-background">
|
||||
<div className="flex">
|
||||
{/* Sidebar */}
|
||||
<DashboardSidebar
|
||||
<ConsoleSidebar
|
||||
activeTab={activeTab}
|
||||
activeSubTab={activeSubTab}
|
||||
onTabNavigate={handleTabNavigate}
|
||||
onLogout={handleLogout}
|
||||
sidebarItems={sidebarItems}
|
||||
bottomPanel={
|
||||
<Button
|
||||
variant="light"
|
||||
startContent={<FaDiscord className="w-5 h-5" />}
|
||||
className="w-full justify-start h-auto p-3"
|
||||
onPress={() => {
|
||||
window.open("https://discord.gg/cyZfcdCXkW", "_blank");
|
||||
}}
|
||||
>
|
||||
<div className="flex justify-between items-center w-full">
|
||||
<span className="font-medium">{t("Discord")}</span>
|
||||
</div>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Main Content */}
|
||||
|
||||
@@ -1,46 +1,56 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import React from 'react';
|
||||
import { StripeConfigForm } from './StripeConfigForm';
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import React from "react";
|
||||
import { StripeConfigForm } from "../payment/StripeConfigForm";
|
||||
import { AlipayConfigForm } from "../payment/AlipayConfigForm";
|
||||
import { WechatConfigForm } from "../payment/WechatConfigForm";
|
||||
import { usePaymentChannelManagement } from "@/hooks/usePaymentChannelManagement";
|
||||
import { StripeConfig } from "@/types/payment";
|
||||
import { toast } from "react-hot-toast";
|
||||
|
||||
export const PaymentChannelsContent: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const {
|
||||
stripeConfig,
|
||||
isSaving,
|
||||
alipayConfig,
|
||||
wechatConfig,
|
||||
isWechatSaving,
|
||||
isStripeSaving,
|
||||
isAlipaySaving,
|
||||
saveStripeConfig,
|
||||
testStripeConnection,
|
||||
saveAlipayConfig,
|
||||
saveWechatConfig,
|
||||
enableChannel,
|
||||
disableChannel,
|
||||
} = usePaymentChannelManagement();
|
||||
|
||||
|
||||
// test stripe connection
|
||||
const handleTestStripeConnection = async (config: StripeConfig) => {
|
||||
const result = await testStripeConnection(config);
|
||||
|
||||
if (result.success) {
|
||||
toast.success(t("Stripe connection test successful"));
|
||||
} else {
|
||||
toast.error(result.message || t("Stripe connection test failed"));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 w-full">
|
||||
{/* stripe configuration */}
|
||||
<StripeConfigForm
|
||||
config={stripeConfig}
|
||||
onSave={saveStripeConfig}
|
||||
onTest={handleTestStripeConnection}
|
||||
isLoading={isSaving}
|
||||
isTestLoading={false}
|
||||
onEnable={enableChannel}
|
||||
onDisable={disableChannel}
|
||||
isLoading={isStripeSaving}
|
||||
/>
|
||||
{/* coming soon */}
|
||||
{/* alipay configuration */}
|
||||
{/* <AlipayConfigForm
|
||||
config={alipayConfig}
|
||||
onSave={saveAlipayConfig}
|
||||
onEnable={enableChannel}
|
||||
onDisable={disableChannel}
|
||||
isLoading={isAlipaySaving}
|
||||
/> */}
|
||||
{/* coming soon */}
|
||||
{/* wechat configuration */}
|
||||
{/* <WechatConfigForm
|
||||
config={wechatConfig}
|
||||
onSave={saveWechatConfig}
|
||||
onEnable={enableChannel}
|
||||
onDisable={disableChannel}
|
||||
isLoading={isWechatSaving}
|
||||
/> */}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PaymentChannelsContent;
|
||||
export default PaymentChannelsContent;
|
||||
@@ -0,0 +1,161 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { Button, Divider, Link, Tooltip } from "@nextui-org/react";
|
||||
import { LogOut } from "lucide-react";
|
||||
import { DashboardSidebarProps } from "@/shared/types/dashboard";
|
||||
import { DynamicLogo } from "@/shared/components/DynamicLogo";
|
||||
import { FaDiscord } from "react-icons/fa";
|
||||
|
||||
const ConsoleSidebar: React.FC<DashboardSidebarProps> = ({
|
||||
activeTab,
|
||||
activeSubTab,
|
||||
onTabNavigate,
|
||||
onLogout,
|
||||
sidebarItems,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const handleSubItemClick = (parentKey: string, subKey: string) => {
|
||||
onTabNavigate?.(parentKey as any, subKey);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex h-screen">
|
||||
{/* Main Sidebar */}
|
||||
<div className="py-2 px-2 w-[70px] overflow-hidden border-r border-divider flex flex-col justify-between">
|
||||
{/* Header */}
|
||||
<div className="mb-6 mt-4 flex flex-col items-center gap-2">
|
||||
<Link href={process.env.NEXT_PUBLIC_DOMAIN || "/"}>
|
||||
<DynamicLogo
|
||||
alt="Platform Logo"
|
||||
className="max-w-full h-auto max-h-[30px]"
|
||||
/>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Navigation */}
|
||||
<div className="flex flex-col gap-2 flex-1">
|
||||
{sidebarItems.map((item) => (
|
||||
<React.Fragment key={item.key}>
|
||||
<Tooltip
|
||||
content={t(item.label)}
|
||||
closeDelay={0}
|
||||
disableAnimation
|
||||
placement="right"
|
||||
>
|
||||
<Button
|
||||
key={item.key}
|
||||
variant={activeTab === item.key ? "flat" : "light"}
|
||||
color={activeTab === item.key ? "primary" : "default"}
|
||||
startContent={item.icon}
|
||||
className="w-full h-auto p-4"
|
||||
onPress={() => onTabNavigate?.(item.key)}
|
||||
isIconOnly
|
||||
></Button>
|
||||
</Tooltip>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Divider className="my-2" />
|
||||
|
||||
<div className="space-y-2">
|
||||
<Tooltip
|
||||
content={t("Discord")}
|
||||
closeDelay={0}
|
||||
disableAnimation
|
||||
placement="right"
|
||||
>
|
||||
<Button
|
||||
variant="light"
|
||||
startContent={<FaDiscord size={18} />}
|
||||
className="w-full h-auto p-4"
|
||||
onPress={() => {
|
||||
window.open("https://discord.gg/cyZfcdCXkW", "_blank");
|
||||
}}
|
||||
isIconOnly
|
||||
></Button>
|
||||
</Tooltip>
|
||||
|
||||
{/* Logout */}
|
||||
<Tooltip
|
||||
content={t("Log Out")}
|
||||
closeDelay={0}
|
||||
disableAnimation
|
||||
placement="right"
|
||||
>
|
||||
<Button
|
||||
variant="light"
|
||||
color="danger"
|
||||
startContent={<LogOut size={18} />}
|
||||
className="w-full h-auto p-4"
|
||||
onPress={onLogout}
|
||||
isIconOnly
|
||||
></Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sub Menu Panel */}
|
||||
{(() => {
|
||||
const activeItem = sidebarItems.find((item) => item.key === activeTab);
|
||||
if (!activeItem?.subItems?.length) return null;
|
||||
|
||||
return (
|
||||
<div className="relative bg-content2/50 border-r overflow-hidden w-[240px] p-3">
|
||||
<div className="mb-3 pb-2 border-b">
|
||||
<h4 className="font-medium text-sm text-default-700">
|
||||
{t(activeItem.label)}
|
||||
</h4>
|
||||
<p className="text-xs text-default-500 mt-1">
|
||||
{t(activeItem.description)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
{activeItem.subItems?.map((subItem) => {
|
||||
const isSubActive = activeSubTab === subItem.key;
|
||||
|
||||
return (
|
||||
<React.Fragment key={subItem.key}>
|
||||
<Button
|
||||
key={subItem.key}
|
||||
variant={isSubActive ? "flat" : "light"}
|
||||
color={isSubActive ? "primary" : "default"}
|
||||
size="sm"
|
||||
className={`w-full justify-start h-auto p-2 text-left ${
|
||||
isSubActive
|
||||
? "bg-primary/10 border border-primary/20"
|
||||
: "hover:bg-default-100"
|
||||
}`}
|
||||
onPress={() =>
|
||||
handleSubItemClick(activeItem.key, subItem.key)
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col items-start w-full">
|
||||
<div className="font-medium text-xs">
|
||||
{t(subItem.label)}
|
||||
</div>
|
||||
{subItem.description && (
|
||||
<div className="text-xs opacity-60 mt-0.5 truncate w-full">
|
||||
{t(subItem.description)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Button>
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ConsoleSidebar;
|
||||
@@ -1,121 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Input, Button, AccordionItem, Accordion } from '@nextui-org/react';
|
||||
import { Eye, EyeOff } from 'lucide-react';
|
||||
import { StripeConfig } from '@/types/payment';
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
|
||||
interface StripeConfigFormProps {
|
||||
config: StripeConfig;
|
||||
onSave: (config: StripeConfig) => void;
|
||||
onTest: (config: StripeConfig) => void;
|
||||
isLoading?: boolean;
|
||||
isTestLoading?: boolean;
|
||||
}
|
||||
|
||||
export const StripeConfigForm: React.FC<StripeConfigFormProps> = ({
|
||||
config,
|
||||
onSave,
|
||||
isLoading = false,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [formData, setFormData] = useState<StripeConfig>(config);
|
||||
const [showSecretKey, setShowSecretKey] = useState(false);
|
||||
const [showWebhookSecret, setShowWebhookSecret] = useState(false);
|
||||
useEffect(() => {
|
||||
console.log("config", config);
|
||||
setFormData(config);
|
||||
}, [config]);
|
||||
|
||||
const handleInputChange = (field: keyof StripeConfig, value: string) => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[field]: value
|
||||
}));
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
|
||||
const isFormValid = formData.secret.trim() !== '' && formData.webhook_secret.trim() !== '';
|
||||
|
||||
return (
|
||||
<Accordion variant='splitted' itemClasses={{
|
||||
base: 'shadow-none border-1',
|
||||
}} defaultExpandedKeys={['stripe-config']} className='px-0'>
|
||||
<AccordionItem key="stripe-config" title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<h3 className="text-lg font-semibold">{t('Stripe Configuration')}</h3>
|
||||
<p className="text-sm text-gray-500">{t('Configure Stripe payment interface')}</p>
|
||||
</div>
|
||||
} >
|
||||
<div className="space-y-4">
|
||||
{/* Secret Key */}
|
||||
<Input
|
||||
label={t('Secret Key')}
|
||||
placeholder="sk_test_... or sk_live_..."
|
||||
description={t('Stripe secret key for server-side API calls')}
|
||||
value={formData.secret}
|
||||
onChange={(e) => handleInputChange('secret', e.target.value)}
|
||||
type={showSecretKey ? "text" : "password"}
|
||||
endContent={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowSecretKey(!showSecretKey)}
|
||||
className="focus:outline-none"
|
||||
>
|
||||
{showSecretKey ? (
|
||||
<EyeOff className="w-4 h-4 text-gray-400" />
|
||||
) : (
|
||||
<Eye className="w-4 h-4 text-gray-400" />
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
isRequired
|
||||
/>
|
||||
|
||||
{/* Webhook Secret (Optional) */}
|
||||
<Input
|
||||
label={t('Webhook Secret')}
|
||||
placeholder="whsec_..."
|
||||
description={t('Webhook signing secret for verifying Stripe events')}
|
||||
value={formData.webhook_secret || ''}
|
||||
onChange={(e) => handleInputChange('webhook_secret', e.target.value)}
|
||||
type={showWebhookSecret ? "text" : "password"}
|
||||
isRequired
|
||||
endContent={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowWebhookSecret(!showWebhookSecret)}
|
||||
className="focus:outline-none"
|
||||
>
|
||||
{showWebhookSecret ? (
|
||||
<EyeOff className="w-4 h-4 text-gray-400" />
|
||||
) : (
|
||||
<Eye className="w-4 h-4 text-gray-400" />
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex gap-3 py-4">
|
||||
<Button
|
||||
color="primary"
|
||||
variant="solid"
|
||||
onPress={handleSave}
|
||||
isLoading={isLoading}
|
||||
isDisabled={!isFormValid}
|
||||
size='sm'
|
||||
>
|
||||
{t('Save')}
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -1,18 +1,33 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { PlatformConfigForm } from "@/components/system-setting/PlatformConfigForm";
|
||||
import { AdminConfigForm } from "@/components/system-setting/AdminConfigForm";
|
||||
import { EmailConfigForm } from "@/components/system-setting/EmailConfigForm";
|
||||
import { HomepageSettings } from "@/components/system-setting/HomepageSettings";
|
||||
import { AboutPageSettings } from "@/components/system-setting/AboutPageSettings";
|
||||
import { EmailAndAdminSettings } from "@/components/system-setting/EmailAndAdminSettings";
|
||||
import { useSystemConfigManagement } from "@/hooks/useSystemConfigManagement";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
import { Theme } from "@/shared/types/system";
|
||||
import i18n from "@/shared/lib/i18n";
|
||||
import { PlatformConfigForm } from "../system-setting/PlatformConfigForm";
|
||||
import DashboardDemoContent from "@/shared/components/DashboardDemoContent";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { SidebarSubItem, TabKey } from "@/shared/types/dashboard";
|
||||
import { LoginSettingsContent } from "./LoginSettingsContent";
|
||||
|
||||
export const SystemSettingsContent: React.FC = () => {
|
||||
interface SystemSettingsContentProps {
|
||||
activeSubTab?: string;
|
||||
subTab?: SidebarSubItem;
|
||||
onTabNavigate: (tab: TabKey, subTab?: string) => void;
|
||||
}
|
||||
|
||||
export const SystemSettingsContent: React.FC<SystemSettingsContentProps> = ({
|
||||
activeSubTab,
|
||||
subTab,
|
||||
onTabNavigate,
|
||||
}) => {
|
||||
const { updateClientConfig } = usePlatformConfig();
|
||||
const [isAboutLoading, setIsAboutLoading] = useState(false);
|
||||
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
// platform config
|
||||
platformConfig,
|
||||
@@ -31,6 +46,10 @@ export const SystemSettingsContent: React.FC = () => {
|
||||
|
||||
// image upload
|
||||
uploadImage,
|
||||
|
||||
// login config
|
||||
loginConfig,
|
||||
saveLoginConfig,
|
||||
} = useSystemConfigManagement();
|
||||
|
||||
// save admin config
|
||||
@@ -77,33 +96,60 @@ export const SystemSettingsContent: React.FC = () => {
|
||||
});
|
||||
};
|
||||
|
||||
// Render content based on active sub tab
|
||||
const renderSubTabContent = () => {
|
||||
switch (activeSubTab) {
|
||||
case "homepage":
|
||||
return <HomepageSettings />;
|
||||
case "about-page":
|
||||
return (
|
||||
<AboutPageSettings
|
||||
config={platformConfig}
|
||||
onAboutSave={handleAboutSave}
|
||||
onImageUpload={uploadImage}
|
||||
isAboutLoading={isAboutLoading}
|
||||
/>
|
||||
);
|
||||
case "email-admin":
|
||||
return (
|
||||
<EmailAndAdminSettings
|
||||
emailConfig={emailConfig}
|
||||
adminConfig={adminConfig}
|
||||
onSaveEmailConfig={handleSaveEmailConfig}
|
||||
onSaveAdminConfig={handleSaveAdminConfig}
|
||||
isLoading={emailLoading}
|
||||
isAdminLoading={adminLoading}
|
||||
/>
|
||||
);
|
||||
case "login-settings":
|
||||
return (
|
||||
<LoginSettingsContent
|
||||
onTabNavigate={onTabNavigate}
|
||||
loginConfig={loginConfig}
|
||||
saveLoginConfig={saveLoginConfig}
|
||||
emailConfig={emailConfig}
|
||||
/>
|
||||
);
|
||||
case "general":
|
||||
default:
|
||||
return (
|
||||
<PlatformConfigForm
|
||||
config={platformConfig}
|
||||
onSave={handleSavePlatformConfig}
|
||||
onThemeChange={handleThemeChange}
|
||||
isLoading={platformLoading}
|
||||
/>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 w-full">
|
||||
{/* platform config */}
|
||||
<PlatformConfigForm
|
||||
config={platformConfig}
|
||||
onSave={handleSavePlatformConfig}
|
||||
onThemeChange={handleThemeChange}
|
||||
onAboutSave={handleAboutSave}
|
||||
isLoading={platformLoading}
|
||||
isAboutLoading={isAboutLoading}
|
||||
onImageUpload={uploadImage}
|
||||
/>
|
||||
|
||||
{/* admin config */}
|
||||
<AdminConfigForm
|
||||
config={adminConfig}
|
||||
onSave={handleSaveAdminConfig}
|
||||
isLoading={adminLoading}
|
||||
/>
|
||||
|
||||
{/* email config */}
|
||||
<EmailConfigForm
|
||||
config={emailConfig}
|
||||
onSave={handleSaveEmailConfig}
|
||||
isLoading={emailLoading}
|
||||
/>
|
||||
</div>
|
||||
<DashboardDemoContent
|
||||
title={t(subTab?.label || "System Settings")}
|
||||
description={t(subTab?.description || "Platform basic configuration")}
|
||||
>
|
||||
{renderSubTabContent()}
|
||||
</DashboardDemoContent>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ const DashboardContent: React.FC = () => {
|
||||
state.user_token,
|
||||
state.user,
|
||||
]);
|
||||
const { loginConfig } = usePlatformConfig();
|
||||
const { loginConfig, paymentChannels } = usePlatformConfig();
|
||||
|
||||
const [logOut, useGetUser] = useGlobalStore((state) => [
|
||||
state.logOut,
|
||||
@@ -163,14 +163,16 @@ const DashboardContent: React.FC = () => {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant="bordered"
|
||||
onPress={handleRecharge}
|
||||
aria-label="Recharge wallet"
|
||||
size="sm"
|
||||
>
|
||||
{t("Recharge")}
|
||||
</Button>
|
||||
{paymentChannels.length > 0 && (
|
||||
<Button
|
||||
variant="bordered"
|
||||
onPress={handleRecharge}
|
||||
aria-label="Recharge wallet"
|
||||
size="sm"
|
||||
>
|
||||
{t("Recharge")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
@@ -21,7 +21,7 @@ interface EmailConfigFormProps {
|
||||
emailConfig: EmailConfig;
|
||||
onSave: (config: LoginConfig) => Promise<void>;
|
||||
isLoading?: boolean;
|
||||
onTabNavigate?: (tab: TabKey) => void;
|
||||
onTabNavigate?: (tab: TabKey, subTab?: string) => void;
|
||||
}
|
||||
|
||||
export const EmailConfigForm: React.FC<EmailConfigFormProps> = ({
|
||||
@@ -180,7 +180,7 @@ export const EmailConfigForm: React.FC<EmailConfigFormProps> = ({
|
||||
<Link
|
||||
className="text-sm underline cursor-pointer"
|
||||
onPress={() => {
|
||||
onTabNavigate?.(TabKey.SYSTEM_SETTINGS);
|
||||
onTabNavigate?.(TabKey.SYSTEM_SETTINGS, "email-admin");
|
||||
}}
|
||||
>
|
||||
{t("Go to Settings")}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { Accordion, AccordionItem } from "@nextui-org/react";
|
||||
import { Plus } from "lucide-react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
|
||||
function FaqClient() {
|
||||
const { faqItems } = usePlatformConfig();
|
||||
const { t } = useTranslation();
|
||||
// Custom indicator component with plus sign that fades out when expanded
|
||||
const CustomIndicator = ({ isOpen }: { isOpen?: boolean }) => (
|
||||
<Plus
|
||||
className={`text-black transition-all duration-300 ${
|
||||
isOpen ? "rotate-0 opacity-0" : "rotate-0 opacity-100"
|
||||
}`}
|
||||
size={16}
|
||||
/>
|
||||
);
|
||||
if (faqItems.length === 0) return null;
|
||||
|
||||
return (
|
||||
<section className="py-12 sm:py-20 px-4 sm:px-6" id="faqs">
|
||||
<div className="max-w-7xl mx-auto">
|
||||
<h2 className="text-2xl sm:text-3xl font-bold mb-8 sm:mb-12 text-center">
|
||||
{t("FAQs")}
|
||||
</h2>
|
||||
{/**content */}
|
||||
<div className="relative bg-white rounded-lg">
|
||||
<Accordion variant="light">
|
||||
{faqItems.map((faq, index) => (
|
||||
<AccordionItem
|
||||
key={index}
|
||||
aria-label={faq.question}
|
||||
title={
|
||||
<span className="text-base sm:text-lg font-medium">
|
||||
{faq.question}
|
||||
</span>
|
||||
}
|
||||
className="pt-2 px-2"
|
||||
indicator={({ isOpen }) => <CustomIndicator isOpen={isOpen} />}
|
||||
>
|
||||
<div className="text-sm sm:text-base text-foreground-600 leading-relaxed space-y-2">
|
||||
{faq.answer}
|
||||
</div>
|
||||
</AccordionItem>
|
||||
))}
|
||||
</Accordion>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function Faq() {
|
||||
return <FaqClient />;
|
||||
}
|
||||
@@ -68,7 +68,7 @@ export const BasicInfoTab: React.FC<BasicInfoTabProps> = ({
|
||||
>
|
||||
<SelectItem key="none" value="none">{t('None')}</SelectItem>
|
||||
<SelectItem key="apikey" value="apikey">{t('API Key')}</SelectItem>
|
||||
<SelectItem key="bearer-token" value="bearer-token">{t('Bearer Token')}</SelectItem>
|
||||
<SelectItem key="token" value="token">{t('Bearer Token')}</SelectItem>
|
||||
</Select>
|
||||
|
||||
{/* auth config input fields */}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import React from 'react';
|
||||
import { useTranslation } from '@/shared/lib/useTranslation';
|
||||
import { MCPServiceFormData } from '@/types/mcp-service';
|
||||
import dynamic from 'next/dynamic';
|
||||
import React from "react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { MCPServiceFormData } from "@/types/mcp-service";
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
// dynamic import MDEditor to avoid SSR problem
|
||||
const MDEditor = dynamic(
|
||||
() => import('@uiw/react-md-editor').then((mod) => mod.default),
|
||||
() => import("@uiw/react-md-editor").then((mod) => mod.default),
|
||||
{ ssr: false }
|
||||
);
|
||||
|
||||
@@ -18,29 +18,30 @@ interface DescriptionTabProps {
|
||||
|
||||
export const DescriptionTab: React.FC<DescriptionTabProps> = ({
|
||||
formData,
|
||||
onInputChange
|
||||
onInputChange,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const handleMarkdownChange = (value?: string) => {
|
||||
onInputChange('long_description', value || '');
|
||||
onInputChange("long_description", value || "");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4 h-full">
|
||||
<div className="w-full h-full">
|
||||
<MDEditor
|
||||
value={formData.long_description || ''}
|
||||
value={formData.long_description || ""}
|
||||
onChange={handleMarkdownChange}
|
||||
preview="live"
|
||||
hideToolbar={false}
|
||||
visibleDragbar={true}
|
||||
textareaProps={{
|
||||
placeholder: t('Detailed description of the service (supports Markdown)'),
|
||||
placeholder: t("Detailed description of the service"),
|
||||
style: {
|
||||
fontSize: 14,
|
||||
lineHeight: 1.5,
|
||||
fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace',
|
||||
fontFamily:
|
||||
'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace',
|
||||
},
|
||||
}}
|
||||
height="100%"
|
||||
@@ -49,4 +50,4 @@ export const DescriptionTab: React.FC<DescriptionTabProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -1,15 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import React from 'react';
|
||||
import {
|
||||
Input,
|
||||
Select,
|
||||
SelectItem,
|
||||
} from '@nextui-org/react';
|
||||
import { useTranslation } from '@/shared/lib/useTranslation';
|
||||
import { MCPServiceFormData } from '@/types/mcp-service';
|
||||
import { getCurrencySymbol } from '@/shared/utils/currency';
|
||||
import { ChargeType } from '@/shared/types/marketplace';
|
||||
import React from "react";
|
||||
import { Input, Select, SelectItem } from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { MCPServiceFormData } from "@/types/mcp-service";
|
||||
import { getCurrencySymbol } from "@/shared/utils/currency";
|
||||
import { ChargeType } from "@/shared/types/marketplace";
|
||||
|
||||
interface PricingTabProps {
|
||||
formData: MCPServiceFormData;
|
||||
@@ -18,52 +14,111 @@ interface PricingTabProps {
|
||||
|
||||
export const PricingTab: React.FC<PricingTabProps> = ({
|
||||
formData,
|
||||
onInputChange
|
||||
onInputChange,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Select
|
||||
label={t('Charge Type')}
|
||||
label={t("Charge Type")}
|
||||
selectedKeys={formData.charge_type ? [formData.charge_type] : []}
|
||||
onSelectionChange={(keys) => {
|
||||
const selectedKey = Array.from(keys)[0] as string;
|
||||
onInputChange('charge_type', selectedKey);
|
||||
onInputChange("charge_type", selectedKey);
|
||||
}}
|
||||
renderValue={() => {
|
||||
const selectedKey = formData.charge_type || ChargeType.PerCall;
|
||||
if (selectedKey === ChargeType.Free) return t('Free');
|
||||
return t(selectedKey === ChargeType.PerCall ? 'Per Call' : 'Per Token');
|
||||
if (selectedKey === ChargeType.Free) return t("Free");
|
||||
return t(
|
||||
selectedKey === ChargeType.PerCall
|
||||
? "Per Call"
|
||||
: "Per Million Tokens"
|
||||
);
|
||||
}}
|
||||
>
|
||||
<SelectItem key="free" value={ChargeType.Free}>
|
||||
<div className="flex flex-col">
|
||||
<span>{t('Free')}</span>
|
||||
<span className="text-xs text-gray-500">{t('No charge for API calls')}</span>
|
||||
<span>{t("Free")}</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{t("No charge for API calls")}
|
||||
</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem key="per_call" value={ChargeType.PerCall}>
|
||||
<div className="flex flex-col">
|
||||
<span>{t('Per Call')}</span>
|
||||
<span className="text-xs text-gray-500">{t('Fixed price per API call')}</span>
|
||||
<span>{t("Per Call")}</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{t("Fixed price per API call")}
|
||||
</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
|
||||
<SelectItem key="per_token" value={ChargeType.PerToken}>
|
||||
<div className="flex flex-col">
|
||||
<span>{t("Per Million Tokens")}</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{t("Price per million tokens consumed")}
|
||||
</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
</Select>
|
||||
|
||||
{formData.charge_type !== ChargeType.Free && (
|
||||
<Input
|
||||
label={t('Price')}
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
value={formData.price || ''}
|
||||
onChange={(e) => onInputChange('price', e.target.value)}
|
||||
description={t('Price per unit (call or token)')}
|
||||
startContent={<span className="text-gray-500 leading-[20px]">{getCurrencySymbol()}</span>}
|
||||
/>
|
||||
<>
|
||||
{formData.charge_type === ChargeType.PerToken ? (
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
label={t("Input Token Price")}
|
||||
value={formData.input_token_price || ""}
|
||||
onChange={(e) =>
|
||||
onInputChange("input_token_price", e.target.value)
|
||||
}
|
||||
placeholder={t("Price per million input tokens")}
|
||||
startContent={
|
||||
<span className="text-gray-500 leading-[20px]">
|
||||
{getCurrencySymbol()}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
label={t("Output Token Price")}
|
||||
value={formData.output_token_price || ""}
|
||||
onChange={(e) =>
|
||||
onInputChange("output_token_price", e.target.value)
|
||||
}
|
||||
placeholder={t("Price per million output tokens")}
|
||||
startContent={
|
||||
<span className="text-gray-500 leading-[20px]">
|
||||
{getCurrencySymbol()}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<Input
|
||||
label={t("Price")}
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
value={formData.price || ""}
|
||||
onChange={(e) => onInputChange("price", e.target.value)}
|
||||
description={t("Price per API call")}
|
||||
startContent={
|
||||
<span className="text-gray-500 leading-[20px]">
|
||||
{getCurrencySymbol()}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -1,10 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import React from 'react';
|
||||
import { Input, Select, SelectItem, Button } from '@nextui-org/react';
|
||||
import { useTranslation } from '@/shared/lib/useTranslation';
|
||||
import { ServiceFilters } from '@/types/mcp-service';
|
||||
import { Search, Plus } from 'lucide-react';
|
||||
import React from "react";
|
||||
import { Input, Select, SelectItem, Button } from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { ServiceFilters } from "@/types/mcp-service";
|
||||
import { Search, Plus } from "lucide-react";
|
||||
|
||||
interface ServiceFiltersBarProps {
|
||||
filters: ServiceFilters;
|
||||
@@ -16,7 +16,7 @@ interface ServiceFiltersBarProps {
|
||||
export const ServiceFiltersBar: React.FC<ServiceFiltersBarProps> = ({
|
||||
filters,
|
||||
onFiltersChange,
|
||||
onImportOpenAPI
|
||||
onImportOpenAPI,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -24,20 +24,20 @@ export const ServiceFiltersBar: React.FC<ServiceFiltersBarProps> = ({
|
||||
onFiltersChange({ ...filters, search: value });
|
||||
};
|
||||
|
||||
|
||||
const handleStatusChange = (value: string) => {
|
||||
onFiltersChange({ ...filters, status: value });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col sm:flex-row gap-4 mb-6">
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
<div className="flex-1">
|
||||
<Button
|
||||
color="primary"
|
||||
onPress={onImportOpenAPI}
|
||||
startContent={<Plus size={16} />}
|
||||
size="sm"
|
||||
>
|
||||
{t('Add Service')}
|
||||
{t("Add Service")}
|
||||
</Button>
|
||||
{/* <Input
|
||||
placeholder={t('Search services...')}
|
||||
@@ -74,10 +74,7 @@ export const ServiceFiltersBar: React.FC<ServiceFiltersBarProps> = ({
|
||||
</SelectItem>
|
||||
))}
|
||||
</Select> */}
|
||||
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React from 'react';
|
||||
import React from "react";
|
||||
import {
|
||||
Table,
|
||||
TableHeader,
|
||||
@@ -12,19 +12,19 @@ import {
|
||||
Button,
|
||||
Tooltip,
|
||||
Pagination,
|
||||
Spinner
|
||||
} from '@nextui-org/react';
|
||||
import { useTranslation } from '@/shared/lib/useTranslation';
|
||||
import { EnabledEnum, MCPService } from '@/types/mcp-service';
|
||||
Spinner,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { EnabledEnum, MCPService } from "@/types/mcp-service";
|
||||
import {
|
||||
Trash2,
|
||||
Zap,
|
||||
PencilIcon,
|
||||
CircleCheckIcon,
|
||||
BanIcon,
|
||||
} from 'lucide-react';
|
||||
import { ChargeType } from '@/shared/types/marketplace';
|
||||
import { Price } from '@/shared/components/marketplace/Price';
|
||||
} from "lucide-react";
|
||||
import { ChargeType } from "@/shared/types/marketplace";
|
||||
import { Price } from "@/shared/components/marketplace/Price";
|
||||
|
||||
interface ServiceTableProps {
|
||||
services: MCPService[];
|
||||
@@ -58,22 +58,29 @@ export const ServiceTable: React.FC<ServiceTableProps> = ({
|
||||
const items = services;
|
||||
|
||||
const getStatusColor = (enabled: number) => {
|
||||
return enabled === EnabledEnum.Online ? 'success' : 'danger';
|
||||
return enabled === EnabledEnum.Online ? "success" : "danger";
|
||||
};
|
||||
|
||||
const handleEdit = React.useCallback(
|
||||
(service: MCPService) => {
|
||||
onEdit(service);
|
||||
},
|
||||
[onEdit]
|
||||
);
|
||||
|
||||
const handleEdit = React.useCallback((service: MCPService) => {
|
||||
onEdit(service);
|
||||
}, [onEdit]);
|
||||
|
||||
const handleDelete = React.useCallback((service: MCPService) => {
|
||||
onDelete(service);
|
||||
}, [onDelete]);
|
||||
|
||||
const handleToggleStatus = React.useCallback((service: MCPService) => {
|
||||
onToggleStatus(service);
|
||||
}, [onToggleStatus]);
|
||||
const handleDelete = React.useCallback(
|
||||
(service: MCPService) => {
|
||||
onDelete(service);
|
||||
},
|
||||
[onDelete]
|
||||
);
|
||||
|
||||
const handleToggleStatus = React.useCallback(
|
||||
(service: MCPService) => {
|
||||
onToggleStatus(service);
|
||||
},
|
||||
[onToggleStatus]
|
||||
);
|
||||
|
||||
if (loading && services.length === 0) {
|
||||
return (
|
||||
@@ -96,7 +103,7 @@ export const ServiceTable: React.FC<ServiceTableProps> = ({
|
||||
<div className="flex w-full justify-center">
|
||||
<Pagination
|
||||
showControls
|
||||
variant='light'
|
||||
variant="light"
|
||||
color="primary"
|
||||
page={currentPage}
|
||||
total={pages}
|
||||
@@ -107,17 +114,17 @@ export const ServiceTable: React.FC<ServiceTableProps> = ({
|
||||
}
|
||||
>
|
||||
<TableHeader>
|
||||
<TableColumn>{t('Service Name')}</TableColumn>
|
||||
<TableColumn>{t('API Endpoint')}</TableColumn>
|
||||
<TableColumn>{t('Status')}</TableColumn>
|
||||
<TableColumn>{t('Pricing')}</TableColumn>
|
||||
<TableColumn className='w-20'>{t('Actions')}</TableColumn>
|
||||
<TableColumn>{t("Service Name")}</TableColumn>
|
||||
<TableColumn>{t("API Endpoint")}</TableColumn>
|
||||
<TableColumn>{t("Status")}</TableColumn>
|
||||
<TableColumn>{t("Pricing")}</TableColumn>
|
||||
<TableColumn className="w-20">{t("Actions")}</TableColumn>
|
||||
</TableHeader>
|
||||
<TableBody
|
||||
items={items}
|
||||
isLoading={loading}
|
||||
loadingContent={<Spinner />}
|
||||
emptyContent={t('No services found')}
|
||||
emptyContent={t("No services found")}
|
||||
>
|
||||
{(service) => (
|
||||
<TableRow key={service.id}>
|
||||
@@ -134,17 +141,22 @@ export const ServiceTable: React.FC<ServiceTableProps> = ({
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
{t(service.enabled === 1 ? 'Online' : 'Offline')}
|
||||
{t(service.enabled === 1 ? "Online" : "Offline")}
|
||||
</Chip>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Price price={service.price} charge_type={service.charge_type} />
|
||||
<Price
|
||||
price={service.price}
|
||||
charge_type={service.charge_type}
|
||||
input_token_price={service.input_token_price}
|
||||
output_token_price={service.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="relative flex items-center gap-2">
|
||||
<Tooltip content={t('Edit')} closeDelay={0}>
|
||||
<Tooltip content={t("Edit")} closeDelay={0} disableAnimation>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
@@ -155,22 +167,40 @@ export const ServiceTable: React.FC<ServiceTableProps> = ({
|
||||
</Button>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip content={service.enabled === EnabledEnum.Online ? t('Take Offline') : t('Bring Online')} closeDelay={0} >
|
||||
<Tooltip
|
||||
content={
|
||||
service.enabled === EnabledEnum.Online
|
||||
? t("Take Offline")
|
||||
: t("Bring Online")
|
||||
}
|
||||
closeDelay={0}
|
||||
disableAnimation
|
||||
>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
color={service.enabled === EnabledEnum.Online ? 'danger' : 'success'}
|
||||
color={
|
||||
service.enabled === EnabledEnum.Online
|
||||
? "danger"
|
||||
: "success"
|
||||
}
|
||||
onPress={() => handleToggleStatus(service)}
|
||||
>
|
||||
{service.enabled === EnabledEnum.Online ?
|
||||
<BanIcon className="w-4 h-4" /> :
|
||||
{service.enabled === EnabledEnum.Online ? (
|
||||
<BanIcon className="w-4 h-4" />
|
||||
) : (
|
||||
<CircleCheckIcon className="w-4 h-4" />
|
||||
}
|
||||
)}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip content={t('Delete Service')} color="danger" closeDelay={0}>
|
||||
<Tooltip
|
||||
content={t("Delete Service")}
|
||||
color="danger"
|
||||
closeDelay={0}
|
||||
disableAnimation
|
||||
>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
@@ -189,4 +219,4 @@ export const ServiceTable: React.FC<ServiceTableProps> = ({
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -38,7 +38,8 @@ export const ToolsTab: React.FC<ToolsTabProps> = ({
|
||||
removeWrapper
|
||||
>
|
||||
<TableHeader>
|
||||
<TableColumn className='w-1/3'>{t('Tool Name')}</TableColumn>
|
||||
<TableColumn className='w-1/4'>{t('Tool Name')}</TableColumn>
|
||||
<TableColumn className='w-1/4'>{t('Tool URL')}</TableColumn>
|
||||
<TableColumn>{t('Description')}</TableColumn>
|
||||
</TableHeader>
|
||||
<TableBody emptyContent={t('No tools added yet. Add your first tool using the input above.')}>
|
||||
@@ -49,7 +50,13 @@ export const ToolsTab: React.FC<ToolsTabProps> = ({
|
||||
<TableCell>
|
||||
<Input
|
||||
value={tool.name}
|
||||
// onChange={(e) => handleToolChange(index, 'name', e.target.value)}
|
||||
size="sm"
|
||||
isDisabled
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input
|
||||
value={tool.url}
|
||||
size="sm"
|
||||
isDisabled
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import {
|
||||
Input,
|
||||
Button,
|
||||
AccordionItem,
|
||||
Accordion,
|
||||
Switch,
|
||||
} from "@nextui-org/react";
|
||||
import { Eye, EyeOff } from "lucide-react";
|
||||
import { AlipayConfig } from "@/types/payment";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
|
||||
interface AlipayConfigFormProps {
|
||||
config: AlipayConfig;
|
||||
onSave: (config: AlipayConfig) => void;
|
||||
onEnable: (channelId: string) => Promise<boolean>;
|
||||
onDisable: (channelId: string) => Promise<boolean>;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export const AlipayConfigForm: React.FC<AlipayConfigFormProps> = ({
|
||||
config,
|
||||
onSave,
|
||||
onEnable,
|
||||
onDisable,
|
||||
isLoading = false,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [formData, setFormData] = useState<AlipayConfig>(config);
|
||||
const [showAppPrivateKey, setShowAppPrivateKey] = useState(false);
|
||||
const [showAlipayPublicKey, setShowAlipayPublicKey] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setFormData(config);
|
||||
}, [config]);
|
||||
|
||||
const handleInputChange = (
|
||||
field: keyof AlipayConfig,
|
||||
value: string | boolean
|
||||
) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
[field]: value,
|
||||
}));
|
||||
};
|
||||
const handleEnableDisable = async (value: boolean) => {
|
||||
let result: boolean | null = null;
|
||||
if (value) {
|
||||
result = await onEnable("alipay");
|
||||
} else {
|
||||
result = await onDisable("alipay");
|
||||
}
|
||||
if (result) {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
is_enabled: value,
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
const isFormValid =
|
||||
formData.app_id.trim() !== "" &&
|
||||
formData.app_private_key.trim() !== "" &&
|
||||
formData.alipay_public_key.trim() !== "";
|
||||
|
||||
return (
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
defaultExpandedKeys={["alipay-config"]}
|
||||
className="px-0"
|
||||
>
|
||||
<AccordionItem
|
||||
key="alipay-config"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold">
|
||||
{t("Alipay Configuration")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure Alipay payment interface")}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
isSelected={formData.is_enabled || false}
|
||||
onValueChange={handleEnableDisable}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{/* App ID */}
|
||||
<Input
|
||||
label={t("App ID")}
|
||||
placeholder={t("Alipay App ID")}
|
||||
value={formData.app_id}
|
||||
onChange={(e) => handleInputChange("app_id", e.target.value)}
|
||||
isRequired
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
/>
|
||||
|
||||
{/* App Private Key */}
|
||||
<Input
|
||||
label={t("App Private Key")}
|
||||
placeholder={t("Alipay App Private Key")}
|
||||
value={formData.app_private_key}
|
||||
onChange={(e) =>
|
||||
handleInputChange("app_private_key", e.target.value)
|
||||
}
|
||||
type={showAppPrivateKey ? "text" : "password"}
|
||||
endContent={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowAppPrivateKey(!showAppPrivateKey)}
|
||||
className="focus:outline-none"
|
||||
>
|
||||
{showAppPrivateKey ? (
|
||||
<EyeOff className="w-4 h-4 text-gray-400" />
|
||||
) : (
|
||||
<Eye className="w-4 h-4 text-gray-400" />
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
isRequired
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
/>
|
||||
|
||||
{/* Alipay Public Key */}
|
||||
<Input
|
||||
label={t("Alipay Public Key")}
|
||||
placeholder={t("Alipay public key for verification")}
|
||||
value={formData.alipay_public_key || ""}
|
||||
onChange={(e) =>
|
||||
handleInputChange("alipay_public_key", e.target.value)
|
||||
}
|
||||
type={showAlipayPublicKey ? "text" : "password"}
|
||||
isRequired
|
||||
endContent={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowAlipayPublicKey(!showAlipayPublicKey)}
|
||||
className="focus:outline-none"
|
||||
>
|
||||
{showAlipayPublicKey ? (
|
||||
<EyeOff className="w-4 h-4 text-gray-400" />
|
||||
) : (
|
||||
<Eye className="w-4 h-4 text-gray-400" />
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
{formData.is_enabled && (
|
||||
<div className="flex gap-3 py-4">
|
||||
<Button
|
||||
color="primary"
|
||||
variant="solid"
|
||||
onPress={handleSave}
|
||||
isLoading={isLoading}
|
||||
isDisabled={!isFormValid}
|
||||
size="sm"
|
||||
>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,177 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import {
|
||||
Input,
|
||||
Button,
|
||||
AccordionItem,
|
||||
Accordion,
|
||||
Switch,
|
||||
} from "@nextui-org/react";
|
||||
import { Eye, EyeOff } from "lucide-react";
|
||||
import { StripeConfig } from "@/types/payment";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
|
||||
interface StripeConfigFormProps {
|
||||
config: StripeConfig;
|
||||
onSave: (config: StripeConfig) => void;
|
||||
onEnable: (channelId: string) => Promise<boolean>;
|
||||
onDisable: (channelId: string) => Promise<boolean>;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export const StripeConfigForm: React.FC<StripeConfigFormProps> = ({
|
||||
config,
|
||||
onSave,
|
||||
onEnable,
|
||||
onDisable,
|
||||
isLoading = false,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [formData, setFormData] = useState<StripeConfig>(config);
|
||||
const [showSecretKey, setShowSecretKey] = useState(false);
|
||||
const [showWebhookSecret, setShowWebhookSecret] = useState(false);
|
||||
useEffect(() => {
|
||||
setFormData(config);
|
||||
}, [config]);
|
||||
|
||||
const handleInputChange = (
|
||||
field: keyof StripeConfig,
|
||||
value: string | boolean
|
||||
) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
[field]: value,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleEnableDisable = async (value: boolean) => {
|
||||
let result: boolean | null = null;
|
||||
if (value) {
|
||||
result = await onEnable("stripe");
|
||||
} else {
|
||||
result = await onDisable("stripe");
|
||||
}
|
||||
if (result) {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
is_enabled: value,
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
const isFormValid =
|
||||
formData.secret.trim() !== "" && formData.webhook_secret.trim() !== "";
|
||||
|
||||
return (
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
defaultExpandedKeys={["stripe-config"]}
|
||||
className="px-0"
|
||||
>
|
||||
<AccordionItem
|
||||
key="stripe-config"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold">
|
||||
{t("Stripe Configuration")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure Stripe payment interface")}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
isSelected={formData.is_enabled || false}
|
||||
onValueChange={handleEnableDisable}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{/* Secret Key */}
|
||||
<Input
|
||||
label={t("Secret Key")}
|
||||
placeholder="sk_test_... or sk_live_..."
|
||||
description={t("Stripe secret key for server-side API calls")}
|
||||
value={formData.secret}
|
||||
onChange={(e) => handleInputChange("secret", e.target.value)}
|
||||
type={showSecretKey ? "text" : "password"}
|
||||
endContent={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowSecretKey(!showSecretKey)}
|
||||
className="focus:outline-none"
|
||||
>
|
||||
{showSecretKey ? (
|
||||
<EyeOff className="w-4 h-4 text-gray-400" />
|
||||
) : (
|
||||
<Eye className="w-4 h-4 text-gray-400" />
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
isRequired
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
/>
|
||||
|
||||
{/* Webhook Secret (Optional) */}
|
||||
<Input
|
||||
label={t("Webhook Secret")}
|
||||
placeholder="whsec_..."
|
||||
description={t(
|
||||
"Webhook signing secret for verifying Stripe events"
|
||||
)}
|
||||
value={formData.webhook_secret || ""}
|
||||
onChange={(e) =>
|
||||
handleInputChange("webhook_secret", e.target.value)
|
||||
}
|
||||
type={showWebhookSecret ? "text" : "password"}
|
||||
isRequired
|
||||
endContent={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowWebhookSecret(!showWebhookSecret)}
|
||||
className="focus:outline-none"
|
||||
>
|
||||
{showWebhookSecret ? (
|
||||
<EyeOff className="w-4 h-4 text-gray-400" />
|
||||
) : (
|
||||
<Eye className="w-4 h-4 text-gray-400" />
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
{formData.is_enabled && (
|
||||
<div className="flex gap-3 py-4">
|
||||
<Button
|
||||
color="primary"
|
||||
variant="solid"
|
||||
onPress={handleSave}
|
||||
isLoading={isLoading}
|
||||
isDisabled={!isFormValid}
|
||||
size="sm"
|
||||
>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,140 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import {
|
||||
Input,
|
||||
Button,
|
||||
AccordionItem,
|
||||
Accordion,
|
||||
Switch,
|
||||
} from "@nextui-org/react";
|
||||
import { WechatConfig } from "@/types/payment";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
|
||||
interface WechatConfigFormProps {
|
||||
config: WechatConfig;
|
||||
onSave: (config: WechatConfig) => void;
|
||||
onEnable: (channelId: string) => Promise<boolean>;
|
||||
onDisable: (channelId: string) => Promise<boolean>;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export const WechatConfigForm: React.FC<WechatConfigFormProps> = ({
|
||||
config,
|
||||
onSave,
|
||||
onEnable,
|
||||
onDisable,
|
||||
isLoading = false,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [formData, setFormData] = useState<WechatConfig>(config);
|
||||
|
||||
useEffect(() => {
|
||||
setFormData(config);
|
||||
}, [config]);
|
||||
|
||||
const handleInputChange = (
|
||||
field: keyof WechatConfig,
|
||||
value: string | boolean
|
||||
) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
[field]: value,
|
||||
}));
|
||||
};
|
||||
const handleEnableDisable = async (value: boolean) => {
|
||||
let result: boolean | null = null;
|
||||
if (value) {
|
||||
result = await onEnable("wechat");
|
||||
} else {
|
||||
result = await onDisable("wechat");
|
||||
}
|
||||
if (result) {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
is_enabled: value,
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = () => {
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
const isFormValid =
|
||||
formData.app_id.trim() !== "" && formData.mch_id.trim() !== "";
|
||||
|
||||
return (
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
defaultExpandedKeys={["wechat-config"]}
|
||||
className="px-0"
|
||||
>
|
||||
<AccordionItem
|
||||
key="wechat-config"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold">
|
||||
{t("WeChat Configuration")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure WeChat payment interface")}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
isSelected={formData.is_enabled || false}
|
||||
onValueChange={handleEnableDisable}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{/* App ID */}
|
||||
<Input
|
||||
label={t("App ID")}
|
||||
placeholder={t("WeChat App ID")}
|
||||
value={formData.app_id}
|
||||
onChange={(e) => handleInputChange("app_id", e.target.value)}
|
||||
isRequired
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
/>
|
||||
|
||||
{/* Merchant ID */}
|
||||
<Input
|
||||
label={t("Merchant ID")}
|
||||
placeholder={t("WeChat Merchant ID")}
|
||||
value={formData.mch_id}
|
||||
onChange={(e) => handleInputChange("mch_id", e.target.value)}
|
||||
isRequired
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
{formData.is_enabled && (
|
||||
<div className="flex gap-3 py-4">
|
||||
<Button
|
||||
color="primary"
|
||||
variant="solid"
|
||||
onPress={handleSave}
|
||||
isLoading={isLoading}
|
||||
isDisabled={!isFormValid}
|
||||
size="sm"
|
||||
>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,138 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { Button, AccordionItem, Accordion } from "@nextui-org/react";
|
||||
import MDEditor, { commands } from "@uiw/react-md-editor";
|
||||
import { PlatformConfig } from "@/shared/types/system";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { calculateFileSha256 } from "@/shared/utils/crypto";
|
||||
import "@uiw/react-md-editor/markdown-editor.css";
|
||||
import "@uiw/react-markdown-preview/markdown.css";
|
||||
|
||||
interface AboutPageSettingsProps {
|
||||
config: PlatformConfig;
|
||||
onAboutSave: (aboutContent: string) => Promise<void>;
|
||||
onImageUpload?: (file: File, sha256?: string) => Promise<string>;
|
||||
isAboutLoading?: boolean;
|
||||
}
|
||||
|
||||
export const AboutPageSettings: React.FC<AboutPageSettingsProps> = ({
|
||||
config,
|
||||
onAboutSave,
|
||||
onImageUpload,
|
||||
isAboutLoading = false,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [aboutContent, setAboutContent] = useState(config.about_page || "");
|
||||
|
||||
useEffect(() => {
|
||||
setAboutContent(config.about_page || "");
|
||||
}, [config.about_page]);
|
||||
|
||||
const handleAboutSave = async () => {
|
||||
await onAboutSave(aboutContent);
|
||||
};
|
||||
|
||||
const handleImageUpload = async (file: File): Promise<string> => {
|
||||
try {
|
||||
// 计算文件的 SHA256 哈希值
|
||||
const sha256 = await calculateFileSha256(file);
|
||||
return await onImageUpload!(file, sha256);
|
||||
} catch (error) {
|
||||
console.error("Image upload failed:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 justify-between h-full">
|
||||
<div className="flex-1">
|
||||
<MDEditor
|
||||
value={aboutContent}
|
||||
onChange={(value?: string) => setAboutContent(value || "")}
|
||||
preview="live"
|
||||
hideToolbar={false}
|
||||
visibleDragbar={false}
|
||||
data-color-mode="light"
|
||||
textareaProps={{
|
||||
placeholder: t("Enter about page content (supports Markdown)"),
|
||||
style: {
|
||||
fontSize: 14,
|
||||
lineHeight: 1.6,
|
||||
fontFamily:
|
||||
'ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
|
||||
},
|
||||
}}
|
||||
height="100%"
|
||||
commands={[
|
||||
// 默认命令
|
||||
commands.bold,
|
||||
commands.italic,
|
||||
commands.strikethrough,
|
||||
commands.hr,
|
||||
commands.title,
|
||||
commands.divider,
|
||||
commands.link,
|
||||
commands.quote,
|
||||
commands.code,
|
||||
commands.codeBlock,
|
||||
commands.comment,
|
||||
commands.divider,
|
||||
commands.unorderedListCommand,
|
||||
commands.orderedListCommand,
|
||||
commands.checkedListCommand,
|
||||
commands.divider,
|
||||
// 自定义图片上传命令
|
||||
{
|
||||
name: "image-upload",
|
||||
keyCommand: "image-upload",
|
||||
buttonProps: {
|
||||
"aria-label": "Upload image",
|
||||
title: "Upload image",
|
||||
},
|
||||
icon: (
|
||||
<svg width="12" height="12" viewBox="0 0 20 20">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M15 9c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm4-7H1c-.55 0-1 .45-1 1v14c0 .55.45 1 1 1h18c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zM2 17l4.5-6 3.5 4.51 2.5-3.01L17 17H2z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
execute: (state, api) => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.accept = "image/*";
|
||||
input.onchange = async (e) => {
|
||||
const file = (e.target as HTMLInputElement).files?.[0];
|
||||
if (file) {
|
||||
try {
|
||||
const dataUrl = await handleImageUpload(file);
|
||||
const imageMarkdown = ``;
|
||||
api.replaceSelection(imageMarkdown);
|
||||
} catch (error) {
|
||||
console.error("Image upload failed:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* About Save Button */}
|
||||
<div className="flex gap-3 pb-4">
|
||||
<Button
|
||||
color="primary"
|
||||
variant="solid"
|
||||
onPress={handleAboutSave}
|
||||
isLoading={isAboutLoading}
|
||||
size="sm"
|
||||
>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,9 +1,9 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Input, Button, AccordionItem, Accordion } from '@nextui-org/react';
|
||||
import { Eye, EyeOff } from 'lucide-react';
|
||||
import { AdminConfig } from '@/types/system';
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Input, Button, AccordionItem, Accordion } from "@nextui-org/react";
|
||||
import { Eye, EyeOff } from "lucide-react";
|
||||
import { AdminConfig } from "@/types/system";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
|
||||
interface AdminConfigFormProps {
|
||||
@@ -20,20 +20,20 @@ export const AdminConfigForm: React.FC<AdminConfigFormProps> = ({
|
||||
const { t } = useTranslation();
|
||||
const [formData, setFormData] = useState<AdminConfig>(config);
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
||||
useEffect(() => {
|
||||
setFormData({
|
||||
...config,
|
||||
password: '',
|
||||
password: "",
|
||||
});
|
||||
setConfirmPassword('');
|
||||
setConfirmPassword("");
|
||||
}, [config]);
|
||||
|
||||
const handleInputChange = (field: keyof AdminConfig, value: string) => {
|
||||
setFormData(prev => ({
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
[field]: value
|
||||
[field]: value,
|
||||
}));
|
||||
};
|
||||
|
||||
@@ -42,41 +42,53 @@ export const AdminConfigForm: React.FC<AdminConfigFormProps> = ({
|
||||
};
|
||||
|
||||
const isFormValid =
|
||||
formData.username.trim() !== '' &&
|
||||
formData.password.trim() !== '' &&
|
||||
formData.username.trim() !== "" &&
|
||||
formData.password?.trim() !== "" &&
|
||||
formData.password === confirmPassword &&
|
||||
formData.password.length >= 8;
|
||||
formData.password?.length >= 8;
|
||||
|
||||
const passwordsMatch = formData.password === confirmPassword;
|
||||
|
||||
return (
|
||||
<Accordion variant='splitted' itemClasses={{
|
||||
base: 'shadow-none border-1',
|
||||
}} defaultExpandedKeys={['admin-config']} className='px-0'>
|
||||
<AccordionItem key="admin-config" title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<h3 className="text-lg font-semibold">{t('Administrator Account')}</h3>
|
||||
<p className="text-sm text-gray-500">{t('Configure administrator login credentials')}</p>
|
||||
</div>
|
||||
}>
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
defaultExpandedKeys={["admin-config"]}
|
||||
className="px-0"
|
||||
>
|
||||
<AccordionItem
|
||||
key="admin-config"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<h3 className="text-lg font-semibold">
|
||||
{t("Administrator Account")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure administrator login credentials")}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{/* admin username */}
|
||||
<Input
|
||||
label={t('Administrator Username')}
|
||||
placeholder={t('Enter administrator username')}
|
||||
description={t('Username for administrator login')}
|
||||
label={t("Administrator Username")}
|
||||
placeholder={t("Enter administrator username")}
|
||||
description={t("Username for administrator login")}
|
||||
value={formData.username}
|
||||
onChange={(e) => handleInputChange('username', e.target.value)}
|
||||
onChange={(e) => handleInputChange("username", e.target.value)}
|
||||
isRequired
|
||||
/>
|
||||
|
||||
{/* admin password */}
|
||||
<Input
|
||||
label={t('Administrator Password')}
|
||||
placeholder={t('Enter administrator password')}
|
||||
description={t('Password must be at least 8 characters long')}
|
||||
label={t("Administrator Password")}
|
||||
placeholder={t("Enter administrator password")}
|
||||
description={t("Password must be at least 8 characters long")}
|
||||
value={formData.password}
|
||||
onChange={(e) => handleInputChange('password', e.target.value)}
|
||||
onChange={(e) => handleInputChange("password", e.target.value)}
|
||||
type={showPassword ? "text" : "password"}
|
||||
endContent={
|
||||
<button
|
||||
@@ -92,16 +104,24 @@ export const AdminConfigForm: React.FC<AdminConfigFormProps> = ({
|
||||
</button>
|
||||
}
|
||||
isRequired
|
||||
autoComplete='new-password'
|
||||
color={formData.password.length > 0 && formData.password.length < 8 ? "danger" : "default"}
|
||||
errorMessage={formData.password.length > 0 && formData.password.length < 8 ? t('Password must be at least 8 characters') : ""}
|
||||
autoComplete="new-password"
|
||||
color={
|
||||
formData.password?.length > 0 && formData.password?.length < 8
|
||||
? "danger"
|
||||
: "default"
|
||||
}
|
||||
errorMessage={
|
||||
formData.password?.length > 0 && formData.password?.length < 8
|
||||
? t("Password must be at least 8 characters")
|
||||
: ""
|
||||
}
|
||||
/>
|
||||
|
||||
{/* confirm password */}
|
||||
<Input
|
||||
label={t('Confirm Password')}
|
||||
placeholder={t('Confirm administrator password')}
|
||||
description={t('Re-enter the password to confirm')}
|
||||
label={t("Confirm Password")}
|
||||
placeholder={t("Confirm administrator password")}
|
||||
description={t("Re-enter the password to confirm")}
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
type={showConfirmPassword ? "text" : "password"}
|
||||
@@ -118,10 +138,18 @@ export const AdminConfigForm: React.FC<AdminConfigFormProps> = ({
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
autoComplete='new-password'
|
||||
autoComplete="new-password"
|
||||
isRequired
|
||||
color={confirmPassword.length > 0 && !passwordsMatch ? "danger" : "default"}
|
||||
errorMessage={confirmPassword.length > 0 && !passwordsMatch ? t('Passwords do not match') : ""}
|
||||
color={
|
||||
confirmPassword?.length > 0 && !passwordsMatch
|
||||
? "danger"
|
||||
: "default"
|
||||
}
|
||||
errorMessage={
|
||||
confirmPassword?.length > 0 && !passwordsMatch
|
||||
? t("Passwords do not match")
|
||||
: ""
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -133,12 +161,12 @@ export const AdminConfigForm: React.FC<AdminConfigFormProps> = ({
|
||||
onPress={handleSave}
|
||||
isLoading={isLoading}
|
||||
isDisabled={!isFormValid}
|
||||
size='sm'
|
||||
size="sm"
|
||||
>
|
||||
{t('Save')}
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { EmailConfigForm } from "./EmailConfigForm";
|
||||
import { AdminConfig, EmailConfig } from "@/types/system";
|
||||
import { AdminConfigForm } from "./AdminConfigForm";
|
||||
|
||||
interface EmailAndAdminSettingsProps {
|
||||
emailConfig: EmailConfig;
|
||||
adminConfig: AdminConfig;
|
||||
onSaveEmailConfig: (config: EmailConfig) => void;
|
||||
onSaveAdminConfig: (config: AdminConfig) => void;
|
||||
isLoading?: boolean;
|
||||
isAdminLoading?: boolean;
|
||||
}
|
||||
|
||||
export const EmailAndAdminSettings: React.FC<EmailAndAdminSettingsProps> = ({
|
||||
emailConfig,
|
||||
adminConfig,
|
||||
onSaveEmailConfig,
|
||||
onSaveAdminConfig,
|
||||
isLoading = false,
|
||||
isAdminLoading = false,
|
||||
}) => {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<EmailConfigForm
|
||||
config={emailConfig}
|
||||
onSave={onSaveEmailConfig}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
<AdminConfigForm
|
||||
config={adminConfig}
|
||||
onSave={onSaveAdminConfig}
|
||||
isLoading={isAdminLoading}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,165 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import {
|
||||
AccordionItem,
|
||||
Accordion,
|
||||
Textarea,
|
||||
Button,
|
||||
Switch,
|
||||
Alert,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { EmbeddedHtmlConfig } from "@/shared/types/system";
|
||||
|
||||
interface EmbeddedHtmlSettingsProps {
|
||||
onSave?: (config: EmbeddedHtmlConfig) => void;
|
||||
config?: EmbeddedHtmlConfig;
|
||||
}
|
||||
|
||||
export const EmbeddedHtmlSettings: React.FC<EmbeddedHtmlSettingsProps> = ({
|
||||
onSave,
|
||||
config = { html: "", is_enabled: false },
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [htmlData, setHtmlData] = useState<EmbeddedHtmlConfig>(config);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
useEffect(() => {
|
||||
setHtmlData(config);
|
||||
}, [config]);
|
||||
|
||||
const handleSave = async () => {
|
||||
setIsSaving(true);
|
||||
try {
|
||||
await onSave?.(htmlData);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleHtmlChange = (value: string) => {
|
||||
setHtmlData((prev) => ({ ...prev, html: value }));
|
||||
};
|
||||
const handleToggleEnabled = async (enabled: boolean) => {
|
||||
const updatedConfig = {
|
||||
...htmlData,
|
||||
is_enabled: enabled,
|
||||
};
|
||||
// when toggle the switch, save directly, same as GoogleAuthConfigForm
|
||||
const result = await onSave?.(updatedConfig);
|
||||
if (result) {
|
||||
setHtmlData((prev) => ({ ...prev, is_enabled: enabled }));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
className="px-0"
|
||||
defaultExpandedKeys={["embedded-html"]}
|
||||
>
|
||||
<AccordionItem
|
||||
key="embedded-html"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<h3 className="text-lg font-semibold flex items-center gap-2">
|
||||
{t("Embedded HTML")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure custom HTML content for global injection")}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{/* Enable/Disable Toggle */}
|
||||
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="text-sm font-medium">
|
||||
{t("Enable Custom HTML")}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{t("Toggle to enable or disable custom HTML injection")}
|
||||
</span>
|
||||
</div>
|
||||
<Switch
|
||||
isSelected={htmlData.is_enabled}
|
||||
onValueChange={handleToggleEnabled}
|
||||
color="primary"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* HTML Editor */}
|
||||
<div className="space-y-2">
|
||||
<Textarea
|
||||
placeholder={t(
|
||||
"Enter your custom HTML, CSS, or JavaScript code here...\n\nExample:\n<script>\n // Google Analytics\n gtag('config', 'GA_MEASUREMENT_ID');\n</script>\n\n<style>\n .custom-style {\n color: #333;\n }\n</style>"
|
||||
)}
|
||||
value={htmlData.html}
|
||||
onValueChange={handleHtmlChange}
|
||||
minRows={10}
|
||||
maxRows={20}
|
||||
description={t(
|
||||
"This HTML will be injected globally into the application. You can include script tags, CSS styles, or any valid HTML."
|
||||
)}
|
||||
radius="sm"
|
||||
className="text-xs"
|
||||
isDisabled={!htmlData.is_enabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
{htmlData.is_enabled && (
|
||||
<div className="flex gap-3 py-4">
|
||||
<Button
|
||||
color="primary"
|
||||
variant="solid"
|
||||
onPress={handleSave}
|
||||
isLoading={isSaving}
|
||||
isDisabled={!htmlData.html.trim()}
|
||||
size="sm"
|
||||
>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Usage Instructions */}
|
||||
<Alert
|
||||
color="primary"
|
||||
variant="flat"
|
||||
title={t("Usage Instructions")}
|
||||
description={
|
||||
<ul className="text-sm space-y-1 mt-2">
|
||||
<li>
|
||||
•{" "}
|
||||
{t(
|
||||
"You can include Google Analytics, custom CSS, or any tracking scripts"
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
•{" "}
|
||||
{t("The HTML will be injected into the document head section")}
|
||||
</li>
|
||||
<li>
|
||||
•{" "}
|
||||
{t(
|
||||
"Make sure your code is valid to avoid breaking the application"
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
•{" "}
|
||||
{t("Changes take effect immediately after saving and enabling")}
|
||||
</li>
|
||||
</ul>
|
||||
}
|
||||
/>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,248 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useRef, useEffect } from "react";
|
||||
import {
|
||||
AccordionItem,
|
||||
Accordion,
|
||||
Table,
|
||||
TableHeader,
|
||||
TableColumn,
|
||||
TableBody,
|
||||
TableRow,
|
||||
TableCell,
|
||||
Button,
|
||||
Input,
|
||||
Textarea,
|
||||
Tooltip,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { GripVertical, Trash2, Plus } from "lucide-react";
|
||||
import { FaqItem } from "@/shared/types/system";
|
||||
|
||||
interface FaqSettingsProps {
|
||||
onSave?: (config: FaqItem[]) => void;
|
||||
config?: FaqItem[];
|
||||
}
|
||||
const defaultFaqs = [{ question: "", answer: "" }];
|
||||
export const FaqSettings: React.FC<FaqSettingsProps> = ({
|
||||
onSave,
|
||||
config = [],
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [faqs, setFaqs] = useState<FaqItem[]>(
|
||||
config && config.length > 0 ? config : defaultFaqs
|
||||
);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [focusedAnswer, setFocusedAnswer] = useState<number | null>(null);
|
||||
const draggedItem = useRef<number | null>(null);
|
||||
const draggedOverItem = useRef<number | null>(null);
|
||||
useEffect(() => {
|
||||
setFaqs(config && config.length > 0 ? config : defaultFaqs);
|
||||
}, [config]);
|
||||
|
||||
const handleQuestionChange = (index: number, value: string) => {
|
||||
setFaqs((prev) =>
|
||||
prev.map((faq, idx) =>
|
||||
idx === index ? { ...faq, question: value } : faq
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const handleAnswerChange = (index: number, value: string) => {
|
||||
setFaqs((prev) =>
|
||||
prev.map((faq, idx) => (idx === index ? { ...faq, answer: value } : faq))
|
||||
);
|
||||
};
|
||||
|
||||
const handleDelete = (index: number) => {
|
||||
setFaqs((prev) => {
|
||||
// Ensure at least one record remains
|
||||
if (prev.length <= 1) {
|
||||
return defaultFaqs;
|
||||
}
|
||||
return prev.filter((_, idx) => idx !== index);
|
||||
});
|
||||
};
|
||||
|
||||
const handleInsertBelow = (index: number) => {
|
||||
setFaqs((prev) => {
|
||||
const newFaqs = [...prev];
|
||||
newFaqs.splice(index + 1, 0, {
|
||||
question: "",
|
||||
answer: "",
|
||||
});
|
||||
return newFaqs;
|
||||
});
|
||||
};
|
||||
|
||||
const handleDragStart = (index: number) => {
|
||||
draggedItem.current = index;
|
||||
};
|
||||
|
||||
const handleDragEnter = (index: number) => {
|
||||
draggedOverItem.current = index;
|
||||
};
|
||||
|
||||
const handleDragEnd = () => {
|
||||
if (draggedItem.current !== null && draggedOverItem.current !== null) {
|
||||
const draggedItemIndex = draggedItem.current;
|
||||
const draggedOverItemIndex = draggedOverItem.current;
|
||||
|
||||
if (draggedItemIndex !== draggedOverItemIndex) {
|
||||
setFaqs((prev) => {
|
||||
const newFaqs = [...prev];
|
||||
const draggedItemContent = newFaqs[draggedItemIndex];
|
||||
newFaqs.splice(draggedItemIndex, 1);
|
||||
newFaqs.splice(draggedOverItemIndex, 0, draggedItemContent);
|
||||
return newFaqs;
|
||||
});
|
||||
}
|
||||
}
|
||||
draggedItem.current = null;
|
||||
draggedOverItem.current = null;
|
||||
};
|
||||
|
||||
const handleSaveAll = async () => {
|
||||
setIsSaving(true);
|
||||
try {
|
||||
await onSave?.(faqs.filter((faq) => faq.question && faq.answer));
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
className="px-0"
|
||||
defaultExpandedKeys={["faq"]}
|
||||
>
|
||||
<AccordionItem
|
||||
key="faq"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<h3 className="text-lg font-semibold flex items-center gap-2">
|
||||
{t("FAQ Management")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure frequently asked questions for your users")}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{/* FAQ Table */}
|
||||
<Table
|
||||
aria-label="FAQ management table"
|
||||
className="border-1 rounded-lg p-2"
|
||||
removeWrapper
|
||||
>
|
||||
<TableHeader>
|
||||
<TableColumn className="w-16">{t("Order")}</TableColumn>
|
||||
<TableColumn className="w-1/3">{t("Question")}</TableColumn>
|
||||
<TableColumn>{t("Answer")}</TableColumn>
|
||||
<TableColumn className="w-32">{t("Actions")}</TableColumn>
|
||||
</TableHeader>
|
||||
<TableBody emptyContent={t("No FAQ items available.")}>
|
||||
{faqs.map((faq, index) => (
|
||||
<TableRow
|
||||
key={index}
|
||||
draggable
|
||||
onDragStart={() => handleDragStart(index)}
|
||||
onDragEnter={() => handleDragEnter(index)}
|
||||
onDragEnd={handleDragEnd}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
className="cursor-move"
|
||||
>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-2">
|
||||
<GripVertical className="w-4 h-4 text-gray-400" />
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input
|
||||
value={faq.question}
|
||||
onValueChange={(value) =>
|
||||
handleQuestionChange(index, value)
|
||||
}
|
||||
placeholder={t("Enter question")}
|
||||
size="sm"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="relative">
|
||||
<Input
|
||||
value={faq.answer}
|
||||
onValueChange={(value) =>
|
||||
handleAnswerChange(index, value)
|
||||
}
|
||||
onFocus={() => setFocusedAnswer(index)}
|
||||
placeholder={t("Enter answer")}
|
||||
size="sm"
|
||||
/>
|
||||
{focusedAnswer === index && (
|
||||
<div className="absolute top-0 left-0 right-0 z-50">
|
||||
<Textarea
|
||||
value={faq.answer}
|
||||
onValueChange={(value) =>
|
||||
handleAnswerChange(index, value)
|
||||
}
|
||||
placeholder={t("Enter answer")}
|
||||
size="sm"
|
||||
minRows={3}
|
||||
onBlur={() => setFocusedAnswer(null)}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex gap-1">
|
||||
<Tooltip content={t("Insert below")}>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
onPress={() => handleInsertBelow(index)}
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Tooltip content={t("Delete")} color="danger">
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
color="danger"
|
||||
onPress={() => handleDelete(index)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
<div className="flex ">
|
||||
<Button
|
||||
color="primary"
|
||||
onPress={handleSaveAll}
|
||||
isLoading={isSaving}
|
||||
isDisabled={faqs.length === 0}
|
||||
size="sm"
|
||||
>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { FaqSettings } from "./FaqSettings";
|
||||
import { TopNavigationSettings } from "./TopNavigationSettings";
|
||||
import { EmbeddedHtmlSettings } from "./EmbeddedHtmlSettings";
|
||||
import { useHomepageConfigManagement } from "@/hooks/useHomepageConfigManagement";
|
||||
|
||||
interface HomepageSettingsProps {
|
||||
// 预留接口,后续扩展
|
||||
}
|
||||
|
||||
export const HomepageSettings: React.FC<HomepageSettingsProps> = () => {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
homepageConfig,
|
||||
error,
|
||||
saveFaqConfig,
|
||||
saveNavigationConfig,
|
||||
saveEmbeddedHtmlConfig,
|
||||
} = useHomepageConfigManagement();
|
||||
|
||||
// 显示错误提示
|
||||
useEffect(() => {
|
||||
if (error) {
|
||||
toast.error(t("Failed to load homepage config"));
|
||||
}
|
||||
}, [error, t]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* FAQ Management */}
|
||||
<FaqSettings onSave={saveFaqConfig} config={homepageConfig.faq} />
|
||||
|
||||
{/* Top Navigation */}
|
||||
<TopNavigationSettings
|
||||
onSave={saveNavigationConfig}
|
||||
config={homepageConfig.top_navigation}
|
||||
/>
|
||||
|
||||
{/* Embedded HTML */}
|
||||
<EmbeddedHtmlSettings
|
||||
onSave={saveEmbeddedHtmlConfig}
|
||||
config={homepageConfig.embeded_html}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,7 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { calculateFileSha256 } from "@/shared/utils/crypto";
|
||||
import {
|
||||
Input,
|
||||
Button,
|
||||
@@ -9,50 +8,113 @@ import {
|
||||
Accordion,
|
||||
Select,
|
||||
SelectItem,
|
||||
Switch,
|
||||
} from "@nextui-org/react";
|
||||
import MDEditor, { commands } from "@uiw/react-md-editor";
|
||||
import { PlatformConfig, Theme } from "@/shared/types/system";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { SUPPORTED_LANGUAGES } from "@/shared/lib/i18n";
|
||||
import { ThemeSelector } from "./ThemeSelector";
|
||||
import "@uiw/react-md-editor/markdown-editor.css";
|
||||
import "@uiw/react-markdown-preview/markdown.css";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
interface PlatformConfigFormProps {
|
||||
config: PlatformConfig;
|
||||
onSave: (config: PlatformConfig) => void;
|
||||
onThemeChange?: (theme: Theme) => Promise<void>;
|
||||
onAboutSave?: (aboutContent: string) => Promise<void>;
|
||||
onImageUpload?: (file: File, sha256?: string) => Promise<string>;
|
||||
isLoading?: boolean;
|
||||
isAboutLoading?: boolean;
|
||||
}
|
||||
|
||||
export const PlatformConfigForm: React.FC<PlatformConfigFormProps> = ({
|
||||
config,
|
||||
onSave,
|
||||
onThemeChange,
|
||||
onAboutSave,
|
||||
onImageUpload,
|
||||
isLoading = false,
|
||||
isAboutLoading = false,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [formData, setFormData] = useState<PlatformConfig>(config);
|
||||
const [validationErrors, setValidationErrors] = useState<{
|
||||
domain?: string;
|
||||
mcp_server_prefix?: string;
|
||||
}>({});
|
||||
|
||||
// when context config updated, sync to form
|
||||
useEffect(() => {
|
||||
setFormData(config);
|
||||
}, [config]);
|
||||
|
||||
const handleInputChange = (field: keyof PlatformConfig, value: string) => {
|
||||
setFormData((prev) => ({
|
||||
// URL validation function with strict regex
|
||||
const validateUrl = (url: string): boolean => {
|
||||
if (!url.trim()) return true; // Empty is valid (optional field)
|
||||
|
||||
// Strict regex for domain validation
|
||||
const domainRegex = /^https?:\/\/(?:[-\w.])+(?:\:[0-9]+)?(?:\/.*)?$/;
|
||||
|
||||
// First check with regex
|
||||
if (!domainRegex.test(url)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Then validate with URL constructor for additional checks
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
return (
|
||||
(urlObj.protocol === "http:" || urlObj.protocol === "https:") &&
|
||||
urlObj.hostname.length > 0 &&
|
||||
urlObj.hostname.includes(".")
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Validate field and update errors
|
||||
const validateField = (
|
||||
field: "domain" | "mcp_server_prefix",
|
||||
value: string
|
||||
) => {
|
||||
const isValid = validateUrl(value);
|
||||
setValidationErrors((prev) => ({
|
||||
...prev,
|
||||
[field]: value,
|
||||
[field]: isValid
|
||||
? undefined
|
||||
: t("Please enter a valid URL with http:// or https://"),
|
||||
}));
|
||||
return isValid;
|
||||
};
|
||||
|
||||
const handleInputChange = (
|
||||
field: keyof PlatformConfig,
|
||||
value: string | boolean
|
||||
) => {
|
||||
// Validate URL fields
|
||||
if (field === "domain" || field === "mcp_server_prefix") {
|
||||
validateField(field, value as string);
|
||||
}
|
||||
|
||||
setFormData((prev) => {
|
||||
const newData = {
|
||||
...prev,
|
||||
[field]: value,
|
||||
};
|
||||
|
||||
return newData;
|
||||
});
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
// Validate all URL fields before saving
|
||||
const domainValid = validateField("domain", formData.domain || "");
|
||||
const mcpServerValid = validateField(
|
||||
"mcp_server_prefix",
|
||||
formData.mcp_server_prefix || ""
|
||||
);
|
||||
|
||||
if (!domainValid || !mcpServerValid) {
|
||||
toast.error(t("Please fix validation errors before saving"));
|
||||
return;
|
||||
}
|
||||
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
@@ -61,21 +123,6 @@ export const PlatformConfigForm: React.FC<PlatformConfigFormProps> = ({
|
||||
onThemeChange?.(theme);
|
||||
};
|
||||
|
||||
const handleAboutSave = async () => {
|
||||
onAboutSave?.(formData.about_page || "");
|
||||
};
|
||||
|
||||
const handleImageUpload = async (file: File): Promise<string> => {
|
||||
try {
|
||||
// 计算文件的 SHA256 哈希值
|
||||
const sha256 = await calculateFileSha256(file);
|
||||
return await onImageUpload!(file, sha256);
|
||||
} catch (error) {
|
||||
console.error("Image upload failed:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Platform Information Accordion */}
|
||||
@@ -170,6 +217,56 @@ export const PlatformConfigForm: React.FC<PlatformConfigFormProps> = ({
|
||||
</SelectItem>
|
||||
))}
|
||||
</Select>
|
||||
|
||||
{/* platform domain */}
|
||||
<Input
|
||||
label={t("Platform Domain")}
|
||||
placeholder={t(
|
||||
"Enter platform domain (e.g., https://example.com)"
|
||||
)}
|
||||
description={t("The domain name of your platform")}
|
||||
value={formData.domain || ""}
|
||||
onChange={(e) => handleInputChange("domain", e.target.value)}
|
||||
isInvalid={!!validationErrors.domain}
|
||||
errorMessage={validationErrors.domain}
|
||||
/>
|
||||
|
||||
{/* mcp server prefix */}
|
||||
<Input
|
||||
label={t("MCP Server Domain")}
|
||||
placeholder={t(
|
||||
"Enter MCP server domain (e.g., https://mcp.example.com)"
|
||||
)}
|
||||
description={t("The domain for MCP server API calls")}
|
||||
value={formData.mcp_server_prefix || ""}
|
||||
onChange={(e) =>
|
||||
handleInputChange("mcp_server_prefix", e.target.value)
|
||||
}
|
||||
isInvalid={!!validationErrors.mcp_server_prefix}
|
||||
errorMessage={validationErrors.mcp_server_prefix}
|
||||
/>
|
||||
|
||||
{/* showcase in xpack */}
|
||||
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="text-sm font-medium">
|
||||
{t("Featured in the XPack showcase")}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{t(
|
||||
"Enable this option to feature your site in the XPack global showcase and reach users worldwide."
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<Switch
|
||||
isSelected={formData.is_showcased ?? false}
|
||||
onValueChange={(value) => {
|
||||
handleInputChange("is_showcased", value);
|
||||
}}
|
||||
color="primary"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
@@ -187,120 +284,6 @@ export const PlatformConfigForm: React.FC<PlatformConfigFormProps> = ({
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* About Page Accordion */}
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
className="px-0"
|
||||
defaultExpandedKeys={["about-config"]}
|
||||
>
|
||||
<AccordionItem
|
||||
key="about-config"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<h3 className="text-lg font-semibold">
|
||||
{t("About Page Content")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure about page content")}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<MDEditor
|
||||
value={formData.about_page || ""}
|
||||
onChange={(value?: string) =>
|
||||
handleInputChange("about_page", value || "")
|
||||
}
|
||||
preview="live"
|
||||
hideToolbar={false}
|
||||
visibleDragbar={false}
|
||||
data-color-mode="light"
|
||||
textareaProps={{
|
||||
placeholder: t("Enter about page content (supports Markdown)"),
|
||||
style: {
|
||||
fontSize: 14,
|
||||
lineHeight: 1.6,
|
||||
fontFamily:
|
||||
'ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
|
||||
},
|
||||
}}
|
||||
height={300}
|
||||
commands={[
|
||||
// 默认命令
|
||||
commands.bold,
|
||||
commands.italic,
|
||||
commands.strikethrough,
|
||||
commands.hr,
|
||||
commands.title,
|
||||
commands.divider,
|
||||
commands.link,
|
||||
commands.quote,
|
||||
commands.code,
|
||||
commands.codeBlock,
|
||||
commands.comment,
|
||||
commands.divider,
|
||||
commands.unorderedListCommand,
|
||||
commands.orderedListCommand,
|
||||
commands.checkedListCommand,
|
||||
commands.divider,
|
||||
// 自定义图片上传命令
|
||||
{
|
||||
name: "image-upload",
|
||||
keyCommand: "image-upload",
|
||||
buttonProps: {
|
||||
"aria-label": "Upload image",
|
||||
title: "Upload image",
|
||||
},
|
||||
icon: (
|
||||
<svg width="12" height="12" viewBox="0 0 20 20">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M15 9c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm4-7H1c-.55 0-1 .45-1 1v14c0 .55.45 1 1 1h18c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zM2 17l4.5-6 3.5 4.51 2.5-3.01L17 17H2z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
execute: (state, api) => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.accept = "image/*";
|
||||
input.onchange = async (e) => {
|
||||
const file = (e.target as HTMLInputElement).files?.[0];
|
||||
if (file) {
|
||||
try {
|
||||
const dataUrl = await handleImageUpload(file);
|
||||
const imageMarkdown = ``;
|
||||
api.replaceSelection(imageMarkdown);
|
||||
} catch (error) {
|
||||
console.error("Image upload failed:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* About Save Button */}
|
||||
<div className="flex gap-3 py-4">
|
||||
<Button
|
||||
color="primary"
|
||||
variant="solid"
|
||||
onPress={handleAboutSave}
|
||||
isLoading={isAboutLoading}
|
||||
size="sm"
|
||||
>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* Theme Accordion */}
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useRef, useEffect } from "react";
|
||||
import {
|
||||
AccordionItem,
|
||||
Accordion,
|
||||
Table,
|
||||
TableHeader,
|
||||
TableColumn,
|
||||
TableBody,
|
||||
TableRow,
|
||||
TableCell,
|
||||
Button,
|
||||
Input,
|
||||
Tooltip,
|
||||
Select,
|
||||
SelectItem,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { Plus, Trash2, GripVertical } from "lucide-react";
|
||||
import {
|
||||
TopNavigationItem,
|
||||
TopNavigationTargetEnum,
|
||||
} from "@/shared/types/system";
|
||||
|
||||
interface TopNavigationSettingsProps {
|
||||
onSave?: (config: TopNavigationItem[]) => void;
|
||||
config?: TopNavigationItem[];
|
||||
}
|
||||
const defaultNavigationItems = [
|
||||
{ title: "", link: "", target: TopNavigationTargetEnum.BLANK },
|
||||
];
|
||||
export const TopNavigationSettings: React.FC<TopNavigationSettingsProps> = ({
|
||||
onSave,
|
||||
config = [],
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [navigationItems, setNavigationItems] = useState<TopNavigationItem[]>(
|
||||
config && config.length > 0 ? config : defaultNavigationItems
|
||||
);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const draggedItem = useRef<number | null>(null);
|
||||
const draggedOverItem = useRef<number | null>(null);
|
||||
useEffect(() => {
|
||||
setNavigationItems(
|
||||
config && config.length > 0 ? config : defaultNavigationItems
|
||||
);
|
||||
}, [config]);
|
||||
|
||||
const handleTitleChange = (index: number, value: string) => {
|
||||
setNavigationItems((prev) =>
|
||||
prev.map((item, idx) =>
|
||||
idx === index ? { ...item, title: value } : item
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const handleHrefChange = (index: number, value: string) => {
|
||||
setNavigationItems((prev) =>
|
||||
prev.map((item, idx) => (idx === index ? { ...item, link: value } : item))
|
||||
);
|
||||
};
|
||||
|
||||
const handleTargetChange = (
|
||||
index: number,
|
||||
target: TopNavigationTargetEnum
|
||||
) => {
|
||||
setNavigationItems((prev) =>
|
||||
prev.map((item, idx) => (idx === index ? { ...item, target } : item))
|
||||
);
|
||||
};
|
||||
|
||||
const handleDelete = (index: number) => {
|
||||
setNavigationItems((prev) => {
|
||||
// Ensure at least one record remains
|
||||
if (prev.length <= 1) {
|
||||
return defaultNavigationItems;
|
||||
}
|
||||
return prev.filter((_, idx) => idx !== index);
|
||||
});
|
||||
};
|
||||
|
||||
const handleInsertBelow = (index: number) => {
|
||||
setNavigationItems((prev) => {
|
||||
const newItem: TopNavigationItem = {
|
||||
title: "",
|
||||
link: "",
|
||||
target: TopNavigationTargetEnum.BLANK,
|
||||
};
|
||||
const newItems = [...prev];
|
||||
newItems.splice(index + 1, 0, newItem);
|
||||
return newItems;
|
||||
});
|
||||
};
|
||||
|
||||
const handleDragStart = (index: number) => {
|
||||
draggedItem.current = index;
|
||||
};
|
||||
|
||||
const handleDragEnter = (index: number) => {
|
||||
draggedOverItem.current = index;
|
||||
};
|
||||
|
||||
const handleDragEnd = () => {
|
||||
if (draggedItem.current !== null && draggedOverItem.current !== null) {
|
||||
const draggedItemIndex = draggedItem.current;
|
||||
const draggedOverItemIndex = draggedOverItem.current;
|
||||
|
||||
if (draggedItemIndex !== draggedOverItemIndex) {
|
||||
setNavigationItems((prev) => {
|
||||
const newItems = [...prev];
|
||||
const draggedItemContent = newItems[draggedItemIndex];
|
||||
newItems.splice(draggedItemIndex, 1);
|
||||
newItems.splice(draggedOverItemIndex, 0, draggedItemContent);
|
||||
return newItems;
|
||||
});
|
||||
}
|
||||
}
|
||||
draggedItem.current = null;
|
||||
draggedOverItem.current = null;
|
||||
};
|
||||
|
||||
const handleSaveAll = async () => {
|
||||
setIsSaving(true);
|
||||
try {
|
||||
await onSave?.(navigationItems.filter((item) => item.title && item.link));
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{
|
||||
base: "shadow-none border-1",
|
||||
}}
|
||||
className="px-0"
|
||||
defaultExpandedKeys={["top-navigation"]}
|
||||
>
|
||||
<AccordionItem
|
||||
key="top-navigation"
|
||||
title={
|
||||
<div className="flex flex-col justify-between">
|
||||
<h3 className="text-lg font-semibold flex items-center gap-2">
|
||||
{t("Top Navigation")}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure top navigation menu items and links")}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{/* Navigation Table */}
|
||||
<Table
|
||||
aria-label="Navigation items management table"
|
||||
className="border-1 rounded-lg p-2"
|
||||
removeWrapper
|
||||
>
|
||||
<TableHeader>
|
||||
<TableColumn className="w-16">{t("Order")}</TableColumn>
|
||||
<TableColumn className="w-1/4">{t("Title")}</TableColumn>
|
||||
<TableColumn className="w-1/3">{t("Link")}</TableColumn>
|
||||
<TableColumn className="w-32">{t("Target")}</TableColumn>
|
||||
<TableColumn className="w-32">{t("Actions")}</TableColumn>
|
||||
</TableHeader>
|
||||
<TableBody emptyContent={t("No navigation items available.")}>
|
||||
{navigationItems.map((item, index) => (
|
||||
<TableRow
|
||||
key={index}
|
||||
draggable
|
||||
onDragStart={() => handleDragStart(index)}
|
||||
onDragEnter={() => handleDragEnter(index)}
|
||||
onDragEnd={handleDragEnd}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
className="cursor-move"
|
||||
>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-2">
|
||||
<GripVertical className="w-4 h-4 text-gray-400" />
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input
|
||||
value={item.title}
|
||||
onValueChange={(value) => handleTitleChange(index, value)}
|
||||
placeholder={t("Enter title")}
|
||||
size="sm"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Input
|
||||
value={item.link}
|
||||
onValueChange={(value) => handleHrefChange(index, value)}
|
||||
placeholder={t("Enter link URL")}
|
||||
size="sm"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Select
|
||||
selectedKeys={[item.target]}
|
||||
onSelectionChange={(keys) => {
|
||||
const target = Array.from(keys)[0] as
|
||||
| TopNavigationTargetEnum.SELF
|
||||
| TopNavigationTargetEnum.BLANK;
|
||||
handleTargetChange(index, target);
|
||||
}}
|
||||
size="sm"
|
||||
className="min-w-24"
|
||||
>
|
||||
<SelectItem
|
||||
key={TopNavigationTargetEnum.SELF}
|
||||
value={TopNavigationTargetEnum.SELF}
|
||||
>
|
||||
{t("Same Tab")}
|
||||
</SelectItem>
|
||||
<SelectItem
|
||||
key={TopNavigationTargetEnum.BLANK}
|
||||
value={TopNavigationTargetEnum.BLANK}
|
||||
>
|
||||
{t("New Tab")}
|
||||
</SelectItem>
|
||||
</Select>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex gap-1">
|
||||
<Tooltip content={t("Insert below")}>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
onPress={() => handleInsertBelow(index)}
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Tooltip content={t("Delete")} color="danger">
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
color="danger"
|
||||
onPress={() => handleDelete(index)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
<div className="flex">
|
||||
<Button
|
||||
color="primary"
|
||||
onPress={handleSaveAll}
|
||||
isLoading={isSaving}
|
||||
isDisabled={navigationItems.length === 0}
|
||||
size="sm"
|
||||
>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -13,24 +13,32 @@ import { NavigationItems } from "@/components/theme/Theme.const";
|
||||
import { AboutContent } from "@/components/about/AboutContent";
|
||||
|
||||
export const AboutThemeSelector: React.FC = () => {
|
||||
const { platformConfig } = usePlatformConfig();
|
||||
const { platformConfig, topNavigation } = usePlatformConfig();
|
||||
const currentTheme = platformConfig.theme || Theme.DEFAULT;
|
||||
const navigationItems = [
|
||||
...NavigationItems,
|
||||
...topNavigation.map((item) => ({
|
||||
label: item.title,
|
||||
href: item.link,
|
||||
target: item.target,
|
||||
})),
|
||||
];
|
||||
|
||||
// Render the About page based on the current theme
|
||||
switch (currentTheme) {
|
||||
case Theme.MODERN:
|
||||
return <ModernAbout navItems={NavigationItems} />;
|
||||
return <ModernAbout navItems={navigationItems} />;
|
||||
case Theme.CLASSIC:
|
||||
return <ClassicAbout navItems={NavigationItems} />;
|
||||
return <ClassicAbout navItems={navigationItems} />;
|
||||
case Theme.CREATIVE:
|
||||
return <CreativeAbout navItems={NavigationItems} />;
|
||||
return <CreativeAbout navItems={navigationItems} />;
|
||||
case Theme.TEMU:
|
||||
return <TemuAbout navItems={NavigationItems} />;
|
||||
return <TemuAbout navItems={navigationItems} />;
|
||||
case Theme.DEFAULT:
|
||||
default:
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex flex-col justify-between">
|
||||
<Navigation items={NavigationItems} />
|
||||
<Navigation items={navigationItems} />
|
||||
<main className="flex-1 max-w-7xl mx-auto px-4 py-8">
|
||||
<AboutContent />
|
||||
</main>
|
||||
|
||||
@@ -12,6 +12,9 @@ import { ProductDetailClient } from "@/shared/components/marketplace/ProductDeta
|
||||
import { Navigation } from "@/shared/components/Navigation";
|
||||
import { Footer } from "@/shared/components/Footer";
|
||||
import { NavigationItems } from "./Theme.const";
|
||||
import { copyToClipboard } from "@/shared/utils/clipboard";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface ProductDetailThemeSelectorProps {
|
||||
product: ServiceData;
|
||||
@@ -24,13 +27,67 @@ interface ProductDetailThemeSelectorProps {
|
||||
export const ProductDetailThemeSelector: React.FC<
|
||||
ProductDetailThemeSelectorProps
|
||||
> = ({ product, breadcrumbs }) => {
|
||||
const { platformConfig } = usePlatformConfig();
|
||||
const { platformConfig, topNavigation } = usePlatformConfig();
|
||||
const currentTheme = platformConfig.theme || Theme.DEFAULT;
|
||||
const [url, setUrl] = useState<string>(process.env.NEXT_PUBLIC_MCP_URL || "");
|
||||
const mcpServerPrefix =
|
||||
platformConfig.mcp_server_prefix || process.env.NEXT_PUBLIC_MCP_URL || "";
|
||||
const [url, setUrl] = useState<string>("");
|
||||
const [mcpName, setMcpName] = useState<string>("");
|
||||
const { t } = useTranslation();
|
||||
const navigationItems = [
|
||||
...NavigationItems,
|
||||
...topNavigation.map((item) => ({
|
||||
label: item.title,
|
||||
href: item.link,
|
||||
target: item.target,
|
||||
})),
|
||||
];
|
||||
useEffect(() => {
|
||||
if (url || !product.slug_name) return;
|
||||
setUrl(`${window.location.origin}/mcp/${product.slug_name}`);
|
||||
setUrl(
|
||||
`${mcpServerPrefix || `${window.location.protocol}//${window.location.hostname}:8002`}/mcp/${product.slug_name}`
|
||||
);
|
||||
}, [product.slug_name]);
|
||||
function sanitizeMCPServerName(rawName: string | undefined): string {
|
||||
if (!rawName) return "xpack-mcp-service";
|
||||
|
||||
// Lower-case & replace invalid chars with hyphen
|
||||
let name = rawName
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-_]+/g, "-");
|
||||
|
||||
// Collapse multiple hyphens
|
||||
name = name.replace(/-+/g, "-");
|
||||
|
||||
// Trim leading/trailing hyphens
|
||||
name = name.replace(/^-+/, "").replace(/-+$/, "");
|
||||
|
||||
return name || "mcp-service";
|
||||
}
|
||||
useEffect(() => {
|
||||
setMcpName(sanitizeMCPServerName(product.name));
|
||||
}, [product.name]);
|
||||
const getCodeContent = () => {
|
||||
return `{
|
||||
"mcpServers": {
|
||||
"${mcpName || "xpack-mcp-market"}": {
|
||||
"type": "sse",
|
||||
"autoApprove":"all",
|
||||
"url": "${url}?apikey={Your-${platformConfig?.name}-API-Key}"
|
||||
}
|
||||
}
|
||||
}`;
|
||||
};
|
||||
|
||||
const handleCopy = async () => {
|
||||
const result = await copyToClipboard(getCodeContent());
|
||||
if (result.success) {
|
||||
toast.success(t("Copied to clipboard"));
|
||||
} else {
|
||||
toast.error(t("Copy failed, please copy manually"));
|
||||
}
|
||||
};
|
||||
|
||||
//Render the About page based on the current theme
|
||||
switch (currentTheme) {
|
||||
@@ -40,7 +97,9 @@ export const ProductDetailThemeSelector: React.FC<
|
||||
product={product}
|
||||
breadcrumbs={breadcrumbs}
|
||||
url={url}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
mcpName={mcpName}
|
||||
onCopy={handleCopy}
|
||||
/>
|
||||
);
|
||||
case Theme.CLASSIC:
|
||||
@@ -49,7 +108,9 @@ export const ProductDetailThemeSelector: React.FC<
|
||||
product={product}
|
||||
breadcrumbs={breadcrumbs}
|
||||
url={url}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
mcpName={mcpName}
|
||||
onCopy={handleCopy}
|
||||
/>
|
||||
);
|
||||
case Theme.CREATIVE:
|
||||
@@ -58,7 +119,9 @@ export const ProductDetailThemeSelector: React.FC<
|
||||
product={product}
|
||||
breadcrumbs={breadcrumbs}
|
||||
url={url}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
mcpName={mcpName}
|
||||
onCopy={handleCopy}
|
||||
/>
|
||||
);
|
||||
case Theme.TEMU:
|
||||
@@ -67,16 +130,22 @@ export const ProductDetailThemeSelector: React.FC<
|
||||
product={product}
|
||||
breadcrumbs={breadcrumbs}
|
||||
url={url}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
mcpName={mcpName}
|
||||
onCopy={handleCopy}
|
||||
/>
|
||||
);
|
||||
case Theme.DEFAULT:
|
||||
default:
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex flex-col justify-between">
|
||||
<Navigation items={NavigationItems} />
|
||||
<Navigation items={navigationItems} />
|
||||
<main className="flex-1">
|
||||
<ProductDetailClient product={product} />
|
||||
<ProductDetailClient
|
||||
product={product}
|
||||
mcpName={mcpName}
|
||||
url={url}
|
||||
/>
|
||||
</main>
|
||||
<div>
|
||||
<Footer />
|
||||
|
||||
@@ -14,6 +14,7 @@ import { Navigation } from "@/shared/components/Navigation";
|
||||
import { MarketplaceMain } from "../marketplace/Main";
|
||||
import { Footer } from "@/shared/components/Footer";
|
||||
import { NavigationItems } from "./Theme.const";
|
||||
import { Faq } from "../marketplace/Faq";
|
||||
|
||||
interface ThemeSelectorProps {
|
||||
initialServices: ServiceData[];
|
||||
@@ -33,8 +34,16 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
error,
|
||||
}) => {
|
||||
const router = useRouter();
|
||||
const { platformConfig } = usePlatformConfig();
|
||||
const { platformConfig, topNavigation } = usePlatformConfig();
|
||||
const currentTheme = platformConfig.theme || Theme.DEFAULT;
|
||||
const navigationItems = [
|
||||
...NavigationItems,
|
||||
...topNavigation.map((item) => ({
|
||||
label: item.title,
|
||||
href: item.link,
|
||||
target: item.target,
|
||||
})),
|
||||
];
|
||||
|
||||
// state management for services, search query, pagination, and loading state
|
||||
const [searchQuery, setSearchQuery] = useState(initialSearch);
|
||||
@@ -122,7 +131,7 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
onSearch={handleSearch}
|
||||
onPageChange={handlePageChange}
|
||||
searchSuggestions={searchSuggestions}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
/>
|
||||
);
|
||||
case Theme.CLASSIC:
|
||||
@@ -139,7 +148,7 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
onSearch={handleSearch}
|
||||
onPageChange={handlePageChange}
|
||||
searchSuggestions={searchSuggestions}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
/>
|
||||
);
|
||||
case Theme.CREATIVE:
|
||||
@@ -156,7 +165,7 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
onSearch={handleSearch}
|
||||
onPageChange={handlePageChange}
|
||||
searchSuggestions={searchSuggestions}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
/>
|
||||
);
|
||||
case Theme.TEMU:
|
||||
@@ -173,14 +182,14 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
onSearch={handleSearch}
|
||||
onPageChange={handlePageChange}
|
||||
searchSuggestions={searchSuggestions}
|
||||
navItems={NavigationItems}
|
||||
navItems={navigationItems}
|
||||
/>
|
||||
);
|
||||
case Theme.DEFAULT:
|
||||
default:
|
||||
return (
|
||||
<div className="min-h-screen bg-background flex flex-col justify-between">
|
||||
<Navigation items={NavigationItems} />
|
||||
<Navigation items={navigationItems} />
|
||||
<main className="flex-1">
|
||||
<MarketplaceMain
|
||||
initialServices={services}
|
||||
@@ -190,6 +199,7 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
pageSize={pageSize}
|
||||
error={error}
|
||||
/>
|
||||
<Faq />
|
||||
</main>
|
||||
<div>
|
||||
<Footer />
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { Tabs, Tab, Chip, Card, CardBody } from "@nextui-org/react";
|
||||
import { Tabs, Tab, Chip, Card, CardBody, Button } from "@nextui-org/react";
|
||||
import { ServiceData } from "@/shared/types/marketplace";
|
||||
import { ProductOverview } from "@/shared/components/marketplace/ProductOverview";
|
||||
import { ProductNotFound } from "@/shared/components/marketplace/ProductNotFound";
|
||||
import { FileText, Wrench, Cog } from "lucide-react";
|
||||
import { FileText, Wrench, Cog, Copy } from "lucide-react";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { Footer } from "./Footer";
|
||||
import Link from "next/link";
|
||||
@@ -21,16 +21,18 @@ interface DetailProps {
|
||||
name: string;
|
||||
}[];
|
||||
url?: string;
|
||||
|
||||
mcpName?: string;
|
||||
// navigation items
|
||||
navItems?: NavigationItem[];
|
||||
onCopy: () => void;
|
||||
}
|
||||
|
||||
export const Detail: React.FC<DetailProps> = ({
|
||||
product,
|
||||
breadcrumbs,
|
||||
url,
|
||||
mcpName,
|
||||
navItems = [],
|
||||
onCopy,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState("overview");
|
||||
@@ -83,7 +85,7 @@ export const Detail: React.FC<DetailProps> = ({
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-lg mb-4">
|
||||
<p className="text-sm mb-4">
|
||||
{product.short_description ||
|
||||
t("No description available")}
|
||||
</p>
|
||||
@@ -93,10 +95,12 @@ export const Detail: React.FC<DetailProps> = ({
|
||||
{/* Price section */}
|
||||
{product.charge_type && (
|
||||
<div className="flex gap-2 items-center">
|
||||
<b className="text-xs">{t("Price")}:</b>
|
||||
<b className="text-md">{t("Price")}:</b>
|
||||
<Price
|
||||
price={product.price}
|
||||
charge_type={product.charge_type}
|
||||
input_token_price={product.input_token_price}
|
||||
output_token_price={product.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -209,18 +213,26 @@ export const Detail: React.FC<DetailProps> = ({
|
||||
{/* Code Snippet */}
|
||||
<Card className="w-full max-w-2xl bg-black text-white p-2 sm:p-4 rounded-lg relative z-10">
|
||||
<div className="text-left font-mono">
|
||||
<Chip
|
||||
className="mb-2 text-white"
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<div className="flex items-center gap-2 mb-2 justify-between">
|
||||
<Chip className="text-white" size="sm" variant="flat">
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="flat"
|
||||
className="min-w-6 w-6 h-6 p-0 text-white"
|
||||
onPress={onCopy}
|
||||
aria-label={t("Copy code")}
|
||||
>
|
||||
<Copy size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
<pre className="p-2 sm:p-4 rounded-md text-xs overflow-x-auto">
|
||||
<code className="text-gray-300 whitespace-pre-wrap">
|
||||
{`{
|
||||
"mcpServers": {
|
||||
"xpack-mcp-market": {
|
||||
"${mcpName}": {
|
||||
"type": "sse",
|
||||
"autoApprove":"all",
|
||||
"url": "${url}?apikey=`}
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
import { Footer } from "./Footer";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { Faq } from "@/components/marketplace/Faq";
|
||||
|
||||
interface HomeProps {
|
||||
// 状态
|
||||
@@ -163,13 +164,14 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<div className="bg-gray-50 py-16">
|
||||
<div className="mx-auto px-6 max-w-7xl">
|
||||
{/* Services Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 mb-12">
|
||||
<div className="flex flex-wrap justify-center gap-4 mb-12">
|
||||
{services.map((service) => (
|
||||
<Link
|
||||
key={service.service_id}
|
||||
href={`/marketplace/${service.service_id}`}
|
||||
className="w-full md:w-[calc(50%-16px)] lg:w-[calc(33%-16px)] xl:w-[calc(25%-16px)]"
|
||||
>
|
||||
<Card className="group h-[200px] hover:shadow-lg transition-shadow duration-200 cursor-pointer border border-gray-200 bg-white rounded-sm shadow-sm">
|
||||
<Card className="group h-[200px] w-full hover:shadow-lg transition-shadow duration-200 cursor-pointer border border-gray-200 bg-white rounded-sm shadow-sm">
|
||||
<CardBody className="p-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
@@ -211,6 +213,8 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<Price
|
||||
price={service.price}
|
||||
charge_type={service.charge_type}
|
||||
input_token_price={service.input_token_price}
|
||||
output_token_price={service.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -245,6 +249,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Faq />
|
||||
</div>
|
||||
<div>
|
||||
<Footer />
|
||||
|
||||
@@ -43,7 +43,12 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
<div className="flex items-center justify-between max-w-7xl mx-auto">
|
||||
<div className="flex space-x-6">
|
||||
{items?.map((item) => (
|
||||
<Link href={item.href} className="text-sm text-gray-500">
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
target={item.target}
|
||||
className="text-sm text-gray-500"
|
||||
>
|
||||
{t(item.label)}
|
||||
</Link>
|
||||
))}
|
||||
|
||||
@@ -2,13 +2,12 @@
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { Tabs, Tab, Chip, Card, CardBody } from "@nextui-org/react";
|
||||
import { Tabs, Tab, Chip, Card, CardBody, Button } from "@nextui-org/react";
|
||||
import { ServiceData } from "@/shared/types/marketplace";
|
||||
import { ProductHeader } from "@/shared/components/marketplace/ProductHeader";
|
||||
import { ProductOverview } from "@/shared/components/marketplace/ProductOverview";
|
||||
import { ProductTools } from "@/shared/components/marketplace/ProductTools";
|
||||
import { ProductNotFound } from "@/shared/components/marketplace/ProductNotFound";
|
||||
import { Sparkles, Zap, Settings2 } from "lucide-react";
|
||||
import { Sparkles, Zap, Settings2, Copy } from "lucide-react";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { Footer } from "./Footer";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
@@ -21,16 +20,19 @@ interface DetailProps {
|
||||
name: string;
|
||||
}[];
|
||||
url?: string;
|
||||
|
||||
mcpName?: string;
|
||||
// navigation items
|
||||
navItems?: NavigationItem[];
|
||||
onCopy: () => void;
|
||||
}
|
||||
|
||||
export const Detail: React.FC<DetailProps> = ({
|
||||
product,
|
||||
breadcrumbs,
|
||||
url,
|
||||
mcpName,
|
||||
navItems = [],
|
||||
onCopy,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState("overview");
|
||||
@@ -41,151 +43,190 @@ export const Detail: React.FC<DetailProps> = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-pink-50 via-orange-50 to-yellow-50 relative overflow-hidden">
|
||||
<div className="min-h-screen bg-gradient-to-br from-pink-50 via-orange-50 to-yellow-50 relative overflow-hidden flex flex-col justify-between">
|
||||
<Navigation items={navItems} />
|
||||
{/* Creative Background */}
|
||||
<div className="absolute inset-0">
|
||||
{/* Artistic decorative elements */}
|
||||
<div className="absolute top-20 left-20 w-32 h-32 bg-gradient-to-br from-pink-200/30 to-orange-200/30 rounded-full blur-2xl" />
|
||||
<div className="absolute top-40 right-32 w-24 h-24 bg-gradient-to-br from-orange-200/40 to-yellow-200/40 rounded-2xl rotate-45 blur-xl" />
|
||||
<div className="absolute bottom-32 left-1/4 w-40 h-40 bg-gradient-to-br from-yellow-200/25 to-pink-200/25 rounded-full blur-3xl" />
|
||||
<div className="absolute bottom-20 right-20 w-28 h-28 bg-gradient-to-br from-pink-200/35 to-red-200/35 rounded-2xl rotate-12 blur-xl" />
|
||||
<div className="flex-1 relative">
|
||||
<div className="absolute inset-0">
|
||||
{/* Artistic decorative elements */}
|
||||
<div className="absolute top-20 left-20 w-32 h-32 bg-gradient-to-br from-pink-200/30 to-orange-200/30 rounded-full blur-2xl" />
|
||||
<div className="absolute top-40 right-32 w-24 h-24 bg-gradient-to-br from-orange-200/40 to-yellow-200/40 rounded-2xl rotate-45 blur-xl" />
|
||||
<div className="absolute bottom-32 left-1/4 w-40 h-40 bg-gradient-to-br from-yellow-200/25 to-pink-200/25 rounded-full blur-3xl" />
|
||||
<div className="absolute bottom-20 right-20 w-28 h-28 bg-gradient-to-br from-pink-200/35 to-red-200/35 rounded-2xl rotate-12 blur-xl" />
|
||||
|
||||
{/* Additional artistic elements */}
|
||||
<div className="absolute top-1/3 left-1/3 w-20 h-20 bg-gradient-to-br from-orange-300/20 to-yellow-300/20 rounded-full blur-xl" />
|
||||
<div className="absolute top-2/3 right-1/3 w-16 h-16 bg-gradient-to-br from-pink-300/25 to-orange-300/25 rounded-lg rotate-45 blur-lg" />
|
||||
</div>
|
||||
|
||||
<div className="relative z-10">
|
||||
{/* Creative Product Header */}
|
||||
<div className="pt-24">
|
||||
<div className="mx-auto p-6 max-w-7xl">
|
||||
<div className="bg-white/90 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-pink-200/50">
|
||||
<ProductHeader product={product} breadcrumbs={breadcrumbs} />
|
||||
</div>
|
||||
</div>
|
||||
{/* Additional artistic elements */}
|
||||
<div className="absolute top-1/3 left-1/3 w-20 h-20 bg-gradient-to-br from-orange-300/20 to-yellow-300/20 rounded-full blur-xl" />
|
||||
<div className="absolute top-2/3 right-1/3 w-16 h-16 bg-gradient-to-br from-pink-300/25 to-orange-300/25 rounded-lg rotate-45 blur-lg" />
|
||||
</div>
|
||||
|
||||
{/* Main Content */}
|
||||
<div className="mx-auto p-6 max-w-7xl">
|
||||
<div className="flex gap-6 mt-6">
|
||||
{/* Left side - Main content */}
|
||||
<div className="flex-1">
|
||||
<Card className="bg-white/95 backdrop-blur-sm border border-pink-200/50 shadow-lg overflow-hidden rounded-2xl">
|
||||
<div className="absolute inset-0 bg-gradient-to-r from-pink-500/5 via-transparent to-orange-500/5" />
|
||||
<CardBody className="p-0 relative">
|
||||
<Tabs
|
||||
selectedKey={activeTab}
|
||||
onSelectionChange={(key) => setActiveTab(key as string)}
|
||||
variant="underlined"
|
||||
color="secondary"
|
||||
className="px-6 pt-6"
|
||||
classNames={{
|
||||
tabList:
|
||||
"gap-6 w-full relative rounded-none p-0 border-b border-pink-200/50",
|
||||
cursor:
|
||||
"w-full bg-gradient-to-r from-pink-500 via-red-500 to-orange-500",
|
||||
tab: "max-w-fit px-0 h-12",
|
||||
tabContent:
|
||||
"group-data-[selected=true]:text-pink-600 font-semibold",
|
||||
}}
|
||||
>
|
||||
<Tab
|
||||
key="overview"
|
||||
title={
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="w-4 h-4" />
|
||||
<span>{t("Overview")}</span>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="p-6 pt-4">
|
||||
<ProductOverview product={product} />
|
||||
</div>
|
||||
</Tab>
|
||||
<Tab
|
||||
key="tools"
|
||||
title={
|
||||
<div className="flex gap-2 items-center">
|
||||
<Zap className="w-4 h-4" />
|
||||
<span>{t("Tools")}</span>
|
||||
<Chip
|
||||
size="sm"
|
||||
className="h-4 text-xs bg-gradient-to-r from-pink-500 via-red-500 to-orange-500 text-white shadow-lg"
|
||||
>
|
||||
{product.tools.length}
|
||||
</Chip>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="p-6 pt-4">
|
||||
<ProductTools product={product} />
|
||||
</div>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</CardBody>
|
||||
</Card>
|
||||
<div className="relative z-10">
|
||||
{/* Creative Product Header */}
|
||||
<div className="pt-24">
|
||||
<div className="mx-auto p-6 max-w-7xl">
|
||||
<div className="bg-white/90 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-pink-200/50">
|
||||
<ProductHeader product={product} breadcrumbs={breadcrumbs} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right side - Server Config */}
|
||||
<div className="min-w-[400px] w-[40%] max-w-100 flex-shrink-0">
|
||||
<Card className="bg-white/95 backdrop-blur-sm border border-pink-200/50 shadow-lg overflow-hidden rounded-2xl">
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-orange-500/5 via-transparent to-pink-500/5" />
|
||||
<CardBody className="relative">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="p-2 bg-gradient-to-r from-pink-500 via-red-500 to-orange-500 rounded-lg">
|
||||
<Settings2 className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<h3 className="font-semibold text-lg bg-gradient-to-r from-pink-600 to-orange-600 bg-clip-text text-transparent">
|
||||
{t("Configuration")}
|
||||
</h3>
|
||||
</div>
|
||||
{/* Code Snippet */}
|
||||
<Card className="w-full max-w-2xl bg-black text-white p-2 sm:p-4 rounded-lg relative z-10">
|
||||
<div className="text-left font-mono">
|
||||
<Chip
|
||||
className="mb-2 text-white"
|
||||
size="sm"
|
||||
variant="flat"
|
||||
{/* Main Content */}
|
||||
<div className="mx-auto p-6 max-w-7xl">
|
||||
<div className="flex gap-6 mt-6">
|
||||
{/* Left side - Main content */}
|
||||
<div className="flex-1">
|
||||
<Card className="bg-white/95 backdrop-blur-sm border border-pink-200/50 shadow-lg overflow-hidden rounded-2xl">
|
||||
<div className="absolute inset-0 bg-gradient-to-r from-pink-500/5 via-transparent to-orange-500/5" />
|
||||
<CardBody className="p-0 relative">
|
||||
<Tabs
|
||||
selectedKey={activeTab}
|
||||
onSelectionChange={(key) => setActiveTab(key as string)}
|
||||
variant="underlined"
|
||||
color="secondary"
|
||||
className="px-6 pt-6"
|
||||
classNames={{
|
||||
tabList:
|
||||
"gap-6 w-full relative rounded-none p-0 border-b border-pink-200/50",
|
||||
cursor:
|
||||
"w-full bg-gradient-to-r from-pink-500 via-red-500 to-orange-500",
|
||||
tab: "max-w-fit px-0 h-12",
|
||||
tabContent:
|
||||
"group-data-[selected=true]:text-pink-600 font-semibold",
|
||||
}}
|
||||
>
|
||||
<Tab
|
||||
key="overview"
|
||||
title={
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="w-4 h-4" />
|
||||
<span>{t("Overview")}</span>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<pre className="p-2 sm:p-4 rounded-md text-xs overflow-x-auto">
|
||||
<code className="text-gray-300 whitespace-pre-wrap">
|
||||
{`{
|
||||
<div className="p-6 pt-4">
|
||||
<ProductOverview product={product} />
|
||||
</div>
|
||||
</Tab>
|
||||
<Tab
|
||||
key="tools"
|
||||
title={
|
||||
<div className="flex gap-2 items-center">
|
||||
<Zap className="w-4 h-4" />
|
||||
<span>{t("Tools")}</span>
|
||||
<Chip
|
||||
size="sm"
|
||||
className="h-4 text-xs bg-gradient-to-r from-pink-500 via-red-500 to-orange-500 text-white shadow-lg"
|
||||
>
|
||||
{product.tools.length}
|
||||
</Chip>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="p-6 pt-4">
|
||||
{product.tools.length > 0 ? (
|
||||
product.tools.map((tool, index) => (
|
||||
<Card
|
||||
radius="sm"
|
||||
key={`${product.service_id}-tool-${index}`}
|
||||
shadow="none"
|
||||
className="border-1"
|
||||
>
|
||||
<CardBody>
|
||||
<h4 className="font-semibold text-sm mb-2 text-pink-600">
|
||||
{tool.name}
|
||||
</h4>
|
||||
<p className="text-sm mb-3">
|
||||
{tool.description ||
|
||||
t("No description available")}
|
||||
</p>
|
||||
</CardBody>
|
||||
</Card>
|
||||
))
|
||||
) : (
|
||||
<Card>
|
||||
<CardBody>
|
||||
<p className="text-center">
|
||||
{t("No tools available in this service.")}
|
||||
</p>
|
||||
</CardBody>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Right side - Server Config */}
|
||||
<div className="min-w-[400px] w-[40%] max-w-100 flex-shrink-0">
|
||||
<Card className="bg-white/95 backdrop-blur-sm border border-pink-200/50 shadow-lg overflow-hidden rounded-2xl">
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-orange-500/5 via-transparent to-pink-500/5" />
|
||||
<CardBody className="relative">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="p-2 bg-gradient-to-r from-pink-500 via-red-500 to-orange-500 rounded-lg">
|
||||
<Settings2 className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<h3 className="font-semibold text-lg bg-gradient-to-r from-pink-600 to-orange-600 bg-clip-text text-transparent">
|
||||
{t("Configuration")}
|
||||
</h3>
|
||||
</div>
|
||||
{/* Code Snippet */}
|
||||
<Card className="w-full max-w-2xl bg-black text-white p-2 sm:p-4 rounded-lg relative z-10">
|
||||
<div className="text-left font-mono">
|
||||
<div className="flex items-center gap-2 mb-2 justify-between">
|
||||
<Chip className="text-white" size="sm" variant="flat">
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="flat"
|
||||
className="min-w-6 w-6 h-6 p-0 text-white"
|
||||
onPress={onCopy}
|
||||
aria-label={t("Copy code")}
|
||||
>
|
||||
<Copy size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
<pre className="p-2 sm:p-4 rounded-md text-xs overflow-x-auto">
|
||||
<code className="text-gray-300 whitespace-pre-wrap">
|
||||
{`{
|
||||
"mcpServers": {
|
||||
"xpack-mcp-market": {
|
||||
"${mcpName}": {
|
||||
"type": "sse",
|
||||
"autoApprove":"all",
|
||||
"url": "${url}?apikey=`}
|
||||
<span className="text-success">{`{Your-${platformConfig?.name}-API-Key}`}</span>
|
||||
{`"
|
||||
<span className="text-success">{`{Your-${platformConfig?.name}-API-Key}`}</span>
|
||||
{`"
|
||||
}
|
||||
}
|
||||
}`}
|
||||
</code>
|
||||
</pre>
|
||||
</div>
|
||||
</Card>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</code>
|
||||
</pre>
|
||||
</div>
|
||||
</Card>
|
||||
</CardBody>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* SEO-friendly: Simple text content for search engines */}
|
||||
<div className="hidden" aria-hidden="true">
|
||||
<h2>Tools ({product.tools.length})</h2>
|
||||
{product.tools.length > 0 &&
|
||||
product.tools.map((tool, index) => (
|
||||
<div key={`seo-${product.service_id}-tool-${index}`}>
|
||||
<h4>{tool.name}</h4>
|
||||
<p>{tool.description || ""}</p>
|
||||
</div>
|
||||
))}
|
||||
{/* SEO-friendly: Simple text content for search engines */}
|
||||
<div className="hidden" aria-hidden="true">
|
||||
<h2>Tools ({product.tools.length})</h2>
|
||||
{product.tools.length > 0 &&
|
||||
product.tools.map((tool, index) => (
|
||||
<div key={`seo-${product.service_id}-tool-${index}`}>
|
||||
<h4>{tool.name}</h4>
|
||||
<p>{tool.description || ""}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Footer />
|
||||
<div>
|
||||
<Footer />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
import { Footer } from "./Footer";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { Faq } from "@/components/marketplace/Faq";
|
||||
|
||||
interface HomeProps {
|
||||
// 状态
|
||||
@@ -69,17 +70,17 @@ export const Home: React.FC<HomeProps> = ({
|
||||
|
||||
{/* Creative Background decorative elements */}
|
||||
<div className="absolute inset-0 overflow-hidden pointer-events-none z-50">
|
||||
{/* 主要装饰圆圈 */}
|
||||
{/* main decorative circles */}
|
||||
<div className="absolute top-1/4 left-1/4 w-64 h-64 bg-gradient-to-r from-pink-400/15 to-orange-400/15 rounded-full blur-3xl animate-pulse"></div>
|
||||
<div className="absolute bottom-1/4 right-1/4 w-96 h-96 bg-gradient-to-r from-orange-400/10 to-yellow-400/10 rounded-full blur-3xl"></div>
|
||||
|
||||
{/* 小装饰圆圈 */}
|
||||
{/* small decorative circles */}
|
||||
<div className="absolute top-10 right-20 w-16 h-16 bg-gradient-to-br from-pink-400/20 to-red-500/20 rounded-full transform rotate-12"></div>
|
||||
<div className="absolute top-32 left-16 w-12 h-12 bg-gradient-to-br from-orange-400/25 to-yellow-400/25 rounded-full transform -rotate-12"></div>
|
||||
<div className="absolute bottom-20 left-1/3 w-20 h-20 bg-gradient-to-br from-yellow-400/15 to-pink-400/15 rounded-full transform rotate-6"></div>
|
||||
<div className="absolute bottom-32 right-16 w-14 h-14 bg-gradient-to-br from-purple-400/20 to-pink-400/20 rounded-full transform -rotate-6"></div>
|
||||
|
||||
{/* 微小装饰点 */}
|
||||
{/* small decorative points */}
|
||||
<div className="absolute top-1/3 right-1/3 w-4 h-4 bg-pink-400/30 rounded-full"></div>
|
||||
<div className="absolute top-2/3 left-1/5 w-3 h-3 bg-orange-400/40 rounded-full"></div>
|
||||
<div className="absolute bottom-1/3 right-1/5 w-5 h-5 bg-yellow-400/25 rounded-full"></div>
|
||||
@@ -129,7 +130,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
placeholder={
|
||||
searchSuggestions.length > 0
|
||||
? t(searchSuggestions[0])
|
||||
: t("✨ 发现神奇的服务...")
|
||||
: t("✨ Discover amazing services...")
|
||||
}
|
||||
value={searchQuery}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
@@ -170,9 +171,6 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<div className="bg-white/90 backdrop-blur-xl p-8 rounded-2xl shadow-lg border border-pink-200/50">
|
||||
<div className="flex items-center gap-4">
|
||||
<Spinner size="lg" color="secondary" />
|
||||
<span className="text-gray-700 text-lg font-bold">
|
||||
✨ 加载魔法中...
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -180,7 +178,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<div className="relative z-10">
|
||||
<div className="relative mx-auto px-6 py-16 max-w-8xl">
|
||||
{/* Creative Services Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 max-w-6xl mx-auto">
|
||||
<div className="flex flex-wrap justify-center gap-4 mb-12">
|
||||
{services.map((service, index) => {
|
||||
const gradientBorders = [
|
||||
"border-pink-200/50",
|
||||
@@ -211,7 +209,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<Link
|
||||
key={service.service_id}
|
||||
href={`/marketplace/${service.service_id}`}
|
||||
className="block group"
|
||||
className="block group w-full md:w-[calc(50%-16px)] lg:w-[calc(33%-16px)] xl:w-[calc(25%-16px)]"
|
||||
>
|
||||
<Card
|
||||
className={`
|
||||
@@ -220,11 +218,11 @@ export const Home: React.FC<HomeProps> = ({
|
||||
hover:scale-105 hover:shadow-xl
|
||||
transition-all duration-300 ease-out
|
||||
group-hover:bg-white/90 relative
|
||||
h-[200px]
|
||||
h-[200px] w-full
|
||||
`}
|
||||
>
|
||||
<CardBody className="p-6">
|
||||
{/* 创意图标 */}
|
||||
{/* creative icon */}
|
||||
<div
|
||||
className={` absolute -top-2 -left-2
|
||||
w-8 h-8 ${iconGradients[index % 6]}
|
||||
@@ -233,17 +231,18 @@ export const Home: React.FC<HomeProps> = ({
|
||||
`}
|
||||
></div>
|
||||
|
||||
{/* 服务标题 */}
|
||||
{/* service title */}
|
||||
<div className="text-lg font-bold text-gray-800 mb-2 group-hover:text-gray-900 transition-colors">
|
||||
{service.name}
|
||||
</div>
|
||||
|
||||
{/* 服务描述 */}
|
||||
<div className="text-sm text-gray-600 group-hover:text-gray-700 transition-colors flex-1">
|
||||
{service.short_description || "探索精彩服务"}
|
||||
{/* service description */}
|
||||
<div className="text-gray-600 text-sm line-clamp-3 leading-relaxed mb-4">
|
||||
{service.short_description ||
|
||||
t("No description available")}
|
||||
</div>
|
||||
|
||||
{/* 装饰性元素 */}
|
||||
{/* decorative elements */}
|
||||
<div className="absolute top-2 right-2 w-3 h-3 bg-gradient-to-r from-pink-400/30 to-orange-400/30 rounded-full opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
|
||||
</CardBody>
|
||||
|
||||
@@ -265,6 +264,8 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<Price
|
||||
price={service.price}
|
||||
charge_type={service.charge_type}
|
||||
input_token_price={service.input_token_price}
|
||||
output_token_price={service.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -317,6 +318,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
`}</style>
|
||||
</div>
|
||||
)}
|
||||
<Faq />
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -52,7 +52,12 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
</div>
|
||||
<div className="hidden lg:flex gap-6 justify-center">
|
||||
{items?.map((item) => (
|
||||
<Link href={item.href} className="text-sm text-gray-500">
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
target={item.target}
|
||||
className="text-sm text-gray-500"
|
||||
>
|
||||
{t(item.label)}
|
||||
</Link>
|
||||
))}
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { Tabs, Tab, Chip, Card, CardBody } from "@nextui-org/react";
|
||||
import { Tabs, Tab, Chip, Card, CardBody, Button } from "@nextui-org/react";
|
||||
import { ServiceData } from "@/shared/types/marketplace";
|
||||
import { ProductHeader } from "@/shared/components/marketplace/ProductHeader";
|
||||
import { ProductOverview } from "@/shared/components/marketplace/ProductOverview";
|
||||
import { ProductTools } from "@/shared/components/marketplace/ProductTools";
|
||||
import { ProductNotFound } from "@/shared/components/marketplace/ProductNotFound";
|
||||
import { Monitor, Code, Settings } from "lucide-react";
|
||||
import { Monitor, Code, Settings, Copy } from "lucide-react";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { Footer } from "./Footer";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
@@ -21,16 +21,19 @@ interface DetailProps {
|
||||
name: string;
|
||||
}[];
|
||||
url?: string;
|
||||
|
||||
mcpName?: string;
|
||||
// navigation items
|
||||
navItems?: NavigationItem[];
|
||||
onCopy: () => void;
|
||||
}
|
||||
|
||||
export const Detail: React.FC<DetailProps> = ({
|
||||
product,
|
||||
breadcrumbs,
|
||||
url,
|
||||
mcpName,
|
||||
navItems = [],
|
||||
onCopy,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState("overview");
|
||||
@@ -137,18 +140,26 @@ export const Detail: React.FC<DetailProps> = ({
|
||||
{/* Code Snippet */}
|
||||
<Card className="w-full max-w-2xl bg-black text-white p-2 sm:p-4 rounded-lg relative z-10">
|
||||
<div className="text-left font-mono">
|
||||
<Chip
|
||||
className="mb-2 text-white"
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<div className="flex items-center gap-2 mb-2 justify-between">
|
||||
<Chip className="text-white" size="sm" variant="flat">
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="flat"
|
||||
className="min-w-6 w-6 h-6 p-0 text-white"
|
||||
onPress={onCopy}
|
||||
aria-label={t("Copy code")}
|
||||
>
|
||||
<Copy size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
<pre className="p-2 sm:p-4 rounded-md text-xs overflow-x-auto">
|
||||
<code className="text-gray-300 whitespace-pre-wrap">
|
||||
{`{
|
||||
"mcpServers": {
|
||||
"xpack-mcp-market": {
|
||||
"${mcpName}": {
|
||||
"type": "sse",
|
||||
"autoApprove":"all",
|
||||
"url": "${url}?apikey=`}
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
import { Navigation } from "./Navigation";
|
||||
import { Footer } from "./Footer";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { Faq } from "@/components/marketplace/Faq";
|
||||
|
||||
interface HomeProps {
|
||||
// 状态
|
||||
@@ -106,7 +107,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
{/* Modern Search Bar */}
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<div className="bg-white p-1 rounded-xl shadow-sm border border-gray-100">
|
||||
<div className="flex">
|
||||
<div className="flex gap-1">
|
||||
<div className="flex-1">
|
||||
<Input
|
||||
size="lg"
|
||||
@@ -141,97 +142,103 @@ export const Home: React.FC<HomeProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Service List Section */}
|
||||
{loading ? (
|
||||
<div className="mx-auto h-[200px] flex items-center justify-center">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md">
|
||||
<Spinner size="lg" color="primary" />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="py-16">
|
||||
<div className="mx-auto px-6 max-w-7xl">
|
||||
{/* Services Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 mb-12">
|
||||
{services.map((service) => (
|
||||
<Link
|
||||
key={service.service_id}
|
||||
href={`/marketplace/${service.service_id}`}
|
||||
>
|
||||
<Card className="group h-[200px] hover:shadow-lg transition-all duration-200 cursor-pointer bg-white border border-gray-100 rounded-xl shadow-sm">
|
||||
<CardBody className="p-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
|
||||
<Zap className="w-4 h-4 text-blue-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="font-semibold text-gray-900 text-base mb-1 truncate group-hover:text-blue-600 transition-colors">
|
||||
{service.name}
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
<ArrowRight className="w-4 h-4 text-gray-400 group-hover:text-blue-600 transition-colors" />
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<p className="text-gray-600 text-sm line-clamp-3 leading-relaxed mb-4">
|
||||
{service.short_description ||
|
||||
t("No description available")}
|
||||
</p>
|
||||
</CardBody>
|
||||
|
||||
{/* Footer */}
|
||||
<CardFooter className="pt-0 px-4 pb-4">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
{/* Tools count */}
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-2 h-2 bg-blue-600 rounded-full"></div>
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
{t("{{count}} Tools", {
|
||||
count: service.tools.length,
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Price */}
|
||||
<div className="flex flex-col items-end">
|
||||
<Price
|
||||
price={service.price}
|
||||
charge_type={service.charge_type}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
<section>
|
||||
{/* Service List Section */}
|
||||
{loading ? (
|
||||
<div className="mx-auto h-[200px] flex items-center justify-center">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md">
|
||||
<Spinner size="lg" color="primary" />
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex justify-center">
|
||||
<Pagination
|
||||
total={totalPages}
|
||||
page={currentPage}
|
||||
onChange={onPageChange}
|
||||
showControls
|
||||
color="primary"
|
||||
variant="light"
|
||||
size="lg"
|
||||
classNames={{
|
||||
wrapper: "gap-2",
|
||||
item: "w-10 h-10 text-sm font-medium",
|
||||
cursor:
|
||||
"bg-gradient-to-r from-blue-500 to-indigo-600 shadow-sm",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
) : (
|
||||
<div className="py-16">
|
||||
<div className="mx-auto px-6 max-w-7xl">
|
||||
{/* Services Grid */}
|
||||
<div className="flex flex-wrap justify-center gap-4 mb-12">
|
||||
{services.map((service) => (
|
||||
<Link
|
||||
key={service.service_id}
|
||||
href={`/marketplace/${service.service_id}`}
|
||||
className="w-full md:w-[calc(50%-16px)] lg:w-[calc(33%-16px)] xl:w-[calc(25%-16px)]"
|
||||
>
|
||||
<Card className="group h-[200px] w-full hover:shadow-lg transition-all duration-200 cursor-pointer bg-white border border-gray-100 rounded-xl shadow-sm">
|
||||
<CardBody className="p-4">
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
|
||||
<Zap className="w-4 h-4 text-blue-600" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="font-semibold text-gray-900 text-base mb-1 truncate group-hover:text-blue-600 transition-colors">
|
||||
{service.name}
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
<ArrowRight className="w-4 h-4 text-gray-400 group-hover:text-blue-600 transition-colors" />
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<p className="text-gray-600 text-sm line-clamp-3 leading-relaxed mb-4">
|
||||
{service.short_description ||
|
||||
t("No description available")}
|
||||
</p>
|
||||
</CardBody>
|
||||
|
||||
{/* Footer */}
|
||||
<CardFooter className="pt-0 px-4 pb-4">
|
||||
<div className="flex items-center justify-between w-full">
|
||||
{/* Tools count */}
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-2 h-2 bg-blue-600 rounded-full"></div>
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
{t("{{count}} Tools", {
|
||||
count: service.tools.length,
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Price */}
|
||||
<div className="flex flex-col items-end">
|
||||
<Price
|
||||
price={service.price}
|
||||
charge_type={service.charge_type}
|
||||
input_token_price={service.input_token_price}
|
||||
output_token_price={service.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex justify-center">
|
||||
<Pagination
|
||||
total={totalPages}
|
||||
page={currentPage}
|
||||
onChange={onPageChange}
|
||||
showControls
|
||||
color="primary"
|
||||
variant="light"
|
||||
size="lg"
|
||||
classNames={{
|
||||
wrapper: "gap-2",
|
||||
item: "w-10 h-10 text-sm font-medium",
|
||||
cursor:
|
||||
"bg-gradient-to-r from-blue-500 to-indigo-600 shadow-sm",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
<Faq />
|
||||
|
||||
<Footer />
|
||||
</div>
|
||||
|
||||
@@ -48,7 +48,12 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
</div>
|
||||
<div className="hidden lg:flex gap-6 justify-center">
|
||||
{items?.map((item) => (
|
||||
<Link href={item.href} className="text-sm text-gray-500">
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
target={item.target}
|
||||
className="text-sm text-gray-500"
|
||||
>
|
||||
{t(item.label)}
|
||||
</Link>
|
||||
))}
|
||||
|
||||
@@ -2,13 +2,12 @@
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { Tabs, Tab, Chip, Card, CardBody } from "@nextui-org/react";
|
||||
import { Tabs, Tab, Chip, Card, CardBody, Button } from "@nextui-org/react";
|
||||
import { ServiceData } from "@/shared/types/marketplace";
|
||||
import { ProductHeader } from "@/shared/components/marketplace/ProductHeader";
|
||||
import { ProductOverview } from "@/shared/components/marketplace/ProductOverview";
|
||||
import { ProductTools } from "@/shared/components/marketplace/ProductTools";
|
||||
import { ProductNotFound } from "@/shared/components/marketplace/ProductNotFound";
|
||||
import { FileText, Wrench, Cog } from "lucide-react";
|
||||
import { FileText, Wrench, Cog, Copy } from "lucide-react";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { Footer } from "./Footer";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
@@ -21,16 +20,19 @@ interface DetailProps {
|
||||
name: string;
|
||||
}[];
|
||||
url?: string;
|
||||
|
||||
mcpName?: string;
|
||||
// navigation items
|
||||
navItems?: NavigationItem[];
|
||||
onCopy: () => void;
|
||||
}
|
||||
|
||||
export const Detail: React.FC<DetailProps> = ({
|
||||
product,
|
||||
breadcrumbs,
|
||||
url,
|
||||
mcpName,
|
||||
navItems = [],
|
||||
onCopy,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState("overview");
|
||||
@@ -158,18 +160,26 @@ export const Detail: React.FC<DetailProps> = ({
|
||||
{/* Code Snippet */}
|
||||
<Card className="w-full bg-black text-white p-2 sm:p-4 rounded-lg relative z-10">
|
||||
<div className="text-left font-mono">
|
||||
<Chip
|
||||
className="mb-2 text-white"
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<div className="flex items-center gap-2 mb-2 justify-between">
|
||||
<Chip className="text-white" size="sm" variant="flat">
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="flat"
|
||||
className="min-w-6 w-6 h-6 p-0 text-white"
|
||||
onPress={onCopy}
|
||||
aria-label={t("Copy code")}
|
||||
>
|
||||
<Copy size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
<pre className="p-2 sm:p-4 rounded-md text-xs overflow-x-auto">
|
||||
<code className="text-gray-300 whitespace-pre-wrap">
|
||||
{`{
|
||||
"mcpServers": {
|
||||
"xpack-mcp-market": {
|
||||
"${mcpName}": {
|
||||
"type": "sse",
|
||||
"autoApprove":"all",
|
||||
"url": "${url}?apikey=`}
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
import { Footer } from "./Footer";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { Faq } from "@/components/marketplace/Faq";
|
||||
|
||||
interface HomeProps {
|
||||
// 状态
|
||||
@@ -188,6 +189,8 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<Price
|
||||
price={service.price}
|
||||
charge_type={service.charge_type}
|
||||
input_token_price={service.input_token_price}
|
||||
output_token_price={service.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
</CardFooter>
|
||||
@@ -212,6 +215,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<Faq />
|
||||
</div>
|
||||
|
||||
<Footer />
|
||||
|
||||
@@ -52,7 +52,9 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
<div className="hidden lg:flex gap-8 justify-center ml-8">
|
||||
{items?.map((item) => (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
target={item.target}
|
||||
className="text-gray-700 hover:text-orange-500 font-medium transition-colors"
|
||||
>
|
||||
{t(item.label)}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import React, { useState } from "react";
|
||||
import {
|
||||
Modal,
|
||||
ModalContent,
|
||||
ModalHeader,
|
||||
ModalBody,
|
||||
ModalFooter,
|
||||
Button,
|
||||
Input,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { User } from "@/types/user";
|
||||
|
||||
interface AdminRechargeModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
user: User | null;
|
||||
onRecharge: (id: string, amount: number) => Promise<boolean>;
|
||||
}
|
||||
|
||||
export const AdminRechargeModal: React.FC<AdminRechargeModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
user,
|
||||
onRecharge,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [amount, setAmount] = useState<string>("");
|
||||
const [error, setError] = useState<string>("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const value = e.target.value;
|
||||
// 只允许输入数字和小数点
|
||||
if (/^\d*\.?\d*$/.test(value) || value === "") {
|
||||
setAmount(value);
|
||||
setError("");
|
||||
}
|
||||
};
|
||||
|
||||
const handleRecharge = async () => {
|
||||
const numAmount = parseFloat(amount);
|
||||
if (isNaN(numAmount) || numAmount <= 0) {
|
||||
setError(t("Please enter a valid amount"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (numAmount < 1) {
|
||||
setError(t("Minimum recharge amount is $1"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
setError(t("User not selected"));
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const success = await onRecharge(user.id, numAmount);
|
||||
|
||||
if (success) {
|
||||
handleClose();
|
||||
}
|
||||
} catch (error) {
|
||||
setError(t("Network error, please try again"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setAmount("");
|
||||
setError("");
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isOpen={isOpen} onClose={handleClose} size="sm">
|
||||
<ModalContent>
|
||||
{() => (
|
||||
<>
|
||||
<ModalHeader className="flex flex-col gap-1">
|
||||
{t("Recharge User")}
|
||||
</ModalHeader>
|
||||
<ModalBody>
|
||||
{user && (
|
||||
<div className="mb-4 p-3 bg-gray-50 rounded-lg">
|
||||
<p className="text-sm text-gray-600">
|
||||
{t("User")}: {user.email}
|
||||
</p>
|
||||
<p className="text-sm text-gray-600">
|
||||
{t("Current Balance")}: ${user.balance.toFixed(2)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<Input
|
||||
autoFocus
|
||||
label={t("Recharge Amount")}
|
||||
placeholder="0.00"
|
||||
value={amount}
|
||||
onChange={handleAmountChange}
|
||||
startContent={
|
||||
<div className="pointer-events-none flex items-center">
|
||||
<span className="text-default-400 text-small">$</span>
|
||||
</div>
|
||||
}
|
||||
isInvalid={!!error}
|
||||
errorMessage={error}
|
||||
type="number"
|
||||
/>
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button color="danger" variant="light" onPress={handleClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
color="primary"
|
||||
onPress={handleRecharge}
|
||||
isLoading={loading}
|
||||
isDisabled={!amount || !!error}
|
||||
>
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</>
|
||||
)}
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
@@ -12,8 +12,14 @@ const UserManagement: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// use custom hook to manage user data
|
||||
const { users, loading, pagination, handleDeleteUser, setPage } =
|
||||
useUserManagement();
|
||||
const {
|
||||
users,
|
||||
loading,
|
||||
pagination,
|
||||
handleDeleteUser,
|
||||
setPage,
|
||||
handleRechargeUser,
|
||||
} = useUserManagement();
|
||||
|
||||
// Modal states
|
||||
const [deleteModal, setDeleteModal] = useState({
|
||||
@@ -47,6 +53,13 @@ const UserManagement: React.FC = () => {
|
||||
setDeleteModal({ isOpen: false, user: null });
|
||||
}, []);
|
||||
|
||||
const handleRecharge = useCallback(
|
||||
async (id: string, amount: number): Promise<boolean> => {
|
||||
return await handleRechargeUser(id, amount);
|
||||
},
|
||||
[handleRechargeUser]
|
||||
);
|
||||
|
||||
return (
|
||||
<DashboardDemoContent
|
||||
title={t("User Management")}
|
||||
@@ -59,6 +72,7 @@ const UserManagement: React.FC = () => {
|
||||
users={users}
|
||||
loading={loading}
|
||||
onDelete={handleDeleteUserClick}
|
||||
onRecharge={handleRecharge}
|
||||
pagination={pagination}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React from 'react';
|
||||
import React from "react";
|
||||
import {
|
||||
Table,
|
||||
TableHeader,
|
||||
@@ -11,16 +11,18 @@ import {
|
||||
Button,
|
||||
Pagination,
|
||||
Tooltip,
|
||||
Spinner
|
||||
} from '@nextui-org/react';
|
||||
import { useTranslation } from '@/shared/lib/useTranslation';
|
||||
import { User } from '@/types/user';
|
||||
import { Trash2 } from 'lucide-react';
|
||||
Spinner,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { User } from "@/types/user";
|
||||
import { Trash2, CreditCard } from "lucide-react";
|
||||
import { AdminRechargeModal } from "@/components/user-management/AdminRechargeModal";
|
||||
|
||||
interface UserTableProps {
|
||||
users: User[];
|
||||
loading?: boolean;
|
||||
onDelete: (user: User) => void;
|
||||
onRecharge: (id: string, amount: number) => Promise<boolean>;
|
||||
pagination: {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
@@ -33,6 +35,7 @@ export const UserTable: React.FC<UserTableProps> = ({
|
||||
users,
|
||||
loading = false,
|
||||
onDelete,
|
||||
onRecharge,
|
||||
pagination,
|
||||
onPageChange,
|
||||
}) => {
|
||||
@@ -45,10 +48,25 @@ export const UserTable: React.FC<UserTableProps> = ({
|
||||
// 直接显示传入的用户数据(已经是当前页的数据)
|
||||
const items = users;
|
||||
|
||||
const [isRechargeModalOpen, setIsRechargeModalOpen] = React.useState(false);
|
||||
const [selectedUser, setSelectedUser] = React.useState<User | null>(null);
|
||||
|
||||
const handleDelete = React.useCallback((user: User) => {
|
||||
onDelete(user);
|
||||
}, [onDelete]);
|
||||
const handleDelete = React.useCallback(
|
||||
(user: User) => {
|
||||
onDelete(user);
|
||||
},
|
||||
[onDelete]
|
||||
);
|
||||
|
||||
const handleRecharge = React.useCallback((user: User) => {
|
||||
setSelectedUser(user);
|
||||
setIsRechargeModalOpen(true);
|
||||
}, []);
|
||||
|
||||
const handleRechargeClose = React.useCallback(() => {
|
||||
setIsRechargeModalOpen(false);
|
||||
setSelectedUser(null);
|
||||
}, []);
|
||||
|
||||
if (loading && users.length === 0) {
|
||||
return (
|
||||
@@ -68,33 +86,50 @@ export const UserTable: React.FC<UserTableProps> = ({
|
||||
removeWrapper
|
||||
>
|
||||
<TableHeader>
|
||||
<TableColumn>{t('Email')}</TableColumn>
|
||||
<TableColumn>{t('Register Date')}</TableColumn>
|
||||
<TableColumn>{t('Balance')}</TableColumn>
|
||||
<TableColumn>{t('Actions')}</TableColumn>
|
||||
<TableColumn>{t("Email")}</TableColumn>
|
||||
<TableColumn>{t("Register Date")}</TableColumn>
|
||||
<TableColumn>{t("Balance")}</TableColumn>
|
||||
<TableColumn>{t("Actions")}</TableColumn>
|
||||
</TableHeader>
|
||||
<TableBody
|
||||
items={items}
|
||||
isLoading={loading}
|
||||
loadingContent={<Spinner />}
|
||||
emptyContent={t('No users found')}
|
||||
emptyContent={t("No users found")}
|
||||
>
|
||||
{(user) => (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell>
|
||||
<span className="text-sm">{user.email}</span>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{user.created_at || '-'}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{user.balance.toFixed(2) || "-"}
|
||||
</TableCell>
|
||||
<TableCell>{user.created_at || "-"}</TableCell>
|
||||
<TableCell>{user.balance.toFixed(2) || "-"}</TableCell>
|
||||
|
||||
<TableCell>
|
||||
<div className="relative flex items-center gap-2">
|
||||
<Tooltip
|
||||
content={t("Recharge User")}
|
||||
color="primary"
|
||||
closeDelay={0}
|
||||
disableAnimation
|
||||
>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
color="primary"
|
||||
onPress={() => handleRecharge(user)}
|
||||
>
|
||||
<CreditCard className="w-4 h-4" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip content={t('Delete User')} color="danger" closeDelay={0}>
|
||||
<Tooltip
|
||||
content={t("Delete User")}
|
||||
color="danger"
|
||||
closeDelay={0}
|
||||
disableAnimation
|
||||
>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
@@ -124,6 +159,14 @@ export const UserTable: React.FC<UserTableProps> = ({
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Admin Recharge Modal */}
|
||||
<AdminRechargeModal
|
||||
isOpen={isRechargeModalOpen}
|
||||
onClose={handleRechargeClose}
|
||||
user={selectedUser}
|
||||
onRecharge={onRecharge}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useState, useCallback, useEffect } from "react";
|
||||
import { HomepageConfig } from "@/services/homepageConfigService";
|
||||
import {
|
||||
FaqItem,
|
||||
TopNavigationItem,
|
||||
EmbeddedHtmlConfig,
|
||||
} from "@/shared/types/system";
|
||||
import { homepageConfigService } from "@/services/homepageConfigService";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
import { revalidatePlatformConfig } from "@/app/actions/revalidate";
|
||||
|
||||
export const useHomepageConfigManagement = () => {
|
||||
const { updateClientConfig } = usePlatformConfig();
|
||||
|
||||
// homepage config state
|
||||
const [homepageConfig, setHomepageConfig] = useState<HomepageConfig>({
|
||||
faq: [],
|
||||
top_navigation: [],
|
||||
embeded_html: {
|
||||
is_enabled: false,
|
||||
html: "",
|
||||
},
|
||||
});
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// load homepage config
|
||||
const loadHomepageConfig = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const config = await homepageConfigService.getHomepageConfig();
|
||||
setHomepageConfig(config);
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Failed to load homepage config";
|
||||
setError(errorMessage);
|
||||
console.error("Failed to load homepage config:", err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// save homepage config
|
||||
const saveHomepageConfig = useCallback(
|
||||
async (config: {
|
||||
faq?: FaqItem[];
|
||||
top_navigation?: TopNavigationItem[];
|
||||
embeded_html?: EmbeddedHtmlConfig;
|
||||
}): Promise<boolean> => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await homepageConfigService.updateHomepageConfig(config);
|
||||
if (result) {
|
||||
updateClientConfig(config);
|
||||
await revalidatePlatformConfig();
|
||||
}
|
||||
return result;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Failed to save homepage config";
|
||||
setError(errorMessage);
|
||||
console.error("Failed to save homepage config:", err);
|
||||
return false;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
// save FAQ data
|
||||
const saveFaqConfig = useCallback(
|
||||
async (faqs: FaqItem[]): Promise<boolean> => {
|
||||
return await saveHomepageConfig({ faq: faqs });
|
||||
},
|
||||
[saveHomepageConfig]
|
||||
);
|
||||
|
||||
// save navigation data
|
||||
const saveNavigationConfig = useCallback(
|
||||
async (navigationItems: TopNavigationItem[]): Promise<boolean> => {
|
||||
return await saveHomepageConfig({ top_navigation: navigationItems });
|
||||
},
|
||||
[saveHomepageConfig]
|
||||
);
|
||||
|
||||
// save embedded HTML data
|
||||
const saveEmbeddedHtmlConfig = useCallback(
|
||||
async (htmlData: EmbeddedHtmlConfig): Promise<boolean> => {
|
||||
return await saveHomepageConfig({ embeded_html: htmlData });
|
||||
},
|
||||
[saveHomepageConfig]
|
||||
);
|
||||
|
||||
// clear error
|
||||
const clearError = useCallback(() => setError(null), []);
|
||||
|
||||
// load config on init
|
||||
useEffect(() => {
|
||||
loadHomepageConfig();
|
||||
}, [loadHomepageConfig]);
|
||||
|
||||
return {
|
||||
// state
|
||||
homepageConfig,
|
||||
loading,
|
||||
error,
|
||||
|
||||
// actions
|
||||
loadHomepageConfig,
|
||||
saveHomepageConfig,
|
||||
saveFaqConfig,
|
||||
saveNavigationConfig,
|
||||
saveEmbeddedHtmlConfig,
|
||||
clearError,
|
||||
};
|
||||
};
|
||||
@@ -2,22 +2,41 @@ import { useState, useEffect, useCallback } from "react";
|
||||
import {
|
||||
PaymentChannelApiItem,
|
||||
StripeConfig,
|
||||
AlipayConfig,
|
||||
WechatConfig,
|
||||
PaymentChannelTestResult,
|
||||
} from "@/types/payment";
|
||||
import { paymentChannelService } from "@/services/paymentChannelService";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
import { revalidatePlatformConfig } from "@/app/actions/revalidate";
|
||||
|
||||
export const usePaymentChannelManagement = () => {
|
||||
const { updateClientConfig, paymentChannels } = usePlatformConfig();
|
||||
const [channels, setChannels] = useState<PaymentChannelApiItem[]>([]);
|
||||
const [stripeConfig, setStripeConfig] = useState<StripeConfig>({
|
||||
secret: "",
|
||||
webhook_secret: "",
|
||||
is_enabled: false,
|
||||
});
|
||||
const [alipayConfig, setAlipayConfig] = useState<AlipayConfig>({
|
||||
app_id: "",
|
||||
app_private_key: "",
|
||||
alipay_public_key: "",
|
||||
is_enabled: false,
|
||||
});
|
||||
const [wechatConfig, setWechatConfig] = useState<WechatConfig>({
|
||||
app_id: "",
|
||||
mch_id: "",
|
||||
is_enabled: false,
|
||||
});
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [testResult, setTestResult] = useState<PaymentChannelTestResult | null>(
|
||||
null
|
||||
);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [isWechatSaving, setIsWechatSaving] = useState(false);
|
||||
const [isStripeSaving, setIsStripeSaving] = useState(false);
|
||||
const [isAlipaySaving, setIsAlipaySaving] = useState(false);
|
||||
|
||||
// get payment channel list
|
||||
const fetchChannels = useCallback(async () => {
|
||||
@@ -29,12 +48,35 @@ export const usePaymentChannelManagement = () => {
|
||||
|
||||
setChannels(response.data);
|
||||
|
||||
// find stripe channel and get config
|
||||
// find channels and get configs
|
||||
const stripeChannel = response.data.find(
|
||||
(channel) => channel.id === "stripe"
|
||||
);
|
||||
if (stripeChannel) {
|
||||
setStripeConfig(stripeChannel.config);
|
||||
setStripeConfig({
|
||||
...stripeChannel.config,
|
||||
is_enabled: stripeChannel.is_enabled,
|
||||
} as StripeConfig);
|
||||
}
|
||||
|
||||
const alipayChannel = response.data.find(
|
||||
(channel) => channel.id === "alipay"
|
||||
);
|
||||
if (alipayChannel) {
|
||||
setAlipayConfig({
|
||||
...alipayChannel.config,
|
||||
is_enabled: alipayChannel.is_enabled,
|
||||
} as AlipayConfig);
|
||||
}
|
||||
|
||||
const wechatChannel = response.data.find(
|
||||
(channel) => channel.id === "wechat"
|
||||
);
|
||||
if (wechatChannel) {
|
||||
setWechatConfig({
|
||||
...wechatChannel.config,
|
||||
is_enabled: wechatChannel.is_enabled,
|
||||
} as WechatConfig);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(
|
||||
@@ -48,9 +90,103 @@ export const usePaymentChannelManagement = () => {
|
||||
}
|
||||
}, []);
|
||||
|
||||
// test alipay connection
|
||||
const testAlipayConnection = useCallback(async (config: AlipayConfig) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await paymentChannelService.testAlipayConnection(config);
|
||||
setTestResult(result);
|
||||
return result;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Failed to test alipay connection";
|
||||
const failedResult: PaymentChannelTestResult = {
|
||||
success: false,
|
||||
message: errorMessage,
|
||||
};
|
||||
setTestResult(failedResult);
|
||||
setError(errorMessage);
|
||||
return failedResult;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// test wechat connection
|
||||
const testWechatConnection = useCallback(async (config: WechatConfig) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await paymentChannelService.testWechatConnection(config);
|
||||
setTestResult(result);
|
||||
return result;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Failed to test wechat connection";
|
||||
const failedResult: PaymentChannelTestResult = {
|
||||
success: false,
|
||||
message: errorMessage,
|
||||
};
|
||||
setTestResult(failedResult);
|
||||
setError(errorMessage);
|
||||
return failedResult;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// save alipay config
|
||||
const saveAlipayConfig = useCallback(async (config: AlipayConfig) => {
|
||||
setIsAlipaySaving(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await paymentChannelService.saveAlipayConfig(config);
|
||||
if (result) {
|
||||
setAlipayConfig(config);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Failed to save alipay config";
|
||||
setError(errorMessage);
|
||||
return false;
|
||||
} finally {
|
||||
setIsAlipaySaving(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// save wechat config
|
||||
const saveWechatConfig = useCallback(async (config: WechatConfig) => {
|
||||
setIsWechatSaving(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await paymentChannelService.saveWechatConfig(config);
|
||||
if (result) {
|
||||
setWechatConfig(config);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Failed to save wechat config";
|
||||
setError(errorMessage);
|
||||
return false;
|
||||
} finally {
|
||||
setIsWechatSaving(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// save stripe config
|
||||
const saveStripeConfig = useCallback(async (config: StripeConfig) => {
|
||||
setIsSaving(true);
|
||||
setIsStripeSaving(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
@@ -67,7 +203,7 @@ export const usePaymentChannelManagement = () => {
|
||||
setError(errorMessage);
|
||||
return false;
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
setIsStripeSaving(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -102,16 +238,25 @@ export const usePaymentChannelManagement = () => {
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await paymentChannelService.enablePaymentChannel(channelId);
|
||||
await fetchChannels(); // re-fetch list
|
||||
return { success: true };
|
||||
const result =
|
||||
await paymentChannelService.enablePaymentChannel(channelId);
|
||||
if (result) {
|
||||
updateClientConfig({
|
||||
payment_channels: [
|
||||
...paymentChannels,
|
||||
{ id: channelId, name: channelId },
|
||||
],
|
||||
});
|
||||
await revalidatePlatformConfig();
|
||||
}
|
||||
return result;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Failed to enable payment channel";
|
||||
setError(errorMessage);
|
||||
return { success: false, message: errorMessage };
|
||||
return false;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -126,16 +271,24 @@ export const usePaymentChannelManagement = () => {
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await paymentChannelService.disablePaymentChannel(channelId);
|
||||
await fetchChannels(); // re-fetch list
|
||||
return { success: true };
|
||||
const result =
|
||||
await paymentChannelService.disablePaymentChannel(channelId);
|
||||
if (result) {
|
||||
updateClientConfig({
|
||||
payment_channels: paymentChannels.filter(
|
||||
(channel) => channel.id !== channelId
|
||||
),
|
||||
});
|
||||
await revalidatePlatformConfig();
|
||||
}
|
||||
return result;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Failed to disable payment channel";
|
||||
setError(errorMessage);
|
||||
return { success: false, message: errorMessage };
|
||||
return false;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -161,13 +314,21 @@ export const usePaymentChannelManagement = () => {
|
||||
return {
|
||||
channels,
|
||||
stripeConfig,
|
||||
isSaving,
|
||||
alipayConfig,
|
||||
wechatConfig,
|
||||
isWechatSaving,
|
||||
isStripeSaving,
|
||||
isAlipaySaving,
|
||||
loading,
|
||||
error,
|
||||
testResult,
|
||||
fetchChannels,
|
||||
saveStripeConfig,
|
||||
saveAlipayConfig,
|
||||
saveWechatConfig,
|
||||
testStripeConnection,
|
||||
testAlipayConnection,
|
||||
testWechatConnection,
|
||||
enableChannel,
|
||||
disableChannel,
|
||||
clearTestResult,
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { useState, useCallback, useEffect } from "react";
|
||||
import { PlatformConfig, LoginConfig, EmailMode } from "@/shared/types/system";
|
||||
import {
|
||||
PlatformConfig,
|
||||
LoginConfig,
|
||||
EmailMode,
|
||||
FaqItem,
|
||||
TopNavigationItem,
|
||||
EmbeddedHtmlConfig,
|
||||
PaymentChannel
|
||||
} from "@/shared/types/system";
|
||||
import { systemConfigService } from "@/services/systemConfigService";
|
||||
import { AdminConfig, EmailConfig } from "@/types/system";
|
||||
import { md5Encrypt } from "@/shared/utils/crypto";
|
||||
@@ -49,6 +57,29 @@ export const useSystemConfigManagement = () => {
|
||||
const [loginLoading, setLoginLoading] = useState(false);
|
||||
const [loginError, setLoginError] = useState<string | null>(null);
|
||||
|
||||
// faq config
|
||||
const [faqItems, setFaqItems] = useState<FaqItem[]>([]);
|
||||
const [faqLoading, setFaqLoading] = useState(false);
|
||||
const [faqError, setFaqError] = useState<string | null>(null);
|
||||
|
||||
// top navigation config
|
||||
const [topNavigation, setTopNavigation] = useState<TopNavigationItem[]>([]);
|
||||
const [navigationLoading, setNavigationLoading] = useState(false);
|
||||
const [navigationError, setNavigationError] = useState<string | null>(null);
|
||||
|
||||
// embedded html config
|
||||
const [embeddedHtml, setEmbeddedHtml] = useState<EmbeddedHtmlConfig | null>(null);
|
||||
const [embeddedHtmlLoading, setEmbeddedHtmlLoading] = useState(false);
|
||||
const [embeddedHtmlError, setEmbeddedHtmlError] = useState<string | null>(null);
|
||||
|
||||
// payment channels config
|
||||
const [paymentChannels, setPaymentChannels] = useState<PaymentChannel[]>([]);
|
||||
const [paymentLoading, setPaymentLoading] = useState(false);
|
||||
const [paymentError, setPaymentError] = useState<string | null>(null);
|
||||
|
||||
// installation status
|
||||
const [isInstalled, setIsInstalled] = useState<boolean>(false);
|
||||
|
||||
// global loading
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
@@ -80,6 +111,11 @@ export const useSystemConfigManagement = () => {
|
||||
mode: EmailMode.PASSWORD,
|
||||
},
|
||||
});
|
||||
setFaqItems(response.faq || []);
|
||||
setTopNavigation(response.top_navigation || []);
|
||||
setEmbeddedHtml(response.embeded_html || null);
|
||||
setPaymentChannels(response.payment_channels || []);
|
||||
setIsInstalled(response.is_installed || false);
|
||||
} catch (error) {
|
||||
console.error("Failed to load configurations:", error);
|
||||
} finally {
|
||||
@@ -160,11 +196,71 @@ export const useSystemConfigManagement = () => {
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
// save faq config
|
||||
const saveFaqConfig = useCallback(async (items: FaqItem[]) => {
|
||||
setFaqLoading(true);
|
||||
setFaqError(null);
|
||||
const result = await systemConfigService.updateSystemConfig({
|
||||
faq: items,
|
||||
}, "faq");
|
||||
if (result) {
|
||||
setFaqItems(items);
|
||||
}
|
||||
setFaqLoading(false);
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
// save top navigation config
|
||||
const saveTopNavigationConfig = useCallback(async (items: TopNavigationItem[]) => {
|
||||
setNavigationLoading(true);
|
||||
setNavigationError(null);
|
||||
const result = await systemConfigService.updateSystemConfig({
|
||||
top_navigation: items,
|
||||
}, "navigation");
|
||||
if (result) {
|
||||
setTopNavigation(items);
|
||||
}
|
||||
setNavigationLoading(false);
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
// save embedded html config
|
||||
const saveEmbeddedHtmlConfig = useCallback(async (config: EmbeddedHtmlConfig) => {
|
||||
setEmbeddedHtmlLoading(true);
|
||||
setEmbeddedHtmlError(null);
|
||||
const result = await systemConfigService.updateSystemConfig({
|
||||
embeded_html: config,
|
||||
}, "embedded_html");
|
||||
if (result) {
|
||||
setEmbeddedHtml(config);
|
||||
}
|
||||
setEmbeddedHtmlLoading(false);
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
// save payment channels config
|
||||
const savePaymentChannelsConfig = useCallback(async (channels: PaymentChannel[]) => {
|
||||
setPaymentLoading(true);
|
||||
setPaymentError(null);
|
||||
const result = await systemConfigService.updateSystemConfig({
|
||||
payment_channels: channels,
|
||||
}, "payment");
|
||||
if (result) {
|
||||
setPaymentChannels(channels);
|
||||
}
|
||||
setPaymentLoading(false);
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
// clear errors
|
||||
const clearPlatformError = useCallback(() => setPlatformError(null), []);
|
||||
const clearAdminError = useCallback(() => setAdminError(null), []);
|
||||
const clearEmailError = useCallback(() => setEmailError(null), []);
|
||||
const clearLoginError = useCallback(() => setLoginError(null), []);
|
||||
const clearFaqError = useCallback(() => setFaqError(null), []);
|
||||
const clearNavigationError = useCallback(() => setNavigationError(null), []);
|
||||
const clearEmbeddedHtmlError = useCallback(() => setEmbeddedHtmlError(null), []);
|
||||
const clearPaymentError = useCallback(() => setPaymentError(null), []);
|
||||
|
||||
// load configs on init
|
||||
useEffect(() => {
|
||||
@@ -217,6 +313,42 @@ export const useSystemConfigManagement = () => {
|
||||
saveLoginConfig,
|
||||
clearLoginError,
|
||||
|
||||
// faq config
|
||||
faqItems,
|
||||
setFaqItems,
|
||||
faqLoading,
|
||||
faqError,
|
||||
saveFaqConfig,
|
||||
clearFaqError,
|
||||
|
||||
// top navigation config
|
||||
topNavigation,
|
||||
setTopNavigation,
|
||||
navigationLoading,
|
||||
navigationError,
|
||||
saveTopNavigationConfig,
|
||||
clearNavigationError,
|
||||
|
||||
// embedded html config
|
||||
embeddedHtml,
|
||||
setEmbeddedHtml,
|
||||
embeddedHtmlLoading,
|
||||
embeddedHtmlError,
|
||||
saveEmbeddedHtmlConfig,
|
||||
clearEmbeddedHtmlError,
|
||||
|
||||
// payment channels config
|
||||
paymentChannels,
|
||||
setPaymentChannels,
|
||||
paymentLoading,
|
||||
paymentError,
|
||||
savePaymentChannelsConfig,
|
||||
clearPaymentError,
|
||||
|
||||
// installation status
|
||||
isInstalled,
|
||||
setIsInstalled,
|
||||
|
||||
// image upload
|
||||
uploadImage,
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { User } from "@/types/user";
|
||||
import { getUserList, deleteUser } from "@/services/userService";
|
||||
import { getUserList, deleteUser, rechargeUser } from "@/services/userService";
|
||||
|
||||
interface PaginationInfo {
|
||||
page: number;
|
||||
@@ -67,6 +67,28 @@ export const useUserManagement = () => {
|
||||
},
|
||||
[fetchUsers]
|
||||
);
|
||||
const handleRechargeUser = async (
|
||||
userId: string,
|
||||
amount: number
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
const result = await rechargeUser(userId, amount);
|
||||
if (result) {
|
||||
// after recharge, fetch users again
|
||||
setUsers((prevUsers: User[]) =>
|
||||
prevUsers.map((user: User) =>
|
||||
user.id === userId
|
||||
? { ...user, balance: user.balance + amount }
|
||||
: user
|
||||
)
|
||||
);
|
||||
return true;
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Recharge user failed");
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const setSearch = useCallback((search: string) => {
|
||||
setSearchQuery(search);
|
||||
@@ -88,6 +110,7 @@ export const useUserManagement = () => {
|
||||
|
||||
return {
|
||||
users,
|
||||
handleRechargeUser,
|
||||
loading,
|
||||
error,
|
||||
searchQuery,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { fetchAdminAPI } from "@/rpc/admin-api";
|
||||
import i18n from "@/shared/lib/i18n";
|
||||
import {
|
||||
EmbeddedHtmlConfig,
|
||||
FaqItem,
|
||||
TopNavigationItem,
|
||||
} from "@/shared/types/system";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
export interface HomepageConfig {
|
||||
faq: FaqItem[];
|
||||
top_navigation: TopNavigationItem[];
|
||||
embeded_html: EmbeddedHtmlConfig;
|
||||
}
|
||||
|
||||
export class HomepageConfigService {
|
||||
// get homepage config
|
||||
async getHomepageConfig(): Promise<HomepageConfig> {
|
||||
const response = await fetchAdminAPI<HomepageConfig>(
|
||||
"/api/sysconfig/homepage",
|
||||
{
|
||||
method: "GET",
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.success) {
|
||||
throw new Error(
|
||||
response.error_message || "Failed to fetch homepage config"
|
||||
);
|
||||
}
|
||||
return response.data;
|
||||
}
|
||||
|
||||
// update homepage config
|
||||
async updateHomepageConfig(config: {
|
||||
faq?: FaqItem[];
|
||||
top_navigation?: TopNavigationItem[];
|
||||
embeded_html?: EmbeddedHtmlConfig;
|
||||
}): Promise<boolean> {
|
||||
const response = await fetchAdminAPI("/api/sysconfig/homepage", {
|
||||
method: "PUT",
|
||||
body: config as unknown as BodyInit,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
toast.error(
|
||||
response.error_message || i18n.t("Failed to update homepage config")
|
||||
);
|
||||
return false;
|
||||
}
|
||||
toast.success(i18n.t("Homepage config updated successfully"));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export const homepageConfigService = new HomepageConfigService();
|
||||
@@ -1,5 +1,7 @@
|
||||
import {
|
||||
StripeConfig,
|
||||
AlipayConfig,
|
||||
WechatConfig,
|
||||
PaymentChannelApiItem,
|
||||
PaymentChannelListResponse,
|
||||
PaymentChannelTestResult,
|
||||
@@ -52,50 +54,74 @@ export class PaymentChannelService {
|
||||
return response.data;
|
||||
}
|
||||
|
||||
// Save Stripe configuration
|
||||
async saveStripeConfig(config: StripeConfig): Promise<boolean> {
|
||||
const response = await fetchAdminAPI<StripeConfig>(
|
||||
"/api/payment_channel/info",
|
||||
{
|
||||
method: "PUT",
|
||||
body: {
|
||||
id: "stripe",
|
||||
config: config,
|
||||
} as unknown as BodyInit,
|
||||
}
|
||||
);
|
||||
// Generic method to save payment channel configuration
|
||||
async savePaymentChannelConfig<T>(
|
||||
channelId: string,
|
||||
config: T,
|
||||
channelName: string
|
||||
): Promise<boolean> {
|
||||
const response = await fetchAdminAPI<T>("/api/payment_channel/info", {
|
||||
method: "PUT",
|
||||
body: {
|
||||
id: channelId,
|
||||
config: {
|
||||
...config,
|
||||
is_enabled: undefined,
|
||||
},
|
||||
} as unknown as BodyInit,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
toast.error(
|
||||
response.error_message || i18n.t("Failed to save Stripe config")
|
||||
response.error_message ||
|
||||
i18n.t("Failed to save {{channelName}} config", { channelName })
|
||||
);
|
||||
return false;
|
||||
}
|
||||
toast.success(i18n.t("Stripe config saved successfully"));
|
||||
toast.success(
|
||||
i18n.t("{{channelName}} config saved successfully", { channelName })
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Test Stripe connection
|
||||
async testStripeConnection(
|
||||
config: StripeConfig
|
||||
// Save Stripe configuration
|
||||
async saveStripeConfig(config: StripeConfig): Promise<boolean> {
|
||||
return this.savePaymentChannelConfig("stripe", config, "Stripe");
|
||||
}
|
||||
|
||||
// Generic method to test payment channel connection
|
||||
async testPaymentChannelConnection<T>(
|
||||
channelId: string,
|
||||
config: T,
|
||||
channelName: string
|
||||
): Promise<PaymentChannelTestResult> {
|
||||
try {
|
||||
const response = await fetchAdminAPI<any>("/api/payment_channel/info", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(config),
|
||||
const response = await fetchAdminAPI<any>("/api/payment_channel/test", {
|
||||
method: "POST",
|
||||
body: {
|
||||
id: channelId,
|
||||
config: {
|
||||
...config,
|
||||
is_enabled: undefined,
|
||||
},
|
||||
} as unknown as BodyInit,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
return {
|
||||
success: false,
|
||||
message: response.error_message || "Stripe connection test failed",
|
||||
message:
|
||||
response.error_message ||
|
||||
i18n.t("{{channelName}} connection test failed", { channelName }),
|
||||
details: response.data,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Stripe connection test successful",
|
||||
message: i18n.t("{{channelName}} connection test successful", {
|
||||
channelName,
|
||||
}),
|
||||
details: response.data,
|
||||
};
|
||||
} catch (error) {
|
||||
@@ -106,36 +132,73 @@ export class PaymentChannelService {
|
||||
}
|
||||
}
|
||||
|
||||
// Test Stripe connection
|
||||
async testStripeConnection(
|
||||
config: StripeConfig
|
||||
): Promise<PaymentChannelTestResult> {
|
||||
return this.testPaymentChannelConnection("stripe", config, "Stripe");
|
||||
}
|
||||
|
||||
// enable payment channel
|
||||
async enablePaymentChannel(id: string): Promise<void> {
|
||||
async enablePaymentChannel(id: string): Promise<boolean> {
|
||||
const response = await fetchAdminAPI("/api/payment_channel/enable", {
|
||||
method: "POST",
|
||||
method: "PUT",
|
||||
body: {
|
||||
id,
|
||||
} as unknown as BodyInit,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
throw new Error(
|
||||
response.error_message || "Failed to enable payment channel"
|
||||
toast.error(
|
||||
response.error_message || i18n.t("Failed to enable payment channel")
|
||||
);
|
||||
return false;
|
||||
}
|
||||
toast.success(i18n.t("Payment channel enabled successfully"));
|
||||
return true;
|
||||
}
|
||||
|
||||
// disable payment channel
|
||||
async disablePaymentChannel(id: string): Promise<void> {
|
||||
async disablePaymentChannel(id: string): Promise<boolean> {
|
||||
const response = await fetchAdminAPI("/api/payment_channel/disable", {
|
||||
method: "POST",
|
||||
method: "PUT",
|
||||
body: {
|
||||
id,
|
||||
} as unknown as BodyInit,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
throw new Error(
|
||||
response.error_message || "Failed to disable payment channel"
|
||||
toast.error(
|
||||
response.error_message || i18n.t("Failed to disable payment channel")
|
||||
);
|
||||
return false;
|
||||
}
|
||||
toast.success(i18n.t("Payment channel disabled successfully"));
|
||||
return true;
|
||||
}
|
||||
|
||||
// Save Alipay configuration
|
||||
async saveAlipayConfig(config: AlipayConfig): Promise<boolean> {
|
||||
return this.savePaymentChannelConfig("alipay", config, "Alipay");
|
||||
}
|
||||
|
||||
// Save WeChat configuration
|
||||
async saveWechatConfig(config: WechatConfig): Promise<boolean> {
|
||||
return this.savePaymentChannelConfig("wechat", config, "WeChat");
|
||||
}
|
||||
|
||||
// Test Alipay connection
|
||||
async testAlipayConnection(
|
||||
config: AlipayConfig
|
||||
): Promise<PaymentChannelTestResult> {
|
||||
return this.testPaymentChannelConnection("alipay", config, "Alipay");
|
||||
}
|
||||
|
||||
// Test WeChat connection
|
||||
async testWechatConnection(
|
||||
config: WechatConfig
|
||||
): Promise<PaymentChannelTestResult> {
|
||||
return this.testPaymentChannelConnection("wechat", config, "WeChat");
|
||||
}
|
||||
|
||||
// validate stripe config
|
||||
|
||||
@@ -37,10 +37,26 @@ export class PlatformConfigService {
|
||||
console.error(response.error_message);
|
||||
return {
|
||||
platform: _DefaultPlatformConfig,
|
||||
login: undefined,
|
||||
faq: [],
|
||||
top_navigation: [],
|
||||
embeded_html: undefined,
|
||||
payment_channels: [],
|
||||
is_installed: false,
|
||||
};
|
||||
}
|
||||
|
||||
return response.data;
|
||||
// 确保返回的数据结构正确
|
||||
const data = response.data;
|
||||
return {
|
||||
platform: data.platform || _DefaultPlatformConfig,
|
||||
login: data.login,
|
||||
faq: data.faq || [],
|
||||
top_navigation: data.top_navigation || [],
|
||||
embeded_html: data.embeded_html,
|
||||
payment_channels: data.payment_channels || [],
|
||||
is_installed: data.is_installed || false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { fetchAdminAPI } from "@/rpc/admin-api";
|
||||
import i18n from "@/shared/lib/i18n";
|
||||
import { PlatformConfig, LoginConfig } from "@/shared/types/system";
|
||||
import {
|
||||
PlatformConfig,
|
||||
LoginConfig,
|
||||
FaqItem,
|
||||
TopNavigationItem,
|
||||
EmbeddedHtmlConfig,
|
||||
PaymentChannel
|
||||
} from "@/shared/types/system";
|
||||
import { AdminConfig, EmailConfig, SystemConfigApiData } from "@/types/system";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
@@ -29,8 +36,13 @@ export class SystemConfigService {
|
||||
account?: AdminConfig;
|
||||
email?: EmailConfig;
|
||||
login?: LoginConfig;
|
||||
faq?: FaqItem[];
|
||||
top_navigation?: TopNavigationItem[];
|
||||
embeded_html?: EmbeddedHtmlConfig;
|
||||
payment_channels?: PaymentChannel[];
|
||||
is_installed?: boolean;
|
||||
},
|
||||
key?: "theme" | "about"
|
||||
key?: "theme" | "about" | "faq" | "navigation" | "embedded_html" | "payment"
|
||||
): Promise<boolean> {
|
||||
const response = await fetchAdminAPI("/api/sysconfig/info", {
|
||||
method: "PUT",
|
||||
@@ -50,6 +62,18 @@ export class SystemConfigService {
|
||||
case "about":
|
||||
toast.success(i18n.t("About page saved successfully"));
|
||||
break;
|
||||
case "faq":
|
||||
toast.success(i18n.t("FAQ updated successfully"));
|
||||
break;
|
||||
case "navigation":
|
||||
toast.success(i18n.t("Navigation updated successfully"));
|
||||
break;
|
||||
case "embedded_html":
|
||||
toast.success(i18n.t("Embedded HTML updated successfully"));
|
||||
break;
|
||||
case "payment":
|
||||
toast.success(i18n.t("Payment channels updated successfully"));
|
||||
break;
|
||||
default: {
|
||||
toast.success(i18n.t("System config updated successfully"));
|
||||
break;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { User } from "@/types/user";
|
||||
import { fetchAdminAPI } from "@/rpc/admin-api";
|
||||
import toast from "react-hot-toast";
|
||||
import i18n from "@/shared/lib/i18n";
|
||||
import { md5Encrypt, sha256Encrypt } from "@/shared/utils/crypto";
|
||||
|
||||
// user list API response interface (according to API document xpack-response-array format)
|
||||
export interface UserListApiResponse extends ApiArrayResponse<User> {}
|
||||
@@ -63,3 +64,42 @@ export const deleteUser = async (userId: string): Promise<boolean> => {
|
||||
toast.success(i18n.t("User deleted successfully"));
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* recharge user balance
|
||||
*/
|
||||
export const rechargeUser = async (
|
||||
userId: string,
|
||||
amount: number
|
||||
): Promise<boolean> => {
|
||||
// Create request body
|
||||
const body = {
|
||||
user_id: userId,
|
||||
balance: amount,
|
||||
type: "incr",
|
||||
};
|
||||
|
||||
// Generate timestamp
|
||||
const timestamp = Date.now().toString();
|
||||
|
||||
// Generate signature: sha256(md5((x-xpack-timestamp){body}))
|
||||
// For this implementation, we're using a simplified approach
|
||||
// In a real implementation, you would use actual crypto functions
|
||||
const bodyString = JSON.stringify(body);
|
||||
const signature = sha256Encrypt(md5Encrypt(`${timestamp}${bodyString}`));
|
||||
const response = await fetchAdminAPI(`/api/user_manager/balance/recharge`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"x-xpack-timestamp": timestamp,
|
||||
"x-xpack-sign": signature,
|
||||
},
|
||||
body: body as unknown as BodyInit,
|
||||
});
|
||||
|
||||
if (!response.success) {
|
||||
toast.error(response.error_message || i18n.t("Failed to recharge user"));
|
||||
return false;
|
||||
}
|
||||
toast.success(i18n.t("User recharged successfully"));
|
||||
return true;
|
||||
};
|
||||
@@ -9,9 +9,16 @@ import React from "react";
|
||||
interface PriceProps {
|
||||
price?: string;
|
||||
charge_type?: ChargeType;
|
||||
input_token_price?: string;
|
||||
output_token_price?: string;
|
||||
}
|
||||
|
||||
export const Price: React.FC<PriceProps> = ({ price, charge_type }) => {
|
||||
export const Price: React.FC<PriceProps> = ({
|
||||
price,
|
||||
charge_type,
|
||||
input_token_price,
|
||||
output_token_price,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
if (!charge_type) {
|
||||
return null;
|
||||
@@ -37,13 +44,24 @@ export const Price: React.FC<PriceProps> = ({ price, charge_type }) => {
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
const inputPrice = parseFloat(input_token_price || "0");
|
||||
const outputPrice = parseFloat(output_token_price || "0");
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<Zap className="w-3 h-3 text-blue-600" />
|
||||
<span className="text-sm font-medium text-blue-600">
|
||||
${priceText.toFixed(2)}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">/{t("token")}</span>
|
||||
<div className="flex flex-col gap-1 text-xs ">
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-gray-600">{t("Input")}:</span>
|
||||
<span className="font-medium text-green-600">
|
||||
${inputPrice.toFixed(2)}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">/{t("1M tokens")}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-gray-600">{t("Output")}:</span>
|
||||
<span className="font-medium text-blue-600">
|
||||
${outputPrice.toFixed(2)}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">/{t("1M tokens")}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,13 +14,17 @@ interface ProductDetailClientProps {
|
||||
product: ServiceData;
|
||||
breadcrumbs?: {
|
||||
link: string;
|
||||
name: string
|
||||
name: string;
|
||||
}[];
|
||||
mcpName?: string;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
export const ProductDetailClient: React.FC<ProductDetailClientProps> = ({
|
||||
product,
|
||||
breadcrumbs
|
||||
breadcrumbs,
|
||||
mcpName,
|
||||
url,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -28,52 +32,58 @@ export const ProductDetailClient: React.FC<ProductDetailClientProps> = ({
|
||||
|
||||
return (
|
||||
<div className="flex flex-col mx-auto p-6 max-w-7xl">
|
||||
{product ? (<>
|
||||
<ProductHeader
|
||||
product={product}
|
||||
breadcrumbs={breadcrumbs}
|
||||
/>
|
||||
{product ? (
|
||||
<>
|
||||
<ProductHeader product={product} breadcrumbs={breadcrumbs} />
|
||||
|
||||
<div className="flex gap-6 mt-6">
|
||||
{/* Left side - Main content */}
|
||||
<div className="flex-1">
|
||||
<Tabs
|
||||
selectedKey={activeTab}
|
||||
onSelectionChange={(key) => setActiveTab(key as string)}
|
||||
variant="underlined"
|
||||
color="primary"
|
||||
>
|
||||
<Tab key="overview" title={t("Overview")}>
|
||||
<ProductOverview product={product} />
|
||||
</Tab>
|
||||
<Tab key="tools" title={<div className="flex gap-2 items-center">
|
||||
<span>{t("Tools")}</span>
|
||||
<Chip size="sm" className="h-4 text-xs"> {product.tools.length}</Chip>
|
||||
</div>}>
|
||||
<ProductTools product={product} />
|
||||
</Tab>
|
||||
</Tabs>
|
||||
<div className="flex gap-6 mt-6">
|
||||
{/* Left side - Main content */}
|
||||
<div className="flex-1">
|
||||
<Tabs
|
||||
selectedKey={activeTab}
|
||||
onSelectionChange={(key) => setActiveTab(key as string)}
|
||||
variant="underlined"
|
||||
color="primary"
|
||||
>
|
||||
<Tab key="overview" title={t("Overview")}>
|
||||
<ProductOverview product={product} />
|
||||
</Tab>
|
||||
<Tab
|
||||
key="tools"
|
||||
title={
|
||||
<div className="flex gap-2 items-center">
|
||||
<span>{t("Tools")}</span>
|
||||
<Chip size="sm" className="h-4 text-xs">
|
||||
{" "}
|
||||
{product.tools.length}
|
||||
</Chip>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<ProductTools product={product} />
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
{/* Right side - Server Config */}
|
||||
<ServerConfig mcpName={mcpName} url={url} />
|
||||
</div>
|
||||
|
||||
{/* Right side - Server Config */}
|
||||
<ServerConfig product={product} />
|
||||
</div>
|
||||
|
||||
{/* SEO-friendly: Simple text content for search engines */}
|
||||
<div className="hidden" aria-hidden="true">
|
||||
<h2>Tools ({product.tools.length})</h2>
|
||||
{product.tools.length > 0 && (
|
||||
product.tools.map((tool, index) => (
|
||||
<div key={`seo-${product.service_id}-tool-${index}`}>
|
||||
<h4>{tool.name}</h4>
|
||||
<p>{tool.description || ""}</p>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : (<ProductNotFound />)}
|
||||
|
||||
{/* SEO-friendly: Simple text content for search engines */}
|
||||
<div className="hidden" aria-hidden="true">
|
||||
<h2>Tools ({product.tools.length})</h2>
|
||||
{product.tools.length > 0 &&
|
||||
product.tools.map((tool, index) => (
|
||||
<div key={`seo-${product.service_id}-tool-${index}`}>
|
||||
<h4>{tool.name}</h4>
|
||||
<p>{tool.description || ""}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<ProductNotFound />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -63,7 +63,7 @@ export const ProductHeader: React.FC<ProductHeaderProps> = ({
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-lg mb-4">
|
||||
<p className="text-sm mb-4">
|
||||
{product.short_description || t("No description available")}
|
||||
</p>
|
||||
</div>
|
||||
@@ -72,8 +72,13 @@ export const ProductHeader: React.FC<ProductHeaderProps> = ({
|
||||
{/* Price section */}
|
||||
{product.charge_type && (
|
||||
<div className="flex gap-2 items-center">
|
||||
<b className="text-xs">{t("Price")}:</b>
|
||||
<Price price={product.price} charge_type={product.charge_type} />
|
||||
<b className="text-md">{t("Price")}:</b>
|
||||
<Price
|
||||
price={product.price}
|
||||
charge_type={product.charge_type}
|
||||
input_token_price={product.input_token_price}
|
||||
output_token_price={product.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</CardBody>
|
||||
|
||||
@@ -1,26 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { ServiceData } from "@/shared/types/marketplace";
|
||||
import { Card, Chip } from "@nextui-org/react";
|
||||
import React from "react";
|
||||
import { Card, Chip, Button } from "@nextui-org/react";
|
||||
import { FlipButton } from "@/shared/components/FlipButton";
|
||||
import { useAuth } from "@/shared/lib/useAuth";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
import { Copy } from "lucide-react";
|
||||
import { copyToClipboard } from "@/shared/utils/clipboard";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
interface ServerConfigProps {
|
||||
product: ServiceData;
|
||||
mcpName?: string;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
export const ServerConfig: React.FC<ServerConfigProps> = ({ product }) => {
|
||||
export const ServerConfig: React.FC<ServerConfigProps> = ({
|
||||
mcpName,
|
||||
url = process.env.NEXT_PUBLIC_MCP_URL,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const { handleLogin } = useAuth();
|
||||
const { platformConfig } = usePlatformConfig();
|
||||
const [url, setUrl] = useState<string>(process.env.NEXT_PUBLIC_MCP_URL || "");
|
||||
useEffect(() => {
|
||||
if (url || !product.slug_name) return;
|
||||
setUrl(`${window.location.origin}/mcp/${product.slug_name}`);
|
||||
}, [product.slug_name]);
|
||||
|
||||
const getCodeContent = () => {
|
||||
return `{
|
||||
"mcpServers": {
|
||||
"${mcpName || "xpack-mcp-market"}": {
|
||||
"type": "sse",
|
||||
"autoApprove":"all",
|
||||
"url": "${url}?apikey={Your-${platformConfig?.name}-API-Key}"
|
||||
}
|
||||
}
|
||||
}`;
|
||||
};
|
||||
|
||||
const handleCopy = async () => {
|
||||
const result = await copyToClipboard(getCodeContent());
|
||||
if (result.success) {
|
||||
toast.success(t("Copied to clipboard"));
|
||||
} else {
|
||||
toast.error(t("Copy failed, please copy manually"));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-w-[400px] w-[40%] max-w-100 flex-shrink-0 mt-12">
|
||||
@@ -35,14 +57,26 @@ export const ServerConfig: React.FC<ServerConfigProps> = ({ product }) => {
|
||||
{/* Code Snippet */}
|
||||
<Card className="w-full max-w-2xl bg-black text-white p-2 sm:p-4 rounded-lg relative z-10">
|
||||
<div className="text-left font-mono">
|
||||
<Chip className="mb-2 text-white" size="sm" variant="flat">
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<div className="flex items-center gap-2 mb-2 justify-between">
|
||||
<Chip className="text-white" size="sm" variant="flat">
|
||||
{platformConfig?.name} MCP
|
||||
</Chip>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="flat"
|
||||
className="min-w-6 w-6 h-6 p-0 text-white"
|
||||
onPress={handleCopy}
|
||||
aria-label={t("Copy code")}
|
||||
>
|
||||
<Copy size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
<pre className="p-2 sm:p-4 rounded-md text-xs overflow-x-auto">
|
||||
<code className="text-gray-300 whitespace-pre-wrap">
|
||||
{`{
|
||||
"mcpServers": {
|
||||
"xpack-mcp-market": {
|
||||
"${mcpName || "xpack-mcp-market"}": {
|
||||
"type": "sse",
|
||||
"autoApprove":"all",
|
||||
"url": "${url}?apikey=`}
|
||||
|
||||
@@ -17,7 +17,10 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ service }) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Link href={`/marketplace/${service.service_id}`}>
|
||||
<Link
|
||||
href={`/marketplace/${service.service_id}`}
|
||||
className="w-full md:w-[calc(50%-16px)] lg:w-[calc(33%-16px)] xl:w-[calc(25%-16px)]"
|
||||
>
|
||||
<Card
|
||||
className="group w-full h-[180px] hover:border-primary-500 transition-all duration-300 border-1"
|
||||
shadow="none"
|
||||
@@ -48,7 +51,12 @@ export const ServiceCard: React.FC<ServiceCardProps> = ({ service }) => {
|
||||
{t("{{count}} Tools", { count: service.tools.length })}
|
||||
</Chip>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Price price={service.price} charge_type={service.charge_type} />
|
||||
<Price
|
||||
price={service.price}
|
||||
charge_type={service.charge_type}
|
||||
input_token_price={service.input_token_price}
|
||||
output_token_price={service.output_token_price}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardFooter>
|
||||
|
||||
@@ -25,7 +25,7 @@ export const ServiceListSection: React.FC<ServiceListSectionProps> = ({
|
||||
return (
|
||||
<div className="mx-auto px-6 py-12 max-w-7xl">
|
||||
{/* Services Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mb-12">
|
||||
<div className="flex flex-wrap justify-center gap-4 mb-12">
|
||||
{services.map((service) => (
|
||||
<ServiceCard key={service.service_id} service={service} />
|
||||
))}
|
||||
@@ -46,4 +46,4 @@ export const ServiceListSection: React.FC<ServiceListSectionProps> = ({
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from "react";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import {
|
||||
Modal,
|
||||
ModalContent,
|
||||
@@ -7,11 +7,14 @@ import {
|
||||
ModalFooter,
|
||||
Button,
|
||||
Input,
|
||||
RadioGroup,
|
||||
Radio,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { fetchAPI } from "@/shared/rpc/common-function";
|
||||
import toast from "react-hot-toast";
|
||||
import { ConfirmPurchaseModal } from "./ConfirmPurchaseModal";
|
||||
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
|
||||
interface RechargeModalProps {
|
||||
isOpen: boolean;
|
||||
@@ -23,13 +26,16 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
onClose,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const { paymentChannels } = usePlatformConfig();
|
||||
const [amount, setAmount] = useState<string>("");
|
||||
const [error, setError] = useState<string>("");
|
||||
const [selectedPaymentChannel, setSelectedPaymentChannel] = useState<string>(
|
||||
paymentChannels[0]?.id || ""
|
||||
);
|
||||
|
||||
const [paymentId, setPaymentId] = useState("");
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
|
||||
|
||||
|
||||
const handlePurchase = async () => {
|
||||
const numAmount = parseFloat(amount);
|
||||
if (isNaN(numAmount) || numAmount <= 0) {
|
||||
@@ -41,10 +47,17 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
setError(t("Minimum recharge amount is $1"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!selectedPaymentChannel) {
|
||||
setError(t("Please select a payment method"));
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await fetchAPI("/api/payment/create_payment_link", {
|
||||
method: "POST",
|
||||
body: {
|
||||
amount: numAmount,
|
||||
payment_channel: selectedPaymentChannel,
|
||||
success_url: window.location.origin + "/pay_success",
|
||||
} as unknown as BodyInit,
|
||||
});
|
||||
@@ -93,6 +106,7 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
const handleClose = () => {
|
||||
setAmount("");
|
||||
setError("");
|
||||
setSelectedPaymentChannel(paymentChannels[0]?.id || "");
|
||||
onClose();
|
||||
};
|
||||
|
||||
@@ -119,23 +133,54 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
}
|
||||
type="text"
|
||||
variant="bordered"
|
||||
isInvalid={!!error}
|
||||
errorMessage={error}
|
||||
isInvalid={!!error && !error.includes("payment method")}
|
||||
errorMessage={
|
||||
error && !error.includes("payment method") ? error : ""
|
||||
}
|
||||
labelPlacement="outside"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
handlePurchase();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<p className="text-xs text-default-500">
|
||||
{t("Funds will be added to your account balance")}
|
||||
</p>
|
||||
{/**coming soon : select payment channel*/}
|
||||
|
||||
{/* {paymentChannels.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-default-700">
|
||||
{t("Payment Method")}
|
||||
</label>
|
||||
<RadioGroup
|
||||
value={selectedPaymentChannel}
|
||||
onValueChange={setSelectedPaymentChannel}
|
||||
isInvalid={!!error && error.includes("payment method")}
|
||||
errorMessage={
|
||||
error && error.includes("payment method") ? error : ""
|
||||
}
|
||||
orientation="horizontal"
|
||||
description={t(
|
||||
"Funds will be added to your account balance"
|
||||
)}
|
||||
>
|
||||
{paymentChannels.map((channel) => (
|
||||
<Radio key={channel.id} value={channel.id}>
|
||||
{channel.name}
|
||||
</Radio>
|
||||
))}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
)} */}
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button variant="light" onPress={handleClose}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button color="primary" onPress={handlePurchase}>
|
||||
<Button
|
||||
color="primary"
|
||||
onPress={handlePurchase}
|
||||
isDisabled={!selectedPaymentChannel || !amount}
|
||||
>
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
@@ -144,7 +189,6 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
|
||||
|
||||
{/**Confirm Purchase Modal */}
|
||||
<ConfirmPurchaseModal
|
||||
isOpen={isConfirmOpen}
|
||||
@@ -154,4 +198,4 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -6,6 +6,10 @@ import {
|
||||
PlatformConfigResponse,
|
||||
Theme,
|
||||
LoginConfig,
|
||||
FaqItem,
|
||||
TopNavigationItem,
|
||||
EmbeddedHtmlConfig,
|
||||
PaymentChannel,
|
||||
} from "@/shared/types/system";
|
||||
export const _DefaultPlatformConfig: PlatformConfig = {
|
||||
name: "XPack",
|
||||
@@ -17,10 +21,18 @@ export const _DefaultPlatformConfig: PlatformConfig = {
|
||||
subheadline:
|
||||
"Open‑source MCP marketplace — publish or consume APIs in minutes.",
|
||||
theme: Theme.DEFAULT,
|
||||
domain: "",
|
||||
is_showcased: false,
|
||||
mcp_server_prefix: "",
|
||||
};
|
||||
interface PlatformConfigContextType {
|
||||
platformConfig: PlatformConfig;
|
||||
loginConfig: LoginConfig | null;
|
||||
faqItems: FaqItem[];
|
||||
topNavigation: TopNavigationItem[];
|
||||
embeddedHtml: EmbeddedHtmlConfig | null;
|
||||
paymentChannels: PaymentChannel[];
|
||||
isInstalled: boolean;
|
||||
updateClientConfig: (config: PlatformConfigResponse) => void;
|
||||
}
|
||||
|
||||
@@ -43,13 +55,41 @@ export const PlatformConfigProvider: React.FC<PlatformConfigProviderProps> = ({
|
||||
const [loginConfig, setLoginConfig] = useState<LoginConfig | null>(
|
||||
initConfig?.login || null
|
||||
);
|
||||
const [faqItems, setFaqItems] = useState<FaqItem[]>(initConfig?.faq || []);
|
||||
const [topNavigation, setTopNavigation] = useState<TopNavigationItem[]>(
|
||||
initConfig?.top_navigation || []
|
||||
);
|
||||
const [embeddedHtml, setEmbeddedHtml] = useState<EmbeddedHtmlConfig | null>(
|
||||
initConfig?.embeded_html || null
|
||||
);
|
||||
const [paymentChannels, setPaymentChannels] = useState<PaymentChannel[]>(
|
||||
initConfig?.payment_channels || []
|
||||
);
|
||||
const [isInstalled, setIsInstalled] = useState<boolean>(
|
||||
initConfig?.is_installed || false
|
||||
);
|
||||
|
||||
const updateClientConfig = (config: PlatformConfigResponse) => {
|
||||
if (config.platform) setPlatformConfig(config.platform);
|
||||
if (config.login) setLoginConfig(config.login);
|
||||
if (config.faq) setFaqItems(config.faq);
|
||||
if (config.top_navigation) setTopNavigation(config.top_navigation);
|
||||
if (config.embeded_html) setEmbeddedHtml(config.embeded_html);
|
||||
if (config.payment_channels) setPaymentChannels(config.payment_channels);
|
||||
if (config.is_installed !== undefined) setIsInstalled(config.is_installed);
|
||||
};
|
||||
return (
|
||||
<PlatformConfigContext.Provider
|
||||
value={{ platformConfig, loginConfig, updateClientConfig }}
|
||||
value={{
|
||||
platformConfig,
|
||||
loginConfig,
|
||||
faqItems,
|
||||
topNavigation,
|
||||
embeddedHtml,
|
||||
paymentChannels,
|
||||
isInstalled,
|
||||
updateClientConfig,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</PlatformConfigContext.Provider>
|
||||
|
||||
@@ -11,16 +11,28 @@ export enum TabKey {
|
||||
ACCOUNT = "account",
|
||||
}
|
||||
|
||||
export interface SidebarSubItem {
|
||||
key: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface SidebarItem {
|
||||
key: TabKey;
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
description: string;
|
||||
subItems?: SidebarSubItem[];
|
||||
}
|
||||
|
||||
export interface SidebarItemWithActive extends SidebarItem {
|
||||
isExpanded?: boolean;
|
||||
}
|
||||
|
||||
export interface DashboardSidebarProps {
|
||||
activeTab: TabKey;
|
||||
onTabNavigate?: (tab: TabKey) => void;
|
||||
activeSubTab?: string;
|
||||
onTabNavigate?: (tab: TabKey, subTab?: string) => void;
|
||||
onLogout: () => void;
|
||||
bottomPanel?: React.ReactNode;
|
||||
sidebarItems: SidebarItem[];
|
||||
|
||||
@@ -8,6 +8,8 @@ export interface ServiceData {
|
||||
tags?: string[];
|
||||
price?: string;
|
||||
charge_type?: ChargeType;
|
||||
input_token_price?: string;
|
||||
output_token_price?: string;
|
||||
}
|
||||
|
||||
export interface ToolData {
|
||||
|
||||
@@ -21,12 +21,48 @@ export interface PlatformConfig {
|
||||
subheadline?: string; // homepage subheadline
|
||||
theme?: Theme; // platform theme for homepage and marketplace templates
|
||||
about_page?: string; // about page content (markdown)
|
||||
domain?: string; // platform domain
|
||||
is_showcased?: boolean; // whether to showcase in xpack official case list
|
||||
mcp_server_prefix?: string; // MCP server domain prefix for API calls
|
||||
}
|
||||
|
||||
export type ThemeType = Theme;
|
||||
// FAQ item
|
||||
export interface FaqItem {
|
||||
question: string;
|
||||
answer: string;
|
||||
}
|
||||
export enum TopNavigationTargetEnum {
|
||||
SELF = "_self",
|
||||
BLANK = "_blank",
|
||||
}
|
||||
// Top navigation item
|
||||
export interface TopNavigationItem {
|
||||
title: string;
|
||||
link: string;
|
||||
target: TopNavigationTargetEnum;
|
||||
}
|
||||
|
||||
// Embedded HTML config
|
||||
export interface EmbeddedHtmlConfig {
|
||||
is_enabled: boolean;
|
||||
html: string;
|
||||
}
|
||||
|
||||
// Payment channel
|
||||
export interface PaymentChannel {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface PlatformConfigResponse {
|
||||
platform: PlatformConfig;
|
||||
platform?: PlatformConfig;
|
||||
login?: LoginConfig;
|
||||
faq?: FaqItem[];
|
||||
top_navigation?: TopNavigationItem[];
|
||||
embeded_html?: EmbeddedHtmlConfig;
|
||||
payment_channels?: PaymentChannel[];
|
||||
is_installed?: boolean;
|
||||
}
|
||||
|
||||
// google auth config
|
||||
|
||||
@@ -19,6 +19,8 @@ export interface BaseMCPService {
|
||||
long_description?: string;
|
||||
charge_type: ChargeType;
|
||||
price?: string;
|
||||
input_token_price?: string;
|
||||
output_token_price?: string;
|
||||
apis: MCPServiceAPIItem[];
|
||||
tags?: string[];
|
||||
}
|
||||
@@ -34,6 +36,7 @@ export interface MCPServiceAPIItem {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
// form data interface, used to create and edit service
|
||||
@@ -48,6 +51,8 @@ export interface MCPServiceFormData {
|
||||
auth_token?: string;
|
||||
charge_type: ChargeType;
|
||||
price?: string;
|
||||
input_token_price?: string; // Price for input tokens when charge_type is PerToken
|
||||
output_token_price?: string; // Price for output tokens when charge_type is PerToken
|
||||
enabled: EnabledEnum; // API requires string type
|
||||
apis: MCPServiceAPIItem[];
|
||||
tags?: string[];
|
||||
@@ -89,41 +94,6 @@ export interface ServiceDeleteRequest {
|
||||
id: string;
|
||||
}
|
||||
|
||||
// predefined auth methods
|
||||
export const AUTH_METHODS = [
|
||||
{ value: "free", label: "free" },
|
||||
{ value: "apikey", label: "API key" },
|
||||
] as const;
|
||||
|
||||
// predefined charge types
|
||||
export const CHARGE_TYPES = [
|
||||
{ value: "free", label: "free" },
|
||||
{ value: "per_call", label: "per call" },
|
||||
{ value: "per_token", label: "per token" },
|
||||
] as const;
|
||||
|
||||
// predefined service categories
|
||||
export const SERVICE_CATEGORIES = [
|
||||
"Web Services",
|
||||
"Database",
|
||||
"AI/ML",
|
||||
"Authentication",
|
||||
"Payment",
|
||||
"Communication",
|
||||
"Analytics",
|
||||
"Storage",
|
||||
"Security",
|
||||
"Development Tools",
|
||||
"Financial",
|
||||
"Logistics & Transportation",
|
||||
"E-commerce",
|
||||
"Social Media",
|
||||
"Content Management",
|
||||
"Other",
|
||||
] as const;
|
||||
|
||||
export type ServiceCategory = (typeof SERVICE_CATEGORIES)[number];
|
||||
|
||||
// tool function: convert frontend form data to API data
|
||||
export function convertFormToAPI(
|
||||
formData: MCPServiceFormData
|
||||
@@ -138,6 +108,8 @@ export function convertFormToAPI(
|
||||
auth_token: formData.auth_token,
|
||||
charge_type: formData.charge_type,
|
||||
price: formData.price,
|
||||
input_token_price: formData.input_token_price,
|
||||
output_token_price: formData.output_token_price,
|
||||
enabled: formData.enabled,
|
||||
apis: formData.apis,
|
||||
tags: formData.tags,
|
||||
|
||||
@@ -1,18 +1,37 @@
|
||||
// payment channel type
|
||||
export type PaymentChannelType = "stripe";
|
||||
export type PaymentChannelType = "stripe" | "alipay" | "wechat";
|
||||
|
||||
// stripe config - admin need to configure
|
||||
export interface StripeConfig {
|
||||
secret: string;
|
||||
webhook_secret: string;
|
||||
is_enabled?: boolean;
|
||||
}
|
||||
|
||||
// alipay config - admin need to configure
|
||||
export interface AlipayConfig {
|
||||
app_id: string;
|
||||
app_private_key: string;
|
||||
alipay_public_key: string;
|
||||
is_enabled?: boolean;
|
||||
}
|
||||
|
||||
// wechat config - admin need to configure
|
||||
export interface WechatConfig {
|
||||
app_id: string;
|
||||
mch_id: string;
|
||||
is_enabled?: boolean;
|
||||
}
|
||||
|
||||
// union type for all payment configs
|
||||
export type PaymentConfig = StripeConfig | AlipayConfig | WechatConfig;
|
||||
|
||||
// API return payment channel item structure
|
||||
export interface PaymentChannelApiItem {
|
||||
id: PaymentChannelType;
|
||||
name: string;
|
||||
is_enabled: boolean;
|
||||
config: StripeConfig;
|
||||
config: PaymentConfig;
|
||||
update_time: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,10 @@ import {
|
||||
GoogleAuthConfig,
|
||||
PlatformConfig,
|
||||
LoginConfig,
|
||||
FaqItem,
|
||||
TopNavigationItem,
|
||||
EmbeddedHtmlConfig,
|
||||
PaymentChannel,
|
||||
} from "@/shared/types/system";
|
||||
|
||||
// API return system config data structure
|
||||
@@ -12,6 +16,11 @@ export interface SystemConfigApiData {
|
||||
account: AdminConfig;
|
||||
email: EmailConfig;
|
||||
login: LoginConfig;
|
||||
faq?: FaqItem[];
|
||||
top_navigation?: TopNavigationItem[];
|
||||
embeded_html?: EmbeddedHtmlConfig;
|
||||
payment_channels?: PaymentChannel[];
|
||||
is_installed?: boolean;
|
||||
}
|
||||
// admin config
|
||||
export interface AdminConfig {
|
||||
|
||||
+2
-1
@@ -13,4 +13,5 @@ PyYAML>=6.0
|
||||
python-multipart
|
||||
google-auth>=2.0.0
|
||||
google-auth-oauthlib>=1.0.0
|
||||
fastapi_mcp
|
||||
fastapi_mcp
|
||||
alipay-sdk-python>=3.0.0
|
||||
@@ -17,7 +17,7 @@ echo "login qiniu..."
|
||||
qshell account ${AccessKey} ${SecretKey} ${QINIU_NAME}
|
||||
|
||||
echo "qshell rput ${QINIU_BUCKET} \"xpack/images/${Tar}\" ${Tar}"
|
||||
qshell rput ${QINIU_BUCKET} "xpack/images/${Tar}" ${Tar}
|
||||
qshell rput --overwrite ${QINIU_BUCKET} "xpack/images/${Tar}" ${Tar}
|
||||
|
||||
rm -f ${Tar}
|
||||
docker rmi -f ${ImageName}:${Version}
|
||||
@@ -926,8 +926,8 @@ print_xpack_mcp_market_info() {
|
||||
webPort=$(read_env_var ${ENV_XPACK_MCP_MARKET_WEB_PORT})
|
||||
echo_pass "XPack MCP Market has run successfully."
|
||||
echo_info "The Web UI access information is as follows:"
|
||||
echo_info "Internal network access address: http://$(read_env_var ${ENV_LAN_IP}):${webPort}/admin-signin"
|
||||
echo_info "External network access address: http://$(read_env_var ${ENV_EXTERNAL_IP}):${webPort}/admin-signin"
|
||||
echo_info "Internal network access address: http://$(read_env_var ${ENV_LAN_IP}):${webPort}/admin"
|
||||
echo_info "External network access address: http://$(read_env_var ${ENV_EXTERNAL_IP}):${webPort}/admin"
|
||||
echo_info "Inital Username: admin"
|
||||
echo_info "Inital Password: 123456789"
|
||||
echo ""
|
||||
@@ -1027,7 +1027,7 @@ operate() {
|
||||
echo_logo
|
||||
echo_split
|
||||
echo_question "Hello, Welcome to use XPack MCP Market! What do you want to do?"
|
||||
echo_point "1. Install XPack MCP Market"
|
||||
echo_point "1. Install or Update XPack MCP Market"
|
||||
echo_point "2. Print system information"
|
||||
echo_point "3. Uninstall XPack MCP Market"
|
||||
echo_point "4. Exit"
|
||||
|
||||
+247
-46
@@ -1,9 +1,10 @@
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
from pathlib import Path
|
||||
from dotenv import load_dotenv
|
||||
import mysql.connector
|
||||
from typing import Optional
|
||||
from typing import Optional, List, Tuple, Union
|
||||
|
||||
# 加载环境变量
|
||||
load_dotenv()
|
||||
@@ -16,77 +17,277 @@ class DBConfig:
|
||||
MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD", "123456")
|
||||
MYSQL_DB = os.getenv("MYSQL_DB", "xpack")
|
||||
|
||||
def execute_sql_file(file_path: str, db_config: Optional[DBConfig] = None) -> None:
|
||||
"""执行 SQL 文件
|
||||
|
||||
def get_db_connection(db_config: Optional[DBConfig] = None):
|
||||
"""获取数据库连接
|
||||
|
||||
Args:
|
||||
file_path: SQL 文件路径
|
||||
db_config: 数据库配置,如果为 None 则使用默认配置
|
||||
|
||||
Returns:
|
||||
数据库连接对象
|
||||
"""
|
||||
if db_config is None:
|
||||
db_config = DBConfig()
|
||||
print(db_config.MYSQL_HOST, db_config.MYSQL_PORT, db_config.MYSQL_USER, db_config.MYSQL_PASSWORD, db_config.MYSQL_DB)
|
||||
# 连接数据库
|
||||
conn = mysql.connector.connect(
|
||||
|
||||
return mysql.connector.connect(
|
||||
host=db_config.MYSQL_HOST,
|
||||
port=db_config.MYSQL_PORT,
|
||||
user=db_config.MYSQL_USER,
|
||||
password=db_config.MYSQL_PASSWORD,
|
||||
database=db_config.MYSQL_DB
|
||||
)
|
||||
cursor = conn.cursor()
|
||||
|
||||
def get_current_version(db_config: Optional[DBConfig] = None) -> Optional[str]:
|
||||
"""查询sys_config表中的version值
|
||||
|
||||
Args:
|
||||
db_config: 数据库配置
|
||||
|
||||
Returns:
|
||||
当前版本号,如果不存在则返回None
|
||||
"""
|
||||
try:
|
||||
conn = get_db_connection(db_config)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 查询version配置
|
||||
cursor.execute("SELECT value FROM sys_config WHERE `key` = 'version'")
|
||||
result = cursor.fetchone()
|
||||
|
||||
cursor.close()
|
||||
conn.close()
|
||||
|
||||
if result and len(result) > 0:
|
||||
# 将元组的第一个元素转换为字符串并返回
|
||||
return str(result['value'] if isinstance(result, dict) else result[0])
|
||||
return None
|
||||
|
||||
except mysql.connector.Error as err:
|
||||
# 如果表不存在或其他数据库错误,返回None
|
||||
print(f"查询版本信息失败: {err}")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"查询版本信息出错: {e}")
|
||||
return None
|
||||
|
||||
def execute_sql_file(file_path: str, db_config: Optional[DBConfig] = None) -> bool:
|
||||
"""执行 SQL 文件
|
||||
|
||||
Args:
|
||||
file_path: SQL 文件路径
|
||||
db_config: 数据库配置,如果为 None 则使用默认配置
|
||||
|
||||
Returns:
|
||||
执行是否成功
|
||||
"""
|
||||
if db_config is None:
|
||||
db_config = DBConfig()
|
||||
|
||||
sql = ""
|
||||
try:
|
||||
# 读取 SQL 文件
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
sql_content = f.read()
|
||||
|
||||
# 设置字符集
|
||||
cursor.execute('SET NAMES utf8mb4')
|
||||
conn = get_db_connection(db_config)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 禁用外键检查
|
||||
cursor.execute('SET FOREIGN_KEY_CHECKS = 0')
|
||||
|
||||
# 执行 SQL 语句
|
||||
for statement in sql_content.split(';'):
|
||||
if statement.strip():
|
||||
sql = statement
|
||||
cursor.execute(statement)
|
||||
|
||||
# 启用外键检查
|
||||
|
||||
# 读取SQL文件
|
||||
with open(file_path, 'r', encoding='utf-8') as file:
|
||||
content = file.read()
|
||||
|
||||
# 移除多行注释 /* ... */
|
||||
import re
|
||||
content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL)
|
||||
|
||||
# 按分号分割语句
|
||||
statements = content.split(';')
|
||||
statement_count = 0
|
||||
|
||||
for statement in statements:
|
||||
# 清理语句:移除空行和注释行
|
||||
lines = statement.strip().split('\n')
|
||||
cleaned_lines = []
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if line and not line.startswith('--'):
|
||||
cleaned_lines.append(line)
|
||||
|
||||
if not cleaned_lines:
|
||||
continue
|
||||
|
||||
sql = '\n'.join(cleaned_lines)
|
||||
statement_count += 1
|
||||
|
||||
# 跳过SET语句,单独处理
|
||||
if sql.upper().startswith('SET '):
|
||||
print(f"执行第{statement_count}个语句: {sql}")
|
||||
try:
|
||||
cursor.execute(sql)
|
||||
print(f" -> 成功")
|
||||
except mysql.connector.Error as e:
|
||||
print(f" -> SET语句执行错误: {e}")
|
||||
# SET语句失败不影响后续执行
|
||||
continue
|
||||
|
||||
# 添加调试信息
|
||||
if sql.upper().startswith('CREATE TABLE'):
|
||||
table_match = re.search(r'CREATE TABLE.*?`(\w+)`', sql, re.IGNORECASE)
|
||||
table_name = table_match.group(1) if table_match else 'unknown'
|
||||
print(f"执行第{statement_count}个语句: 创建表 {table_name}")
|
||||
elif sql.upper().startswith('INSERT INTO'):
|
||||
table_match = re.search(r'INSERT INTO.*?`(\w+)`', sql, re.IGNORECASE)
|
||||
table_name = table_match.group(1) if table_match else 'unknown'
|
||||
print(f"执行第{statement_count}个语句: 插入数据到表 {table_name}")
|
||||
else:
|
||||
print(f"执行第{statement_count}个语句: {sql[:50]}...")
|
||||
|
||||
try:
|
||||
cursor.execute(sql)
|
||||
print(f" -> 成功")
|
||||
except mysql.connector.Error as e:
|
||||
if "Duplicate column name" in str(e):
|
||||
print(f" -> 忽略重复列错误: {e}")
|
||||
continue
|
||||
else:
|
||||
print(f" -> 执行错误: {e}")
|
||||
print(f" -> 语句内容: {sql}")
|
||||
raise
|
||||
|
||||
# 恢复外键检查
|
||||
cursor.execute('SET FOREIGN_KEY_CHECKS = 1')
|
||||
# 提交事务
|
||||
conn.commit()
|
||||
print(f"成功执行 SQL 文件: {file_path}")
|
||||
except FileNotFoundError:
|
||||
print(f"错误: SQL 文件不存在: {file_path}")
|
||||
sys.exit(1)
|
||||
except mysql.connector.Error as err:
|
||||
# 输出语句
|
||||
print(f"数据库错误: {err}, 语句: {sql}")
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f"执行出错: {e}")
|
||||
sys.exit(1)
|
||||
finally:
|
||||
# 关闭连接
|
||||
print(f"成功执行 SQL 文件: {file_path},共执行 {statement_count} 个语句")
|
||||
|
||||
cursor.close()
|
||||
conn.close()
|
||||
return True
|
||||
|
||||
except FileNotFoundError:
|
||||
print(f"错误: SQL 文件不存在: {file_path}")
|
||||
return False
|
||||
except mysql.connector.Error as err:
|
||||
print(f"数据库错误: {err}")
|
||||
if sql:
|
||||
print(f"出错的SQL语句: {sql}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"未知错误: {e}")
|
||||
return False
|
||||
|
||||
def get_version_files(sql_dir: Path) -> List[Tuple[str, Path]]:
|
||||
"""获取所有版本SQL文件并按版本号排序
|
||||
|
||||
Args:
|
||||
sql_dir: SQL文件目录
|
||||
|
||||
Returns:
|
||||
排序后的版本文件列表,格式为[(版本号, 文件路径), ...]
|
||||
"""
|
||||
version_files = []
|
||||
|
||||
# 查找所有version-*.sql文件
|
||||
for file_path in sql_dir.glob("version-*.sql"):
|
||||
# 提取版本号
|
||||
match = re.match(r'version-(.+)\.sql', file_path.name)
|
||||
if match:
|
||||
version_str = match.group(1)
|
||||
version_files.append((version_str, file_path))
|
||||
|
||||
# 按版本号排序(简单的字符串排序)
|
||||
version_files.sort(key=lambda x: x[0])
|
||||
|
||||
return version_files
|
||||
|
||||
def should_apply_version(current_version: Optional[str], target_version: str) -> bool:
|
||||
"""判断是否需要应用指定版本的更新
|
||||
|
||||
Args:
|
||||
current_version: 当前版本号
|
||||
target_version: 目标版本号
|
||||
|
||||
Returns:
|
||||
是否需要应用更新
|
||||
"""
|
||||
if current_version is None:
|
||||
return True
|
||||
|
||||
# 简单的字符串比较
|
||||
return target_version > current_version
|
||||
|
||||
def main():
|
||||
"""主函数:实现版本化数据库迁移策略"""
|
||||
print("开始数据库初始化和迁移...")
|
||||
|
||||
# 获取项目根目录
|
||||
project_root = Path(__file__).parent
|
||||
sql_dir = project_root / 'sql'
|
||||
|
||||
# SQL 文件路径(优先使用 scripts/resource/db.sql,如果不存在则使用 docs/db.sql)
|
||||
sql_paths = [
|
||||
project_root / 'sql' / 'init.sql'
|
||||
]
|
||||
print(sql_paths)
|
||||
sql_file = next((path for path in sql_paths if path.exists()), None)
|
||||
if not sql_file:
|
||||
print("错误: 未找到 init.sql 文件")
|
||||
if not sql_dir.exists():
|
||||
print(f"错误: SQL目录不存在: {sql_dir}")
|
||||
sys.exit(1)
|
||||
|
||||
execute_sql_file(str(sql_file))
|
||||
|
||||
# 步骤1: 查询sys_config,获取当key=version的值
|
||||
print("步骤1: 查询当前数据库版本...")
|
||||
current_version = get_current_version()
|
||||
|
||||
# 步骤2: 当不存在该key时,执行init.sql
|
||||
if current_version is None:
|
||||
print("步骤2: 未找到版本信息,执行初始化SQL...")
|
||||
init_sql_file = sql_dir / 'init.sql'
|
||||
|
||||
if not init_sql_file.exists():
|
||||
print(f"错误: 初始化SQL文件不存在: {init_sql_file}")
|
||||
sys.exit(1)
|
||||
|
||||
if not execute_sql_file(str(init_sql_file)):
|
||||
print("初始化SQL执行失败")
|
||||
sys.exit(1)
|
||||
|
||||
# 重新查询版本信息
|
||||
current_version = get_current_version()
|
||||
print(f"初始化完成,当前版本: {current_version}")
|
||||
else:
|
||||
print(f"当前数据库版本: {current_version}")
|
||||
|
||||
# 步骤3: 获取对应的版本号
|
||||
# 步骤4: 依次读取sql下的version-*.sql文件,执行更新sql,直到所有sql执行完成
|
||||
print("步骤3-4: 检查并执行版本更新...")
|
||||
|
||||
# 获取所有版本文件
|
||||
version_files = get_version_files(sql_dir)
|
||||
|
||||
if not version_files:
|
||||
print("未找到版本更新文件,数据库已是最新版本")
|
||||
return
|
||||
|
||||
print(f"找到 {len(version_files)} 个版本更新文件")
|
||||
|
||||
# 依次执行需要的版本更新
|
||||
updated_count = 0
|
||||
for version_str, file_path in version_files:
|
||||
if should_apply_version(current_version, version_str):
|
||||
print(f"执行版本更新: {version_str} ({file_path.name})")
|
||||
|
||||
if execute_sql_file(str(file_path)):
|
||||
print(f"版本 {version_str} 更新成功")
|
||||
current_version = version_str
|
||||
updated_count += 1
|
||||
else:
|
||||
print(f"版本 {version_str} 更新失败,停止后续更新")
|
||||
sys.exit(1)
|
||||
else:
|
||||
print(f"跳过版本 {version_str}(已应用或版本较低)")
|
||||
|
||||
if updated_count > 0:
|
||||
print(f"数据库迁移完成,共应用了 {updated_count} 个版本更新")
|
||||
# 验证最终版本
|
||||
final_version = get_current_version()
|
||||
print(f"最终数据库版本: {final_version}")
|
||||
else:
|
||||
print("数据库已是最新版本,无需更新")
|
||||
|
||||
print("数据库初始化和迁移流程完成!")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -275,15 +275,7 @@ UNIQUE KEY `uk_key` (`key`) USING BTREE COMMENT '配置键名唯一索引'
|
||||
|
||||
INSERT INTO `user` (`id`, `name`, `email`, `password`, `is_active`, `is_deleted`, `register_type`, `role_id`, `created_at`, `updated_at`)
|
||||
VALUES ('admin', 'admin', 'admin@xpack.com', '25f9e794323b453885f5181f1b624d0b', 1, 0, 'inner', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
`name` = VALUES(`name`),
|
||||
`email` = VALUES(`email`),
|
||||
`password` = VALUES(`password`),
|
||||
`is_active` = VALUES(`is_active`),
|
||||
`is_deleted` = VALUES(`is_deleted`),
|
||||
`register_type` = VALUES(`register_type`),
|
||||
`role_id` = VALUES(`role_id`),
|
||||
`updated_at` = CURRENT_TIMESTAMP;
|
||||
ON DUPLICATE KEY UPDATE `register_type` = VALUES(`register_type`);
|
||||
|
||||
INSERT INTO `user_wallet` (`id`, `user_id`, `balance`, `frozen_balance`, `created_at`, `updated_at`)
|
||||
SELECT UUID(), 'admin', 0.00, 0.00, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
@@ -293,4 +285,8 @@ INSERT INTO `payment_channel` (`id`, `name`, `status`, `config`, `updated_at`)
|
||||
SELECT 'stripe', 'Stripe', 1, '{\"secret\": \"\", \"webhook_secret\": \"\"}', '2025-07-17 06:42:55'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM `payment_channel` WHERE `id` = 'stripe');
|
||||
|
||||
INSERT INTO `sys_config` (`id`,`key`, `value`,`description`,`created_at`,`updated_at`)
|
||||
VALUES ('xpack-version','version', '0.2.2', 'User wallet history max count', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), `description` = VALUES(`description`), `updated_at` = CURRENT_TIMESTAMP;
|
||||
|
||||
SET FOREIGN_KEY_CHECKS = 1;
|
||||
@@ -0,0 +1,23 @@
|
||||
-- mcp_call_log
|
||||
ALTER TABLE `mcp_call_log` DROP COLUMN `apikey`;
|
||||
ALTER TABLE `mcp_call_log` ADD COLUMN `apikey_id` char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT 'apikey_id' AFTER `wallet_history_id`;
|
||||
|
||||
-- mcp_service
|
||||
ALTER TABLE `mcp_service` ADD COLUMN `input_token_price` decimal(10, 2) NULL DEFAULT NULL COMMENT 'input token price' AFTER `price`;
|
||||
ALTER TABLE `mcp_service` ADD COLUMN `output_token_price` decimal(10, 2) NULL DEFAULT NULL COMMENT 'output token price' AFTER `price`;
|
||||
|
||||
-- temp_mcp_service
|
||||
ALTER TABLE `temp_mcp_service` ADD COLUMN `input_token_price` decimal(10, 2) NULL DEFAULT NULL COMMENT 'input token price' AFTER `price`;
|
||||
ALTER TABLE `temp_mcp_service` ADD COLUMN `output_token_price` decimal(10, 2) NULL DEFAULT NULL COMMENT 'output token price' AFTER `price`;
|
||||
|
||||
-- user_wallet
|
||||
ALTER TABLE `user_wallet` MODIFY COLUMN `balance` decimal(16, 6) NOT NULL COMMENT 'Wallet balance' AFTER `user_id`;
|
||||
ALTER TABLE `user_wallet` MODIFY COLUMN `frozen_balance` decimal(16, 6) NOT NULL COMMENT 'Frozen balance' AFTER `balance`;
|
||||
|
||||
-- user_wallet_history
|
||||
ALTER TABLE `user_wallet_history` MODIFY COLUMN `amount` decimal(16, 6) NOT NULL COMMENT 'Change amount' AFTER `payment_method`;
|
||||
ALTER TABLE `user_wallet_history` MODIFY COLUMN `balance_after` decimal(16, 6) NOT NULL COMMENT 'Balance after change' AFTER `amount`;
|
||||
|
||||
INSERT INTO `sys_config` (`id`,`key`, `value`,`description`,`created_at`,`updated_at`)
|
||||
VALUES ('xpack-version','version', '1.0.0', 'User wallet history max count', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), `description` = VALUES(`description`), `updated_at` = CURRENT_TIMESTAMP;
|
||||
@@ -0,0 +1,20 @@
|
||||
|
||||
INSERT INTO `sys_config` (`id`,`key`, `value`,`description`,`created_at`,`updated_at`)
|
||||
VALUES ('xpack-is_showcased','is_showcased', '1', 'Is showcase', 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-login_google_enable','login_google_enable', '1', 'Login google enable', 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-login_email_enable','login_email_enable', '1', 'Login email enable', 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-login_email_mode','email_mode', 'password', 'Login email mode', 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.0.1', 'User wallet history max count', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), `description` = VALUES(`description`), `updated_at` = CURRENT_TIMESTAMP;
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"version": "v0.1",
|
||||
"releaseDate": "2025-07-20",
|
||||
"version": "v1.0",
|
||||
"releaseDate": "2025-07-30",
|
||||
"description": "This is the latest release of the application.",
|
||||
"downloads": {
|
||||
"program": {
|
||||
"xpack_mcp_market": {
|
||||
"version": "v0.1.0",
|
||||
"version": "v1.0.1",
|
||||
"docker": "xpackai/xpack-mcp-market",
|
||||
"tar": "xpack-mcp-market.tar.gz",
|
||||
"url": "https://public.eolinker.com/xpack/images/xpack-mcp-market.${VERSION}.${ARCH}.tar.gz"
|
||||
|
||||
@@ -20,4 +20,12 @@ KEY_EMAIL_SMTP_PASSWORD = "email_smtp_password"
|
||||
KEY_EMAIL_SMTP_SENDER = "email_smtp_sender"
|
||||
KEY_LOGIN_EMAIL_ENABLE = "login_email_enable"
|
||||
KEY_LOGIN_EMAIL_MODE = "login_email_mode"
|
||||
KEY_DOMAIN = "domain"
|
||||
KEY_IS_SHOWCASED = "is_showcased"
|
||||
KEY_MCP_SERVER_PREFIX = "mcp_server_prefix"
|
||||
|
||||
KEY_FAQ = "faq"
|
||||
KEY_TOP_NAVIGATION = "top_navigation"
|
||||
KEY_EMBEDED_HTML = "embedded_html"
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import threading
|
||||
import time
|
||||
import logging
|
||||
from typing import Callable
|
||||
|
||||
import os
|
||||
from services.common.config import Config
|
||||
from services.common.database import get_db
|
||||
from services.admin_service.services.billing_message_handler import BillingMessageHandler
|
||||
@@ -20,7 +20,7 @@ class BillingMessageConsumer:
|
||||
"""Billing message consumer"""
|
||||
|
||||
def __init__(self):
|
||||
self.queue_name = "billing.api.calls"
|
||||
self.queue_name = os.getenv("BILLING_QUEUE_NAME") or "billing.api.calls"
|
||||
self.connection = None
|
||||
self.channel = None
|
||||
self.consuming = False
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import logging
|
||||
from fastapi import APIRouter, Depends
|
||||
import json
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.database import get_db
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
@@ -19,19 +20,26 @@ from services.admin_service.constants.sys_config_key import (
|
||||
KEY_LOGIN_GOOGLE_ENABLE,
|
||||
KEY_LOGIN_EMAIL_ENABLE,
|
||||
KEY_LOGIN_EMAIL_MODE,
|
||||
KEY_FAQ,
|
||||
KEY_EMBEDED_HTML,
|
||||
KEY_TOP_NAVIGATION,
|
||||
KEY_MCP_SERVER_PREFIX
|
||||
)
|
||||
from services.admin_service.services.payment_channel_service import PaymentChannelService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/config", summary="Get configuration (no login required)", tags=["common"])
|
||||
def get_config(db: Session = Depends(get_db)):
|
||||
def get_config(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get platform configuration settings without authentication."""
|
||||
try:
|
||||
# Create service instance
|
||||
sys_config_service = SysConfigService(db)
|
||||
payment_channel_service = PaymentChannelService(db)
|
||||
|
||||
# Get platform config
|
||||
platform_name = sys_config_service.get_value_by_key(KEY_PLATFORM_NAME) or "XPack"
|
||||
@@ -54,7 +62,24 @@ def get_config(db: Session = Depends(get_db)):
|
||||
# Convert to boolean
|
||||
email_is_enabled = email_is_enabled_raw.lower() in ("true", "t", "yes", "y", "1")
|
||||
email_mode = sys_config_service.get_value_by_key(KEY_LOGIN_EMAIL_MODE) or "password"
|
||||
|
||||
mcp_server_prefix = sys_config_service.get_value_by_key(KEY_MCP_SERVER_PREFIX) or ""
|
||||
|
||||
# Get homepage config
|
||||
faq = sys_config_service.get_value_by_key(KEY_FAQ) or "[]"
|
||||
embeded_html = sys_config_service.get_value_by_key(KEY_EMBEDED_HTML,True) or "{}"
|
||||
top_navigation = sys_config_service.get_value_by_key(KEY_TOP_NAVIGATION) or "[]"
|
||||
try:
|
||||
faq = json.loads(faq)
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("FAQ配置格式错误")
|
||||
try:
|
||||
embeded_html = json.loads(embeded_html)
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("Embeded HTML配置格式错误")
|
||||
try:
|
||||
top_navigation = json.loads(top_navigation)
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("Top Navigation配置格式错误")
|
||||
# Build response data
|
||||
config_data = {
|
||||
"login": {
|
||||
@@ -70,10 +95,48 @@ def get_config(db: Session = Depends(get_db)):
|
||||
"language": language,
|
||||
"theme": theme,
|
||||
"about_page": about_page,
|
||||
"mcp_server_prefix": mcp_server_prefix,
|
||||
},
|
||||
"faq": faq,
|
||||
"embeded_html": embeded_html,
|
||||
"top_navigation": top_navigation,
|
||||
"payment_channels": [{"id": item.id, "name": item.name} for item in payment_channel_service.available_list()],
|
||||
}
|
||||
|
||||
return ResponseUtils.success(data=config_data)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to get config: {str(e)}")
|
||||
return ResponseUtils.error(message="Failed to get configuration")
|
||||
|
||||
@router.get("/homepage", summary="Get homepage configuration (no login required)", tags=["common"])
|
||||
def get_homepage_config(db: Session = Depends(get_db)):
|
||||
"""Get homepage configuration settings without authentication."""
|
||||
try:
|
||||
# Create service instance
|
||||
sys_config_service = SysConfigService(db)
|
||||
|
||||
# Get homepage config
|
||||
faq = sys_config_service.get_value_by_key(KEY_FAQ) or "[]"
|
||||
embeded_html = sys_config_service.get_value_by_key(KEY_EMBEDED_HTML,True) or "{}"
|
||||
top_navigation = sys_config_service.get_value_by_key(KEY_TOP_NAVIGATION) or "[]"
|
||||
try:
|
||||
faq = json.loads(faq)
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("FAQ配置格式错误")
|
||||
try:
|
||||
embeded_html = json.loads(embeded_html)
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("Embeded HTML配置格式错误")
|
||||
try:
|
||||
top_navigation = json.loads(top_navigation)
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("Top Navigation配置格式错误")
|
||||
config_data = {
|
||||
"faq": faq,
|
||||
"embeded_html": embeded_html,
|
||||
"top_navigation": top_navigation,
|
||||
}
|
||||
return ResponseUtils.success(data=config_data)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to get homepage config: {str(e)}")
|
||||
return ResponseUtils.error(message="Failed to get configuration")
|
||||
@@ -12,6 +12,8 @@ from services.common.utils.cache_utils import CacheUtils
|
||||
from services.common.redis_keys import RedisKeys
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.common import error_msg
|
||||
from services.common.models.mcp_service import ChargeType
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -199,7 +201,9 @@ def get_mcp_service_list(
|
||||
"auth_header": service.auth_header,
|
||||
"auth_token": service.auth_token,
|
||||
"charge_type": service.charge_type.value if service.charge_type else None,
|
||||
"price": float(service.price) if service.price else 0.0,
|
||||
"price": str(float(service.price)) if service.price and service.charge_type == ChargeType.PER_CALL else "0.00",
|
||||
"input_token_price": str(float(service.input_token_price)) if service.input_token_price and service.charge_type == ChargeType.PER_TOKEN else "0.00",
|
||||
"output_token_price": str(float(service.output_token_price)) if service.output_token_price and service.charge_type == ChargeType.PER_TOKEN else "0.00",
|
||||
"enabled": service.enabled,
|
||||
"tags": parse_tags_to_array(service.tags),
|
||||
"created_at": str(service.created_at) if service.created_at else None,
|
||||
|
||||
@@ -26,7 +26,7 @@ def get_user_order_list(
|
||||
):
|
||||
"""Get paginated list of user order history."""
|
||||
offset = (page - 1) * page_size
|
||||
total, orders = user_wallet_history_service.success_order_list(offset, page_size)
|
||||
total, orders = user_wallet_history_service.success_deposit_order_list(offset, page_size)
|
||||
if not orders:
|
||||
return ResponseUtils.success_page(data=[], total=total, page_num=page, page_size=page_size)
|
||||
result = []
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from services.common.database import get_db
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from services.common.utils.request_utils import RequestUtils
|
||||
from services.admin_service.services.payment_service import PaymentService
|
||||
from services.admin_service.services.user_wallet_history_service import UserWalletHistoryService
|
||||
|
||||
@@ -30,22 +26,39 @@ class CreatePaymentLinkRequest(BaseModel):
|
||||
|
||||
|
||||
@router.post("/create_payment_link", response_model=dict)
|
||||
def create_payment_link(request: Request, body: CreatePaymentLinkRequest, payment: PaymentService = Depends(get_payment)):
|
||||
def create_payment_link(
|
||||
request: Request,
|
||||
body: CreatePaymentLinkRequest,
|
||||
payment: PaymentService = Depends(get_payment),
|
||||
):
|
||||
"""Create Stripe payment link for the user."""
|
||||
user = request.scope.get("user")
|
||||
if not user:
|
||||
return ResponseUtils.error(message="User not found", code=404)
|
||||
|
||||
try:
|
||||
payment_info = payment.create_stripe_payment_link(body.success_url, user_id=user.id, amount=body.amount, currency=body.currency)
|
||||
match body.payment_method:
|
||||
case "alipay":
|
||||
payment_info = payment.create_alipay_payment_link(user_id=user.id, amount=body.amount, currency=body.currency)
|
||||
if not payment_info:
|
||||
return ResponseUtils.error(message="Failed to create Alipay payment link", code=500)
|
||||
from services.admin_service.tasks.alipay_order_monitor_task import AlipayOrderMonitorTask
|
||||
alipay_monitor_task = AlipayOrderMonitorTask.get_instance()
|
||||
alipay_monitor_task.add_order_to_monitor(payment_id=payment_info.get("payment_id"))
|
||||
case _:
|
||||
if not body.success_url:
|
||||
return ResponseUtils.error(message="Success URL is required for Stripe payments", code=400)
|
||||
payment_info = payment.create_stripe_payment_link(body.success_url, user_id=user.id, amount=body.amount, currency=body.currency)
|
||||
if payment_info:
|
||||
return ResponseUtils.success({"pay_url": payment_info.get("payment_link"), "payment_id": payment_info.get("payment_id")})
|
||||
return ResponseUtils.error(message="Failed to create payment link", code=500)
|
||||
except Exception as e:
|
||||
return ResponseUtils.error(message=str(e), code=500)
|
||||
|
||||
|
||||
@router.post("/callback_stripe", response_model=dict)
|
||||
async def callback_stripe(request: Request, payment: PaymentService = Depends(get_payment)):
|
||||
@router.post("/callback_stripe", response_model = dict)
|
||||
async def callback_stripe(
|
||||
request: Request,
|
||||
payment: PaymentService = Depends(get_payment),
|
||||
):
|
||||
"""Handle Stripe payment webhook callback."""
|
||||
payload = (await request.body()).decode("utf-8")
|
||||
sig_header = request.headers.get("Stripe-Signature") or ""
|
||||
@@ -55,6 +68,16 @@ async def callback_stripe(request: Request, payment: PaymentService = Depends(ge
|
||||
else:
|
||||
return ResponseUtils.error(message="Stripe callback failed", code=500)
|
||||
|
||||
@router.post("/callback_alipay", response_model=dict)
|
||||
async def callback_alipay(request: Request, payment: PaymentService = Depends(get_payment)):
|
||||
"""Handle Alipay payment webhook callback."""
|
||||
payload = (await request.body()).decode("utf-8")
|
||||
result = payment.alipay_payment_callback(payload)
|
||||
if result:
|
||||
return ResponseUtils.success()
|
||||
else:
|
||||
return ResponseUtils.error(message="Alipay callback failed", code=500)
|
||||
|
||||
|
||||
@router.get("/order_status", response_model=dict)
|
||||
async def order_status(
|
||||
|
||||
@@ -37,7 +37,7 @@ async def payment_channel_list(
|
||||
"name": item.name,
|
||||
"config": cfg,
|
||||
"is_enabled": enable,
|
||||
"updated_time": item.update_at,
|
||||
"updated_time": item.updated_at,
|
||||
}
|
||||
)
|
||||
return ResponseUtils.success_page(data=result, total=total, page_num=page, page_size=page_size)
|
||||
@@ -53,14 +53,19 @@ async def payment_channel_enable(
|
||||
if not id:
|
||||
return ResponseUtils.error("Payment channel id cannot be empty")
|
||||
data = payment_channel_service.update_status(id, 1)
|
||||
|
||||
if data:
|
||||
if id == "alipay":
|
||||
from services.admin_service.tasks.alipay_order_monitor_task import AlipayOrderMonitorTask
|
||||
alipay_monitor_task = AlipayOrderMonitorTask.get_instance()
|
||||
alipay_monitor_task.start_monitor()
|
||||
return ResponseUtils.success(
|
||||
{
|
||||
"id": id,
|
||||
"name": data.name,
|
||||
"config": data.config,
|
||||
"is_enabled": data.status == 1,
|
||||
"updated_time": data.update_at,
|
||||
"updated_time": data.updated_at,
|
||||
}
|
||||
)
|
||||
return ResponseUtils.success(data={})
|
||||
@@ -77,13 +82,17 @@ async def payment_channel_disable(
|
||||
return ResponseUtils.error("Payment channel id cannot be empty")
|
||||
data = payment_channel_service.update_status(id, 0)
|
||||
if data:
|
||||
if id == "alipay":
|
||||
from services.admin_service.tasks.alipay_order_monitor_task import AlipayOrderMonitorTask
|
||||
alipay_monitor_task = AlipayOrderMonitorTask.get_instance()
|
||||
alipay_monitor_task.stop_monitor()
|
||||
return ResponseUtils.success(
|
||||
{
|
||||
"id": id,
|
||||
"name": data.name,
|
||||
"config": data.config,
|
||||
"is_enabled": data.status == 1,
|
||||
"updated_time": data.update_at,
|
||||
"updated_time": data.updated_at,
|
||||
}
|
||||
)
|
||||
return ResponseUtils.success(data={})
|
||||
@@ -110,7 +119,7 @@ async def payment_channel_config(
|
||||
"name": data.name,
|
||||
"config": config,
|
||||
"is_enabled": data.status == 1,
|
||||
"updated_time": data.update_at,
|
||||
"updated_time": data.updated_at,
|
||||
}
|
||||
)
|
||||
return ResponseUtils.success(data={})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from fastapi import APIRouter, Depends, Body
|
||||
import json
|
||||
from sqlalchemy import false, table
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.database import get_db
|
||||
@@ -6,7 +7,11 @@ from services.common.utils.response_utils import ResponseUtils
|
||||
from services.common.utils.email_utils import EmailUtils
|
||||
from services.admin_service.services.sys_config_service import SysConfigService
|
||||
from services.admin_service.services.user_service import UserService
|
||||
from services.admin_service.services.platform_report_service import PlatformReportService
|
||||
from services.admin_service.constants import sys_config_key
|
||||
from services.common.logging_config import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -18,6 +23,61 @@ def get_sysconfig_service(db: Session = Depends(get_db)) -> SysConfigService:
|
||||
def get_user_service(db: Session = Depends(get_db)) -> UserService:
|
||||
return UserService(db)
|
||||
|
||||
@router.get("/homepage")
|
||||
def get_homepage(
|
||||
sysconfig_service: SysConfigService = Depends(get_sysconfig_service),
|
||||
):
|
||||
faq = sysconfig_service.get_value_by_key(sys_config_key.KEY_FAQ) or "[]"
|
||||
# 判断是否为空值,若非空,则json反序列化
|
||||
try:
|
||||
# 数组类型
|
||||
if faq.startswith("[") and faq.endswith("]"):
|
||||
faq = json.loads(faq)
|
||||
else:
|
||||
return ResponseUtils.error("FAQ配置格式错误")
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("FAQ配置格式错误")
|
||||
|
||||
|
||||
top_navigation = sysconfig_service.get_value_by_key(sys_config_key.KEY_TOP_NAVIGATION) or "[]"
|
||||
try:
|
||||
# 数组类型
|
||||
if top_navigation.startswith("[") and top_navigation.endswith("]"):
|
||||
top_navigation = json.loads(top_navigation)
|
||||
else:
|
||||
return ResponseUtils.error("Top Navigation配置格式错误")
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("Top Navigation配置格式错误")
|
||||
embeded_html = sysconfig_service.get_value_by_key(sys_config_key.KEY_EMBEDED_HTML,True) or "{}"
|
||||
try:
|
||||
embeded_html = json.loads(embeded_html)
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error("Embeded HTML配置格式错误")
|
||||
|
||||
return ResponseUtils.success(
|
||||
data={
|
||||
"faq": faq,
|
||||
"top_navigation": top_navigation,
|
||||
"embeded_html": embeded_html,
|
||||
}
|
||||
)
|
||||
|
||||
@router.put("/homepage")
|
||||
def update_homepage(
|
||||
sysconfig_service: SysConfigService = Depends(get_sysconfig_service),
|
||||
body: dict = Body(...),
|
||||
):
|
||||
faq = body.get("faq")
|
||||
top_navigation = body.get("top_navigation")
|
||||
embeded_html = body.get("embeded_html")
|
||||
"""Update system configuration settings."""
|
||||
if faq:
|
||||
sysconfig_service.set_value_by_key(sys_config_key.KEY_FAQ, json.dumps(faq),"FAQ")
|
||||
if top_navigation:
|
||||
sysconfig_service.set_value_by_key(sys_config_key.KEY_TOP_NAVIGATION, json.dumps(top_navigation),"Top Navigation")
|
||||
if embeded_html:
|
||||
sysconfig_service.set_value_by_key(sys_config_key.KEY_EMBEDED_HTML, json.dumps(embeded_html),"Embeded HTML",True)
|
||||
return ResponseUtils.success()
|
||||
|
||||
@router.get("/info")
|
||||
def get_sysconfig(
|
||||
@@ -63,6 +123,12 @@ def get_sysconfig(
|
||||
email_smtp_password = sysconfig_service.get_value_by_key(sys_config_key.KEY_EMAIL_SMTP_PASSWORD)
|
||||
email_smtp_sender = sysconfig_service.get_value_by_key(sys_config_key.KEY_EMAIL_SMTP_SENDER)
|
||||
|
||||
domain = sysconfig_service.get_value_by_key(sys_config_key.KEY_DOMAIN)
|
||||
is_showcased_raw = sysconfig_service.get_value_by_key(sys_config_key.KEY_IS_SHOWCASED) or "false"
|
||||
is_showcased = is_showcased_raw.lower() in ("true", "t", "yes", "y", "1")
|
||||
|
||||
mcp_server_prefix = sysconfig_service.get_value_by_key(sys_config_key.KEY_MCP_SERVER_PREFIX)
|
||||
|
||||
return ResponseUtils.success(
|
||||
data={
|
||||
"platform": {
|
||||
@@ -75,6 +141,9 @@ def get_sysconfig(
|
||||
"language": language,
|
||||
"theme": theme,
|
||||
"about_page": about_page,
|
||||
"domain": domain,
|
||||
"is_showcased": is_showcased,
|
||||
"mcp_server_prefix": mcp_server_prefix,
|
||||
},
|
||||
"account": {
|
||||
"username": admin_username,
|
||||
@@ -138,6 +207,9 @@ def set_sysconfig(
|
||||
language = platform.get("language")
|
||||
theme = platform.get("theme")
|
||||
about_page = platform.get("about_page")
|
||||
domain = platform.get("domain")
|
||||
is_showcased = platform.get("is_showcased")
|
||||
mcp_server_prefix = platform.get("mcp_server_prefix")
|
||||
|
||||
account = body.get("account", {})
|
||||
admin_username = account.get("username")
|
||||
@@ -151,7 +223,7 @@ def set_sysconfig(
|
||||
login_email_config = login.get("email", {})
|
||||
login_email_mode = login_email_config.get("mode")
|
||||
login_email_is_enable = login_email_config.get("is_enabled") # 设置默认值为 False
|
||||
print("email info:",login_email_is_enable,login_email_mode)
|
||||
|
||||
# 获取邮件配置 - 现在从外层获取
|
||||
email_config = body.get("email", {})
|
||||
email_smtp_host = email_config.get("smtp_host")
|
||||
@@ -159,17 +231,9 @@ def set_sysconfig(
|
||||
email_smtp_user = email_config.get("smtp_user")
|
||||
email_smtp_password = email_config.get("smtp_password")
|
||||
email_smtp_sender = email_config.get("smtp_sender")
|
||||
|
||||
# if login_google_enable:
|
||||
# if login_google_enable == "false":
|
||||
# login_google_enable = "False"
|
||||
# else:
|
||||
# login_google_enable = "True"
|
||||
# if login_email_is_enable:
|
||||
# if login_email_is_enable == "false":
|
||||
# login_email_is_enable = "False"
|
||||
# else:
|
||||
# login_email_is_enable = "True"
|
||||
|
||||
|
||||
|
||||
# 批量更新配置
|
||||
configs = [
|
||||
(sys_config_key.KEY_PLATFORM_NAME, platform_name, "Platform name"),
|
||||
@@ -181,6 +245,9 @@ def set_sysconfig(
|
||||
(sys_config_key.KEY_LANGUAGE, language, "Language"),
|
||||
(sys_config_key.KEY_THEME, theme, "Theme"),
|
||||
(sys_config_key.KEY_ABOUT_PAGE, about_page, "About page"),
|
||||
(sys_config_key.KEY_DOMAIN, domain, "Domain"),
|
||||
(sys_config_key.KEY_IS_SHOWCASED, is_showcased, "Is showcased"),
|
||||
(sys_config_key.KEY_MCP_SERVER_PREFIX, mcp_server_prefix, "MCP server prefix"),
|
||||
(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, "谷歌登录是否启用"),
|
||||
@@ -203,6 +270,33 @@ def set_sysconfig(
|
||||
is_large = True
|
||||
sysconfig_service.set_value_by_key(key, value, desc,is_large)
|
||||
|
||||
# Report platform information asynchronously to avoid impacting main operations
|
||||
try:
|
||||
platform_report_service = PlatformReportService()
|
||||
|
||||
# Prepare platform data for reporting
|
||||
platform_report_data = {
|
||||
"name": platform_name,
|
||||
"logo": platform_logo,
|
||||
"url": platform_url,
|
||||
"website_title": website_title,
|
||||
"headline": headline,
|
||||
"subheadline": subheadline,
|
||||
"language": language,
|
||||
"theme": theme,
|
||||
"domain": domain,
|
||||
"is_showcased": is_showcased,
|
||||
"mcp_server_prefix": mcp_server_prefix,
|
||||
}
|
||||
|
||||
# Use background reporting to avoid blocking the main configuration update
|
||||
platform_report_service.report_platform_info_background(platform_report_data)
|
||||
logger.debug("Platform information reporting initiated in background")
|
||||
|
||||
except Exception as e:
|
||||
# Log error but continue with main operation - reporting failure should not affect configuration update
|
||||
logger.warning(f"Failed to initiate platform reporting: {e}")
|
||||
|
||||
return get_sysconfig(sysconfig_service, user_service)
|
||||
|
||||
except Exception as e:
|
||||
@@ -239,5 +333,5 @@ def test_email_config(
|
||||
return ResponseUtils.error(f"测试邮件配置失败:{str(e)}")
|
||||
|
||||
|
||||
def str_to_bool(s):
|
||||
return s.lower() in ("true", "t", "yes", "y", "1")
|
||||
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
from fastapi import APIRouter, Query
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
from fastapi import APIRouter, Query, Body, Request
|
||||
from sqlalchemy.orm import Session
|
||||
from fastapi import Depends
|
||||
from services.admin_service.services.user_service import UserService
|
||||
from services.admin_service.services.user_wallet_service import UserWalletService
|
||||
from services.common.database import get_db
|
||||
from services.common.models.user import User
|
||||
from services.common.response.user_manager_response import UserManagerResponse
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from services.common.utils.validation_utils import ValidationUtils
|
||||
from services.common.logging_config import get_logger
|
||||
import json,hashlib
|
||||
from services.admin_service.services.payment_service import PaymentService
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -24,6 +23,9 @@ def get_user_wallet_service(db: Session = Depends(get_db)) -> UserWalletService:
|
||||
def get_user_service(db: Session = Depends(get_db)) -> UserService:
|
||||
return UserService(db)
|
||||
|
||||
def get_payment_service(db: Session = Depends(get_db)) -> PaymentService:
|
||||
return PaymentService(db)
|
||||
|
||||
|
||||
@router.delete("/account", summary="Delete user account")
|
||||
async def delete_user(
|
||||
@@ -77,3 +79,36 @@ async def get_user_list(
|
||||
user_list.append({"id": user.id, "email": user.email, "created_at": user.created_at, "balance": wallet.balance if wallet else 0})
|
||||
|
||||
return ResponseUtils.success_page(data=user_list, total=total, page_num=page, page_size=page_size)
|
||||
|
||||
@router.post("/balance/recharge")
|
||||
async def recharge_balance(
|
||||
request: Request,
|
||||
payment_service: PaymentService = Depends(get_payment_service),
|
||||
):
|
||||
body = await request.body()
|
||||
body_str = body.decode('utf-8')
|
||||
timestamp=request.headers.get("x-xpack-timestamp")
|
||||
sign = request.headers.get("x-xpack-sign")
|
||||
# calculate md5 hash of the body and timestamp
|
||||
md5_hash = hashlib.md5(f"{timestamp}{body_str}".encode('utf-8')).hexdigest()
|
||||
calculated_sign = hashlib.sha256(md5_hash.encode('utf-8')).hexdigest()
|
||||
print(f"sign: {sign}, calculated_sign: {calculated_sign},md5_hash: {md5_hash}")
|
||||
if sign != calculated_sign:
|
||||
return ResponseUtils.error(message="Invalid signature")
|
||||
try:
|
||||
body_str = body_str.replace("'", '"') # Ensure JSON format
|
||||
body = json.loads(body_str)
|
||||
except json.JSONDecodeError:
|
||||
return ResponseUtils.error(message="Invalid JSON format")
|
||||
|
||||
user_id = body.get("user_id")
|
||||
balance = body.get("balance")
|
||||
typ = body.get("type")
|
||||
transaction_id = hashlib.md5(f"{timestamp}{user_id}{balance}{typ}".encode('utf-8')).hexdigest()
|
||||
if payment_service.check_transaction_id_exists(transaction_id):
|
||||
return ResponseUtils.error(message="Transaction ID already exists")
|
||||
print(f"user_id: {user_id}, amount: {balance}, typ: {typ}, transaction_id: {transaction_id}")
|
||||
success = payment_service.platform_payment(user_id=user_id, amount=balance, typ=typ, transaction_id=transaction_id)
|
||||
if not success:
|
||||
return ResponseUtils.error(message="Failed to recharge wallet balance")
|
||||
return ResponseUtils.success(message="Wallet recharge successful")
|
||||
@@ -3,7 +3,6 @@ from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
import asyncio
|
||||
import threading
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -26,12 +25,15 @@ from services.admin_service.controllers import user_stats
|
||||
from services.admin_service.controllers import email_test
|
||||
from services.admin_service.controllers import upload
|
||||
|
||||
|
||||
|
||||
from services.admin_service.consumers.billing_message_consumer import BillingMessageConsumer
|
||||
from services.admin_service.middleware import AuthMiddleware
|
||||
from services.common.middleware.exception_middleware import ExceptionHandlingMiddleware
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from services.common import error_msg
|
||||
from fastapi.responses import JSONResponse
|
||||
from services.admin_service.task import *
|
||||
|
||||
# Setup logging for admin service
|
||||
setup_logging("admin_service")
|
||||
@@ -60,12 +62,12 @@ def stop_billing_consumer():
|
||||
logger.info("Stopping billing message consumer...")
|
||||
consumer_instance.stop_consuming()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Application lifecycle management"""
|
||||
global consumer_thread
|
||||
|
||||
# start_alipay_order_monitor()
|
||||
|
||||
# Startup: Start consumer in separate thread
|
||||
logger.info("Admin Service starting...")
|
||||
try:
|
||||
@@ -80,6 +82,7 @@ async def lifespan(app: FastAPI):
|
||||
# Shutdown: Stop consumer
|
||||
logger.info("Admin Service shutting down...")
|
||||
stop_billing_consumer()
|
||||
# start_alipay_order_monitor()
|
||||
|
||||
|
||||
app = FastAPI(title="Admin Service", openapi_url="/openapi.json", lifespan=lifespan)
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
from fastapi import Request, HTTPException
|
||||
from fastapi.responses import JSONResponse
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.database import get_db
|
||||
from services.common.utils.auth import verify_token
|
||||
from services.common.models.user import User
|
||||
from services.common.config import Config
|
||||
from services.common.logging_config import get_logger
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from typing import Optional
|
||||
import re
|
||||
import json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, List
|
||||
from typing import Optional, List, Tuple
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.models.mcp_call_log import McpCallLog, ProcessStatus
|
||||
|
||||
@@ -34,7 +34,7 @@ class McpCallLogRepository:
|
||||
return True
|
||||
return False
|
||||
|
||||
def get_user_call_history(self, user_id: str, page: int = 1, page_size: int = 20) -> tuple[int, List[McpCallLog]]:
|
||||
def get_user_call_history(self, user_id: str, page: int = 1, page_size: int = 20) -> Tuple[int, List[McpCallLog]]:
|
||||
total = self.db.query(McpCallLog).filter(McpCallLog.user_id == user_id).count()
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.models.mcp_service import McpService
|
||||
from typing import Optional, Tuple
|
||||
from typing import Optional, Tuple, List
|
||||
|
||||
|
||||
class McpServiceRepository:
|
||||
@@ -51,10 +51,10 @@ class McpServiceRepository:
|
||||
def get_by_slug_name(self, slug_name: str) -> Optional[McpService]:
|
||||
return self.db.query(McpService).filter(McpService.slug_name == slug_name).first()
|
||||
|
||||
def get_all(self) -> list[McpService]:
|
||||
def get_all(self) -> List[McpService]:
|
||||
return self.db.query(McpService).order_by(McpService.created_at.desc()).all()
|
||||
|
||||
def get_all_paginated(self, page: int = 1, page_size: int = 10) -> Tuple[list[McpService], int]:
|
||||
def get_all_paginated(self, page: int = 1, page_size: int = 10) -> Tuple[List[McpService], int]:
|
||||
"""Get service list with pagination"""
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
@@ -77,7 +77,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) -> Tuple[List[McpService], int]:
|
||||
"""Get public service list with pagination, supports keyword search"""
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.models.mcp_tool_api import McpToolApi
|
||||
from typing import Optional
|
||||
from typing import Optional, List
|
||||
|
||||
|
||||
class McpToolApiRepository:
|
||||
@@ -31,7 +31,7 @@ class McpToolApiRepository:
|
||||
self.db.refresh(mcp_tool_api)
|
||||
return mcp_tool_api
|
||||
|
||||
def get_by_service_id(self, service_id: str) -> list[McpToolApi]:
|
||||
def get_by_service_id(self, service_id: str) -> List[McpToolApi]:
|
||||
"""Get API list by service ID"""
|
||||
return self.db.query(McpToolApi).filter(
|
||||
McpToolApi.service_id == service_id,
|
||||
|
||||
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user