Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
721a2be32b | ||
|
|
1fbb6711f2 | ||
|
|
d18adf035b |
No files matched your search
@@ -42,3 +42,6 @@ local_settings.py
|
||||
/.secrets
|
||||
/uploads/
|
||||
/.vercel/
|
||||
|
||||
# Local deployment data
|
||||
mysql-data/
|
||||
@@ -0,0 +1,68 @@
|
||||
version: '3'
|
||||
services:
|
||||
xpack-mysql:
|
||||
image: mysql:8.0.37
|
||||
privileged: true
|
||||
restart: always
|
||||
container_name: xpack-mysql
|
||||
hostname: xpack-mysql
|
||||
command:
|
||||
- "--character-set-server=utf8mb4"
|
||||
- "--collation-server=utf8mb4_unicode_ci"
|
||||
ports:
|
||||
- "33306:3306"
|
||||
environment:
|
||||
- MYSQL_ROOT_PASSWORD=mysql_ZTdhRB
|
||||
- MYSQL_DATABASE=xpack
|
||||
volumes:
|
||||
- /vol3/1000/HD3/docker/xpack-mcp/mysql-data:/var/lib/mysql
|
||||
networks:
|
||||
- xpack
|
||||
xpack-mcp-market:
|
||||
image: xpackai/xpack-mcp-market:zhcn
|
||||
container_name: xpack-mcp-market
|
||||
privileged: true
|
||||
restart: always
|
||||
environment:
|
||||
# AES-256-GCM key protecting payment channel config (epay merchant key, stripe secret).
|
||||
# Lives here rather than in the image so the sample key shipped in .env.example
|
||||
# can never decrypt this deployment's config.
|
||||
- PAYMENT_CONFIG_SECRET_KEY=${PAYMENT_CONFIG_SECRET_KEY:?PAYMENT_CONFIG_SECRET_KEY not set - copy .env.example to .env}
|
||||
- PAYMENT_CONFIG_KEY_ID=default
|
||||
networks:
|
||||
- xpack
|
||||
ports:
|
||||
- "8010:80"
|
||||
depends_on:
|
||||
- xpack-mysql
|
||||
- xpack-redis
|
||||
- xpack-rabbitmq
|
||||
xpack-redis:
|
||||
container_name: xpack-redis
|
||||
image: redis:7.2.4
|
||||
hostname: xpack-redis
|
||||
privileged: true
|
||||
restart: always
|
||||
command:
|
||||
- bash
|
||||
- -c
|
||||
- "redis-server --protected-mode yes --logfile redis.log --appendonly no --port 6379 --requirepass redis_6sJZDm"
|
||||
networks:
|
||||
- xpack
|
||||
xpack-rabbitmq:
|
||||
container_name: xpack-rabbitmq
|
||||
image: rabbitmq:4.1.2-alpine
|
||||
privileged: true
|
||||
restart: always
|
||||
environment:
|
||||
- RABBITMQ_DEFAULT_USER=rabbitmq
|
||||
- RABBITMQ_DEFAULT_PASS=rabbitmq_Gs123dA
|
||||
networks:
|
||||
- xpack
|
||||
networks:
|
||||
xpack:
|
||||
driver: bridge
|
||||
ipam:
|
||||
driver: default
|
||||
config:
|
||||
- subnet: 172.101.0.0/24
|
||||
@@ -483,7 +483,6 @@
|
||||
"Enter server ID": "Enter server ID",
|
||||
"Modifying the ID will affect the MCP access URL. Please modify with caution.": "Modifying the ID will affect the MCP access URL. Please modify with caution.",
|
||||
"You have modified the Server ID. This will affect the MCP access URL and may break existing integrations. Are you sure you want to continue?": "You have modified the Server ID. This will affect the MCP access URL and may break existing integrations. Are you sure you want to continue?",
|
||||
|
||||
"The header name for the API key (e.g., X-API-Key, Authorization)": "The header name for the API key (e.g., X-API-Key, Authorization)",
|
||||
"Enter API key": "Enter API key",
|
||||
"Enter bearer token": "Enter bearer token",
|
||||
@@ -891,5 +890,17 @@
|
||||
"Auth key name \"{{name}}\" already exists": "Auth key name \"{{name}}\" already exists",
|
||||
"Start date must be before end date": "Start date must be before end date",
|
||||
"Start date cannot be earlier than 30 days ago": "Start date cannot be earlier than 30 days ago",
|
||||
"Resource Groups": "Resource Groups"
|
||||
}
|
||||
"Resource Groups": "Resource Groups",
|
||||
"Daily call limit per user": "Daily call limit per user",
|
||||
"Max calls per user per day (Beijing time). Leave blank or 0 for unlimited": "Max calls per user per day (Beijing time). Leave blank or 0 for unlimited",
|
||||
"e.g. 50": "e.g. 50",
|
||||
"Free Call Limits": "Free Call Limits",
|
||||
"Global daily call cap for free services": "Global daily call cap for free services",
|
||||
"Platform-wide daily call limit per user": "Platform-wide daily call limit per user",
|
||||
"Applies to every free service, leave blank or 0 for unlimited": "Applies to every free service, leave blank or 0 for unlimited",
|
||||
"If a service also has its own limit, the smaller number wins": "If a service also has its own limit, the smaller number wins",
|
||||
"Example 100": "Example 100",
|
||||
"Enter a non-negative integer": "Enter a non-negative integer",
|
||||
"Free call limit saved": "Free call limit saved",
|
||||
"Failed to save free call limit": "Failed to save free call limit"
|
||||
}
|
||||
@@ -485,7 +485,6 @@
|
||||
"Enter server ID": "输入服务器ID",
|
||||
"Modifying the ID will affect the MCP access URL. Please modify with caution.": "修改ID会影响MCP的访问地址,需要谨慎修改。",
|
||||
"You have modified the Server ID. This will affect the MCP access URL and may break existing integrations. Are you sure you want to continue?": "您已修改了服务器ID。这将影响MCP访问地址,可能会破坏现有的集成。您确定要继续吗?",
|
||||
|
||||
"The header name for the API key (e.g., X-API-Key, Authorization)": "API密钥的头部名称(例如:X-API-Key, Authorization)",
|
||||
"Enter API key": "输入API密钥",
|
||||
"Enter bearer token": "输入Bearer令牌",
|
||||
@@ -957,5 +956,17 @@
|
||||
"Resource group name \"{{name}}\" already exists": "资源组名称 \"{{name}}\" 已存在",
|
||||
"Auth key name \"{{name}}\" already exists": "认证密钥 \"{{name}}\" 已存在",
|
||||
"Start date must be before end date": "开始日期必须早于结束日期",
|
||||
"Start date cannot be earlier than 30 days ago": "开始日期不能早于30天前"
|
||||
}
|
||||
"Start date cannot be earlier than 30 days ago": "开始日期不能早于30天前",
|
||||
"Daily call limit per user": "每用户每日调用上限",
|
||||
"Max calls per user per day (Beijing time). Leave blank or 0 for unlimited": "每个用户每天最多调用次数(北京时间)。留空或填 0 表示不限",
|
||||
"e.g. 50": "如 50",
|
||||
"Free Call Limits": "免费调用限制",
|
||||
"Global daily call cap for free services": "免费服务的全局每日调用上限",
|
||||
"Platform-wide daily call limit per user": "全站每用户每日调用上限",
|
||||
"Applies to every free service, leave blank or 0 for unlimited": "对所有免费服务生效,留空或填 0 表示不限",
|
||||
"If a service also has its own limit, the smaller number wins": "若单个服务也设置了上限,两者取更小值",
|
||||
"Example 100": "如 100",
|
||||
"Enter a non-negative integer": "请输入非负整数",
|
||||
"Free call limit saved": "免费调用上限已保存",
|
||||
"Failed to save free call limit": "保存免费调用上限失败"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
"use client";
|
||||
import React from "react";
|
||||
import { SubmissionsManagement } from "@/components/console/SubmissionsManagement";
|
||||
|
||||
export default function AdminSubmissionsPage() {
|
||||
return <SubmissionsManagement />;
|
||||
}
|
||||
@@ -27,12 +27,12 @@ export default async function RootLayout({
|
||||
const platformConfig = await getCachedPlatformConfig();
|
||||
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning data-color-mode="light">
|
||||
<html lang="zh-CN" suppressHydrationWarning data-color-mode="light">
|
||||
<head>
|
||||
<script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `
|
||||
window.localStorage.setItem("i18nextLng", "${platformConfig?.platform?.language || "en"}");
|
||||
window.localStorage.setItem("i18nextLng", "${platformConfig?.platform?.language || "zh-CN"}");
|
||||
`,
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
"use client";
|
||||
import React, { useState } from "react";
|
||||
import { fetchAPI } from "@/shared/rpc/common-function";
|
||||
|
||||
type SubType = "mcp" | "skill" | "plugin";
|
||||
|
||||
export default function SubmitPage() {
|
||||
const [type, setType] = useState<SubType>("mcp");
|
||||
const [name, setName] = useState("");
|
||||
const [desc, setDesc] = useState("");
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [baseUrl, setBaseUrl] = useState("");
|
||||
const [serviceType, setServiceType] = useState("openapi");
|
||||
const [tags, setTags] = useState("");
|
||||
const [chargeType, setChargeType] = useState<"free" | "paid">("free");
|
||||
const [price, setPrice] = useState("");
|
||||
const [freeDailyLimit, setFreeDailyLimit] = useState("");
|
||||
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setMsg(null);
|
||||
|
||||
if (typeof window !== "undefined" && !localStorage.getItem("user_token")) {
|
||||
setMsg({ ok: false, text: "请先登录后再提交(右上角登录)" });
|
||||
return;
|
||||
}
|
||||
if (type === "mcp" && !baseUrl.trim()) {
|
||||
setMsg({ ok: false, text: "MCP 服务必须填写服务地址 base_url" });
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append("type", type);
|
||||
fd.append("name", name);
|
||||
if (desc) fd.append("description", desc);
|
||||
if (file) fd.append("file", file);
|
||||
if (type === "mcp") {
|
||||
fd.append("base_url", baseUrl.trim());
|
||||
fd.append("service_type", serviceType);
|
||||
if (tags.trim()) fd.append("tags", tags.trim());
|
||||
fd.append("charge_type", chargeType);
|
||||
if (chargeType === "paid" && price) fd.append("price", price);
|
||||
if (chargeType === "free" && freeDailyLimit) fd.append("free_daily_limit", freeDailyLimit);
|
||||
}
|
||||
|
||||
const data = await fetchAPI<{ success: boolean; error_message?: string; data?: { id: string; status: string } }>(
|
||||
"/api/submission/submission",
|
||||
{ method: "POST", body: fd }
|
||||
);
|
||||
if (data?.success) {
|
||||
setMsg({ ok: true, text: "提交成功,等待管理员审核。审核通过后将自动上架到市场。" });
|
||||
setName(""); setDesc(""); setFile(null); setBaseUrl(""); setTags("");
|
||||
} else {
|
||||
setMsg({ ok: false, text: data?.error_message || "提交失败,请稍后重试" });
|
||||
}
|
||||
} catch (err) {
|
||||
setMsg({ ok: false, text: "提交失败:" + (err as Error).message });
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const inputCls = "border p-2 w-full rounded";
|
||||
|
||||
return (
|
||||
<div className="max-w-xl mx-auto p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h1 className="text-2xl font-bold">上传 MCP / Skill / Plugin</h1>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<select value={type} onChange={(e) => setType(e.target.value as SubType)} className={inputCls}>
|
||||
<option value="mcp">MCP 服务</option>
|
||||
<option value="skill">AI 技能</option>
|
||||
<option value="plugin">AI 插件</option>
|
||||
</select>
|
||||
|
||||
<input value={name} onChange={(e) => setName(e.target.value)} placeholder="名称" className={inputCls} required />
|
||||
<textarea value={desc} onChange={(e) => setDesc(e.target.value)} placeholder="描述" className={inputCls} rows={3} />
|
||||
|
||||
{type === "mcp" && (
|
||||
<div className="space-y-3 border rounded p-3 bg-gray-50">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">服务地址 base_url *</label>
|
||||
<input
|
||||
value={baseUrl}
|
||||
onChange={(e) => setBaseUrl(e.target.value)}
|
||||
placeholder="http://192.168.1.10:8020"
|
||||
className={inputCls}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">服务类型</label>
|
||||
<select value={serviceType} onChange={(e) => setServiceType(e.target.value)} className={inputCls}>
|
||||
<option value="openapi">openapi(HTTP 接口)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">标签(逗号分隔)</label>
|
||||
<input value={tags} onChange={(e) => setTags(e.target.value)} placeholder="工具, 搜索, 免费" className={inputCls} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">计费方式</label>
|
||||
<select
|
||||
value={chargeType}
|
||||
onChange={(e) => setChargeType(e.target.value as "free" | "paid")}
|
||||
className={inputCls}
|
||||
>
|
||||
<option value="free">免费</option>
|
||||
<option value="paid">按次付费</option>
|
||||
</select>
|
||||
</div>
|
||||
{chargeType === "paid" ? (
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">单价(元/次)</label>
|
||||
<input
|
||||
type="number" step="0.01" min="0"
|
||||
value={price}
|
||||
onChange={(e) => setPrice(e.target.value)}
|
||||
placeholder="0.10"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">每日免费次数(留空 = 不限)</label>
|
||||
<input
|
||||
type="number" min="1"
|
||||
value={freeDailyLimit}
|
||||
onChange={(e) => setFreeDailyLimit(e.target.value)}
|
||||
placeholder="100"
|
||||
className={inputCls}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">
|
||||
OpenAPI 规范文件(.json,用于自动生成工具列表)
|
||||
</label>
|
||||
<input type="file" onChange={(e) => setFile(e.target.files?.[0] || null)} className={inputCls} />
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
上传后审核通过会自动生成工具;不上传则上架后需在服务管理里手动添加工具。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{type !== "mcp" && (
|
||||
<input type="file" onChange={(e) => setFile(e.target.files?.[0] || null)} className={inputCls} />
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting}
|
||||
className="bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-50"
|
||||
>
|
||||
{submitting ? "提交中..." : "提交"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{msg && (
|
||||
<pre className={`mt-4 text-sm whitespace-pre-wrap ${msg.ok ? "text-green-700" : "text-red-600"}`}>
|
||||
{msg.text}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import UserManagement from "@/components/user-management/UserManagement";
|
||||
import RevenueManagement from "@/components/revenue-management/RevenueManagement";
|
||||
import ConsoleSidebar from "./Sidebar";
|
||||
import { withComponentInjection } from "@/shared/hooks/useComponentInjection";
|
||||
import { Boxes, DollarSign, Home, ServerIcon, Users } from "lucide-react";
|
||||
import { Boxes, DollarSign, Home, Inbox, ServerIcon, Users } from "lucide-react";
|
||||
import OnboardingWelcome, { REQUIRED_TASK_KEYS } from "./OnboardingWelcome";
|
||||
import ConsoleStats from "./ConsoleStats";
|
||||
import SystemSettingsModal from "./SystemSettingsModal";
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
updateAdminOnboardingTasks,
|
||||
} from "@/api/onboard.api";
|
||||
import ResourceGroupManagement from "../resource-group/resourceGroup";
|
||||
import { SubmissionsManagement } from "./SubmissionsManagement";
|
||||
|
||||
const ConsoleContent: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
@@ -37,9 +38,13 @@ const ConsoleContent: React.FC = () => {
|
||||
const tabFromUrl = searchParams.get("tab") as TabKey;
|
||||
if (
|
||||
tabFromUrl &&
|
||||
["mcp-services", "user-management", "revenue-management", "resource-group"].includes(
|
||||
tabFromUrl
|
||||
)
|
||||
[
|
||||
"mcp-services",
|
||||
"user-management",
|
||||
"revenue-management",
|
||||
"resource-group",
|
||||
"submissions",
|
||||
].includes(tabFromUrl)
|
||||
) {
|
||||
return tabFromUrl;
|
||||
}
|
||||
@@ -69,6 +74,12 @@ const ConsoleContent: React.FC = () => {
|
||||
label: t("MCP"),
|
||||
description: t("Manage MCP servers and API tools"),
|
||||
},
|
||||
{
|
||||
key: TabKey.SUBMISSIONS,
|
||||
icon: <Inbox size={18} />,
|
||||
label: t("Submissions"),
|
||||
description: t("Review user submissions and publish to marketplace"),
|
||||
},
|
||||
{
|
||||
key: TabKey.USER_MANAGEMENT,
|
||||
icon: <Users size={18} />,
|
||||
@@ -213,6 +224,12 @@ const ConsoleContent: React.FC = () => {
|
||||
switch (activeTab) {
|
||||
case TabKey.MCP_SERVICES:
|
||||
return <MCPServicesManagement />;
|
||||
case TabKey.SUBMISSIONS:
|
||||
return (
|
||||
<div className="h-full overflow-auto">
|
||||
<SubmissionsManagement />
|
||||
</div>
|
||||
);
|
||||
case TabKey.USER_MANAGEMENT:
|
||||
return (
|
||||
<div className="h-full overflow-auto">
|
||||
|
||||
@@ -4,6 +4,7 @@ import React from "react";
|
||||
import { StripeConfigForm } from "../payment/StripeConfigForm";
|
||||
import { AlipayConfigForm } from "../payment/AlipayConfigForm";
|
||||
import { WechatConfigForm } from "../payment/WechatConfigForm";
|
||||
import { EpayConfigForm } from "../payment/EpayConfigForm";
|
||||
import { usePaymentChannelManagement } from "@/hooks/usePaymentChannelManagement";
|
||||
|
||||
interface PaymentChannelsContentProps {
|
||||
@@ -17,12 +18,15 @@ export const PaymentChannelsContent: React.FC<PaymentChannelsContentProps> = ({
|
||||
stripeConfig,
|
||||
alipayConfig,
|
||||
wechatConfig,
|
||||
epayConfig,
|
||||
isWechatSaving,
|
||||
isStripeSaving,
|
||||
isAlipaySaving,
|
||||
isEpaySaving,
|
||||
saveStripeConfig,
|
||||
saveAlipayConfig,
|
||||
saveWechatConfig,
|
||||
saveEpayConfig,
|
||||
enableChannel,
|
||||
disableChannel,
|
||||
} = usePaymentChannelManagement();
|
||||
@@ -38,6 +42,15 @@ export const PaymentChannelsContent: React.FC<PaymentChannelsContentProps> = ({
|
||||
isLoading={isStripeSaving}
|
||||
labelPlacement={labelPlacement}
|
||||
/>
|
||||
{/* epay (易支付) configuration */}
|
||||
<EpayConfigForm
|
||||
config={epayConfig}
|
||||
onSave={saveEpayConfig}
|
||||
onEnable={enableChannel}
|
||||
onDisable={disableChannel}
|
||||
isLoading={isEpaySaving}
|
||||
labelPlacement={labelPlacement}
|
||||
/>
|
||||
{/* coming soon */}
|
||||
{/* alipay configuration */}
|
||||
{/* <AlipayConfigForm
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
"use client";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { fetchAdminAPI } from "@/rpc/admin-api";
|
||||
|
||||
interface Metadata {
|
||||
base_url?: string;
|
||||
service_type?: string;
|
||||
tags?: string;
|
||||
charge_type?: string;
|
||||
price?: number;
|
||||
free_daily_limit?: number | null;
|
||||
published_service_id?: string;
|
||||
}
|
||||
|
||||
interface Submission {
|
||||
id: string;
|
||||
user_id: string;
|
||||
type: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
file_path?: string;
|
||||
metadata_json?: Metadata | null;
|
||||
status: string;
|
||||
created_at?: string;
|
||||
review_note?: string;
|
||||
}
|
||||
|
||||
const statusColor: Record<string, string> = {
|
||||
pending: "bg-yellow-100 text-yellow-800",
|
||||
approved: "bg-green-100 text-green-800",
|
||||
rejected: "bg-red-100 text-red-800",
|
||||
};
|
||||
|
||||
export function SubmissionsManagement() {
|
||||
const [subs, setSubs] = useState<Submission[]>([]);
|
||||
const [filter, setFilter] = useState<string>("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [rejectNote, setRejectNote] = useState<Record<string, string>>({});
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const qs = filter ? `?status=${filter}` : "";
|
||||
// fetchAdminAPI<T> already returns the { success, error_message, data } envelope
|
||||
const response = await fetchAdminAPI<Submission[]>(
|
||||
`/api/submission/admin/submissions${qs}`
|
||||
);
|
||||
if (response?.success === false) {
|
||||
setError(response.error_message || "加载失败");
|
||||
setSubs([]);
|
||||
} else if (response?.data) {
|
||||
setSubs(response.data);
|
||||
} else {
|
||||
setSubs([]);
|
||||
}
|
||||
} catch (err) {
|
||||
setError("加载失败:" + (err as Error).message);
|
||||
setSubs([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => { load(); }, [filter]);
|
||||
|
||||
const act = async (id: string, action: "approve" | "reject") => {
|
||||
const body: RequestInit =
|
||||
action === "approve"
|
||||
? { method: "PUT" }
|
||||
: {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ note: rejectNote[id] || "" }),
|
||||
};
|
||||
await fetchAdminAPI(`/api/submission/admin/submission/${id}/${action}`, body);
|
||||
load();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h1 className="text-2xl font-bold">投稿审核</h1>
|
||||
<select value={filter} onChange={(e) => setFilter(e.target.value)} className="border p-2">
|
||||
<option value="">全部</option>
|
||||
<option value="pending">待审核</option>
|
||||
<option value="approved">已通过</option>
|
||||
<option value="rejected">已拒绝</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{error && <div className="mb-4 p-3 bg-red-50 text-red-700 rounded">{error}</div>}
|
||||
{loading && <div className="mb-4 text-gray-500">加载中...</div>}
|
||||
{!loading && !error && subs.length === 0 && (
|
||||
<div className="mb-4 text-gray-500">暂无提交记录</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{subs.map((s) => {
|
||||
const meta = s.metadata_json || {};
|
||||
return (
|
||||
<div key={s.id} className="border rounded p-4 space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-semibold">{s.name}</span>
|
||||
<span className="px-2 py-0.5 rounded text-xs">{s.type}</span>
|
||||
<span className={`px-2 py-0.5 rounded text-xs ${statusColor[s.status] || "bg-gray-100"}`}>{s.status}</span>
|
||||
</div>
|
||||
<span className="text-sm text-gray-500">{s.created_at?.slice(0, 19).replace("T", " ")}</span>
|
||||
</div>
|
||||
|
||||
{s.description && <p className="text-sm text-gray-700">{s.description}</p>}
|
||||
|
||||
{s.type === "mcp" && (meta.base_url || meta.tags || meta.charge_type) && (
|
||||
<div className="text-sm text-gray-600 bg-gray-50 rounded p-2 space-y-1">
|
||||
{meta.base_url && <div>服务地址:<code className="text-xs">{meta.base_url}</code></div>}
|
||||
{meta.tags && <div>标签:{meta.tags}</div>}
|
||||
<div>
|
||||
计费:
|
||||
{meta.charge_type === "paid"
|
||||
? `按次付费 ¥${meta.price ?? 0}/次`
|
||||
: `免费${meta.free_daily_limit ? `(每日 ${meta.free_daily_limit} 次)` : "(不限次)"}`}
|
||||
</div>
|
||||
{meta.published_service_id && (
|
||||
<div className="text-green-700">
|
||||
已上架市场,服务 ID:<code className="text-xs">{meta.published_service_id}</code>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{s.file_path && (
|
||||
<div className="text-sm text-gray-500">
|
||||
附件:<code className="text-xs">{s.file_path}</code>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{s.review_note && (
|
||||
<div className="text-sm text-gray-600">审核备注:{s.review_note}</div>
|
||||
)}
|
||||
|
||||
{s.status === "pending" ? (
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
value={rejectNote[s.id] || ""}
|
||||
onChange={(e) => setRejectNote({ ...rejectNote, [s.id]: e.target.value })}
|
||||
placeholder="拒绝原因(可选)"
|
||||
className="border p-2 w-full text-sm"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => act(s.id, "approve")}
|
||||
className="bg-green-600 text-white px-3 py-1 rounded text-sm"
|
||||
>
|
||||
通过(自动上架)
|
||||
</button>
|
||||
<button
|
||||
onClick={() => act(s.id, "reject")}
|
||||
className="bg-red-600 text-white px-3 py-1 rounded text-sm"
|
||||
>
|
||||
拒绝
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
Captions,
|
||||
Code,
|
||||
CreditCard,
|
||||
Gauge,
|
||||
GhostIcon,
|
||||
GlobeIcon,
|
||||
LockIcon,
|
||||
@@ -181,6 +182,12 @@ const SystemSettingsModal: React.FC<SystemSettingsModalProps> = ({
|
||||
icon: <CreditCard size={16} />,
|
||||
description: "Configure payment channels",
|
||||
},
|
||||
{
|
||||
key: SettingModalTab.FREE_QUOTA,
|
||||
label: "Free Call Limits",
|
||||
icon: <Gauge size={16} />,
|
||||
description: "Global daily call cap for free services",
|
||||
},
|
||||
{
|
||||
key: SettingModalTab.XPACK_EXPLORE,
|
||||
label: "XPack Explore",
|
||||
@@ -256,6 +263,7 @@ const SystemSettingsModal: React.FC<SystemSettingsModalProps> = ({
|
||||
title: "Business",
|
||||
items: groupItems([
|
||||
SettingModalTab.PAYMENT,
|
||||
SettingModalTab.FREE_QUOTA,
|
||||
SettingModalTab.XPACK_EXPLORE,
|
||||
]),
|
||||
},
|
||||
|
||||
@@ -31,6 +31,7 @@ import { AdminConfig, EmailConfig } from "@/types/system";
|
||||
import { LoginSettingsContent } from "./LoginSettingsContent";
|
||||
import { EmailConfigForm } from "@/components/system-setting/EmailConfigForm";
|
||||
import { LanguageSetting } from "@/components/system-setting/LanguageSetting";
|
||||
import { FreeQuotaSettings } from "@/components/system-setting/FreeQuotaSettings";
|
||||
import { TagsBarSetting } from "../system-setting/TagsBarSetting";
|
||||
|
||||
interface SystemSettingsRightContentProps {
|
||||
@@ -221,6 +222,8 @@ const SystemSettingsRightContent: React.FC<SystemSettingsRightContentProps> = ({
|
||||
<PaymentChannelsContent labelPlacement="outside" />
|
||||
)}
|
||||
|
||||
{section.key === "free-quota" && <FreeQuotaSettings />}
|
||||
|
||||
{section.key === "xpack-explore" && (
|
||||
<ExplorePanel
|
||||
isEnabled={!!platformConfig.is_showcased}
|
||||
|
||||
@@ -5,6 +5,7 @@ export enum SettingModalTab {
|
||||
BRANDING = "branding",
|
||||
THEME = "theme",
|
||||
PAYMENT = "payment",
|
||||
FREE_QUOTA = "free-quota",
|
||||
CODE_INJECTION = "code-injection",
|
||||
XPACK_EXPLORE = "xpack-explore",
|
||||
NAVIGATION = "navigation",
|
||||
|
||||
@@ -30,6 +30,7 @@ const _DefaultFormData: MCPServiceFormData = {
|
||||
auth_token: "",
|
||||
charge_type: ChargeType.Free,
|
||||
price: "",
|
||||
free_daily_limit: "",
|
||||
enabled: 0,
|
||||
tags: [],
|
||||
apis: [],
|
||||
@@ -46,12 +47,18 @@ const isValidUrl = (url: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
// Helper function to validate domain format
|
||||
// Helper function to validate domain format (allow domain or IP address including LAN IPs)
|
||||
const isValidDomain = (url: string) => {
|
||||
if (!url) return false;
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const hostname = parsed.hostname;
|
||||
// Allow IPv4 addresses (including private/lan IPs like 192.168.x.x, 10.x.x.x, 172.x.x.x)
|
||||
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
|
||||
if (ipv4Regex.test(hostname)) return true;
|
||||
// Allow IPv6 (simplified)
|
||||
if (hostname.includes(":")) return true;
|
||||
// Domain format
|
||||
const domainRegex = /^(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,})$/;
|
||||
return domainRegex.test(hostname);
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
"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 { EpayChannelConfig } from "@/types/payment";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
|
||||
interface EpayConfigFormProps {
|
||||
config: EpayChannelConfig;
|
||||
onSave: (config: EpayChannelConfig) => void;
|
||||
onEnable: (channelId: string) => Promise<boolean>;
|
||||
onDisable: (channelId: string) => Promise<boolean>;
|
||||
isLoading?: boolean;
|
||||
labelPlacement?: "outside" | "inside";
|
||||
}
|
||||
|
||||
export const EpayConfigForm: React.FC<EpayConfigFormProps> = ({
|
||||
config,
|
||||
onSave,
|
||||
onEnable,
|
||||
onDisable,
|
||||
isLoading = false,
|
||||
labelPlacement = "inside",
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [formData, setFormData] = useState<EpayChannelConfig>(config);
|
||||
const [showKey, setShowKey] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setFormData(config);
|
||||
}, [config]);
|
||||
|
||||
const handleInputChange = (field: keyof EpayChannelConfig, value: string | boolean) => {
|
||||
setFormData((prev) => ({ ...prev, [field]: value }));
|
||||
};
|
||||
|
||||
const handleEnableDisable = async (value: boolean) => {
|
||||
const result = value ? await onEnable("epay") : await onDisable("epay");
|
||||
if (result) {
|
||||
setFormData((prev) => ({ ...prev, is_enabled: value }));
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = () => onSave(formData);
|
||||
|
||||
const isFormValid =
|
||||
!!formData?.gateway?.trim() && !!formData?.pid?.trim() && !!formData?.key?.trim();
|
||||
|
||||
const panelContent = () => (
|
||||
<>
|
||||
<div className={`flex flex-col gap-4 ${formData.is_enabled ? "" : "hidden"}`}>
|
||||
<Input
|
||||
label={t("Gateway URL")}
|
||||
placeholder="https://pay.example.com"
|
||||
description={t("Epay gateway base address, no trailing slash")}
|
||||
value={formData.gateway || ""}
|
||||
onChange={(e) => handleInputChange("gateway", e.target.value)}
|
||||
isRequired
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
labelPlacement="outside"
|
||||
/>
|
||||
|
||||
<Input
|
||||
label={t("Merchant ID (pid)")}
|
||||
placeholder={t("Enter Merchant ID")}
|
||||
description={t("Numeric merchant id issued by the epay platform")}
|
||||
value={formData.pid || ""}
|
||||
onChange={(e) => handleInputChange("pid", e.target.value)}
|
||||
isRequired
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
labelPlacement="outside"
|
||||
/>
|
||||
|
||||
<Input
|
||||
label={t("Merchant Key (key)")}
|
||||
placeholder={t("Enter Merchant Key")}
|
||||
description={t("Used to sign requests and verify notifications, 32 characters")}
|
||||
value={formData.key || ""}
|
||||
onChange={(e) => handleInputChange("key", e.target.value)}
|
||||
type={showKey ? "text" : "password"}
|
||||
isRequired
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
labelPlacement="outside"
|
||||
endContent={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowKey(!showKey)}
|
||||
className="focus:outline-none"
|
||||
>
|
||||
{showKey ? (
|
||||
<EyeOff className="w-4 h-4 text-gray-400" />
|
||||
) : (
|
||||
<Eye className="w-4 h-4 text-gray-400" />
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-sm font-medium">{t("Payment Method")}</label>
|
||||
<select
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-primary-500 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
value={formData.pay_type || ""}
|
||||
disabled={!formData.is_enabled}
|
||||
onChange={(e) => handleInputChange("pay_type", e.target.value)}
|
||||
>
|
||||
<option value="">{t("Let customer choose at checkout")}</option>
|
||||
<option value="alipay">{t("Alipay")}</option>
|
||||
<option value="wxpay">{t("WeChat Pay")}</option>
|
||||
<option value="qqpay">{t("QQ Wallet")}</option>
|
||||
</select>
|
||||
<span className="text-xs text-gray-500">
|
||||
{t("Leave empty to show the gateway cashier with all methods")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<Input
|
||||
label={t("Exchange Rate")}
|
||||
placeholder="1"
|
||||
description={t(
|
||||
"CNY charged per 1 balance unit. Default 1 means 1:1. e.g. 7 means a $10 recharge bills ¥70"
|
||||
)}
|
||||
value={String(formData.exchange_rate ?? 1)}
|
||||
onChange={(e) => handleInputChange("exchange_rate", e.target.value)}
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
labelPlacement="outside"
|
||||
/>
|
||||
|
||||
<Input
|
||||
label={t("Notify URL (optional)")}
|
||||
placeholder={t("Auto derived from the site URL when empty")}
|
||||
description={t(
|
||||
"Async payment notification address that the gateway can reach from the internet"
|
||||
)}
|
||||
value={formData.notify_url || ""}
|
||||
onChange={(e) => handleInputChange("notify_url", e.target.value)}
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
labelPlacement="outside"
|
||||
/>
|
||||
|
||||
<Input
|
||||
label={t("Return URL (optional)")}
|
||||
placeholder={t("Auto derived when empty")}
|
||||
description={t("Page opened after the customer finishes paying")}
|
||||
value={formData.return_url || ""}
|
||||
onChange={(e) => handleInputChange("return_url", e.target.value)}
|
||||
autoComplete="off"
|
||||
isDisabled={!formData.is_enabled}
|
||||
labelPlacement="outside"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
if (labelPlacement === "outside") {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<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 Epay Payment")}</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{t("Alipay / WeChat Pay through your own epay gateway")}
|
||||
</span>
|
||||
</div>
|
||||
<Switch
|
||||
isSelected={formData.is_enabled || false}
|
||||
onValueChange={handleEnableDisable}
|
||||
color="primary"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
{panelContent()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Accordion
|
||||
variant="splitted"
|
||||
itemClasses={{ base: "shadow-none border-1" }}
|
||||
defaultExpandedKeys={["epay-config"]}
|
||||
className="px-0"
|
||||
>
|
||||
<AccordionItem
|
||||
key="epay-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("Epay Configuration")}</h3>
|
||||
<p className="text-sm text-gray-500">
|
||||
{t("Configure your epay (Epay) gateway")}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
isSelected={formData.is_enabled || false}
|
||||
onValueChange={handleEnableDisable}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{panelContent()}
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
|
||||
export default EpayConfigForm;
|
||||
@@ -0,0 +1,111 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Button, Input } from "@nextui-org/react";
|
||||
import { fetchAdminAPI } from "@/rpc/admin-api";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
interface FreeQuotaResponse {
|
||||
free_global_daily_limit: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Platform-wide daily call cap for free services.
|
||||
*
|
||||
* Stored in sys_config under free_global_daily_limit. The billing service takes
|
||||
* the smaller of this value and any per-service limit, so a service with no
|
||||
* limit of its own still inherits this one.
|
||||
*/
|
||||
export const FreeQuotaSettings: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
const [value, setValue] = useState<string>("");
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [saving, setSaving] = useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
(async () => {
|
||||
const res = await fetchAdminAPI<FreeQuotaResponse>(
|
||||
"/api/sysconfig/free-quota",
|
||||
{ method: "GET" }
|
||||
);
|
||||
if (!mounted) return;
|
||||
if (res.success) {
|
||||
const n = res.data?.free_global_daily_limit;
|
||||
setValue(n && n > 0 ? String(n) : "");
|
||||
} else if (res.error_message) {
|
||||
toast.error(res.error_message);
|
||||
}
|
||||
setLoading(false);
|
||||
})();
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleSave = async () => {
|
||||
const raw = value.trim();
|
||||
let payload: number | null = null;
|
||||
if (raw !== "") {
|
||||
const n = Number(raw);
|
||||
if (!Number.isInteger(n) || n < 0) {
|
||||
toast.error(t("Enter a non-negative integer"));
|
||||
return;
|
||||
}
|
||||
payload = n;
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
const res = await fetchAdminAPI<FreeQuotaResponse>(
|
||||
"/api/sysconfig/free-quota",
|
||||
{ method: "PUT", body: { free_global_daily_limit: payload } as unknown as BodyInit }
|
||||
);
|
||||
setSaving(false);
|
||||
|
||||
if (res.success) {
|
||||
const n = res.data?.free_global_daily_limit;
|
||||
setValue(n && n > 0 ? String(n) : "");
|
||||
toast.success(t("Free call limit saved"));
|
||||
} else {
|
||||
toast.error(res.error_message || t("Failed to save free call limit"));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
step={1}
|
||||
labelPlacement="outside"
|
||||
label={t("Platform-wide daily call limit per user")}
|
||||
placeholder={t("Example 100")}
|
||||
value={value}
|
||||
isDisabled={loading || saving}
|
||||
onValueChange={setValue}
|
||||
description={t(
|
||||
"Applies to every free service, leave blank or 0 for unlimited"
|
||||
)}
|
||||
/>
|
||||
|
||||
<p className="text-xs text-default-400">
|
||||
{t("If a service also has its own limit, the smaller number wins")}
|
||||
</p>
|
||||
|
||||
<div className="flex gap-3 py-4">
|
||||
<Button
|
||||
color="primary"
|
||||
variant="solid"
|
||||
onPress={handleSave}
|
||||
isLoading={saving}
|
||||
size="sm"
|
||||
>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default FreeQuotaSettings;
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
StripeConfig,
|
||||
AlipayConfig,
|
||||
WechatConfig,
|
||||
EpayChannelConfig,
|
||||
PaymentChannelTestResult,
|
||||
} from "@/types/payment";
|
||||
import { paymentChannelService } from "@/services/paymentChannelService";
|
||||
@@ -29,6 +30,14 @@ export const usePaymentChannelManagement = () => {
|
||||
mch_id: "",
|
||||
is_enabled: false,
|
||||
});
|
||||
const [epayConfig, setEpayConfig] = useState<EpayChannelConfig>({
|
||||
gateway: "",
|
||||
pid: "",
|
||||
key: "",
|
||||
pay_type: "",
|
||||
exchange_rate: 1,
|
||||
is_enabled: false,
|
||||
});
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [testResult, setTestResult] = useState<PaymentChannelTestResult | null>(
|
||||
@@ -37,6 +46,7 @@ export const usePaymentChannelManagement = () => {
|
||||
const [isWechatSaving, setIsWechatSaving] = useState(false);
|
||||
const [isStripeSaving, setIsStripeSaving] = useState(false);
|
||||
const [isAlipaySaving, setIsAlipaySaving] = useState(false);
|
||||
const [isEpaySaving, setIsEpaySaving] = useState(false);
|
||||
|
||||
// get payment channel list
|
||||
const fetchChannels = useCallback(async () => {
|
||||
@@ -69,6 +79,16 @@ export const usePaymentChannelManagement = () => {
|
||||
} as AlipayConfig);
|
||||
}
|
||||
|
||||
const epayChannel = response.data.find(
|
||||
(channel) => channel.id === "epay"
|
||||
);
|
||||
if (epayChannel) {
|
||||
setEpayConfig({
|
||||
...epayChannel.config,
|
||||
is_enabled: epayChannel.is_enabled,
|
||||
} as EpayChannelConfig);
|
||||
}
|
||||
|
||||
const wechatChannel = response.data.find(
|
||||
(channel) => channel.id === "wechat"
|
||||
);
|
||||
@@ -184,6 +204,28 @@ export const usePaymentChannelManagement = () => {
|
||||
}
|
||||
}, []);
|
||||
|
||||
// save epay config
|
||||
const saveEpayConfig = useCallback(async (config: EpayChannelConfig) => {
|
||||
setIsEpaySaving(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await paymentChannelService.saveEpayConfig(config);
|
||||
if (result) {
|
||||
setEpayConfig(config);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
err instanceof Error ? err.message : "Failed to save epay config";
|
||||
setError(errorMessage);
|
||||
return false;
|
||||
} finally {
|
||||
setIsEpaySaving(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// save stripe config
|
||||
const saveStripeConfig = useCallback(async (config: StripeConfig) => {
|
||||
setIsStripeSaving(true);
|
||||
@@ -316,6 +358,8 @@ export const usePaymentChannelManagement = () => {
|
||||
stripeConfig,
|
||||
alipayConfig,
|
||||
wechatConfig,
|
||||
epayConfig,
|
||||
isEpaySaving,
|
||||
isWechatSaving,
|
||||
isStripeSaving,
|
||||
isAlipaySaving,
|
||||
@@ -326,6 +370,7 @@ export const usePaymentChannelManagement = () => {
|
||||
saveStripeConfig,
|
||||
saveAlipayConfig,
|
||||
saveWechatConfig,
|
||||
saveEpayConfig,
|
||||
testStripeConnection,
|
||||
testAlipayConnection,
|
||||
testWechatConnection,
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
StripeConfig,
|
||||
AlipayConfig,
|
||||
WechatConfig,
|
||||
EpayChannelConfig,
|
||||
PaymentChannelApiItem,
|
||||
PaymentChannelListResponse,
|
||||
PaymentChannelTestResult,
|
||||
@@ -187,6 +188,11 @@ export class PaymentChannelService {
|
||||
return this.savePaymentChannelConfig("wechat", config, "WeChat");
|
||||
}
|
||||
|
||||
// Save Epay (易支付) configuration
|
||||
async saveEpayConfig(config: EpayChannelConfig): Promise<boolean> {
|
||||
return this.savePaymentChannelConfig("epay", config, "Epay");
|
||||
}
|
||||
|
||||
// Test Alipay connection
|
||||
async testAlipayConnection(
|
||||
config: AlipayConfig
|
||||
|
||||
@@ -65,6 +65,27 @@ export const PricingTab: React.FC<PricingTabProps> = ({
|
||||
</SelectItem>
|
||||
</Select>
|
||||
|
||||
{formData.charge_type === ChargeType.Free && (
|
||||
<Input
|
||||
type="number"
|
||||
min="0"
|
||||
step="1"
|
||||
value={
|
||||
formData.free_daily_limit === null ||
|
||||
formData.free_daily_limit === undefined
|
||||
? ""
|
||||
: String(formData.free_daily_limit)
|
||||
}
|
||||
onChange={(e) => onInputChange("free_daily_limit", e.target.value)}
|
||||
description={t(
|
||||
"Max calls per user per day (Beijing time). Leave blank or 0 for unlimited"
|
||||
)}
|
||||
placeholder={t("e.g. 50")}
|
||||
label={t("Daily call limit per user")}
|
||||
labelPlacement="outside"
|
||||
/>
|
||||
)}
|
||||
|
||||
{formData.charge_type !== ChargeType.Free && (
|
||||
<>
|
||||
{formData.charge_type === ChargeType.PerToken ? (
|
||||
|
||||
@@ -33,6 +33,17 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
paymentChannels[0]?.id || ""
|
||||
);
|
||||
|
||||
// payment channels arrive asynchronously -- fall back to the first one so the
|
||||
// confirm button is not stuck disabled on a modal opened before they load.
|
||||
const effectiveChannel = selectedPaymentChannel || paymentChannels[0]?.id || "";
|
||||
const currencySymbol = effectiveChannel === "epay" ? "¥" : "$";
|
||||
|
||||
const channelLabel = (id: string, name: string) => {
|
||||
if (id === "epay") return t("Epay (Alipay / WeChat)");
|
||||
if (id === "stripe") return name || t("Credit Card");
|
||||
return name || id;
|
||||
};
|
||||
|
||||
const [paymentId, setPaymentId] = useState("");
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
|
||||
|
||||
@@ -48,7 +59,7 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
return;
|
||||
}
|
||||
|
||||
if (!selectedPaymentChannel) {
|
||||
if (!effectiveChannel) {
|
||||
setError(t("Please select a payment method"));
|
||||
return;
|
||||
}
|
||||
@@ -57,7 +68,9 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
method: "POST",
|
||||
body: {
|
||||
amount: numAmount,
|
||||
payment_channel: selectedPaymentChannel,
|
||||
currency: effectiveChannel === "epay" ? "cny" : "usd",
|
||||
// channel id doubles as the payment method the backend switches on
|
||||
payment_method: effectiveChannel,
|
||||
success_url: window.location.origin + "/pay_success",
|
||||
} as unknown as BodyInit,
|
||||
});
|
||||
@@ -128,7 +141,9 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
onChange={handleAmountChange}
|
||||
startContent={
|
||||
<div className="pointer-events-none flex items-center">
|
||||
<span className="text-default-400 text-small">$</span>
|
||||
<span className="text-default-400 text-small">
|
||||
{currencySymbol}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
type="text"
|
||||
@@ -144,15 +159,13 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{/**coming soon : select payment channel*/}
|
||||
|
||||
{/* {paymentChannels.length > 0 && (
|
||||
{paymentChannels.length > 1 && (
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium text-default-700">
|
||||
{t("Payment Method")}
|
||||
</label>
|
||||
<RadioGroup
|
||||
value={selectedPaymentChannel}
|
||||
value={effectiveChannel}
|
||||
onValueChange={setSelectedPaymentChannel}
|
||||
isInvalid={!!error && error.includes("payment method")}
|
||||
errorMessage={
|
||||
@@ -165,12 +178,20 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
>
|
||||
{paymentChannels.map((channel) => (
|
||||
<Radio key={channel.id} value={channel.id}>
|
||||
{channel.name}
|
||||
{channelLabel(channel.id, channel.name)}
|
||||
</Radio>
|
||||
))}
|
||||
</RadioGroup>
|
||||
</div>
|
||||
)} */}
|
||||
)}
|
||||
|
||||
{effectiveChannel === "epay" && (
|
||||
<p className="text-xs text-default-500">
|
||||
{t(
|
||||
"Billed in CNY via your epay gateway (Alipay / WeChat Pay), credited to your balance 1:1"
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button variant="light" onPress={handleClose}>
|
||||
@@ -179,7 +200,7 @@ export const RechargeModal: React.FC<RechargeModalProps> = ({
|
||||
<Button
|
||||
color="primary"
|
||||
onPress={handlePurchase}
|
||||
isDisabled={!selectedPaymentChannel || !amount}
|
||||
isDisabled={!effectiveChannel || !amount}
|
||||
>
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
|
||||
@@ -4,6 +4,7 @@ export enum TabKey {
|
||||
USER_MANAGEMENT = "user-management",
|
||||
RESOURCE_GROUP = "resource-group",
|
||||
REVENUE_MANAGEMENT = "revenue-management",
|
||||
SUBMISSIONS = "submissions",
|
||||
PAYMENT_CHANNELS = "payment-channels",
|
||||
LOGIN_SETTINGS = "login-settings",
|
||||
SYSTEM_SETTINGS = "system-settings",
|
||||
|
||||
@@ -68,6 +68,7 @@ export interface MCPServiceFormData {
|
||||
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
|
||||
free_daily_limit?: string | number | null; // free services only: max calls per user per day (Beijing time), blank/0 = unlimited
|
||||
enabled: EnabledEnum; // API requires string type
|
||||
apis: MCPServiceAPIItem[];
|
||||
headers?: MCPAuthHeaderItem[]; // add headers to form data
|
||||
|
||||
@@ -15,8 +15,8 @@ const getUrlLanguage = (): string | null => {
|
||||
|
||||
const getBrowserDefaultLanguage = (): string => {
|
||||
if (typeof window === "undefined") {
|
||||
// SSR时根据Accept-Language header判断,这里先返回英语
|
||||
return "en";
|
||||
// SSR时根据Accept-Language header判断,这里先返回中文
|
||||
return "zh-CN";
|
||||
}
|
||||
|
||||
const browserLang = navigator.language;
|
||||
@@ -31,7 +31,7 @@ const getBrowserDefaultLanguage = (): string => {
|
||||
const langPrefix = browserLang.split("-")[0];
|
||||
const match = supportedLanguages.find((lang) => lang.startsWith(langPrefix));
|
||||
|
||||
return match || "en"; // 最后才fallback到英语
|
||||
return match || "zh-CN"; // 最后才fallback到中文
|
||||
};
|
||||
|
||||
export const getDefaultLanguage = (): string => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// payment channel type
|
||||
export type PaymentChannelType = "stripe" | "alipay" | "wechat";
|
||||
export type PaymentChannelType = "stripe" | "alipay" | "wechat" | "epay";
|
||||
|
||||
// stripe config - admin need to configure
|
||||
export interface StripeConfig {
|
||||
@@ -23,8 +23,27 @@ export interface WechatConfig {
|
||||
is_enabled?: boolean;
|
||||
}
|
||||
|
||||
// epay (易支付) config - admin need to configure
|
||||
export interface EpayChannelConfig {
|
||||
/** gateway base address, e.g. https://pay.example.com */
|
||||
gateway: string;
|
||||
/** merchant id */
|
||||
pid: string;
|
||||
/** merchant key used for md5 signing */
|
||||
key: string;
|
||||
/** "", alipay, wxpay or qqpay -- empty lets the customer choose */
|
||||
pay_type?: string;
|
||||
/** CNY charged per 1 balance unit (default 1 = 1:1) */
|
||||
exchange_rate?: number | string;
|
||||
/** async notify url, auto derived when empty */
|
||||
notify_url?: string;
|
||||
/** browser return url, auto derived when empty */
|
||||
return_url?: string;
|
||||
is_enabled?: boolean;
|
||||
}
|
||||
|
||||
// union type for all payment configs
|
||||
export type PaymentConfig = StripeConfig | AlipayConfig | WechatConfig;
|
||||
export type PaymentConfig = StripeConfig | AlipayConfig | WechatConfig | EpayChannelConfig;
|
||||
|
||||
// API return payment channel item structure
|
||||
export interface PaymentChannelApiItem {
|
||||
|
||||
@@ -44,4 +44,7 @@ KEY_SOCIAL_ACCOUNT_X_URL = "social_account_x_url"
|
||||
|
||||
KEY_CNAME_A_IP = "cname_a_ip"
|
||||
|
||||
KEY_DEFAULT_RESOURCE_GROUP = "default_resource_group"
|
||||
KEY_DEFAULT_RESOURCE_GROUP = "default_resource_group"
|
||||
|
||||
# Platform-wide daily cap on free MCP services (see api_service billing_service)
|
||||
KEY_FREE_GLOBAL_DAILY_LIMIT = "free_global_daily_limit"
|
||||
@@ -1,6 +1,8 @@
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import PlainTextResponse
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel
|
||||
from urllib.parse import parse_qsl
|
||||
|
||||
from services.common.database import get_db
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
@@ -20,6 +22,15 @@ def get_user_wallet_history(db: Session = Depends(get_db)) -> UserWalletHistoryS
|
||||
return UserWalletHistoryService(db)
|
||||
|
||||
|
||||
def _request_base_url(request: Request) -> str:
|
||||
"""Public base URL of this site (honours the reverse proxy headers)."""
|
||||
forwarded_proto = (request.headers.get("X-Forwarded-Proto") or "").split(",")[0].strip()
|
||||
scheme = forwarded_proto or request.url.scheme or "http"
|
||||
host = (request.headers.get("X-Forwarded-Host") or "").split(",")[0].strip()
|
||||
host = host or request.headers.get("Host") or request.url.netloc
|
||||
return f"{scheme}://{host}"
|
||||
|
||||
|
||||
class CreatePaymentLinkRequest(BaseModel):
|
||||
amount: float
|
||||
currency: str = "usd"
|
||||
@@ -53,6 +64,20 @@ def create_payment_link(
|
||||
return ResponseUtils.error(message="Failed to create Wechat payment link", code=500)
|
||||
task = OrderMonitorTask.get_instance()
|
||||
task.add_order_to_monitor(payment_id=payment_info.get("payment_id"))
|
||||
case "epay":
|
||||
payment_info = payment.create_epay_payment_link(
|
||||
user_id=user.id,
|
||||
amount=body.amount,
|
||||
base_url=_request_base_url(request),
|
||||
success_url=body.success_url,
|
||||
currency=body.currency,
|
||||
)
|
||||
if not payment_info:
|
||||
return ResponseUtils.error(
|
||||
message="Failed to create Epay payment link (check channel config)", code=500
|
||||
)
|
||||
# epay is settled by the async notify; the order monitor has no
|
||||
# epay client, so it is intentionally not registered here.
|
||||
case _:
|
||||
if not body.success_url:
|
||||
return ResponseUtils.error(message="Success URL is required for Stripe payments", code=400)
|
||||
@@ -77,6 +102,32 @@ async def callback_stripe(
|
||||
else:
|
||||
return ResponseUtils.error(message="Stripe callback failed", code=500)
|
||||
|
||||
@router.get("/callback_epay")
|
||||
@router.post("/callback_epay")
|
||||
async def callback_epay(
|
||||
request: Request,
|
||||
payment: PaymentService = Depends(get_payment),
|
||||
):
|
||||
"""Handle an epay (易支付) async notify.
|
||||
|
||||
The gateway sends a GET query string (some forks POST form data) and
|
||||
expects the literal body `success` to stop retrying.
|
||||
"""
|
||||
if request.method == "POST":
|
||||
body = (await request.body()).decode("utf-8", "replace")
|
||||
params = dict(parse_qsl(body, keep_blank_values=True))
|
||||
else:
|
||||
params = dict(request.query_params)
|
||||
|
||||
try:
|
||||
ok = payment.epay_payment_callback(params)
|
||||
except Exception as e: # never let an unexpected error hide the ack
|
||||
from services.common.logging_config import get_logger
|
||||
get_logger(__name__).error(f"Epay callback failed: {e}")
|
||||
ok = False
|
||||
return PlainTextResponse("success" if ok else "error", status_code=200 if ok else 500)
|
||||
|
||||
|
||||
# @router.post("/callback_alipay", response_model=dict)
|
||||
# async def callback_alipay(request: Request, payment: PaymentService = Depends(get_payment)):
|
||||
# """Handle Alipay payment webhook callback."""
|
||||
@@ -92,11 +143,22 @@ async def callback_stripe(
|
||||
async def order_status(
|
||||
request: Request,
|
||||
payment_id: str,
|
||||
payment: PaymentService = Depends(get_payment),
|
||||
get_user_wallet_history: UserWalletHistoryService = Depends(get_user_wallet_history),
|
||||
):
|
||||
"""Check payment order completion status."""
|
||||
if not UserUtils.is_normal_user(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
if get_user_wallet_history.check_order_complete(payment_id):
|
||||
return ResponseUtils.success({"status": 1})
|
||||
|
||||
# epay fallback: if the async notify never reached us, ask the gateway now.
|
||||
try:
|
||||
if payment.sync_epay_order(payment_id):
|
||||
return ResponseUtils.success({"status": 1})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if get_user_wallet_history.check_order_complete(payment_id):
|
||||
return ResponseUtils.success({"status": 1})
|
||||
return ResponseUtils.success({"status": 0})
|
||||
@@ -0,0 +1,308 @@
|
||||
"""User submission controller for MCP/Skill/Plugin marketplace."""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, UploadFile, File, Form, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from services.common.database import get_db
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.common import error_msg
|
||||
from services.common.models.submission import Submission
|
||||
from services.common.models.mcp_service import McpService, ChargeType
|
||||
from services.common.models.mcp_tool_api import McpToolApi, HttpMethod
|
||||
from services.admin_service.services.openapi_helper import convert_openapi_for_ai
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter()
|
||||
|
||||
UPLOAD_DIR = "/tmp/submission_uploads"
|
||||
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
||||
|
||||
|
||||
def _slugify(text: str) -> str:
|
||||
"""Convert text to a slug-safe English string (letters, digits, -, _)."""
|
||||
import re
|
||||
|
||||
s = re.sub(r"[^A-Za-z0-9]+", "-", (text or "").strip()).strip("-").lower()
|
||||
return s or "service"
|
||||
|
||||
|
||||
def _unique_slug(db: Session, text: str) -> str:
|
||||
base = _slugify(text)
|
||||
slug = base
|
||||
counter = 1
|
||||
while db.query(McpService).filter(McpService.slug_name == slug).first():
|
||||
slug = f"{base}-{counter}"
|
||||
counter += 1
|
||||
return slug
|
||||
|
||||
|
||||
def _publish_mcp_service(db: Session, sub: Submission) -> str:
|
||||
"""
|
||||
Create a market listing (mcp_service + mcp_tool_api rows) from an approved
|
||||
MCP submission. Returns the new service id.
|
||||
|
||||
Tool definitions come from the uploaded file when it parses as an OpenAPI
|
||||
spec; otherwise the service is published without tools (admin can add them
|
||||
later from the service edit page).
|
||||
"""
|
||||
meta = sub.metadata_json or {}
|
||||
base_url = (meta.get("base_url") or "").strip()
|
||||
if not base_url:
|
||||
raise ValueError("MCP submission is missing base_url")
|
||||
|
||||
charge_type_raw = (meta.get("charge_type") or "free").strip().lower()
|
||||
try:
|
||||
price = float(meta.get("price") or 0)
|
||||
except (TypeError, ValueError):
|
||||
price = 0.0
|
||||
try:
|
||||
free_daily_limit = int(meta.get("free_daily_limit")) if meta.get("free_daily_limit") else None
|
||||
except (TypeError, ValueError):
|
||||
free_daily_limit = None
|
||||
if free_daily_limit is not None and free_daily_limit <= 0:
|
||||
free_daily_limit = None
|
||||
service_type = (meta.get("service_type") or "openapi").strip() or "openapi"
|
||||
tags = meta.get("tags") or ""
|
||||
if isinstance(tags, list):
|
||||
tags = ",".join(str(t).strip() for t in tags if str(t).strip())
|
||||
|
||||
# Best-effort: parse the uploaded file as an OpenAPI spec to build tool rows.
|
||||
openapi_data = None
|
||||
if sub.file_path and os.path.exists(sub.file_path):
|
||||
try:
|
||||
with open(sub.file_path, "r", encoding="utf-8", errors="ignore") as f:
|
||||
content = f.read()
|
||||
openapi_data = convert_openapi_for_ai(content)
|
||||
if not getattr(openapi_data, "apis", None):
|
||||
openapi_data = None
|
||||
except Exception as e: # noqa: BLE001 - file may not be an OpenAPI doc
|
||||
logger.info("Submission %s file is not an OpenAPI spec: %s", sub.id, e)
|
||||
openapi_data = None
|
||||
|
||||
service = McpService()
|
||||
service.id = str(uuid.uuid4())
|
||||
service.name = sub.name
|
||||
service.slug_name = _unique_slug(db, sub.name)
|
||||
desc = (sub.description or "").strip() or sub.name
|
||||
service.short_description = desc[:255]
|
||||
service.long_description = desc
|
||||
service.base_url = base_url
|
||||
service.headers = "[]"
|
||||
service.charge_type = ChargeType.PER_CALL if (charge_type_raw in ("paid", "per_call") and price > 0) else ChargeType.FREE
|
||||
service.price = price if service.charge_type == ChargeType.PER_CALL else 0.0
|
||||
service.free_daily_limit = free_daily_limit if service.charge_type == ChargeType.FREE else None
|
||||
service.tags = tags
|
||||
service.service_type = service_type
|
||||
service.enabled = 1 # auto-publish: immediately visible in the market
|
||||
|
||||
db.add(service)
|
||||
db.flush()
|
||||
|
||||
tool_count = 0
|
||||
if openapi_data is not None:
|
||||
for api in openapi_data.apis:
|
||||
try:
|
||||
http_method = HttpMethod(api.method)
|
||||
except ValueError:
|
||||
# HEAD/OPTIONS/TRACE are not part of the supported tool enum
|
||||
continue
|
||||
tool = McpToolApi()
|
||||
tool.id = str(uuid.uuid4())
|
||||
tool.service_id = service.id
|
||||
tool.name = api.summary or f"{api.method} {api.path}"
|
||||
tool.description = api.description or api.summary or tool.name
|
||||
tool.path = api.path
|
||||
tool.method = http_method
|
||||
tool.header_parameters = json.dumps(api.header_parameters) if api.header_parameters else ""
|
||||
tool.query_parameters = json.dumps(api.query_parameters) if api.query_parameters else ""
|
||||
tool.path_parameters = json.dumps(api.path_parameters) if api.path_parameters else ""
|
||||
tool.request_body_schema = json.dumps(api.request_body_schema) if api.request_body_schema else ""
|
||||
tool.response_schema = json.dumps(api.response_schema) if api.response_schema else ""
|
||||
tool.response_examples = json.dumps(api.response_examples) if api.response_examples else ""
|
||||
tool.response_headers = json.dumps(api.response_headers) if api.response_headers else ""
|
||||
tool.operation_examples = json.dumps(api.operation_examples) if api.operation_examples else ""
|
||||
tool.enabled = 1
|
||||
tool.is_deleted = 0
|
||||
db.add(tool)
|
||||
tool_count += 1
|
||||
|
||||
db.flush()
|
||||
logger.info(
|
||||
"Auto-published submission %s -> service %s (%d tools, base_url=%s)",
|
||||
sub.id, service.id, tool_count, base_url,
|
||||
)
|
||||
return service.id
|
||||
|
||||
|
||||
@router.post("/submission", summary="User submit MCP/Skill/Plugin")
|
||||
async def create_submission(
|
||||
request: Request,
|
||||
type: str = Form(...),
|
||||
name: str = Form(...),
|
||||
description: str = Form(None),
|
||||
file: UploadFile = File(None),
|
||||
base_url: str = Form(None),
|
||||
service_type: str = Form(None),
|
||||
tags: str = Form(None),
|
||||
charge_type: str = Form(None),
|
||||
price: float = Form(None),
|
||||
free_daily_limit: int = Form(None),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
user_id = UserUtils.get_request_user_id(request)
|
||||
except Exception:
|
||||
user_id = None
|
||||
if not user_id:
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
|
||||
if type not in ("mcp", "skill", "plugin"):
|
||||
return ResponseUtils.error(error_msg=error_msg.INVALID_PARAMETER)
|
||||
|
||||
# MCP submissions must declare where the service lives so that approving
|
||||
# the submission can auto-publish a working market listing.
|
||||
base_url = (base_url or "").strip()
|
||||
if type == "mcp" and not base_url:
|
||||
return ResponseUtils.error(message="base_url is required for MCP submissions")
|
||||
|
||||
file_path = None
|
||||
if file:
|
||||
safe_name = f"{uuid.uuid4()}_{file.filename}"
|
||||
file_path = os.path.join(UPLOAD_DIR, safe_name)
|
||||
with open(file_path, "wb") as f:
|
||||
f.write(await file.read())
|
||||
|
||||
metadata = {}
|
||||
if type == "mcp":
|
||||
metadata = {
|
||||
"base_url": base_url,
|
||||
"service_type": (service_type or "openapi").strip() or "openapi",
|
||||
"tags": (tags or "").strip(),
|
||||
"charge_type": (charge_type or "free").strip() or "free",
|
||||
"price": price,
|
||||
"free_daily_limit": free_daily_limit,
|
||||
}
|
||||
|
||||
sub = Submission(
|
||||
user_id=user_id,
|
||||
type=type,
|
||||
name=name,
|
||||
description=description,
|
||||
file_path=file_path,
|
||||
metadata_json=metadata or None,
|
||||
status="pending",
|
||||
)
|
||||
db.add(sub)
|
||||
db.commit()
|
||||
db.refresh(sub)
|
||||
return ResponseUtils.success(data={"id": sub.id, "status": sub.status})
|
||||
|
||||
|
||||
@router.get("/submissions", summary="List user submissions")
|
||||
def list_submissions(request: Request, db: Session = Depends(get_db)):
|
||||
try:
|
||||
user_id = UserUtils.get_request_user_id(request)
|
||||
except Exception:
|
||||
user_id = None
|
||||
if not user_id:
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
|
||||
subs = db.query(Submission).filter(Submission.user_id == user_id).order_by(Submission.created_at.desc()).all()
|
||||
data = [
|
||||
{
|
||||
"id": s.id,
|
||||
"type": s.type,
|
||||
"name": s.name,
|
||||
"description": s.description,
|
||||
"status": s.status,
|
||||
"metadata_json": s.metadata_json,
|
||||
"created_at": s.created_at.isoformat() if s.created_at else None,
|
||||
"review_note": s.review_note,
|
||||
}
|
||||
for s in subs
|
||||
]
|
||||
return ResponseUtils.success(data=data)
|
||||
|
||||
|
||||
# Admin endpoints
|
||||
@router.get("/admin/submissions", summary="Admin list submissions")
|
||||
def admin_list_submissions(request: Request, status: str = None, db: Session = Depends(get_db)):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
|
||||
q = db.query(Submission)
|
||||
if status:
|
||||
q = q.filter(Submission.status == status)
|
||||
subs = q.order_by(Submission.created_at.desc()).all()
|
||||
data = [
|
||||
{
|
||||
"id": s.id,
|
||||
"user_id": s.user_id,
|
||||
"type": s.type,
|
||||
"name": s.name,
|
||||
"description": s.description,
|
||||
"file_path": s.file_path,
|
||||
"metadata_json": s.metadata_json,
|
||||
"status": s.status,
|
||||
"created_at": s.created_at.isoformat() if s.created_at else None,
|
||||
"review_note": s.review_note,
|
||||
"reviewed_at": s.reviewed_at.isoformat() if s.reviewed_at else None,
|
||||
}
|
||||
for s in subs
|
||||
]
|
||||
return ResponseUtils.success(data=data)
|
||||
|
||||
|
||||
@router.put("/admin/submission/{sub_id}/approve", summary="Approve submission (auto-publish to market)")
|
||||
def approve_submission(sub_id: str, request: Request, db: Session = Depends(get_db)):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
|
||||
sub = db.query(Submission).filter(Submission.id == sub_id).first()
|
||||
if not sub:
|
||||
return ResponseUtils.error(error_msg=error_msg.NOT_FOUND)
|
||||
if sub.status != "pending":
|
||||
return ResponseUtils.error(message="Submission has already been processed")
|
||||
|
||||
service_id = None
|
||||
if sub.type == "mcp":
|
||||
try:
|
||||
service_id = _publish_mcp_service(db, sub)
|
||||
except Exception as e: # noqa: BLE001 - report the exact reason to the admin
|
||||
db.rollback()
|
||||
logger.error("Auto-publish failed for submission %s: %s", sub_id, e)
|
||||
return ResponseUtils.error(error_msg=f"Auto-publish failed: {e}")
|
||||
|
||||
sub.status = "approved"
|
||||
sub.reviewer_id = UserUtils.get_request_user_id(request)
|
||||
sub.reviewed_at = datetime.utcnow()
|
||||
if service_id:
|
||||
meta = sub.metadata_json or {}
|
||||
meta["published_service_id"] = service_id
|
||||
sub.metadata_json = meta
|
||||
db.commit()
|
||||
return ResponseUtils.success(data={"service_id": service_id})
|
||||
|
||||
|
||||
@router.put("/admin/submission/{sub_id}/reject", summary="Reject submission")
|
||||
def reject_submission(sub_id: str, request: Request, body: dict = None, db: Session = Depends(get_db)):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
|
||||
sub = db.query(Submission).filter(Submission.id == sub_id).first()
|
||||
if not sub:
|
||||
return ResponseUtils.error(error_msg=error_msg.NOT_FOUND)
|
||||
sub.status = "rejected"
|
||||
sub.reviewer_id = UserUtils.get_request_user_id(request)
|
||||
sub.reviewed_at = datetime.utcnow()
|
||||
if body:
|
||||
sub.review_note = body.get("note")
|
||||
db.commit()
|
||||
return ResponseUtils.success()
|
||||
@@ -34,6 +34,58 @@ 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("/free-quota")
|
||||
def get_free_quota(
|
||||
sysconfig_service: SysConfigService = Depends(get_sysconfig_service),
|
||||
):
|
||||
"""Platform-wide daily cap applied to every free service (None = unlimited)."""
|
||||
raw = sysconfig_service.get_value_by_key(sys_config_key.KEY_FREE_GLOBAL_DAILY_LIMIT)
|
||||
limit = None
|
||||
if raw not in (None, ""):
|
||||
try:
|
||||
limit = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
limit = None
|
||||
if limit is not None and limit <= 0:
|
||||
limit = None
|
||||
return ResponseUtils.success(data={"free_global_daily_limit": limit})
|
||||
|
||||
|
||||
@router.put("/free-quota")
|
||||
def set_free_quota(
|
||||
request: Request,
|
||||
body: dict = Body(...),
|
||||
sysconfig_service: SysConfigService = Depends(get_sysconfig_service),
|
||||
):
|
||||
"""Update the platform-wide daily cap. Empty value clears it (unlimited)."""
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
|
||||
raw = body.get("free_global_daily_limit")
|
||||
if raw in (None, ""):
|
||||
sysconfig_service.set_value_by_key(
|
||||
sys_config_key.KEY_FREE_GLOBAL_DAILY_LIMIT, "", "Global free daily limit"
|
||||
)
|
||||
return ResponseUtils.success(data={"free_global_daily_limit": None})
|
||||
|
||||
try:
|
||||
limit = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
return ResponseUtils.error(
|
||||
message="free_global_daily_limit must be a non-negative integer", code=400
|
||||
)
|
||||
if limit < 0:
|
||||
return ResponseUtils.error(
|
||||
message="free_global_daily_limit must be a non-negative integer", code=400
|
||||
)
|
||||
|
||||
sysconfig_service.set_value_by_key(
|
||||
sys_config_key.KEY_FREE_GLOBAL_DAILY_LIMIT, str(limit), "Global free daily limit"
|
||||
)
|
||||
return ResponseUtils.success(data={"free_global_daily_limit": limit})
|
||||
|
||||
|
||||
@router.get("/homepage")
|
||||
def get_homepage(
|
||||
sysconfig_service: SysConfigService = Depends(get_sysconfig_service),
|
||||
|
||||
@@ -26,6 +26,7 @@ from services.admin_service.controllers import email_test
|
||||
from services.admin_service.controllers import upload
|
||||
from services.admin_service.controllers import user_task
|
||||
from services.admin_service.controllers import resource_group
|
||||
from services.admin_service.controllers import submission
|
||||
|
||||
|
||||
|
||||
@@ -170,6 +171,7 @@ app.include_router(email_test.router, prefix="/api/email_test")
|
||||
app.include_router(upload.router, prefix="/api/upload")
|
||||
app.include_router(user_task.router, prefix="/api/onboarding")
|
||||
app.include_router(resource_group.router, prefix="/api/resource_group")
|
||||
app.include_router(submission.router, prefix="/api/submission")
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -181,6 +181,23 @@ class UserWalletHistoryRepository:
|
||||
self.db.refresh(history)
|
||||
return history
|
||||
|
||||
def set_callback_data(self, record_id: str, data: str) -> bool:
|
||||
"""Persist raw gateway metadata (e.g. charged CNY amount) on a record."""
|
||||
try:
|
||||
obj = self.db.query(UserWalletHistory).filter(
|
||||
UserWalletHistory.id == record_id
|
||||
).first()
|
||||
if not obj:
|
||||
self.logging.error(f"UserWalletHistory not found: id={record_id}")
|
||||
return False
|
||||
obj.callback_data = data
|
||||
self.db.commit()
|
||||
return True
|
||||
except Exception as e:
|
||||
self.logging.error(f"Error setting callback_data: id={record_id}, error={str(e)}")
|
||||
self.db.rollback()
|
||||
return False
|
||||
|
||||
def deposit_complete(self, id: str, transaction_id: str) -> bool:
|
||||
"""
|
||||
Mark deposit order as completed and safely update balance_after.
|
||||
|
||||
@@ -228,6 +228,21 @@ class McpManagerService:
|
||||
if body["output_token_price"] != existing_service.output_token_price:
|
||||
self._delete_service_price_cache(service_id)
|
||||
existing_service.output_token_price = body["output_token_price"]
|
||||
if "free_daily_limit" in body:
|
||||
raw_limit = body["free_daily_limit"]
|
||||
if raw_limit in (None, ""):
|
||||
new_limit = None
|
||||
else:
|
||||
try:
|
||||
new_limit = int(raw_limit)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("free_daily_limit must be a non-negative integer")
|
||||
if new_limit < 0:
|
||||
raise ValueError("free_daily_limit must be a non-negative integer")
|
||||
if new_limit != existing_service.free_daily_limit:
|
||||
# api_service reads this out of the 1h price cache
|
||||
self._delete_service_price_cache(service_id)
|
||||
existing_service.free_daily_limit = new_limit
|
||||
if "tags" in body and body["tags"] is not None:
|
||||
# If provided as array, convert to string for storage
|
||||
if isinstance(body["tags"], list):
|
||||
@@ -316,6 +331,7 @@ class McpManagerService:
|
||||
"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,
|
||||
"free_daily_limit": service.free_daily_limit,
|
||||
"tags": parse_tags_to_array(service.tags),
|
||||
"apis": [{"id": api.id, "name": api.name, "description": api.description,"url":api.path} for api in apis],
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
import stripe
|
||||
import logging
|
||||
import asyncio
|
||||
@@ -11,10 +12,12 @@ from services.admin_service.repositories.user_wallet_history_repository import U
|
||||
from services.admin_service.repositories.sys_config_repository import SysConfigRepository
|
||||
from services.admin_service.services.payment_channel_service import PaymentChannelService
|
||||
from services.admin_service.utils.alipay_client import AlipayClient
|
||||
from services.admin_service.utils.epay_client import EpayClient, verify_sign
|
||||
from services.admin_service.utils.wxpay_client import WxPayClient,WxPayConfig
|
||||
from services.admin_service.constants.sys_config_key import (
|
||||
KEY_PLATFORM_NAME
|
||||
)
|
||||
from services.common.models.user_wallet_history import PaymentMethod
|
||||
from services.common.redis import redis_client
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -242,6 +245,202 @@ class PaymentService:
|
||||
logger.error(f"Failed to create WeChat payment link: {str(e)}")
|
||||
return None
|
||||
|
||||
def create_epay_payment_link(
|
||||
self,
|
||||
user_id: str,
|
||||
amount: float,
|
||||
base_url: str,
|
||||
success_url: str = "",
|
||||
currency: str = "cny",
|
||||
) -> Optional[dict]:
|
||||
"""Create an epay (易支付) page-pay link for the user.
|
||||
|
||||
The gateway settles in CNY while wallet balances use the platform unit,
|
||||
so `exchange_rate` (CNY per 1 balance unit, default 1) converts the amount.
|
||||
"""
|
||||
config = self.payment_channel_service.get_config("epay")
|
||||
if config is None or not config.get("enable"):
|
||||
logger.error("Epay payment channel is not enabled or configured")
|
||||
return None
|
||||
|
||||
gateway = str(config.get("gateway") or "").strip()
|
||||
pid = str(config.get("pid") or "").strip()
|
||||
key = str(config.get("key") or "").strip()
|
||||
missing = [n for n, v in (("gateway", gateway), ("pid", pid), ("key", key)) if not v]
|
||||
if missing:
|
||||
logger.error(f"Epay payment configuration incomplete. Missing: {', '.join(missing)}")
|
||||
return None
|
||||
|
||||
if amount is None or float(amount) <= 0:
|
||||
raise ValueError("Invalid amount.")
|
||||
|
||||
user = self.user_repository.get_by_id(user_id)
|
||||
if not user:
|
||||
logger.error(f"User with ID {user_id} not found.")
|
||||
raise ValueError("User not found.")
|
||||
|
||||
# Pending deposit record; its id is used as epay's out_trade_no.
|
||||
history = self.user_wallet_history_repository.add_deposit(
|
||||
user_id=user_id, amount=float(amount), payment_method="epay"
|
||||
)
|
||||
if history is None:
|
||||
logger.error("Failed to create user wallet history for deposit.")
|
||||
raise RuntimeError("Failed to create payment.")
|
||||
|
||||
try:
|
||||
rate = float(config.get("exchange_rate") or 1)
|
||||
except (TypeError, ValueError):
|
||||
rate = 1.0
|
||||
if rate <= 0:
|
||||
rate = 1.0
|
||||
money_cny = round(float(amount) * rate, 2)
|
||||
if money_cny < 0.01:
|
||||
money_cny = 0.01
|
||||
|
||||
base = (base_url or "").rstrip("/")
|
||||
notify_url = str(config.get("notify_url") or "").strip() or f"{base}/api/payment/callback_epay"
|
||||
return_url = str(config.get("return_url") or "").strip() or success_url or (base + "/")
|
||||
|
||||
platform_name = self.sys_config_repository.get_by_key(KEY_PLATFORM_NAME)
|
||||
if platform_name is None:
|
||||
platform_name = "XPack"
|
||||
|
||||
client = EpayClient(gateway=gateway, pid=pid, key=key)
|
||||
pay_url = client.build_submit_url(
|
||||
out_trade_no=history.id,
|
||||
name=f"[Deposit] {platform_name}",
|
||||
money=money_cny,
|
||||
notify_url=notify_url,
|
||||
return_url=return_url,
|
||||
pay_type=str(config.get("pay_type") or "").strip(),
|
||||
)
|
||||
if not pay_url:
|
||||
logger.error(f"Failed to build epay payment URL for order {history.id}")
|
||||
return None
|
||||
|
||||
self.user_wallet_history_repository.set_callback_data(
|
||||
history.id,
|
||||
json.dumps({"money_cny": money_cny, "exchange_rate": rate}, ensure_ascii=False),
|
||||
)
|
||||
logger.info(
|
||||
f"Created epay payment link for order {history.id}: {money_cny} CNY "
|
||||
f"({amount} x {rate})"
|
||||
)
|
||||
return {"payment_link": pay_url, "payment_id": history.id}
|
||||
|
||||
def epay_payment_callback(self, params: dict) -> bool:
|
||||
"""Handle an epay (易支付) async notify.
|
||||
|
||||
Verifies the MD5 signature, the trade status and the notified amount,
|
||||
then credits the wallet exactly once (idempotent).
|
||||
"""
|
||||
config = self.payment_channel_service.get_config("epay")
|
||||
if config is None or not config.get("enable"):
|
||||
logger.error("Epay payment channel is disabled, dropping notify")
|
||||
return False
|
||||
|
||||
key = str(config.get("key") or "")
|
||||
out_trade_no = str(params.get("out_trade_no") or "")
|
||||
if not verify_sign(params, key):
|
||||
logger.error(f"Epay notify signature verification failed for order {out_trade_no}")
|
||||
return False
|
||||
|
||||
trade_status = str(params.get("trade_status") or "")
|
||||
if trade_status != "TRADE_SUCCESS":
|
||||
logger.info(f"Epay notify order {out_trade_no} status '{trade_status}' ignored")
|
||||
return True # acknowledged: nothing to credit, gateway should stop retrying
|
||||
|
||||
if not out_trade_no:
|
||||
logger.error("Epay notify without out_trade_no")
|
||||
return False
|
||||
|
||||
history = self.user_wallet_history_repository.get_by_id(out_trade_no)
|
||||
if history is None:
|
||||
logger.error(f"Epay notify for unknown order {out_trade_no}")
|
||||
return False
|
||||
method = getattr(history.payment_method, "value", history.payment_method)
|
||||
if method != PaymentMethod.EPAY.value:
|
||||
logger.error(f"Epay notify for order {out_trade_no} paid via '{method}'")
|
||||
return False
|
||||
|
||||
try:
|
||||
notified_money = round(float(params.get("money")), 2)
|
||||
except (TypeError, ValueError):
|
||||
logger.error(f"Epay notify for order {out_trade_no} has invalid money")
|
||||
return False
|
||||
|
||||
charged_money = None
|
||||
try:
|
||||
meta = json.loads(history.callback_data) if history.callback_data else {}
|
||||
charged_money = round(float(meta.get("money_cny")), 2)
|
||||
except (TypeError, ValueError, json.JSONDecodeError):
|
||||
charged_money = None
|
||||
if charged_money is not None and abs(charged_money - notified_money) > 0.01:
|
||||
logger.error(
|
||||
f"Epay notify amount mismatch for order {out_trade_no}: "
|
||||
f"notified={notified_money} charged={charged_money}"
|
||||
)
|
||||
return False
|
||||
|
||||
if history.status == 1:
|
||||
logger.info(f"Epay notify order {out_trade_no} already completed")
|
||||
return True
|
||||
|
||||
# `transaction_id` is unique: use the gateway trade_no as the channel id.
|
||||
channel_tx = str(params.get("trade_no") or "") or f"epay-{out_trade_no}"
|
||||
return self._add_wallet_balance(payment_id=out_trade_no, payment_channel_id=channel_tx)
|
||||
|
||||
def sync_epay_order(self, payment_id: str) -> bool:
|
||||
"""Fallback settlement: query the gateway for a pending epay order.
|
||||
|
||||
Used when the async notify could not reach us (e.g. the site has no
|
||||
public URL). Credits the wallet when the gateway reports payment.
|
||||
Safe to call repeatedly -- already settled orders are a no-op.
|
||||
"""
|
||||
if not payment_id:
|
||||
return False
|
||||
history = self.user_wallet_history_repository.get_by_id(payment_id)
|
||||
if history is None:
|
||||
return False
|
||||
method = getattr(history.payment_method, "value", history.payment_method)
|
||||
if method != PaymentMethod.EPAY.value or history.status == 1:
|
||||
return False
|
||||
|
||||
config = self.payment_channel_service.get_config("epay")
|
||||
if config is None or not config.get("enable"):
|
||||
return False
|
||||
client = EpayClient(
|
||||
gateway=str(config.get("gateway") or "").strip(),
|
||||
pid=str(config.get("pid") or "").strip(),
|
||||
key=str(config.get("key") or "").strip(),
|
||||
)
|
||||
data = client.query_order(payment_id)
|
||||
if not data:
|
||||
return False
|
||||
if int(data.get("status", 0) or 0) != 1:
|
||||
return False
|
||||
|
||||
try:
|
||||
notified_money = round(float(data.get("money")), 2)
|
||||
except (TypeError, ValueError):
|
||||
notified_money = None
|
||||
if notified_money is not None:
|
||||
try:
|
||||
meta = json.loads(history.callback_data) if history.callback_data else {}
|
||||
charged_money = round(float(meta.get("money_cny")), 2)
|
||||
except (TypeError, ValueError, json.JSONDecodeError):
|
||||
charged_money = None
|
||||
if charged_money is not None and abs(charged_money - notified_money) > 0.01:
|
||||
logger.error(
|
||||
f"Epay query amount mismatch for order {payment_id}: "
|
||||
f"queried={notified_money} charged={charged_money}"
|
||||
)
|
||||
return False
|
||||
|
||||
channel_tx = str(data.get("trade_no") or "") or f"epay-{payment_id}"
|
||||
logger.info(f"Settling epay order {payment_id} via gateway query (trade_no={channel_tx})")
|
||||
return self._add_wallet_balance(payment_id=payment_id, payment_channel_id=channel_tx)
|
||||
|
||||
def payment_callback(self, payment_id: str, payment_channel_id: str, status: int = 1) -> bool:
|
||||
"""
|
||||
Handle Alipay payment webhook callback.
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
"""
|
||||
Epay (易支付) V1 protocol client.
|
||||
|
||||
Protocol reference: https://pay.88531.cn gateway (classic epay / V1):
|
||||
* Submit page : GET {gateway}/submit.php (browser side, no IP whitelist)
|
||||
* API order : POST {gateway}/mapi.php (server side, IP whitelist)
|
||||
* Query order : GET {gateway}/api.php?act=order (uses plaintext `key`, no sign)
|
||||
* Async notify: GET {notify_url} -> reply exactly `success`
|
||||
|
||||
Signature (MD5):
|
||||
1. drop `sign`, `sign_type` and params whose value is empty
|
||||
2. sort params by ASCII ascending
|
||||
3. join as `k1=v1&k2=v2` -- values are NOT url-encoded
|
||||
4. append the merchant key directly (no separator), md5 -> 32 char LOWERCASE hex
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from typing import Optional
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SIGN_TYPE = "MD5"
|
||||
|
||||
|
||||
def build_sign(params: dict, key: str) -> str:
|
||||
"""Build the epay V1 MD5 signature for `params`."""
|
||||
parts = []
|
||||
for field in sorted(params.keys()):
|
||||
if field in ("sign", "sign_type"):
|
||||
continue
|
||||
value = params[field]
|
||||
if value is None or value == "":
|
||||
continue
|
||||
if isinstance(value, (list, dict, tuple, set)):
|
||||
continue
|
||||
parts.append(f"{field}={value}")
|
||||
raw = "&".join(parts) + str(key)
|
||||
return hashlib.md5(raw.encode("utf-8")).hexdigest().lower()
|
||||
|
||||
|
||||
def verify_sign(params: dict, key: str) -> bool:
|
||||
"""Verify an inbound epay notify. Comparison is case insensitive."""
|
||||
given = str(params.get("sign", "") or "").strip()
|
||||
if not given:
|
||||
return False
|
||||
return build_sign(params, key).lower() == given.lower()
|
||||
|
||||
|
||||
class EpayClient:
|
||||
"""Builds epay payment requests."""
|
||||
|
||||
def __init__(self, gateway: str, pid: str, key: str):
|
||||
self.gateway = (gateway or "").rstrip("/")
|
||||
self.pid = str(pid or "")
|
||||
self.key = str(key or "")
|
||||
|
||||
@property
|
||||
def configured(self) -> bool:
|
||||
return bool(self.gateway and self.pid and self.key)
|
||||
|
||||
def build_submit_url(
|
||||
self,
|
||||
out_trade_no: str,
|
||||
name: str,
|
||||
money: float,
|
||||
notify_url: str,
|
||||
return_url: str = "",
|
||||
pay_type: str = "",
|
||||
param: str = "",
|
||||
) -> Optional[str]:
|
||||
"""Build the browser payment URL ({gateway}/submit.php).
|
||||
|
||||
Returns None when the client is not configured or the URL cannot be built.
|
||||
"""
|
||||
if not self.configured:
|
||||
logger.error("Epay client is not configured (gateway/pid/key missing)")
|
||||
return None
|
||||
if not out_trade_no or not notify_url:
|
||||
logger.error("Epay payment requires out_trade_no and notify_url")
|
||||
return None
|
||||
|
||||
params = {
|
||||
"pid": self.pid,
|
||||
"out_trade_no": out_trade_no,
|
||||
"notify_url": notify_url,
|
||||
"name": str(name or "Deposit")[:64],
|
||||
"money": f"{float(money):.2f}",
|
||||
"sign_type": SIGN_TYPE,
|
||||
}
|
||||
if return_url:
|
||||
params["return_url"] = return_url
|
||||
if pay_type:
|
||||
params["type"] = str(pay_type)
|
||||
if param:
|
||||
params["param"] = str(param)
|
||||
|
||||
params["sign"] = build_sign(params, self.key)
|
||||
# urlencode for the actual HTTP request only -- the signature above was
|
||||
# computed on the raw (decoded) values, exactly as the gateway expects.
|
||||
query = urlencode(list(params.items()), quote_via=quote, safe="")
|
||||
return f"{self.gateway}/submit.php?{query}"
|
||||
|
||||
def query_order(self, out_trade_no: str, timeout: float = 8.0) -> Optional[dict]:
|
||||
"""Query one order through {gateway}/api.php?act=order.
|
||||
|
||||
Returns the parsed JSON body, or None when the gateway is unreachable
|
||||
or rejects the call (e.g. our IP is not whitelisted).
|
||||
"""
|
||||
if not self.configured or not out_trade_no:
|
||||
return None
|
||||
params = {
|
||||
"act": "order",
|
||||
"pid": self.pid,
|
||||
"key": self.key,
|
||||
"out_trade_no": out_trade_no,
|
||||
}
|
||||
url = f"{self.gateway}/api.php?{urlencode(list(params.items()), quote_via=quote, safe='')}"
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=timeout) as resp:
|
||||
payload = resp.read().decode("utf-8", "replace")
|
||||
except (urllib.error.URLError, OSError, ValueError) as exc:
|
||||
logger.error(f"Epay order query failed for {out_trade_no}: {exc}")
|
||||
return None
|
||||
try:
|
||||
data = json.loads(payload)
|
||||
except json.JSONDecodeError:
|
||||
logger.error(f"Epay order query returned non-JSON for {out_trade_no}: {payload[:200]}")
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
return data
|
||||
@@ -12,13 +12,16 @@ from typing import Tuple, Optional
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from services.common.redis import redis_client
|
||||
from services.common.redis_keys import RedisKeys
|
||||
from services.common.rabbitmq import rabbitmq_client
|
||||
from services.common.models.billing import BillingMessage, PreDeductResult, ApiCallLogInfo
|
||||
from services.common.models.mcp_service import ChargeType
|
||||
from services.common.models.sys_config import SysConfig
|
||||
from services.common.models.user_wallet import UserWallet
|
||||
from services.common.database import get_db
|
||||
from services.api_service.repositories.mcp_service_repository import McpServiceRepository
|
||||
from services.api_service.repositories.user_wallet_repository import UserWalletRepository
|
||||
from services.admin_service.constants import sys_config_key
|
||||
from services.common.logging_config import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
@@ -51,10 +54,45 @@ class BillingService:
|
||||
"""
|
||||
try:
|
||||
# Get service price information
|
||||
price, input_token_price, output_token_price, charge_type = await self._get_service_price(service_id)
|
||||
price, input_token_price, output_token_price, charge_type, free_daily_limit = await self._get_service_price(service_id)
|
||||
service_price = price
|
||||
match charge_type:
|
||||
case ChargeType.FREE:
|
||||
# Free services are not billed, but may be limited to N calls
|
||||
# per user per day (Beijing time) to stop one user draining them.
|
||||
# The platform-wide cap (sys_config) applies to every free service
|
||||
# and wins whenever it is the smaller of the two, so a service
|
||||
# with no per-service value still inherits the global one.
|
||||
limits = [
|
||||
(value, scope)
|
||||
for value, scope in (
|
||||
(free_daily_limit, "service"),
|
||||
(self._get_global_free_limit(), "platform"),
|
||||
)
|
||||
if value and value > 0
|
||||
]
|
||||
if limits:
|
||||
limit, scope = min(limits, key=lambda item: item[0])
|
||||
allowed, used = self._check_free_quota(user_id, service_id, limit)
|
||||
if not allowed:
|
||||
scope_note = " (platform-wide limit)" if scope == "platform" else ""
|
||||
logger.warning(
|
||||
f"Free daily limit reached - User ID: {user_id}, Service ID: {service_id}, "
|
||||
f"Limit: {limit}{scope_note}, Used: {used}"
|
||||
)
|
||||
return PreDeductResult(
|
||||
success=False,
|
||||
message=(
|
||||
f"Free daily limit reached: {limit} calls per day{scope_note}. "
|
||||
f"Used {used} today, please try again after midnight (Beijing time) "
|
||||
f"or upgrade to a paid plan"
|
||||
),
|
||||
service_price=Decimal("0"),
|
||||
user_balance=Decimal("0"),
|
||||
input_token_price=input_token_price,
|
||||
output_token_price=output_token_price,
|
||||
charge_type=charge_type.value
|
||||
)
|
||||
logger.info(f"Free service, skip billing check - User ID: {user_id}, Service ID: {service_id}")
|
||||
return PreDeductResult(
|
||||
success=True,
|
||||
@@ -168,7 +206,76 @@ class BillingService:
|
||||
logger.error(f"Failed to send billing message: {str(e)}", exc_info=True)
|
||||
# Consider saving failed messages to local queue for retry
|
||||
|
||||
async def _get_service_price(self, service_id: str) -> Tuple[Decimal, Decimal, Decimal, ChargeType]:
|
||||
def _check_free_quota(self, user_id: str, service_id: str, limit: int) -> tuple[bool, int]:
|
||||
"""Count today's calls for a free service and say whether this one is still allowed.
|
||||
|
||||
One Redis key per service/user/Beijing-day, so the counter costs a single
|
||||
INCR and expires by itself after midnight (no cleanup job).
|
||||
Returns (allowed, used_today). A rejected call is counted too, otherwise a
|
||||
client could loop past the limit by simply retrying.
|
||||
"""
|
||||
from datetime import timedelta
|
||||
|
||||
tz_cst = timezone(timedelta(hours=8))
|
||||
now_cst = datetime.now(tz_cst)
|
||||
day = now_cst.strftime("%Y%m%d")
|
||||
|
||||
key = f"xpack:free:calls:{service_id}:{user_id}:{day}"
|
||||
try:
|
||||
used = int(self.redis.incr(key))
|
||||
if used == 1:
|
||||
# seconds until the next Beijing midnight, plus a day of slack
|
||||
next_midnight = (now_cst + timedelta(days=1)).replace(
|
||||
hour=0, minute=0, second=0, microsecond=0
|
||||
)
|
||||
ttl = int((next_midnight - now_cst).total_seconds()) + 86400
|
||||
self.redis.expire(key, ttl)
|
||||
except Exception as e:
|
||||
# Redis being down must not lock paying/free users out of their tools
|
||||
logger.warning(f"Free quota counter unavailable, allowing call - User ID: {user_id}: {e}")
|
||||
return True, 0
|
||||
|
||||
return used <= limit, used
|
||||
|
||||
def _get_global_free_limit(self) -> Optional[int]:
|
||||
"""Platform-wide daily cap on free services, stored in sys_config.
|
||||
|
||||
Reads the same cache key the admin service invalidates on save, so a new
|
||||
value takes effect on the very next call. Unset / empty / unparsable all
|
||||
mean "no platform cap" and never fail the request.
|
||||
"""
|
||||
cache_key = RedisKeys.sys_config_key(sys_config_key.KEY_FREE_GLOBAL_DAILY_LIMIT)
|
||||
raw = None
|
||||
try:
|
||||
cached = self.redis.get(cache_key)
|
||||
if cached is not None:
|
||||
raw = None if cached == "__NULL__" else str(cached)
|
||||
else:
|
||||
db = next(get_db())
|
||||
try:
|
||||
row = (
|
||||
db.query(SysConfig)
|
||||
.filter(SysConfig.key == sys_config_key.KEY_FREE_GLOBAL_DAILY_LIMIT)
|
||||
.first()
|
||||
)
|
||||
raw = row.value if row is not None else None
|
||||
finally:
|
||||
db.close()
|
||||
# Cache the miss too, so an unset key costs no query per call
|
||||
self.redis.set(cache_key, "__NULL__" if raw in (None, "") else raw, ex=3600)
|
||||
except Exception as e:
|
||||
logger.warning(f"Global free limit unavailable, treating as unset: {e}")
|
||||
return None
|
||||
|
||||
if raw in (None, "", "__NULL__"):
|
||||
return None
|
||||
try:
|
||||
value = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return value if value > 0 else None
|
||||
|
||||
async def _get_service_price(self, service_id: str) -> Tuple[Decimal, Decimal, Decimal, ChargeType, Optional[int]]:
|
||||
"""
|
||||
Get service price and charge type
|
||||
|
||||
@@ -184,7 +291,15 @@ class BillingService:
|
||||
if cached_data:
|
||||
try:
|
||||
data = json.loads(cached_data)
|
||||
return Decimal(data["price"]), Decimal(data["input_token_price"]), Decimal(data["output_token_price"]), ChargeType(data["charge_type"])
|
||||
# free_daily_limit was added later; older cache entries simply lack it
|
||||
free_daily_limit = data.get("free_daily_limit")
|
||||
return (
|
||||
Decimal(data["price"]),
|
||||
Decimal(data["input_token_price"]),
|
||||
Decimal(data["output_token_price"]),
|
||||
ChargeType(data["charge_type"]),
|
||||
int(free_daily_limit) if free_daily_limit not in (None, "") else None,
|
||||
)
|
||||
except (json.JSONDecodeError, KeyError, ValueError):
|
||||
logger.warning(f"Service price cache data anomaly, re-fetch from database - Service ID: {service_id}")
|
||||
|
||||
@@ -209,17 +324,20 @@ class BillingService:
|
||||
input_token_price = Decimal(str(service.input_token_price))
|
||||
output_token_price = Decimal(str(service.output_token_price))
|
||||
charge_type = service.charge_type
|
||||
free_daily_limit = getattr(service, "free_daily_limit", None)
|
||||
free_daily_limit = int(free_daily_limit) if free_daily_limit else None
|
||||
|
||||
# Cache to Redis
|
||||
cache_data = {
|
||||
"price": str(price),
|
||||
"input_token_price": str(input_token_price),
|
||||
"output_token_price":str(output_token_price),
|
||||
"charge_type": charge_type.value
|
||||
"charge_type": charge_type.value,
|
||||
"free_daily_limit": free_daily_limit
|
||||
}
|
||||
self.redis.set(cache_key, json.dumps(cache_data), ex=self.SERVICE_CACHE_EXPIRE)
|
||||
|
||||
return price,input_token_price,output_token_price, charge_type
|
||||
return price,input_token_price,output_token_price, charge_type, free_daily_limit
|
||||
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@@ -33,6 +33,11 @@ class McpService(Base):
|
||||
Numeric(10, 2), nullable=True, comment="Output token price (2 decimal places, for per_token charge type)"
|
||||
)
|
||||
enabled: Mapped[int] = mapped_column(Integer, nullable=True, comment="Service status: 0=disabled, 1=enabled")
|
||||
free_daily_limit: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
nullable=True,
|
||||
comment="Free service: max calls per user per day (Beijing time). NULL or 0 = unlimited",
|
||||
)
|
||||
tags: Mapped[str] = mapped_column(String, nullable=True, comment="Tags")
|
||||
service_type: Mapped[str] = mapped_column(String(255), nullable=True, comment="Service type",default="openapi")
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
"""User submission model for MCP/Skill/Plugin marketplace."""
|
||||
from sqlalchemy import Column, String, Text, DateTime, JSON, Enum
|
||||
from sqlalchemy.sql import func
|
||||
from services.common.models.base import Base
|
||||
import uuid
|
||||
|
||||
|
||||
class Submission(Base):
|
||||
__tablename__ = "submission"
|
||||
|
||||
id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
user_id = Column(String(36), nullable=False, index=True)
|
||||
type = Column(Enum("mcp", "skill", "plugin", name="submission_type"), nullable=False)
|
||||
name = Column(String(255), nullable=False)
|
||||
description = Column(Text, nullable=True)
|
||||
file_path = Column(String(512), nullable=True)
|
||||
metadata_json = Column(JSON, nullable=True)
|
||||
status = Column(Enum("pending", "approved", "rejected", name="submission_status"), default="pending", nullable=False)
|
||||
reviewer_id = Column(String(36), nullable=True)
|
||||
review_note = Column(Text, nullable=True)
|
||||
created_at = Column(DateTime, server_default=func.now())
|
||||
reviewed_at = Column(DateTime, nullable=True)
|
||||
@@ -10,6 +10,7 @@ class PaymentMethod(PyEnum):
|
||||
STRIPE = "stripe"
|
||||
ALIPAY = "alipay"
|
||||
WECHAT = "wechat"
|
||||
EPAY = "epay"
|
||||
|
||||
|
||||
class TransactionType(PyEnum):
|
||||
|
||||
@@ -66,9 +66,9 @@ class HttpUtils:
|
||||
if parsed.scheme not in ("http", "https"):
|
||||
raise ValidationException("URL scheme must be http or https")
|
||||
host = (parsed.hostname or "").lower()
|
||||
private_prefixes = ("127.", "10.", "192.168.")
|
||||
if host in ("localhost", "127.0.0.1") or host.startswith(private_prefixes) or host.startswith("172."):
|
||||
raise ValidationException("Access to local/private addresses is not allowed")
|
||||
# Allow LAN/private IPs (user request), only block loopback
|
||||
if host in ("localhost", "127.0.0.1", "::1") or host.startswith("127."):
|
||||
raise ValidationException("Access to loopback addresses is not allowed")
|
||||
|
||||
async with aiohttp.ClientSession(
|
||||
timeout=aiohttp.ClientTimeout(total=timeout),
|
||||
@@ -193,9 +193,9 @@ class HttpUtils:
|
||||
if parsed.scheme not in ("http", "https"):
|
||||
raise ValidationException("URL scheme must be http or https")
|
||||
host = (parsed.hostname or "").lower()
|
||||
private_prefixes = ("127.", "10.", "192.168.")
|
||||
if host in ("localhost", "127.0.0.1") or host.startswith(private_prefixes) or host.startswith("172."):
|
||||
raise ValidationException("Access to local/private addresses is not allowed")
|
||||
# Allow LAN/private IPs (user request), only block loopback
|
||||
if host in ("localhost", "127.0.0.1", "::1") or host.startswith("127."):
|
||||
raise ValidationException("Access to loopback addresses is not allowed")
|
||||
|
||||
async with aiohttp.ClientSession(
|
||||
timeout=aiohttp.ClientTimeout(total=timeout),
|
||||
|
||||
Reference in new issue
Block a user