Sfoglia il codice sorgente

fix(admin): 修复后台管理多个接口路径、表单交互及动态配置删除与搜索功能

jerry 2 mesi fa
parent
commit
0dc1a09000

+ 1 - 1
src/app/admin/accounts/page.tsx

@@ -192,7 +192,7 @@ export default function AdminAccountsPage() {
     });
     if (!ok) return;
     try {
-      await api.delete('/api/account/delete', { params: { id: account.id } });
+      await api.delete('/api/account/delete', { params: { account_id: account.id } });
       toast.success('账号已删除');
       fetchAccounts(page);
     } catch {

+ 72 - 25
src/app/admin/configurations/page.tsx

@@ -14,6 +14,7 @@ import {
   X,
 } from 'lucide-react';
 import { toast } from 'react-hot-toast';
+import { retroConfirm } from '@/lib/dialog';
 import api from '@/lib/api';
 import ConfigurationTable from '@/components/admin/configurations/ConfigurationTable';
 import ConfigurationModal from '@/components/admin/configurations/ConfigurationModal';
@@ -23,15 +24,27 @@ import ConfigurationImportModal from '@/components/admin/configurations/Configur
 import { DynamicConfiguration } from '@/types';
 
 function normalizeConfig(item: Partial<DynamicConfiguration>): DynamicConfiguration {
+  let val = '';
+  if (item.config_value !== null && item.config_value !== undefined) {
+    if (typeof item.config_value === 'string') {
+      val = item.config_value;
+    } else if (typeof item.config_value === 'object') {
+      try {
+        val = JSON.stringify(item.config_value, null, 2);
+      } catch {
+        val = String(item.config_value);
+      }
+    } else {
+      val = String(item.config_value);
+    }
+  }
+
   return {
     id: item.id,
-    config_key: item.config_key || '',
-    config_value:
-      typeof item.config_value === 'string'
-        ? item.config_value
-        : JSON.stringify(item.config_value ?? ''),
-    description: item.description || '',
-    type: item.type || '',
+    config_key: String(item.config_key || ''),
+    config_value: val,
+    description: String(item.description || ''),
+    type: String(item.type || ''),
     created_at: item.created_at,
     updated_at: item.updated_at,
   };
@@ -104,16 +117,22 @@ export default function AdminConfigurationsPage() {
   };
 
   const filteredConfigs = useMemo(() => {
+    const q = keyword.trim().toLowerCase();
     return configs.filter((c) => {
-      const q = keyword.trim().toLowerCase();
+      const configKey = String(c.config_key || '').toLowerCase();
+      const desc = String(c.description || '').toLowerCase();
+      const configVal = String(c.config_value || '').toLowerCase();
+      const configType = String(c.type || '').toLowerCase();
+
       const matchKeyword =
         !q ||
-        c.config_key.toLowerCase().includes(q) ||
-        (c.description && c.description.toLowerCase().includes(q)) ||
-        c.config_value.toLowerCase().includes(q);
+        configKey.includes(q) ||
+        desc.includes(q) ||
+        configVal.includes(q) ||
+        configType.includes(q);
 
-      const isJson =
-        c.config_value?.trim().startsWith('{') || c.config_value?.trim().startsWith('[');
+      const valTrimmed = String(c.config_value || '').trim();
+      const isJson = valTrimmed.startsWith('{') || valTrimmed.startsWith('[');
       const computedType = (c.type || (isJson ? 'json' : 'string')).toLowerCase();
 
       const matchType =
@@ -133,9 +152,9 @@ export default function AdminConfigurationsPage() {
     let stringCount = 0;
 
     configs.forEach((c) => {
-      const isJson =
-        c.config_value?.trim().startsWith('{') || c.config_value?.trim().startsWith('[');
-      if (isJson || c.type?.toLowerCase() === 'json') {
+      const valTrimmed = String(c.config_value || '').trim();
+      const isJson = valTrimmed.startsWith('{') || valTrimmed.startsWith('[');
+      if (isJson || (c.type && c.type.toLowerCase() === 'json')) {
         jsonCount++;
       } else {
         stringCount++;
@@ -160,6 +179,24 @@ export default function AdminConfigurationsPage() {
     setDrawerOpen(true);
   };
 
+  const handleDelete = async (config: DynamicConfiguration) => {
+    const ok = await retroConfirm({
+      title: '[ CONFIRM // 永久删除配置项 ]',
+      message: `警告:确定要永久删除配置项 "${config.config_key}" 吗?此操作不可撤销!`,
+      type: 'danger',
+      confirmText: '[ 确认删除 ]',
+    });
+    if (!ok) return;
+
+    try {
+      await api.delete(`/api/dynamic-configurations/key/${encodeURIComponent(config.config_key)}`);
+      toast.success(`配置 "${config.config_key}" 已删除`);
+      fetchConfigs();
+    } catch (e: any) {
+      toast.error('删除失败: ' + (e.response?.data?.message || e.message || '未知错误'));
+    }
+  };
+
   return (
     <div className="space-y-6 font-mono">
       {/* 顶部标头 */}
@@ -246,19 +283,27 @@ export default function AdminConfigurationsPage() {
             <input
               type="text"
               placeholder="搜索配置 Key / 作用描述 / Value 内容..."
-              className="w-full pl-9 pr-8 py-2 border-2 border-black bg-neutral-50 text-xs font-mono focus:bg-white outline-none shadow-[2px_2px_0px_#000] text-black"
+              className="w-full pl-9 pr-24 py-2 border-2 border-black bg-neutral-50 text-xs font-mono focus:bg-white outline-none shadow-[2px_2px_0px_#000] text-black"
               value={keyword}
               onChange={(e) => setKeyword(e.target.value)}
             />
             <Search size={14} className="absolute left-3 top-2.5 text-black pointer-events-none" />
-            {keyword && (
-              <button
-                onClick={() => setKeyword('')}
-                className="absolute right-2.5 top-2 text-black hover:text-rose-600 font-bold"
-              >
-                ✕
-              </button>
-            )}
+            <div className="absolute right-2.5 top-2 flex items-center gap-1.5">
+              {keyword && (
+                <button
+                  onClick={() => setKeyword('')}
+                  className="text-black hover:text-rose-600 font-bold px-1 text-xs"
+                  title="清空输入"
+                >
+                  ✕
+                </button>
+              )}
+              {keyword && (
+                <span className="text-[10px] font-mono font-bold bg-amber-300 px-1 border border-black text-black">
+                  {filteredConfigs.length} 项
+                </span>
+              )}
+            </div>
           </div>
 
           <div className="flex items-center gap-2 w-full md:w-auto">
@@ -310,6 +355,7 @@ export default function AdminConfigurationsPage() {
         loading={loading}
         onEdit={handleOpenEdit}
         onViewDetails={handleOpenDetails}
+        onDelete={handleDelete}
       />
 
       {/* 5. 新建 / 编辑弹窗 */}
@@ -329,6 +375,7 @@ export default function AdminConfigurationsPage() {
           setDrawerOpen(false);
           handleOpenEdit(cfg);
         }}
+        onDelete={handleDelete}
       />
 
       {/* 7. 导出配置弹窗 */}

+ 1 - 1
src/app/admin/proxies/page.tsx

@@ -206,7 +206,7 @@ export default function AdminProxiesPage() {
     });
     if (!ok) return;
     try {
-      await api.delete('/api/proxy/delete', { params: { id: proxy.id } });
+      await api.delete('/api/proxy/delete', { params: { proxy_id: proxy.id } });
       toast.success('代理节点已删除');
       fetchProxies(page);
     } catch {

+ 41 - 19
src/app/admin/tasks/page.tsx

@@ -153,25 +153,43 @@ export default function AdminTasksPage() {
     return result;
   }, [tasks, routingKeyFilter, retryFilter, keyword, sortField, sortOrder]);
 
-  const metrics = useMemo(() => {
-    const totalCount = tasks.length;
-    const pendingCount = tasks.filter((t) => (t.status || '').toLowerCase() === 'pending').length;
-    const runningCount = tasks.filter((t) => (t.status || '').toLowerCase() === 'running').length;
-    const pauseCount = tasks.filter(
-      (t) => (t.status || '').toLowerCase() === 'pause' || (t.status || '').toLowerCase() === 'paused'
-    ).length;
-    const completedCount = tasks.filter((t) => (t.status || '').toLowerCase() === 'completed').length;
-    const retryingCount = tasks.filter((t) => t.attempt_count > 0).length;
-
-    return {
-      total: totalCount,
-      pending: pendingCount,
-      running: runningCount,
-      pause: pauseCount,
-      completed: completedCount,
-      retrying: retryingCount,
-    };
-  }, [tasks]);
+  // 独立的全局统计数据(不受 statusFilter 影响)
+  const [metrics, setMetrics] = useState({
+    total: 0,
+    pending: 0,
+    running: 0,
+    pause: 0,
+    completed: 0,
+    retrying: 0,
+  });
+
+  const fetchMetrics = useCallback(async () => {
+    try {
+      const res = await api.get('/api/vas/task/list', {
+        params: { page: 1, size: 9999 },
+      });
+      const data = res.data.data || {};
+      const allTasks: VasTask[] = Array.isArray(data) ? data : data.items || [];
+
+      setMetrics({
+        total: allTasks.length,
+        pending: allTasks.filter((t) => (t.status || '').toLowerCase() === 'pending').length,
+        running: allTasks.filter((t) => (t.status || '').toLowerCase() === 'running').length,
+        pause: allTasks.filter(
+          (t) => (t.status || '').toLowerCase() === 'pause' || (t.status || '').toLowerCase() === 'paused'
+        ).length,
+        completed: allTasks.filter((t) => (t.status || '').toLowerCase() === 'completed').length,
+        retrying: allTasks.filter((t) => t.attempt_count > 0).length,
+      });
+    } catch {
+      // 统计请求失败不影响主流程
+    }
+  }, []);
+
+  // 页面加载和任务变更时刷新统计
+  useEffect(() => {
+    fetchMetrics();
+  }, [fetchMetrics]);
 
   const handleSortChange = (field: string) => {
     if (sortField === field) {
@@ -202,6 +220,7 @@ export default function AdminTasksPage() {
       await api.post('/api/vas/task/return_to_queue', null, { params: { task_id: taskId } });
       toast.success('任务已重新排队待命中');
       fetchTasks(page);
+      fetchMetrics();
     } catch (e: any) {
       toast.error('操作失败: ' + (e.response?.data?.message || '未知错误'));
     }
@@ -219,6 +238,7 @@ export default function AdminTasksPage() {
       await api.post('/api/vas/task/manual_confirm', null, { params: { task_id: taskId } });
       toast.success('任务已强制标记为完成');
       fetchTasks(page);
+      fetchMetrics();
     } catch (e: any) {
       toast.error('操作失败: ' + (e.response?.data?.message || '未知错误'));
     }
@@ -236,6 +256,7 @@ export default function AdminTasksPage() {
       await api.post('/api/vas/task/pause', null, { params: { task_id: taskId } });
       toast.success('任务已暂停');
       fetchTasks(page);
+      fetchMetrics();
     } catch (e: any) {
       toast.error('操作失败: ' + (e.response?.data?.message || '未知错误'));
     }
@@ -252,6 +273,7 @@ export default function AdminTasksPage() {
       toast.success('任务信息已更新');
       setIsEditOpen(false);
       fetchTasks(page);
+      fetchMetrics();
     } catch (e: any) {
       toast.error('更新失败: ' + (e.response?.data?.message || '未知错误'));
     }

+ 1 - 1
src/app/admin/users/page.tsx

@@ -24,7 +24,7 @@ export default function AdminUsersPage() {
   const fetchUsers = async (targetPage = 1, currentKeyword = keyword) => {
     setLoading(true);
     try {
-      const res = await api.get('/api/user/list', {
+      const res = await api.get('/api/user/list_all', {
         params: {
           page: targetPage,
           size: pageSize,

+ 28 - 10
src/components/admin/configurations/ConfigurationDetailDrawer.tsx

@@ -14,6 +14,7 @@ import {
   KeyRound,
   FileText,
   Braces,
+  Trash2,
 } from 'lucide-react';
 import { toast } from 'react-hot-toast';
 import { DynamicConfiguration } from '@/types';
@@ -24,6 +25,7 @@ interface ConfigurationDetailDrawerProps {
   onClose: () => void;
   config: DynamicConfiguration | null;
   onEdit: (config: DynamicConfiguration) => void;
+  onDelete?: (config: DynamicConfiguration) => void;
 }
 
 export default function ConfigurationDetailDrawer({
@@ -31,6 +33,7 @@ export default function ConfigurationDetailDrawer({
   onClose,
   config,
   onEdit,
+  onDelete,
 }: ConfigurationDetailDrawerProps) {
   const [copiedKey, setCopiedKey] = useState<string | null>(null);
 
@@ -214,16 +217,31 @@ export default function ConfigurationDetailDrawer({
 
           {/* Drawer Footer */}
           <div className="px-5 py-3 bg-neutral-200 border-t-2 border-black flex justify-between items-center shrink-0">
-            <button
-              onClick={() => {
-                onClose();
-                onEdit(config);
-              }}
-              className="flex items-center gap-1.5 px-4 py-1.5 bg-amber-300 hover:bg-amber-400 border-2 border-black text-black text-xs font-black uppercase shadow-[2px_2px_0px_#000] transition active:translate-x-0.5 active:translate-y-0.5"
-            >
-              <Pencil size={13} />
-              <span>[ 在线编辑此项 ]</span>
-            </button>
+            <div className="flex items-center gap-2">
+              <button
+                onClick={() => {
+                  onClose();
+                  onEdit(config);
+                }}
+                className="flex items-center gap-1.5 px-4 py-1.5 bg-amber-300 hover:bg-amber-400 border-2 border-black text-black text-xs font-black uppercase shadow-[2px_2px_0px_#000] transition active:translate-x-0.5 active:translate-y-0.5"
+              >
+                <Pencil size={13} />
+                <span>[ 在线编辑此项 ]</span>
+              </button>
+
+              {onDelete && (
+                <button
+                  onClick={() => {
+                    onClose();
+                    onDelete(config);
+                  }}
+                  className="flex items-center gap-1.5 px-3 py-1.5 bg-white hover:bg-rose-100 border-2 border-black text-rose-700 hover:text-rose-900 text-xs font-bold uppercase shadow-[2px_2px_0px_#000] transition active:translate-x-0.5 active:translate-y-0.5"
+                >
+                  <Trash2 size={13} />
+                  <span>[ 删除此项 ]</span>
+                </button>
+              )}
+            </div>
 
             <button
               onClick={onClose}

+ 16 - 7
src/components/admin/configurations/ConfigurationImportModal.tsx

@@ -101,13 +101,22 @@ export default function ConfigurationImportModal({
         }
 
         try {
-          await api.post('/api/dynamic-configurations/create', {
-            config_key: item.config_key,
-            config_value: item.config_value,
-            description: item.description,
-            type: item.type,
-          });
-          successCount++;
+          if (isExists && overwrite) {
+            await api.put(`/api/dynamic-configurations/key/${encodeURIComponent(item.config_key)}`, {
+              config_value: item.config_value,
+              description: item.description || undefined,
+              type: item.type || undefined,
+            });
+            successCount++;
+          } else if (!isExists) {
+            await api.post('/api/dynamic-configurations', {
+              config_key: item.config_key,
+              config_value: item.config_value,
+              description: item.description || undefined,
+              type: item.type || undefined,
+            });
+            successCount++;
+          }
         } catch {
           skipCount++;
         }

+ 12 - 3
src/components/admin/configurations/ConfigurationModal.tsx

@@ -75,11 +75,20 @@ export default function ConfigurationModal({
 
     setSubmitting(true);
     try {
-      if (config && config.id) {
-        await api.post(`/api/dynamic-configurations/update/${config.id}`, form);
+      if (config && config.config_key) {
+        await api.put(`/api/dynamic-configurations/key/${encodeURIComponent(config.config_key)}`, {
+          config_value: form.config_value,
+          description: form.description || undefined,
+          type: form.type || undefined,
+        });
         toast.success(`配置 "${form.config_key}" 更新成功`);
       } else {
-        await api.post('/api/dynamic-configurations/create', form);
+        await api.post('/api/dynamic-configurations', {
+          config_key: form.config_key.trim(),
+          config_value: form.config_value,
+          description: form.description || undefined,
+          type: form.type || undefined,
+        });
         toast.success(`配置 "${form.config_key}" 创建成功`);
       }
       onSuccess();

+ 10 - 1
src/components/admin/configurations/ConfigurationTable.tsx

@@ -19,6 +19,7 @@ interface ConfigurationTableProps {
   loading: boolean;
   onEdit: (config: DynamicConfiguration) => void;
   onViewDetails: (config: DynamicConfiguration) => void;
+  onDelete: (config: DynamicConfiguration) => void;
 }
 
 export default function ConfigurationTable({
@@ -26,6 +27,7 @@ export default function ConfigurationTable({
   loading,
   onEdit,
   onViewDetails,
+  onDelete,
 }: ConfigurationTableProps) {
   const [copiedKey, setCopiedKey] = useState<string | null>(null);
 
@@ -76,7 +78,8 @@ export default function ConfigurationTable({
             <tbody className="bg-white divide-y divide-black text-xs">
               {configs.map((config) => {
                 const isCopied = copiedKey === config.config_key;
-                const isJson = config.config_value?.trim().startsWith('{') || config.config_value?.trim().startsWith('[');
+                const valTrimmed = String(config.config_value || '').trim();
+                const isJson = valTrimmed.startsWith('{') || valTrimmed.startsWith('[');
 
                 return (
                   <tr
@@ -136,6 +139,12 @@ export default function ConfigurationTable({
                         >
                           编辑
                         </button>
+                        <button
+                          onClick={() => onDelete(config)}
+                          className="px-2 py-1 bg-white hover:bg-rose-100 text-rose-700 hover:text-rose-900 border border-black text-[11px] font-bold shadow-[1px_1px_0px_#000] active:translate-x-0.5 active:translate-y-0.5 uppercase"
+                        >
+                          删除
+                        </button>
                       </div>
                     </td>
                   </tr>

+ 19 - 5
src/components/admin/payments/ExchangeRateModal.tsx

@@ -77,12 +77,26 @@ export default function ExchangeRateModal({ isOpen, onClose }: ExchangeRateModal
 
   const handleSave = async () => {
     setSubmitting(true);
+    const payload = {
+      config_key: 'EXCHANGE_RATES',
+      config_value: JSON.stringify(config),
+      description: '系统全局汇率换算表',
+      type: 'json',
+    };
     try {
-      await api.post('/api/dynamic-configurations/upsert', {
-        config_key: 'EXCHANGE_RATES',
-        config_value: config,
-        description: '系统全局汇率换算表'
-      });
+      try {
+        await api.put('/api/dynamic-configurations/key/EXCHANGE_RATES', {
+          config_value: payload.config_value,
+          description: payload.description,
+          type: payload.type,
+        });
+      } catch (err: any) {
+        if (err.response?.status === 404) {
+          await api.post('/api/dynamic-configurations', payload);
+        } else {
+          throw err;
+        }
+      }
       toast.success('汇率配置保存成功!系统将在后续计价中实时生效。');
       onClose();
     } catch (e: any) {

+ 7 - 4
src/components/admin/proxies/ProxyAddModal.tsx

@@ -13,6 +13,8 @@ interface ProxyAddModalProps {
   existingPools?: string[];
 }
 
+const EMPTY_POOLS: string[] = [];
+
 interface ParsedProxy {
   pool_name: string;
   proto: string;
@@ -27,7 +29,7 @@ export default function ProxyAddModal({
   isOpen,
   onClose,
   onSuccess,
-  existingPools = [],
+  existingPools = EMPTY_POOLS,
 }: ProxyAddModalProps) {
   const [mode, setMode] = useState<'single' | 'batch'>('single');
 
@@ -68,7 +70,8 @@ export default function ProxyAddModal({
       setBatchText('');
       setMode('single');
     }
-  }, [isOpen, existingPools]);
+  // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [isOpen]);
 
   if (!isOpen) return null;
 
@@ -151,7 +154,7 @@ export default function ProxyAddModal({
 
     setSubmitting(true);
     try {
-      const res = await api.post('/api/proxies/create', {
+      const res = await api.post('/api/proxy/create', {
         pool_name: singleForm.pool_name.trim(),
         proto: singleForm.proto,
         ip: singleForm.ip.trim(),
@@ -188,7 +191,7 @@ export default function ProxyAddModal({
     try {
       for (const item of parsedBatchList) {
         try {
-          const res = await api.post('/api/proxies/create', {
+          const res = await api.post('/api/proxy/create', {
             pool_name: item.pool_name,
             proto: item.proto,
             ip: item.ip,

+ 9 - 9
src/lib/services/pluginService.ts

@@ -14,7 +14,7 @@ export const pluginService = {
    * 获取插件列表 (支持分页与状态过滤)
    */
   async getList(params?: { page?: number; page_size?: number; status?: number }) {
-    const res = await api.get('/plugins/list_all', { params });
+    const res = await api.get('/api/plugins/list_all', { params });
     return res.data;
   },
 
@@ -22,7 +22,7 @@ export const pluginService = {
    * 获取插件详情 (含所有历史版本)
    */
   async getDetail(pluginId: number): Promise<{ code: number; msg: string; data: PluginDetail }> {
-    const res = await api.get('/plugins/detail', {
+    const res = await api.get('/api/plugins/detail', {
       params: { plugin_id: pluginId },
     });
     return res.data;
@@ -34,7 +34,7 @@ export const pluginService = {
    */
   async publish(data: FormData | PublishPluginPayload) {
     const isFormData = typeof FormData !== 'undefined' && data instanceof FormData;
-    const res = await api.post('/plugins/publish', data, {
+    const res = await api.post('/api/plugins/publish', data, {
       headers: isFormData
         ? { 'Content-Type': 'multipart/form-data' }
         : { 'Content-Type': 'application/json' },
@@ -46,7 +46,7 @@ export const pluginService = {
    * 编辑插件基础信息 (展示名称、描述、启用/停用状态)
    */
   async update(pluginId: number, data: UpdatePluginPayload) {
-    const res = await api.put('/plugins/update', data, {
+    const res = await api.put('/api/plugins/update', data, {
       params: { plugin_id: pluginId },
     });
     return res.data;
@@ -56,7 +56,7 @@ export const pluginService = {
    * 切换生效版本 / 一键回滚
    */
   async switchVersion(pluginId: number, version: string) {
-    const res = await api.post('/plugins/switch-version', {
+    const res = await api.post('/api/plugins/switch-version', {
       plugin_id: pluginId,
       version,
     });
@@ -67,7 +67,7 @@ export const pluginService = {
    * 删除整套插件及其所有历史版本
    */
   async deletePlugin(pluginId: number) {
-    const res = await api.delete('/plugins/delete', {
+    const res = await api.delete('/api/plugins/delete', {
       params: { plugin_id: pluginId },
     });
     return res.data;
@@ -77,7 +77,7 @@ export const pluginService = {
    * 删除指定历史版本
    */
   async deleteVersion(pluginId: number, version: string) {
-    const res = await api.delete('/plugins/delete_version', {
+    const res = await api.delete('/api/plugins/delete_version', {
       params: { plugin_id: pluginId, version },
     });
     return res.data;
@@ -87,7 +87,7 @@ export const pluginService = {
    * 下发插件集群升级命令 (向 Redis 广播热重载通知)
    */
   async dispatchUpgrade(payload: UpgradeDispatchPayload) {
-    const res = await api.post('/plugins/upgrade/dispatch', payload);
+    const res = await api.post('/api/plugins/upgrade/dispatch', payload);
     return res.data;
   },
 
@@ -95,7 +95,7 @@ export const pluginService = {
    * 获取全量最新生效插件列表
    */
   async getLatest() {
-    const res = await api.get('/plugins/latest');
+    const res = await api.get('/api/plugins/latest');
     return res.data;
   },
 };