diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index b99a8ba..e023d5b 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -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 -## 开发建议 -- 有适当的日志记录(英文格式,统一格式) -- 添加方法级别英文注释,需要简洁 -- 添加的注释一律使用英文 \ No newline at end of file +## 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 \ No newline at end of file diff --git a/README-zh-cn.md b/README-zh-cn.md index 9071350..17595a7 100644 --- a/README-zh-cn.md +++ b/README-zh-cn.md @@ -8,18 +8,18 @@ 简体中文
-**XPack** 是一款轻量级、开源的 MCP(Model Context Protocol)服务市场框架。 -它可以将任何符合 OpenAPI 规范的接口快速转换为 MCP 服务,并帮助你在数分钟内搭建自己的 API 商店。 +**XPack** 是全球首个开源 MCP 交易平台,帮助你在10分钟内快速搭建自己的 MCP 商店并立刻开始销售 MCP 服务。+ {t(activeItem.description)} +
+{t('Configure Stripe payment interface')}
-+ {t("Configure Alipay payment interface")} +
++ {t("Configure Stripe payment interface")} +
++ {t("Configure WeChat payment interface")} +
+{t('Configure administrator login credentials')}
- - }> ++ {t("Configure administrator login credentials")} +
+ + } + >+ {t("Configure custom HTML content for global injection")} +
+ + } + > ++ {t("Configure frequently asked questions for your users")} +
+ + } + > +- {t("Configure about page content")} -
- - } - > -+ {t("Configure top navigation menu items and links")} +
+ + } + > +
{`{
"mcpServers": {
- "${mcpName || "xpack-mcp-market"}": {
+ "${mcpName}": {
"type": "sse",
"autoApprove":"all",
"url": "${url}?apikey=`}
diff --git a/frontend/src/components/theme/classic/Home.tsx b/frontend/src/components/theme/classic/Home.tsx
index 847cfd2..e6a3a79 100644
--- a/frontend/src/components/theme/classic/Home.tsx
+++ b/frontend/src/components/theme/classic/Home.tsx
@@ -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 = ({
{/* Services Grid */}
-
+
{services.map((service) => (
-
+
{/* Header */}
@@ -211,6 +213,8 @@ export const Home: React.FC = ({
@@ -245,6 +249,7 @@ export const Home: React.FC = ({
)}
+
diff --git a/frontend/src/components/theme/classic/Navigation.tsx b/frontend/src/components/theme/classic/Navigation.tsx
index 70df4a9..8946cc6 100644
--- a/frontend/src/components/theme/classic/Navigation.tsx
+++ b/frontend/src/components/theme/classic/Navigation.tsx
@@ -43,7 +43,12 @@ export const Navigation: React.FC = ({ items }) => {
{items?.map((item) => (
-
+
{t(item.label)}
))}
diff --git a/frontend/src/components/theme/creative/Detail.tsx b/frontend/src/components/theme/creative/Detail.tsx
index 71af15c..dac9143 100644
--- a/frontend/src/components/theme/creative/Detail.tsx
+++ b/frontend/src/components/theme/creative/Detail.tsx
@@ -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";
@@ -24,6 +23,7 @@ interface DetailProps {
mcpName?: string;
// navigation items
navItems?: NavigationItem[];
+ onCopy: () => void;
}
export const Detail: React.FC = ({
@@ -32,6 +32,7 @@ export const Detail: React.FC = ({
url,
mcpName,
navItems = [],
+ onCopy,
}) => {
const { t } = useTranslation();
const [activeTab, setActiveTab] = useState("overview");
@@ -42,151 +43,190 @@ export const Detail: React.FC = ({
}
return (
-
+
{/* Creative Background */}
-
- {/* Artistic decorative elements */}
-
-
-
-
+
+
+ {/* Artistic decorative elements */}
+
+
+
+
- {/* Additional artistic elements */}
-
-
-
-
-
- {/* Creative Product Header */}
-
-
-
-
-
-
+ {/* Additional artistic elements */}
+
+
- {/* Main Content */}
-
-
- {/* Left side - Main content */}
-
-
-
-
- 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",
- }}
- >
-
-
- {t("Overview")}
-
- }
- >
-
-
-
-
-
-
- {t("Tools")}
-
- {product.tools.length}
-
-
- }
- >
-
-
-
-
-
-
-
+
+ {/* Creative Product Header */}
+
+
+
+
+
+
- {/* Right side - Server Config */}
-
-
-
-
-
-
-
-
-
- {t("Configuration")}
-
-
- {/* Code Snippet */}
-
-
-
+
+ {/* Left side - Main content */}
+
+
+
+
+ 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",
+ }}
+ >
+
+
+ {t("Overview")}
+
+ }
>
- {platformConfig?.name} MCP
-
-
-
- {`{
+
+
+
+
+
+
+ {t("Tools")}
+
+ {product.tools.length}
+
+
+ }
+ >
+
+ {product.tools.length > 0 ? (
+ product.tools.map((tool, index) => (
+
+
+
+ {tool.name}
+
+
+ {tool.description ||
+ t("No description available")}
+
+
+
+ ))
+ ) : (
+
+
+
+ {t("No tools available in this service.")}
+
+
+
+ )}
+
+
+
+
+
+
+
+ {/* Right side - Server Config */}
+
+
+
+
+
+
+
+
+
+ {t("Configuration")}
+
+
+ {/* Code Snippet */}
+
+
+
+
+ {platformConfig?.name} MCP
+
+
+
+
+
+ {`{
"mcpServers": {
- "${mcpName || "xpack-mcp-market"}": {
+ "${mcpName}": {
"type": "sse",
"autoApprove":"all",
"url": "${url}?apikey=`}
- {`{Your-${platformConfig?.name}-API-Key}`}
- {`"
+ {`{Your-${platformConfig?.name}-API-Key}`}
+ {`"
}
}
}`}
-
-
-
-
-
-
+
+
+
+
+
+
+
-
- {/* SEO-friendly: Simple text content for search engines */}
-
-
+
+
+
);
};
diff --git a/frontend/src/components/theme/creative/Home.tsx b/frontend/src/components/theme/creative/Home.tsx
index 46bad2a..e2acc69 100644
--- a/frontend/src/components/theme/creative/Home.tsx
+++ b/frontend/src/components/theme/creative/Home.tsx
@@ -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 = ({
{/* Creative Background decorative elements */}
- {/* 主要装饰圆圈 */}
+ {/* main decorative circles */}
- {/* 小装饰圆圈 */}
+ {/* small decorative circles */}
- {/* 微小装饰点 */}
+ {/* small decorative points */}
@@ -129,7 +130,7 @@ export const Home: React.FC = ({
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 = ({
-
- ✨ 加载魔法中...
-
@@ -180,7 +178,7 @@ export const Home: React.FC = ({
{/* Creative Services Grid */}
-
+
{services.map((service, index) => {
const gradientBorders = [
"border-pink-200/50",
@@ -211,7 +209,7 @@ export const Home: React.FC = ({
= ({
hover:scale-105 hover:shadow-xl
transition-all duration-300 ease-out
group-hover:bg-white/90 relative
- h-[200px]
+ h-[200px] w-full
`}
>
- {/* 创意图标 */}
+ {/* creative icon */}
= ({
`}
>
- {/* 服务标题 */}
+ {/* service title */}
{service.name}
- {/* 服务描述 */}
-
- {service.short_description || "探索精彩服务"}
+ {/* service description */}
+
+ {service.short_description ||
+ t("No description available")}
- {/* 装饰性元素 */}
+ {/* decorative elements */}
@@ -265,6 +264,8 @@ export const Home: React.FC = ({
@@ -317,6 +318,7 @@ export const Home: React.FC = ({
`}
)}
+
);
diff --git a/frontend/src/components/theme/creative/Navigation.tsx b/frontend/src/components/theme/creative/Navigation.tsx
index f7a6f52..18efda2 100644
--- a/frontend/src/components/theme/creative/Navigation.tsx
+++ b/frontend/src/components/theme/creative/Navigation.tsx
@@ -52,7 +52,12 @@ export const Navigation: React.FC = ({ items }) => {
{items?.map((item) => (
-
+
{t(item.label)}
))}
diff --git a/frontend/src/components/theme/modern/Detail.tsx b/frontend/src/components/theme/modern/Detail.tsx
index b7ff790..91a3e2f 100644
--- a/frontend/src/components/theme/modern/Detail.tsx
+++ b/frontend/src/components/theme/modern/Detail.tsx
@@ -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";
@@ -24,6 +24,7 @@ interface DetailProps {
mcpName?: string;
// navigation items
navItems?: NavigationItem[];
+ onCopy: () => void;
}
export const Detail: React.FC = ({
@@ -32,6 +33,7 @@ export const Detail: React.FC = ({
url,
mcpName,
navItems = [],
+ onCopy,
}) => {
const { t } = useTranslation();
const [activeTab, setActiveTab] = useState("overview");
@@ -138,18 +140,26 @@ export const Detail: React.FC = ({
{/* Code Snippet */}
-
- {platformConfig?.name} MCP
-
+
+
+ {platformConfig?.name} MCP
+
+
+
{`{
"mcpServers": {
- "${mcpName || "xpack-mcp-market"}": {
+ "${mcpName}": {
"type": "sse",
"autoApprove":"all",
"url": "${url}?apikey=`}
diff --git a/frontend/src/components/theme/modern/Home.tsx b/frontend/src/components/theme/modern/Home.tsx
index 84741bf..323efce 100644
--- a/frontend/src/components/theme/modern/Home.tsx
+++ b/frontend/src/components/theme/modern/Home.tsx
@@ -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 = ({
{/* Modern Search Bar */}
-
+
= ({
- {/* Service List Section */}
- {loading ? (
-
-
-
-
-
- ) : (
-
-
- {/* Services Grid */}
-
- {services.map((service) => (
-
-
-
- {/* Header */}
-
-
-
-
-
-
-
- {service.name}
-
-
-
-
-
-
- {/* Description */}
-
- {service.short_description ||
- t("No description available")}
-
-
-
- {/* Footer */}
-
-
- {/* Tools count */}
-
-
-
- {t("{{count}} Tools", {
- count: service.tools.length,
- })}
-
-
-
- {/* Price */}
-
-
-
-
-
-
-
- ))}
+
+ {/* Service List Section */}
+ {loading ? (
+
+
+
-
- {/* Pagination */}
- {totalPages > 1 && (
-
-
-
- )}
-
- )}
+ ) : (
+
+
+ {/* Services Grid */}
+
+ {services.map((service) => (
+
+
+
+ {/* Header */}
+
+
+
+
+
+
+
+ {service.name}
+
+
+
+
+
+
+ {/* Description */}
+
+ {service.short_description ||
+ t("No description available")}
+
+
+
+ {/* Footer */}
+
+
+ {/* Tools count */}
+
+
+
+ {t("{{count}} Tools", {
+ count: service.tools.length,
+ })}
+
+
+
+ {/* Price */}
+
+
+
+
+
+
+
+ ))}
+
+
+ {/* Pagination */}
+ {totalPages > 1 && (
+
+
+
+ )}
+
+
+ )}
+
+
diff --git a/frontend/src/components/theme/modern/Navigation.tsx b/frontend/src/components/theme/modern/Navigation.tsx
index a0f8eca..e2288be 100644
--- a/frontend/src/components/theme/modern/Navigation.tsx
+++ b/frontend/src/components/theme/modern/Navigation.tsx
@@ -48,7 +48,12 @@ export const Navigation: React.FC = ({ items }) => {
{items?.map((item) => (
-
+
{t(item.label)}
))}
diff --git a/frontend/src/components/theme/temu/Detail.tsx b/frontend/src/components/theme/temu/Detail.tsx
index e8ad3ba..d93d628 100644
--- a/frontend/src/components/theme/temu/Detail.tsx
+++ b/frontend/src/components/theme/temu/Detail.tsx
@@ -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";
@@ -24,6 +23,7 @@ interface DetailProps {
mcpName?: string;
// navigation items
navItems?: NavigationItem[];
+ onCopy: () => void;
}
export const Detail: React.FC = ({
@@ -32,6 +32,7 @@ export const Detail: React.FC = ({
url,
mcpName,
navItems = [],
+ onCopy,
}) => {
const { t } = useTranslation();
const [activeTab, setActiveTab] = useState("overview");
@@ -159,18 +160,26 @@ export const Detail: React.FC = ({
{/* Code Snippet */}
-
- {platformConfig?.name} MCP
-
+
+
+ {platformConfig?.name} MCP
+
+
+
{`{
"mcpServers": {
- "${mcpName || "xpack-mcp-market"}": {
+ "${mcpName}": {
"type": "sse",
"autoApprove":"all",
"url": "${url}?apikey=`}
diff --git a/frontend/src/components/theme/temu/Home.tsx b/frontend/src/components/theme/temu/Home.tsx
index f1c301a..e530cf8 100644
--- a/frontend/src/components/theme/temu/Home.tsx
+++ b/frontend/src/components/theme/temu/Home.tsx
@@ -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 = ({
@@ -212,6 +215,7 @@ export const Home: React.FC = ({
)}
>
)}
+
diff --git a/frontend/src/components/theme/temu/Navigation.tsx b/frontend/src/components/theme/temu/Navigation.tsx
index 6d8952f..1e1aea7 100644
--- a/frontend/src/components/theme/temu/Navigation.tsx
+++ b/frontend/src/components/theme/temu/Navigation.tsx
@@ -52,7 +52,9 @@ export const Navigation: React.FC = ({ items }) => {
{items?.map((item) => (
{t(item.label)}
diff --git a/frontend/src/components/user-management/AdminRechargeModal.tsx b/frontend/src/components/user-management/AdminRechargeModal.tsx
new file mode 100644
index 0000000..957b80b
--- /dev/null
+++ b/frontend/src/components/user-management/AdminRechargeModal.tsx
@@ -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;
+}
+
+export const AdminRechargeModal: React.FC = ({
+ isOpen,
+ onClose,
+ user,
+ onRecharge,
+}) => {
+ const { t } = useTranslation();
+ const [amount, setAmount] = useState("");
+ const [error, setError] = useState("");
+ const [loading, setLoading] = useState(false);
+
+ const handleAmountChange = (e: React.ChangeEvent) => {
+ 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 (
+
+
+ {() => (
+ <>
+
+ {t("Recharge User")}
+
+
+ {user && (
+
+
+ {t("User")}: {user.email}
+
+
+ {t("Current Balance")}: ${user.balance.toFixed(2)}
+
+
+ )}
+
+ $
+
+ }
+ isInvalid={!!error}
+ errorMessage={error}
+ type="number"
+ />
+
+
+
+
+
+ >
+ )}
+
+
+ );
+};
diff --git a/frontend/src/components/user-management/UserManagement.tsx b/frontend/src/components/user-management/UserManagement.tsx
index 31108f5..11e8907 100644
--- a/frontend/src/components/user-management/UserManagement.tsx
+++ b/frontend/src/components/user-management/UserManagement.tsx
@@ -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 => {
+ return await handleRechargeUser(id, amount);
+ },
+ [handleRechargeUser]
+ );
+
return (
{
users={users}
loading={loading}
onDelete={handleDeleteUserClick}
+ onRecharge={handleRecharge}
pagination={pagination}
onPageChange={setPage}
/>
diff --git a/frontend/src/components/user-management/UserTable.tsx b/frontend/src/components/user-management/UserTable.tsx
index 7bb185a..031f918 100644
--- a/frontend/src/components/user-management/UserTable.tsx
+++ b/frontend/src/components/user-management/UserTable.tsx
@@ -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;
pagination: {
page: number;
pageSize: number;
@@ -33,6 +35,7 @@ export const UserTable: React.FC = ({
users,
loading = false,
onDelete,
+ onRecharge,
pagination,
onPageChange,
}) => {
@@ -45,10 +48,25 @@ export const UserTable: React.FC = ({
// 直接显示传入的用户数据(已经是当前页的数据)
const items = users;
+ const [isRechargeModalOpen, setIsRechargeModalOpen] = React.useState(false);
+ const [selectedUser, setSelectedUser] = React.useState(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 = ({
removeWrapper
>
- {t('Email')}
- {t('Register Date')}
- {t('Balance')}
- {t('Actions')}
+ {t("Email")}
+ {t("Register Date")}
+ {t("Balance")}
+ {t("Actions")}
}
- emptyContent={t('No users found')}
+ emptyContent={t("No users found")}
>
{(user) => (
{user.email}
-
- {user.created_at || '-'}
-
-
- {user.balance.toFixed(2) || "-"}
-
+ {user.created_at || "-"}
+ {user.balance.toFixed(2) || "-"}
+
+
+
-
+
)}
+
+ {/* Admin Recharge Modal */}
+
);
-};
\ No newline at end of file
+};
diff --git a/frontend/src/hooks/useHomepageConfigManagement.ts b/frontend/src/hooks/useHomepageConfigManagement.ts
new file mode 100644
index 0000000..91174cf
--- /dev/null
+++ b/frontend/src/hooks/useHomepageConfigManagement.ts
@@ -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({
+ faq: [],
+ top_navigation: [],
+ embeded_html: {
+ is_enabled: false,
+ html: "",
+ },
+ });
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState(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 => {
+ 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 => {
+ return await saveHomepageConfig({ faq: faqs });
+ },
+ [saveHomepageConfig]
+ );
+
+ // save navigation data
+ const saveNavigationConfig = useCallback(
+ async (navigationItems: TopNavigationItem[]): Promise => {
+ return await saveHomepageConfig({ top_navigation: navigationItems });
+ },
+ [saveHomepageConfig]
+ );
+
+ // save embedded HTML data
+ const saveEmbeddedHtmlConfig = useCallback(
+ async (htmlData: EmbeddedHtmlConfig): Promise => {
+ 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,
+ };
+};
diff --git a/frontend/src/hooks/usePaymentChannelManagement.ts b/frontend/src/hooks/usePaymentChannelManagement.ts
index 579ef86..2ad7167 100644
--- a/frontend/src/hooks/usePaymentChannelManagement.ts
+++ b/frontend/src/hooks/usePaymentChannelManagement.ts
@@ -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([]);
const [stripeConfig, setStripeConfig] = useState({
secret: "",
webhook_secret: "",
+ is_enabled: false,
+ });
+ const [alipayConfig, setAlipayConfig] = useState({
+ app_id: "",
+ app_private_key: "",
+ alipay_public_key: "",
+ is_enabled: false,
+ });
+ const [wechatConfig, setWechatConfig] = useState({
+ app_id: "",
+ mch_id: "",
+ is_enabled: false,
});
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [testResult, setTestResult] = useState(
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,
diff --git a/frontend/src/hooks/useSystemConfigManagement.ts b/frontend/src/hooks/useSystemConfigManagement.ts
index 187e5b9..64d250d 100644
--- a/frontend/src/hooks/useSystemConfigManagement.ts
+++ b/frontend/src/hooks/useSystemConfigManagement.ts
@@ -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(null);
+ // faq config
+ const [faqItems, setFaqItems] = useState([]);
+ const [faqLoading, setFaqLoading] = useState(false);
+ const [faqError, setFaqError] = useState(null);
+
+ // top navigation config
+ const [topNavigation, setTopNavigation] = useState([]);
+ const [navigationLoading, setNavigationLoading] = useState(false);
+ const [navigationError, setNavigationError] = useState(null);
+
+ // embedded html config
+ const [embeddedHtml, setEmbeddedHtml] = useState(null);
+ const [embeddedHtmlLoading, setEmbeddedHtmlLoading] = useState(false);
+ const [embeddedHtmlError, setEmbeddedHtmlError] = useState(null);
+
+ // payment channels config
+ const [paymentChannels, setPaymentChannels] = useState([]);
+ const [paymentLoading, setPaymentLoading] = useState(false);
+ const [paymentError, setPaymentError] = useState(null);
+
+ // installation status
+ const [isInstalled, setIsInstalled] = useState(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,
diff --git a/frontend/src/hooks/useUserManagement.ts b/frontend/src/hooks/useUserManagement.ts
index 7bacf71..8c12b65 100644
--- a/frontend/src/hooks/useUserManagement.ts
+++ b/frontend/src/hooks/useUserManagement.ts
@@ -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 => {
+ 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,
diff --git a/frontend/src/services/homepageConfigService.ts b/frontend/src/services/homepageConfigService.ts
new file mode 100644
index 0000000..bc88ea6
--- /dev/null
+++ b/frontend/src/services/homepageConfigService.ts
@@ -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 {
+ const response = await fetchAdminAPI(
+ "/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 {
+ 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();
diff --git a/frontend/src/services/paymentChannelService.ts b/frontend/src/services/paymentChannelService.ts
index 313b177..484a298 100644
--- a/frontend/src/services/paymentChannelService.ts
+++ b/frontend/src/services/paymentChannelService.ts
@@ -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 {
- const response = await fetchAdminAPI(
- "/api/payment_channel/info",
- {
- method: "PUT",
- body: {
- id: "stripe",
- config: config,
- } as unknown as BodyInit,
- }
- );
+ // Generic method to save payment channel configuration
+ async savePaymentChannelConfig(
+ channelId: string,
+ config: T,
+ channelName: string
+ ): Promise {
+ const response = await fetchAdminAPI("/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 {
+ return this.savePaymentChannelConfig("stripe", config, "Stripe");
+ }
+
+ // Generic method to test payment channel connection
+ async testPaymentChannelConnection(
+ channelId: string,
+ config: T,
+ channelName: string
): Promise {
try {
- const response = await fetchAdminAPI("/api/payment_channel/info", {
- method: "PUT",
- body: JSON.stringify(config),
+ const response = await fetchAdminAPI("/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 {
+ return this.testPaymentChannelConnection("stripe", config, "Stripe");
+ }
+
// enable payment channel
- async enablePaymentChannel(id: string): Promise {
+ async enablePaymentChannel(id: string): Promise {
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 {
+ async disablePaymentChannel(id: string): Promise {
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 {
+ return this.savePaymentChannelConfig("alipay", config, "Alipay");
+ }
+
+ // Save WeChat configuration
+ async saveWechatConfig(config: WechatConfig): Promise {
+ return this.savePaymentChannelConfig("wechat", config, "WeChat");
+ }
+
+ // Test Alipay connection
+ async testAlipayConnection(
+ config: AlipayConfig
+ ): Promise {
+ return this.testPaymentChannelConnection("alipay", config, "Alipay");
+ }
+
+ // Test WeChat connection
+ async testWechatConnection(
+ config: WechatConfig
+ ): Promise {
+ return this.testPaymentChannelConnection("wechat", config, "WeChat");
}
// validate stripe config
diff --git a/frontend/src/services/platformConfigService.ts b/frontend/src/services/platformConfigService.ts
index d7eae21..56c5aa6 100644
--- a/frontend/src/services/platformConfigService.ts
+++ b/frontend/src/services/platformConfigService.ts
@@ -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,
+ };
}
}
diff --git a/frontend/src/services/systemConfigService.ts b/frontend/src/services/systemConfigService.ts
index bd27320..de43170 100644
--- a/frontend/src/services/systemConfigService.ts
+++ b/frontend/src/services/systemConfigService.ts
@@ -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 {
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;
diff --git a/frontend/src/services/userService.ts b/frontend/src/services/userService.ts
index 4db7f0f..32af8b2 100644
--- a/frontend/src/services/userService.ts
+++ b/frontend/src/services/userService.ts
@@ -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 {}
@@ -63,3 +64,42 @@ export const deleteUser = async (userId: string): Promise => {
toast.success(i18n.t("User deleted successfully"));
return true;
};
+
+/**
+ * recharge user balance
+ */
+export const rechargeUser = async (
+ userId: string,
+ amount: number
+): Promise => {
+ // 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;
+};
diff --git a/frontend/src/shared/components/marketplace/Price.tsx b/frontend/src/shared/components/marketplace/Price.tsx
index 262aa65..5fb16aa 100644
--- a/frontend/src/shared/components/marketplace/Price.tsx
+++ b/frontend/src/shared/components/marketplace/Price.tsx
@@ -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 = ({ price, charge_type }) => {
+export const Price: React.FC = ({
+ 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 = ({ price, charge_type }) => {
);
} else {
+ const inputPrice = parseFloat(input_token_price || "0");
+ const outputPrice = parseFloat(output_token_price || "0");
return (
-
-
-
- ${priceText.toFixed(2)}
-
- /{t("token")}
+
+
+ {t("Input")}:
+
+ ${inputPrice.toFixed(2)}
+
+ /{t("1M tokens")}
+
+
+ {t("Output")}:
+
+ ${outputPrice.toFixed(2)}
+
+ /{t("1M tokens")}
+
);
}
diff --git a/frontend/src/shared/components/marketplace/ProductDetail.tsx b/frontend/src/shared/components/marketplace/ProductDetail.tsx
index 347bbfb..350b857 100644
--- a/frontend/src/shared/components/marketplace/ProductDetail.tsx
+++ b/frontend/src/shared/components/marketplace/ProductDetail.tsx
@@ -14,15 +14,17 @@ interface ProductDetailClientProps {
product: ServiceData;
breadcrumbs?: {
link: string;
- name: string
+ name: string;
}[];
mcpName?: string;
+ url?: string;
}
export const ProductDetailClient: React.FC = ({
product,
breadcrumbs,
- mcpName
+ mcpName,
+ url,
}) => {
const { t } = useTranslation();
@@ -30,52 +32,58 @@ export const ProductDetailClient: React.FC = ({
return (
- {product ? (<>
-
+ {product ? (
+ <>
+
-
- {/* Left side - Main content */}
-
- setActiveTab(key as string)}
- variant="underlined"
- color="primary"
- >
-
-
-
-
- {t("Tools")}
- {product.tools.length}
- }>
-
-
-
+
+ {/* Left side - Main content */}
+
+ setActiveTab(key as string)}
+ variant="underlined"
+ color="primary"
+ >
+
+
+
+
+ {t("Tools")}
+
+ {" "}
+ {product.tools.length}
+
+
+ }
+ >
+
+
+
+
+
+ {/* Right side - Server Config */}
+
- {/* Right side - Server Config */}
-
-
-
- {/* SEO-friendly: Simple text content for search engines */}
-
- >
- ) : ( )}
-
+ {/* SEO-friendly: Simple text content for search engines */}
+
+ >
+ ) : (
+
+ )}
);
};
diff --git a/frontend/src/shared/components/marketplace/ProductHeader.tsx b/frontend/src/shared/components/marketplace/ProductHeader.tsx
index 4208e31..4da53e1 100644
--- a/frontend/src/shared/components/marketplace/ProductHeader.tsx
+++ b/frontend/src/shared/components/marketplace/ProductHeader.tsx
@@ -73,7 +73,12 @@ export const ProductHeader: React.FC = ({
{product.charge_type && (
{t("Price")}:
-
+
)}
diff --git a/frontend/src/shared/components/marketplace/ServerConfig.tsx b/frontend/src/shared/components/marketplace/ServerConfig.tsx
index 43db7b1..dcc0082 100644
--- a/frontend/src/shared/components/marketplace/ServerConfig.tsx
+++ b/frontend/src/shared/components/marketplace/ServerConfig.tsx
@@ -1,29 +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 = ({ product, mcpName }) => {
-
+export const ServerConfig: React.FC = ({
+ mcpName,
+ url = process.env.NEXT_PUBLIC_MCP_URL,
+}) => {
const { t } = useTranslation();
const { handleLogin } = useAuth();
const { platformConfig } = usePlatformConfig();
- const [url, setUrl] = useState(process.env.NEXT_PUBLIC_MCP_URL || "");
- useEffect(() => {
- if (url || !product.slug_name) return
- setUrl(`${window.location.protocol}//${window.location.hostname}:8002/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 (
@@ -38,9 +57,21 @@ export const ServerConfig: React.FC = ({ product, mcpName })
{/* Code Snippet */}
-
- {platformConfig?.name} MCP
-
+
+
+ {platformConfig?.name} MCP
+
+
+
{`{
@@ -60,4 +91,4 @@ export const ServerConfig: React.FC = ({ product, mcpName })
);
-};
\ No newline at end of file
+};
diff --git a/frontend/src/shared/components/marketplace/ServiceCard.tsx b/frontend/src/shared/components/marketplace/ServiceCard.tsx
index 650c25d..bf399b7 100644
--- a/frontend/src/shared/components/marketplace/ServiceCard.tsx
+++ b/frontend/src/shared/components/marketplace/ServiceCard.tsx
@@ -17,7 +17,10 @@ export const ServiceCard: React.FC = ({ service }) => {
const { t } = useTranslation();
return (
-
+
= ({ service }) => {
{t("{{count}} Tools", { count: service.tools.length })}
-
+
diff --git a/frontend/src/shared/components/marketplace/ServiceListSection.tsx b/frontend/src/shared/components/marketplace/ServiceListSection.tsx
index 19af4b7..dbdec73 100644
--- a/frontend/src/shared/components/marketplace/ServiceListSection.tsx
+++ b/frontend/src/shared/components/marketplace/ServiceListSection.tsx
@@ -25,7 +25,7 @@ export const ServiceListSection: React.FC = ({
return (
{/* Services Grid */}
-
+
{services.map((service) => (
))}
@@ -46,4 +46,4 @@ export const ServiceListSection: React.FC = ({
)}
);
-};
\ No newline at end of file
+};
diff --git a/frontend/src/shared/components/modal/RechargeModal.tsx b/frontend/src/shared/components/modal/RechargeModal.tsx
index 085c1f2..2353375 100644
--- a/frontend/src/shared/components/modal/RechargeModal.tsx
+++ b/frontend/src/shared/components/modal/RechargeModal.tsx
@@ -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 = ({
onClose,
}) => {
const { t } = useTranslation();
+ const { paymentChannels } = usePlatformConfig();
const [amount, setAmount] = useState("");
const [error, setError] = useState("");
+ const [selectedPaymentChannel, setSelectedPaymentChannel] = useState(
+ 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 = ({
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 = ({
const handleClose = () => {
setAmount("");
setError("");
+ setSelectedPaymentChannel(paymentChannels[0]?.id || "");
onClose();
};
@@ -119,23 +133,54 @@ export const RechargeModal: React.FC = ({
}
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();
}
}}
/>
-
- {t("Funds will be added to your account balance")}
-
+ {/**coming soon : select payment channel*/}
+
+ {/* {paymentChannels.length > 0 && (
+
+
+
+ {paymentChannels.map((channel) => (
+
+ {channel.name}
+
+ ))}
+
+
+ )} */}
-
@@ -144,7 +189,6 @@ export const RechargeModal: React.FC = ({
-
{/**Confirm Purchase Modal */}
= ({
/>
>
);
-};
\ No newline at end of file
+};
diff --git a/frontend/src/shared/contexts/PlatformConfigContext.tsx b/frontend/src/shared/contexts/PlatformConfigContext.tsx
index 41181af..c2b4754 100644
--- a/frontend/src/shared/contexts/PlatformConfigContext.tsx
+++ b/frontend/src/shared/contexts/PlatformConfigContext.tsx
@@ -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 = ({
const [loginConfig, setLoginConfig] = useState(
initConfig?.login || null
);
+ const [faqItems, setFaqItems] = useState(initConfig?.faq || []);
+ const [topNavigation, setTopNavigation] = useState(
+ initConfig?.top_navigation || []
+ );
+ const [embeddedHtml, setEmbeddedHtml] = useState(
+ initConfig?.embeded_html || null
+ );
+ const [paymentChannels, setPaymentChannels] = useState(
+ initConfig?.payment_channels || []
+ );
+ const [isInstalled, setIsInstalled] = useState(
+ 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 (
{children}
diff --git a/frontend/src/shared/types/dashboard.ts b/frontend/src/shared/types/dashboard.ts
index 62ec7fc..95e687b 100644
--- a/frontend/src/shared/types/dashboard.ts
+++ b/frontend/src/shared/types/dashboard.ts
@@ -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[];
diff --git a/frontend/src/shared/types/marketplace.ts b/frontend/src/shared/types/marketplace.ts
index 5180805..b1ecffa 100644
--- a/frontend/src/shared/types/marketplace.ts
+++ b/frontend/src/shared/types/marketplace.ts
@@ -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 {
diff --git a/frontend/src/shared/types/system.ts b/frontend/src/shared/types/system.ts
index 1a9990c..3de0973 100644
--- a/frontend/src/shared/types/system.ts
+++ b/frontend/src/shared/types/system.ts
@@ -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
diff --git a/frontend/src/types/mcp-service.ts b/frontend/src/types/mcp-service.ts
index 49d56e9..dabf23e 100644
--- a/frontend/src/types/mcp-service.ts
+++ b/frontend/src/types/mcp-service.ts
@@ -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,
diff --git a/frontend/src/types/payment.ts b/frontend/src/types/payment.ts
index 6139107..4b839d9 100644
--- a/frontend/src/types/payment.ts
+++ b/frontend/src/types/payment.ts
@@ -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;
}
diff --git a/frontend/src/types/system.ts b/frontend/src/types/system.ts
index e9d61c4..76dfd5d 100644
--- a/frontend/src/types/system.ts
+++ b/frontend/src/types/system.ts
@@ -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 {
diff --git a/services/admin_service/controllers/sys_config.py b/services/admin_service/controllers/sys_config.py
index 6072d1a..d95c60a 100644
--- a/services/admin_service/controllers/sys_config.py
+++ b/services/admin_service/controllers/sys_config.py
@@ -7,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()
@@ -266,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:
diff --git a/services/admin_service/services/mcp_manager_service.py b/services/admin_service/services/mcp_manager_service.py
index 295fbac..5d3f7a8 100644
--- a/services/admin_service/services/mcp_manager_service.py
+++ b/services/admin_service/services/mcp_manager_service.py
@@ -493,7 +493,7 @@ class McpManagerService:
# Build service info
service_info = {
- "id": service.id,
+ "id": service.slug_name,
"name": service.name,
"short_description": service.short_description,
"long_description": service.long_description,
@@ -513,11 +513,15 @@ class McpManagerService:
def get_public_service_info(self, id: str) -> Optional[dict]:
"""Get public service details (only returns enabled services and APIs)"""
service = self.mcp_service_repository.get_by_id(id)
- if not service or service.enabled != 1:
+ if not service:
+ service = self.mcp_service_repository.get_by_slug_name(id)
+ if not service:
+ return None
+ if service.enabled != 1:
return None
# Get service's API list (only return enabled APIs)
- all_apis = self.mcp_tool_api_repository.get_by_service_id(id)
+ all_apis = self.mcp_tool_api_repository.get_by_service_id(service.id)
apis = [api for api in all_apis if api.enabled == 1]
# Build API info (according to API specification format)
@@ -528,7 +532,7 @@ class McpManagerService:
# Build return data (according to API specification format)
service_info = {
- "id": service.id,
+ "id": service.slug_name,
"name": service.name,
"short_description": service.short_description,
"long_description": service.long_description,
diff --git a/services/admin_service/services/platform_report_service.py b/services/admin_service/services/platform_report_service.py
new file mode 100644
index 0000000..d3753c1
--- /dev/null
+++ b/services/admin_service/services/platform_report_service.py
@@ -0,0 +1,165 @@
+"""
+Platform Report Service
+
+This service handles reporting platform information to the official XPack platform
+when is_showcased is enabled.
+"""
+
+import asyncio
+from typing import Optional, Dict, Any
+from services.common.logging_config import get_logger
+from services.common.utils.http_utils import HttpUtils
+from services.common.exceptions import ServiceUnavailableException, InternalServerException
+
+logger = get_logger(__name__)
+
+
+class PlatformReportService:
+ """Service for reporting platform information to XPack official platform"""
+
+ # Official XPack platform reporting endpoint
+ XPACK_REPORT_URL = "https://platform.xpack.ai/v1/cases/report"
+
+ def __init__(self):
+ """Initialize platform report service"""
+ self.http_utils = HttpUtils()
+
+ async def report_platform_info(self, platform_data: Dict[str, Any]) -> bool:
+ """
+ Report platform information to XPack official platform
+
+ Args:
+ platform_data: Platform configuration data containing:
+ - name: Platform name
+ - logo: Platform logo URL
+ - url: Platform URL
+ - website_title: Website title
+ - headline: Homepage headline
+ - subheadline: Homepage subheadline
+ - language: Platform language
+ - theme: Platform theme
+ - domain: Platform domain
+ - is_showcased: Whether to showcase on XPack website
+ - mcp_server_prefix: MCP server prefix
+
+ Returns:
+ bool: True if report was successful, False otherwise
+ """
+ try:
+ # Validate required fields
+ if not self._validate_platform_data(platform_data):
+ logger.warning("Platform data validation failed, skipping report")
+ return False
+
+ # Check if showcasing is enabled
+ if not platform_data.get("is_showcased", False):
+ logger.info("Platform showcasing is disabled, skipping report")
+ return True
+
+ # Prepare report payload
+ report_payload = {
+ "platform": {
+ "name": platform_data.get("name", ""),
+ "logo": platform_data.get("logo", ""),
+ "url": platform_data.get("url", ""),
+ "website_title": platform_data.get("website_title", ""),
+ "domain": platform_data.get("domain", ""),
+ "headline": platform_data.get("headline", ""),
+ "subheadline": platform_data.get("subheadline", ""),
+ "language": platform_data.get("language", ""),
+ "is_showcased": platform_data.get("is_showcased", False),
+ "mcp_server_prefix": platform_data.get("mcp_server_prefix", ""),
+ }
+ }
+
+ logger.info(f"Reporting platform information to XPack platform: {platform_data.get('name', 'Unknown')}")
+
+ # Send report to XPack platform
+ response = await self.http_utils.post_json(
+ url=self.XPACK_REPORT_URL, data=report_payload, timeout=15 # Reduced timeout to avoid blocking main operations
+ )
+
+ logger.info(f"Platform report successful: {response}")
+ return True
+
+ except ServiceUnavailableException as e:
+ logger.error(f"Failed to report platform info due to network issue: {e}")
+ return False
+ except InternalServerException as e:
+ logger.error(f"Failed to report platform info due to internal error: {e}")
+ return False
+ except Exception as e:
+ logger.error(f"Unexpected error during platform reporting: {e}")
+ return False
+
+ def _validate_platform_data(self, platform_data: Dict[str, Any]) -> bool:
+ """
+ Validate platform data before reporting
+
+ Args:
+ platform_data: Platform data to validate
+
+ Returns:
+ bool: True if data is valid, False otherwise
+ """
+ required_fields = ["name"]
+
+ for field in required_fields:
+ if not platform_data.get(field):
+ logger.warning(f"Missing required field for platform report: {field}")
+ return False
+
+ return True
+
+ def report_platform_info_sync(self, platform_data: Dict[str, Any]) -> bool:
+ """
+ Synchronous wrapper for reporting platform information
+ This method is designed to be non-blocking and fail-safe to avoid impacting main business logic.
+
+ Args:
+ platform_data: Platform configuration data
+
+ Returns:
+ bool: True if report was successful, False otherwise
+ """
+ try:
+ # Try to get the current event loop
+ try:
+ loop = asyncio.get_running_loop()
+ # If we're already in an event loop, use asyncio.create_task
+ import concurrent.futures
+
+ with concurrent.futures.ThreadPoolExecutor() as executor:
+ future = executor.submit(asyncio.run, self.report_platform_info(platform_data))
+ # Reduced timeout to avoid blocking main operations
+ return future.result(timeout=30)
+ except RuntimeError:
+ # No event loop running, create a new one
+ return asyncio.run(self.report_platform_info(platform_data))
+ except Exception as e:
+ # Log error but don't propagate to avoid affecting main business logic
+ logger.warning(f"Platform reporting failed but continuing with main operation: {e}")
+ return False
+
+ def report_platform_info_background(self, platform_data: Dict[str, Any]) -> None:
+ """
+ Background reporting method that runs asynchronously without blocking main operations.
+ This method is fire-and-forget style to ensure zero impact on main business logic.
+
+ Args:
+ platform_data: Platform configuration data
+ """
+ import threading
+
+ def _background_report():
+ try:
+ # Use a shorter timeout for background operations
+ self.report_platform_info_sync(platform_data)
+ except Exception as e:
+ # Silently handle any exceptions to avoid affecting main operations
+ logger.debug(f"Background platform reporting completed with issues: {e}")
+
+ # Start reporting in background thread
+ thread = threading.Thread(target=_background_report, daemon=True)
+ thread.start()
+ logger.debug("Platform reporting started in background thread")