Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
503b3bf078 | ||
|
|
7f8947f070 | ||
|
|
6dca9b08cc | ||
|
|
06034cf46e | ||
|
|
24e59f18d0 | ||
|
|
f468fe270f | ||
|
|
4cc8b87de5 | ||
|
|
d351afb732 | ||
|
|
fab064975d | ||
|
|
30a06d74d6 | ||
|
|
33d66e7d3b | ||
|
|
b7c67cc44f | ||
|
|
32562b9c25 | ||
|
|
ffc09b7b83 | ||
|
|
f4bd572fff | ||
|
|
3c4e2be1dd | ||
|
|
c0ec39f1d6 | ||
|
|
22fa608220 | ||
|
|
e20dacde6b | ||
|
|
fef2e2a1f7 | ||
|
|
3cb1cca751 | ||
|
|
71807c0c67 | ||
|
|
14e6b5c23b | ||
|
|
64d5b2abfc | ||
|
|
fdbb077293 | ||
|
|
10809113f4 | ||
|
|
f592178d83 | ||
|
|
db9a5d571c | ||
|
|
1ebac24a3b | ||
|
|
875a7bf906 | ||
|
|
bf79191194 | ||
|
|
24ee3078d8 | ||
|
|
302277bad2 | ||
|
|
6724801d60 | ||
|
|
51338373e7 | ||
|
|
aa2fd609c6 | ||
|
|
46bdf470c8 | ||
|
|
6b758c3acd | ||
|
|
1589d6ef0a | ||
|
|
d55cc3e216 | ||
|
|
e1c59da804 | ||
|
|
60c9698cdd | ||
|
|
11de1de3b1 | ||
|
|
c16bab66ee | ||
|
|
ec3bef1cae | ||
|
|
060bcf7f73 | ||
|
|
8394afe581 | ||
|
|
85140f8bdc | ||
|
|
595994de8c | ||
|
|
ff725d766f | ||
|
|
c7bbd0589c | ||
|
|
cbfc4310b5 | ||
|
|
6f83fc7a88 | ||
|
|
714e19a4fc | ||
|
|
64d559dd31 | ||
|
|
50637087ae | ||
|
|
d9fe780665 | ||
|
|
fa23805b5c | ||
|
|
9d5d1ce2c5 | ||
|
|
d6dea1f1e8 | ||
|
|
f9c8a74849 | ||
|
|
915a2bcf9e | ||
|
|
b23662d76a | ||
|
|
77ca12045d | ||
|
|
4f27baf93a | ||
|
|
88325a0ba9 | ||
|
|
20f09ce044 | ||
|
|
cb93e5c5aa | ||
|
|
ae57e5b431 | ||
|
|
06b71995f3 | ||
|
|
52c135a7c6 | ||
|
|
2c5c28c74f | ||
|
|
1eb0e23971 | ||
|
|
a0c2bfe9a6 | ||
|
|
9f55110fb3 | ||
|
|
01cbdbe5b0 | ||
|
|
0e58492387 | ||
|
|
8fabe93710 |
No files matched your search
+1
-1
@@ -9,7 +9,7 @@
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
/pnpm-lock.yaml
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
reactStrictMode: false,
|
||||
// Enable SSR
|
||||
output: "standalone",
|
||||
|
||||
// Optimize images
|
||||
images: {
|
||||
domains: [],
|
||||
unoptimized: false, // Enable image optimization for SSR
|
||||
},
|
||||
|
||||
// Webpack configuration
|
||||
webpack: (config) => {
|
||||
return config;
|
||||
},
|
||||
|
||||
// Redirect configuration
|
||||
async redirects() {
|
||||
return [];
|
||||
},
|
||||
async rewrites() {
|
||||
return [
|
||||
// {
|
||||
// source: "/api/:path*",
|
||||
// destination: `${process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:8001"}/api/:path*`,
|
||||
// },
|
||||
{
|
||||
source: "/uploads/:path*",
|
||||
destination: `${
|
||||
process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:8001"
|
||||
}/uploads/:path*`,
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
// Headers for better performance
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: "/(.*)",
|
||||
headers: [
|
||||
{
|
||||
key: "X-Content-Type-Options",
|
||||
value: "nosniff",
|
||||
},
|
||||
{
|
||||
key: "X-XSS-Protection",
|
||||
value: "1; mode=block",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = nextConfig;
|
||||
@@ -1,10 +1,15 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
reactStrictMode: false,
|
||||
output: "standalone",
|
||||
|
||||
experimental: {
|
||||
optimizePackageImports: ["@nextui-org/react"],
|
||||
},
|
||||
|
||||
transpilePackages: ["@nextui-org/react", "@nextui-org/theme"],
|
||||
|
||||
images: {
|
||||
remotePatterns: [
|
||||
{
|
||||
@@ -12,6 +17,42 @@ const nextConfig: NextConfig = {
|
||||
hostname: "**",
|
||||
},
|
||||
],
|
||||
unoptimized: false,
|
||||
},
|
||||
|
||||
// Redirect configuration
|
||||
async redirects() {
|
||||
return [];
|
||||
},
|
||||
|
||||
async rewrites() {
|
||||
return [
|
||||
{
|
||||
source: "/uploads/:path*",
|
||||
destination: `${
|
||||
process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:8001"
|
||||
}/uploads/:path*`,
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
// Headers for better performance
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: "/(.*)",
|
||||
headers: [
|
||||
{
|
||||
key: "X-Content-Type-Options",
|
||||
value: "nosniff",
|
||||
},
|
||||
{
|
||||
key: "X-XSS-Protection",
|
||||
value: "1; mode=block",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^3.3.4",
|
||||
"@iconify/react": "^5.0.2",
|
||||
"@internationalized/date": "^3.10.1",
|
||||
"@nextui-org/react": "^2.6.11",
|
||||
"@nextui-org/theme": "^2.4.5",
|
||||
"@tailwindcss/typography": "^0.5.16",
|
||||
@@ -32,7 +33,7 @@
|
||||
"immer": "^10.0.3",
|
||||
"lottie-react": "^2.4.1",
|
||||
"lucide-react": "^0.475.0",
|
||||
"next": "^15.5.9",
|
||||
"next": "^16.1.5",
|
||||
"react": "^19.1.4",
|
||||
"react-dom": "^19.1.4",
|
||||
"react-hook-form": "^7.49.3",
|
||||
@@ -54,7 +55,7 @@
|
||||
"@types/three": "^0.177.0",
|
||||
"autoprefixer": "^10.4.17",
|
||||
"eslint": "^8.56.0",
|
||||
"eslint-config-next": "15.5.9",
|
||||
"eslint-config-next": "16.1.5",
|
||||
"postcss": "^8.4.33",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"typescript": "^5.3.3"
|
||||
|
||||
Generated
-16290
File diff suppressed because it is too large.
Load diff
@@ -881,5 +881,15 @@
|
||||
"Server Name must be less than 255 characters": "Server Name must be less than 255 characters",
|
||||
"API Endpoint must be a valid HTTP/HTTPS URL": "API Endpoint must be a valid HTTP/HTTPS URL",
|
||||
"Server ID is required": "Server ID is required",
|
||||
"Short description is required": "Short description is required"
|
||||
"Short description is required": "Short description is required",
|
||||
"Auth Key Name": "Auth Key Name",
|
||||
"Search by email": "Search by email",
|
||||
"Search by service name": "Search by service name",
|
||||
"Select Date Range": "Select Date Range",
|
||||
"Resource group name \"{{name}}\" is reserved and cannot be used": "Resource group name \"{{name}}\" is reserved and cannot be used",
|
||||
"Resource group name \"{{name}}\" already exists": "Resource group name \"{{name}}\" already exists",
|
||||
"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"
|
||||
}
|
||||
@@ -937,5 +937,25 @@
|
||||
"Failed to load resource group detail": "获取资源组详情失败",
|
||||
"Resource Group Detail": "资源组详情",
|
||||
"Current display time is UTC time": "当前显示时间为UTC时间",
|
||||
"View Resource Group Detail": "查看资源组详情"
|
||||
"View Resource Group Detail": "查看资源组详情",
|
||||
"Configure tags bar display": "配置标签栏显示",
|
||||
"Failed to load orders": "加载订单失败",
|
||||
"Transaction Time": "交易时间",
|
||||
"All": "全部",
|
||||
"Purchase": "消费",
|
||||
"No orders found": "无订单",
|
||||
"Account Balance": "账户余额",
|
||||
"View your balance and transaction history": "查看您的余额和交易历史",
|
||||
"Display tags bar": "显示标签栏",
|
||||
"Front end displays tags bar and allows users to filter products based on tags.": "前端显示标签栏,允许用户根据标签过滤产品。",
|
||||
"Tags Bar": "标签栏",
|
||||
"Auth Key Name": "认证密钥名称",
|
||||
"Search by email": "按邮箱搜索",
|
||||
"Search by service name": "按服务名称搜索",
|
||||
"Select Date Range": "选择日期范围",
|
||||
"Resource group name \"{{name}}\" is reserved and cannot be used": "资源组名称 \"{{name}}\" 是保留名称,不能使用",
|
||||
"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天前"
|
||||
}
|
||||
@@ -67,9 +67,26 @@ export interface AdminAnalyticsResponse
|
||||
/**
|
||||
* Get admin analytics data
|
||||
* Headers: { Authorization: string }
|
||||
* @param start_time - Start time timestamp (seconds)
|
||||
* @param end_time - End time timestamp (seconds)
|
||||
*/
|
||||
export async function getAdminAnalytics(): Promise<AdminAnalyticsResponse> {
|
||||
return fetchAdminAPI<AdminAnalyticsData>("/api/admin/stats/analytics", {
|
||||
export async function getAdminAnalytics(
|
||||
start_time?: number,
|
||||
end_time?: number
|
||||
): Promise<AdminAnalyticsResponse> {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (start_time !== undefined) {
|
||||
params.append('start', start_time.toString());
|
||||
}
|
||||
|
||||
if (end_time !== undefined) {
|
||||
params.append('end', end_time.toString());
|
||||
}
|
||||
|
||||
const url = `/api/admin/stats/analytics${params.toString() ? `?${params.toString()}` : ''}`;
|
||||
|
||||
return fetchAdminAPI<AdminAnalyticsData>(url, {
|
||||
method: "GET",
|
||||
}) as unknown as AdminAnalyticsResponse;
|
||||
}
|
||||
@@ -183,7 +183,14 @@ export const createResourceGroup = async (name: string, isDefault: boolean): Pro
|
||||
body: { name: name, is_default: isDefault } as unknown as BodyInit,
|
||||
});
|
||||
if (!response.success) {
|
||||
toast.error(response.error_message || i18n.t("Failed to create resource group"));
|
||||
const errorMsg = response.error_message
|
||||
if (errorMsg?.endsWith('already exists')) {
|
||||
toast.error(i18n.t(errorMsg, { name: name }));
|
||||
} else if(errorMsg?.endsWith('cannot be used')) {
|
||||
toast.error(i18n.t(errorMsg, { name: name }));
|
||||
} else {
|
||||
toast.error(errorMsg || i18n.t("Failed to create resource group"));
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
id: "",
|
||||
@@ -215,7 +222,14 @@ export const updateResourceGroup = async (
|
||||
body: { name: name, is_default: isDefault } as unknown as BodyInit,
|
||||
});
|
||||
if (!response.success) {
|
||||
toast.error(response.error_message || i18n.t("Failed to update resource group"));
|
||||
const errorMsg = response.error_message
|
||||
if (errorMsg?.endsWith('already exists')) {
|
||||
toast.error(i18n.t(errorMsg, { name: name }));
|
||||
} else if(errorMsg?.endsWith('cannot be used')) {
|
||||
toast.error(i18n.t(errorMsg, { name: name }));
|
||||
} else {
|
||||
toast.error(errorMsg || i18n.t("Failed to update resource group"));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -12,7 +12,7 @@ export async function revalidatePlatformConfig() {
|
||||
revalidatePath("/", "layout");
|
||||
|
||||
// Revalidate host-specific cache tag
|
||||
revalidateTag(`platform-config-${host}`);
|
||||
revalidateTag(`platform-config-${host}`, 'max');
|
||||
|
||||
console.info(
|
||||
`Platform config cache revalidated for host: platform-config-${host}`
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
input::placeholder,
|
||||
textarea::placeholder {
|
||||
--nextui-foreground-500: 240 5.03% 64.9%;
|
||||
}
|
||||
/* Import theme styles */
|
||||
@import "../styles/themes.css";
|
||||
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/* Import theme styles */
|
||||
@import "../styles/themes.css";
|
||||
input::placeholder,
|
||||
textarea::placeholder {
|
||||
--nextui-foreground-500: 240 5.03% 64.9%;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
|
||||
@@ -10,7 +10,9 @@ import {
|
||||
Listbox,
|
||||
ListboxItem,
|
||||
Skeleton,
|
||||
DateRangePicker
|
||||
} from "@nextui-org/react";
|
||||
import { parseDate } from "@internationalized/date";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import {
|
||||
LineChart,
|
||||
@@ -60,9 +62,9 @@ const transformToChartData = (
|
||||
userRegDay?.stats_day || payDay?.stats_day || callDay?.stats_day;
|
||||
const formattedDate = rawDate
|
||||
? new Date(rawDate).toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
})
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
})
|
||||
: `Day ${i + 1}`;
|
||||
|
||||
chartData.push({
|
||||
@@ -99,12 +101,114 @@ const ConsoleStats: React.FC = () => {
|
||||
);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Fetch analytics data on component mount
|
||||
// 日期范围状态 - 默认最近30天
|
||||
const [dateRange, setDateRange] = useState<any>(() => {
|
||||
const today = new Date();
|
||||
const thirtyDaysAgo = new Date();
|
||||
thirtyDaysAgo.setDate(today.getDate() - 29);
|
||||
|
||||
// 格式化为 YYYY-MM-DD
|
||||
const formatDate = (date: Date) => {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return `${year}-${month}-${day}`;
|
||||
};
|
||||
|
||||
return {
|
||||
start: parseDate(formatDate(thirtyDaysAgo)),
|
||||
end: parseDate(formatDate(today)),
|
||||
};
|
||||
});
|
||||
|
||||
// 计算最早可选日期(30天前)
|
||||
const minValue = useMemo(() => {
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() - 30);
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return parseDate(`${year}-${month}-${day}`);
|
||||
}, []);
|
||||
|
||||
// 计算最大可选日期(今天)
|
||||
const maxValue = useMemo(() => {
|
||||
const date = new Date();
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return parseDate(`${year}-${month}-${day}`);
|
||||
}, []);
|
||||
|
||||
// 校验:开始日期必须早于结束日期,且不能早于30天前
|
||||
const dateValidation = useMemo(() => {
|
||||
if (!dateRange?.start || !dateRange?.end) {
|
||||
return { isInvalid: false, error: "" };
|
||||
}
|
||||
|
||||
const start = dateRange.start;
|
||||
const end = dateRange.end;
|
||||
const minDate = minValue;
|
||||
|
||||
// 检查开始日期是否早于30天前
|
||||
const isStartTooEarly =
|
||||
start.year < minDate.year ||
|
||||
(start.year === minDate.year && start.month < minDate.month) ||
|
||||
(start.year === minDate.year && start.month === minDate.month && start.day < minDate.day);
|
||||
|
||||
if (isStartTooEarly) {
|
||||
return {
|
||||
isInvalid: true,
|
||||
error: t("Start date cannot be earlier than 30 days ago")
|
||||
};
|
||||
}
|
||||
|
||||
// 检查开始日期是否晚于结束日期
|
||||
const isEndBeforeStart =
|
||||
start.year > end.year ||
|
||||
(start.year === end.year && start.month > end.month) ||
|
||||
(start.year === end.year && start.month === end.month && start.day >= end.day);
|
||||
|
||||
if (isEndBeforeStart) {
|
||||
return {
|
||||
isInvalid: true,
|
||||
error: t("Start date must be before end date")
|
||||
};
|
||||
}
|
||||
|
||||
return { isInvalid: false, error: "" };
|
||||
}, [dateRange, minValue, t]);
|
||||
|
||||
// 错误消息
|
||||
const errorMessage = dateValidation.error;
|
||||
const isInvalidDateRange = dateValidation.isInvalid;
|
||||
|
||||
// Fetch analytics data on component mount and when date range changes
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
if (!dateRange?.start || !dateRange?.end) return;
|
||||
|
||||
// 如果日期范围无效,不发送请求
|
||||
if (isInvalidDateRange) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await getAdminAnalytics();
|
||||
|
||||
// parseDate 返回的对象有 year, month, day 属性
|
||||
const start = dateRange.start;
|
||||
const end = dateRange.end;
|
||||
|
||||
// 转换日期为时间戳(秒)
|
||||
const startDateTime = new Date(start.year, start.month - 1, start.day, 0, 0, 0);
|
||||
const startTime = Math.floor(startDateTime.getTime() / 1000);
|
||||
|
||||
const endDateTime = new Date(end.year, end.month - 1, end.day, 23, 59, 59);
|
||||
const endTime = Math.floor(endDateTime.getTime() / 1000);
|
||||
|
||||
const response = await getAdminAnalytics(startTime, endTime);
|
||||
|
||||
if (response.success) {
|
||||
setAnalyticsData(response.data);
|
||||
@@ -113,14 +217,15 @@ const ConsoleStats: React.FC = () => {
|
||||
response.error_message || "Failed to load analytics data"
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
} catch {
|
||||
toast.error("Failed to load analytics data");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
}, [dateRange, isInvalidDateRange]);
|
||||
|
||||
// Transform API data to chart format
|
||||
const chartData = useMemo<ChartDataItem[]>(() => {
|
||||
@@ -156,6 +261,24 @@ const ConsoleStats: React.FC = () => {
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* 日期范围选择器 */}
|
||||
<div className="flex justify-end">
|
||||
<DateRangePicker
|
||||
label={t("Select Date Range")}
|
||||
value={dateRange}
|
||||
onChange={setDateRange}
|
||||
minValue={minValue}
|
||||
maxValue={maxValue}
|
||||
isInvalid={isInvalidDateRange}
|
||||
errorMessage={errorMessage}
|
||||
onKeyDown={(e) => e.preventDefault()}
|
||||
onKeyUp={(e) => e.preventDefault()}
|
||||
className="w-[250px]"
|
||||
visibleMonths={2}
|
||||
granularity="day"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Charts with Tabs */}
|
||||
<Card shadow="none" className="border-1">
|
||||
<CardHeader className="p-0 flex items-center justify-between">
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
Palette,
|
||||
SquareMenu,
|
||||
TableOfContents,
|
||||
Tags,
|
||||
Trello,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
@@ -161,6 +162,12 @@ const SystemSettingsModal: React.FC<SystemSettingsModalProps> = ({
|
||||
icon: <SquareMenu size={16} />,
|
||||
description: "Configure site navigation and menus",
|
||||
},
|
||||
{
|
||||
key: SettingModalTab.TAGS_BAR,
|
||||
label: "Tags Bar",
|
||||
icon: <Tags size={16} />,
|
||||
description: "Configure tags bar display",
|
||||
},
|
||||
{
|
||||
key: SettingModalTab.FAQ,
|
||||
label: "FAQ",
|
||||
@@ -240,6 +247,7 @@ const SystemSettingsModal: React.FC<SystemSettingsModalProps> = ({
|
||||
items: groupItems([
|
||||
SettingModalTab.THEME,
|
||||
SettingModalTab.NAVIGATION,
|
||||
SettingModalTab.TAGS_BAR,
|
||||
SettingModalTab.FAQ,
|
||||
]),
|
||||
},
|
||||
|
||||
@@ -31,6 +31,7 @@ import { AdminConfig, EmailConfig } from "@/types/system";
|
||||
import { LoginSettingsContent } from "./LoginSettingsContent";
|
||||
import { EmailConfigForm } from "@/components/system-setting/EmailConfigForm";
|
||||
import { LanguageSetting } from "@/components/system-setting/LanguageSetting";
|
||||
import { TagsBarSetting } from "../system-setting/TagsBarSetting";
|
||||
|
||||
interface SystemSettingsRightContentProps {
|
||||
filteredKeys: string[];
|
||||
@@ -201,6 +202,13 @@ const SystemSettingsRightContent: React.FC<SystemSettingsRightContentProps> = ({
|
||||
/>
|
||||
)}
|
||||
|
||||
{section.key === "tagsBar" && (
|
||||
<TagsBarSetting
|
||||
isEnabled={!!platformConfig.tag_bar_display}
|
||||
onSave={onSavePlatformConfig}
|
||||
/>
|
||||
)}
|
||||
|
||||
{section.key === "faq" && (
|
||||
<FaqSettings
|
||||
onSave={saveFaqConfig}
|
||||
|
||||
@@ -8,6 +8,7 @@ export enum SettingModalTab {
|
||||
CODE_INJECTION = "code-injection",
|
||||
XPACK_EXPLORE = "xpack-explore",
|
||||
NAVIGATION = "navigation",
|
||||
TAGS_BAR = "tagsBar",
|
||||
FAQ = "faq",
|
||||
CHANGE_PASSWORD = "change-password",
|
||||
EMAIL_LOGIN_SETTINGS = "email-login-settings",
|
||||
|
||||
@@ -64,7 +64,12 @@ export const APIKeyModal = ({
|
||||
|
||||
if (!response.success) {
|
||||
console.error("Error creating auth key:", response.error_message);
|
||||
toast.error(t("Failed to create auth key"));
|
||||
const errorMsg = response.error_message
|
||||
if (errorMsg?.endsWith('already exists')) {
|
||||
toast.error(t(errorMsg, { name: keyName }));
|
||||
} else {
|
||||
toast.error(t("Failed to create auth key"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -79,7 +84,12 @@ export const APIKeyModal = ({
|
||||
|
||||
if (!response.success) {
|
||||
console.error("Error updating auth key:", response.error_message);
|
||||
toast.error(t("Failed to update auth key"));
|
||||
const errorMsg = response.error_message
|
||||
if (errorMsg?.endsWith('already exists')) {
|
||||
toast.error(t(errorMsg, { name: keyName }));
|
||||
} else {
|
||||
toast.error(t("Failed to update auth key"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -90,6 +100,7 @@ export const APIKeyModal = ({
|
||||
toast.success(t("Auth key updated successfully"));
|
||||
onClose();
|
||||
}
|
||||
setName('')
|
||||
} catch (error) {
|
||||
console.error("Error creating/updating auth key:", error);
|
||||
toast.error(t("Failed to create/update auth key"));
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useCallback, useRef, useEffect } from "react";
|
||||
import {
|
||||
Table,
|
||||
TableHeader,
|
||||
TableColumn,
|
||||
TableBody,
|
||||
TableRow,
|
||||
TableCell,
|
||||
Button,
|
||||
Pagination,
|
||||
Tooltip,
|
||||
Spinner,
|
||||
Chip,
|
||||
Dropdown,
|
||||
DropdownTrigger,
|
||||
DropdownMenu,
|
||||
DropdownItem,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { Calendar, HelpCircle, Filter } from "lucide-react";
|
||||
import { fetchAPI } from "@/shared/rpc/common-function";
|
||||
import i18n from "@/shared/lib/i18n";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { fetchAdminAPI } from "@/rpc/admin-api";
|
||||
|
||||
export interface OrderItem {
|
||||
id: string;
|
||||
amount: string;
|
||||
balance: string;
|
||||
order_id: string;
|
||||
// 支付类型,stripe默认值
|
||||
payment_type: string;
|
||||
// 支付状态,0=未支付,1=已支付,2=支付失败
|
||||
payment_state: number;
|
||||
description: string;
|
||||
// 充值时间
|
||||
create_at: string;
|
||||
// 交易时间,确认订单时间,只有充值完成后才有
|
||||
confirm_at: string;
|
||||
// 订单类型,充值(recharge),消费(purchase),退款(refund),冲正(reversal)
|
||||
order_type: string;
|
||||
}
|
||||
|
||||
interface AccountBalanceTableProps {
|
||||
userId?: string;
|
||||
source?: "client" | "admin";
|
||||
}
|
||||
|
||||
const AccountBalanceTable: React.FC<AccountBalanceTableProps> = ({ userId, source }) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [items, setItems] = useState<OrderItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [pagination, setPagination] = useState({
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
total: 0,
|
||||
});
|
||||
const [selectedType, setSelectedType] = useState<string>("all");
|
||||
const [selectedStatus, setSelectedStatus] = useState<string>("all");
|
||||
const resourceGroupsParams = useRef({
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
keyword: "",
|
||||
orderType: "",
|
||||
status: "",
|
||||
});
|
||||
|
||||
const pages = Math.ceil(pagination.total / pagination.pageSize);
|
||||
const currentPage = Number(pagination.page);
|
||||
|
||||
const fetchOrders = useCallback(
|
||||
async (
|
||||
page: number,
|
||||
page_size: number,
|
||||
order_type?: string,
|
||||
status?: string
|
||||
): Promise<{ data: OrderItem[]; total: number; page: number; page_size: number }> => {
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
page: page.toString(),
|
||||
page_size: page_size.toString(),
|
||||
});
|
||||
if (order_type) params.append("order_type", order_type);
|
||||
if (status) params.append("status", status);
|
||||
if (userId) params.append("user_id", userId);
|
||||
|
||||
// 根据是否有 userId 来决定使用哪个 API
|
||||
const apiUrl = userId
|
||||
? `/api/order/list/by_user?${params.toString()}`
|
||||
: `/api/user/order/list?${params.toString()}`;
|
||||
|
||||
const response = source === "client" ? await fetchAPI<OrderItem[]>(apiUrl) : await fetchAdminAPI<OrderItem[]>(apiUrl);
|
||||
if (!response.success) {
|
||||
toast.error(response.error_message || i18n.t("Failed to load orders"));
|
||||
return {
|
||||
data: [],
|
||||
total: 0,
|
||||
page,
|
||||
page_size,
|
||||
};
|
||||
}
|
||||
return {
|
||||
data: response.data || [],
|
||||
total: response.page?.total || 0,
|
||||
page: response.page?.page || page,
|
||||
page_size: response.page?.page_size || page_size,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error fetching orders:", error);
|
||||
return {
|
||||
data: [],
|
||||
total: 0,
|
||||
page,
|
||||
page_size,
|
||||
};
|
||||
}
|
||||
},
|
||||
[userId]
|
||||
);
|
||||
|
||||
const loadOrders = useCallback(
|
||||
async (
|
||||
page: number = 1,
|
||||
pageSize: number = 10,
|
||||
keyword: string = "",
|
||||
orderType: string = "",
|
||||
status: string = ""
|
||||
) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetchOrders(
|
||||
page,
|
||||
pageSize,
|
||||
orderType || undefined,
|
||||
status || undefined
|
||||
);
|
||||
setItems(response.data);
|
||||
setPagination({
|
||||
page: response.page,
|
||||
pageSize: response.page_size,
|
||||
total: response.total,
|
||||
});
|
||||
resourceGroupsParams.current = {
|
||||
page: response.page,
|
||||
pageSize: response.page_size,
|
||||
keyword,
|
||||
orderType,
|
||||
status,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(t("Failed to load orders"), error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[fetchOrders]
|
||||
);
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<Calendar className="w-3 h-3 text-gray-500" />
|
||||
<span className="text-sm text-gray-600">
|
||||
{new Date(dateString).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// 格式化金额,带正负号和美元符号
|
||||
const formatAmount = (amount: string | number): string => {
|
||||
const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount;
|
||||
if (isNaN(numAmount)) return '$0.00';
|
||||
const absAmount = Math.abs(numAmount).toFixed(2);
|
||||
if (numAmount > 0) {
|
||||
return `+$${absAmount}`;
|
||||
} else if (numAmount < 0) {
|
||||
return `-$${absAmount}`;
|
||||
}
|
||||
return `$${absAmount}`;
|
||||
};
|
||||
|
||||
// 格式化余额,只显示美元符号,不带正负号
|
||||
const formatBalance = (balance: string | number): string => {
|
||||
const numBalance = typeof balance === 'string' ? parseFloat(balance) : balance;
|
||||
if (isNaN(numBalance)) return '$0.00';
|
||||
|
||||
return `$${Math.abs(numBalance).toFixed(2)}`;
|
||||
};
|
||||
|
||||
const getStatusColor = (status: number) => {
|
||||
switch (status) {
|
||||
case 1:
|
||||
return "success";
|
||||
case 2:
|
||||
return "danger";
|
||||
default:
|
||||
return "warning";
|
||||
}
|
||||
};
|
||||
|
||||
const onPageChange = (page: number) => {
|
||||
const { pageSize, orderType, status } = resourceGroupsParams.current;
|
||||
loadOrders(page, pageSize, "", orderType, status);
|
||||
};
|
||||
|
||||
const handleTypeChange = (value: string) => {
|
||||
setSelectedType(value);
|
||||
const orderType = value === "all" ? "" : value;
|
||||
const { status } = resourceGroupsParams.current;
|
||||
loadOrders(1, pagination.pageSize, "", orderType, status);
|
||||
};
|
||||
|
||||
const handleStatusChange = (value: string) => {
|
||||
setSelectedStatus(value);
|
||||
const status = value === "all" ? "" : value;
|
||||
const { orderType } = resourceGroupsParams.current;
|
||||
loadOrders(1, pagination.pageSize, "", orderType, status);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadOrders(1, 10, "");
|
||||
}, [loadOrders]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Table
|
||||
aria-label="Orders table"
|
||||
classNames={{
|
||||
wrapper: "min-h-[400px]",
|
||||
}}
|
||||
removeWrapper
|
||||
>
|
||||
<TableHeader>
|
||||
<TableColumn>
|
||||
<div className="flex items-center gap-1">
|
||||
<span>{t("Transaction Time")}</span>
|
||||
</div>
|
||||
</TableColumn>
|
||||
<TableColumn>
|
||||
<div className="flex items-center gap-2">
|
||||
<span>{t("Type")}</span>
|
||||
<Dropdown>
|
||||
<DropdownTrigger>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
aria-label="Filter by type"
|
||||
>
|
||||
<Filter
|
||||
className={`w-4 h-4 ${
|
||||
selectedType !== "all" ? "text-primary" : ""
|
||||
}`}
|
||||
/>
|
||||
</Button>
|
||||
</DropdownTrigger>
|
||||
<DropdownMenu
|
||||
aria-label="Type filter"
|
||||
selectionMode="single"
|
||||
selectedKeys={[selectedType]}
|
||||
onSelectionChange={(keys) => {
|
||||
const selected = Array.from(keys)[0] as string;
|
||||
handleTypeChange(selected);
|
||||
}}
|
||||
>
|
||||
<DropdownItem key="all">{t("All")}</DropdownItem>
|
||||
<DropdownItem key="recharge">{t("Recharge")}</DropdownItem>
|
||||
<DropdownItem key="purchase">{t("Purchase")}</DropdownItem>
|
||||
</DropdownMenu>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</TableColumn>
|
||||
<TableColumn>{t("Description")}</TableColumn>
|
||||
<TableColumn>{t("Amount")}</TableColumn>
|
||||
<TableColumn>{t("Balance")}</TableColumn>
|
||||
<TableColumn>
|
||||
<div className="flex items-center gap-2">
|
||||
<span>{t("Status")}</span>
|
||||
<Dropdown>
|
||||
<DropdownTrigger>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
aria-label="Filter by status"
|
||||
>
|
||||
<Filter
|
||||
className={`w-4 h-4 ${
|
||||
selectedStatus !== "all" ? "text-primary" : ""
|
||||
}`}
|
||||
/>
|
||||
</Button>
|
||||
</DropdownTrigger>
|
||||
<DropdownMenu
|
||||
aria-label="Status filter"
|
||||
selectionMode="single"
|
||||
selectedKeys={[selectedStatus]}
|
||||
onSelectionChange={(keys) => {
|
||||
const selected = Array.from(keys)[0] as string;
|
||||
handleStatusChange(selected);
|
||||
}}
|
||||
>
|
||||
<DropdownItem key="all">{t("All")}</DropdownItem>
|
||||
<DropdownItem key="0">{t("Pending")}</DropdownItem>
|
||||
<DropdownItem key="1">{t("Completed")}</DropdownItem>
|
||||
<DropdownItem key="2">{t("Failed")}</DropdownItem>
|
||||
</DropdownMenu>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</TableColumn>
|
||||
</TableHeader>
|
||||
<TableBody
|
||||
items={items}
|
||||
isLoading={loading}
|
||||
loadingContent={<Spinner />}
|
||||
emptyContent={t("No orders found")}
|
||||
>
|
||||
{(order) => (
|
||||
<TableRow key={order.id}>
|
||||
<TableCell>{formatDate(order.payment_state === 0 ? order.create_at : order.confirm_at)}</TableCell>
|
||||
<TableCell>
|
||||
<span
|
||||
className={
|
||||
order.order_type === "recharge"
|
||||
? "text-green-500"
|
||||
: "text-red-500"
|
||||
}
|
||||
>
|
||||
{
|
||||
order.order_type === "recharge" ? t("Recharge") : t("Purchase")
|
||||
}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell>{order.description}</TableCell>
|
||||
<TableCell>
|
||||
<span
|
||||
className={
|
||||
order.order_type === "recharge"
|
||||
? "text-green-500"
|
||||
: "text-red-500"
|
||||
}
|
||||
>
|
||||
{formatAmount(order.amount)}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell>{formatBalance(order.balance)}</TableCell>
|
||||
<TableCell>
|
||||
<Chip
|
||||
className="capitalize"
|
||||
color={getStatusColor(order.payment_state)}
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
{t(
|
||||
order.payment_state === 1
|
||||
? "Completed"
|
||||
: order.payment_state === 2
|
||||
? "Failed"
|
||||
: "Pending"
|
||||
)}
|
||||
</Chip>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
{pages > 1 && (
|
||||
<div className="flex w-full justify-center">
|
||||
<Pagination
|
||||
showControls
|
||||
color="primary"
|
||||
variant="light"
|
||||
page={currentPage}
|
||||
total={pages}
|
||||
onChange={onPageChange}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AccountBalanceTable;
|
||||
@@ -53,6 +53,10 @@ const OverviewPage: React.FC = () => {
|
||||
|
||||
useEffect(() => {
|
||||
fetchApiKeys();
|
||||
if (sessionStorage.getItem('create_new_authorization')) {
|
||||
handleNewKey();
|
||||
sessionStorage.removeItem('create_new_authorization');
|
||||
}
|
||||
}, []);
|
||||
|
||||
// create new auth key
|
||||
|
||||
@@ -11,8 +11,9 @@ import { formatCurrency } from "@/shared/utils/currency";
|
||||
// Import dashboard content components
|
||||
import DashboardOverview from "@/components/dashboard/DashboardOverview";
|
||||
import WalletManagement from "@/components/wallet/WalletManagement";
|
||||
import UserAccountBalance from "@/components/dashboard/UserAccountBalance";
|
||||
import { Home, Key, Wallet } from "lucide-react";
|
||||
import { Avatar, Card, CardBody, Button, Divider } from "@nextui-org/react";
|
||||
import { Avatar, Card, CardBody, Button, Divider, Link } from "@nextui-org/react";
|
||||
import { RechargeModal } from "@/shared/components/modal/RechargeModal";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { ChangePasswordModal } from "@/components/common/ChangePasswordModal";
|
||||
@@ -41,7 +42,7 @@ const DashboardContent: React.FC = () => {
|
||||
const [isRechargeModalOpen, setIsRechargeModalOpen] = useState(false);
|
||||
const getInitialTab = (): TabKey => {
|
||||
const tabFromUrl = searchParams.get("tab") as TabKey;
|
||||
if (tabFromUrl && [TabKey.OVERVIEW, TabKey.WALLET].includes(tabFromUrl)) {
|
||||
if (tabFromUrl && [TabKey.OVERVIEW, TabKey.WALLET, TabKey.USER_ACCOUNT].includes(tabFromUrl)) {
|
||||
return tabFromUrl;
|
||||
}
|
||||
return TabKey.OVERVIEW;
|
||||
@@ -158,8 +159,15 @@ const DashboardContent: React.FC = () => {
|
||||
<Wallet size={16} />
|
||||
<span>
|
||||
{t("Balance: {{amount}}", {
|
||||
amount: formatCurrency(user?.wallet?.balance || 0),
|
||||
})}
|
||||
amount: "",
|
||||
}).replace("{{amount}}", "")}
|
||||
<Link
|
||||
href="#"
|
||||
className="text-xs cursor-pointer"
|
||||
onPress={() => handleTabNavigate(TabKey.USER_ACCOUNT)}
|
||||
>
|
||||
{formatCurrency(user?.wallet?.balance || 0)}
|
||||
</Link>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -187,6 +195,7 @@ const DashboardContent: React.FC = () => {
|
||||
{activeTab === TabKey.WALLET && (
|
||||
<WalletManagement onRecharge={() => setIsRechargeModalOpen(true)} />
|
||||
)}
|
||||
{activeTab === TabKey.USER_ACCOUNT && <UserAccountBalance />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import DashboardDemoContent from "@/shared/components/DashboardDemoContent";
|
||||
import AccountBalanceTable from "./AccountBalanceTable";
|
||||
|
||||
const UserAccountBalance: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<DashboardDemoContent
|
||||
title={t("Account Balance")}
|
||||
description={t("View your balance and transaction history")}
|
||||
>
|
||||
<div className="space-y-6 w-full">
|
||||
<AccountBalanceTable source="client" />
|
||||
</div>
|
||||
</DashboardDemoContent>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserAccountBalance;
|
||||
@@ -4,12 +4,19 @@ import React, { useState, useEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { HeroSection } from "../../shared/components/marketplace/HeroSection";
|
||||
import { ServiceListSection } from "@/shared/components/marketplace/ServiceListSection";
|
||||
import { TagFilter } from "@/shared/components/marketplace/TagFilter";
|
||||
import { ServiceData } from "@/shared/types/marketplace";
|
||||
import { fetchServices } from "@/services/marketplaceService";
|
||||
import { Spinner } from "@nextui-org/react";
|
||||
import { ThemeType } from "@/shared/types/system";
|
||||
|
||||
interface MarketplaceMainProps {
|
||||
initialServices: ServiceData[];
|
||||
availableTags: string[];
|
||||
isTagBarDisplay: boolean;
|
||||
selectedTag: string;
|
||||
setSelectedTag: (tag: string) => void;
|
||||
currentTheme: ThemeType;
|
||||
initialTotal: number;
|
||||
initialPage: number;
|
||||
initialSearch: string;
|
||||
@@ -19,6 +26,11 @@ interface MarketplaceMainProps {
|
||||
|
||||
export const MarketplaceMain: React.FC<MarketplaceMainProps> = ({
|
||||
initialServices,
|
||||
availableTags,
|
||||
isTagBarDisplay,
|
||||
selectedTag,
|
||||
setSelectedTag,
|
||||
currentTheme,
|
||||
initialTotal,
|
||||
initialPage,
|
||||
initialSearch,
|
||||
@@ -33,16 +45,18 @@ export const MarketplaceMain: React.FC<MarketplaceMainProps> = ({
|
||||
const [total, setTotal] = useState(initialTotal);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
|
||||
// load services data
|
||||
const loadServices = async (page: number, search: string) => {
|
||||
const loadServices = async (page: number, search: string, tag: string = "ALL") => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const result = await fetchServices({
|
||||
page,
|
||||
page_size: pageSize,
|
||||
keyword: search,
|
||||
// 如果需要,可以在这里添加tag参数传递给API
|
||||
tag: tag !== "ALL" ? tag : undefined,
|
||||
});
|
||||
|
||||
setServices(result.data.services);
|
||||
setTotal(result.page.total);
|
||||
setCurrentPage(page);
|
||||
@@ -79,13 +93,20 @@ export const MarketplaceMain: React.FC<MarketplaceMainProps> = ({
|
||||
// when page number changes, reload
|
||||
const handlePageChange = (page: number) => {
|
||||
updateURL(page, searchQuery);
|
||||
loadServices(page, searchQuery);
|
||||
loadServices(page, searchQuery, selectedTag);
|
||||
};
|
||||
|
||||
// handle search submit
|
||||
const handleSearch = () => {
|
||||
updateURL(1, searchQuery);
|
||||
loadServices(1, searchQuery);
|
||||
loadServices(1, searchQuery, selectedTag);
|
||||
};
|
||||
|
||||
// handle tag change
|
||||
const handleTagChange = (tag: string) => {
|
||||
setSelectedTag(tag);
|
||||
setCurrentPage(1);
|
||||
loadServices(1, searchQuery, tag);
|
||||
};
|
||||
|
||||
// if there is an error, show error message
|
||||
@@ -102,9 +123,25 @@ export const MarketplaceMain: React.FC<MarketplaceMainProps> = ({
|
||||
{/* Hero Section */}
|
||||
<HeroSection
|
||||
searchQuery={searchQuery}
|
||||
isTagBarDisplay={isTagBarDisplay}
|
||||
onSearchChange={setSearchQuery}
|
||||
onSearch={handleSearch}
|
||||
/>
|
||||
|
||||
{/* filter section */}
|
||||
{
|
||||
isTagBarDisplay && (
|
||||
<>
|
||||
<TagFilter
|
||||
theme={currentTheme}
|
||||
tags={availableTags}
|
||||
selectedTag={selectedTag}
|
||||
onTagChange={handleTagChange}
|
||||
maxWidthPercent={80}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
{/* Server List Section */}
|
||||
{loading ? (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useCallback, useEffect } from "react";
|
||||
import React, { useState, useCallback, useEffect, useRef } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { useMCPServicesList } from "@/hooks/useMCPServicesList";
|
||||
import { MCPService, MCPServiceFormData } from "@/shared/types/mcp-service";
|
||||
@@ -12,6 +12,8 @@ import { DeleteConfirmModal } from "@/shared/components/modal/DeleteConfirmModal
|
||||
import DashboardDemoContent from "@/shared/components/DashboardDemoContent";
|
||||
import { ServiceTable } from "@/shared/components/mcp-services/ServiceTable";
|
||||
import { OpenAPIGeneratorModal } from "@/shared/components/mcp-services/OpenAPIGeneratorModal";
|
||||
import { Input } from "@nextui-org/react";
|
||||
import { Search } from "lucide-react";
|
||||
|
||||
type ViewMode = "list" | "edit" | "create";
|
||||
|
||||
@@ -30,9 +32,24 @@ export const MCPServicesManagement: React.FC = () => {
|
||||
toggleServiceStatus,
|
||||
parseOpenAPIDocument,
|
||||
loadServices,
|
||||
setSearchTerm,
|
||||
setStatusFilter,
|
||||
} = useMCPServicesList();
|
||||
const [addServiceType, setAddServiceType] = useState<string | null>(null);
|
||||
|
||||
// 搜索相关状态
|
||||
const [searchValue, setSearchValue] = useState('');
|
||||
const searchTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// 清理定时器
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (searchTimerRef.current) {
|
||||
clearTimeout(searchTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Get initial state from URL
|
||||
const getInitialViewMode = (): ViewMode => {
|
||||
const mode = searchParams.get("mode") as ViewMode;
|
||||
@@ -190,6 +207,26 @@ export const MCPServicesManagement: React.FC = () => {
|
||||
setServiceToDelete(null);
|
||||
}, []);
|
||||
|
||||
// 处理搜索 - 使用防抖
|
||||
const handleSearchChange = useCallback((value: string) => {
|
||||
setSearchValue(value);
|
||||
|
||||
// 清除之前的定时器
|
||||
if (searchTimerRef.current) {
|
||||
clearTimeout(searchTimerRef.current);
|
||||
}
|
||||
|
||||
// 设置新的定时器,500ms 后触发搜索
|
||||
searchTimerRef.current = setTimeout(() => {
|
||||
setSearchTerm(value);
|
||||
}, 500);
|
||||
}, [setSearchTerm]);
|
||||
|
||||
// 处理状态筛选
|
||||
const handleStatusFilterChange = useCallback((status: string) => {
|
||||
setStatusFilter(status);
|
||||
}, [setStatusFilter]);
|
||||
|
||||
// Render edit page if in edit/create mode
|
||||
if (viewMode === "edit" || viewMode === "create") {
|
||||
return (
|
||||
@@ -214,8 +251,27 @@ export const MCPServicesManagement: React.FC = () => {
|
||||
)}
|
||||
>
|
||||
<div className="space-y-6 w-full">
|
||||
{/* comming soon:Filters and Actions */}
|
||||
<ServiceFiltersBar onAddService={handleCreateService} />
|
||||
{/* Filters and Actions */}
|
||||
<div className="flex justify-between items-center gap-4">
|
||||
<ServiceFiltersBar onAddService={handleCreateService} />
|
||||
|
||||
{/* 搜索框 - 右侧 */}
|
||||
<Input
|
||||
isClearable
|
||||
className="w-full sm:max-w-[400px]"
|
||||
placeholder={t('Search by service name')}
|
||||
startContent={<Search className="w-4 h-4" />}
|
||||
value={searchValue}
|
||||
onClear={() => {
|
||||
setSearchValue('');
|
||||
if (searchTimerRef.current) {
|
||||
clearTimeout(searchTimerRef.current);
|
||||
}
|
||||
setSearchTerm('');
|
||||
}}
|
||||
onValueChange={handleSearchChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Servers Table */}
|
||||
<ServiceTable
|
||||
@@ -226,6 +282,7 @@ export const MCPServicesManagement: React.FC = () => {
|
||||
onDelete={handleDeleteService}
|
||||
onToggleStatus={handleToggleStatus}
|
||||
onPageChange={onPageChange}
|
||||
onStatusFilterChange={handleStatusFilterChange}
|
||||
/>
|
||||
|
||||
{/* Modals */}
|
||||
|
||||
@@ -66,8 +66,8 @@ export const StripeConfigForm: React.FC<StripeConfigFormProps> = ({
|
||||
onSave(formData);
|
||||
};
|
||||
|
||||
const isFormValid =
|
||||
formData.secret.trim() !== "" && formData.webhook_secret.trim() !== "";
|
||||
const isFormValid =
|
||||
formData?.secret?.trim() !== "" && formData?.webhook_secret?.trim() !== "";
|
||||
|
||||
const panelContent = () => {
|
||||
return (
|
||||
|
||||
@@ -5,6 +5,7 @@ interface AddServerModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
name: string;
|
||||
id: string;
|
||||
onSaveServer: (name: string, isDefault: boolean) => Promise<void>;
|
||||
type: "add" | "edit";
|
||||
isDefault: boolean;
|
||||
@@ -13,6 +14,7 @@ export const AddServerModal: React.FC<AddServerModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
name,
|
||||
id,
|
||||
onSaveServer,
|
||||
type,
|
||||
isDefault,
|
||||
@@ -49,12 +51,17 @@ export const AddServerModal: React.FC<AddServerModalProps> = ({
|
||||
{type === "add" ? t("Create New Resource Group") : t("Edit Resource Group")}
|
||||
</ModalHeader>
|
||||
<ModalBody>
|
||||
<Input
|
||||
label={t("Resource Group Name")}
|
||||
value={serverName}
|
||||
placeholder={t("Edit Resource Group Name")}
|
||||
onChange={(e) => setServerName(e.target.value)}
|
||||
/>
|
||||
{
|
||||
!['allow-all', 'deny-all'].includes(id) && <>
|
||||
<Input
|
||||
label={t("Resource Group Name")}
|
||||
value={serverName}
|
||||
placeholder={t("Edit Resource Group Name")}
|
||||
onChange={(e) => setServerName(e.target.value)}
|
||||
maxLength={255}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
<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">
|
||||
@@ -73,9 +80,9 @@ export const AddServerModal: React.FC<AddServerModalProps> = ({
|
||||
</div>
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button
|
||||
color="danger"
|
||||
variant="light"
|
||||
<Button
|
||||
color="danger"
|
||||
variant="light"
|
||||
onPress={onClose}
|
||||
isDisabled={isLoading}
|
||||
>
|
||||
|
||||
@@ -106,7 +106,7 @@ const GroupServiceTable: React.FC<GroupServiceTableProps> = ({
|
||||
{resourceGroupDetail?.name}
|
||||
</h2>
|
||||
<div className="flex gap-2 h-[32px]">
|
||||
{showOptions && currentGroupId && <>
|
||||
{currentGroupId && <>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
@@ -114,7 +114,9 @@ const GroupServiceTable: React.FC<GroupServiceTableProps> = ({
|
||||
onPress={() => onEditGroup(currentGroupId)}
|
||||
>
|
||||
<Edit2 size={18} />
|
||||
</Button>
|
||||
</Button></>
|
||||
}
|
||||
{showOptions && currentGroupId && <>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
|
||||
@@ -10,6 +10,7 @@ import { DeleteServerModal } from "./DeleteServerModal";
|
||||
import { Divider, Select, SelectItem } from "@nextui-org/react";
|
||||
import { useResourceGroups } from "@/hooks/useResourceGroups";
|
||||
import { AddMcpServerModal } from "./AddMcpServerModal";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
const ResourceGroupManagement: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
@@ -99,19 +100,22 @@ const ResourceGroupManagement: React.FC = () => {
|
||||
|
||||
// 保存组(创建或编辑)
|
||||
const handleSaveGroup = async (name: string, isDefault: boolean) => {
|
||||
// 去除首尾空格
|
||||
const trimmedName = name.trim();
|
||||
|
||||
let success = false;
|
||||
|
||||
if (editingGroup) {
|
||||
// 编辑现有组
|
||||
success = await updateGroup(editingGroup.id, name, isDefault);
|
||||
success = await updateGroup(editingGroup.id, trimmedName, isDefault);
|
||||
if (success && selectedGroup?.id === editingGroup.id) {
|
||||
setSelectedGroup({ ...selectedGroup, name, isDefault });
|
||||
setSelectedGroup({ ...selectedGroup, name: trimmedName, isDefault });
|
||||
// 触发 GroupServiceTable 刷新
|
||||
setRefreshTrigger(prev => prev + 1);
|
||||
}
|
||||
} else {
|
||||
// 创建新组
|
||||
const newGroupId = await createGroup(name, isDefault);
|
||||
const newGroupId = await createGroup(trimmedName, isDefault);
|
||||
success = !!newGroupId;
|
||||
if (newGroupId) {
|
||||
setNewGroupId(newGroupId);
|
||||
@@ -330,6 +334,7 @@ const ResourceGroupManagement: React.FC = () => {
|
||||
setEditingGroup(null);
|
||||
}}
|
||||
name={editingGroup?.name || ""}
|
||||
id={editingGroup?.id || ""}
|
||||
isDefault={editingGroup?.isDefault || false}
|
||||
onSaveServer={handleSaveGroup}
|
||||
type={editingGroup ? "edit" : "add"}
|
||||
|
||||
@@ -1,13 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import React, { useState, useRef, useEffect } from "react";
|
||||
import { RevenueTable } from "./RevenueTable";
|
||||
import DashboardDemoContent from "@/shared/components/DashboardDemoContent";
|
||||
import { useRevenueManagement } from "@/hooks/useRevenueManagement";
|
||||
import { Input } from "@nextui-org/react";
|
||||
import { Search } from "lucide-react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
|
||||
const RevenueManagement: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
// use custom hook to manage revenue data
|
||||
const { records, loading, pagination, setPage } = useRevenueManagement();
|
||||
const {
|
||||
records,
|
||||
loading,
|
||||
pagination,
|
||||
setPage,
|
||||
setSearch,
|
||||
setPaymentType,
|
||||
setSort
|
||||
} = useRevenueManagement();
|
||||
|
||||
const [searchValue, setSearchValue] = useState('');
|
||||
const searchTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// 清理定时器
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (searchTimerRef.current) {
|
||||
clearTimeout(searchTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 处理搜索 - 使用防抖
|
||||
const handleSearchChange = (value: string) => {
|
||||
setSearchValue(value);
|
||||
|
||||
// 清除之前的定时器
|
||||
if (searchTimerRef.current) {
|
||||
clearTimeout(searchTimerRef.current);
|
||||
}
|
||||
|
||||
// 设置新的定时器,500ms 后触发搜索
|
||||
searchTimerRef.current = setTimeout(() => {
|
||||
setSearch(value);
|
||||
}, 500);
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardDemoContent
|
||||
@@ -15,13 +54,24 @@ const RevenueManagement: React.FC = () => {
|
||||
description="Monitor platform revenue and view user recharge history"
|
||||
>
|
||||
<div className="space-y-6 w-full">
|
||||
{/* comming soon:Filters */}
|
||||
{/* <RevenueFiltersBar
|
||||
searchQuery={searchQuery}
|
||||
onSearchChange={setSearch}
|
||||
statusFilter={statusFilter}
|
||||
onStatusChange={setStatus}
|
||||
/> */}
|
||||
{/* 搜索框 - 右上角 */}
|
||||
<div className="flex justify-end items-center gap-4">
|
||||
<Input
|
||||
isClearable
|
||||
className="w-full sm:max-w-[400px]"
|
||||
placeholder={t('Search by email')}
|
||||
startContent={<Search className="w-4 h-4" />}
|
||||
value={searchValue}
|
||||
onClear={() => {
|
||||
setSearchValue('');
|
||||
if (searchTimerRef.current) {
|
||||
clearTimeout(searchTimerRef.current);
|
||||
}
|
||||
setSearch('');
|
||||
}}
|
||||
onValueChange={handleSearchChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Revenue Table */}
|
||||
<RevenueTable
|
||||
@@ -29,6 +79,8 @@ const RevenueManagement: React.FC = () => {
|
||||
loading={loading}
|
||||
pagination={pagination}
|
||||
onPageChange={setPage}
|
||||
onPaymentTypeChange={setPaymentType}
|
||||
onSortChange={setSort}
|
||||
/>
|
||||
</div>
|
||||
</DashboardDemoContent>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
Table,
|
||||
TableHeader,
|
||||
@@ -11,11 +11,16 @@ import {
|
||||
Pagination,
|
||||
Chip,
|
||||
Spinner,
|
||||
Tooltip
|
||||
Tooltip,
|
||||
Dropdown,
|
||||
DropdownTrigger,
|
||||
DropdownMenu,
|
||||
DropdownItem,
|
||||
Button
|
||||
} from '@nextui-org/react';
|
||||
import { useTranslation } from '@/shared/lib/useTranslation';
|
||||
import { PaymentState, RevenueRecord } from '@/types/revenue';
|
||||
import { Calendar, CreditCard, HelpCircle } from 'lucide-react';
|
||||
import { Calendar, CreditCard, HelpCircle, Filter, ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react';
|
||||
import { formatCurrency } from '@/shared/utils/currency';
|
||||
|
||||
interface RevenueTableProps {
|
||||
@@ -27,6 +32,8 @@ interface RevenueTableProps {
|
||||
total: number;
|
||||
};
|
||||
onPageChange: (page: number) => void;
|
||||
onPaymentTypeChange?: (paymentType: string) => void;
|
||||
onSortChange?: (field: string | undefined, order: 'asc' | 'desc' | undefined) => void;
|
||||
}
|
||||
|
||||
export const RevenueTable: React.FC<RevenueTableProps> = ({
|
||||
@@ -34,8 +41,12 @@ export const RevenueTable: React.FC<RevenueTableProps> = ({
|
||||
loading = false,
|
||||
pagination,
|
||||
onPageChange,
|
||||
onPaymentTypeChange,
|
||||
onSortChange,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [selectedPaymentType, setSelectedPaymentType] = useState('all');
|
||||
const [sortState, setSortState] = useState<'none' | 'desc' | 'asc'>('none');
|
||||
|
||||
const pages = Math.ceil(pagination.total / pagination.pageSize);
|
||||
const currentPage = pagination.page;
|
||||
@@ -92,6 +103,35 @@ export const RevenueTable: React.FC<RevenueTableProps> = ({
|
||||
);
|
||||
};
|
||||
|
||||
// 处理付款方式筛选
|
||||
const handlePaymentTypeChange = (type: string) => {
|
||||
setSelectedPaymentType(type);
|
||||
onPaymentTypeChange?.(type);
|
||||
};
|
||||
|
||||
// 处理排序
|
||||
const handleSortClick = () => {
|
||||
let newSortState: 'none' | 'desc' | 'asc';
|
||||
if (sortState === 'none') {
|
||||
newSortState = 'desc';
|
||||
onSortChange?.('amount', 'desc');
|
||||
} else if (sortState === 'desc') {
|
||||
newSortState = 'asc';
|
||||
onSortChange?.('amount', 'asc');
|
||||
} else {
|
||||
newSortState = 'none';
|
||||
onSortChange?.(undefined, undefined);
|
||||
}
|
||||
setSortState(newSortState);
|
||||
};
|
||||
|
||||
// 获取排序图标
|
||||
const getSortIcon = () => {
|
||||
if (sortState === 'desc') return <ArrowDown className="w-4 h-4" />;
|
||||
if (sortState === 'asc') return <ArrowUp className="w-4 h-4" />;
|
||||
return <ArrowUpDown className="w-4 h-4" />;
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
@@ -122,7 +162,20 @@ export const RevenueTable: React.FC<RevenueTableProps> = ({
|
||||
>
|
||||
<TableHeader>
|
||||
<TableColumn>{t('Account (Email)')}</TableColumn>
|
||||
<TableColumn>{t('Recharge Amount')}</TableColumn>
|
||||
<TableColumn>
|
||||
<div className="flex items-center gap-2">
|
||||
<span>{t('Recharge Amount')}</span>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
onPress={handleSortClick}
|
||||
className="min-w-unit-6 w-6 h-6"
|
||||
>
|
||||
{getSortIcon()}
|
||||
</Button>
|
||||
</div>
|
||||
</TableColumn>
|
||||
<TableColumn>
|
||||
<div className="flex items-center gap-1">
|
||||
<span>{t('Recharge Time')}</span>
|
||||
@@ -136,7 +189,41 @@ export const RevenueTable: React.FC<RevenueTableProps> = ({
|
||||
</Tooltip>
|
||||
</div>
|
||||
</TableColumn>
|
||||
<TableColumn>{t('Payment Method')}</TableColumn>
|
||||
<TableColumn>
|
||||
<div className="flex items-center gap-2">
|
||||
<span>{t('Payment Method')}</span>
|
||||
<Dropdown>
|
||||
<DropdownTrigger>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
aria-label="Filter by payment method"
|
||||
className="min-w-unit-6 w-6 h-6"
|
||||
>
|
||||
<Filter
|
||||
className={`w-4 h-4 ${
|
||||
selectedPaymentType !== 'all' ? 'text-primary' : ''
|
||||
}`}
|
||||
/>
|
||||
</Button>
|
||||
</DropdownTrigger>
|
||||
<DropdownMenu
|
||||
aria-label="Payment method filter"
|
||||
selectionMode="single"
|
||||
selectedKeys={[selectedPaymentType]}
|
||||
onSelectionChange={(keys) => {
|
||||
const selected = Array.from(keys)[0] as string;
|
||||
handlePaymentTypeChange(selected);
|
||||
}}
|
||||
>
|
||||
<DropdownItem key="all">{t('All')}</DropdownItem>
|
||||
<DropdownItem key="stripe">Stripe</DropdownItem>
|
||||
<DropdownItem key="platform">Platform</DropdownItem>
|
||||
</DropdownMenu>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</TableColumn>
|
||||
<TableColumn>{t('Transaction ID')}</TableColumn>
|
||||
<TableColumn>{t('Status')}</TableColumn>
|
||||
</TableHeader>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { Switch } from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
|
||||
export type TagsBarSettingConfig = {
|
||||
tag_bar_display: boolean;
|
||||
};
|
||||
|
||||
interface TagsBarSettingProps {
|
||||
isEnabled: boolean;
|
||||
onSave: (config: TagsBarSettingConfig) => void;
|
||||
}
|
||||
|
||||
export const TagsBarSetting: React.FC<TagsBarSettingProps> = ({
|
||||
isEnabled,
|
||||
onSave,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* showcase in xpack */}
|
||||
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className="text-sm font-medium">
|
||||
{t("Display tags bar")}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{t(
|
||||
"Front end displays tags bar and allows users to filter products based on tags."
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<Switch
|
||||
isSelected={isEnabled}
|
||||
onValueChange={(value) => {
|
||||
onSave({
|
||||
tag_bar_display: value
|
||||
});
|
||||
}}
|
||||
color="primary"
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -9,7 +9,7 @@ import { Home as ClassicHome } from "./classic/Home";
|
||||
import { Home as CreativeHome } from "./creative/Home";
|
||||
import { Home as TemuHome } from "./temu/Home";
|
||||
import { ServiceData } from "@/shared/types/marketplace";
|
||||
import { fetchServices } from "@/services/marketplaceService";
|
||||
import { fetchServices, fetchTagsList } from "@/services/marketplaceService";
|
||||
import { Navigation } from "@/shared/components/Navigation";
|
||||
import { MarketplaceMain } from "../marketplace/Main";
|
||||
import { Footer } from "@/shared/components/Footer";
|
||||
@@ -53,18 +53,36 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
const [currentPage, setCurrentPage] = useState(initialPage);
|
||||
const [total, setTotal] = useState(initialTotal);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const isTagBarDisplay = platformConfig.tag_bar_display || false;
|
||||
// 可用的标签列表(这里可以从API获取或配置)
|
||||
const [availableTags, setAvailableTags] = useState<string[]>([]);
|
||||
const [selectedTag, setSelectedTag] = useState("ALL");
|
||||
// search suggestion
|
||||
const searchSuggestions = ["Search MCP servers"];
|
||||
|
||||
useEffect(() => {
|
||||
const loadTagsList = async () => {
|
||||
const tags = await fetchTagsList();
|
||||
setAvailableTags(tags);
|
||||
};
|
||||
loadTagsList();
|
||||
}, []);
|
||||
|
||||
// handle tag change
|
||||
const handleTagChange = (tag: string) => {
|
||||
setSelectedTag(tag);
|
||||
setCurrentPage(1);
|
||||
loadServices(1, searchQuery, tag);
|
||||
};
|
||||
// loading service data
|
||||
const loadServices = async (page: number, search: string) => {
|
||||
const loadServices = async (page: number, search: string, tag: string = "ALL") => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const result = await fetchServices({
|
||||
page,
|
||||
page_size: pageSize,
|
||||
keyword: search,
|
||||
tag: tag !== "ALL" ? tag : undefined,
|
||||
});
|
||||
|
||||
setServices(result.data.services);
|
||||
@@ -103,13 +121,13 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
// page change handler
|
||||
const handlePageChange = (page: number) => {
|
||||
updateURL(page, searchQuery);
|
||||
loadServices(page, searchQuery);
|
||||
loadServices(page, searchQuery, selectedTag);
|
||||
};
|
||||
|
||||
// search submit handler
|
||||
const handleSearch = () => {
|
||||
updateURL(1, searchQuery);
|
||||
loadServices(1, searchQuery);
|
||||
loadServices(1, searchQuery, selectedTag);
|
||||
};
|
||||
|
||||
// search input change handler
|
||||
@@ -122,6 +140,11 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
case Theme.MODERN:
|
||||
return (
|
||||
<ModernHome
|
||||
currentTheme={currentTheme}
|
||||
selectedTag={selectedTag}
|
||||
handleTagChange={handleTagChange}
|
||||
isTagBarDisplay={isTagBarDisplay}
|
||||
availableTags={availableTags}
|
||||
searchQuery={searchQuery}
|
||||
services={services}
|
||||
currentPage={currentPage}
|
||||
@@ -139,6 +162,11 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
case Theme.CLASSIC:
|
||||
return (
|
||||
<ClassicHome
|
||||
currentTheme={currentTheme}
|
||||
selectedTag={selectedTag}
|
||||
handleTagChange={handleTagChange}
|
||||
isTagBarDisplay={isTagBarDisplay}
|
||||
availableTags={availableTags}
|
||||
searchQuery={searchQuery}
|
||||
services={services}
|
||||
currentPage={currentPage}
|
||||
@@ -156,6 +184,11 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
case Theme.CREATIVE:
|
||||
return (
|
||||
<CreativeHome
|
||||
currentTheme={currentTheme}
|
||||
selectedTag={selectedTag}
|
||||
handleTagChange={handleTagChange}
|
||||
isTagBarDisplay={isTagBarDisplay}
|
||||
availableTags={availableTags}
|
||||
searchQuery={searchQuery}
|
||||
services={services}
|
||||
currentPage={currentPage}
|
||||
@@ -173,6 +206,11 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
case Theme.TEMU:
|
||||
return (
|
||||
<TemuHome
|
||||
currentTheme={currentTheme}
|
||||
selectedTag={selectedTag}
|
||||
handleTagChange={handleTagChange}
|
||||
isTagBarDisplay={isTagBarDisplay}
|
||||
availableTags={availableTags}
|
||||
searchQuery={searchQuery}
|
||||
services={services}
|
||||
currentPage={currentPage}
|
||||
@@ -194,6 +232,11 @@ export const ThemeSelector: React.FC<ThemeSelectorProps> = ({
|
||||
<Navigation items={navigationItems} />
|
||||
<main className="flex-1">
|
||||
<MarketplaceMain
|
||||
currentTheme={currentTheme}
|
||||
selectedTag={selectedTag}
|
||||
setSelectedTag={setSelectedTag}
|
||||
isTagBarDisplay={isTagBarDisplay}
|
||||
availableTags={availableTags}
|
||||
initialServices={services}
|
||||
initialTotal={total}
|
||||
initialPage={currentPage}
|
||||
|
||||
@@ -24,11 +24,18 @@ import { Footer } from "./Footer";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { Faq } from "@/components/marketplace/Faq";
|
||||
import { TagFilter } from "@/shared/components/marketplace/TagFilter";
|
||||
import { ThemeType } from "@/shared/types/system";
|
||||
|
||||
interface HomeProps {
|
||||
// 状态
|
||||
searchQuery: string;
|
||||
services: ServiceData[];
|
||||
isTagBarDisplay: boolean;
|
||||
availableTags: string[];
|
||||
selectedTag: string;
|
||||
handleTagChange: (tag: string) => void;
|
||||
currentTheme: ThemeType;
|
||||
currentPage: number;
|
||||
total: number;
|
||||
pageSize: number;
|
||||
@@ -50,6 +57,11 @@ interface HomeProps {
|
||||
export const Home: React.FC<HomeProps> = ({
|
||||
searchQuery,
|
||||
services,
|
||||
isTagBarDisplay,
|
||||
availableTags,
|
||||
selectedTag,
|
||||
handleTagChange,
|
||||
currentTheme,
|
||||
currentPage,
|
||||
total,
|
||||
pageSize,
|
||||
@@ -83,9 +95,9 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<h1 className="text-4xl lg:text-5xl font-bold mb-6 text-slate-800">
|
||||
{t(
|
||||
platformConfig.headline ||
|
||||
platformConfig.name ||
|
||||
_DefaultPlatformConfig.headline ||
|
||||
""
|
||||
platformConfig.name ||
|
||||
_DefaultPlatformConfig.headline ||
|
||||
""
|
||||
)}
|
||||
</h1>
|
||||
|
||||
@@ -93,8 +105,8 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<p className="text-xl text-gray-600 max-w-3xl mx-auto leading-relaxed">
|
||||
{t(
|
||||
platformConfig.subheadline ||
|
||||
_DefaultPlatformConfig.subheadline ||
|
||||
""
|
||||
_DefaultPlatformConfig.subheadline ||
|
||||
""
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
@@ -140,6 +152,21 @@ export const Home: React.FC<HomeProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* filter section */}
|
||||
{
|
||||
isTagBarDisplay && (
|
||||
<div className="pt-10">
|
||||
<TagFilter
|
||||
theme={currentTheme}
|
||||
tags={availableTags}
|
||||
selectedTag={selectedTag}
|
||||
onTagChange={handleTagChange}
|
||||
maxWidthPercent={80}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
{/* Server List Section */}
|
||||
{loading ? (
|
||||
<div className="mx-auto h-[200px] flex items-center justify-center">
|
||||
@@ -148,7 +175,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-gray-50 py-16">
|
||||
<div className={`bg-gray-50 ${isTagBarDisplay ? 'py-10' : 'py-16'}`}>
|
||||
<div className="mx-auto px-6 max-w-7xl">
|
||||
{/* Server Grid */}
|
||||
<div className="flex flex-wrap justify-center gap-4 mb-12">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { Button } from "@nextui-org/react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -8,6 +8,7 @@ import { DynamicLogo } from "@/shared/components/DynamicLogo";
|
||||
import { useAuth } from "@/shared/lib/useAuth";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import Link from "next/link";
|
||||
import { useSharedStore } from "@/shared/store/share";
|
||||
|
||||
interface NavigationProps {
|
||||
items?: NavigationItem[];
|
||||
@@ -17,6 +18,13 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
const { t } = useTranslation();
|
||||
const { handleLogin } = useAuth();
|
||||
|
||||
const [userToken, setUserToken] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const userToken = useSharedStore?.getState?.().user_token
|
||||
setUserToken(userToken);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="fixed top-0 left-0 right-0 z-50">
|
||||
{/* Classic Header */}
|
||||
@@ -26,21 +34,27 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
<DynamicLogo alt="Platform Logo" className="h-[32px] text-white" />
|
||||
</div>
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
onPress={handleLogin}
|
||||
variant="light"
|
||||
className="hidden sm:block text-white text-sm px-4 py-1 rounded-sm font-medium"
|
||||
size="sm"
|
||||
>
|
||||
<b className="text-md"> {t("Sign In")}</b>
|
||||
</Button>
|
||||
{
|
||||
!userToken && (
|
||||
<>
|
||||
<Button
|
||||
onPress={handleLogin}
|
||||
variant="light"
|
||||
className="hidden sm:block text-white text-sm px-4 py-1 rounded-sm font-medium"
|
||||
size="sm"
|
||||
>
|
||||
<b className="text-md"> {t("Sign In")}</b>
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
<Button
|
||||
color="primary"
|
||||
className="bg-red-600 hover:bg-red-700 text-white text-sm px-4 py-1 rounded-sm font-medium"
|
||||
size="sm"
|
||||
onPress={handleLogin}
|
||||
>
|
||||
{t("Get Started")}
|
||||
{userToken ? t("Dashboard") : t("Get Started")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -24,11 +24,18 @@ import { Footer } from "./Footer";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { Faq } from "@/components/marketplace/Faq";
|
||||
import { TagFilter } from "@/shared/components/marketplace/TagFilter";
|
||||
import { ThemeType } from "@/shared/types/system";
|
||||
|
||||
interface HomeProps {
|
||||
// 状态
|
||||
searchQuery: string;
|
||||
services: ServiceData[];
|
||||
isTagBarDisplay: boolean;
|
||||
availableTags: string[];
|
||||
selectedTag: string;
|
||||
handleTagChange: (tag: string) => void;
|
||||
currentTheme: ThemeType;
|
||||
currentPage: number;
|
||||
total: number;
|
||||
pageSize: number;
|
||||
@@ -50,6 +57,11 @@ interface HomeProps {
|
||||
export const Home: React.FC<HomeProps> = ({
|
||||
searchQuery,
|
||||
services,
|
||||
isTagBarDisplay,
|
||||
availableTags,
|
||||
selectedTag,
|
||||
handleTagChange,
|
||||
currentTheme,
|
||||
currentPage,
|
||||
total,
|
||||
pageSize,
|
||||
@@ -102,9 +114,9 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<span className="bg-clip-text text-transparent bg-gradient-to-r from-pink-600 via-red-500 to-orange-600">
|
||||
{t(
|
||||
platformConfig.headline ||
|
||||
platformConfig.name ||
|
||||
_DefaultPlatformConfig.headline ||
|
||||
""
|
||||
platformConfig.name ||
|
||||
_DefaultPlatformConfig.headline ||
|
||||
""
|
||||
)}
|
||||
</span>
|
||||
</h1>
|
||||
@@ -113,8 +125,8 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<p className="text-lg font-medium max-w-3xl mx-auto leading-relaxed text-gray-700">
|
||||
{t(
|
||||
platformConfig.subheadline ||
|
||||
_DefaultPlatformConfig.subheadline ||
|
||||
""
|
||||
_DefaultPlatformConfig.subheadline ||
|
||||
""
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
@@ -166,6 +178,21 @@ export const Home: React.FC<HomeProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* filter section */}
|
||||
{
|
||||
isTagBarDisplay && (
|
||||
<>
|
||||
<TagFilter
|
||||
theme={currentTheme}
|
||||
tags={availableTags}
|
||||
selectedTag={selectedTag}
|
||||
onTagChange={handleTagChange}
|
||||
maxWidthPercent={80}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
{/* Creative Server List Section */}
|
||||
{loading ? (
|
||||
<div className="relative z-10 mx-auto h-[200px] flex items-center justify-center">
|
||||
@@ -177,7 +204,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
</div>
|
||||
) : (
|
||||
<div className="relative z-10">
|
||||
<div className="relative mx-auto px-6 py-16 max-w-8xl">
|
||||
<div className={`relative mx-auto px-6 ${isTagBarDisplay ? 'py-12' : 'py-16'} max-w-8xl`}>
|
||||
{/* Creative Server Grid */}
|
||||
<div className="flex flex-wrap justify-center gap-4 mb-12">
|
||||
{services.map((service, index) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import React, { useEffect } from "react";
|
||||
import { Button } from "@nextui-org/react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Link from "next/link";
|
||||
@@ -16,6 +16,7 @@ import { ArrowRightIcon } from "lucide-react";
|
||||
import { DynamicLogo } from "@/shared/components/DynamicLogo";
|
||||
import { useAuth } from "@/shared/lib/useAuth";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { useSharedStore } from "@/shared/store/share";
|
||||
|
||||
interface NavigationProps {
|
||||
items?: NavigationItem[];
|
||||
@@ -26,6 +27,13 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
const { handleLogin } = useAuth();
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
|
||||
const [userToken, setUserToken] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const userToken = useSharedStore?.getState?.().user_token
|
||||
setUserToken(userToken);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Creative Navigation */}
|
||||
@@ -65,16 +73,22 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
</NavbarContent>
|
||||
<NavbarContent justify="end" className="items-center gap-2 sm:gap-4">
|
||||
<div className="hidden sm:flex gap-2">
|
||||
<Button onPress={handleLogin} variant="light">
|
||||
<b className="text-md"> {t("Sign In")}</b>
|
||||
</Button>
|
||||
{
|
||||
!userToken && (
|
||||
<>
|
||||
<Button onPress={handleLogin} variant="light">
|
||||
<b className="text-md"> {t("Sign In")}</b>
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
<Button
|
||||
color="primary"
|
||||
className="bg-gradient-to-r from-pink-500 via-red-500 to-orange-500 hover:from-pink-600 hover:via-red-600 hover:to-orange-600 text-white shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105 flex items-center justify-center gap-4 pr-1 h-[45px]"
|
||||
radius="full"
|
||||
onPress={handleLogin}
|
||||
>
|
||||
<b className="text-md">{t("Get Started")}</b>
|
||||
<b className="text-md">{userToken ? t("Dashboard") : t("Get Started")}</b>
|
||||
<div className="w-8 h-8 bg-white/20 flex items-center justify-center rounded-full">
|
||||
<ArrowRightIcon
|
||||
size={16}
|
||||
@@ -89,7 +103,7 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
onPress={handleLogin}
|
||||
size="sm"
|
||||
>
|
||||
<b className="text-md">{t("Get Started")}</b>
|
||||
<b className="text-md">{userToken ? t("Dashboard") : t("Get Started")}</b>
|
||||
</Button>
|
||||
</div>
|
||||
</NavbarContent>
|
||||
@@ -101,7 +115,7 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
radius="full"
|
||||
onPress={handleLogin}
|
||||
>
|
||||
<b className="text-md">{t("Get Started")}</b>
|
||||
<b className="text-md">{userToken ? t("Dashboard") : t("Get Started")}</b>
|
||||
<div className="w-8 h-8 bg-white/20 flex items-center justify-center rounded-full">
|
||||
<ArrowRightIcon
|
||||
size={16}
|
||||
|
||||
@@ -26,11 +26,18 @@ import { Navigation } from "./Navigation";
|
||||
import { Footer } from "./Footer";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { Faq } from "@/components/marketplace/Faq";
|
||||
import { TagFilter } from "@/shared/components/marketplace/TagFilter";
|
||||
import { ThemeType } from "@/shared/types/system";
|
||||
|
||||
interface HomeProps {
|
||||
// 状态
|
||||
searchQuery: string;
|
||||
services: ServiceData[];
|
||||
isTagBarDisplay: boolean;
|
||||
availableTags: string[];
|
||||
selectedTag: string;
|
||||
handleTagChange: (tag: string) => void;
|
||||
currentTheme: ThemeType;
|
||||
currentPage: number;
|
||||
total: number;
|
||||
pageSize: number;
|
||||
@@ -52,6 +59,11 @@ interface HomeProps {
|
||||
export const Home: React.FC<HomeProps> = ({
|
||||
searchQuery,
|
||||
services,
|
||||
isTagBarDisplay,
|
||||
availableTags,
|
||||
selectedTag,
|
||||
handleTagChange,
|
||||
currentTheme,
|
||||
currentPage,
|
||||
total,
|
||||
pageSize,
|
||||
@@ -78,7 +90,7 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<Navigation items={navItems} />
|
||||
{/* Modern Hero Section */}
|
||||
<div className="pt-32">
|
||||
<div className="mx-auto px-6 py-20 max-w-6xl">
|
||||
<div className={`mx-auto px-6 max-w-6xl ${isTagBarDisplay ? 'py-16' : 'py-20'}`}>
|
||||
<div className="text-center mb-16">
|
||||
{/* Modern Icon */}
|
||||
<div className="flex justify-center mb-8">
|
||||
@@ -91,9 +103,9 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<h1 className="text-4xl lg:text-6xl font-bold mb-6 text-gray-900 leading-tight">
|
||||
{t(
|
||||
platformConfig.headline ||
|
||||
platformConfig.name ||
|
||||
_DefaultPlatformConfig.headline ||
|
||||
""
|
||||
platformConfig.name ||
|
||||
_DefaultPlatformConfig.headline ||
|
||||
""
|
||||
)}
|
||||
</h1>
|
||||
|
||||
@@ -101,8 +113,8 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<p className="text-lg text-gray-600 max-w-2xl mx-auto leading-relaxed">
|
||||
{t(
|
||||
platformConfig.subheadline ||
|
||||
_DefaultPlatformConfig.subheadline ||
|
||||
""
|
||||
_DefaultPlatformConfig.subheadline ||
|
||||
""
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
@@ -145,6 +157,21 @@ export const Home: React.FC<HomeProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* filter section */}
|
||||
{
|
||||
isTagBarDisplay && (
|
||||
<>
|
||||
<TagFilter
|
||||
theme={currentTheme}
|
||||
tags={availableTags}
|
||||
selectedTag={selectedTag}
|
||||
onTagChange={handleTagChange}
|
||||
maxWidthPercent={80}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
<section>
|
||||
{/* Server List Section */}
|
||||
{loading ? (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import React, { useEffect } from "react";
|
||||
import { Button } from "@nextui-org/react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Link from "next/link";
|
||||
@@ -16,6 +16,7 @@ import { ArrowRightIcon } from "lucide-react";
|
||||
import { DynamicLogo } from "@/shared/components/DynamicLogo";
|
||||
import { useAuth } from "@/shared/lib/useAuth";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { useSharedStore } from "@/shared/store/share";
|
||||
|
||||
interface NavigationProps {
|
||||
items?: NavigationItem[];
|
||||
@@ -25,7 +26,12 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
const { t } = useTranslation();
|
||||
const { handleLogin } = useAuth();
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const [userToken, setUserToken] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const userToken = useSharedStore?.getState?.().user_token
|
||||
setUserToken(userToken);
|
||||
}, []);
|
||||
return (
|
||||
<>
|
||||
{/* Modern Navigation */}
|
||||
@@ -61,16 +67,22 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
</NavbarContent>
|
||||
<NavbarContent justify="end" className="items-center gap-2 sm:gap-4">
|
||||
<div className="hidden sm:flex gap-2">
|
||||
<Button onPress={handleLogin} variant="light">
|
||||
<b className="text-md"> {t("Sign In")}</b>
|
||||
</Button>
|
||||
{
|
||||
!userToken && (
|
||||
<>
|
||||
<Button onPress={handleLogin} variant="light">
|
||||
<b className="text-md"> {t("Sign In")}</b>
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
<Button
|
||||
color="primary"
|
||||
className="bg-gradient-to-r from-blue-500 to-purple-600 text-white hover:from-blue-600 hover:to-purple-700 flex items-center justify-center gap-4 pr-1 h-[45px] shadow-lg"
|
||||
radius="full"
|
||||
onPress={handleLogin}
|
||||
>
|
||||
<b className="text-md">{t("Get Started")}</b>
|
||||
<b className="text-md">{userToken ? t("Dashboard") : t("Get Started")}</b>
|
||||
<div className="w-8 h-8 bg-white/20 flex items-center justify-center rounded-full">
|
||||
<ArrowRightIcon
|
||||
size={16}
|
||||
@@ -85,7 +97,7 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
onPress={handleLogin}
|
||||
size="sm"
|
||||
>
|
||||
<b className="text-md">{t("Get Started")}</b>
|
||||
<b className="text-md">{userToken ? t("Dashboard") : t("Get Started")}</b>
|
||||
</Button>
|
||||
</div>
|
||||
</NavbarContent>
|
||||
@@ -97,7 +109,7 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
radius="full"
|
||||
onPress={handleLogin}
|
||||
>
|
||||
<b className="text-md">{t("Get Started")}</b>
|
||||
<b className="text-md">{userToken ? t("Dashboard") : t("Get Started")}</b>
|
||||
<div className="w-8 h-8 bg-white/20 flex items-center justify-center rounded-full">
|
||||
<ArrowRightIcon
|
||||
size={16}
|
||||
|
||||
@@ -23,11 +23,18 @@ import { Footer } from "./Footer";
|
||||
import { Navigation } from "./Navigation";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { Faq } from "@/components/marketplace/Faq";
|
||||
import { TagFilter } from "@/shared/components/marketplace/TagFilter";
|
||||
import { ThemeType } from "@/shared/types/system";
|
||||
|
||||
interface HomeProps {
|
||||
// 状态
|
||||
searchQuery: string;
|
||||
services: ServiceData[];
|
||||
isTagBarDisplay: boolean;
|
||||
availableTags: string[];
|
||||
selectedTag: string;
|
||||
handleTagChange: (tag: string) => void;
|
||||
currentTheme: ThemeType;
|
||||
currentPage: number;
|
||||
total: number;
|
||||
pageSize: number;
|
||||
@@ -49,6 +56,11 @@ interface HomeProps {
|
||||
export const Home: React.FC<HomeProps> = ({
|
||||
searchQuery,
|
||||
services,
|
||||
isTagBarDisplay,
|
||||
availableTags,
|
||||
selectedTag,
|
||||
handleTagChange,
|
||||
currentTheme,
|
||||
currentPage,
|
||||
total,
|
||||
pageSize,
|
||||
@@ -95,9 +107,9 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<h1 className="text-4xl lg:text-6xl font-bold mb-6 text-white">
|
||||
{t(
|
||||
platformConfig.headline ||
|
||||
platformConfig.name ||
|
||||
_DefaultPlatformConfig.headline ||
|
||||
""
|
||||
platformConfig.name ||
|
||||
_DefaultPlatformConfig.headline ||
|
||||
""
|
||||
)}
|
||||
</h1>
|
||||
|
||||
@@ -105,8 +117,8 @@ export const Home: React.FC<HomeProps> = ({
|
||||
<p className="text-xl text-white/90 mb-8 max-w-2xl mx-auto">
|
||||
{t(
|
||||
platformConfig.subheadline ||
|
||||
_DefaultPlatformConfig.subheadline ||
|
||||
""
|
||||
_DefaultPlatformConfig.subheadline ||
|
||||
""
|
||||
)}
|
||||
</p>
|
||||
|
||||
@@ -139,6 +151,21 @@ export const Home: React.FC<HomeProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* filter section */}
|
||||
{
|
||||
isTagBarDisplay && (
|
||||
<div className="pt-12">
|
||||
<TagFilter
|
||||
theme={currentTheme}
|
||||
tags={availableTags}
|
||||
selectedTag={selectedTag}
|
||||
onTagChange={handleTagChange}
|
||||
maxWidthPercent={80}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
{/* Products Section */}
|
||||
<div className="mx-auto px-6 py-12 max-w-7xl">
|
||||
{/* Section Header */}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import React, { useEffect } from "react";
|
||||
import { Button } from "@nextui-org/react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Link from "next/link";
|
||||
@@ -16,6 +16,7 @@ import { DynamicLogo } from "@/shared/components/DynamicLogo";
|
||||
import { useAuth } from "@/shared/lib/useAuth";
|
||||
import { NavigationItem } from "@/shared/components/Navigation";
|
||||
import { ArrowRightIcon } from "lucide-react";
|
||||
import { useSharedStore } from "@/shared/store/share";
|
||||
|
||||
interface NavigationProps {
|
||||
items?: NavigationItem[];
|
||||
@@ -26,6 +27,13 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
const { handleLogin } = useAuth();
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
|
||||
const [userToken, setUserToken] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const userToken = useSharedStore?.getState?.().user_token
|
||||
setUserToken(userToken);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Temu Style Navigation */}
|
||||
@@ -64,15 +72,21 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
</NavbarContent>
|
||||
<NavbarContent justify="end" className="items-center gap-2 sm:gap-4">
|
||||
<div className="hidden sm:flex items-center gap-2">
|
||||
<Button onPress={handleLogin} variant="light">
|
||||
<b className="text-md"> {t("Sign In")}</b>
|
||||
</Button>
|
||||
{
|
||||
!userToken && (
|
||||
<>
|
||||
<Button onPress={handleLogin} variant="light">
|
||||
<b className="text-md"> {t("Sign In")}</b>
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
<Button
|
||||
className="bg-orange-500 hover:bg-orange-600 text-white font-semibold px-6 h-[40px] transition-all duration-200"
|
||||
radius="md"
|
||||
onPress={handleLogin}
|
||||
>
|
||||
{t("Get Started")}
|
||||
{userToken ? t("Dashboard") : t("Get Started")}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="sm:hidden">
|
||||
@@ -81,7 +95,7 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
onPress={handleLogin}
|
||||
size="sm"
|
||||
>
|
||||
{t("Sign In")}
|
||||
{userToken ? t("Dashboard") : t("Sign In")}
|
||||
</Button>
|
||||
</div>
|
||||
</NavbarContent>
|
||||
@@ -100,7 +114,7 @@ export const Navigation: React.FC<NavigationProps> = ({ items }) => {
|
||||
radius="md"
|
||||
onPress={handleLogin}
|
||||
>
|
||||
{t("Sign In")}
|
||||
{userToken ? t("Dashboard") : t("Sign In")}
|
||||
</Button>
|
||||
</NavbarMenuItem>
|
||||
</NavbarMenu>
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { Button} from "@nextui-org/react";
|
||||
import { ChevronLeftIcon } from "lucide-react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { withComponentInjection } from "@/shared/hooks/useComponentInjection";
|
||||
import AccountBalanceTable from "../dashboard/AccountBalanceTable";
|
||||
|
||||
interface UserBalanceDetailProps {
|
||||
userId: string;
|
||||
userEmail: string;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
const BaseUserBalanceDetail: React.FC<UserBalanceDetailProps> = ({
|
||||
userId,
|
||||
userEmail,
|
||||
onCancel,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="w-full py-8 h-full flex flex-col">
|
||||
{/* page title */}
|
||||
<div className="flex items-center justify-between mb-6 px-8">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button isIconOnly onPress={onCancel} variant="flat" size="sm">
|
||||
<ChevronLeftIcon className="w-5 h-5" />
|
||||
</Button>
|
||||
<h1 className="text-2xl font-bold">
|
||||
{t("Account Balance")}
|
||||
</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span>{t("Email")}: </span>{userEmail || '-'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="px-8">
|
||||
<AccountBalanceTable userId={userId} source="admin" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
export const UserBalanceDetail = withComponentInjection(
|
||||
"components/user-management/UserBalanceDetail",
|
||||
BaseUserBalanceDetail
|
||||
);
|
||||
@@ -1,12 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useCallback } from "react";
|
||||
import React, { useState, useCallback, useRef, useEffect } from "react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { User } from "@/types/user";
|
||||
import { UserTable } from "./UserTable";
|
||||
import { DeleteConfirmModal } from "@/shared/components/modal/DeleteConfirmModal";
|
||||
import DashboardDemoContent from "@/shared/components/DashboardDemoContent";
|
||||
import { useUserManagement } from "@/hooks/useUserManagement";
|
||||
import { UserBalanceDetail } from "./UserBalanceDetail";
|
||||
import { Input } from "@nextui-org/react";
|
||||
import { Search } from "lucide-react";
|
||||
|
||||
type ViewMode = "list" | "detail";
|
||||
|
||||
const UserManagement: React.FC = () => {
|
||||
const { t } = useTranslation();
|
||||
@@ -20,6 +25,7 @@ const UserManagement: React.FC = () => {
|
||||
handleDeleteUser,
|
||||
setPage,
|
||||
handleRechargeUser,
|
||||
setSearch,
|
||||
} = useUserManagement();
|
||||
|
||||
// Modal states
|
||||
@@ -28,6 +34,24 @@ const UserManagement: React.FC = () => {
|
||||
user: null as User | null,
|
||||
});
|
||||
|
||||
const [viewMode, setViewMode] = useState<ViewMode>('list');
|
||||
const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
|
||||
const [selectedUserEmail, setSelectedUserEmail] = useState<string | null>(null);
|
||||
|
||||
// 搜索相关状态
|
||||
const [searchValue, setSearchValue] = useState('');
|
||||
const searchTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// 清理定时器
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (searchTimerRef.current) {
|
||||
clearTimeout(searchTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
|
||||
const handleDeleteUserClick = useCallback((user: User) => {
|
||||
setDeleteModal({
|
||||
isOpen: true,
|
||||
@@ -35,6 +59,18 @@ const UserManagement: React.FC = () => {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleViewUserBalanceDetail = useCallback((user: User) => {
|
||||
setSelectedUserId(user.id);
|
||||
setSelectedUserEmail(user.email);
|
||||
setViewMode('detail');
|
||||
}, []);
|
||||
|
||||
const handleCloseUserBalanceDetail = useCallback(() => {
|
||||
setSelectedUserId(null);
|
||||
setSelectedUserEmail(null);
|
||||
setViewMode('list');
|
||||
}, []);
|
||||
|
||||
const handleConfirmDelete = useCallback(async () => {
|
||||
if (deleteModal.user) {
|
||||
try {
|
||||
@@ -61,6 +97,31 @@ const UserManagement: React.FC = () => {
|
||||
[handleRechargeUser]
|
||||
);
|
||||
|
||||
// 处理搜索 - 使用防抖
|
||||
const handleSearchChange = useCallback((value: string) => {
|
||||
setSearchValue(value);
|
||||
|
||||
// 清除之前的定时器
|
||||
if (searchTimerRef.current) {
|
||||
clearTimeout(searchTimerRef.current);
|
||||
}
|
||||
|
||||
// 设置新的定时器,500ms 后触发搜索
|
||||
searchTimerRef.current = setTimeout(() => {
|
||||
setSearch(value);
|
||||
}, 500);
|
||||
}, [setSearch]);
|
||||
|
||||
if (viewMode === "detail" ) {
|
||||
return (
|
||||
<UserBalanceDetail
|
||||
userId={selectedUserId || ''}
|
||||
userEmail={selectedUserEmail || ''}
|
||||
onCancel={handleCloseUserBalanceDetail}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DashboardDemoContent
|
||||
title={t("User")}
|
||||
@@ -69,11 +130,31 @@ const UserManagement: React.FC = () => {
|
||||
)}
|
||||
>
|
||||
<div className="space-y-6 w-full">
|
||||
{/* 搜索框 - 右上角 */}
|
||||
<div className="flex justify-end items-center gap-4">
|
||||
<Input
|
||||
isClearable
|
||||
className="w-full sm:max-w-[400px]"
|
||||
placeholder={t('Search by email')}
|
||||
startContent={<Search className="w-4 h-4" />}
|
||||
value={searchValue}
|
||||
onClear={() => {
|
||||
setSearchValue('');
|
||||
if (searchTimerRef.current) {
|
||||
clearTimeout(searchTimerRef.current);
|
||||
}
|
||||
setSearch('');
|
||||
}}
|
||||
onValueChange={handleSearchChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<UserTable
|
||||
users={users}
|
||||
fetchUsers={fetchUsers}
|
||||
loading={loading}
|
||||
onDelete={handleDeleteUserClick}
|
||||
viewUserBalanceDetail={handleViewUserBalanceDetail}
|
||||
onRecharge={handleRecharge}
|
||||
pagination={pagination}
|
||||
onPageChange={setPage}
|
||||
|
||||
@@ -14,10 +14,12 @@ import {
|
||||
Spinner,
|
||||
Select,
|
||||
SelectItem,
|
||||
Link
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { User } from "@/types/user";
|
||||
import { Trash2, CreditCard, Calendar, HelpCircle } from "lucide-react";
|
||||
|
||||
import { AdminRechargeModal } from "@/components/user-management/AdminRechargeModal";
|
||||
import { fetchSimpleResourceGroups, updateUserResourceGroup } from "@/api/resourceGroup.api";
|
||||
import toast from "react-hot-toast";
|
||||
@@ -27,6 +29,7 @@ interface UserTableProps {
|
||||
fetchUsers: () => void;
|
||||
loading?: boolean;
|
||||
onDelete: (user: User) => void;
|
||||
viewUserBalanceDetail: (userId: User) => void;
|
||||
onRecharge: (id: string, amount: number) => Promise<boolean>;
|
||||
pagination: {
|
||||
page: number;
|
||||
@@ -40,6 +43,7 @@ export const UserTable: React.FC<UserTableProps> = ({
|
||||
users,
|
||||
fetchUsers,
|
||||
loading = false,
|
||||
viewUserBalanceDetail,
|
||||
onDelete,
|
||||
onRecharge,
|
||||
pagination,
|
||||
@@ -135,7 +139,7 @@ export const UserTable: React.FC<UserTableProps> = ({
|
||||
<TableHeader>
|
||||
<TableColumn>{t("Email")}</TableColumn>
|
||||
<TableColumn width={250}>{t("Resource Group")}</TableColumn>
|
||||
<TableColumn>
|
||||
<TableColumn width={200}>
|
||||
<div className="flex items-center gap-1">
|
||||
<span>{t("Register Date")}</span>
|
||||
<Tooltip
|
||||
@@ -148,8 +152,8 @@ export const UserTable: React.FC<UserTableProps> = ({
|
||||
</Tooltip>
|
||||
</div>
|
||||
</TableColumn>
|
||||
<TableColumn>{t("Balance")}</TableColumn>
|
||||
<TableColumn>{t("Actions")}</TableColumn>
|
||||
<TableColumn width={120}>{t("Balance")}</TableColumn>
|
||||
<TableColumn width={100}>{t("Actions")}</TableColumn>
|
||||
</TableHeader>
|
||||
<TableBody
|
||||
items={items}
|
||||
@@ -185,7 +189,15 @@ export const UserTable: React.FC<UserTableProps> = ({
|
||||
</Select>
|
||||
</TableCell>
|
||||
<TableCell>{formatDate(user.created_at)}</TableCell>
|
||||
<TableCell>{user.balance.toFixed(2) || "-"}</TableCell>
|
||||
<TableCell>
|
||||
<Link
|
||||
href="#"
|
||||
className="text-xs cursor-pointer"
|
||||
onPress={() => viewUserBalanceDetail(user)}
|
||||
>
|
||||
{user.balance.toFixed(2) || "-"}
|
||||
</Link>
|
||||
</TableCell>
|
||||
|
||||
<TableCell>
|
||||
<div className="relative flex items-center gap-2">
|
||||
|
||||
@@ -78,15 +78,15 @@ export const useMCPServicesList = () => {
|
||||
|
||||
// load servers list when component mount
|
||||
useEffect(() => {
|
||||
loadServices(1);
|
||||
loadServices(1, searchTerm, statusFilter);
|
||||
}, []); // only execute once when component mount
|
||||
|
||||
// pagination
|
||||
const handlePageChange = useCallback(
|
||||
(page: number) => {
|
||||
loadServices(page);
|
||||
loadServices(page, searchTerm, statusFilter);
|
||||
},
|
||||
[loadServices]
|
||||
[loadServices, searchTerm, statusFilter]
|
||||
);
|
||||
|
||||
// search
|
||||
@@ -156,7 +156,7 @@ export const useMCPServicesList = () => {
|
||||
try {
|
||||
const result = await saveMCPService(data);
|
||||
|
||||
if (result) await loadServices(1);
|
||||
if (result) await loadServices(1, searchTerm, statusFilter);
|
||||
return result;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
@@ -167,7 +167,7 @@ export const useMCPServicesList = () => {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[loadServices]
|
||||
[loadServices, searchTerm, statusFilter]
|
||||
);
|
||||
|
||||
// update server
|
||||
@@ -180,7 +180,7 @@ export const useMCPServicesList = () => {
|
||||
const formDataWithId = { ...data, id: serviceId };
|
||||
const result = await saveMCPService(formDataWithId);
|
||||
|
||||
if (result) await loadServices(pagination.page);
|
||||
if (result) await loadServices(pagination.page, searchTerm, statusFilter);
|
||||
return result;
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
@@ -191,7 +191,7 @@ export const useMCPServicesList = () => {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[loadServices, pagination.page]
|
||||
[loadServices, pagination.page, searchTerm, statusFilter]
|
||||
);
|
||||
|
||||
// delete server
|
||||
@@ -205,7 +205,7 @@ export const useMCPServicesList = () => {
|
||||
|
||||
if (result) {
|
||||
// reload servers list
|
||||
await loadServices();
|
||||
await loadServices(pagination.page, searchTerm, statusFilter);
|
||||
}
|
||||
} catch (err) {
|
||||
const errorMessage =
|
||||
@@ -216,7 +216,7 @@ export const useMCPServicesList = () => {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[loadServices]
|
||||
[loadServices, pagination.page, searchTerm, statusFilter]
|
||||
);
|
||||
|
||||
// toggle server status
|
||||
|
||||
@@ -14,6 +14,9 @@ export const useRevenueManagement = () => {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [statusFilter, setStatusFilter] = useState("all");
|
||||
const [paymentTypeFilter, setPaymentTypeFilter] = useState("all"); // 付款方式筛选
|
||||
const [sortBy, setSortBy] = useState<string | undefined>(undefined); // 排序字段
|
||||
const [sortOrder, setSortOrder] = useState<'asc' | 'desc' | undefined>(undefined); // 排序顺序
|
||||
const [pagination, setPagination] = useState<PaginationInfo>({
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
@@ -30,6 +33,9 @@ export const useRevenueManagement = () => {
|
||||
page_size: pagination.pageSize,
|
||||
search: searchQuery,
|
||||
status: statusFilter === "all" ? undefined : statusFilter,
|
||||
payment_type: paymentTypeFilter === "all" ? undefined : paymentTypeFilter,
|
||||
sort_by: sortBy,
|
||||
sort_order: sortOrder,
|
||||
});
|
||||
|
||||
if (response.success && response.data) {
|
||||
@@ -52,7 +58,7 @@ export const useRevenueManagement = () => {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [pagination.page, pagination.pageSize, searchQuery, statusFilter]);
|
||||
}, [pagination.page, pagination.pageSize, searchQuery, statusFilter, paymentTypeFilter, sortBy, sortOrder]);
|
||||
|
||||
const setSearch = useCallback((search: string) => {
|
||||
setSearchQuery(search);
|
||||
@@ -72,6 +78,17 @@ export const useRevenueManagement = () => {
|
||||
setPagination((prev) => ({ ...prev, pageSize, page: 1 }));
|
||||
}, []);
|
||||
|
||||
const setPaymentType = useCallback((paymentType: string) => {
|
||||
setPaymentTypeFilter(paymentType);
|
||||
setPagination((prev) => ({ ...prev, page: 1 })); // reset to first page
|
||||
}, []);
|
||||
|
||||
const setSort = useCallback((field: string | undefined, order: 'asc' | 'desc' | undefined) => {
|
||||
setSortBy(field);
|
||||
setSortOrder(order);
|
||||
setPagination((prev) => ({ ...prev, page: 1 })); // reset to first page
|
||||
}, []);
|
||||
|
||||
// initial load and pagination change
|
||||
useEffect(() => {
|
||||
fetchRevenues();
|
||||
@@ -83,10 +100,15 @@ export const useRevenueManagement = () => {
|
||||
error,
|
||||
searchQuery,
|
||||
statusFilter,
|
||||
paymentTypeFilter,
|
||||
sortBy,
|
||||
sortOrder,
|
||||
pagination,
|
||||
fetchRevenues,
|
||||
setSearch,
|
||||
setStatus,
|
||||
setPaymentType,
|
||||
setSort,
|
||||
setPage,
|
||||
setPageSize,
|
||||
};
|
||||
|
||||
@@ -17,6 +17,7 @@ interface FetchServicesParams {
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
keyword?: string;
|
||||
tag?: string;
|
||||
}
|
||||
interface ServicesResponseData {
|
||||
services: ServiceData[];
|
||||
@@ -42,6 +43,7 @@ export async function fetchServices(
|
||||
page_size: _BasePageDetail.page_size,
|
||||
page: _BasePageDetail.page,
|
||||
keyword: "",
|
||||
tag: "",
|
||||
}
|
||||
): Promise<ServicesResponse> {
|
||||
// Build query parameters
|
||||
@@ -50,7 +52,7 @@ export async function fetchServices(
|
||||
if (params.page_size)
|
||||
queryParams.append("page_size", params.page_size.toString());
|
||||
if (params.keyword) queryParams.append("keyword", params.keyword);
|
||||
|
||||
if (params.tag) queryParams.append("tag", params.tag);
|
||||
const response = await fetchAPI<BaseMCPService[]>(
|
||||
`/api/web/mcp_services${queryParams.toString() ? "?" + queryParams.toString() : ""}`
|
||||
);
|
||||
@@ -99,3 +101,26 @@ export async function fetchServiceById(
|
||||
|
||||
return convertMcpService([response.data])[0];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Fetch tags list
|
||||
*/
|
||||
export async function fetchTagsList(
|
||||
): Promise<string[] | []> {
|
||||
const response = await fetchAPI<string[]>(
|
||||
`/api/web/mcp_tags`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.success) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return response.data || []
|
||||
}
|
||||
@@ -63,8 +63,8 @@ export const getMCPServiceList = async (
|
||||
const queryParams = new URLSearchParams({
|
||||
page: params.page.toString(),
|
||||
page_size: params.page_size.toString(),
|
||||
...(params.search && { search: params.search }),
|
||||
...(params.status && { status: params.status }),
|
||||
...(params.search && { keyword: params.search }),
|
||||
...(params.status && { filter_status: params.status }),
|
||||
});
|
||||
|
||||
const response = await fetchAdminAPI<MCPService[]>(
|
||||
|
||||
@@ -15,6 +15,9 @@ export interface GetRevenueListParams {
|
||||
user_id?: string;
|
||||
search?: string;
|
||||
status?: string;
|
||||
payment_type?: string; // 付款方式筛选
|
||||
sort_by?: string; // 排序字段
|
||||
sort_order?: 'asc' | 'desc'; // 排序顺序
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -29,8 +32,10 @@ export const getRevenueList = async (
|
||||
...(params.start_date && { start_date: params.start_date }),
|
||||
...(params.end_date && { end_date: params.end_date }),
|
||||
...(params.user_id && { user_id: params.user_id }),
|
||||
...(params.search && { search: params.search }),
|
||||
...(params.search && { keyword: params.search }),
|
||||
...(params.status && { status: params.status }),
|
||||
...(params.payment_type && { filter_payment_type: params.payment_type }),
|
||||
...(params.sort_by === 'amount' && params.sort_order && { sort_amount: params.sort_order }),
|
||||
});
|
||||
|
||||
const response = await fetchAdminAPI<RevenueRecord[]>(
|
||||
|
||||
@@ -28,7 +28,7 @@ export const getUserList = async (
|
||||
const queryParams = new URLSearchParams({
|
||||
page: params.page.toString(),
|
||||
page_size: params.page_size.toString(),
|
||||
...(params.search && { search: params.search }),
|
||||
...(params.search && { keyword: params.search }),
|
||||
...(params.status && { status: params.status }),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import {
|
||||
Navbar,
|
||||
NavbarContent,
|
||||
@@ -15,6 +15,7 @@ import { useAuth } from "@/shared/lib/useAuth";
|
||||
import { ArrowRightIcon } from "lucide-react";
|
||||
import { DynamicLogo } from "@/shared/components/DynamicLogo";
|
||||
import Link from "next/link";
|
||||
import { useSharedStore } from "../store/share";
|
||||
export type NavigationItem = {
|
||||
label: string;
|
||||
href: string;
|
||||
@@ -45,6 +46,13 @@ function NavigationClient({
|
||||
const { t } = useTranslation();
|
||||
const { handleLogin } = useAuth();
|
||||
|
||||
const [userToken, setUserToken] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const userToken = useSharedStore?.getState?.().user_token
|
||||
setUserToken(userToken);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Main Navigation */}
|
||||
@@ -97,9 +105,17 @@ function NavigationClient({
|
||||
{langNode ? (
|
||||
langNode
|
||||
) : (
|
||||
<Button onPress={handleLogin} variant="light">
|
||||
<b className="text-md"> {t("Sign In")}</b>
|
||||
</Button>
|
||||
<>
|
||||
{
|
||||
!userToken && (
|
||||
<>
|
||||
<Button onPress={handleLogin} variant="light">
|
||||
<b className="text-md"> {t("Sign In")}</b>
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Desktop Auth Button */}
|
||||
@@ -110,7 +126,7 @@ function NavigationClient({
|
||||
radius="full"
|
||||
onPress={onLogin || handleLogin}
|
||||
>
|
||||
<b className="text-md"> {t(signinText)}</b>
|
||||
<b className="text-md"> {userToken ? t("Dashboard") : t(signinText) }</b>
|
||||
<div className="w-8 h-8 bg-gradient-to-r from-primary to-[#9ab0f2] flex items-center justify-center rounded-full">
|
||||
<ArrowRightIcon
|
||||
size={16}
|
||||
@@ -128,7 +144,7 @@ function NavigationClient({
|
||||
onPress={onLogin || handleLogin}
|
||||
size="sm"
|
||||
>
|
||||
<b className="text-md"> {t(signinText)}</b>
|
||||
<b className="text-md"> {userToken ? t("Dashboard") : t(signinText) }</b>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
@@ -156,7 +172,7 @@ function NavigationClient({
|
||||
radius="full"
|
||||
onPress={onLogin || handleLogin}
|
||||
>
|
||||
<b className="text-md"> {t(signinText)}</b>
|
||||
<b className="text-md"> {userToken ? t("Dashboard") : t(signinText) }</b>
|
||||
<div className="w-8 h-8 bg-gradient-to-r from-primary to-[#9ab0f2] flex items-center justify-center rounded-full">
|
||||
<ArrowRightIcon
|
||||
size={16}
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
|
||||
interface HeroSectionProps {
|
||||
searchQuery: string;
|
||||
isTagBarDisplay: boolean;
|
||||
onSearchChange: (value: string) => void;
|
||||
onSearch?: () => void;
|
||||
searchSuggestions?: string[];
|
||||
@@ -16,6 +17,7 @@ interface HeroSectionProps {
|
||||
|
||||
export const HeroSection: React.FC<HeroSectionProps> = ({
|
||||
searchQuery,
|
||||
isTagBarDisplay,
|
||||
onSearchChange,
|
||||
onSearch,
|
||||
searchSuggestions = [],
|
||||
@@ -77,7 +79,7 @@ export const HeroSection: React.FC<HeroSectionProps> = ({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative overflow-hidden mx-auto p-6 py-24 max-w-7xl">
|
||||
<div className={`relative overflow-hidden mx-auto p-6 ${isTagBarDisplay ? 'py-12' : 'py-24'} max-w-7xl`}>
|
||||
<div className="text-center mb-12">
|
||||
<h1 className="text-5xl lg:text-6xl font-bold mb-6 leading-tight">
|
||||
{t(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import { Card, Chip, Button, Select, SelectItem } from "@nextui-org/react";
|
||||
import { FlipButton } from "@/shared/components/FlipButton";
|
||||
import { useAuth } from "@/shared/lib/useAuth";
|
||||
@@ -9,7 +9,16 @@ import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
|
||||
import { Copy } from "lucide-react";
|
||||
import { copyToClipboard } from "@/shared/utils/clipboard";
|
||||
import toast from "react-hot-toast";
|
||||
import { useSharedStore } from "@/shared/store/share";
|
||||
import { fetchAPI } from "@/shared/rpc/common-function";
|
||||
import i18n from "@/shared/lib/i18n";
|
||||
|
||||
type apiKeyList = {
|
||||
name: string;
|
||||
apikey: string;
|
||||
create_time: string;
|
||||
apikey_id: number;
|
||||
}
|
||||
interface ServerConfigProps {
|
||||
mcpName?: string;
|
||||
url?: string;
|
||||
@@ -20,6 +29,18 @@ interface ServerConfigProps {
|
||||
|
||||
type McpType = "sse" | "streamable-http";
|
||||
|
||||
// 辅助函数:将 API Key 掩码显示,只保留前2位和后4位
|
||||
const maskApiKey = (apiKey: string): string => {
|
||||
if (!apiKey || apiKey.length <= 6) {
|
||||
return apiKey; // 如果太短就直接返回
|
||||
}
|
||||
const prefix = apiKey.slice(0, 2);
|
||||
const suffix = apiKey.slice(-4);
|
||||
const maskedLength = apiKey.length - 6;
|
||||
const masked = '*'.repeat(maskedLength);
|
||||
return `${prefix}${masked}${suffix}`;
|
||||
};
|
||||
|
||||
export const ServerConfig: React.FC<ServerConfigProps> = ({
|
||||
mcpName,
|
||||
url = process.env.NEXT_PUBLIC_MCP_URL,
|
||||
@@ -31,6 +52,49 @@ export const ServerConfig: React.FC<ServerConfigProps> = ({
|
||||
const { handleLogin } = useAuth();
|
||||
const { platformConfig } = usePlatformConfig();
|
||||
const [mcpType, setMcpType] = useState<McpType>("sse");
|
||||
// API Key List
|
||||
const [apiKeys, setApiKeys] = useState<{ key: string, label: string }[]>([]);
|
||||
// Selected API Key
|
||||
const [selectedApiKey, setSelectedApiKey] = useState<string | null>(null);
|
||||
// User Token
|
||||
const [userToken, setUserToken] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
const userToken = useSharedStore?.getState?.().user_token
|
||||
setUserToken(userToken);
|
||||
if (userToken) {
|
||||
const data = await fetchApiKeys()
|
||||
if (data.length > 0) {
|
||||
setApiKeys(data.map((item) => ({
|
||||
key: item.apikey,
|
||||
label: item.name,
|
||||
})));
|
||||
setSelectedApiKey(data[0].apikey)
|
||||
}
|
||||
}
|
||||
}
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
const fetchApiKeys = useCallback(
|
||||
async (
|
||||
): Promise<apiKeyList[]> => {
|
||||
try {
|
||||
|
||||
const response = await fetchAPI<apiKeyList[]>('/api/apikey/list');
|
||||
if (!response.success) {
|
||||
toast.error(response.error_message || i18n.t("Failed to load api keys"));
|
||||
return []
|
||||
}
|
||||
return response.data || []
|
||||
} catch (error) {
|
||||
console.error("Error fetching api keys:", error);
|
||||
return []
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const mcpTypeOptions = [
|
||||
{ key: "sse", label: "SSE (Server-Sent Events)" },
|
||||
@@ -40,8 +104,8 @@ export const ServerConfig: React.FC<ServerConfigProps> = ({
|
||||
const getCodeContent = () => {
|
||||
const serverUrl =
|
||||
mcpType === "streamable-http"
|
||||
? `${url}/streamable-http?authkey={Your-${platformConfig?.name}-Auth-Key}`
|
||||
: `${url}?authkey={Your-${platformConfig?.name}-Auth-Key}`;
|
||||
? `${url}/streamable-http?authkey=${selectedApiKey ? selectedApiKey : `{Your-${platformConfig?.name}-Auth-Key}`}`
|
||||
: `${url}?authkey=${selectedApiKey ? selectedApiKey : `{Your-${platformConfig?.name}-Auth-Key}`}`;
|
||||
|
||||
return `{
|
||||
"mcpServers": {
|
||||
@@ -63,16 +127,62 @@ export const ServerConfig: React.FC<ServerConfigProps> = ({
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateNewAuthorization = () => {
|
||||
sessionStorage.setItem('create_new_authorization', 'true');
|
||||
handleLogin()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`min-w-full ${className} flex-shrink-0`}>
|
||||
<div className="mb-2 mt-1">
|
||||
{
|
||||
visitor || can_invoke ? <>
|
||||
<FlipButton
|
||||
className="w-full rounded-md"
|
||||
text={t("Sign up to get the auth key")}
|
||||
onPress={handleLogin}
|
||||
/>
|
||||
{
|
||||
!userToken ? <>
|
||||
<FlipButton
|
||||
className="w-full rounded-md"
|
||||
text={t("Sign up to get the auth key")}
|
||||
onPress={handleLogin}
|
||||
/>
|
||||
</> : <>
|
||||
{
|
||||
apiKeys.length ?
|
||||
<>
|
||||
<Select
|
||||
label={t("Auth Key")}
|
||||
placeholder={t("Auth Key Name")}
|
||||
selectedKeys={selectedApiKey ? [selectedApiKey] : []}
|
||||
onSelectionChange={(keys) => {
|
||||
const selectedKey = Array.from(keys)[0] as string;
|
||||
setSelectedApiKey(selectedKey);
|
||||
}}
|
||||
className="w-full"
|
||||
size="sm"
|
||||
classNames={{
|
||||
trigger: " bg-black text-white data-[hover=true]:bg-dark-200",
|
||||
label: "!text-default-200",
|
||||
value: "!text-white",
|
||||
popoverContent: "bg-black text-white",
|
||||
}}
|
||||
>
|
||||
{apiKeys.map((option) => (
|
||||
<SelectItem key={option.key} value={option.key}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</Select>
|
||||
</>
|
||||
:
|
||||
<>
|
||||
<FlipButton
|
||||
className="w-full rounded-md"
|
||||
text={t("Create New Authorization")}
|
||||
onPress={handleCreateNewAuthorization}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
</>
|
||||
}
|
||||
</> : <>
|
||||
<div className="w-full rounded-lg bg-[#F3126033] md:pr-2 h-[40px] md:h-[50px] shadow-lg flex items-center justify-center">
|
||||
<p className="text-[#C20E4D] text-center font-bold text-lg leading-none">
|
||||
@@ -140,7 +250,7 @@ export const ServerConfig: React.FC<ServerConfigProps> = ({
|
||||
{mcpType === "streamable-http"
|
||||
? `${url}/streamable-http?authkey=`
|
||||
: `${url}?authkey=`}
|
||||
<span className="text-success">{`{Your-${platformConfig?.name}-Auth-Key}`}</span>
|
||||
<span className="text-success">{selectedApiKey ? maskApiKey(selectedApiKey) : `{Your-${platformConfig?.name}-Auth-Key}`}</span>
|
||||
{`"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect, useRef } from "react";
|
||||
import {
|
||||
Modal,
|
||||
ModalContent,
|
||||
ModalHeader,
|
||||
ModalBody,
|
||||
ModalFooter,
|
||||
Button,
|
||||
} from "@nextui-org/react";
|
||||
import { Theme, ThemeType } from "@/shared/types/system";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface TagFilterProps {
|
||||
tags: string[];
|
||||
theme: ThemeType;
|
||||
selectedTag: string;
|
||||
onTagChange: (tag: string) => void;
|
||||
maxWidthPercent?: number; // 最大宽度百分比,默认80%
|
||||
}
|
||||
|
||||
export const TagFilter: React.FC<TagFilterProps> = ({
|
||||
tags,
|
||||
theme,
|
||||
selectedTag,
|
||||
onTagChange,
|
||||
maxWidthPercent = 80,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
// 是否打开标签筛选弹窗
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
// 临时选中的标签
|
||||
const [tempSelectedTag, setTempSelectedTag] = useState<string | null>(null);
|
||||
// 可见的标签
|
||||
const [visibleTags, setVisibleTags] = useState<string[]>(["ALL", ...tags]);
|
||||
// 是否显示更多按钮
|
||||
const [showMore, setShowMore] = useState(false);
|
||||
// 从弹窗选择的额外标签
|
||||
const [extraTag, setExtraTag] = useState<string | null>(null);
|
||||
// 容器引用
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
// 标签容器引用
|
||||
const tagsContainerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
|
||||
// 根据主题获取颜色配置
|
||||
const getThemeColors = () => {
|
||||
switch (theme) {
|
||||
case Theme.DEFAULT:
|
||||
case Theme.MODERN:
|
||||
return {
|
||||
selected: "bg-[#C8DCFF] text-[#1E40AF]",
|
||||
unselected: "text-gray-700 hover:bg-gray-200",
|
||||
shadow: "shadow-lg shadow-[#C8DCFF]/50",
|
||||
};
|
||||
case Theme.CLASSIC:
|
||||
return {
|
||||
selected: "bg-[#475569] text-white",
|
||||
unselected: "text-gray-700 hover:bg-gray-200",
|
||||
shadow: "shadow-lg shadow-[#475569]/50",
|
||||
};
|
||||
case Theme.TEMU:
|
||||
return {
|
||||
selected: "bg-[#F97316] text-white",
|
||||
unselected: "text-gray-700 hover:bg-gray-200",
|
||||
shadow: "shadow-lg shadow-[#F97316]/50",
|
||||
};
|
||||
case Theme.CREATIVE:
|
||||
return {
|
||||
selected: "to-orange-500 via-red-500 from-pink-500 bg-gradient-to-r text-white",
|
||||
unselected: "text-gray-700 hover:bg-gray-200",
|
||||
shadow: "shadow-lg shadow-[#EF5082]/50",
|
||||
};
|
||||
default:
|
||||
return {
|
||||
selected: "bg-[#C8DCFF] text-[#1E40AF]",
|
||||
unselected: "text-gray-700 hover:bg-gray-200",
|
||||
shadow: "shadow-lg shadow-[#C8DCFF]/50",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const themeColors = getThemeColors();
|
||||
|
||||
// 计算哪些标签可以显示
|
||||
useEffect(() => {
|
||||
const calculateVisibleTags = () => {
|
||||
if (!containerRef.current) return;
|
||||
|
||||
const containerWidth = containerRef.current.offsetWidth;
|
||||
const maxWidth = (containerWidth * maxWidthPercent) / 100;
|
||||
|
||||
// More按钮的宽度(估算)
|
||||
const moreButtonWidth = 80;
|
||||
|
||||
// 创建临时元素来测量标签宽度
|
||||
const tempDiv = document.createElement("div");
|
||||
tempDiv.style.position = "absolute";
|
||||
tempDiv.style.visibility = "hidden";
|
||||
tempDiv.style.whiteSpace = "nowrap";
|
||||
tempDiv.className = "px-6 py-2 rounded-full text-sm font-medium";
|
||||
document.body.appendChild(tempDiv);
|
||||
|
||||
let currentWidth = 0;
|
||||
const visible: string[] = ["ALL"];
|
||||
let needsMore = false;
|
||||
|
||||
// 先计算常规标签
|
||||
for (const tag of tags) {
|
||||
if (tag === extraTag) continue; // 跳过额外标签,稍后处理
|
||||
|
||||
tempDiv.textContent = tag;
|
||||
const tagWidth = tempDiv.offsetWidth; // 不加间距
|
||||
|
||||
if (currentWidth + tagWidth + moreButtonWidth > maxWidth) {
|
||||
needsMore = true;
|
||||
break;
|
||||
}
|
||||
|
||||
currentWidth += tagWidth;
|
||||
visible.push(tag);
|
||||
}
|
||||
|
||||
// 处理额外标签或当前选中的标签
|
||||
// 如果当前选中的标签不在可见列表中(除了ALL),需要作为额外标签显示
|
||||
const tagToShow = extraTag || (selectedTag !== "ALL" && !visible.includes(selectedTag) ? selectedTag : null);
|
||||
|
||||
if (tagToShow && tagToShow !== "ALL" && !visible.includes(tagToShow)) {
|
||||
tempDiv.textContent = tagToShow;
|
||||
const tagWidth = tempDiv.offsetWidth; // 不加间距
|
||||
|
||||
// 检查是否还有空间显示额外标签
|
||||
if (currentWidth + tagWidth + moreButtonWidth <= maxWidth) {
|
||||
// 空间足够,直接添加
|
||||
currentWidth += tagWidth;
|
||||
visible.push(tagToShow);
|
||||
} else {
|
||||
// 空间不够,替换掉最后一个常规标签(保留 ALL)
|
||||
if (visible.length > 1) {
|
||||
visible.pop(); // 移除最后一个标签
|
||||
visible.push(tagToShow); // 添加额外标签
|
||||
needsMore = true; // 确保显示 More 按钮
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
document.body.removeChild(tempDiv);
|
||||
|
||||
setVisibleTags(visible);
|
||||
setShowMore(needsMore);
|
||||
};
|
||||
|
||||
// 延迟执行以确保DOM已渲染
|
||||
setTimeout(calculateVisibleTags, 0);
|
||||
|
||||
// 监听窗口大小变化
|
||||
window.addEventListener("resize", calculateVisibleTags);
|
||||
return () => window.removeEventListener("resize", calculateVisibleTags);
|
||||
}, [tags, extraTag, selectedTag, maxWidthPercent]);
|
||||
|
||||
const handleTagClick = (tag: string) => {
|
||||
// 如果点击的是额外标签以外的标签,清除额外标签
|
||||
if (extraTag && tag !== extraTag) {
|
||||
setExtraTag(null);
|
||||
}
|
||||
onTagChange(tag);
|
||||
};
|
||||
|
||||
const handleModalOpen = () => {
|
||||
// 打开弹窗时,初始化临时选中的标签为当前选中的标签
|
||||
setTempSelectedTag(selectedTag);
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleModalConfirm = () => {
|
||||
if (tempSelectedTag) {
|
||||
// 如果选择的是 ALL 或者已经在可见标签中的标签,不设置为额外标签
|
||||
if (tempSelectedTag === "ALL" || visibleTags.includes(tempSelectedTag)) {
|
||||
setExtraTag(null);
|
||||
} else {
|
||||
// 否则设置为额外标签
|
||||
setExtraTag(tempSelectedTag);
|
||||
}
|
||||
onTagChange(tempSelectedTag);
|
||||
}
|
||||
setIsModalOpen(false);
|
||||
};
|
||||
|
||||
const handleModalCancel = () => {
|
||||
setTempSelectedTag(null);
|
||||
setIsModalOpen(false);
|
||||
};
|
||||
|
||||
const handleModalTagClick = (tag: string) => {
|
||||
setTempSelectedTag(tag);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div ref={containerRef} className="w-full px-6 py-6">
|
||||
<div className="mx-auto max-w-7xl text-center">
|
||||
<div
|
||||
ref={tagsContainerRef}
|
||||
className="inline-flex items-center border-1 bg-[#fff] rounded-full transition-all duration-300"
|
||||
>
|
||||
{visibleTags.map((tag) => {
|
||||
const isSelected = selectedTag === tag;
|
||||
return (
|
||||
<button
|
||||
key={tag}
|
||||
onClick={() => handleTagClick(tag)}
|
||||
className={`
|
||||
px-6 py-2 rounded-full text-sm font-medium transition-all duration-200
|
||||
whitespace-nowrap
|
||||
${
|
||||
isSelected
|
||||
? `${themeColors.selected} ${themeColors.shadow}`
|
||||
: themeColors.unselected
|
||||
}
|
||||
`}
|
||||
>
|
||||
{tag}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
|
||||
{showMore && (
|
||||
<button
|
||||
onClick={handleModalOpen}
|
||||
className="px-4 py-2 text-sm font-medium text-blue-500 hover:text-blue-600 transition-colors whitespace-nowrap"
|
||||
>
|
||||
More
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* More Modal */}
|
||||
<Modal
|
||||
isOpen={isModalOpen}
|
||||
onClose={handleModalCancel}
|
||||
size="2xl"
|
||||
scrollBehavior="inside"
|
||||
>
|
||||
<ModalContent>
|
||||
<ModalHeader className="flex flex-col gap-1">
|
||||
Tag Filter
|
||||
</ModalHeader>
|
||||
<ModalBody>
|
||||
<div className="flex flex-wrap gap-3 py-4">
|
||||
<button
|
||||
onClick={() => handleModalTagClick("ALL")}
|
||||
className={`
|
||||
px-6 py-2 rounded-full text-sm font-medium transition-all duration-200
|
||||
${
|
||||
tempSelectedTag === "ALL"
|
||||
? "bg-blue-500 text-white shadow-lg shadow-blue-500/50"
|
||||
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||
}
|
||||
`}
|
||||
>
|
||||
ALL
|
||||
</button>
|
||||
|
||||
{tags.map((tag) => {
|
||||
const isSelected = tempSelectedTag === tag;
|
||||
return (
|
||||
<button
|
||||
key={tag}
|
||||
onClick={() => handleModalTagClick(tag)}
|
||||
className={`
|
||||
px-6 py-2 rounded-full text-sm font-medium transition-all duration-200
|
||||
${
|
||||
isSelected
|
||||
? "bg-blue-500 text-white shadow-lg shadow-blue-500/50"
|
||||
: "bg-gray-100 text-gray-700 hover:bg-gray-200"
|
||||
}
|
||||
`}
|
||||
>
|
||||
{tag}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button
|
||||
color="default"
|
||||
variant="light"
|
||||
onPress={handleModalCancel}
|
||||
>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
color="primary"
|
||||
onPress={handleModalConfirm}
|
||||
isDisabled={!tempSelectedTag}
|
||||
>
|
||||
{t("Confirm")}
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import React, { useState } from "react";
|
||||
import {
|
||||
Table,
|
||||
TableHeader,
|
||||
@@ -13,10 +13,14 @@ import {
|
||||
Tooltip,
|
||||
Pagination,
|
||||
Spinner,
|
||||
Dropdown,
|
||||
DropdownTrigger,
|
||||
DropdownMenu,
|
||||
DropdownItem,
|
||||
} from "@nextui-org/react";
|
||||
import { useTranslation } from "@/shared/lib/useTranslation";
|
||||
import { EnabledEnum, MCPService } from "@/shared/types/mcp-service";
|
||||
import { Trash2, PencilIcon, Calendar } from "lucide-react";
|
||||
import { Trash2, PencilIcon, Calendar, Filter } from "lucide-react";
|
||||
import { Price } from "@/shared/components/marketplace/Price";
|
||||
import { MdOutlineUnpublished, MdOutlineCheckCircle } from "react-icons/md";
|
||||
import { withComponentInjection } from "@/shared/hooks/useComponentInjection";
|
||||
@@ -33,6 +37,7 @@ interface ServiceTableProps {
|
||||
onDelete: (service: MCPService) => void;
|
||||
onToggleStatus: (serviceId: string) => void;
|
||||
onPageChange: (page: number) => void;
|
||||
onStatusFilterChange?: (status: string) => void;
|
||||
columns?: string[];
|
||||
}
|
||||
|
||||
@@ -44,9 +49,11 @@ const BaseServiceTable: React.FC<ServiceTableProps> = ({
|
||||
onDelete,
|
||||
onToggleStatus,
|
||||
onPageChange,
|
||||
onStatusFilterChange,
|
||||
columns = ["name", "endpoints", "status", "pricing", "actions"],
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [selectedStatusFilter, setSelectedStatusFilter] = useState('all');
|
||||
|
||||
const pages = Math.ceil(pagination.total / pagination.pageSize);
|
||||
const currentPage = pagination.page;
|
||||
@@ -78,6 +85,13 @@ const BaseServiceTable: React.FC<ServiceTableProps> = ({
|
||||
},
|
||||
[onToggleStatus]
|
||||
);
|
||||
|
||||
// 处理状态筛选
|
||||
const handleStatusFilterChange = React.useCallback((status: string) => {
|
||||
setSelectedStatusFilter(status);
|
||||
onStatusFilterChange?.(status);
|
||||
}, [onStatusFilterChange]);
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
@@ -122,7 +136,41 @@ const BaseServiceTable: React.FC<ServiceTableProps> = ({
|
||||
<TableHeader>
|
||||
<TableColumn>{t("Service Name")}</TableColumn>
|
||||
<TableColumn>{t("API Endpoint")}</TableColumn>
|
||||
<TableColumn>{t("Status")}</TableColumn>
|
||||
<TableColumn>
|
||||
<div className="flex items-center gap-2">
|
||||
<span>{t("Status")}</span>
|
||||
<Dropdown>
|
||||
<DropdownTrigger>
|
||||
<Button
|
||||
isIconOnly
|
||||
size="sm"
|
||||
variant="light"
|
||||
aria-label="Filter by status"
|
||||
className="min-w-unit-6 w-6 h-6"
|
||||
>
|
||||
<Filter
|
||||
className={`w-4 h-4 ${
|
||||
selectedStatusFilter !== 'all' ? 'text-primary' : ''
|
||||
}`}
|
||||
/>
|
||||
</Button>
|
||||
</DropdownTrigger>
|
||||
<DropdownMenu
|
||||
aria-label="Status filter"
|
||||
selectionMode="single"
|
||||
selectedKeys={[selectedStatusFilter]}
|
||||
onSelectionChange={(keys) => {
|
||||
const selected = Array.from(keys)[0] as string;
|
||||
handleStatusFilterChange(selected);
|
||||
}}
|
||||
>
|
||||
<DropdownItem key="all">{t('All')}</DropdownItem>
|
||||
<DropdownItem key="1">{t('Published')}</DropdownItem>
|
||||
<DropdownItem key="0">{t('Unpublished')}</DropdownItem>
|
||||
</DropdownMenu>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</TableColumn>
|
||||
<TableColumn hidden={!columns.includes("pricing")}>
|
||||
{t("Pricing")}
|
||||
</TableColumn>
|
||||
|
||||
@@ -10,6 +10,7 @@ export enum TabKey {
|
||||
OVERVIEW = "overview",
|
||||
WALLET = "wallet",
|
||||
ACCOUNT = "account",
|
||||
USER_ACCOUNT = "user-account",
|
||||
}
|
||||
|
||||
export interface SidebarSubItem {
|
||||
|
||||
@@ -31,6 +31,7 @@ export interface PlatformConfig {
|
||||
facebook_description?: string; // facebook description
|
||||
facebook_image_url?: string; // facebook image url
|
||||
meta_description?: string; // meta description
|
||||
tag_bar_display?: boolean; // whether to display tags bar
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
|
||||
+19
-5
@@ -1,7 +1,11 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
@@ -11,7 +15,7 @@
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve",
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
@@ -19,9 +23,19 @@
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
"@/*": [
|
||||
"./src/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
+1
-1
@@ -5,7 +5,7 @@ pydantic>=2.8.2
|
||||
python-dotenv>=1.0.1
|
||||
redis>=5.0.8
|
||||
pika>=1.3.2
|
||||
mysql-connector-python>=9.0.0
|
||||
pymysql>=1.1.0
|
||||
objtyping
|
||||
stripe>=5.0.0
|
||||
aiohttp>=3.8.0
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
INSERT INTO `sys_config` (`id`,`key`, `value`,`description`,`created_at`,`updated_at`)
|
||||
VALUES ('xpack-tag-bar-display','tag_bar_display', 'true', 'Display tag bar on the top of the page', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), `description` = VALUES(`description`), `updated_at` = CURRENT_TIMESTAMP;
|
||||
|
||||
|
||||
INSERT INTO `sys_config` (`id`,`key`, `value`,`description`,`created_at`,`updated_at`)
|
||||
VALUES ('xpack-version','version', '1.3.0', 'The user interface supports viewing the transaction list.', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), `description` = VALUES(`description`), `updated_at` = CURRENT_TIMESTAMP;
|
||||
@@ -7,6 +7,7 @@ KEY_SUBHEADLINE = "subheadline"
|
||||
KEY_LANGUAGE = "language"
|
||||
KEY_THEME = "theme"
|
||||
KEY_ABOUT_PAGE = "about_page"
|
||||
KEY_TAG_BAR_DISPLAY = "tag_bar_display"
|
||||
KEY_ADMIN_USERNAME = "admin_username"
|
||||
KEY_ADMIN_PASSWORD = "admin_password"
|
||||
KEY_LOGIN_GOOGLE_CLIENT = "login_google_client_id"
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import func
|
||||
from datetime import datetime, date
|
||||
|
||||
from yarl import Query
|
||||
from services.common.database import get_db
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from services.common.models.user import User
|
||||
from services.common.models.user_wallet import UserWallet
|
||||
from services.common.models.mcp_service import McpService
|
||||
from services.common.models.mcp_call_log import McpCallLog
|
||||
from services.admin_service.services.stats_service import StatsService
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.common import error_msg
|
||||
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -17,15 +19,28 @@ def get_stats_service(db: Session = Depends(get_db)) -> StatsService:
|
||||
|
||||
@router.get("/stats/analytics")
|
||||
async def stats(
|
||||
request: Request,
|
||||
start: int= 0,
|
||||
end: int=0,
|
||||
stats_service: StatsService = Depends(get_stats_service)
|
||||
):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
if end == 0:
|
||||
end = int(datetime.now().timestamp())
|
||||
if start == 0:
|
||||
# 30天前
|
||||
start = int(end - 30 * 24 * 60 * 60)
|
||||
|
||||
try:
|
||||
start_dt = datetime.fromtimestamp(start)
|
||||
end_dt = datetime.fromtimestamp(end)
|
||||
return ResponseUtils.success(
|
||||
{
|
||||
"user_register": stats_service.get_registered_user_stats(),
|
||||
"user_pay": stats_service.get_deposit_stats(),
|
||||
"mcp_call": stats_service.get_call_stats(),
|
||||
"top_services": stats_service.get_call_stats_group_by_service()
|
||||
"user_register": stats_service.get_registered_user_stats(start_dt, end_dt),
|
||||
"user_pay": stats_service.get_deposit_stats(start_dt, end_dt),
|
||||
"mcp_call": stats_service.get_call_stats(start_dt, end_dt),
|
||||
"top_services": stats_service.get_call_stats_group_by_service(start_dt, end_dt)
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
|
||||
@@ -6,6 +6,7 @@ from services.admin_service.services.auth_service import AuthService
|
||||
from services.admin_service.services.sys_config_service import SysConfigService
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.admin_service.constants import sys_config_key
|
||||
from services.common.utils.request_utils import RequestUtils
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -19,11 +20,13 @@ def get_sys_config_service(db: Session = Depends(get_db)) -> SysConfigService:
|
||||
|
||||
@router.post("/email/sign", response_model=dict)
|
||||
def email_login(
|
||||
request: Request,
|
||||
body: dict = Body(...),
|
||||
auth_service: AuthService = Depends(get_auth_service),
|
||||
sys_config_service: SysConfigService = Depends(get_sys_config_service),
|
||||
):
|
||||
"""Authenticate user via email and captcha code."""
|
||||
|
||||
email_is_enabled_raw = sys_config_service.get_value_by_key(sys_config_key.KEY_LOGIN_EMAIL_ENABLE) or "false"
|
||||
# Convert to boolean
|
||||
email_is_enabled = email_is_enabled_raw.lower() in ("true", "t", "yes", "y", "1")
|
||||
@@ -31,6 +34,13 @@ def email_login(
|
||||
return ResponseUtils.error(message="email login not enabled", code=400)
|
||||
email_mode = sys_config_service.get_value_by_key(sys_config_key.KEY_LOGIN_EMAIL_MODE) or "password"
|
||||
email = body.get("user_email")
|
||||
if not email:
|
||||
return ResponseUtils.error(message="email required", code=400)
|
||||
# Check IP ban
|
||||
ip = RequestUtils.get_client_ip(request)
|
||||
if auth_service.check_ip_ban(ip, email):
|
||||
return ResponseUtils.error(message="Login failed: You are banned due to too many failed attempts. Please try again in 5 minutes.", code=403)
|
||||
|
||||
token = None
|
||||
match email_mode:
|
||||
case "password":
|
||||
@@ -39,8 +49,10 @@ def email_login(
|
||||
return ResponseUtils.error(message="email and password required", code=400)
|
||||
token = auth_service.email_login_by_password(email=email, password=password)
|
||||
if token:
|
||||
auth_service.clear_login_fail(ip, email)
|
||||
return ResponseUtils.success({"user_token": token})
|
||||
else:
|
||||
auth_service.record_login_fail(ip, email)
|
||||
return ResponseUtils.error(message="login failed, please enter the correct account or password", code=401)
|
||||
case "captcha":
|
||||
captcha = body.get("captcha")
|
||||
@@ -48,8 +60,10 @@ def email_login(
|
||||
return ResponseUtils.error(message="email and captcha required", code=400)
|
||||
token = auth_service.email_login_by_captcha(email=email, captcha=captcha)
|
||||
if token:
|
||||
auth_service.clear_login_fail(ip, email)
|
||||
return ResponseUtils.success({"user_token": token})
|
||||
else:
|
||||
auth_service.record_login_fail(ip, email)
|
||||
return ResponseUtils.error(message="login failed, please enter the correct captcha", code=401)
|
||||
case _:
|
||||
return ResponseUtils.error(message="email login mode not supported", code=400)
|
||||
@@ -68,17 +82,27 @@ def email_login_send_captcha(body: dict = Body(...), auth_service: AuthService =
|
||||
|
||||
|
||||
@router.post("/account/sign", response_model=dict)
|
||||
def account_login(body: dict = Body(...), auth_service: AuthService = Depends(get_auth_service)):
|
||||
def account_login(request: Request, body: dict = Body(...), auth_service: AuthService = Depends(get_auth_service)):
|
||||
"""Authenticate user via username and password."""
|
||||
|
||||
name = body.get("name")
|
||||
if not name:
|
||||
return ResponseUtils.error(message="account required", code=400)
|
||||
# Check IP ban
|
||||
ip = RequestUtils.get_client_ip(request)
|
||||
if auth_service.check_ip_ban(ip, name):
|
||||
return ResponseUtils.error(message="Login failed: You are banned due to too many failed attempts. Please try again in 5 minutes.", code=403)
|
||||
|
||||
password = body.get("password")
|
||||
if not name or not password:
|
||||
return ResponseUtils.error(message="account and password required", code=400)
|
||||
token = auth_service.account_login(name, password)
|
||||
if token:
|
||||
auth_service.clear_login_fail(ip, name)
|
||||
return ResponseUtils.success({"user_token": token})
|
||||
else:
|
||||
return ResponseUtils.error(message="login failed", code=401)
|
||||
auth_service.record_login_fail(ip, name)
|
||||
return ResponseUtils.error(message="login failed, please enter the correct account or password", code=401)
|
||||
|
||||
|
||||
@router.post("/google/sign", response_model=dict)
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
# Read config from sys_config table, key is configured in services/admin_service/constants/sys_config_key.py
|
||||
|
||||
import logging
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
import json
|
||||
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.admin_service.services.sys_config_service import SysConfigService
|
||||
from services.admin_service.constants.sys_config_key import *
|
||||
from services.admin_service.services.payment_channel_service import PaymentChannelService
|
||||
@@ -16,9 +18,12 @@ router = APIRouter()
|
||||
|
||||
@router.get("/config", summary="Get configuration (no login required)", tags=["common"])
|
||||
def get_config(
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get platform configuration settings without authentication."""
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
try:
|
||||
# Create service instance
|
||||
sys_config_service = SysConfigService(db)
|
||||
@@ -67,6 +72,7 @@ def get_config(
|
||||
"facebook_image_url": values.get(KEY_FACEBOOK_IMAGE_URL, ""),
|
||||
"social_account_facebook_url": values.get(KEY_SOCIAL_ACCOUNT_FACEBOOK_URL, ""),
|
||||
"social_account_x_url": values.get(KEY_SOCIAL_ACCOUNT_X_URL, ""),
|
||||
"tag_bar_display": values.get(KEY_TAG_BAR_DISPLAY, "false").lower() in ("true", "t", "yes", "y", "1"),
|
||||
},
|
||||
"faq": faq,
|
||||
"embeded_html": embeded_html,
|
||||
@@ -80,8 +86,13 @@ def get_config(
|
||||
return ResponseUtils.error(message="Failed to get configuration")
|
||||
|
||||
@router.get("/homepage", summary="Get homepage configuration (no login required)", tags=["common"])
|
||||
def get_homepage_config(db: Session = Depends(get_db)):
|
||||
def get_homepage_config(
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get homepage configuration settings without authentication."""
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
try:
|
||||
# Create service instance
|
||||
sys_config_service = SysConfigService(db)
|
||||
|
||||
@@ -90,7 +90,9 @@ def update_mcp_service_info(request: Request, body: dict = Body(...), mcp_manage
|
||||
|
||||
|
||||
@router.delete("/service", summary="Delete MCP service")
|
||||
def delete_mcp_service(body: dict = Body(...), mcp_manager_service: McpManagerService = Depends(get_mcp_manager)):
|
||||
def delete_mcp_service(request: Request, body: dict = Body(...), mcp_manager_service: McpManagerService = Depends(get_mcp_manager)):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
"""Delete MCP service by ID."""
|
||||
id = body.get("id")
|
||||
if not id:
|
||||
@@ -102,11 +104,14 @@ def delete_mcp_service(body: dict = Body(...), mcp_manager_service: McpManagerSe
|
||||
|
||||
@router.post("/openapi_parse", summary="openapi import", response_model=dict)
|
||||
async def openapi_parse(
|
||||
request: Request,
|
||||
url: Optional[HttpUrl] = Form(None, description="OpenAPI document URL (optional)"),
|
||||
file: Optional[UploadFile] = File(None, description="OpenAPI document file (JSON/YAML, optional)"),
|
||||
mcp_manager_service: McpManagerService = Depends(get_mcp_manager),
|
||||
):
|
||||
"""Parse and import OpenAPI document from URL or file upload."""
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
try:
|
||||
if url:
|
||||
url_str = str(url)
|
||||
@@ -197,16 +202,18 @@ def get_mcp_service_info(request: Request, id: str, mcp_manager_service: McpMana
|
||||
|
||||
@router.get("/service/list", summary="Get MCP service list")
|
||||
def get_mcp_service_list(
|
||||
request: Request, page: int = 1, page_size: int = 10, mcp_manager_service: McpManagerService = Depends(get_mcp_manager)
|
||||
request: Request, page: int = 1, page_size: int = 10,keyword: str = "",filter_status: str = "", mcp_manager_service: McpManagerService = Depends(get_mcp_manager)
|
||||
):
|
||||
"""Get paginated list of all MCP services."""
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
|
||||
status = None
|
||||
if filter_status:
|
||||
status = filter_status.split(",")
|
||||
try:
|
||||
# Fetch paginated data
|
||||
try:
|
||||
services, total = mcp_manager_service.get_all_paginated(page=page, page_size=page_size)
|
||||
services, total = mcp_manager_service.get_all_paginated(page=page, page_size=page_size,keyword=keyword,filter_status=status)
|
||||
except AttributeError:
|
||||
# Fallback to non-paginated method when missing
|
||||
all_services = mcp_manager_service.get_all()
|
||||
@@ -270,6 +277,20 @@ def get_mcp_service_simple_list(
|
||||
logger.error(f"Failed to get service simple list: {str(e)}")
|
||||
return ResponseUtils.error(error_msg=error_msg.INTERNAL_ERROR)
|
||||
|
||||
@router.get("/service/tags", summary="Get MCP service tags")
|
||||
def get_mcp_service_tags(
|
||||
request: Request,
|
||||
mcp_manager_service: McpManagerService = Depends(get_mcp_manager),
|
||||
):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
try:
|
||||
tags = mcp_manager_service.get_tags_list(enabled_only=False)
|
||||
return ResponseUtils.success(data=tags)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to get service tags: {str(e)}")
|
||||
return ResponseUtils.error(error_msg=error_msg.INTERNAL_ERROR)
|
||||
|
||||
@router.get("/service/resource_group/list", summary="Get MCP service's resource group list")
|
||||
def get_mcp_service_resource_group_list(
|
||||
request: Request,
|
||||
@@ -360,4 +381,4 @@ def unbind_group(
|
||||
return ResponseUtils.success()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to unbind resource groups: {str(e)}")
|
||||
return ResponseUtils.error(error_msg=error_msg.INTERNAL_ERROR)
|
||||
return ResponseUtils.error(error_msg=error_msg.INTERNAL_ERROR)
|
||||
@@ -1,10 +1,13 @@
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from typing import Optional, List
|
||||
from fastapi import APIRouter, Depends, Query, Request
|
||||
from sqlalchemy import table
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.database import get_db
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from services.admin_service.services.user_service import UserService
|
||||
from services.admin_service.services.user_wallet_history_service import UserWalletHistoryService
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.common import error_msg
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -19,14 +22,24 @@ def get_user_service(db: Session = Depends(get_db)) -> UserService:
|
||||
|
||||
@router.get("/list", summary="Get user order list")
|
||||
def get_user_order_list(
|
||||
request: Request,
|
||||
page: int = Query(1, description="Current page number"),
|
||||
page_size: int = Query(15, description="Number of items per page"),
|
||||
keyword: str = Query("", description="Search keyword for user email or name"),
|
||||
sort_amount: str = Query("desc", description="Sort amount by desc or asc"),
|
||||
filter_payment_type: str = Query("", description="Filter payment type"),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
user_wallet_history_service: UserWalletHistoryService = Depends(get_user_wallet_history_service),
|
||||
):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
"""Get paginated list of user order history."""
|
||||
offset = (page - 1) * page_size
|
||||
total, orders = user_wallet_history_service.success_deposit_order_list(offset, page_size)
|
||||
if filter_payment_type:
|
||||
filter_payment_type_list = filter_payment_type.split(",")
|
||||
else:
|
||||
filter_payment_type_list = None
|
||||
total, orders = user_wallet_history_service.success_deposit_order_list(offset, page_size, keyword, sort_amount, filter_payment_type_list)
|
||||
if not orders:
|
||||
return ResponseUtils.success_page(data=[], total=total, page_num=page, page_size=page_size)
|
||||
result = []
|
||||
@@ -52,3 +65,42 @@ def get_user_order_list(
|
||||
)
|
||||
|
||||
return ResponseUtils.success_page(data=result, total=total, page_num=page, page_size=page_size)
|
||||
|
||||
@router.get("/list/by_user", summary="Get user order list by user id")
|
||||
def get_user_order_list_by_user_id(
|
||||
request: Request,
|
||||
user_id: str = Query(..., description="User ID"),
|
||||
page: int = Query(1, description="Current page number"),
|
||||
page_size: int = Query(15, description="Number of items per page"),
|
||||
order_type: Optional[str] = Query(None, description="Order type"),
|
||||
status: Optional[str] = Query(None, description="Order status"),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
user_wallet_history_service: UserWalletHistoryService = Depends(get_user_wallet_history_service),
|
||||
):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
"""Get paginated list of user order history by user id."""
|
||||
user = user_service.get_by_id(user_id)
|
||||
if not user:
|
||||
return ResponseUtils.error(message="not found user", code=404)
|
||||
offset = (page - 1) * page_size
|
||||
order_type_list = []
|
||||
if order_type:
|
||||
# 将字符串转成列表,中间使用逗号分隔
|
||||
ots = order_type.split(",")
|
||||
for ot in ots:
|
||||
ot = ot.strip()
|
||||
if ot == "purchase":
|
||||
order_type_list.append("api_call")
|
||||
elif ot == "recharge":
|
||||
order_type_list.append("deposit")
|
||||
else:
|
||||
order_type_list.append(ot)
|
||||
status_list: Optional[List[int]] = []
|
||||
if status:
|
||||
sl = status.split(",")
|
||||
for s in sl:
|
||||
status_list.append(int(s.strip()))
|
||||
total, orders = user_wallet_history_service.success_order_list_by_user(user_id, offset, page_size, order_type_list, status_list)
|
||||
|
||||
return ResponseUtils.success_page(data=orders, total=total, page_num=page, page_size=page_size)
|
||||
@@ -7,6 +7,8 @@ from services.common.utils.response_utils import ResponseUtils
|
||||
from services.admin_service.services.payment_service import PaymentService
|
||||
from services.admin_service.services.user_wallet_history_service import UserWalletHistoryService
|
||||
from services.admin_service.tasks.order_monitor_task import OrderMonitorTask
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.common import error_msg
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@@ -32,6 +34,8 @@ def create_payment_link(
|
||||
payment: PaymentService = Depends(get_payment),
|
||||
):
|
||||
"""Create Stripe payment link for the user."""
|
||||
if not UserUtils.is_normal_user(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
user = request.scope.get("user")
|
||||
if not user:
|
||||
return ResponseUtils.error(message="User not found", code=404)
|
||||
@@ -86,10 +90,13 @@ async def callback_stripe(
|
||||
|
||||
@router.get("/order_status", response_model=dict)
|
||||
async def order_status(
|
||||
request: Request,
|
||||
payment_id: str,
|
||||
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})
|
||||
return ResponseUtils.success({"status": 0})
|
||||
@@ -1,4 +1,4 @@
|
||||
from fastapi import APIRouter, Depends, Query, Body
|
||||
from fastapi import APIRouter, Depends, Query, Body, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from services.common.database import get_db
|
||||
@@ -6,7 +6,8 @@ from services.common.utils.response_utils import ResponseUtils
|
||||
from services.admin_service.services.payment_channel_service import PaymentChannelService
|
||||
from services.common.utils.secure_config import decrypt_config, encrypt_config
|
||||
from services.admin_service.tasks.order_monitor_task import OrderMonitorTask
|
||||
import json
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.common import error_msg
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -17,10 +18,13 @@ def get_payment_channel(db: Session = Depends(get_db)) -> PaymentChannelService:
|
||||
|
||||
@router.get("/list")
|
||||
async def payment_channel_list(
|
||||
request: Request,
|
||||
page: int = Query(1, description="Current page number"),
|
||||
page_size: int = Query(15, description="Number of items per page"),
|
||||
payment_channel_service: PaymentChannelService = Depends(get_payment_channel),
|
||||
):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
"""Get paginated list of payment channels."""
|
||||
total, list = payment_channel_service.list()
|
||||
if total == 0:
|
||||
@@ -45,9 +49,12 @@ async def payment_channel_list(
|
||||
|
||||
@router.put("/enable")
|
||||
async def payment_channel_enable(
|
||||
request: Request,
|
||||
payment_channel_service: PaymentChannelService = Depends(get_payment_channel),
|
||||
body: dict = Body(..., description="Payment channel configuration"),
|
||||
):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
"""Enable a payment channel by ID."""
|
||||
id = body.get("id")
|
||||
if not id:
|
||||
@@ -103,9 +110,12 @@ async def payment_channel_disable(
|
||||
|
||||
@router.put("/info")
|
||||
async def payment_channel_config(
|
||||
request: Request,
|
||||
payment_channel_service: PaymentChannelService = Depends(get_payment_channel),
|
||||
body: dict = Body(..., description="Payment channel configuration"),
|
||||
):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
"""Update payment channel configuration."""
|
||||
id = body.get("id")
|
||||
if not id:
|
||||
|
||||
@@ -8,7 +8,7 @@ from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.common import error_msg
|
||||
from services.admin_service.services.resource_group_service import ResourceGroupService
|
||||
from services.admin_service.services.sys_config_service import SysConfigService
|
||||
|
||||
from services.admin_service.constants.sys_config_key import KEY_DEFAULT_RESOURCE_GROUP
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -24,7 +24,12 @@ def get_resource_group_service(db: Session = Depends(get_db)) -> ResourceGroupSe
|
||||
|
||||
|
||||
@router.post("", summary="Create resource group")
|
||||
def create_group(request: Request, body: dict = Body(...), svc: ResourceGroupService = Depends(get_resource_group_service)):
|
||||
def create_group(
|
||||
request: Request,
|
||||
body: dict = Body(...),
|
||||
svc: ResourceGroupService = Depends(get_resource_group_service),
|
||||
sys_svc: SysConfigService = Depends(get_sysconfig_service)
|
||||
):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
gid = body.get("id")
|
||||
@@ -36,20 +41,26 @@ def create_group(request: Request, body: dict = Body(...), svc: ResourceGroupSer
|
||||
return ResponseUtils.error(error_msg=error_msg.MISSING_PARAMETER)
|
||||
is_default = body.get("is_default", False)
|
||||
try:
|
||||
gid = svc.create_group(gid=gid, name=name, description=description, is_default=is_default)
|
||||
svc.create_group(gid=gid, name=name, description=description)
|
||||
if is_default:
|
||||
sys_svc.set_value_by_key(key=KEY_DEFAULT_RESOURCE_GROUP, value=gid, description="Default resource group")
|
||||
except ValueError as e:
|
||||
return ResponseUtils.error(message=str(e))
|
||||
|
||||
|
||||
return ResponseUtils.success(data={"id": gid})
|
||||
|
||||
|
||||
@router.put("", summary="Update resource group")
|
||||
def update_group(request: Request,id: str, body: dict = Body(...), svc: ResourceGroupService = Depends(get_resource_group_service)):
|
||||
def update_group(request: Request,id: str, body: dict = Body(...), svc: ResourceGroupService = Depends(get_resource_group_service), sys_svc: SysConfigService = Depends(get_sysconfig_service)):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
try:
|
||||
svc.update_group(id, body)
|
||||
ok = svc.update_group(id, body)
|
||||
if not ok:
|
||||
return ResponseUtils.error(code=400,message="Failed to update group, check the input data")
|
||||
is_default = body.get("is_default", False)
|
||||
if is_default:
|
||||
sys_svc.set_value_by_key(key=KEY_DEFAULT_RESOURCE_GROUP, value=id, description="Default resource group")
|
||||
return ResponseUtils.success()
|
||||
except ValueError as e:
|
||||
return ResponseUtils.error(message=str(e))
|
||||
@@ -59,7 +70,7 @@ def update_group(request: Request,id: str, body: dict = Body(...), svc: Resource
|
||||
|
||||
|
||||
@router.delete("", summary="Delete resource group")
|
||||
def delete_group(request: Request, id: str, migrate_id: str | None = None, svc: ResourceGroupService = Depends(get_resource_group_service)):
|
||||
def delete_group(request: Request, id: str, migrate_id: str | None = None, svc: ResourceGroupService = Depends(get_resource_group_service), sys_svc: SysConfigService = Depends(get_sysconfig_service)):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
if not id:
|
||||
@@ -68,6 +79,9 @@ def delete_group(request: Request, id: str, migrate_id: str | None = None, svc:
|
||||
ok = svc.delete_group(id, migrate_id)
|
||||
if not ok:
|
||||
return ResponseUtils.error(error_msg=error_msg.NOT_FOUND)
|
||||
default_group = sys_svc.get_value_by_key(KEY_DEFAULT_RESOURCE_GROUP)
|
||||
if id == default_group:
|
||||
sys_svc.set_value_by_key(key=KEY_DEFAULT_RESOURCE_GROUP, value="", description="Default resource group")
|
||||
return ResponseUtils.success()
|
||||
|
||||
|
||||
@@ -75,7 +89,9 @@ def delete_group(request: Request, id: str, migrate_id: str | None = None, svc:
|
||||
def get_group_info(request: Request, id: str, svc: ResourceGroupService = Depends(get_resource_group_service), sys_svc: SysConfigService = Depends(get_sysconfig_service)):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
info = svc.get_info(id)
|
||||
default_group = sys_svc.get_value_by_key(KEY_DEFAULT_RESOURCE_GROUP)
|
||||
|
||||
info = svc.get_info(id, default_group)
|
||||
if not info:
|
||||
return ResponseUtils.error(error_msg=error_msg.NOT_FOUND)
|
||||
return ResponseUtils.success(data=info)
|
||||
@@ -86,7 +102,8 @@ def get_group_list(request: Request, page: int = 1, page_size: int = 10, keyword
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
|
||||
groups, total = svc.list_groups(page=page, page_size=page_size, keyword=keyword)
|
||||
default_group = sys_svc.get_value_by_key(KEY_DEFAULT_RESOURCE_GROUP)
|
||||
groups, total = svc.list_groups(page=page, page_size=page_size, default_group=default_group, keyword=keyword)
|
||||
|
||||
return ResponseUtils.success_page(data=groups, page_num=page, page_size=page_size, total=total)
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
Provides endpoints to read and update platform configurations, homepage content,
|
||||
and to test email settings. All responses and comments are standardized in English.
|
||||
"""
|
||||
from fastapi import APIRouter, Depends, Body
|
||||
from fastapi import APIRouter, Depends, Body, Request
|
||||
import json
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.database import get_db
|
||||
@@ -11,6 +11,8 @@ from services.common.utils.response_utils import ResponseUtils
|
||||
from services.common.utils.email_utils import EmailUtils
|
||||
from services.admin_service.services.sys_config_service import SysConfigService
|
||||
from services.admin_service.services.user_service import UserService
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.common import error_msg
|
||||
from services.admin_service.services.platform_report_service import PlatformReportService
|
||||
from services.admin_service.constants import sys_config_key
|
||||
from services.common.logging_config import get_logger
|
||||
@@ -91,9 +93,12 @@ def update_homepage(
|
||||
|
||||
@router.get("/info")
|
||||
def get_sysconfig(
|
||||
request: Request,
|
||||
sysconfig_service: SysConfigService = Depends(get_sysconfig_service),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
"""Get all system configuration settings."""
|
||||
admin_user = user_service.get_admin_user()
|
||||
# Batch read configurations (small table)
|
||||
@@ -144,6 +149,7 @@ def get_sysconfig(
|
||||
"social_account_facebook_url": small_values.get(sys_config_key.KEY_SOCIAL_ACCOUNT_FACEBOOK_URL, ""),
|
||||
"social_account_x_url": small_values.get(sys_config_key.KEY_SOCIAL_ACCOUNT_X_URL, ""),
|
||||
"cname_a_ip": cname_a_ip,
|
||||
"tag_bar_display": small_values.get(sys_config_key.KEY_TAG_BAR_DISPLAY, "").lower() in ("true", "t", "yes", "y", "1"),
|
||||
},
|
||||
"account": {
|
||||
"username": admin_username,
|
||||
@@ -172,10 +178,13 @@ def get_sysconfig(
|
||||
|
||||
@router.put("/info")
|
||||
def set_sysconfig(
|
||||
request: Request,
|
||||
body: dict = Body(...),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
sysconfig_service: SysConfigService = Depends(get_sysconfig_service),
|
||||
):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
"""Update system configuration settings."""
|
||||
try:
|
||||
platform_name = ""
|
||||
@@ -219,6 +228,9 @@ def set_sysconfig(
|
||||
facebook_image_url = platform.get("facebook_image_url")
|
||||
social_account_facebook_url = platform.get("social_account_facebook_url")
|
||||
social_account_x_url = platform.get("social_account_x_url")
|
||||
tag_bar_display = platform.get("tag_bar_display")
|
||||
|
||||
|
||||
|
||||
account = body.get("account", {})
|
||||
admin_username = account.get("username")
|
||||
@@ -270,6 +282,7 @@ def set_sysconfig(
|
||||
(sys_config_key.KEY_FACEBOOK_IMAGE_URL, facebook_image_url, "Facebook image URL"),
|
||||
(sys_config_key.KEY_SOCIAL_ACCOUNT_FACEBOOK_URL, social_account_facebook_url, "Facebook URL"),
|
||||
(sys_config_key.KEY_SOCIAL_ACCOUNT_X_URL, social_account_x_url, "X URL"),
|
||||
(sys_config_key.KEY_TAG_BAR_DISPLAY, tag_bar_display, "Tag bar display"),
|
||||
(sys_config_key.KEY_LOGIN_GOOGLE_CLIENT, login_google_client, "Google login client ID"),
|
||||
(sys_config_key.KEY_LOGIN_GOOGLE_SECRET, login_google_secret, "Google login client secret"),
|
||||
(sys_config_key.KEY_LOGIN_GOOGLE_ENABLE, login_google_enable, "Google login enabled"),
|
||||
@@ -318,6 +331,7 @@ def set_sysconfig(
|
||||
"facebook_image_url": facebook_image_url,
|
||||
"social_account_facebook_url": social_account_facebook_url,
|
||||
"social_account_x_url": social_account_x_url,
|
||||
"tag_bar_display": tag_bar_display,
|
||||
}
|
||||
|
||||
# Use background reporting to avoid blocking the main configuration update
|
||||
@@ -328,7 +342,7 @@ def set_sysconfig(
|
||||
# Log error but continue with main operation - reporting failure should not affect configuration update
|
||||
logger.warning(f"Failed to initiate platform reporting: {e}")
|
||||
|
||||
return get_sysconfig(sysconfig_service, user_service)
|
||||
return get_sysconfig(request, sysconfig_service, user_service)
|
||||
|
||||
except Exception as e:
|
||||
return ResponseUtils.error(f"Failed to update system configuration: {str(e)}")
|
||||
|
||||
@@ -3,7 +3,10 @@ import hashlib
|
||||
import os
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from fastapi import Request
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.common import error_msg
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -14,6 +17,7 @@ and store files under date-based directories.
|
||||
"""
|
||||
@router.post("/image")
|
||||
async def upload(
|
||||
request: Request,
|
||||
img: UploadFile = File(None),
|
||||
sha256: str = Form(None),
|
||||
):
|
||||
@@ -24,6 +28,8 @@ async def upload(
|
||||
- Saves the file under `uploads/images/<YYYYMMDD>/`
|
||||
- Returns the relative `file_path`
|
||||
"""
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
# 1. Get uploaded file name
|
||||
if not img:
|
||||
return ResponseUtils.error(message="No file provided", code=400)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from fastapi import APIRouter, Depends, Request,Body
|
||||
from fastapi import APIRouter, Depends, Request,Body,Query
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.database import get_db
|
||||
from services.admin_service.constants.user_task import user_task_ids
|
||||
@@ -10,6 +10,12 @@ from services.admin_service.services.user_wallet_service import UserWalletServic
|
||||
from services.admin_service.services.user_task_service import UserTaskService
|
||||
from services.admin_service.services.auth_service import AuthService
|
||||
from services.admin_service.services.resource_group_service import ResourceGroupService
|
||||
from services.admin_service.services.user_wallet_history_service import UserWalletHistoryService
|
||||
from services.common import error_msg
|
||||
|
||||
|
||||
|
||||
from typing import Optional,List
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -27,9 +33,15 @@ def get_user_task_service(db: Session = Depends(get_db)) -> UserTaskService:
|
||||
def get_resource_group_service(db: Session = Depends(get_db)) -> ResourceGroupService:
|
||||
return ResourceGroupService(db)
|
||||
|
||||
def get_order_service(db: Session = Depends(get_db)) -> UserWalletHistoryService:
|
||||
return UserWalletHistoryService(db)
|
||||
|
||||
|
||||
@router.get("/info", response_model=dict)
|
||||
def get_user(request: Request, user_wallet: UserWalletService = Depends(get_user_wallet), user_task: UserTaskService = Depends(get_user_task_service), resource_group_service: ResourceGroupService = Depends(get_resource_group_service)):
|
||||
"""Get current user information and wallet balance."""
|
||||
if not UserUtils.is_normal_user(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
user_response = UserResponse()
|
||||
user_wallet_resp = UserWalletResponse()
|
||||
user_wallet_resp.balance = 0.00
|
||||
@@ -87,3 +99,37 @@ def update_password(
|
||||
|
||||
return ResponseUtils.error(message="not found user", code=404)
|
||||
|
||||
@router.get("/order/list", summary="Get order list")
|
||||
def get_order_list(
|
||||
request: Request,
|
||||
page: int = Query(1, description="Current page number"),
|
||||
page_size: int = Query(15, description="Number of items per page"),
|
||||
order_type: Optional[str] = Query(None, description="Order type"),
|
||||
status: Optional[str] = Query(None, description="Order status"),
|
||||
user_wallet_history_service: UserWalletHistoryService = Depends(get_order_service),
|
||||
):
|
||||
"""Get order list."""
|
||||
user = UserUtils.get_request_user(request)
|
||||
if not user:
|
||||
return ResponseUtils.error(message="not found user", code=404)
|
||||
offset = (page - 1) * page_size
|
||||
order_type_list = []
|
||||
if order_type:
|
||||
# 将字符串转成列表,中间使用逗号分隔
|
||||
ots = order_type.split(",")
|
||||
for ot in ots:
|
||||
ot = ot.strip()
|
||||
if ot == "purchase":
|
||||
order_type_list.append("api_call")
|
||||
elif ot == "recharge":
|
||||
order_type_list.append("deposit")
|
||||
else:
|
||||
order_type_list.append(ot)
|
||||
status_list: Optional[List[int]] = []
|
||||
if status:
|
||||
sl = status.split(",")
|
||||
for s in sl:
|
||||
status_list.append(int(s.strip()))
|
||||
total, orders = user_wallet_history_service.success_order_list_by_user(user.id, offset, page_size, order_type_list, status_list)
|
||||
|
||||
return ResponseUtils.success_page(data=orders, total=total, page_num=page, page_size=page_size)
|
||||
@@ -6,6 +6,9 @@ from services.common.response.apikey_response import ApikeyResponse
|
||||
from services.admin_service.services.user_apikey_service import UserApiKeyService
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.common.models.user_apikey import UserApiKey
|
||||
from services.common import error_msg
|
||||
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -29,20 +32,27 @@ def convert_to_apikey_response(user_apikey: UserApiKey) -> ApikeyResponse:
|
||||
@router.post("/info", summary="add apikey")
|
||||
def add_apikey(request: Request, apikey_service: UserApiKeyService = Depends(get_apikey_service), body: dict = Body(...)):
|
||||
"""Create a new API key for the user."""
|
||||
if not UserUtils.is_normal_user(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
user_id = UserUtils.get_request_user_id(request)
|
||||
name = body.get("name")
|
||||
if name is None:
|
||||
return ResponseUtils.error(message="name are required")
|
||||
|
||||
user_apikey = apikey_service.create(user_id=user_id, name=name)
|
||||
if not user_apikey:
|
||||
return ResponseUtils.error(message="Create failed")
|
||||
return ResponseUtils.success(data=convert_to_apikey_response(user_apikey))
|
||||
try:
|
||||
user_apikey = apikey_service.create(user_id=user_id, name=name)
|
||||
if not user_apikey:
|
||||
return ResponseUtils.error(message="Create failed")
|
||||
return ResponseUtils.success(data=convert_to_apikey_response(user_apikey))
|
||||
except ValueError as e:
|
||||
return ResponseUtils.error(message=str(e))
|
||||
|
||||
|
||||
|
||||
@router.get("/list", summary="get user apikey list")
|
||||
def get_user_apikey_list(request: Request, apikey_service: UserApiKeyService = Depends(get_apikey_service)):
|
||||
"""Get list of API keys for the current user."""
|
||||
if not UserUtils.is_normal_user(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
user_id = UserUtils.get_request_user_id(request)
|
||||
apikey_list = apikey_service.get_by_user_id(user_id)
|
||||
data = [convert_to_apikey_response(item) for item in apikey_list]
|
||||
@@ -52,6 +62,8 @@ def get_user_apikey_list(request: Request, apikey_service: UserApiKeyService = D
|
||||
@router.delete("/info", summary="delete user apikey")
|
||||
def delete_apikey(request: Request, apikey_service: UserApiKeyService = Depends(get_apikey_service), body: dict = Body(...)):
|
||||
"""Delete an API key by ID for the current user."""
|
||||
if not UserUtils.is_normal_user(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
user_id = UserUtils.get_request_user_id(request)
|
||||
id = body.get("apikey_id")
|
||||
if id is None:
|
||||
@@ -65,6 +77,8 @@ def delete_apikey(request: Request, apikey_service: UserApiKeyService = Depends(
|
||||
@router.put("/info", summary="modify user apikey")
|
||||
def modify_apikey(request: Request, apikey_service: UserApiKeyService = Depends(get_apikey_service), body: dict = Body(...)):
|
||||
"""Update API key information for the current user."""
|
||||
if not UserUtils.is_normal_user(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
user_id = UserUtils.get_request_user_id(request)
|
||||
id = body.get("apikey_id")
|
||||
name = body.get("name")
|
||||
@@ -72,7 +86,10 @@ def modify_apikey(request: Request, apikey_service: UserApiKeyService = Depends(
|
||||
expire_at = body.get("expire_at")
|
||||
if id is None:
|
||||
return ResponseUtils.error(message="id are required")
|
||||
apikey_obj = apikey_service.modify(id, user_id, name=name, description=description, expire_at=expire_at)
|
||||
if not apikey_obj:
|
||||
return ResponseUtils.error(message="Modify failed or not found or no permission")
|
||||
return ResponseUtils.success(data=convert_to_apikey_response(apikey_obj))
|
||||
try:
|
||||
apikey_obj = apikey_service.modify(id, user_id, name=name, description=description, expire_at=expire_at)
|
||||
if not apikey_obj:
|
||||
return ResponseUtils.error(message="Modify failed or not found or no permission")
|
||||
return ResponseUtils.success(data=convert_to_apikey_response(apikey_obj))
|
||||
except ValueError as e:
|
||||
return ResponseUtils.error(message=str(e))
|
||||
@@ -50,7 +50,7 @@ async def update_user_resource_group(
|
||||
group_id = body.get("resource_group")
|
||||
if not user_id or not group_id:
|
||||
return ResponseUtils.error(error_msg=error_msg.MISSING_PARAMETER)
|
||||
group = resource_group_service.get_info(group_id)
|
||||
group = resource_group_service.get_info(group_id, "")
|
||||
if not group:
|
||||
return ResponseUtils.error(error_msg=error_msg.RESOURCE_NOT_FOUND)
|
||||
user = user_service.get_by_id(user_id)
|
||||
@@ -63,11 +63,13 @@ async def update_user_resource_group(
|
||||
|
||||
@router.delete("/account", summary="Delete user account")
|
||||
async def delete_user(
|
||||
request: Request,
|
||||
id: str,
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""Delete user by ID."""
|
||||
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
# Validate user ID parameter
|
||||
ValidationUtils.require_non_empty_string(id, "id")
|
||||
|
||||
@@ -88,13 +90,16 @@ async def delete_user(
|
||||
|
||||
@router.get("/account/list", summary="Get user list with pagination")
|
||||
async def get_user_list(
|
||||
request: Request,
|
||||
page: int = Query(1, description="Page number (starts from 1)"),
|
||||
page_size: int = Query(15, description="Number of items per page"),
|
||||
keyword: str = Query(None, description="Search keyword for email or name"),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
user_wallet_service: UserWalletService = Depends(get_user_wallet_service),
|
||||
):
|
||||
"""Get paginated list of users with wallet information."""
|
||||
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
# Validate pagination parameters
|
||||
validated_page, validated_page_size = ValidationUtils.validate_pagination(page, page_size)
|
||||
|
||||
@@ -104,7 +109,7 @@ async def get_user_list(
|
||||
skip = (validated_page - 1) * validated_page_size
|
||||
|
||||
# Get user list - let any exception bubble up to middleware
|
||||
total, users = user_service.get_user_list(skip, validated_page_size)
|
||||
total, users = user_service.get_user_list(skip, validated_page_size, keyword)
|
||||
|
||||
# Convert user data to list
|
||||
user_list = []
|
||||
@@ -125,6 +130,8 @@ async def recharge_balance(
|
||||
request: Request,
|
||||
payment_service: PaymentService = Depends(get_payment_service),
|
||||
):
|
||||
if not UserUtils.is_admin(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
body = await request.body()
|
||||
body_str = body.decode('utf-8')
|
||||
timestamp=request.headers.get("x-xpack-timestamp")
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
User statistics controller
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from fastapi import APIRouter, Depends, Query, Request
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.database import get_db
|
||||
from services.common.utils.response_utils import ResponseUtils
|
||||
from services.admin_service.services.user_stats_service import UserStatsService
|
||||
from services.admin_service.utils.user_utils import UserUtils
|
||||
from services.common.logging_config import get_logger
|
||||
from services.common import error_msg
|
||||
|
||||
logger = get_logger(__name__)
|
||||
router = APIRouter()
|
||||
@@ -15,10 +17,13 @@ router = APIRouter()
|
||||
|
||||
@router.get("/key_call_tool")
|
||||
async def get_key_call_tool(
|
||||
request: Request,
|
||||
apikey_id: str = Query(..., description="apikey ID (not the apikey itself)"),
|
||||
last_day: int = Query(30, description="Days to query, default 30"),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
if not UserUtils.is_normal_user(request):
|
||||
return ResponseUtils.error(error_msg=error_msg.NO_PERMISSION)
|
||||
"""
|
||||
Get tool call statistics by apikey
|
||||
"""
|
||||
@@ -51,12 +56,12 @@ async def get_key_call_tool(
|
||||
|
||||
except ValueError as e:
|
||||
# Handle business logic errors (invalid apikey_id)
|
||||
error_msg = str(e)
|
||||
logger.error(f"Business logic error: {error_msg}")
|
||||
return ResponseUtils.error(error_msg, code=400)
|
||||
err_msg = str(e)
|
||||
logger.error(f"Business logic error: {err_msg}")
|
||||
return ResponseUtils.error(err_msg, code=400)
|
||||
|
||||
except Exception as e:
|
||||
# Handle unexpected errors
|
||||
error_msg = f"Failed to retrieve call tool statistics: {str(e)}"
|
||||
logger.error(f"Unexpected error in get_key_call_tool_count: {error_msg}", exc_info=True)
|
||||
err_msg = f"Failed to retrieve call tool statistics: {str(e)}"
|
||||
logger.error(f"Unexpected error in get_key_call_tool_count: {err_msg}", exc_info=True)
|
||||
return ResponseUtils.error("Internal server error occurred while retrieving statistics", code=500)
|
||||
@@ -29,6 +29,7 @@ def get_public_mcp_services(
|
||||
keyword: Optional[str] = Query(None, description="Search keyword"),
|
||||
page: Optional[int] = Query(1, description="Page number (starts from 1)"),
|
||||
page_size: Optional[int] = Query(10, description="Page size (default 10)"),
|
||||
tag: Optional[str] = Query(None, description="Filter by tag"),
|
||||
mcp_manager_service: McpManagerService = Depends(get_mcp_manager),
|
||||
):
|
||||
"""Get paginated list of public MCP services with keyword search."""
|
||||
@@ -43,12 +44,19 @@ def get_public_mcp_services(
|
||||
|
||||
# Get service list - let any exception bubble up to middleware
|
||||
service_list, total = mcp_manager_service.get_public_services_paginated(
|
||||
keyword=search_keyword, page=validated_page, page_size=validated_page_size
|
||||
keyword=search_keyword, page=validated_page, page_size=validated_page_size, tag=tag
|
||||
)
|
||||
|
||||
logger.info(f"Successfully retrieved {len(service_list)} services")
|
||||
return ResponseUtils.success_page(data=service_list, page_num=validated_page, page_size=validated_page_size, total=total)
|
||||
|
||||
@router.get("/mcp_tags", summary="Get public MCP tags list")
|
||||
def get_public_mcp_tags(
|
||||
mcp_manager_service: McpManagerService = Depends(get_mcp_manager),
|
||||
):
|
||||
tags = mcp_manager_service.get_tags_list(enabled_only=True)
|
||||
return ResponseUtils.success(data=tags)
|
||||
|
||||
|
||||
@router.get("/mcp_service_info", summary="Get public MCP service information")
|
||||
def get_public_mcp_service_info(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.models.mcp_service import McpService
|
||||
from typing import Optional, Tuple, List
|
||||
@@ -70,17 +71,19 @@ class McpServiceRepository:
|
||||
query = query.filter((McpService.name.like(keyword)) | (McpService.short_description.like(keyword)))
|
||||
return query.all()
|
||||
|
||||
def get_all_paginated(self, page: int = 1, page_size: int = 10, keyword: Optional[str] = None) -> Tuple[List[McpService], int]:
|
||||
def get_all_paginated(self, page: int = 1, page_size: int = 10, keyword: Optional[str] = None,filter_status: Optional[list] = None) -> Tuple[List[McpService], int]:
|
||||
"""Get service list with pagination"""
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
total = self.db.query(McpService).count()
|
||||
|
||||
query = self.db.query(McpService).order_by(McpService.created_at.desc()).offset(offset).limit(page_size)
|
||||
query = self.db.query(McpService)
|
||||
if keyword:
|
||||
keyword = f"%{keyword}%"
|
||||
query = query.filter((McpService.name.like(keyword)) | (McpService.short_description.like(keyword)))
|
||||
|
||||
if filter_status:
|
||||
query = query.filter(McpService.enabled.in_(filter_status))
|
||||
total = query.count()
|
||||
query = query.order_by(McpService.created_at.desc()).offset(offset).limit(page_size)
|
||||
|
||||
services = query.all()
|
||||
|
||||
return services, total
|
||||
@@ -103,7 +106,7 @@ class McpServiceRepository:
|
||||
self.db.refresh(mcp_service)
|
||||
return mcp_service
|
||||
|
||||
def get_public_services_paginated(self, keyword: str, page: int = 1, page_size: int = 10) -> Tuple[List[McpService], int]:
|
||||
def get_public_services_paginated(self, keyword: str, page: int = 1, page_size: int = 10, tag: Optional[str] = None) -> Tuple[List[McpService], int]:
|
||||
"""Get public service list with pagination, supports keyword search"""
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
@@ -112,9 +115,21 @@ class McpServiceRepository:
|
||||
if keyword:
|
||||
keyword = f"%{keyword}%"
|
||||
query = query.filter((McpService.name.like(keyword)) | (McpService.short_description.like(keyword)))
|
||||
if tag:
|
||||
normalized_tag = tag.strip()
|
||||
if normalized_tag:
|
||||
normalized_tags = func.replace(func.replace(McpService.tags, ", ", ","), " ,", ",")
|
||||
query = query.filter(func.find_in_set(normalized_tag, normalized_tags) > 0)
|
||||
|
||||
|
||||
total = query.count()
|
||||
|
||||
services = query.order_by(McpService.created_at.desc()).offset(offset).limit(page_size).all()
|
||||
|
||||
return services, total
|
||||
|
||||
def get_tags_strings(self, enabled_only: bool = False) -> List[str]:
|
||||
query = self.db.query(McpService.tags).filter(McpService.tags.isnot(None)).filter(McpService.tags != "")
|
||||
if enabled_only:
|
||||
query = query.filter(McpService.enabled == 1)
|
||||
return [row[0] for row in query.all() if row and row[0]]
|
||||
@@ -44,6 +44,10 @@ class ResourceGroupRepository:
|
||||
self.db.commit()
|
||||
return existing
|
||||
|
||||
def check_name_duplicate(self, id: str, name: str) -> bool:
|
||||
"""Check if the resource group name already exists."""
|
||||
return self.db.query(ResourceGroup).filter(ResourceGroup.name == name, ResourceGroup.id != id).first() is not None
|
||||
|
||||
def get_by_id(self, id: str) -> Optional[ResourceGroup]:
|
||||
return self.db.query(ResourceGroup).filter(ResourceGroup.id == id).first()
|
||||
|
||||
|
||||
@@ -12,6 +12,12 @@ class UserApiKeyRepository:
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def check_user_apikey_by_name(self, user_id: str, name: str, id: Optional[str] = None) -> bool:
|
||||
"""Check if the API key already exists."""
|
||||
if id:
|
||||
return self.db.query(UserApiKey).filter(UserApiKey.id != id, UserApiKey.user_id == user_id, UserApiKey.name == name,UserApiKey.is_deleted == 0).first() is not None
|
||||
return self.db.query(UserApiKey).filter(UserApiKey.user_id == user_id, UserApiKey.name == name,UserApiKey.is_deleted == 0).first() is not None
|
||||
|
||||
def create(self, user_id: str, name: str, description: str) -> UserApiKey:
|
||||
"""Create a new API key for the user with generated token."""
|
||||
now = datetime.now(timezone.utc)
|
||||
@@ -54,14 +60,15 @@ class UserApiKeyRepository:
|
||||
user_apikey = self.db.query(UserApiKey).filter(UserApiKey.id == id).first()
|
||||
if not user_apikey:
|
||||
raise ValueError("API key not found or does not belong to the user")
|
||||
|
||||
self.db.delete(user_apikey)
|
||||
|
||||
user_apikey.is_deleted = 1
|
||||
user_apikey.updated_at = datetime.now(timezone.utc)
|
||||
self.db.commit()
|
||||
|
||||
def get_by_user_id(self, user_id: str) -> List[UserApiKey]:
|
||||
"""List API keys belonging to the specified user."""
|
||||
return self.db.query(UserApiKey).filter(UserApiKey.user_id == user_id).all()
|
||||
return self.db.query(UserApiKey).filter(UserApiKey.user_id == user_id, UserApiKey.is_deleted == 0).all()
|
||||
|
||||
def get_by_id(self, id: str) -> Optional[UserApiKey]:
|
||||
"""Get API key by primary ID."""
|
||||
return self.db.query(UserApiKey).filter(UserApiKey.id == id).first()
|
||||
return self.db.query(UserApiKey).filter(UserApiKey.id == id, UserApiKey.is_deleted == 0).first()
|
||||
@@ -15,8 +15,8 @@ class UserRepository:
|
||||
def get_by_email(self, email: str) -> Optional[User]:
|
||||
return self.db.query(User).filter(User.email == email).first()
|
||||
|
||||
def get_by_account(self, name: str) -> Optional[User]:
|
||||
return self.db.query(User).filter(User.name == name).first()
|
||||
def get_by_account(self, name: str, role_id: int = 1) -> Optional[User]:
|
||||
return self.db.query(User).filter(User.name == name, User.role_id == role_id).first()
|
||||
|
||||
def update_password(self,user_id:str, password:str) -> Optional[User]:
|
||||
user = self.get_by_id(user_id)
|
||||
@@ -81,11 +81,23 @@ class UserRepository:
|
||||
self.db.commit()
|
||||
self.db.refresh(user)
|
||||
return user
|
||||
|
||||
def get_all_user(self,keyword: Optional[str] = None,include_deleted: bool = False) -> List[User]:
|
||||
"""Get all user"""
|
||||
query = self.db.query(User).filter(User.role_id == 2)
|
||||
if not include_deleted:
|
||||
query = query.filter(User.is_deleted == 0)
|
||||
if keyword:
|
||||
query = query.filter((User.email.like(f"%{keyword}%")) | (User.name.like(f"%{keyword}%")))
|
||||
return query.all()
|
||||
|
||||
def get_user_list(self, offset: int, limit: int) -> Tuple[int, List[User]]:
|
||||
total = self.db.query(User).filter(User.is_deleted == 0, User.role_id == 2).count()
|
||||
|
||||
users = self.db.query(User).filter(User.is_deleted == 0, User.role_id == 2).order_by(User.created_at.desc()).offset(offset).limit(limit).all()
|
||||
def get_user_list(self, offset: int, limit: int, keyword: Optional[str] = None) -> Tuple[int, List[User]]:
|
||||
"""Get user list"""
|
||||
query = self.db.query(User).filter(User.is_deleted == 0, User.role_id == 2)
|
||||
if keyword:
|
||||
query = query.filter((User.email.like(f"%{keyword}%")) | (User.name.like(f"%{keyword}%")))
|
||||
total = query.count()
|
||||
users = query.order_by(User.created_at.desc()).offset(offset).limit(limit).all()
|
||||
return total, users
|
||||
|
||||
def get_admin_user(self) -> Optional[User]:
|
||||
|
||||
@@ -18,8 +18,20 @@ class UserWalletHistoryRepository:
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def get_by_id(self, transaction_id: str) -> Optional[UserWalletHistory]:
|
||||
"""
|
||||
Get a user wallet history record by ID.
|
||||
|
||||
def add_deposit(self, user_id: str, amount: float, payment_method: str, transaction_id: str = "", status: int = 0) -> UserWalletHistory:
|
||||
Args:
|
||||
transaction_id: Transaction ID
|
||||
|
||||
Returns:
|
||||
Optional[UserWalletHistory]: Found record or None
|
||||
"""
|
||||
return self.db.query(UserWalletHistory).filter(UserWalletHistory.id == transaction_id).first()
|
||||
|
||||
def add_deposit(self, user_id: str, amount: float, payment_method: str, transaction_id: str = "", status: int = 0, balance_after: float = 0.00) -> UserWalletHistory:
|
||||
"""
|
||||
Create a new deposit record.
|
||||
|
||||
@@ -40,7 +52,7 @@ class UserWalletHistoryRepository:
|
||||
user_id=user_id,
|
||||
payment_method=PaymentMethod(payment_method),
|
||||
amount=amount,
|
||||
balance_after=0.00,
|
||||
balance_after=balance_after,
|
||||
type=TransactionType.DEPOSIT,
|
||||
transaction_id=transaction_id,
|
||||
status=status,
|
||||
@@ -81,7 +93,7 @@ class UserWalletHistoryRepository:
|
||||
self.db.refresh(history)
|
||||
return history
|
||||
|
||||
def set_balance(self,user_id: str,amount:float, payment_method: str, transaction_id: str = "", status: int = 0) -> UserWalletHistory:
|
||||
def set_balance(self,user_id: str,amount:float, payment_method: str, transaction_id: str = "", status: int = 0, balance_after: float = 0.00) -> UserWalletHistory:
|
||||
"""
|
||||
Create a new balance record.
|
||||
|
||||
@@ -102,7 +114,7 @@ class UserWalletHistoryRepository:
|
||||
user_id=user_id,
|
||||
payment_method=PaymentMethod(payment_method),
|
||||
amount=amount,
|
||||
balance_after=0.00,
|
||||
balance_after=balance_after,
|
||||
type=TransactionType.RESET,
|
||||
status=status, # 0=new, 1=completed, 2=refunded
|
||||
created_at=now,
|
||||
@@ -216,7 +228,7 @@ class UserWalletHistoryRepository:
|
||||
self.db.rollback()
|
||||
return False
|
||||
|
||||
def success_deposit_order_list(self, offset: int, limit: int) -> Tuple[int, List[UserWalletHistory]]:
|
||||
def success_deposit_order_list(self, offset: int, limit: int, userIds: Optional[list] = None, sort_amount: Optional[str] = "desc", filter_payment_type: Optional[list] = None) -> Tuple[int, List[UserWalletHistory]]:
|
||||
"""
|
||||
Get list of successful orders.
|
||||
|
||||
@@ -231,6 +243,47 @@ class UserWalletHistoryRepository:
|
||||
UserWalletHistory.status == 1,
|
||||
UserWalletHistory.type == TransactionType.DEPOSIT,
|
||||
)
|
||||
if userIds and len(userIds) > 0:
|
||||
query = query.filter(UserWalletHistory.user_id.in_(userIds))
|
||||
|
||||
if filter_payment_type and len(filter_payment_type) > 0:
|
||||
filter_payment_type_enum = [PaymentMethod(method) for method in filter_payment_type]
|
||||
print(f"filter_payment_type,{filter_payment_type_enum}")
|
||||
query = query.filter(UserWalletHistory.payment_method.in_(filter_payment_type_enum))
|
||||
total = query.count()
|
||||
if total < offset:
|
||||
return total, []
|
||||
if sort_amount == "desc":
|
||||
query = query.order_by(UserWalletHistory.amount.desc())
|
||||
else:
|
||||
query = query.order_by(UserWalletHistory.amount.asc())
|
||||
history = (
|
||||
query
|
||||
.order_by(UserWalletHistory.created_at.desc())
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
.all()
|
||||
)
|
||||
return total, history
|
||||
|
||||
def success_order_list_by_user(self, user_id: str, offset: int, limit: int, order_type: Optional[List[str]] = None, status: Optional[List[int]] = None) -> Tuple[int, List[UserWalletHistory]]:
|
||||
"""
|
||||
Get user wallet history record by ID.
|
||||
|
||||
Args:
|
||||
history_id: History record ID
|
||||
|
||||
Returns:
|
||||
Optional[UserWalletHistory]: UserWalletHistory object or None
|
||||
"""
|
||||
|
||||
query = self.db.query(UserWalletHistory).filter(
|
||||
UserWalletHistory.user_id == user_id,
|
||||
)
|
||||
if order_type and len(order_type) > 0:
|
||||
query = query.filter(UserWalletHistory.type.in_(order_type))
|
||||
if status and len(status) > 0:
|
||||
query = query.filter(UserWalletHistory.status.in_(status))
|
||||
total = query.count()
|
||||
if total < offset:
|
||||
return total, []
|
||||
@@ -243,18 +296,6 @@ class UserWalletHistoryRepository:
|
||||
)
|
||||
return total, history
|
||||
|
||||
def get_by_id(self, history_id: str) -> Optional[UserWalletHistory]:
|
||||
"""
|
||||
Get user wallet history record by ID.
|
||||
|
||||
Args:
|
||||
history_id: History record ID
|
||||
|
||||
Returns:
|
||||
Optional[UserWalletHistory]: UserWalletHistory object or None
|
||||
"""
|
||||
return self.db.query(UserWalletHistory).filter(UserWalletHistory.id == history_id).first()
|
||||
|
||||
def add_consume_record(self, wallet_history: UserWalletHistory) -> Optional[UserWalletHistory]:
|
||||
"""
|
||||
Add consume record to database.
|
||||
|
||||
@@ -16,6 +16,7 @@ from services.admin_service.constants.sys_config_key import (
|
||||
KEY_DEFAULT_RESOURCE_GROUP,
|
||||
)
|
||||
from services.common.utils.auth import delete_token
|
||||
from services.common.redis import redis_client
|
||||
|
||||
from google.auth.transport.requests import Request as GoogleRequest
|
||||
from google.oauth2 import id_token
|
||||
@@ -32,6 +33,32 @@ class AuthService:
|
||||
self.user_access_token_repository = UserAccessTokenRepository(db)
|
||||
self.sys_config_service = SysConfigService(db)
|
||||
|
||||
def check_ip_ban(self, ip: str, user: str) -> bool:
|
||||
"""Check if IP is banned. Returns True if banned."""
|
||||
ban_key = RedisKeys.login_ban_key(ip,user)
|
||||
return redis_client.exists(ban_key) > 0
|
||||
|
||||
def record_login_fail(self, ip: str, user: str):
|
||||
"""Record login failure for IP."""
|
||||
fail_key = RedisKeys.login_fail_count_key(ip,user)
|
||||
# Increment count
|
||||
count = redis_client.incr(fail_key)
|
||||
# Set expiration if it's the first failure
|
||||
if count == 1:
|
||||
redis_client.expire(fail_key, 300) # 5 minutes window
|
||||
|
||||
if count >= 5:
|
||||
# Ban IP
|
||||
ban_key = RedisKeys.login_ban_key(ip,user)
|
||||
redis_client.set(ban_key, "1", ex=300) # Ban for 5 minutes
|
||||
# Clear fail count
|
||||
redis_client.delete(fail_key)
|
||||
|
||||
def clear_login_fail(self, ip: str, user: str):
|
||||
"""Clear login failure count for IP."""
|
||||
fail_key = RedisKeys.login_fail_count_key(ip,user)
|
||||
redis_client.delete(fail_key)
|
||||
|
||||
def send_email_login_captcha(self, email: str) -> bool:
|
||||
"""
|
||||
Sends a login captcha code to the specified email address with simple rate limiting.
|
||||
@@ -244,5 +271,5 @@ class AuthService:
|
||||
return token
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Google login failed: {e}")
|
||||
logger.error(f"Google login failed, error: {e}")
|
||||
return None
|
||||
@@ -325,9 +325,34 @@ class McpManagerService:
|
||||
def get_all(self) -> List[McpService]:
|
||||
return self.mcp_service_repository.get_all()
|
||||
|
||||
def get_all_paginated(self, page: int = 1, page_size: int = 10) -> Tuple[List[McpService], int]:
|
||||
def get_all_paginated(self, page: int = 1, page_size: int = 10,keyword: Optional[str] = None,filter_status: Optional[list] = None) -> Tuple[List[McpService], int]:
|
||||
"""Get service list with pagination"""
|
||||
return self.mcp_service_repository.get_all_paginated(page=page, page_size=page_size)
|
||||
return self.mcp_service_repository.get_all_paginated(page=page, page_size=page_size,keyword=keyword,filter_status=filter_status)
|
||||
|
||||
def get_tags_list(self, enabled_only: bool = False) -> List[str]:
|
||||
tags_strings = self.mcp_service_repository.get_tags_strings(enabled_only=enabled_only)
|
||||
tag_counts: dict[str, int] = {}
|
||||
canonical: dict[str, str] = {}
|
||||
|
||||
for tags_str in tags_strings:
|
||||
normalized_in_service: set[str] = set()
|
||||
for tag in parse_tags_to_array(tags_str):
|
||||
normalized = tag.casefold()
|
||||
if not normalized:
|
||||
continue
|
||||
if normalized in normalized_in_service:
|
||||
continue
|
||||
normalized_in_service.add(normalized)
|
||||
canonical.setdefault(normalized, tag)
|
||||
|
||||
for normalized in normalized_in_service:
|
||||
tag_counts[normalized] = tag_counts.get(normalized, 0) + 1
|
||||
|
||||
sorted_normalized = sorted(
|
||||
tag_counts.keys(),
|
||||
key=lambda normalized: (-tag_counts[normalized], canonical[normalized].casefold()),
|
||||
)
|
||||
return [canonical[normalized] for normalized in sorted_normalized]
|
||||
|
||||
def create_service_from_openapi(self, openapi_data: OpenApiForAI) -> str:
|
||||
# Convert OpenApiForAI info to McpService object and McpToolApi object list, return service ID or exception.
|
||||
@@ -488,9 +513,9 @@ class McpManagerService:
|
||||
logger.error(f"Failed to update service from OpenAPI: {str(e)}")
|
||||
raise ValueError(f"Failed to update service from OpenAPI.")
|
||||
|
||||
def get_public_services_paginated(self, keyword: str, page: int = 1, page_size: int = 10) -> Tuple[List[dict], int]:
|
||||
def get_public_services_paginated(self, keyword: str, page: int = 1, page_size: int = 10, tag: Optional[str] = None) -> Tuple[List[dict], int]:
|
||||
"""Get public services list with pagination, returns formatted data with API info"""
|
||||
services, total = self.mcp_service_repository.get_public_services_paginated(keyword, page, page_size)
|
||||
services, total = self.mcp_service_repository.get_public_services_paginated(keyword, page, page_size, tag)
|
||||
|
||||
service_list = []
|
||||
for service in services:
|
||||
|
||||
@@ -403,11 +403,21 @@ class PaymentService:
|
||||
try:
|
||||
if typ == "incr":
|
||||
self.user_wallet_history_repository.add_deposit(
|
||||
user_id=user_id, amount=amount, payment_method=payment_method, transaction_id=transaction_id,status=1
|
||||
user_id=user_id,
|
||||
amount=amount,
|
||||
payment_method=payment_method,
|
||||
transaction_id=transaction_id,
|
||||
status=1,
|
||||
balance_after=new_balance,
|
||||
)
|
||||
elif typ == "set":
|
||||
self.user_wallet_history_repository.set_balance(
|
||||
user_id=user_id, amount=amount, payment_method=payment_method, transaction_id=transaction_id,status=1
|
||||
user_id=user_id,
|
||||
amount=amount,
|
||||
payment_method=payment_method,
|
||||
transaction_id=transaction_id,
|
||||
status=1,
|
||||
balance_after=new_balance,
|
||||
)
|
||||
self._delete_wallet_cache(user_id)
|
||||
logger.info(f"Successfully updated balance for user_id {user_id}: {current_wallet.balance} -> {new_balance}")
|
||||
|
||||
@@ -7,7 +7,7 @@ from services.admin_service.repositories.resource_group_service_map_repository i
|
||||
from services.admin_service.repositories.user_repository import UserRepository
|
||||
from services.admin_service.repositories.mcp_service_repository import McpServiceRepository
|
||||
from services.admin_service.repositories.sys_config_repository import SysConfigRepository
|
||||
from services.admin_service.constants.sys_config_key import KEY_DEFAULT_RESOURCE_GROUP
|
||||
|
||||
from services.common.models.mcp_service import ChargeType
|
||||
from services.common.redis import redis_client
|
||||
|
||||
@@ -20,11 +20,15 @@ class ResourceGroupService:
|
||||
self.user_repo = UserRepository(db)
|
||||
self.map_repo = ResourceGroupServiceMapRepository(db)
|
||||
self.mcp_repo = McpServiceRepository(db)
|
||||
self.sys_repo = SysConfigRepository(db)
|
||||
|
||||
def create_group(self, gid: str, name: str, description: Optional[str], is_default: bool = False) -> str:
|
||||
def create_group(self, gid: str, name: str, description: Optional[str]) -> str:
|
||||
try:
|
||||
if gid != "deny-all" and gid != "allow-all":
|
||||
# 忽略大小写检查重复
|
||||
lower_name = name.strip().lower() if name else None
|
||||
if lower_name == "allow all" or lower_name == "deny all" or self.group_repo.check_name_duplicate(gid, name):
|
||||
raise ValueError("Resource group name \"{{name}}\" already exists")
|
||||
|
||||
group = ResourceGroup()
|
||||
group.id = gid
|
||||
group.name = name
|
||||
@@ -34,8 +38,6 @@ class ResourceGroupService:
|
||||
if result is None:
|
||||
raise ValueError("Failed to create resource group")
|
||||
|
||||
if is_default:
|
||||
self.sys_repo.set_value_by_key(key=KEY_DEFAULT_RESOURCE_GROUP, value=gid, description="Default resource group", commit=False)
|
||||
self.db.commit()
|
||||
return gid
|
||||
except Exception:
|
||||
@@ -45,47 +47,49 @@ class ResourceGroupService:
|
||||
def update_group(self, gid: str, body: dict) -> bool:
|
||||
if not gid:
|
||||
raise ValueError("Group ID is required")
|
||||
existing = self.group_repo.get_by_id(gid)
|
||||
if not existing:
|
||||
raise ValueError("Resource group not found")
|
||||
try:
|
||||
if gid != "deny-all" and gid != "allow-all":
|
||||
name = body.get("name","")
|
||||
# 忽略大小写检查重复
|
||||
lower_name = name.strip().lower() if name else None
|
||||
if lower_name == "allow all" or lower_name == "deny all" or self.group_repo.check_name_duplicate(gid, name):
|
||||
raise ValueError("Resource group name \"{{name}}\" already exists")
|
||||
existing = self.group_repo.get_by_id(gid)
|
||||
if not existing:
|
||||
raise ValueError("Resource group not found")
|
||||
patch = ResourceGroup()
|
||||
patch.id = gid
|
||||
patch.name = body.get("name", existing.name)
|
||||
patch.description = body.get("description", existing.description)
|
||||
patch.enabled = body.get("enabled", existing.enabled)
|
||||
self.group_repo.update(patch, commit=False)
|
||||
is_default = body.get("is_default", False)
|
||||
if is_default:
|
||||
self.sys_repo.set_value_by_key(key=KEY_DEFAULT_RESOURCE_GROUP, value=gid, description="Default resource group", commit=False)
|
||||
|
||||
self.db.commit()
|
||||
return True
|
||||
except Exception:
|
||||
self.db.rollback()
|
||||
raise
|
||||
|
||||
def delete_group(self, gid: str, migrate_id: Optional[str] = None) -> bool:
|
||||
def delete_group(self, gid: str, migrate_id: Optional[str] = None) -> bool:
|
||||
try:
|
||||
if migrate_id:
|
||||
migrate_group = self.group_repo.get_by_id(migrate_id)
|
||||
if not migrate_group:
|
||||
raise ValueError("Migrate resource group not found")
|
||||
if migrate_id != "deny-all" and migrate_id != "allow-all":
|
||||
migrate_group = self.group_repo.get_by_id(migrate_id)
|
||||
if not migrate_group:
|
||||
raise ValueError("Migrate resource group not found")
|
||||
self.map_repo.migrate_services(gid, migrate_id, commit=False)
|
||||
current_default = self.sys_repo.get_value_by_key(KEY_DEFAULT_RESOURCE_GROUP)
|
||||
if current_default == gid:
|
||||
self.sys_repo.set_value_by_key(KEY_DEFAULT_RESOURCE_GROUP, migrate_id, "Default resource group", commit=False)
|
||||
|
||||
else:
|
||||
self.map_repo.delete_by_group_id(gid, commit=False)
|
||||
current_default = self.sys_repo.get_value_by_key(KEY_DEFAULT_RESOURCE_GROUP)
|
||||
if current_default == gid:
|
||||
self.sys_repo.set_value_by_key(KEY_DEFAULT_RESOURCE_GROUP, "", "Default resource group", commit=False)
|
||||
|
||||
deleted = self.group_repo.delete(gid, commit=False)
|
||||
if deleted is None:
|
||||
raise ValueError("Resource group not found")
|
||||
users = self.user_repo.update_resource_group_by_group_id(gid, migrate_id or "deny-all", commit=False)
|
||||
if not users:
|
||||
raise ValueError("Failed to update user resource group")
|
||||
self.db.commit()
|
||||
return True
|
||||
|
||||
for user in users:
|
||||
cache_key = f"xpack:user:{user.id}"
|
||||
self.redis.set(cache_key, user, 600)
|
||||
@@ -97,8 +101,7 @@ class ResourceGroupService:
|
||||
self.db.rollback()
|
||||
raise
|
||||
|
||||
def get_info(self, gid: str) -> Optional[dict]:
|
||||
default_group = self.sys_repo.get_value_by_key(KEY_DEFAULT_RESOURCE_GROUP)
|
||||
def get_info(self, gid: str,default_group: str) -> Optional[dict]:
|
||||
if gid == "allow-all":
|
||||
return {
|
||||
"id":"allow-all",
|
||||
@@ -127,8 +130,7 @@ class ResourceGroupService:
|
||||
"is_default": g.id == default_group,
|
||||
}
|
||||
|
||||
def list_groups(self, page: int = 1, page_size: int = 10, keyword: Optional[str] = None) -> Tuple[List[dict], int]:
|
||||
default_group = self.sys_repo.get_value_by_key(KEY_DEFAULT_RESOURCE_GROUP)
|
||||
def list_groups(self, page: int = 1, page_size: int = 10, default_group: str = "", keyword: Optional[str] = None) -> Tuple[List[dict], int]:
|
||||
groups,total = self.group_repo.get_all_paginated(page=page, page_size=page_size, keyword=keyword)
|
||||
if total == 0:
|
||||
return [
|
||||
@@ -177,10 +179,19 @@ class ResourceGroupService:
|
||||
"enabled": True, # 统一为 bool
|
||||
"is_default": "deny-all" == default_group,
|
||||
}
|
||||
if len(data) < page_size:
|
||||
s_index = (page - 1) * page_size
|
||||
e_index = page * page_size
|
||||
if total > s_index and total < e_index:
|
||||
data.append(allow_all)
|
||||
if len(data) < page_size:
|
||||
if total < e_index-1:
|
||||
data.append(deny_all)
|
||||
elif total < s_index and s_index - total == 1:
|
||||
data.append(deny_all)
|
||||
elif total == s_index:
|
||||
data.append(allow_all)
|
||||
data.append(deny_all)
|
||||
|
||||
|
||||
|
||||
return data,total+2
|
||||
|
||||
@@ -353,7 +364,7 @@ class ResourceGroupService:
|
||||
"created_at": str(s.created_at) if s.created_at else None,
|
||||
"updated_at": str(s.updated_at) if s.updated_at else None,
|
||||
}
|
||||
for s in (service_map[sid] for sid in sids)
|
||||
for s in (service_map[sid] for sid in sids if sid in service_map)
|
||||
],total
|
||||
def get_unbind_services(self, gid: str) -> List[dict]:
|
||||
if gid == "deny-all" or gid == "allow-all":
|
||||
|
||||
@@ -20,7 +20,7 @@ class StatsService:
|
||||
self.mcp_service_repository = McpServiceRepository(db)
|
||||
self.drop_mcp_service_repository = DropMcpServiceRepository(db)
|
||||
|
||||
def get_registered_user_stats(self) -> dict:
|
||||
def get_registered_user_stats(self, start: datetime, end: datetime) -> dict:
|
||||
"""
|
||||
Get registered stats
|
||||
|
||||
@@ -29,14 +29,13 @@ class StatsService:
|
||||
"""
|
||||
# Start of day (00:00)
|
||||
today_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
pass30 = today_start - timedelta(days=30)
|
||||
|
||||
return {
|
||||
"total": self.user_repository.get_registered_user_count(),
|
||||
"total": self.user_repository.get_registered_user_count(start, end),
|
||||
"today": self.user_repository.get_registered_user_count(today_start),
|
||||
"days": self.user_repository.get_registered_user_trend(pass30)
|
||||
"days": self.user_repository.get_registered_user_trend(start, end)
|
||||
}
|
||||
def get_deposit_stats(self) -> dict:
|
||||
def get_deposit_stats(self, start: datetime, end: datetime) -> dict:
|
||||
"""
|
||||
Get deposit stats
|
||||
|
||||
@@ -45,14 +44,13 @@ class StatsService:
|
||||
"""
|
||||
# Start of day (00:00)
|
||||
today_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
pass30 = today_start - timedelta(days=30)
|
||||
|
||||
return {
|
||||
"total": self.user_wallet_repository.stats_deposit_amount(),
|
||||
"total": self.user_wallet_repository.stats_deposit_amount(start, end),
|
||||
"today": self.user_wallet_repository.stats_deposit_amount(today_start),
|
||||
"days": self.user_wallet_repository.stats_deposit_amount_trend(pass30)
|
||||
"days": self.user_wallet_repository.stats_deposit_amount_trend(start,end)
|
||||
}
|
||||
def get_call_stats(self) -> dict:
|
||||
def get_call_stats(self, start: datetime, end: datetime) -> dict:
|
||||
"""
|
||||
Get call stats
|
||||
|
||||
@@ -64,22 +62,20 @@ class StatsService:
|
||||
pass30 = today_start - timedelta(days=30)
|
||||
|
||||
return {
|
||||
"total": self.stats_mcp_service_date_repository.stats_call_count(),
|
||||
"total": self.stats_mcp_service_date_repository.stats_call_count(start, end),
|
||||
"today": self.stats_mcp_service_date_repository.stats_call_count(today_start),
|
||||
"days": self.stats_mcp_service_date_repository.stats_call_count_trend(pass30)
|
||||
"days": self.stats_mcp_service_date_repository.stats_call_count_trend(start, end)
|
||||
}
|
||||
|
||||
def get_call_stats_group_by_service(self) -> list:
|
||||
def get_call_stats_group_by_service(self, start: datetime, end: datetime) -> list:
|
||||
"""
|
||||
Get call stats group by service
|
||||
|
||||
Returns:
|
||||
dict: Call stats group by service
|
||||
"""
|
||||
now = datetime.now()
|
||||
pass30 = now - timedelta(days=30)
|
||||
# Get stats (include only services with calls)
|
||||
stats = self.stats_mcp_service_date_repository.stats_call_count_group_by_service(pass30)
|
||||
stats = self.stats_mcp_service_date_repository.stats_call_count_group_by_service(start, end)
|
||||
stats_map = {item["service_id"]: int(item.get("count", 0)) for item in stats}
|
||||
|
||||
# Iterate all services, fill missing call count as 0, sort by calls desc
|
||||
|
||||
@@ -16,12 +16,18 @@ class UserApiKeyService:
|
||||
self.user_apikey_repository = UserApiKeyRepository(db)
|
||||
|
||||
def create(self, user_id: str, name: str, description: str = "") -> UserApiKey:
|
||||
"""Create a new API key for the user with generated token."""
|
||||
if self.user_apikey_repository.check_user_apikey_by_name(user_id, name):
|
||||
raise ValueError("Auth key name \"{{name}}\" already exists")
|
||||
user_apikey = self.user_apikey_repository.create(user_id, name, description)
|
||||
return user_apikey
|
||||
|
||||
def modify(
|
||||
self, id: str, user_id: str, name: Optional[str] = None, description: Optional[str] = None, expire_at: Optional[datetime] = None
|
||||
) -> Optional[UserApiKey]:
|
||||
"""Modify an existing API key."""
|
||||
if name and self.user_apikey_repository.check_user_apikey_by_name(user_id, name, id):
|
||||
raise ValueError("Auth key name \"{{name}}\" already exists")
|
||||
user_apikey = self.user_apikey_repository.get_by_id(id)
|
||||
if not user_apikey or user_apikey.user_id != user_id:
|
||||
return None
|
||||
|
||||
@@ -37,9 +37,9 @@ class UserService:
|
||||
"""Delete user"""
|
||||
return self.user_repository.delete(user_id)
|
||||
|
||||
def get_user_list(self, offset: int, limit: int) -> Tuple[int, List[User]]:
|
||||
def get_user_list(self, offset: int, limit: int, keyword: Optional[str] = None) -> Tuple[int, List[User]]:
|
||||
"""Get user list"""
|
||||
return self.user_repository.get_user_list(offset, limit)
|
||||
return self.user_repository.get_user_list(offset, limit, keyword)
|
||||
|
||||
def get_admin_user(self) -> Optional[User]:
|
||||
"""Get admin user"""
|
||||
|
||||
@@ -1,13 +1,23 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.models.user_wallet_history import UserWalletHistory
|
||||
|
||||
from services.admin_service.repositories.user_wallet_history_repository import UserWalletHistoryRepository
|
||||
from services.admin_service.repositories.user_repository import UserRepository
|
||||
|
||||
|
||||
from typing import Optional, Dict, Any, List, Tuple
|
||||
from datetime import datetime
|
||||
from services.common.models.user_wallet_history import TransactionType
|
||||
from services.admin_service.repositories.mcp_service_repository import McpServiceRepository
|
||||
import json
|
||||
|
||||
|
||||
|
||||
class UserWalletHistoryService:
|
||||
def __init__(self, db: Session):
|
||||
self.user_wallet_history_repository = UserWalletHistoryRepository(db)
|
||||
self.user_repository = UserRepository(db)
|
||||
self.mcp_service_repository = McpServiceRepository(db)
|
||||
|
||||
def add_deposit(self, user_id: str, amount: float, payment_method: str) -> UserWalletHistory:
|
||||
return self.user_wallet_history_repository.add_deposit(user_id, amount, payment_method)
|
||||
@@ -15,8 +25,58 @@ class UserWalletHistoryService:
|
||||
def add_refund(self, user_id: str, amount: float, payment_method: str, transaction_id: str) -> UserWalletHistory:
|
||||
return self.user_wallet_history_repository.add_refund(user_id, amount, payment_method, transaction_id)
|
||||
|
||||
def success_deposit_order_list(self, offset: int, limit: int) -> Tuple[int, List[UserWalletHistory]]:
|
||||
return self.user_wallet_history_repository.success_deposit_order_list(offset, limit)
|
||||
def success_deposit_order_list(self, offset: int, limit: int, keyword: Optional[str] = None, sort_amount: Optional[str] = "desc", filter_payment_type: Optional[list] = None) -> Tuple[int, List[UserWalletHistory]]:
|
||||
userIds = None
|
||||
if keyword:
|
||||
|
||||
users = self.user_repository.get_all_user(keyword, include_deleted=True)
|
||||
userIds = [user.id for user in users]
|
||||
print(f"users,{userIds},keyword:{keyword}")
|
||||
if len(userIds) == 0:
|
||||
return 0, []
|
||||
return self.user_wallet_history_repository.success_deposit_order_list(offset, limit, userIds, sort_amount, filter_payment_type)
|
||||
|
||||
def success_order_list_by_user(self, user_id: str, offset: int, limit: int, order_type: Optional[List[str]] = None, status: Optional[List[int]] = None) -> Tuple[int, List[dict]]:
|
||||
total, orders = self.user_wallet_history_repository.success_order_list_by_user(user_id, offset, limit, order_type, status)
|
||||
if total == 0:
|
||||
return total, []
|
||||
result = []
|
||||
for order in orders:
|
||||
confirm_at = ""
|
||||
if order.status == 1:
|
||||
confirm_at = order.updated_at
|
||||
info = {
|
||||
"id": order.id,
|
||||
"user_id": order.user_id,
|
||||
"order_id": order.transaction_id,
|
||||
"payment_type": order.payment_method,
|
||||
"payment_state": order.status,
|
||||
"amount": order.amount,
|
||||
"create_at": order.created_at,
|
||||
"confirm_at": confirm_at,
|
||||
}
|
||||
if order.type == TransactionType.API_CALL:
|
||||
info["order_type"] = "purchase"
|
||||
try:
|
||||
callback_data = json.loads(order.callback_data)
|
||||
service = self.mcp_service_repository.get_by_id(callback_data["service_id"])
|
||||
if service:
|
||||
info["description"] = service.name
|
||||
except:
|
||||
info["description"] = "-"
|
||||
info["balance"] = order.balance_after
|
||||
elif order.type == TransactionType.DEPOSIT:
|
||||
info["order_type"] = "recharge"
|
||||
if order.status == 1:
|
||||
info["balance"] = order.balance_after
|
||||
else:
|
||||
info["balance"] = "-"
|
||||
info["description"] = order.payment_method
|
||||
else:
|
||||
info["order_type"] = order.type
|
||||
result.append(info)
|
||||
return total, result
|
||||
return total, orders
|
||||
|
||||
def order_list(self, payment_method: str, status: int, start: Optional[datetime] = None, end: Optional[datetime] = None) -> List[UserWalletHistory]:
|
||||
return self.user_wallet_history_repository.order_list(payment_method, status, start, end)
|
||||
|
||||
@@ -25,3 +25,9 @@ class UserUtils:
|
||||
"""Check if current user is admin"""
|
||||
user = UserUtils.get_request_user(request)
|
||||
return user and user.role_id == 1 if user else False
|
||||
|
||||
@staticmethod
|
||||
def is_normal_user(request) -> bool:
|
||||
"""Check if current user is normal user"""
|
||||
user = UserUtils.get_request_user(request)
|
||||
return user and user.role_id == 2 if user else False
|
||||
@@ -293,40 +293,42 @@ class HttpRequestBuilder:
|
||||
"""
|
||||
if not hasattr(tool_config, 'request_body_schema') or not tool_config.request_body_schema or tool_config.method.value not in ["POST", "PUT", "PATCH"]:
|
||||
return None
|
||||
|
||||
try:
|
||||
# First try to parse as parameters list (similar to query/path parameters)
|
||||
request_body = {}
|
||||
body_params = self._safe_parse_params(tool_config.request_body_schema, 'body')
|
||||
if body_params:
|
||||
# If it's a list of parameters, process them like query parameters
|
||||
request_body = {}
|
||||
for param in body_params:
|
||||
if isinstance(param, dict) and "name" in param:
|
||||
param_name = param["name"]
|
||||
if param_name in arguments:
|
||||
request_body[param_name] = arguments[param_name]
|
||||
|
||||
if isinstance(param, dict):
|
||||
name = param.get("name")
|
||||
if name and name in arguments:
|
||||
request_body[name] = arguments[name]
|
||||
else:
|
||||
t = param.get("type")
|
||||
if t == "object":
|
||||
props = param.get("properties")
|
||||
if isinstance(props, dict):
|
||||
for prop_name in props.keys():
|
||||
if prop_name in arguments:
|
||||
request_body[prop_name] = arguments[prop_name]
|
||||
if request_body:
|
||||
# logger.debug(f"Built request body from parameters: {request_body}")
|
||||
return request_body
|
||||
else:
|
||||
# If not a parameters list, try to parse as JSON schema object
|
||||
try:
|
||||
body_schema = json.loads(tool_config.request_body_schema)
|
||||
logger.debug(f"Request body schema: {body_schema}")
|
||||
|
||||
if isinstance(body_schema, dict) and "properties" in body_schema:
|
||||
request_body = {}
|
||||
for prop_name in body_schema["properties"]:
|
||||
try:
|
||||
body_schema = json.loads(tool_config.request_body_schema)
|
||||
if isinstance(body_schema, dict):
|
||||
props = body_schema.get("properties")
|
||||
if isinstance(props, dict):
|
||||
for prop_name in props.keys():
|
||||
if prop_name in arguments:
|
||||
request_body[prop_name] = arguments[prop_name]
|
||||
|
||||
if request_body:
|
||||
# logger.debug(f"Built request body from schema: {request_body}")
|
||||
return request_body
|
||||
except json.JSONDecodeError:
|
||||
logger.warning(f"Failed to parse request body schema as JSON")
|
||||
|
||||
else:
|
||||
for key in body_schema.keys():
|
||||
if key in arguments:
|
||||
request_body[key] = arguments[key]
|
||||
if request_body:
|
||||
return request_body
|
||||
except json.JSONDecodeError:
|
||||
logger.warning(f"Failed to parse request body schema as JSON")
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"Request body schema parsing failed: {e}")
|
||||
|
||||
|
||||
@@ -25,7 +25,8 @@ class Config:
|
||||
DB_POOL_SIZE = int(os.getenv("DB_POOL_SIZE", 20))
|
||||
DB_MAX_OVERFLOW = int(os.getenv("DB_MAX_OVERFLOW", 30))
|
||||
DB_POOL_TIMEOUT = int(os.getenv("DB_POOL_TIMEOUT", 30))
|
||||
DB_POOL_RECYCLE = int(os.getenv("DB_POOL_RECYCLE", 3600))
|
||||
# 默认回收时间改为600秒(10分钟),避免防火墙或MySQL wait_timeout断开连接
|
||||
DB_POOL_RECYCLE = int(os.getenv("DB_POOL_RECYCLE", 600))
|
||||
DB_POOL_PRE_PING = os.getenv("DB_POOL_PRE_PING", "true").lower() == "true"
|
||||
|
||||
SMTP_HOST = os.getenv("SMTP_HOST", "smtp.example.com")
|
||||
@@ -58,6 +59,7 @@ class Config:
|
||||
"/api/auth/account/sign",
|
||||
"/api/auth/email/send_captcha",
|
||||
"/api/auth/google/sign",
|
||||
"/api/web/mcp_tags",
|
||||
"/api/web/mcp_services",
|
||||
"/api/web/mcp_service_info",
|
||||
"/api/payment/callback_stripe",
|
||||
|
||||
@@ -8,7 +8,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
# Build database engine configuration
|
||||
engine_config = {
|
||||
"url": f"mysql+mysqlconnector://{Config.MYSQL_USER}:{Config.MYSQL_PASSWORD}@{Config.MYSQL_HOST}:{Config.MYSQL_PORT}/{Config.MYSQL_DB}",
|
||||
"url": f"mysql+pymysql://{Config.MYSQL_USER}:{Config.MYSQL_PASSWORD}@{Config.MYSQL_HOST}:{Config.MYSQL_PORT}/{Config.MYSQL_DB}",
|
||||
"echo": Config.DEBUG,
|
||||
"pool_size": Config.DB_POOL_SIZE,
|
||||
"max_overflow": Config.DB_MAX_OVERFLOW,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from sqlalchemy import String, Text, DateTime
|
||||
from sqlalchemy import Integer, String, Text, DateTime, false
|
||||
from sqlalchemy.sql import func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from services.common.models.base import Base
|
||||
@@ -27,3 +27,4 @@ class UserApiKey(Base):
|
||||
server_onupdate=func.current_timestamp(),
|
||||
comment="Last update timestamp",
|
||||
)
|
||||
is_deleted: Mapped[int] = mapped_column(Integer,nullable=False,default=0,comment="Already be Deleted")
|
||||
@@ -94,6 +94,13 @@ class RedisClient:
|
||||
except redis.RedisError as e:
|
||||
raise Exception(f"Redis TTL operation failed: {e}")
|
||||
|
||||
def incr(self, key: str, amount: int = 1) -> Any:
|
||||
"""Increment key value"""
|
||||
try:
|
||||
return self.client.incr(key, amount)
|
||||
except redis.RedisError as e:
|
||||
raise Exception(f"Redis INCR operation failed: {e}")
|
||||
|
||||
def close(self):
|
||||
"""Close Redis connection"""
|
||||
try:
|
||||
|
||||
@@ -42,3 +42,13 @@ class RedisKeys:
|
||||
def user_apikey_key(apikey_hash: str) -> str:
|
||||
"""Generate user API key cache key (using hash for security)"""
|
||||
return f"xpack:user_apikey:{apikey_hash}"
|
||||
|
||||
@staticmethod
|
||||
def login_fail_count_key(ip: str, user: str) -> str:
|
||||
"""Generate login fail count cache key"""
|
||||
return f"xpack:login:fail:{user}:{ip}"
|
||||
|
||||
@staticmethod
|
||||
def login_ban_key(ip: str, user: str) -> str:
|
||||
"""Generate login ban cache key"""
|
||||
return f"xpack:login:ban:{user}:{ip}"
|
||||
@@ -33,7 +33,7 @@ def verify_token(token: str, db: Session) -> Optional[User]:
|
||||
set_model_cache(token_cache_key, user_access_token, TOKEN_CACHE_EXPIRE_TIME)
|
||||
|
||||
logging.info(f"query token info")
|
||||
|
||||
print(f'user_access_token: {user_access_token}, expire_at: {user_access_token.expire_at},token_cache_key: {token_cache_key}')
|
||||
# Check if token is expired
|
||||
expire_at = user_access_token.expire_at
|
||||
try:
|
||||
|
||||
@@ -125,6 +125,8 @@ class CacheUtils:
|
||||
else:
|
||||
logger.warning(f"Unexpected cache value type for key {cache_key}: {type(cache_value)}")
|
||||
return None
|
||||
if isinstance(model_data,list):
|
||||
return model_data
|
||||
return SqlalchemyUtils.dict_to_model(model_class, model_data)
|
||||
return None
|
||||
except Exception as e:
|
||||
@@ -145,7 +147,10 @@ class CacheUtils:
|
||||
bool: True if successful, False otherwise
|
||||
"""
|
||||
try:
|
||||
model_dict = SqlalchemyUtils.model_to_dict(model)
|
||||
if isinstance(model, list):
|
||||
return CacheUtils.set_sqlalchemy_list_cache(cache_key, model, expire_time)
|
||||
else:
|
||||
model_dict = SqlalchemyUtils.model_to_dict(model)
|
||||
serialized_data = json.dumps(model_dict, ensure_ascii=False)
|
||||
redis_client.set(cache_key, serialized_data, ex=expire_time)
|
||||
return True
|
||||
@@ -203,11 +208,15 @@ class CacheUtils:
|
||||
if not isinstance(model_list, list):
|
||||
logger.error(f"Expected list for cache key {cache_key}, got {type(model_list)}")
|
||||
return False
|
||||
|
||||
model_dict_list = [SqlalchemyUtils.model_to_dict(model) for model in model_list]
|
||||
serialized_data = json.dumps(model_dict_list, ensure_ascii=False)
|
||||
data = []
|
||||
for model in model_list:
|
||||
if isinstance(model,dict):
|
||||
data.append(SqlalchemyUtils.model_to_dict(model))
|
||||
else:
|
||||
data.append(model)
|
||||
serialized_data = json.dumps(data, ensure_ascii=False)
|
||||
redis_client.set(cache_key, serialized_data, ex=expire_time)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to set SQLAlchemy list cache for key {cache_key}: {e}")
|
||||
logger.error(f"Failed to set SQLAlchemy list cache for key aaa {cache_key}: {e}")
|
||||
return False
|
||||
Reference in new issue
Block a user