Quellcode durchsuchen

feat: enhance routing manager, accounts, proxies, and node config tables

jerry vor 2 Monaten
Ursprung
Commit
d4a5a82e1b

+ 32 - 15
src/app/admin/accounts/page.tsx

@@ -28,6 +28,7 @@ import AccountDetailDrawer from '@/components/admin/accounts/AccountDetailDrawer
 import AccountExportModal from '@/components/admin/accounts/AccountExportModal';
 import Pagination from '@/components/common/Pagination';
 import { Account } from '@/types';
+import { isItemInCooldown } from '@/lib/cooldown';
 
 export default function AdminAccountsPage() {
   const [loading, setLoading] = useState<boolean>(true);
@@ -38,7 +39,8 @@ export default function AdminAccountsPage() {
   const [total, setTotal] = useState(0);
   const [keyword, setKeyword] = useState('');
   const [selectedPool, setSelectedPool] = useState<string>('all');
-  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'locked' | 'disable'>('all');
+  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'disable'>('all');
+  const [cooldownFilter, setCooldownFilter] = useState<'all' | 'cooling' | 'ready'>('all');
 
   const [selectedIds, setSelectedIds] = useState<number[]>([]);
 
@@ -105,14 +107,20 @@ export default function AdminAccountsPage() {
     return data.filter((item) => {
       const matchPool = selectedPool === 'all' || item.pool_name === selectedPool;
       const matchStatus = statusFilter === 'all' || item.status === statusFilter;
-      return matchPool && matchStatus;
+      const isCooling = isItemInCooldown(item.next_use_time);
+      const matchCooldown =
+        cooldownFilter === 'all' ||
+        (cooldownFilter === 'cooling' && isCooling) ||
+        (cooldownFilter === 'ready' && !isCooling);
+
+      return matchPool && matchStatus && matchCooldown;
     });
-  }, [data, selectedPool, statusFilter]);
+  }, [data, selectedPool, statusFilter, cooldownFilter]);
 
   const stats = useMemo(() => {
     const totalCount = data.length;
     const activeCount = data.filter((a) => a.status === 'active').length;
-    const lockedCount = data.filter((a) => a.status === 'locked').length;
+    const lockedCount = data.filter((a) => isItemInCooldown(a.next_use_time)).length;
     const disabledCount = data.filter((a) => a.status === 'disable').length;
     const poolsCount = uniquePools.length;
 
@@ -243,27 +251,27 @@ export default function AdminAccountsPage() {
       {/* 2. 统计指标卡片看板 */}
       <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
         <div className="bg-white p-4 border-2 border-black shadow-[4px_4px_0px_#000] space-y-1">
-          <span className="text-[10px] font-black uppercase text-neutral-500">[ 总账号池 ]</span>
+          <span className="text-[10px] font-black uppercase text-neutral-500">[ 总账号池 TOTAL ]</span>
           <div className="text-2xl font-black text-black">{stats.total} 个</div>
           <div className="text-[10px] text-neutral-500 font-sans">全量登记账号</div>
         </div>
 
         <div className="bg-white p-4 border-2 border-black shadow-[4px_4px_0px_#000] space-y-1">
-          <span className="text-[10px] font-black uppercase text-black">[ 正常可用 ACTIVE ]</span>
-          <div className="text-2xl font-black text-black">{stats.active} 个</div>
-          <div className="text-[10px] text-neutral-500 font-sans">就绪直接调用</div>
+          <span className="text-[10px] font-black uppercase text-emerald-800">[ 启用中 ACTIVE ]</span>
+          <div className="text-2xl font-black text-emerald-800">{stats.active} 个</div>
+          <div className="text-[10px] text-neutral-500 font-sans">正常启用账号</div>
         </div>
 
         <div className="bg-white p-4 border-2 border-black shadow-[4px_4px_0px_#000] space-y-1">
-          <span className="text-[10px] font-black uppercase text-neutral-600">[ 冷却锁定 LOCKED ]</span>
-          <div className="text-2xl font-black text-black">{stats.locked} 个</div>
+          <span className="text-[10px] font-black uppercase text-amber-700">[ 冷却锁定 COOLING ]</span>
+          <div className="text-2xl font-black text-amber-700">{stats.locked} 个</div>
           <div className="text-[10px] text-neutral-500 font-sans">冷却倒计时中</div>
         </div>
 
         <div className="bg-white p-4 border-2 border-black shadow-[4px_4px_0px_#000] space-y-1">
           <span className="text-[10px] font-black uppercase text-rose-800">[ 已禁用 DISABLED ]</span>
           <div className="text-2xl font-black text-rose-800">{stats.disabled} 个</div>
-          <div className="text-[10px] text-neutral-500 font-sans">失效或手动停用</div>
+          <div className="text-[10px] text-neutral-500 font-sans">手动停用账号</div>
         </div>
 
         <div className="bg-white p-4 border-2 border-black shadow-[4px_4px_0px_#000] space-y-1 col-span-2 sm:col-span-1">
@@ -306,10 +314,19 @@ export default function AdminAccountsPage() {
             onChange={(e: any) => setStatusFilter(e.target.value)}
             className="px-2.5 py-1.5 border-2 border-black bg-neutral-50 text-xs font-bold text-black outline-none shadow-[2px_2px_0px_#000]"
           >
-            <option value="all">[ 全部状态 ]</option>
-            <option value="active">正常 (Active)</option>
-            <option value="locked">锁定 (Locked)</option>
-            <option value="disable">禁用 (Disabled)</option>
+            <option value="all">[ 全部启用状态 ]</option>
+            <option value="active">仅启用 (Active)</option>
+            <option value="disable">仅禁用 (Disabled)</option>
+          </select>
+
+          <select
+            value={cooldownFilter}
+            onChange={(e: any) => setCooldownFilter(e.target.value)}
+            className="px-2.5 py-1.5 border-2 border-black bg-neutral-50 text-xs font-bold text-black outline-none shadow-[2px_2px_0px_#000]"
+          >
+            <option value="all">[ 全部冷却状态 ]</option>
+            <option value="cooling">仅冷却中 (Cooling)</option>
+            <option value="ready">仅就绪可用 (Ready)</option>
           </select>
         </div>
       </div>

+ 32 - 15
src/app/admin/proxies/page.tsx

@@ -29,6 +29,7 @@ import ProxyDetailDrawer from '@/components/admin/proxies/ProxyDetailDrawer';
 import ProxyExportModal from '@/components/admin/proxies/ProxyExportModal';
 import Pagination from '@/components/common/Pagination';
 import { ProxyItem } from '@/types';
+import { isItemInCooldown } from '@/lib/cooldown';
 
 export default function AdminProxiesPage() {
   const [loading, setLoading] = useState<boolean>(true);
@@ -40,7 +41,8 @@ export default function AdminProxiesPage() {
   const [keyword, setKeyword] = useState('');
   const [selectedPool, setSelectedPool] = useState<string>('all');
   const [selectedProto, setSelectedProto] = useState<string>('all');
-  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'locked' | 'disable'>('all');
+  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'disable'>('all');
+  const [cooldownFilter, setCooldownFilter] = useState<'all' | 'cooling' | 'ready'>('all');
 
   const [selectedIds, setSelectedIds] = useState<number[]>([]);
 
@@ -119,14 +121,20 @@ export default function AdminProxiesPage() {
       const matchProto =
         selectedProto === 'all' || (item.proto || '').toUpperCase() === selectedProto.toUpperCase();
       const matchStatus = statusFilter === 'all' || item.status === statusFilter;
-      return matchPool && matchProto && matchStatus;
+      const isCooling = isItemInCooldown(item.next_use_time);
+      const matchCooldown =
+        cooldownFilter === 'all' ||
+        (cooldownFilter === 'cooling' && isCooling) ||
+        (cooldownFilter === 'ready' && !isCooling);
+
+      return matchPool && matchProto && matchStatus && matchCooldown;
     });
-  }, [data, selectedPool, selectedProto, statusFilter]);
+  }, [data, selectedPool, selectedProto, statusFilter, cooldownFilter]);
 
   const stats = useMemo(() => {
     const totalCount = data.length;
     const activeCount = data.filter((p) => p.status === 'active').length;
-    const lockedCount = data.filter((p) => p.status === 'locked').length;
+    const lockedCount = data.filter((p) => isItemInCooldown(p.next_use_time)).length;
     const disabledCount = data.filter((p) => p.status === 'disable').length;
     const poolsCount = uniquePools.length;
 
@@ -257,21 +265,21 @@ export default function AdminProxiesPage() {
       {/* 2. 统计指标看板 */}
       <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
         <div className="bg-white p-4 border-2 border-black shadow-[4px_4px_0px_#000] space-y-1">
-          <span className="text-[10px] font-black uppercase text-neutral-500">[ 代理 IP 总数 ]</span>
+          <span className="text-[10px] font-black uppercase text-neutral-500">[ 代理 IP 总数 TOTAL ]</span>
           <div className="text-2xl font-black text-black">{stats.total} 个</div>
           <div className="text-[10px] text-neutral-500 font-sans">全量纳管节点</div>
         </div>
 
         <div className="bg-white p-4 border-2 border-black shadow-[4px_4px_0px_#000] space-y-1">
-          <span className="text-[10px] font-black uppercase text-black">[ 正常可用 ACTIVE ]</span>
-          <div className="text-2xl font-black text-black">{stats.active} 个</div>
-          <div className="text-[10px] text-neutral-500 font-sans">路由轮询就绪</div>
+          <span className="text-[10px] font-black uppercase text-emerald-800">[ 启用中 ACTIVE ]</span>
+          <div className="text-2xl font-black text-emerald-800">{stats.active} 个</div>
+          <div className="text-[10px] text-neutral-500 font-sans">正常启用节点</div>
         </div>
 
         <div className="bg-white p-4 border-2 border-black shadow-[4px_4px_0px_#000] space-y-1">
-          <span className="text-[10px] font-black uppercase text-neutral-600">[ 冷却锁定 LOCKED ]</span>
-          <div className="text-2xl font-black text-black">{stats.locked} 个</div>
-          <div className="text-[10px] text-neutral-500 font-sans">限流冷却中</div>
+          <span className="text-[10px] font-black uppercase text-amber-700">[ 冷却锁定 COOLING ]</span>
+          <div className="text-2xl font-black text-amber-700">{stats.locked} 个</div>
+          <div className="text-[10px] text-neutral-500 font-sans">限流冷却倒计时</div>
         </div>
 
         <div className="bg-white p-4 border-2 border-black shadow-[4px_4px_0px_#000] space-y-1">
@@ -333,10 +341,19 @@ export default function AdminProxiesPage() {
             onChange={(e: any) => setStatusFilter(e.target.value)}
             className="px-2.5 py-1.5 border-2 border-black bg-neutral-50 text-xs font-bold text-black outline-none shadow-[2px_2px_0px_#000]"
           >
-            <option value="all">[ 全部状态 ]</option>
-            <option value="active">正常 (Active)</option>
-            <option value="locked">锁定 (Locked)</option>
-            <option value="disable">禁用 (Disabled)</option>
+            <option value="all">[ 全部启用状态 ]</option>
+            <option value="active">仅启用 (Active)</option>
+            <option value="disable">仅禁用 (Disabled)</option>
+          </select>
+
+          <select
+            value={cooldownFilter}
+            onChange={(e: any) => setCooldownFilter(e.target.value)}
+            className="px-2.5 py-1.5 border-2 border-black bg-neutral-50 text-xs font-bold text-black outline-none shadow-[2px_2px_0px_#000]"
+          >
+            <option value="all">[ 全部冷却状态 ]</option>
+            <option value="cooling">仅冷却中 (Cooling)</option>
+            <option value="ready">仅就绪可用 (Ready)</option>
           </select>
         </div>
       </div>

+ 6 - 19
src/components/admin/accounts/AccountDetailDrawer.tsx

@@ -29,6 +29,7 @@ import {
 import { toast } from 'react-hot-toast';
 import { Account } from '@/types';
 import LocalTime from '@/components/common/LocalTime';
+import { getCooldownRemainingText } from '@/lib/cooldown';
 
 interface AccountDetailDrawerProps {
   isOpen: boolean;
@@ -63,8 +64,6 @@ export default function AccountDetailDrawer({
     }
   }, [isOpen, account]);
 
-  if (!isOpen || !account) return null;
-
   const handleCopy = async (text: string | null | undefined, key: string, label: string) => {
     if (!text) {
       toast.error(`没有可复制的${label}`);
@@ -81,6 +80,7 @@ export default function AccountDetailDrawer({
   };
 
   const handleToggle = async () => {
+    if (!account) return;
     setTogglingStatus(true);
     try {
       await onToggleStatus(account);
@@ -89,23 +89,10 @@ export default function AccountDetailDrawer({
     }
   };
 
-  let isLocked = false;
-  let remainingTimeStr = '';
-  if (account.next_use_time) {
-    const nextTime = new Date(account.next_use_time).getTime();
-    if (!Number.isNaN(nextTime) && nextTime > now) {
-      isLocked = true;
-      const diffSec = Math.floor((nextTime - now) / 1000);
-      const m = Math.floor(diffSec / 60);
-      const s = diffSec % 60;
-      const h = Math.floor(m / 60);
-      if (h > 0) {
-        remainingTimeStr = `${h}小时${m % 60}分`;
-      } else {
-        remainingTimeStr = `${m}分${s}秒`;
-      }
-    }
-  }
+  if (!isOpen || !account) return null;
+
+  const remainingTimeStr = getCooldownRemainingText(account.next_use_time, now);
+  const isLocked = remainingTimeStr !== null;
 
   const extraData = account.extra_data || {};
   const extraKeys = Object.keys(extraData);

+ 26 - 26
src/components/admin/accounts/AccountTable.tsx

@@ -25,6 +25,7 @@ import {
 } from 'lucide-react';
 import { toast } from 'react-hot-toast';
 import { Account } from '@/types';
+import { getCooldownRemainingTime } from '@/lib/cooldown';
 
 interface AccountTableProps {
   data: Account[];
@@ -77,18 +78,6 @@ export default function AccountTable({
     }
   };
 
-  const getRemainingTime = (nextUseTime?: string | null) => {
-    if (!nextUseTime) return null;
-    const target = new Date(nextUseTime).getTime();
-    if (Number.isNaN(target) || target <= now) return null;
-    const diffSec = Math.floor((target - now) / 1000);
-    const m = Math.floor(diffSec / 60);
-    const s = diffSec % 60;
-    const h = Math.floor(m / 60);
-    if (h > 0) return `${h}h${m % 60}m`;
-    return `${m}m${s}s`;
-  };
-
   const isAllSelected = data.length > 0 && selectedIds.length === data.length;
 
   if (loading && data.length === 0) {
@@ -135,7 +124,7 @@ export default function AccountTable({
             {data.map((item) => {
               const isSelected = selectedIds.includes(item.id);
               const isRevealed = revealedPasswords[item.id] || false;
-              const remainingTime = getRemainingTime(item.next_use_time);
+              const remainingTime = getCooldownRemainingTime(item.next_use_time, now);
               const isLocked = remainingTime !== null;
               const isDisabled = item.status?.toLowerCase() === 'disable';
               const extraKeysCount = Object.keys(item.extra_data || {}).length;
@@ -203,19 +192,30 @@ export default function AccountTable({
                   </td>
 
                   <td className="p-3">
-                    {isDisabled ? (
-                      <span className="px-1.5 py-0.2 border border-black bg-neutral-300 text-neutral-700 font-bold uppercase text-[10px]">
-                        已禁用
-                      </span>
-                    ) : isLocked ? (
-                      <span className="px-1.5 py-0.2 border border-black bg-amber-300 text-black font-black uppercase text-[10px]">
-                        锁定 {remainingTime}
-                      </span>
-                    ) : (
-                      <span className="px-1.5 py-0.2 border border-black bg-white text-black font-bold uppercase text-[10px]">
-                        正常可用
-                      </span>
-                    )}
+                    <div className="flex flex-wrap items-center gap-1.5">
+                      {/* 启用状态 */}
+                      {isDisabled ? (
+                        <span className="px-1.5 py-0.5 border border-black bg-neutral-200 text-neutral-600 font-bold uppercase text-[10px] shadow-[1px_1px_0px_#000]">
+                          已禁用
+                        </span>
+                      ) : (
+                        <span className="px-1.5 py-0.5 border border-black bg-emerald-100 text-emerald-900 font-bold uppercase text-[10px] shadow-[1px_1px_0px_#000]">
+                          启用中
+                        </span>
+                      )}
+
+                      {/* 冷却状态 */}
+                      {isLocked ? (
+                        <span className="px-1.5 py-0.5 border border-black bg-amber-300 text-black font-black uppercase text-[10px] shadow-[1px_1px_0px_#000] flex items-center gap-1">
+                          <Timer size={10} className="shrink-0" />
+                          <span>冷却 {remainingTime}</span>
+                        </span>
+                      ) : (
+                        <span className="px-1.5 py-0.5 border border-black bg-white text-neutral-700 font-bold uppercase text-[10px] shadow-[1px_1px_0px_#000]">
+                          就绪
+                        </span>
+                      )}
+                    </div>
                   </td>
 
                   <td className="p-3">

+ 35 - 15
src/components/admin/node-configurations/NodeConfigDetailDrawer.tsx

@@ -194,16 +194,26 @@ export default function NodeConfigDetailDrawer({
 
               {/* Live Telemetry Stack Card */}
               {(() => {
+                const targetInstances =
+                  entryType === 'booker'
+                    ? (config.booker?.target_instances && config.booker.target_instances > 0 ? config.booker.target_instances : 1)
+                    : entryType === 'sentinel'
+                    ? (config.sentinel?.target_instances && config.sentinel.target_instances > 0 ? config.sentinel.target_instances : 1)
+                    : 1;
+
                 const matchedNode = runtimeNodes?.find(
                   (n) => n.node_id === config.node_id && n.role === entryType
                 );
                 const matchedGroup = matchedNode?.groups?.find(
-                  (g) =>
-                    g.group_id === config.identifier ||
-                    g.group_id === config.identifier.split('.')[0] ||
-                    g.plugin_name === config.plugin_config?.plugin_name
+                  (g) => g.group_id === config.identifier
                 );
 
+                const currentInstances = matchedGroup
+                  ? (matchedGroup.plugins?.length ?? matchedGroup.total_tasks ?? 0)
+                  : 0;
+                const healthyInstances = matchedGroup?.healthy_tasks ?? 0;
+                const hasRunningInstances = matchedGroup && currentInstances > 0;
+
                 return (
                   <div className="p-4 bg-neutral-100 border-2 border-black shadow-[2px_2px_0px_#000] space-y-3">
                     <div className="font-black text-black border-b-2 border-black pb-1.5 flex items-center justify-between">
@@ -227,26 +237,36 @@ export default function NodeConfigDetailDrawer({
                       )}
                     </div>
 
-                    {matchedGroup ? (
+                    {hasRunningInstances ? (
                       <div className="space-y-3">
                         <div className="grid grid-cols-2 md:grid-cols-4 gap-2 text-xs">
                           <div>
-                            <span className="text-neutral-500 block text-[10px]">Wrapper 状态:</span>
-                            <span className="font-black text-black">{matchedGroup.wrapper_state}</span>
+                            <span className="text-neutral-500 block text-[10px]">运行并发:</span>
+                            <span
+                              className={`font-black ${
+                                currentInstances >= targetInstances && healthyInstances >= currentInstances
+                                  ? 'text-emerald-600'
+                                  : healthyInstances > 0
+                                  ? 'text-amber-600'
+                                  : 'text-rose-600'
+                              }`}
+                            >
+                              {currentInstances} / {targetInstances} 实例
+                            </span>
                           </div>
                           <div>
-                            <span className="text-neutral-500 block text-[10px]">健康并发数:</span>
-                            <span className="font-black text-emerald-600">
-                              {matchedGroup.healthy_tasks} / {matchedGroup.total_tasks} 实例
+                            <span className="text-neutral-500 block text-[10px]">健康实例:</span>
+                            <span className="font-black text-black">
+                              {healthyInstances} / {currentInstances} 健康
                             </span>
                           </div>
                           <div>
-                            <span className="text-neutral-500 block text-[10px]">装载插件:</span>
-                            <span className="font-bold text-black">{matchedGroup.plugin_name}</span>
+                            <span className="text-neutral-500 block text-[10px]">Wrapper 状态:</span>
+                            <span className="font-bold text-black">{matchedGroup.wrapper_state}</span>
                           </div>
                           <div>
-                            <span className="text-neutral-500 block text-[10px]">上报时间:</span>
-                            <span className="font-bold text-neutral-700">{matchedGroup.updated_at || '-'}</span>
+                            <span className="text-neutral-500 block text-[10px]">装载插件:</span>
+                            <span className="font-bold text-black">{matchedGroup.plugin_name}</span>
                           </div>
                         </div>
 
@@ -309,7 +329,7 @@ export default function NodeConfigDetailDrawer({
                     ) : (
                       <div className="p-3 bg-white border border-black text-center text-neutral-500 font-bold text-xs">
                         {matchedNode?.is_online
-                          ? '该节点已在线,但当前任务组尚未启动或无活跃实例上报'
+                          ? `该节点已在线,当前任务待机中 (0/${targetInstances} 实例)`
                           : '节点未上报心跳数据'}
                       </div>
                     )}

+ 20 - 10
src/components/admin/node-configurations/NodeConfigTable.tsx

@@ -197,6 +197,13 @@ export default function NodeConfigTable({
                   {/* Live Telemetry Status Pill */}
                   <td className="p-3.5">
                     {(() => {
+                      const targetInstances =
+                        entryType === 'booker'
+                          ? (item.booker?.target_instances && item.booker.target_instances > 0 ? item.booker.target_instances : 1)
+                          : entryType === 'sentinel'
+                          ? (item.sentinel?.target_instances && item.sentinel.target_instances > 0 ? item.sentinel.target_instances : 1)
+                          : 1;
+
                       const matchedNode = runtimeNodes?.find(
                         (n) => n.node_id === item.node_id && n.role === entryType
                       );
@@ -210,21 +217,24 @@ export default function NodeConfigTable({
                       }
 
                       const matchedGroup = matchedNode.groups?.find(
-                        (g) =>
-                          g.group_id === item.identifier ||
-                          g.group_id === item.identifier.split('.')[0] ||
-                          g.plugin_name === item.plugin_config?.plugin_name
+                        (g) => g.group_id === item.identifier
                       );
 
-                      if (!matchedGroup) {
+                      const currentInstances = matchedGroup
+                        ? (matchedGroup.plugins?.length ?? matchedGroup.total_tasks ?? 0)
+                        : 0;
+                      const healthyInstances = matchedGroup?.healthy_tasks ?? 0;
+
+                      if (!matchedGroup || currentInstances === 0) {
                         return (
                           <span className="px-2 py-0.5 border border-black bg-neutral-100 text-neutral-600 text-[10px] font-bold">
-                            ○ 待机中
+                            ○ 0/{targetInstances} 待机
                           </span>
                         );
                       }
 
-                      const isHealthy = matchedGroup.healthy_tasks > 0 && matchedGroup.healthy_tasks === matchedGroup.total_tasks;
+                      const isFullyHealthy = currentInstances >= targetInstances && healthyInstances >= currentInstances;
+                      const isPartiallyHealthy = healthyInstances > 0;
                       const activeInstance = matchedGroup.plugins?.[0];
 
                       return (
@@ -233,15 +243,15 @@ export default function NodeConfigTable({
                             type="button"
                             onClick={() => onInspectInstances?.(item.node_id, item.identifier)}
                             className={`px-2 py-0.5 border border-black text-[10px] font-black uppercase shadow-[1px_1px_0px_#000] active:translate-x-0.5 active:translate-y-0.5 text-left w-fit transition ${
-                              isHealthy
+                              isFullyHealthy
                                 ? 'bg-emerald-300 hover:bg-emerald-400 text-black'
-                                : matchedGroup.healthy_tasks > 0
+                                : isPartiallyHealthy
                                 ? 'bg-amber-300 hover:bg-amber-400 text-black'
                                 : 'bg-rose-200 hover:bg-rose-300 text-rose-950'
                             }`}
                             title="点击查看该任务正在运行的并发实例堆栈"
                           >
-                            ● {matchedGroup.healthy_tasks}/{matchedGroup.total_tasks} 活跃
+                            ● {currentInstances}/{targetInstances} 活跃
                             {activeInstance?.state ? ` [${activeInstance.state}]` : ''} 🔍
                           </button>
                         </div>

+ 6 - 6
src/components/admin/products/RoutingManager.tsx

@@ -196,18 +196,18 @@ export default function RoutingManager({
       if (editingId) {
         await productService.updateRouting(editingId, {
           product_id: productId,
-          routing_key: form.routing_key,
-          script_version: form.script_version || null,
-          priority: Number(form.priority) || 0,
+          routing_key: form.routing_key.trim(),
+          script_version: form.script_version?.trim() || 'latest',
+          priority: Number(form.priority) || 10,
           config: parsedConfig,
         });
         toast.success(`路由规则 #${editingId} 更新成功`);
       } else {
         await productService.createRouting({
           product_id: productId,
-          routing_key: form.routing_key,
-          script_version: form.script_version || null,
-          priority: Number(form.priority) || 0,
+          routing_key: form.routing_key.trim(),
+          script_version: form.script_version?.trim() || 'latest',
+          priority: Number(form.priority) || 10,
           config: parsedConfig,
         });
         toast.success('分发路由策略创建成功');

+ 7 - 19
src/components/admin/proxies/ProxyDetailDrawer.tsx

@@ -25,6 +25,7 @@ import {
 import { toast } from 'react-hot-toast';
 import { ProxyItem } from '@/types';
 import LocalTime from '@/components/common/LocalTime';
+import { getCooldownRemainingText } from '@/lib/cooldown';
 
 interface ProxyDetailDrawerProps {
   isOpen: boolean;
@@ -56,11 +57,10 @@ export default function ProxyDetailDrawer({
     if (isOpen) {
       setShowPassword(false);
       setActiveTab('info');
+      setNow(Date.now());
     }
   }, [isOpen, proxy?.id]);
 
-  if (!isOpen || !proxy) return null;
-
   const handleCopy = async (text: string | null | undefined, key: string, label: string) => {
     if (!text) {
       toast.error(`没有可复制的${label}`);
@@ -77,6 +77,7 @@ export default function ProxyDetailDrawer({
   };
 
   const handleToggle = async () => {
+    if (!proxy) return;
     setTogglingStatus(true);
     try {
       await onToggleStatus(proxy);
@@ -85,6 +86,8 @@ export default function ProxyDetailDrawer({
     }
   };
 
+  if (!isOpen || !proxy) return null;
+
   const hasAuth = Boolean(proxy.username && proxy.password);
   const authString = hasAuth ? `${encodeURIComponent(proxy.username!)}:${encodeURIComponent(proxy.password!)}@` : '';
   const standardUrl = `${proxy.proto}://${authString}${proxy.ip}:${proxy.port}`;
@@ -92,23 +95,8 @@ export default function ProxyDetailDrawer({
     ? `${proxy.ip}:${proxy.port}:${proxy.username}:${proxy.password}`
     : `${proxy.ip}:${proxy.port}`;
 
-  let isLocked = false;
-  let remainingTimeStr = '';
-  if (proxy.next_use_time) {
-    const nextTime = new Date(proxy.next_use_time).getTime();
-    if (!Number.isNaN(nextTime) && nextTime > now) {
-      isLocked = true;
-      const diffSec = Math.floor((nextTime - now) / 1000);
-      const m = Math.floor(diffSec / 60);
-      const s = diffSec % 60;
-      const h = Math.floor(m / 60);
-      if (h > 0) {
-        remainingTimeStr = `${h}小时${m % 60}分`;
-      } else {
-        remainingTimeStr = `${m}分${s}秒`;
-      }
-    }
-  }
+  const remainingTimeStr = getCooldownRemainingText(proxy.next_use_time, now);
+  const isLocked = remainingTimeStr !== null;
 
   const getCodeSnippet = (lang: typeof codeLang) => {
     switch (lang) {

+ 26 - 26
src/components/admin/proxies/ProxyTable.tsx

@@ -21,6 +21,7 @@ import {
 } from 'lucide-react';
 import { toast } from 'react-hot-toast';
 import { ProxyItem } from '@/types';
+import { getCooldownRemainingTime } from '@/lib/cooldown';
 
 interface ProxyTableProps {
   data: ProxyItem[];
@@ -73,18 +74,6 @@ export default function ProxyTable({
     }
   };
 
-  const getRemainingTime = (nextUseTime?: string | null) => {
-    if (!nextUseTime) return null;
-    const target = new Date(nextUseTime).getTime();
-    if (Number.isNaN(target) || target <= now) return null;
-    const diffSec = Math.floor((target - now) / 1000);
-    const m = Math.floor(diffSec / 60);
-    const s = diffSec % 60;
-    const h = Math.floor(m / 60);
-    if (h > 0) return `${h}h${m % 60}m`;
-    return `${m}m${s}s`;
-  };
-
   const isAllSelected = data.length > 0 && selectedIds.length === data.length;
 
   if (loading && data.length === 0) {
@@ -131,7 +120,7 @@ export default function ProxyTable({
             {data.map((item) => {
               const isSelected = selectedIds.includes(item.id);
               const isRevealed = revealedPasswords[item.id] || false;
-              const remainingTime = getRemainingTime(item.next_use_time);
+              const remainingTime = getCooldownRemainingTime(item.next_use_time, now);
               const isLocked = remainingTime !== null;
               const isDisabled = item.status?.toLowerCase() === 'disable';
 
@@ -224,19 +213,30 @@ export default function ProxyTable({
                   </td>
 
                   <td className="p-3">
-                    {isDisabled ? (
-                      <span className="px-1.5 py-0.2 border border-black bg-neutral-300 text-neutral-700 font-bold uppercase text-[10px]">
-                        已禁用
-                      </span>
-                    ) : isLocked ? (
-                      <span className="px-1.5 py-0.2 border border-black bg-amber-300 text-black font-black uppercase text-[10px]">
-                        锁定 {remainingTime}
-                      </span>
-                    ) : (
-                      <span className="px-1.5 py-0.2 border border-black bg-white text-black font-bold uppercase text-[10px]">
-                        正常可用
-                      </span>
-                    )}
+                    <div className="flex flex-wrap items-center gap-1.5">
+                      {/* 启用状态 */}
+                      {isDisabled ? (
+                        <span className="px-1.5 py-0.5 border border-black bg-neutral-200 text-neutral-600 font-bold uppercase text-[10px] shadow-[1px_1px_0px_#000]">
+                          已禁用
+                        </span>
+                      ) : (
+                        <span className="px-1.5 py-0.5 border border-black bg-emerald-100 text-emerald-900 font-bold uppercase text-[10px] shadow-[1px_1px_0px_#000]">
+                          启用中
+                        </span>
+                      )}
+
+                      {/* 冷却状态 */}
+                      {isLocked ? (
+                        <span className="px-1.5 py-0.5 border border-black bg-amber-300 text-black font-black uppercase text-[10px] shadow-[1px_1px_0px_#000] flex items-center gap-1">
+                          <Timer size={10} className="shrink-0" />
+                          <span>冷却 {remainingTime}</span>
+                        </span>
+                      ) : (
+                        <span className="px-1.5 py-0.5 border border-black bg-white text-neutral-700 font-bold uppercase text-[10px] shadow-[1px_1px_0px_#000]">
+                          就绪
+                        </span>
+                      )}
+                    </div>
                   </td>
 
                   <td className="p-3 text-right">

+ 88 - 0
src/lib/cooldown.ts

@@ -0,0 +1,88 @@
+/**
+ * 冷却锁定与 UTC 时间解析工具函数
+ */
+
+/**
+ * 将可能缺失时区后缀的 UTC 日期字符串或 Date 对象标准化解析为 Date
+ */
+export function parseUtcDate(dateStr?: string | Date | null): Date | null {
+  if (!dateStr) return null;
+  if (dateStr instanceof Date) {
+    return isNaN(dateStr.getTime()) ? null : dateStr;
+  }
+  if (typeof dateStr !== 'string') return null;
+
+  let normalized = dateStr.trim().replace(' ', 'T');
+  if (!normalized) return null;
+
+  // 若无时区标识 (Z 或 +08:00 / -05:00),补全 Z 作为 UTC 解析
+  if (!normalized.endsWith('Z') && !normalized.includes('+') && !normalized.match(/-\d{2}:\d{2}$/)) {
+    normalized += 'Z';
+  }
+
+  const d = new Date(normalized);
+  return isNaN(d.getTime()) ? null : d;
+}
+
+/**
+ * 判断当前资产是否处于冷却锁定中 (next_use_time > now)
+ */
+export function isItemInCooldown(nextUseTime?: string | Date | null, nowMs: number = Date.now()): boolean {
+  const targetDate = parseUtcDate(nextUseTime);
+  if (!targetDate) return false;
+  return targetDate.getTime() > nowMs;
+}
+
+/**
+ * 计算剩余冷却时间格式化字符串 (例如: 1h20m, 14m32s, 45s),若已过期则返回 null
+ */
+export function getCooldownRemainingTime(nextUseTime?: string | Date | null, nowMs: number = Date.now()): string | null {
+  const targetDate = parseUtcDate(nextUseTime);
+  if (!targetDate) return null;
+  const diffMs = targetDate.getTime() - nowMs;
+  if (diffMs <= 0) return null;
+
+  const diffSec = Math.floor(diffMs / 1000);
+  const m = Math.floor(diffSec / 60);
+  const s = diffSec % 60;
+  const h = Math.floor(m / 60);
+  const d = Math.floor(h / 24);
+
+  if (d > 0) {
+    return `${d}d${h % 24}h`;
+  }
+  if (h > 0) {
+    return `${h}h${m % 60}m`;
+  }
+  if (m > 0) {
+    return `${m}m${s}s`;
+  }
+  return `${s}s`;
+}
+
+/**
+ * 详细中文剩余时间 (用于抽屉详情等场景)
+ */
+export function getCooldownRemainingText(nextUseTime?: string | Date | null, nowMs: number = Date.now()): string | null {
+  const targetDate = parseUtcDate(nextUseTime);
+  if (!targetDate) return null;
+  const diffMs = targetDate.getTime() - nowMs;
+  if (diffMs <= 0) return null;
+
+  const diffSec = Math.floor(diffMs / 1000);
+  const m = Math.floor(diffSec / 60);
+  const s = diffSec % 60;
+  const h = Math.floor(m / 60);
+  const d = Math.floor(h / 24);
+
+  if (d > 0) {
+    return `${d}天${h % 24}小时`;
+  }
+  if (h > 0) {
+    return `${h}小时${m % 60}分`;
+  }
+  if (m > 0) {
+    return `${m}分${s}秒`;
+  }
+  return `${s}秒`;
+}

+ 41 - 7
src/lib/services/productService.ts

@@ -117,9 +117,17 @@ export const productService = {
    * 获取产品的路由配置列表
    */
   async listRoutings(productId: number) {
-    const res = await api.get('/api/vas/product_routing/list_by_product', {
+    const res = await api.get('/api/vas/product_routing/list', {
       params: { product_id: productId },
     });
+    if (res.data && Array.isArray(res.data.data)) {
+      // 按照 priority 降序,其次 id 降序排列
+      res.data.data.sort((a: any, b: any) => {
+        const pDiff = (b.priority ?? 0) - (a.priority ?? 0);
+        if (pDiff !== 0) return pDiff;
+        return (b.id ?? 0) - (a.id ?? 0);
+      });
+    }
     return res.data;
   },
 
@@ -127,18 +135,44 @@ export const productService = {
    * 创建产品路由配置
    */
   async createRouting(payload: Record<string, any>) {
-    const res = await api.post('/api/vas/product_routing/create', payload);
+    const normalizedPayload = {
+      product_id: payload.product_id,
+      routing_key: payload.routing_key,
+      script_version: payload.script_version || 'latest',
+      priority: Number(payload.priority) || 10,
+      config: payload.config && typeof payload.config === 'object' ? payload.config : {},
+    };
+    const res = await api.post('/api/vas/product_routing/create', normalizedPayload);
     return res.data;
   },
 
   /**
-   * 更新产品路由配置
+   * 更新产品路由配置 (若后端无独立 update 端点则优雅回退至先删后建)
    */
   async updateRouting(id: number, payload: Record<string, any>) {
-    const res = await api.post('/api/vas/product_routing/update', payload, {
-      params: { id },
-    });
-    return res.data;
+    try {
+      const res = await api.post('/api/vas/product_routing/update', payload, {
+        params: { id },
+      });
+      return res.data;
+    } catch (err: any) {
+      // 若后端 404/405 无 update 接口,采用删除 + 重新创建策略
+      if (err?.response?.status === 404 || err?.response?.status === 405) {
+        await api.delete('/api/vas/product_routing/delete', {
+          params: { id },
+        });
+        const normalizedPayload = {
+          product_id: payload.product_id,
+          routing_key: payload.routing_key,
+          script_version: payload.script_version || 'latest',
+          priority: Number(payload.priority) || 10,
+          config: payload.config && typeof payload.config === 'object' ? payload.config : {},
+        };
+        const createRes = await api.post('/api/vas/product_routing/create', normalizedPayload);
+        return createRes.data;
+      }
+      throw err;
+    }
   },
 
   /**