Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
588f2770b7 | ||
|
|
ad743d6ab7 | ||
|
|
6145d0b005 | ||
|
|
d147fcb070 | ||
|
|
6196b93e97 | ||
|
|
b51933d625 | ||
|
|
40ff118798 | ||
|
|
d470677abe | ||
|
|
6eac3c6100 | ||
|
|
d22513730a | ||
|
|
613cece94b | ||
|
|
5cd1c12323 | ||
|
|
dcf73b25bf | ||
|
|
64a67e9c8d | ||
|
|
b6160af3c5 | ||
|
|
2ea41dfb75 | ||
|
|
cbcc419f0b | ||
|
|
687949beb2 | ||
|
|
fedaa5f5df | ||
|
|
c272c87e1f | ||
|
|
8a052ff910 | ||
|
|
d1c7a4b8c0 | ||
|
|
1a104338e8 | ||
|
|
5dd47b2d01 | ||
|
|
a28de60b1c | ||
|
|
e4a807b2a0 | ||
|
|
d0e7ed2771 | ||
|
|
05c0088f1b | ||
|
|
7f66cfd21e | ||
|
|
05b48f3656 | ||
|
|
07fe83b7b5 | ||
|
|
5fa1cd741e | ||
|
|
3e1d986c1c | ||
|
|
2cf95fd1c1 | ||
|
|
09b6811391 | ||
|
|
08d326dc1f | ||
|
|
fb23d62fb2 | ||
|
|
79400146ea | ||
|
|
503b3bf078 | ||
|
|
eb4ecff6ed | ||
|
|
7f8947f070 | ||
|
|
6dca9b08cc | ||
|
|
06034cf46e | ||
|
|
ffdf931cad | ||
|
|
24e59f18d0 | ||
|
|
5a538863b1 | ||
|
|
f468fe270f | ||
|
|
4cc8b87de5 | ||
|
|
f6e0130035 | ||
|
|
d351afb732 | ||
|
|
fab064975d | ||
|
|
30a06d74d6 | ||
|
|
6f882845c2 | ||
|
|
33d66e7d3b | ||
|
|
5654f83644 | ||
|
|
b7c67cc44f | ||
|
|
6d15420b08 | ||
|
|
32562b9c25 | ||
|
|
5469eca450 | ||
|
|
94fd46c8ca | ||
|
|
ffc09b7b83 | ||
|
|
f4bd572fff | ||
|
|
57bd964d22 | ||
|
|
3c4e2be1dd | ||
|
|
aac3a187d1 | ||
|
|
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 | ||
|
|
595994de8c | ||
|
|
c7bbd0589c | ||
|
|
6f83fc7a88 | ||
|
|
64d559dd31 | ||
|
|
d9fe780665 | ||
|
|
9d5d1ce2c5 | ||
|
|
f9c8a74849 | ||
|
|
b23662d76a | ||
|
|
4f27baf93a | ||
|
|
20f09ce044 | ||
|
|
cb93e5c5aa | ||
|
|
ae57e5b431 | ||
|
|
06b71995f3 | ||
|
|
52c135a7c6 | ||
|
|
2c5c28c74f | ||
|
|
1eb0e23971 | ||
|
|
a0c2bfe9a6 | ||
|
|
9f55110fb3 | ||
|
|
01cbdbe5b0 | ||
|
|
0e58492387 | ||
|
|
8fabe93710 |
No files matched your search
+10
-1
@@ -26,8 +26,17 @@ RABBITMQ_USER=rabbitmq
|
||||
RABBITMQ_PASSWORD=rabbitmq_Gs123dA
|
||||
RABBITMQ_VHOST=/
|
||||
|
||||
# Billing queue / retry settings
|
||||
BILLING_QUEUE_NAME=billing.api.calls
|
||||
# Max retry attempts (excluding initial consumption)
|
||||
BILLING_RETRY_TIMES=3
|
||||
# Base delay seconds for exponential backoff: base * 2^retry_count
|
||||
BILLING_RETRY_BASE_DELAY_SECONDS=30
|
||||
# Max delay seconds cap
|
||||
BILLING_RETRY_MAX_DELAY_SECONDS=1800
|
||||
|
||||
# Payment config encryption key (Base64-encoded 32-byte random value for AES-GCM)
|
||||
# Quick generation: python -c "import os,base64; print(base64.b64encode(os.urandom(32)).decode())"
|
||||
PAYMENT_CONFIG_SECRET_KEY=uyyhfMJ+xpEE+IC5mPigpscekkR2ucz6Sj7sHYLhJQA=
|
||||
# Optional: key ID used to support key rotation identification
|
||||
PAYMENT_CONFIG_KEY_ID=default
|
||||
PAYMENT_CONFIG_KEY_ID=default
|
||||
+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"
|
||||
}
|
||||
@@ -949,5 +949,13 @@
|
||||
"Display tags bar": "显示标签栏",
|
||||
"Front end displays tags bar and allows users to filter products based on tags.": "前端显示标签栏,允许用户根据标签过滤产品。",
|
||||
"Tags Bar": "标签栏",
|
||||
"Auth Key Name": "认证密钥名称"
|
||||
"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">
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"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";
|
||||
@@ -8,6 +8,8 @@ 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";
|
||||
|
||||
@@ -23,6 +25,7 @@ const UserManagement: React.FC = () => {
|
||||
handleDeleteUser,
|
||||
setPage,
|
||||
handleRechargeUser,
|
||||
setSearch,
|
||||
} = useUserManagement();
|
||||
|
||||
// Modal states
|
||||
@@ -35,6 +38,19 @@ const UserManagement: React.FC = () => {
|
||||
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({
|
||||
@@ -81,6 +97,21 @@ 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
|
||||
@@ -99,6 +130,25 @@ 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}
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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 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>
|
||||
|
||||
+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
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"version": "v1.2",
|
||||
"releaseDate": "2025-12-22",
|
||||
"version": "v1.4",
|
||||
"releaseDate": "2026-02-23",
|
||||
"description": "This is the latest release of the application.",
|
||||
"downloads": {
|
||||
"program": {
|
||||
"xpack_mcp_market": {
|
||||
"version": "v1.2.1",
|
||||
"version": "v1.4.1",
|
||||
"docker": "xpackai/xpack-mcp-market",
|
||||
"tar": "xpack-mcp-market.tar.gz",
|
||||
"url": "https://public.eolinker.com/xpack/images/xpack-mcp-market.${VERSION}.${ARCH}.tar.gz"
|
||||
|
||||
@@ -21,9 +21,14 @@ class BillingMessageConsumer:
|
||||
|
||||
def __init__(self):
|
||||
self.queue_name = os.getenv("BILLING_QUEUE_NAME") or "billing.api.calls"
|
||||
self.retry_queue_name = f"{self.queue_name}.retry"
|
||||
self.connection = None
|
||||
self.channel = None
|
||||
self.consuming = False
|
||||
# retry times from env, default 3
|
||||
self.max_retries = int(os.getenv("BILLING_RETRY_TIMES", "3"))
|
||||
self.retry_base_delay_seconds = int(os.getenv("BILLING_RETRY_BASE_DELAY_SECONDS", "30"))
|
||||
self.retry_max_delay_seconds = int(os.getenv("BILLING_RETRY_MAX_DELAY_SECONDS", "1800"))
|
||||
self._setup_connection()
|
||||
|
||||
def _setup_connection(self):
|
||||
@@ -48,6 +53,14 @@ class BillingMessageConsumer:
|
||||
|
||||
# Declare queue
|
||||
self.channel.queue_declare(queue=self.queue_name, durable=True)
|
||||
self.channel.queue_declare(
|
||||
queue=self.retry_queue_name,
|
||||
durable=True,
|
||||
arguments={
|
||||
"x-dead-letter-exchange": "",
|
||||
"x-dead-letter-routing-key": self.queue_name,
|
||||
},
|
||||
)
|
||||
|
||||
# Set QoS, only process one message at a time
|
||||
self.channel.basic_qos(prefetch_count=1)
|
||||
@@ -124,6 +137,29 @@ class BillingMessageConsumer:
|
||||
body: Message body
|
||||
"""
|
||||
message_data = None
|
||||
settled = False
|
||||
raw_body = body.decode("utf-8", errors="replace") if isinstance(body, (bytes, bytearray)) else str(body)
|
||||
|
||||
def _safe_ack() -> None:
|
||||
nonlocal settled
|
||||
if settled:
|
||||
return
|
||||
settled = True
|
||||
try:
|
||||
channel.basic_ack(delivery_tag=method.delivery_tag)
|
||||
except Exception:
|
||||
logger.error("Failed to ack message", exc_info=True)
|
||||
|
||||
def _safe_nack(requeue: bool) -> None:
|
||||
nonlocal settled
|
||||
if settled:
|
||||
return
|
||||
settled = True
|
||||
try:
|
||||
channel.basic_nack(delivery_tag=method.delivery_tag, requeue=requeue)
|
||||
except Exception:
|
||||
logger.error("Failed to nack message", exc_info=True)
|
||||
|
||||
try:
|
||||
# Parse message
|
||||
message_data = json.loads(body)
|
||||
@@ -137,27 +173,68 @@ class BillingMessageConsumer:
|
||||
|
||||
if success:
|
||||
# Ack if processed successfully
|
||||
channel.basic_ack(delivery_tag=method.delivery_tag)
|
||||
_safe_ack()
|
||||
logger.info(f"Message processed and acknowledged: {message_data.get('user_id')}")
|
||||
else:
|
||||
# If failed, ack and drop (avoid infinite retry)
|
||||
channel.basic_ack(delivery_tag=method.delivery_tag)
|
||||
logger.error(f"Message processing failed, message dropped: {message_data.get('user_id')}")
|
||||
# Retry with limited attempts
|
||||
retry_count = self._get_retry_count(properties)
|
||||
if retry_count < self.max_retries:
|
||||
try:
|
||||
delay_ms = self._get_retry_delay_ms(retry_count)
|
||||
self._publish_delayed_retry(channel, message_data, retry_count + 1, delay_ms)
|
||||
_safe_ack()
|
||||
logger.warning(
|
||||
f"Message processing failed, scheduled retry {retry_count + 1}/{self.max_retries} after {delay_ms}ms: {message_data.get('user_id')}, tool={message_data.get('tool_name')}, "
|
||||
)
|
||||
except Exception as pub_err:
|
||||
logger.error(f"Failed to requeue message for retry: {pub_err}", exc_info=True)
|
||||
# Requeue original message
|
||||
_safe_nack(requeue=True)
|
||||
else:
|
||||
# Exceeded retries; ack and drop
|
||||
_safe_ack()
|
||||
self._log_retry_exceeded(
|
||||
reason="handler_returned_false",
|
||||
retry_count=retry_count,
|
||||
properties=properties,
|
||||
method=method,
|
||||
message_data=message_data,
|
||||
raw_body=raw_body,
|
||||
)
|
||||
|
||||
finally:
|
||||
db.close()
|
||||
try:
|
||||
db.close()
|
||||
except Exception:
|
||||
logger.error("Failed to close db session", exc_info=True)
|
||||
|
||||
except json.JSONDecodeError as e:
|
||||
logger.error(f"Message format error: {str(e)}, body: {body}")
|
||||
# Format error, ack directly (do not requeue)
|
||||
channel.basic_ack(delivery_tag=method.delivery_tag)
|
||||
_safe_ack()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Exception occurred while processing message: {str(e)}", exc_info=True)
|
||||
# On exception, ack and drop (avoid infinite retry)
|
||||
try:
|
||||
channel.basic_ack(delivery_tag=method.delivery_tag)
|
||||
logger.error(f"Exception handling failed, message dropped")
|
||||
retry_count = self._get_retry_count(properties)
|
||||
if message_data is not None and retry_count < self.max_retries:
|
||||
delay_ms = self._get_retry_delay_ms(retry_count)
|
||||
self._publish_delayed_retry(channel, message_data, retry_count + 1, delay_ms, error=str(e))
|
||||
_safe_ack()
|
||||
logger.warning(
|
||||
f"Exception during processing, scheduled retry {retry_count + 1}/{self.max_retries} after {delay_ms}ms: {message_data.get('user_id')}"
|
||||
)
|
||||
else:
|
||||
_safe_ack()
|
||||
self._log_retry_exceeded(
|
||||
reason="exception",
|
||||
retry_count=retry_count,
|
||||
properties=properties,
|
||||
method=method,
|
||||
message_data=message_data,
|
||||
error=str(e),
|
||||
raw_body=raw_body,
|
||||
)
|
||||
except:
|
||||
# If even ack fails, log error but do not raise
|
||||
logger.error("Unable to acknowledge message", exc_info=True)
|
||||
@@ -173,9 +250,62 @@ class BillingMessageConsumer:
|
||||
int: Retry count
|
||||
"""
|
||||
if properties and properties.headers:
|
||||
return properties.headers.get("x-retry-count", 0)
|
||||
raw = properties.headers.get("x-retry-count", 0)
|
||||
try:
|
||||
return int(raw)
|
||||
except Exception:
|
||||
return 0
|
||||
return 0
|
||||
|
||||
def _get_retry_delay_ms(self, current_retry_count: int) -> int:
|
||||
delay_seconds = self.retry_base_delay_seconds * (2 ** current_retry_count)
|
||||
if delay_seconds > self.retry_max_delay_seconds:
|
||||
delay_seconds = self.retry_max_delay_seconds
|
||||
return int(delay_seconds * 1000)
|
||||
|
||||
def _publish_delayed_retry(self, channel, message_data: dict, next_retry_count: int, delay_ms: int, error: str | None = None) -> None:
|
||||
headers: dict[str, str | int] = {"x-retry-count": next_retry_count}
|
||||
if error:
|
||||
headers["x-last-error"] = error
|
||||
props = pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
headers=headers,
|
||||
expiration=str(delay_ms),
|
||||
)
|
||||
channel.basic_publish(exchange="", routing_key=self.retry_queue_name, body=json.dumps(message_data), properties=props)
|
||||
|
||||
def _log_retry_exceeded(self, reason: str, retry_count: int, properties, method, message_data: dict | None, error: str | None = None, raw_body: str | None = None) -> None:
|
||||
headers = {}
|
||||
if properties and properties.headers:
|
||||
try:
|
||||
headers = dict(properties.headers)
|
||||
except Exception:
|
||||
headers = {}
|
||||
event = {
|
||||
"reason": reason,
|
||||
"retry_count": retry_count,
|
||||
"max_retries": self.max_retries,
|
||||
"queue": self.queue_name,
|
||||
"routing_key": getattr(method, "routing_key", None),
|
||||
"delivery_tag": getattr(method, "delivery_tag", None),
|
||||
"headers": headers,
|
||||
"user_id": (message_data or {}).get("user_id"),
|
||||
"service_id": (message_data or {}).get("service_id"),
|
||||
"api_id": (message_data or {}).get("api_id"),
|
||||
"tool_name": (message_data or {}).get("tool_name"),
|
||||
"call_start_time": (message_data or {}).get("call_start_time"),
|
||||
"call_end_time": (message_data or {}).get("call_end_time"),
|
||||
}
|
||||
if error:
|
||||
event["error"] = error
|
||||
if raw_body is not None:
|
||||
event["raw_body"] = raw_body
|
||||
try:
|
||||
payload = json.dumps(event, ensure_ascii=False, default=str)
|
||||
except Exception:
|
||||
payload = repr(event)
|
||||
logger.error(f"ALERT billing message retries exceeded: {payload}")
|
||||
|
||||
|
||||
def start_billing_consumer():
|
||||
"""Start billing message consumer"""
|
||||
|
||||
@@ -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,6 +18,7 @@ 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."""
|
||||
@@ -81,8 +84,10 @@ 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)):
|
||||
"""Get homepage configuration settings without authentication."""
|
||||
def get_homepage_config(
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
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()
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
from os import stat
|
||||
from typing import Optional, List
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from services.common.models.user_wallet_history import TransactionType
|
||||
from 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()
|
||||
|
||||
@@ -22,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 = []
|
||||
@@ -58,6 +68,7 @@ def get_user_order_list(
|
||||
|
||||
@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"),
|
||||
@@ -66,6 +77,8 @@ def get_user_order_list_by_user_id(
|
||||
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:
|
||||
|
||||
@@ -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)
|
||||
@@ -173,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 = ""
|
||||
@@ -334,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)
|
||||
|
||||
@@ -11,6 +11,9 @@ 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
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -11,17 +11,20 @@ class McpCallLogRepository:
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def create(self, call_log: McpCallLog) -> McpCallLog:
|
||||
def create(self, call_log: McpCallLog, commit: bool = True) -> McpCallLog:
|
||||
self.db.add(call_log)
|
||||
self.db.commit()
|
||||
self.db.refresh(call_log)
|
||||
if commit:
|
||||
self.db.commit()
|
||||
self.db.refresh(call_log)
|
||||
else:
|
||||
self.db.flush()
|
||||
return call_log
|
||||
|
||||
def get_by_id(self, log_id: str) -> Optional[McpCallLog]:
|
||||
return self.db.query(McpCallLog).filter(McpCallLog.id == log_id).first()
|
||||
|
||||
def update_status(
|
||||
self, log_id: str, status: ProcessStatus, error_msg: Optional[str] = None, wallet_history_id: Optional[str] = None
|
||||
self, log_id: str, status: ProcessStatus, error_msg: Optional[str] = None, wallet_history_id: Optional[str] = None, commit: bool = True
|
||||
) -> bool:
|
||||
log_record = self.get_by_id(log_id)
|
||||
if log_record:
|
||||
@@ -30,7 +33,10 @@ class McpCallLogRepository:
|
||||
log_record.error_msg = error_msg
|
||||
if wallet_history_id:
|
||||
log_record.wallet_history_id = wallet_history_id
|
||||
self.db.commit()
|
||||
if commit:
|
||||
self.db.commit()
|
||||
else:
|
||||
self.db.flush()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@@ -71,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
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Optional, List, Tuple, cast
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import func, literal_column
|
||||
from sqlalchemy import Boolean, func, literal_column
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.dialects.mysql import insert as mysql_insert
|
||||
from sqlalchemy.sql.schema import Table
|
||||
@@ -91,14 +91,12 @@ class StatsMcpServiceDateRepository:
|
||||
total = query.scalar()
|
||||
return int(total or 0)
|
||||
|
||||
def increment(self, service_id: str, stats_date: datetime, inc: int = 1) -> None:
|
||||
def increment(self, service_id: str, stats_date: datetime, inc: int = 1, commit: bool = True):
|
||||
"""Atomically increment call_count for (service_id, stats_date) under high concurrency.
|
||||
|
||||
Implementation uses MySQL's ON DUPLICATE KEY UPDATE to avoid race conditions.
|
||||
If the row does not exist, it will be inserted with call_count=inc; otherwise, call_count is increased.
|
||||
"""
|
||||
# Logger for debug purposes
|
||||
print(f"Incrementing call count for service {service_id} on {stats_date} by {inc}")
|
||||
|
||||
# Cast mapped table for typing compatibility with mysql_insert
|
||||
table: Table = cast(Table, StatsMcpServiceDate.__table__)
|
||||
@@ -114,7 +112,10 @@ class StatsMcpServiceDateRepository:
|
||||
updated_at=func.current_timestamp(),
|
||||
)
|
||||
self.db.execute(ondup)
|
||||
self.db.commit()
|
||||
if commit:
|
||||
self.db.commit()
|
||||
else:
|
||||
self.db.flush()
|
||||
|
||||
def increment_fallback(self, service_id: str, stats_date: datetime, inc: int = 1) -> None:
|
||||
"""Fallback increment strategy without dialect-specific upsert.
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -228,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.
|
||||
|
||||
@@ -243,9 +243,20 @@ 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())
|
||||
@@ -285,7 +296,7 @@ class UserWalletHistoryRepository:
|
||||
)
|
||||
return total, history
|
||||
|
||||
def add_consume_record(self, wallet_history: UserWalletHistory) -> Optional[UserWalletHistory]:
|
||||
def add_consume_record(self, wallet_history: UserWalletHistory, commit: bool = True) -> Optional[UserWalletHistory]:
|
||||
"""
|
||||
Add consume record to database.
|
||||
|
||||
@@ -299,12 +310,18 @@ class UserWalletHistoryRepository:
|
||||
# Add the wallet history record to database
|
||||
# The created_at and updated_at fields should be set by the caller
|
||||
self.db.add(wallet_history)
|
||||
self.db.commit()
|
||||
self.db.refresh(wallet_history)
|
||||
if commit:
|
||||
self.db.commit()
|
||||
self.db.refresh(wallet_history)
|
||||
else:
|
||||
self.db.flush()
|
||||
return wallet_history
|
||||
except Exception as e:
|
||||
self.logging.error(f"Failed to add consume record: {str(e)}")
|
||||
self.db.rollback()
|
||||
try:
|
||||
self.db.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
def order_list(self, payment_method: str, status: int, start: Optional[datetime] = None, end: Optional[datetime] = None) -> List[UserWalletHistory]:
|
||||
@@ -424,4 +441,4 @@ class UserWalletHistoryRepository:
|
||||
result.append({"stats_day": current_day, "count": amounts_by_day.get(current_day, 0.0)})
|
||||
current_day += timedelta(days=1)
|
||||
|
||||
return result
|
||||
return result
|
||||
@@ -32,13 +32,16 @@ class UserWalletRepository:
|
||||
"""Get user wallet with row-level lock for update"""
|
||||
return self.db.query(UserWallet).filter(UserWallet.user_id == user_id).with_for_update().first()
|
||||
|
||||
def update_balance(self, user_id: str, new_balance: float) -> bool:
|
||||
def update_balance(self, user_id: str, new_balance: float, commit: bool = True) -> bool:
|
||||
"""Update user balance"""
|
||||
wallet = self.get_by_user_id(user_id)
|
||||
if wallet:
|
||||
wallet.balance = new_balance
|
||||
wallet.updated_at = datetime.now(timezone.utc)
|
||||
self.db.commit()
|
||||
if commit:
|
||||
self.db.commit()
|
||||
else:
|
||||
self.db.flush()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -3,6 +3,7 @@ Billing message handler service
|
||||
"""
|
||||
|
||||
import json
|
||||
from re import finditer
|
||||
import uuid
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
@@ -44,41 +45,60 @@ class BillingMessageHandler:
|
||||
Returns:
|
||||
bool: Whether processing was successful
|
||||
"""
|
||||
call_log_id: Optional[str] = None
|
||||
tx = self.db.begin()
|
||||
try:
|
||||
# Parse message
|
||||
billing_message = self._parse_message(message_data)
|
||||
if not billing_message:
|
||||
tx.rollback()
|
||||
return False
|
||||
|
||||
# Create API call log
|
||||
call_log_id = self._create_call_log(billing_message)
|
||||
if not call_log_id:
|
||||
tx.rollback()
|
||||
return False
|
||||
|
||||
# Update stats_mcp_service_date record
|
||||
# Bucket stats by hour (UTC), aligned to full hours
|
||||
|
||||
start_dt = billing_message.call_start_time
|
||||
start_utc = start_dt.replace(tzinfo=timezone.utc) if start_dt.tzinfo is None else start_dt.astimezone(timezone.utc)
|
||||
# Store as naive UTC datetime to match MySQL DATETIME behavior
|
||||
stats_date = start_utc.replace(minute=0, second=0, microsecond=0, tzinfo=None)
|
||||
self.stats_repo.increment(billing_message.service_id, stats_date, 1)
|
||||
stats_date = start_utc.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
|
||||
self.stats_repo.increment(billing_message.service_id, stats_date, 1, commit=False)
|
||||
|
||||
# Process billing logic
|
||||
if billing_message.call_success and billing_message.unit_price > 0:
|
||||
success = self._process_billing(billing_message, call_log_id)
|
||||
success = self._process_billing(billing_message, call_log_id, commit=False)
|
||||
if not success:
|
||||
# Update record status to failed
|
||||
self.call_log_repo.update_status(call_log_id, ProcessStatus.FAILED, "Billing processing failed")
|
||||
self.call_log_repo.update_status(call_log_id, ProcessStatus.FAILED, "Billing processing failed", commit=False)
|
||||
tx.rollback()
|
||||
return False
|
||||
|
||||
# Update record status to processed
|
||||
self.call_log_repo.update_status(call_log_id, ProcessStatus.PROCESSED)
|
||||
logger.info(f"Billing message processed successfully - User ID: {billing_message.user_id}, Tool: {billing_message.tool_name}")
|
||||
return True
|
||||
|
||||
if not self.call_log_repo.update_status(call_log_id, ProcessStatus.PROCESSED, commit=False):
|
||||
tx.rollback()
|
||||
return False
|
||||
tx.commit()
|
||||
logger.info(f"Billing message processed successfully - User ID: {billing_message.user_id}, Tool: {billing_message.tool_name}")
|
||||
# Update wallet cache after successful commit
|
||||
try:
|
||||
wallet = self.wallet_repo.get_by_user_id(billing_message.user_id)
|
||||
if wallet:
|
||||
self._update_wallet_cache(billing_message.user_id, Decimal(str(wallet.balance)))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to process billing message: {str(e)}", exc_info=True)
|
||||
try:
|
||||
tx.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
if call_log_id:
|
||||
try:
|
||||
self.call_log_repo.update_status(call_log_id, ProcessStatus.FAILED, "Billing processing exception")
|
||||
except Exception:
|
||||
logger.exception("Failed to update call log status after exception")
|
||||
return False
|
||||
finally:
|
||||
if tx.is_active:
|
||||
tx.rollback()
|
||||
|
||||
def _parse_message(self, message_data: dict) -> Optional[BillingMessage]:
|
||||
"""
|
||||
@@ -146,14 +166,14 @@ class BillingMessageHandler:
|
||||
updated_at=datetime.now(timezone.utc),
|
||||
)
|
||||
|
||||
created_log = self.call_log_repo.create(call_log)
|
||||
created_log = self.call_log_repo.create(call_log, commit=False)
|
||||
return created_log.id
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create API call log record: {str(e)}")
|
||||
return None
|
||||
|
||||
def _process_billing(self, billing_message: BillingMessage, call_log_id: str) -> bool:
|
||||
def _process_billing(self, billing_message: BillingMessage, call_log_id: str, commit: bool = True) -> bool:
|
||||
"""
|
||||
Process actual billing logic
|
||||
|
||||
@@ -183,7 +203,7 @@ class BillingMessageHandler:
|
||||
|
||||
# Execute deduction
|
||||
new_balance = current_balance - amount
|
||||
success = self.wallet_repo.update_balance(user_id, float(new_balance))
|
||||
success = self.wallet_repo.update_balance(user_id, float(new_balance), commit=commit)
|
||||
if not success:
|
||||
logger.error(f"Failed to update user wallet balance - User ID: {user_id}")
|
||||
return False
|
||||
@@ -206,22 +226,15 @@ class BillingMessageHandler:
|
||||
updated_at=now,
|
||||
)
|
||||
|
||||
created_history = self.wallet_history_repo.add_consume_record(wallet_history)
|
||||
created_history = self.wallet_history_repo.add_consume_record(wallet_history, commit=commit)
|
||||
if not created_history:
|
||||
logger.error(f"Failed to create wallet history record - User ID: {user_id}")
|
||||
# Rollback balance update
|
||||
self.wallet_repo.update_balance(user_id, float(current_balance))
|
||||
return False
|
||||
|
||||
logger.info(f"Wallet history record created successfully - User ID: {user_id}, History ID: {history_id}, Created at: {now}")
|
||||
|
||||
# Update API call record's actual deduction amount and associated history record ID
|
||||
self.call_log_repo.update_status(call_log_id, ProcessStatus.PROCESSED, None, history_id)
|
||||
|
||||
|
||||
|
||||
# Update wallet balance cache in Redis
|
||||
self._update_wallet_cache(user_id, new_balance)
|
||||
self.call_log_repo.update_status(call_log_id, ProcessStatus.PROCESSED, None, history_id, commit=commit)
|
||||
|
||||
logger.info(
|
||||
f"Billing processing completed successfully - User ID: {user_id}, Amount deducted: {amount}, Balance: {current_balance} -> {new_balance}"
|
||||
|
||||
@@ -325,9 +325,9 @@ 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)
|
||||
|
||||
@@ -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,6 +1,10 @@
|
||||
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
|
||||
@@ -12,6 +16,7 @@ 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:
|
||||
@@ -20,8 +25,16 @@ 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)
|
||||
|
||||
@@ -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
|
||||
@@ -37,7 +37,7 @@ class UserApiKeyRepository:
|
||||
return cached_model
|
||||
|
||||
# Query from database if not in cache
|
||||
user_apikey = self.db.query(UserApiKey).filter(UserApiKey.apikey == apikey).first()
|
||||
user_apikey = self.db.query(UserApiKey).filter(UserApiKey.apikey == apikey, UserApiKey.is_deleted == 0).first()
|
||||
if user_apikey:
|
||||
# Cache the result using new SQLAlchemy-specific method
|
||||
CacheUtils.set_sqlalchemy_cache(cache_key, user_apikey, 300)
|
||||
|
||||
@@ -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}")
|
||||
|
||||
|
||||
@@ -45,7 +45,9 @@ class RedisEventStore(EventStore):
|
||||
|
||||
async def store_event(self, stream_id: StreamId, message: JSONRPCMessage) -> EventId:
|
||||
key = self._key(stream_id)
|
||||
payload = json.dumps(message.model_dump(by_alias=True, exclude_none=True))
|
||||
payload = json.dumps(
|
||||
message.model_dump(by_alias=True, exclude_none=True) if message is not None else {}
|
||||
)
|
||||
# Append to Redis list via thread wrapper to avoid blocking
|
||||
seq: int = await asyncio.to_thread(self._rpush, key, payload)
|
||||
# rpush returns new length; sequence index is length-1
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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")
|
||||
@@ -30,7 +30,7 @@ class RabbitMQClient:
|
||||
logger.error(f"Failed to establish RabbitMQ connection: {str(e)}")
|
||||
raise
|
||||
|
||||
def publish(self, queue: str, message: str, persistent: bool = True):
|
||||
def publish(self, queue: str, message: str, persistent: bool = True, headers: dict | None = None):
|
||||
"""Publish message to queue"""
|
||||
try:
|
||||
# Ensure connection is available
|
||||
@@ -46,7 +46,9 @@ class RabbitMQClient:
|
||||
# Publish message
|
||||
properties = None
|
||||
if persistent:
|
||||
properties = pika.BasicProperties(delivery_mode=2)
|
||||
properties = pika.BasicProperties(delivery_mode=2, headers=headers or None)
|
||||
elif headers:
|
||||
properties = pika.BasicProperties(headers=headers)
|
||||
|
||||
self.channel.basic_publish(exchange="", routing_key=queue, body=message, properties=properties)
|
||||
logger.info(f"Message successfully published to queue: {queue}, message length: {len(message)} bytes")
|
||||
@@ -61,7 +63,10 @@ class RabbitMQClient:
|
||||
|
||||
# Retry sending
|
||||
self.channel.queue_declare(queue=queue, durable=True)
|
||||
properties = pika.BasicProperties(delivery_mode=2) if persistent else None
|
||||
if persistent:
|
||||
properties = pika.BasicProperties(delivery_mode=2, headers=headers or None)
|
||||
else:
|
||||
properties = pika.BasicProperties(headers=headers or None)
|
||||
self.channel.basic_publish(exchange="", routing_key=queue, body=message, properties=properties)
|
||||
logger.info(f"Message retry successful to queue {queue}")
|
||||
except Exception as retry_error:
|
||||
|
||||
@@ -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,6 @@ 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")
|
||||
|
||||
# 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