21 files changed
+597
-83
No files matched your search
@@ -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",
|
||||
|
||||
@@ -881,5 +881,13 @@
|
||||
"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",
|
||||
"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"
|
||||
}
|
||||
@@ -949,5 +949,12 @@
|
||||
"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}}\" 已存在",
|
||||
"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;
|
||||
}
|
||||
@@ -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">
|
||||
|
||||
@@ -90,6 +90,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 */}
|
||||
|
||||
@@ -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,43 @@ const ResourceGroupManagement: React.FC = () => {
|
||||
|
||||
// 保存组(创建或编辑)
|
||||
const handleSaveGroup = async (name: string, isDefault: boolean) => {
|
||||
// 去除首尾空格
|
||||
const trimmedName = name.trim();
|
||||
|
||||
// 验证保留名称(不区分大小写)
|
||||
const reservedNames = ['allow all', 'deny all'];
|
||||
if (reservedNames.some(reserved => reserved.toLowerCase() === trimmedName.toLowerCase())) {
|
||||
toast.error(t('Resource group name "{{name}}" is reserved and cannot be used', { name: trimmedName }));
|
||||
return;
|
||||
}
|
||||
|
||||
// 验证名称是否重复
|
||||
const isDuplicate = groups.some(group => {
|
||||
// 编辑时排除当前组
|
||||
if (editingGroup && group.id === editingGroup.id) {
|
||||
return false;
|
||||
}
|
||||
return group.name.toLowerCase() === trimmedName.toLowerCase();
|
||||
});
|
||||
|
||||
if (isDuplicate) {
|
||||
toast.error(t('Resource group name "{{name}}" already exists', { name: trimmedName }));
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -78,7 +78,7 @@ def account_login(body: dict = Body(...), auth_service: AuthService = Depends(ge
|
||||
if token:
|
||||
return ResponseUtils.success({"user_token": token})
|
||||
else:
|
||||
return ResponseUtils.error(message="login failed", code=401)
|
||||
return ResponseUtils.error(message="login failed, please enter the correct account or password", code=401)
|
||||
|
||||
|
||||
@router.post("/google/sign", response_model=dict)
|
||||
@@ -95,7 +95,7 @@ def google_login(request: Request, body: dict = Body(...), auth_service: AuthSer
|
||||
if token:
|
||||
return ResponseUtils.success({"user_token": token})
|
||||
else:
|
||||
return ResponseUtils.error(message=f"login failed: {redirect_uri}", code=401)
|
||||
return ResponseUtils.error(message=f"login failed, please check the redirect_uri: {redirect_uri}", code=401)
|
||||
|
||||
|
||||
@router.delete("/logout", response_model=dict)
|
||||
|
||||
@@ -244,5 +244,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
|
||||
@@ -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}")
|
||||
|
||||
|
||||
@@ -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