ソースを参照

refactor: 全量重构剥离 HTTP API 到 lib/services 并修复账号解锁冷却时间字段

jerry 2 ヶ月 前
親
コミット
0601c4bcb5
62 ファイル変更、1741 行追加、603 行削除
  1. 10 12
      src/app/admin/accounts/page.tsx
  2. 8 12
      src/app/admin/configurations/page.tsx
  3. 8 10
      src/app/admin/orders/new/page.tsx
  4. 12 13
      src/app/admin/orders/page.tsx
  5. 3 3
      src/app/admin/page.tsx
  6. 10 12
      src/app/admin/payments/page.tsx
  7. 28 38
      src/app/admin/products/page.tsx
  8. 10 12
      src/app/admin/proxies/page.tsx
  9. 32 34
      src/app/admin/tasks/page.tsx
  10. 6 8
      src/app/admin/tickets/page.tsx
  11. 10 14
      src/app/admin/users/page.tsx
  12. 3 3
      src/app/slots/page.tsx
  13. 5 5
      src/components/AuthForm.tsx
  14. 4 4
      src/components/AutoRegistrar.tsx
  15. 6 6
      src/components/BindEmailModal.tsx
  16. 52 48
      src/components/CreateOrderForm.tsx
  17. 3 3
      src/components/ForgotPasswordModal.tsx
  18. 11 11
      src/components/PaymentProcessor.tsx
  19. 4 6
      src/components/ServiceList.tsx
  20. 4 4
      src/components/admin/accounts/AccountAddModal.tsx
  21. 5 6
      src/components/admin/accounts/AccountEditModal.tsx
  22. 3 3
      src/components/admin/configurations/ConfigurationImportModal.tsx
  23. 7 11
      src/components/admin/configurations/ConfigurationModal.tsx
  24. 3 3
      src/components/admin/orders/AiDataParserPanel.tsx
  25. 61 46
      src/components/admin/orders/OrderDetailDrawer.tsx
  26. 14 15
      src/components/admin/orders/OrderDetailModal.tsx
  27. 5 22
      src/components/admin/orders/OrderPaymentModal.tsx
  28. 11 12
      src/components/admin/orders/OrderPriceAdjustModal.tsx
  29. 6 4
      src/components/admin/orders/ProductSearchSelector.tsx
  30. 5 5
      src/components/admin/payments/ExchangeRateModal.tsx
  31. 6 8
      src/components/admin/payments/QrManager.tsx
  32. 29 17
      src/components/admin/products/ProductDetailDrawer.tsx
  33. 5 5
      src/components/admin/products/ProductModal.tsx
  34. 19 23
      src/components/admin/products/RoutingManager.tsx
  35. 145 59
      src/components/admin/products/SchemaManager.tsx
  36. 6 6
      src/components/admin/proxies/ProxyAddModal.tsx
  37. 10 11
      src/components/admin/proxies/ProxyEditModal.tsx
  38. 10 10
      src/components/admin/tasks/TaskTable.tsx
  39. 6 12
      src/components/admin/tickets/TicketDetailModal.tsx
  40. 12 9
      src/components/dashboard/ChangePasswordModal.tsx
  41. 6 8
      src/components/dashboard/OrderList.tsx
  42. 4 10
      src/components/dashboard/ProfileSettings.tsx
  43. 6 8
      src/components/dashboard/TicketList.tsx
  44. 2 2
      src/components/dashboard/TicketModal.tsx
  45. 5 5
      src/components/dashboard/UserOrderDetailModal.tsx
  46. 6 11
      src/components/dashboard/UserTicketDetailModal.tsx
  47. 2 7
      src/components/payment/PaymentConfirmCard.tsx
  48. 5 7
      src/hooks/useAutoRegister.ts
  49. 96 0
      src/lib/services/accountService.ts
  50. 71 0
      src/lib/services/authService.ts
  51. 61 0
      src/lib/services/configService.ts
  52. 16 0
      src/lib/services/index.ts
  53. 121 0
      src/lib/services/orderService.ts
  54. 186 0
      src/lib/services/paymentService.ts
  55. 153 0
      src/lib/services/productService.ts
  56. 100 0
      src/lib/services/proxyService.ts
  57. 23 0
      src/lib/services/statsService.ts
  58. 125 0
      src/lib/services/taskService.ts
  59. 85 0
      src/lib/services/ticketService.ts
  60. 68 0
      src/lib/services/userService.ts
  61. 1 0
      src/types/order.ts
  62. 2 0
      src/types/product.ts

+ 10 - 12
src/app/admin/accounts/page.tsx

@@ -16,9 +16,9 @@ import {
   Trash2,
   X,
 } from 'lucide-react';
-import api from '@/lib/api';
 import { toast } from 'react-hot-toast';
 import { retroConfirm } from '@/lib/dialog';
+import { accountService } from '@/lib/services';
 
 import AccountTable from '@/components/admin/accounts/AccountTable';
 import AccountAddModal from '@/components/admin/accounts/AccountAddModal';
@@ -52,15 +52,13 @@ export default function AdminAccountsPage() {
   const fetchAccounts = async (targetPage: number = page) => {
     setLoading(true);
     try {
-      const res = await api.get('/api/account/list_all', {
-        params: {
-          page: targetPage,
-          size: pageSize,
-          keyword: keyword.trim(),
-        },
+      const res = await accountService.listAll({
+        page: targetPage,
+        size: pageSize,
+        keyword: keyword.trim(),
       });
 
-      const resData = res.data?.data || {};
+      const resData = res?.data || {};
       if (resData && Array.isArray(resData.items)) {
         setData(resData.items);
         setTotal(resData.total || 0);
@@ -159,10 +157,10 @@ export default function AdminAccountsPage() {
   const handleExecuteLock = async (account: Account, unlock: boolean, duration: number) => {
     try {
       if (unlock) {
-        await api.post('/api/account/unlock', null, { params: { id: account.id } });
+        await accountService.unlock(account.id);
         toast.success(`账号 "${account.username}" 已解锁`);
       } else {
-        await api.post('/api/account/lock', { duration }, { params: { id: account.id } });
+        await accountService.lock(account.id, duration);
         toast.success(`账号 "${account.username}" 已锁定`);
       }
       setShowLockModal(false);
@@ -175,7 +173,7 @@ export default function AdminAccountsPage() {
   const handleToggleStatus = async (account: Account) => {
     const newStatus = account.status === 'active' ? 'disable' : 'active';
     try {
-      await api.post('/api/account/set_status', { status: newStatus }, { params: { id: account.id } });
+      await accountService.setStatus(account.id, newStatus);
       toast.success(`账号状态已切换为: ${newStatus}`);
       fetchAccounts(page);
     } catch {
@@ -192,7 +190,7 @@ export default function AdminAccountsPage() {
     });
     if (!ok) return;
     try {
-      await api.delete('/api/account/delete', { params: { account_id: account.id } });
+      await accountService.delete(account.id);
       toast.success('账号已删除');
       fetchAccounts(page);
     } catch {

+ 8 - 12
src/app/admin/configurations/page.tsx

@@ -15,32 +15,30 @@ import {
 } 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';
 import ConfigurationDetailDrawer from '@/components/admin/configurations/ConfigurationDetailDrawer';
 import ConfigurationExportModal from '@/components/admin/configurations/ConfigurationExportModal';
 import ConfigurationImportModal from '@/components/admin/configurations/ConfigurationImportModal';
 import { DynamicConfiguration } from '@/types';
+import { configService } from '@/lib/services';
 
 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') {
+    } else {
       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,
+    id: item.id || 0,
     config_key: String(item.config_key || ''),
     config_value: val,
     description: String(item.description || ''),
@@ -67,8 +65,8 @@ export default function AdminConfigurationsPage() {
   const fetchConfigs = async () => {
     setLoading(true);
     try {
-      const res = await api.get('/api/dynamic-configurations/all');
-      const list = res.data?.data || [];
+      const res = await configService.getAll();
+      const list = res?.data || [];
       setConfigs(Array.isArray(list) ? list.map(normalizeConfig) : []);
     } catch (e: any) {
       toast.error('读取配置失败: ' + (e.response?.data?.message || e.message || '未知错误'));
@@ -91,10 +89,8 @@ export default function AdminConfigurationsPage() {
 
     setLoading(true);
     try {
-      const res = await api.get(
-        `/api/dynamic-configurations/key/${encodeURIComponent(targetKey)}`
-      );
-      const item = res.data?.data;
+      const res = await configService.getByKey(targetKey);
+      const item = res?.data;
       if (item) {
         setConfigs([normalizeConfig(item)]);
         toast.success(`找到配置 "${targetKey}"`);
@@ -189,7 +185,7 @@ export default function AdminConfigurationsPage() {
     if (!ok) return;
 
     try {
-      await api.delete(`/api/dynamic-configurations/key/${encodeURIComponent(config.config_key)}`);
+      await configService.delete(config.config_key);
       toast.success(`配置 "${config.config_key}" 已删除`);
       fetchConfigs();
     } catch (e: any) {

+ 8 - 10
src/app/admin/orders/new/page.tsx

@@ -3,7 +3,7 @@
 import { useState, useEffect } from 'react';
 import { useRouter } from 'next/navigation';
 import { ArrowLeft } from 'lucide-react';
-import api from '@/lib/api';
+import { productService, orderService } from '@/lib/services';
 import ProductSearchSelector from '@/components/admin/orders/ProductSearchSelector';
 import AiDataParserPanel from '@/components/admin/orders/AiDataParserPanel';
 import DynamicOrderSchemaForm from '@/components/admin/orders/DynamicOrderSchemaForm';
@@ -32,19 +32,17 @@ export default function AdminCreateOrderPage() {
         return;
       }
       try {
-        const res = await api.get('/api/vas/schema/detail', {
-          params: { schema_id: selectedProduct.schema_id },
-        });
-        const data = res.data.data || res.data;
+        const res = await productService.getSchemaDetail(selectedProduct.schema_id);
+        const data = res?.data || res;
         const schemaJson =
-          typeof data.schema_json === 'string'
+          typeof data?.schema_json === 'string'
             ? JSON.parse(data.schema_json)
-            : data.schema_json;
+            : data?.schema_json;
 
         setFormSchema(schemaJson);
         setFormValues({});
 
-        if (schemaJson.properties) {
+        if (schemaJson?.properties) {
           const keys = Object.keys(schemaJson.properties);
           if (Array.isArray(schemaJson['ui:order'])) {
             setSortedFields(schemaJson['ui:order']);
@@ -91,8 +89,8 @@ export default function AdminCreateOrderPage() {
         user_inputs: formValues,
       };
 
-      const res = await api.post('/api/vas/order/create_by_admin', payload);
-      const orderId = res.data.data?.id || res.data?.id || res.data?.order_id;
+      const res = await orderService.createByAdmin(payload);
+      const orderId = res?.data?.id || res?.id || res?.data?.order_id || res?.order_id;
 
       toast.success(`代下单成功!订单号: ${orderId}`);
       router.push('/admin/orders');

+ 12 - 13
src/app/admin/orders/page.tsx

@@ -2,7 +2,7 @@
 
 import { useState, useEffect, useCallback } from 'react';
 import { useRouter } from 'next/navigation';
-import api from '@/lib/api';
+import { orderService } from '@/lib/services';
 import OrderStats from '@/components/admin/orders/OrderStats';
 import OrderFilterBar, { OrderStatusFilter } from '@/components/admin/orders/OrderFilterBar';
 import OrderTable from '@/components/admin/orders/OrderTable';
@@ -25,6 +25,7 @@ export default function AdminOrdersPage() {
   const [page, setPage] = useState(1);
   const [pageSize] = useState(10);
   const [total, setTotal] = useState(0);
+
   const [keyword, setKeyword] = useState('');
   const [statusFilter, setStatusFilter] = useState<OrderStatusFilter>('all');
 
@@ -48,8 +49,8 @@ export default function AdminOrdersPage() {
         params.status = targetStatus;
       }
 
-      const res = await api.get('/api/vas/order/list_all', { params });
-      const data = res.data?.data;
+      const res = await orderService.listAll(params);
+      const data = res?.data;
 
       if (data && Array.isArray(data.items)) {
         setOrders(data.items);
@@ -92,7 +93,7 @@ export default function AdminOrdersPage() {
     });
     if (!ok) return;
     try {
-      await api.post('/api/vas/order/cancel', null, { params: { order_id: orderId } });
+      await orderService.cancel(Number(orderId));
       toast.success('订单已成功取消');
       fetchOrders(page);
       if (selectedOrder?.id === orderId) {
@@ -132,7 +133,7 @@ export default function AdminOrdersPage() {
 
   const handleSubmitEdit = async (orderId: string, data: any) => {
     try {
-      await api.post(`/api/vas/order/patch_user_inputs`, data, { params: { order_id: orderId } });
+      await orderService.patchUserInputs(Number(orderId), data);
       toast.success('订单信息更新成功。');
       setIsEditOpen(false);
       fetchOrders(page);
@@ -144,17 +145,15 @@ export default function AdminOrdersPage() {
   const handleExportCsv = async () => {
     setExporting(true);
     try {
-      const res = await api.get('/api/vas/order/list_all', {
-        params: {
-          keyword: keyword.trim() || undefined,
-          status: statusFilter !== 'all' ? statusFilter : undefined,
-          page: 1,
-          size: 500,
-        },
+      const res = await orderService.listAll({
+        keyword: keyword.trim() || undefined,
+        status: statusFilter !== 'all' ? statusFilter : undefined,
+        page: 1,
+        size: 500,
       });
 
       const list: ExtendedOrderDetail[] =
-        res.data?.data?.items || (Array.isArray(res.data?.data) ? res.data?.data : orders);
+        res?.data?.items || (Array.isArray(res?.data) ? res?.data : orders);
 
       if (!list || list.length === 0) {
         toast.error('当前无订单数据可供导出');

+ 3 - 3
src/app/admin/page.tsx

@@ -1,12 +1,12 @@
 'use client';
 
 import { useState, useEffect } from 'react';
-import api from '@/lib/api';
 import DataStats from '@/components/admin/DataStats'; 
 import OverviewCharts from '@/components/admin/dashboard/OverviewCharts'; 
 import RecentActivities, { ActivityItem } from '@/components/admin/dashboard/RecentActivities';
 import { ShoppingBag, AlertCircle, CheckCircle, Wallet, ArrowRight, ShieldAlert, Cpu } from 'lucide-react';
 import Link from 'next/link';
+import { statsService } from '@/lib/services';
 
 interface DashboardStats {
   totalOrders: number;
@@ -51,8 +51,8 @@ export default function AdminDashboard() {
   const fetchDashboardData = async () => {
     setLoading(true);
     try {
-      const res = await api.get('/api/vas/statistics/overview');
-      const data = res.data.data;
+      const res = await statsService.getOverview();
+      const data = res?.data;
 
       if (data) {
         setStats(data.stats);

+ 10 - 12
src/app/admin/payments/page.tsx

@@ -1,7 +1,6 @@
 'use client';
 
 import { useState, useEffect, useCallback } from 'react';
-import api from '@/lib/api';
 import { Plus, RefreshCw, Banknote, ShieldCheck } from 'lucide-react';
 import ProviderList from '@/components/admin/payments/ProviderList';
 import ProviderModal from '@/components/admin/payments/ProviderModal';
@@ -12,6 +11,7 @@ import { DEFAULT_PAYMENT_ICONS } from '@/components/admin/payments/paymentIcons'
 import { toast } from 'react-hot-toast';
 import { retroConfirm } from '@/lib/dialog';
 import { Provider, RateConfig } from '@/types';
+import { paymentService, configService } from '@/lib/services';
 
 export default function AdminPaymentsPage() {
   const [providers, setProviders] = useState<Provider[]>([]);
@@ -27,8 +27,8 @@ export default function AdminPaymentsPage() {
   const fetchProviders = useCallback(async () => {
     setLoading(true);
     try {
-      const res = await api.get('/api/vas/payment_provider/list_all');
-      const list = Array.isArray(res.data) ? res.data : (res.data.data || []);
+      const res = await paymentService.listAllProviders();
+      const list = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : []);
       setProviders(list);
     } catch {
       setProviders([
@@ -44,8 +44,8 @@ export default function AdminPaymentsPage() {
 
   const fetchRateConfig = useCallback(async () => {
     try {
-      const res = await api.get('/api/dynamic-configurations/key/EXCHANGE_RATES');
-      const val = res.data?.data?.config_value;
+      const res = await configService.getByKey('EXCHANGE_RATES');
+      const val = res?.data?.config_value;
       if (val && typeof val === 'object') {
         setRateConfig(val);
       } else if (typeof val === 'string') {
@@ -72,9 +72,9 @@ export default function AdminPaymentsPage() {
   const handleSaveProvider = async (data: any) => {
     try {
       if (data.id) {
-        await api.post('/api/vas/payment_provider/update', data, { params: { id: data.id } });
+        await paymentService.updateProvider(data);
       } else {
-        await api.post('/api/vas/payment_provider/create', data);
+        await paymentService.createProvider(data);
       }
       toast.success("保存成功");
       fetchProviders();
@@ -87,10 +87,10 @@ export default function AdminPaymentsPage() {
   const handleToggleProviderStatus = async (provider: Provider) => {
     const nextEnabled = provider.enabled ? 0 : 1;
     try {
-      await api.post('/api/vas/payment_provider/update', {
+      await paymentService.updateProvider({
         ...provider,
         enabled: nextEnabled
-      }, { params: { id: provider.id } });
+      });
 
       setProviders(prev => prev.map(p => p.id === provider.id ? { ...p, enabled: nextEnabled } : p));
     } catch (e: any) {
@@ -110,9 +110,7 @@ export default function AdminPaymentsPage() {
     if (!ok) return;
 
     try {
-      await api.delete('/api/vas/payment_provider/delete', {
-        params: { id: provider.id }
-      });
+      await paymentService.deleteProvider(provider.id);
       toast.success("服务商已成功删除");
       fetchProviders(); 
     } catch (e: any) {

+ 28 - 38
src/app/admin/products/page.tsx

@@ -1,7 +1,6 @@
 'use client';
 
 import { useState, useEffect, useMemo } from 'react';
-import api from '@/lib/api';
 import {
   Plus,
   RefreshCw,
@@ -23,29 +22,31 @@ import RoutingManager from '@/components/admin/products/RoutingManager';
 import SchemaManager from '@/components/admin/products/SchemaManager';
 import ProductDetailDrawer from '@/components/admin/products/ProductDetailDrawer';
 import Pagination from '@/components/common/Pagination';
-import { Product, SchemaItem } from '@/types';
+import { Product, FormSchema } from '@/types';
+import { productService } from '@/lib/services';
 
 export default function AdminProductsPage() {
   const [allProducts, setAllProducts] = useState<Product[]>([]);
-  const [schemas, setSchemas] = useState<SchemaItem[]>([]);
+  const [schemas, setSchemas] = useState<FormSchema[]>([]);
   const [loading, setLoading] = useState(true);
 
-  const [statusTab, setStatusTab] = useState<'all' | 'active' | 'inactive'>('all');
-
+  // 筛选与搜索
   const [keyword, setKeyword] = useState('');
+  const [statusTab, setStatusTab] = useState<'all' | 'active' | 'inactive'>('all');
   const [selectedVisaType, setSelectedVisaType] = useState<string>('all');
   const [selectedCountry, setSelectedCountry] = useState<string>('all');
   const [selectedProvider, setSelectedProvider] = useState<string>('all');
-  const [selectedSchemaFilter, setSelectedSchemaFilter] = useState<'all' | 'bound' | 'unbound'>('all');
+  const [selectedSchemaFilter, setSelectedSchemaFilter] = useState<string>('all');
 
+  // 分页
   const [page, setPage] = useState(1);
-  const [pageSize] = useState(10);
+  const pageSize = 10;
 
+  // 模态框与抽屉状态
   const [isProductModalOpen, setProductModalOpen] = useState(false);
   const [isRoutingModalOpen, setRoutingModalOpen] = useState(false);
   const [isSchemaModalOpen, setSchemaModalOpen] = useState(false);
   const [isDrawerOpen, setIsDrawerOpen] = useState(false);
-
   const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
 
   useEffect(() => {
@@ -56,12 +57,12 @@ export default function AdminProductsPage() {
     setLoading(true);
     try {
       const [prodRes, schemaRes] = await Promise.allSettled([
-        api.get('/api/vas/product/list', { params: { size: 1000 } }),
-        api.get('/api/vas/schema/list'),
+        productService.listAll({ size: 1000 }),
+        productService.listSchemas(),
       ]);
 
       if (prodRes.status === 'fulfilled') {
-        const data = prodRes.value.data?.data || {};
+        const data = prodRes.value?.data || {};
         if (Array.isArray(data)) {
           setAllProducts(data);
         } else if (Array.isArray(data.items)) {
@@ -74,7 +75,7 @@ export default function AdminProductsPage() {
       }
 
       if (schemaRes.status === 'fulfilled') {
-        const schemaData = schemaRes.value.data?.data;
+        const schemaData = schemaRes.value?.data;
         setSchemas(Array.isArray(schemaData) ? schemaData : []);
       }
     } catch {
@@ -87,8 +88,8 @@ export default function AdminProductsPage() {
   const fetchProductsOnly = async () => {
     setLoading(true);
     try {
-      const res = await api.get('/api/vas/product/list', { params: { size: 1000 } });
-      const data = res.data?.data || {};
+      const res = await productService.listAll({ size: 1000 });
+      const data = res?.data || {};
       if (Array.isArray(data)) {
         setAllProducts(data);
       } else if (Array.isArray(data.items)) {
@@ -161,9 +162,9 @@ export default function AdminProductsPage() {
       list = list.filter((p) => p.provider === selectedProvider);
     }
 
-    if (selectedSchemaFilter === 'bound') {
+    if (selectedSchemaFilter === 'has_schema') {
       list = list.filter((p) => p.schema_id && p.schema_id > 0);
-    } else if (selectedSchemaFilter === 'unbound') {
+    } else if (selectedSchemaFilter === 'no_schema') {
       list = list.filter((p) => !p.schema_id || p.schema_id === 0);
     }
 
@@ -175,24 +176,17 @@ export default function AdminProductsPage() {
     });
 
     return list;
-  }, [
-    allProducts,
-    statusTab,
-    keyword,
-    selectedVisaType,
-    selectedCountry,
-    selectedProvider,
-    selectedSchemaFilter,
-  ]);
+  }, [allProducts, statusTab, keyword, selectedVisaType, selectedCountry, selectedProvider, selectedSchemaFilter]);
 
+  const totalPages = Math.ceil(filteredProducts.length / pageSize) || 1;
   const paginatedProducts = useMemo(() => {
     const start = (page - 1) * pageSize;
     return filteredProducts.slice(start, start + pageSize);
   }, [filteredProducts, page, pageSize]);
 
   const handleResetFilters = () => {
-    setStatusTab('all');
     setKeyword('');
+    setStatusTab('all');
     setSelectedVisaType('all');
     setSelectedCountry('all');
     setSelectedProvider('all');
@@ -211,10 +205,10 @@ export default function AdminProductsPage() {
   const handleSaveProduct = async (data: any) => {
     try {
       if (data.id) {
-        await api.post('/api/vas/product/update', data, { params: { id: data.id } });
+        await productService.update(data.id, data);
         toast.success(`商品 #${data.id} 更新成功`);
       } else {
-        await api.post('/api/vas/product/create', data);
+        await productService.create(data);
         toast.success('新商品发布成功');
       }
       fetchProductsOnly();
@@ -231,14 +225,10 @@ export default function AdminProductsPage() {
     const newStatus = product.enabled ? 0 : 1;
     const actionText = newStatus ? '上架' : '下架';
     try {
-      await api.post(
-        '/api/vas/product/update',
-        {
-          ...product,
-          enabled: newStatus,
-        },
-        { params: { id: product.id } }
-      );
+      await productService.update(product.id, {
+        ...product,
+        enabled: newStatus,
+      });
 
       toast.success(`商品 #${product.id} 已${actionText}`);
 
@@ -645,8 +635,8 @@ export default function AdminProductsPage() {
         isOpen={isSchemaModalOpen}
         onClose={() => {
           setSchemaModalOpen(false);
-          api.get('/api/vas/schema/list').then((res) => {
-            setSchemas(Array.isArray(res.data?.data) ? res.data.data : []);
+          productService.listSchemas().then((res) => {
+            setSchemas(Array.isArray(res?.data) ? res.data : []);
           });
         }}
       />

+ 10 - 12
src/app/admin/proxies/page.tsx

@@ -17,9 +17,9 @@ import {
   X,
   Globe,
 } from 'lucide-react';
-import api from '@/lib/api';
 import { toast } from 'react-hot-toast';
 import { retroConfirm } from '@/lib/dialog';
+import { proxyService } from '@/lib/services';
 
 import ProxyTable from '@/components/admin/proxies/ProxyTable';
 import ProxyAddModal from '@/components/admin/proxies/ProxyAddModal';
@@ -54,15 +54,13 @@ export default function AdminProxiesPage() {
   const fetchProxies = async (targetPage: number = page) => {
     setLoading(true);
     try {
-      const res = await api.get('/api/proxy/list_all', {
-        params: {
-          page: targetPage,
-          size: pageSize,
-          keyword: keyword.trim(),
-        },
+      const res = await proxyService.listAll({
+        page: targetPage,
+        size: pageSize,
+        keyword: keyword.trim(),
       });
 
-      const resData = res.data?.data || {};
+      const resData = res?.data || {};
       if (resData && Array.isArray(resData.items)) {
         setData(resData.items);
         setTotal(resData.total || 0);
@@ -173,10 +171,10 @@ export default function AdminProxiesPage() {
   const handleExecuteLock = async (proxy: ProxyItem, unlock: boolean, duration: number) => {
     try {
       if (unlock) {
-        await api.post('/api/proxy/unlock', null, { params: { id: proxy.id } });
+        await proxyService.unlock(proxy.id);
         toast.success(`代理 "${proxy.ip}:${proxy.port}" 已解锁`);
       } else {
-        await api.post('/api/proxy/lock', { duration }, { params: { id: proxy.id } });
+        await proxyService.lock(proxy.id, duration);
         toast.success(`代理 "${proxy.ip}:${proxy.port}" 已锁定`);
       }
       setShowLockModal(false);
@@ -189,7 +187,7 @@ export default function AdminProxiesPage() {
   const handleToggleStatus = async (proxy: ProxyItem) => {
     const newStatus = proxy.status === 'active' ? 'disable' : 'active';
     try {
-      await api.post('/api/proxy/set_status', { status: newStatus }, { params: { id: proxy.id } });
+      await proxyService.setStatus(proxy.id, newStatus);
       toast.success(`代理状态已切换为: ${newStatus}`);
       fetchProxies(page);
     } catch {
@@ -206,7 +204,7 @@ export default function AdminProxiesPage() {
     });
     if (!ok) return;
     try {
-      await api.delete('/api/proxy/delete', { params: { proxy_id: proxy.id } });
+      await proxyService.delete(proxy.id);
       toast.success('代理节点已删除');
       fetchProxies(page);
     } catch {

+ 32 - 34
src/app/admin/tasks/page.tsx

@@ -1,7 +1,6 @@
 'use client';
 
 import { useState, useEffect, useMemo, useCallback } from 'react';
-import api from '@/lib/api';
 import {
   RefreshCw,
   Search,
@@ -22,6 +21,7 @@ import Pagination from '@/components/common/Pagination';
 import { toast } from 'react-hot-toast';
 import { retroConfirm } from '@/lib/dialog';
 import { VasTask } from '@/types';
+import { taskService } from '@/lib/services';
 
 export default function AdminTasksPage() {
   const [tasks, setTasks] = useState<VasTask[]>([]);
@@ -58,8 +58,8 @@ export default function AdminTasksPage() {
           params.status = statusFilter;
         }
 
-        const res = await api.get('/api/vas/task/list', { params });
-        const data = res.data.data || {};
+        const res = await taskService.listAll(params);
+        const data = res?.data || {};
 
         if (Array.isArray(data)) {
           setTasks(data);
@@ -118,42 +118,43 @@ export default function AdminTasksPage() {
     }
 
     if (keyword.trim()) {
-      const q = keyword.trim().toLowerCase();
+      const lower = keyword.trim().toLowerCase();
       result = result.filter((t) => {
-        return (
-          String(t.id).includes(q) ||
-          String(t.order_id).toLowerCase().includes(q) ||
-          (t.routing_key || '').toLowerCase().includes(q) ||
-          (t.script_version || '').toLowerCase().includes(q)
-        );
+        const idMatch = String(t.id).includes(lower);
+        const orderIdMatch = String(t.order_id).toLowerCase().includes(lower);
+        const routingMatch = (t.routing_key || '').toLowerCase().includes(lower);
+        const scriptMatch = (t.script_version || '').toLowerCase().includes(lower);
+        return idMatch || orderIdMatch || routingMatch || scriptMatch;
       });
     }
 
-    result = [...result].sort((a, b) => {
-      let aVal: any = (a as any)[sortField];
-      let bVal: any = (b as any)[sortField];
+    result.sort((a: any, b: any) => {
+      let valA = a[sortField];
+      let valB = b[sortField];
 
-      if (sortField === 'updated_at' || sortField === 'created_at' || sortField === 'expire_at') {
-        const aTime = aVal ? new Date(aVal).getTime() : 0;
-        const bTime = bVal ? new Date(bVal).getTime() : 0;
-        return sortOrder === 'asc' ? aTime - bTime : bTime - aTime;
+      if (valA === null || valA === undefined) return 1;
+      if (valB === null || valB === undefined) return -1;
+
+      if (sortField.includes('at') || sortField.includes('time')) {
+        const timeA = new Date(valA).getTime() || 0;
+        const timeB = new Date(valB).getTime() || 0;
+        return sortOrder === 'asc' ? timeA - timeB : timeB - timeA;
       }
 
-      if (sortField === 'priority' || sortField === 'id' || sortField === 'attempt_count') {
-        const aNum = Number(aVal) || 0;
-        const bNum = Number(bVal) || 0;
-        return sortOrder === 'asc' ? aNum - bNum : bNum - aNum;
+      if (typeof valA === 'number' && typeof valB === 'number') {
+        return sortOrder === 'asc' ? valA - valB : valB - valA;
       }
 
-      const strA = String(aVal || '');
-      const strB = String(bVal || '');
-      return sortOrder === 'asc' ? strA.localeCompare(strB) : strB.localeCompare(strA);
+      const strA = String(valA).toLowerCase();
+      const strB = String(valB).toLowerCase();
+      if (strA < strB) return sortOrder === 'asc' ? -1 : 1;
+      if (strA > strB) return sortOrder === 'asc' ? 1 : -1;
+      return 0;
     });
 
     return result;
   }, [tasks, routingKeyFilter, retryFilter, keyword, sortField, sortOrder]);
 
-  // 独立的全局统计数据(不受 statusFilter 影响)
   const [metrics, setMetrics] = useState({
     total: 0,
     pending: 0,
@@ -165,10 +166,8 @@ export default function AdminTasksPage() {
 
   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 res = await taskService.listAll({ page: 1, size: 9999 });
+      const data = res?.data || {};
       const allTasks: VasTask[] = Array.isArray(data) ? data : data.items || [];
 
       setMetrics({
@@ -186,7 +185,6 @@ export default function AdminTasksPage() {
     }
   }, []);
 
-  // 页面加载和任务变更时刷新统计
   useEffect(() => {
     fetchMetrics();
   }, [fetchMetrics]);
@@ -217,7 +215,7 @@ export default function AdminTasksPage() {
     });
     if (!ok) return;
     try {
-      await api.post('/api/vas/task/return_to_queue', null, { params: { task_id: taskId } });
+      await taskService.returnToQueue(taskId);
       toast.success('任务已重新排队待命中');
       fetchTasks(page);
       fetchMetrics();
@@ -235,7 +233,7 @@ export default function AdminTasksPage() {
     });
     if (!ok) return;
     try {
-      await api.post('/api/vas/task/manual_confirm', null, { params: { task_id: taskId } });
+      await taskService.manualConfirm(taskId);
       toast.success('任务已强制标记为完成');
       fetchTasks(page);
       fetchMetrics();
@@ -253,7 +251,7 @@ export default function AdminTasksPage() {
     });
     if (!ok) return;
     try {
-      await api.post('/api/vas/task/pause', null, { params: { task_id: taskId } });
+      await taskService.pause(taskId);
       toast.success('任务已暂停');
       fetchTasks(page);
       fetchMetrics();
@@ -269,7 +267,7 @@ export default function AdminTasksPage() {
 
   const handleSubmitEdit = async (taskId: number, data: any) => {
     try {
-      await api.post('/api/vas/task/update', data, { params: { id: taskId } });
+      await taskService.update(taskId, data);
       toast.success('任务信息已更新');
       setIsEditOpen(false);
       fetchTasks(page);

+ 6 - 8
src/app/admin/tickets/page.tsx

@@ -1,12 +1,12 @@
 'use client';
 
 import { useState, useEffect } from 'react';
-import api from '@/lib/api';
 import TicketTable from '@/components/admin/tickets/TicketTable';
 import TicketDetailModal from '@/components/admin/tickets/TicketDetailModal';
 import Pagination from '@/components/common/Pagination';
 import { RefreshCw, Search, LifeBuoy } from 'lucide-react';
 import { AdminTicket } from '@/types';
+import { ticketService } from '@/lib/services';
 
 export default function AdminTicketsPage() {
   const [loading, setLoading] = useState<boolean>(true);
@@ -23,15 +23,13 @@ export default function AdminTicketsPage() {
   const fetchTickets = async (targetPage: number = page) => {
     setLoading(true);
     try {
-      const res = await api.get('/api/vas/ticket/list_all', {
-        params: {
-          page: targetPage,
-          size: pageSize,
-          keyword: keyword
-        }
+      const res = await ticketService.listAll({
+        page: targetPage,
+        size: pageSize,
+        keyword: keyword
       });
 
-      const data = res.data.data;
+      const data = res?.data;
       if (data && Array.isArray(data.items)) {
         setTickets(data.items);
         setTotal(data.total || 0);

+ 10 - 14
src/app/admin/users/page.tsx

@@ -1,13 +1,13 @@
 'use client';
 
 import { useState, useEffect } from 'react';
-import api from '@/lib/api';
 import { RefreshCw, Search, Users } from 'lucide-react';
 import UserTable from '@/components/admin/users/UserTable';
 import UserModal from '@/components/admin/users/UserModal';
 import Pagination from '@/components/common/Pagination';
 import { toast } from 'react-hot-toast';
 import { AdminUser } from '@/types';
+import { userService } from '@/lib/services';
 
 export default function AdminUsersPage() {
   const [users, setUsers] = useState<AdminUser[]>([]);
@@ -24,17 +24,15 @@ export default function AdminUsersPage() {
   const fetchUsers = async (targetPage = 1, currentKeyword = keyword) => {
     setLoading(true);
     try {
-      const res = await api.get('/api/user/list_all', {
-        params: {
-          page: targetPage,
-          size: pageSize,
-          keyword: currentKeyword || undefined
-        }
+      const res = await userService.listAll({
+        page: targetPage,
+        size: pageSize,
+        keyword: currentKeyword || undefined
       });
-      const data = res.data.data;
-      setUsers(data.items || []);
-      setTotal(data.total || 0);
-      setPage(data.page || targetPage);
+      const data = res?.data;
+      setUsers(data?.items || []);
+      setTotal(data?.total || 0);
+      setPage(data?.page || targetPage);
     } catch (error) {
       console.error("Failed to fetch users", error);
       toast.error("获取用户列表失败");
@@ -59,9 +57,7 @@ export default function AdminUsersPage() {
 
   const handleSubmitUpdate = async (userId: string, data: any) => {
     try {
-      await api.post('/api/user/update', data, {
-        params: { uid: userId }
-      });
+      await userService.update(userId, data);
       toast.success("用户信息更新成功");
       setIsEditOpen(false);
       fetchUsers(page);

+ 3 - 3
src/app/slots/page.tsx

@@ -1,12 +1,12 @@
 'use client';
 
 import { useState, useEffect, useMemo } from 'react';
-import api from '@/lib/api';
 import { Info, Activity, Radio } from 'lucide-react';
 import { useLanguage } from '@/lib/i18n/LanguageContext';
 import SlotFilterBar, { LOCATIONS } from '@/components/slots/SlotFilterBar';
 import SlotGrid from '@/components/slots/SlotGrid';
 import { SlotSnapshot } from '@/types';
+import { statsService } from '@/lib/services';
 
 const SUBSCRIPTION_BLACKLIST = [
   { city: 'Dublin', country: 'France' },
@@ -45,8 +45,8 @@ export default function SlotDashboardPage() {
   const fetchDashboard = async () => {
     setLoading(true);
     try {
-      const res = await api.get('/api/slots/overview', { params: { city: selectedCity } }); 
-      const data = res.data.data || [];
+      const res = await statsService.getSlotsOverview(selectedCity); 
+      const data = res?.data || [];
 
       // 过滤当前城市
       const filtered = data.filter((i: SlotSnapshot) => i.city === selectedCity);

+ 5 - 5
src/components/AuthForm.tsx

@@ -1,12 +1,12 @@
 'use client';
 
 import { useState } from 'react';
-import api from '@/lib/api';
 import { useRouter } from 'next/navigation';
 import ForgotPasswordModal from '@/components/ForgotPasswordModal';
 import { useLanguage } from '@/lib/i18n/LanguageContext';
 import { Zap, KeyRound, ShieldAlert, ArrowRight, UserCheck } from 'lucide-react';
 import MessageModal from '@/components/common/MessageModal';
+import { authService } from '@/lib/services';
 
 export default function AuthForm() {
   const router = useRouter();
@@ -48,13 +48,13 @@ export default function AuthForm() {
     try {
       let res;
       if (isLoginMode) {
-        res = await api.post('/api/auth/login', formData);
+        res = await authService.login(formData);
       } else {
-        res = await api.post('/api/auth/auto-register', {});
+        res = await authService.autoRegister({});
       }
       
-      const data = res.data.data || res.data;
-      const token = data.token || data.access_token;
+      const data = res?.data || res;
+      const token = data?.token || data?.access_token;
       
       if (token) {
         localStorage.setItem('rsid', token);

+ 4 - 4
src/components/AutoRegistrar.tsx

@@ -1,7 +1,7 @@
 'use client'; // <--- 必须加这行
 
 import { useEffect } from 'react';
-import api from '@/lib/api';
+import { authService } from '@/lib/services';
 
 export default function AutoRegistrar() {
   useEffect(() => {
@@ -19,12 +19,12 @@ export default function AutoRegistrar() {
 
       try {
         // 2. 调用自动注册接口
-        const res = await api.post('/api/auth/auto-register', {
+        const res = await authService.autoRegister({
           register_ip: 'client-init'
         });
 
-        const data = res.data.data || res.data;
-        const newToken = data.token || data.access_token;
+        const data = res?.data || res;
+        const newToken = data?.token || data?.access_token;
 
         // 3. 保存 Token
         if (newToken) {

+ 6 - 6
src/components/BindEmailModal.tsx

@@ -1,10 +1,10 @@
 'use client';
 
 import { useState, useEffect } from 'react';
-import api from '@/lib/api';
 import { Mail, Loader2, Save, Lock, ArrowRight, ArrowLeft } from 'lucide-react';
 import { useLanguage } from '@/lib/i18n/LanguageContext';
 import MessageModal from '@/components/common/MessageModal';
+import { authService } from '@/lib/services';
 
 interface BindEmailModalProps {
   isOpen: boolean;
@@ -70,7 +70,7 @@ export default function BindEmailModal({ isOpen, onClose, onSuccess }: BindEmail
     
     setLoading(true);
     try {
-      await api.post('/api/auth/send-bind-code', { email });
+      await authService.sendBindCode(email);
       
       showMessage(`${t('bind_email.alert_code_sent') || '验证码已发送至'} ${email}`, 'success');
       setStep(2);
@@ -91,11 +91,11 @@ export default function BindEmailModal({ isOpen, onClose, onSuccess }: BindEmail
 
     setLoading(true);
     try {
-      const res = await api.post('/api/auth/bind-email', { email, code });
+      const res = await authService.bindEmail({ email, code });
 
-      const data = res.data.data || res.data;
-      const newToken = data.token || data.access_token;
-      const newUser = data.user;
+      const data = res?.data || res;
+      const newToken = data?.token || data?.access_token;
+      const newUser = data?.user;
 
       if (newToken) {
         localStorage.setItem('rsid', newToken);

+ 52 - 48
src/components/CreateOrderForm.tsx

@@ -1,7 +1,6 @@
 'use client';
 
 import { useState, useEffect } from 'react';
-import api from '@/lib/api';
 import { useRouter, useSearchParams } from 'next/navigation';
 import { 
   Loader2, 
@@ -21,11 +20,21 @@ import { useLanguage } from '@/lib/i18n/LanguageContext';
 import ConfirmModal from '@/components/common/ConfirmModal';
 import MessageModal from '@/components/common/MessageModal';
 import { ProductDetail, SchemaProperty, JsonSchema } from '@/types';
+import { productService, authService, orderService } from '@/lib/services';
 
 // ==========================================
-// 组件入参
+// 辅助函数与常量 (原有字段美化逻辑保持不变)
 // ==========================================
 
+const getFieldLabel = (key: string, prop: SchemaProperty, t: any): string => {
+  return prop.title || key;
+};
+
+const getFieldPlaceholder = (key: string, prop: SchemaProperty, t: any): string => {
+  if (prop.description) return prop.description;
+  return `${t('common.enter')} ${getFieldLabel(key, prop, t)}`;
+};
+
 interface CreateOrderFormProps {
   productId: string;
   productName?: string;
@@ -37,46 +46,45 @@ interface CreateOrderFormProps {
 
 export default function CreateOrderForm({ productId, productName }: CreateOrderFormProps) {
   const router = useRouter();
-  const { t } = useLanguage();
   const searchParams = useSearchParams();
-  const slotRoutingKey = searchParams?.get('slot_routing_key') || undefined;
-  const slotCity = searchParams?.get('slot_city') || undefined;
-  const slotCountry = searchParams?.get('slot_country') || undefined;
-  const slotVisaType = searchParams?.get('slot_visa_type') || undefined;
-  const isSlotSubscription = Boolean(slotRoutingKey);
-  const promoLabel = isSlotSubscription
-    ? (t('order.promo_label_slot') || '实时监控提醒')
-    : (t('order.promo_label') || '限时官方保障');
-  const promoSubtext = isSlotSubscription
-    ? (t('order.promo_subtext_slot') || '名额放出邮件/WhatsApp即时通知')
-    : (t('order.promo_subtext') || '自动锁位 · 失败全退');
-
-  // --- 状态管理 ---
-  const [loading, setLoading] = useState<boolean>(true);
-  const [submitting, setSubmitting] = useState<boolean>(false);
-  
-  // 数据状态
+  const slotRoutingKey = searchParams?.get('routing_key') || '';
+  const slotCountry = searchParams?.get('slot_country') || '';
+  const slotCity = searchParams?.get('slot_city') || '';
+  const slotVisaType = searchParams?.get('slot_visa_type') || '';
+  const { t } = useLanguage();
+
+  const promoLabel = t('services.promo_tag') || '限时立减 / 闪电退款';
+  const promoSubtext = t('services.guarantee_text') || '未成功锁位全额原路退款';
+
   const [product, setProduct] = useState<ProductDetail | null>(null);
   const [formSchema, setFormSchema] = useState<JsonSchema | null>(null);
   const [formValues, setFormValues] = useState<Record<string, any>>({});
-
-  // 弹窗控制状态
-  const [isBindEmailOpen, setIsBindEmailOpen] = useState(false);
-  const [showConfirmModal, setShowConfirmModal] = useState(false);
   
-  const [msgModal, setMsgModal] = useState({
+  const [loading, setLoading] = useState<boolean>(true);
+  const [submitting, setSubmitting] = useState<boolean>(false);
+  const [isBindEmailOpen, setIsBindEmailOpen] = useState<boolean>(false);
+
+  // 待创建订单的缓存数据
+  const [pendingCreation, setPendingCreation] = useState<boolean>(false);
+
+  const [showConfirmModal, setShowConfirmModal] = useState<boolean>(false);
+
+  const [msgModal, setMsgModal] = useState<{
+    isOpen: boolean;
+    title: string;
+    message: string;
+    type?: 'info' | 'error' | 'success';
+  }>({
     isOpen: false,
     title: '',
     message: '',
-    type: 'error' as 'error' | 'info' | 'success'
   });
 
-  // --- 辅助函数:显示消息 ---
-  const showMessage = (msg: string, title?: string, type: 'error' | 'info' = 'error') => {
+  const showMessage = (message: string, title = t('common.notice'), type: 'info' | 'error' | 'success' = 'info') => {
     setMsgModal({
       isOpen: true,
-      message: msg,
-      title: title || t('common.notice'),
+      title,
+      message,
       type
     });
   };
@@ -88,29 +96,25 @@ export default function CreateOrderForm({ productId, productName }: CreateOrderF
         setLoading(true);
         
         // 1. 获取商品详情
-        const prodRes = await api.get('/api/vas/product/detail', {
-          params: { "product_id": productId }
-        });
-        const prodData = prodRes.data.data || prodRes.data;
+        const prodRes = await productService.getDetail(parseInt(productId));
+        const prodData = prodRes?.data || prodRes;
         setProduct(prodData);
 
         // 2. 获取动态表单定义
-        if (prodData.schema_id) {
+        if (prodData?.schema_id) {
           try {
-            const schemaRes = await api.get('/api/vas/schema/detail', {
-              params: { "schema_id": prodData.schema_id }
-            });
-            const schemaData = schemaRes.data.data || schemaRes.data;
+            const schemaRes = await productService.getSchemaDetail(prodData.schema_id);
+            const schemaData = schemaRes?.data || schemaRes;
             
-            const schemaJson = typeof schemaData.schema_json === 'string' 
+            const schemaJson = typeof schemaData?.schema_json === 'string' 
               ? JSON.parse(schemaData.schema_json) 
-              : schemaData.schema_json;
+              : schemaData?.schema_json;
 
             setFormSchema(schemaJson);
             
             // 3. 初始化默认值
             const initialValues: Record<string, any> = {};
-            if (schemaJson.properties) {
+            if (schemaJson?.properties) {
               Object.keys(schemaJson.properties).forEach(key => {
                 const prop = schemaJson.properties[key];
 
@@ -146,7 +150,7 @@ export default function CreateOrderForm({ productId, productName }: CreateOrderF
     if (productId) {
       initData();
     }
-  }, [productId, t]);
+  }, [productId, t, slotRoutingKey]);
 
   // --- 辅助函数:用户状态检查 ---
   const ensureUserLoggedIn = async (forceNew = false): Promise<boolean> => {
@@ -157,12 +161,12 @@ export default function CreateOrderForm({ productId, productName }: CreateOrderF
 
     try {
       console.log("Detecting no session, auto-registering...");
-      const res = await api.post('/api/auth/auto-register', {
+      const res = await authService.autoRegister({
         register_ip: 'client-lazy-init'
       });
 
-      const data = res.data.data || res.data;
-      const newToken = data.token || data.access_token;
+      const data = res?.data || res;
+      const newToken = data?.token || data?.access_token;
 
       if (newToken) {
         localStorage.setItem('rsid', newToken);
@@ -205,8 +209,8 @@ export default function CreateOrderForm({ productId, productName }: CreateOrderF
       user_inputs: formValues
     };
 
-    const res = await api.post('/api/vas/order/create', payload);
-    const orderId = res.data.data?.id || res.data.id;
+    const res = await orderService.create(payload);
+    const orderId = res?.data?.id || res?.id || res?.data?.order_id || res?.order_id;
     
     if (!orderId) throw new Error("Missing Order ID in response");
     return orderId;

+ 3 - 3
src/components/ForgotPasswordModal.tsx

@@ -1,10 +1,10 @@
 'use client';
 
 import { useState, useEffect } from 'react';
-import api from '@/lib/api';
 import { X, Lock, Loader2, Save, Mail, ArrowRight, KeyRound, Eye, EyeOff } from 'lucide-react';
 import { useLanguage } from '@/lib/i18n/LanguageContext';
 import MessageModal from '@/components/common/MessageModal';
+import { authService } from '@/lib/services';
 
 interface ForgotPasswordModalProps {
   isOpen: boolean;
@@ -69,7 +69,7 @@ export default function ForgotPasswordModal({ isOpen, onClose }: ForgotPasswordM
     
     setLoading(true);
     try {
-      await api.post('/api/auth/send-reset-code', { email });
+      await authService.sendResetCode(email);
       
       showMessage(`${t('forgot_password.code_sent_alert')} ${email}`, 'success');
       setStep(2);
@@ -90,7 +90,7 @@ export default function ForgotPasswordModal({ isOpen, onClose }: ForgotPasswordM
 
     setLoading(true);
     try {
-      await api.post('/api/auth/reset-password', { 
+      await authService.resetPassword({ 
         email, 
         code, 
         new_password: newPassword 

+ 11 - 11
src/components/PaymentProcessor.tsx

@@ -1,7 +1,6 @@
 'use client';
 
 import { useEffect, useMemo, useState } from 'react';
-import api from '@/lib/api';
 import { useRouter } from 'next/navigation';
 import { 
   Loader2, 
@@ -18,6 +17,7 @@ import { useLanguage } from '@/lib/i18n/LanguageContext';
 import LocalTime from '@/components/common/LocalTime';
 import MessageModal from '@/components/common/MessageModal';
 import { PaymentProvider, PaymentResult } from '@/types';
+import { paymentService, orderService } from '@/lib/services';
 
 // === 组件入参 ===
 
@@ -80,8 +80,8 @@ export default function PaymentProcessor({ orderId }: PaymentProcessorProps) {
 
   const fetchProviders = async () => {
     try {
-      const res = await api.get('/api/vas/payment_provider/list_enabled');
-      const list = Array.isArray(res.data) ? res.data : (res.data.data || []);
+      const res = await paymentService.listEnabledProviders();
+      const list = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : []);
       setProviders(list);
     } catch (error) {
       console.error("Failed to load providers", error);
@@ -90,8 +90,8 @@ export default function PaymentProcessor({ orderId }: PaymentProcessorProps) {
 
   const fetchOrderInfo = async () => {
     try {
-      const res = await api.get('/api/vas/order/detail', { params: { order_id: orderId } });
-      const data = res.data.data || res.data;
+      const res = await orderService.getDetail(Number(orderId));
+      const data = res?.data || res;
       const hasSlotRouting = Boolean(data?.user_inputs?.slot_routing_key);
       const isProductMatch = data?.product_id === 16;
       setIsSlotSubscription(hasSlotRouting || isProductMatch);
@@ -115,12 +115,12 @@ export default function PaymentProcessor({ orderId }: PaymentProcessorProps) {
       }
 
       // 1. 创建支付单
-      const payRes = await api.post('/api/vas/payment/create', {
+      const payRes = await paymentService.createPayment({
         order_id: String(orderId),
         provider: providerCode
       });
       
-      const data: PaymentResult = payRes.data.data || payRes.data;
+      const data: PaymentResult = payRes?.data || payRes;
       if (!data?.id) throw new Error("Payment creation failed");
 
       setPaymentData(data); 
@@ -134,10 +134,10 @@ export default function PaymentProcessor({ orderId }: PaymentProcessorProps) {
         }
       } 
       else if (data.channel === 'qr_static') {
-        const qrRes = await api.get('/api/vas/payment_qr/qrcode', {
-          params: { id: data.qr_id }
+        const qrRes = await paymentService.getPaymentQrCode({
+          qr_id: data.qr_id,
         });
-        const qrData = qrRes.data.data || qrRes.data;
+        const qrData = qrRes?.data || qrRes;
         const qrUrl = qrData?.qr_code || qrData?.qrcode_url;
 
         if (qrUrl) {
@@ -177,7 +177,7 @@ export default function PaymentProcessor({ orderId }: PaymentProcessorProps) {
         confirmed_at: new Date().toISOString()
       };
 
-      await api.post('/api/vas/payment/confirm_by_user', payload);
+      await paymentService.confirmByUser(payload);
 
       showMessage(t('payment.confirm_success_alert') || '支付核销申请已提交,系统将尽快确认!', 'success', () => {
         router.push('/dashboard');

+ 4 - 6
src/components/ServiceList.tsx

@@ -2,7 +2,6 @@
 
 import { useEffect, useState, useMemo } from 'react';
 import { useRouter } from 'next/navigation';
-import api from '@/lib/api';
 import {
   Search,
   MapPin,
@@ -19,6 +18,7 @@ import Pagination from '@/components/common/Pagination';
 import { useLanguage } from '@/lib/i18n/LanguageContext';
 import { Product } from '@/types';
 import ServiceDetailModal from '@/components/services/ServiceDetailModal';
+import { productService } from '@/lib/services';
 
 export default function ServiceList() {
   const router = useRouter();
@@ -66,13 +66,11 @@ export default function ServiceList() {
     setError('');
 
     try {
-      const res = await api.get('/api/vas/product/list-enable', {
-        params: {
-          size: 1000,
-        },
+      const res = await productService.listEnabled({
+        size: 1000,
       });
 
-      const data = res.data.data || {};
+      const data = res?.data || {};
       if (Array.isArray(data)) {
         setAllProducts(data);
       } else if (Array.isArray(data.items)) {

+ 4 - 4
src/components/admin/accounts/AccountAddModal.tsx

@@ -3,7 +3,7 @@
 import { useState, useEffect } from 'react';
 import { X, Plus, Eye, EyeOff, Sparkles } from 'lucide-react';
 import { toast } from 'react-hot-toast';
-import api from '@/lib/api';
+import { accountService } from '@/lib/services';
 import { AccountStatus } from '@/types';
 
 const DEFAULT_EXTRA_DATA = '{}';
@@ -77,7 +77,7 @@ export default function AccountAddModal({ isOpen, onClose, onSuccess, existingPo
 
     setSubmitting(true);
     try {
-      const res = await api.post('/api/accounts/create', {
+      const res = await accountService.add({
         pool_name: form.pool_name.trim(),
         username: form.username.trim(),
         password: form.password.trim() || undefined,
@@ -85,12 +85,12 @@ export default function AccountAddModal({ isOpen, onClose, onSuccess, existingPo
         status: form.status,
       });
 
-      if (res.data?.code === 0 || res.status === 200) {
+      if (res?.code === 0 || res?.data) {
         toast.success(`账号 "${form.username}" 已录入`);
         onSuccess();
         onClose();
       } else {
-        toast.error(res.data?.msg || '添加失败');
+        toast.error(res?.msg || '添加失败');
       }
     } catch (e: any) {
       toast.error('添加失败: ' + (e.response?.data?.msg || e.message || '网络错误'));

+ 5 - 6
src/components/admin/accounts/AccountEditModal.tsx

@@ -3,7 +3,7 @@
 import { useState, useEffect } from 'react';
 import { X, Pencil, Eye, EyeOff, Sparkles } from 'lucide-react';
 import { toast } from 'react-hot-toast';
-import api from '@/lib/api';
+import { accountService } from '@/lib/services';
 import LocalTime from '@/components/common/LocalTime';
 import { Account, AccountStatus } from '@/types';
 
@@ -120,12 +120,11 @@ export default function AccountEditModal({
       }
     }
 
-    const nextUseTimeIso = toApiDateTime(form.next_use_time);
+    const nextUseTimeIso = toApiDateTime(form.next_use_time) || new Date().toISOString();
 
     setSubmitting(true);
     try {
-      const res = await api.post('/api/accounts/update', {
-        id: account.id,
+      const res = await accountService.update(account.id, {
         pool_name: form.pool_name.trim(),
         username: form.username.trim(),
         password: form.password.trim() || undefined,
@@ -134,12 +133,12 @@ export default function AccountEditModal({
         next_use_time: nextUseTimeIso,
       });
 
-      if (res.data?.code === 0 || res.status === 200) {
+      if (res?.code === 0 || res?.data) {
         toast.success(`账号 #${account.id} 修改成功`);
         onSuccess();
         onClose();
       } else {
-        toast.error(res.data?.msg || '修改失败');
+        toast.error(res?.msg || '修改失败');
       }
     } catch (e: any) {
       toast.error('修改失败: ' + (e.response?.data?.msg || e.message || '网络错误'));

+ 3 - 3
src/components/admin/configurations/ConfigurationImportModal.tsx

@@ -3,8 +3,8 @@
 import { useState } from 'react';
 import { X, Upload, FileText, CheckCircle2, AlertCircle, Sparkles } from 'lucide-react';
 import { toast } from 'react-hot-toast';
-import api from '@/lib/api';
 import { DynamicConfiguration } from '@/types';
+import { configService } from '@/lib/services';
 
 interface ConfigurationImportModalProps {
   isOpen: boolean;
@@ -102,14 +102,14 @@ export default function ConfigurationImportModal({
 
         try {
           if (isExists && overwrite) {
-            await api.put(`/api/dynamic-configurations/key/${encodeURIComponent(item.config_key)}`, {
+            await configService.updateByKey(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', {
+            await configService.create({
               config_key: item.config_key,
               config_value: item.config_value,
               description: item.description || undefined,

+ 7 - 11
src/components/admin/configurations/ConfigurationModal.tsx

@@ -4,8 +4,8 @@ import { useState, useEffect, useCallback } from 'react';
 import { X, Save, Loader2, AlertCircle, Sparkles, KeyRound, Info, Braces } from 'lucide-react';
 import { toast } from 'react-hot-toast';
 import JsonConfigEditor from '@/components/common/JsonConfigEditor';
-import api from '@/lib/api';
 import { DynamicConfiguration } from '@/types';
+import { configService } from '@/lib/services';
 
 type ConfigurationForm = DynamicConfiguration;
 
@@ -38,15 +38,11 @@ export default function ConfigurationModal({
   useEffect(() => {
     if (isOpen) {
       if (config) {
-        let displayValue = config.config_value;
-        try {
-          displayValue = JSON.stringify(JSON.parse(config.config_value), null, 2);
-        } catch {
-          // keep as is
-        }
         setForm({
-          ...config,
-          config_value: displayValue,
+          id: config.id,
+          config_key: config.config_key || '',
+          config_value: config.config_value || '',
+          description: config.description || '',
           type: config.type || 'json',
         });
       } else {
@@ -76,14 +72,14 @@ export default function ConfigurationModal({
     setSubmitting(true);
     try {
       if (config && config.config_key) {
-        await api.put(`/api/dynamic-configurations/key/${encodeURIComponent(config.config_key)}`, {
+        await configService.updateByKey(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', {
+        await configService.create({
           config_key: form.config_key.trim(),
           config_value: form.config_value,
           description: form.description || undefined,

+ 3 - 3
src/components/admin/orders/AiDataParserPanel.tsx

@@ -3,7 +3,7 @@
 import { useState } from 'react';
 import { Bot, Loader2, Wand2 } from 'lucide-react';
 import { toast } from 'react-hot-toast';
-import api from '@/lib/api';
+import { orderService } from '@/lib/services';
 
 interface AiDataParserPanelProps {
   schemaId: number | string | undefined;
@@ -26,12 +26,12 @@ export default function AiDataParserPanel({ schemaId, onFieldsParsed }: AiDataPa
 
     setParsing(true);
     try {
-      const res = await api.post('/api/vas/llm/data_parsing', {
+      const res = await orderService.parseDataWithLlm({
         input_raw_str: rawInput,
         schema_id: schemaId,
       });
 
-      const responseData = res.data?.data || res.data;
+      const responseData = res?.data || res;
       const fieldsToFill = responseData?.parsed_obj || responseData;
 
       if (fieldsToFill && typeof fieldsToFill === 'object') {

+ 61 - 46
src/components/admin/orders/OrderDetailDrawer.tsx

@@ -1,7 +1,6 @@
 'use client';
 
 import { useState, useEffect, useMemo } from 'react';
-import api from '@/lib/api';
 import {
   X,
   User,
@@ -23,63 +22,79 @@ import {
 } from 'lucide-react';
 import LocalTime from '@/components/common/LocalTime';
 import { getPaymentProviderIcon } from '@/components/admin/payments/paymentIcons';
-import { OrderDetail, PaymentRecord, PaymentQrDetail, UserDetail, OrderEvent, ExtendedOrderDetail } from '@/types';
+import { ExtendedOrderDetail, PaymentRecord } from '@/types';
+import { toast } from 'react-hot-toast';
+import { paymentService, orderService, userService } from '@/lib/services';
+
+const FIELD_DISPLAY_ORDER = [
+  'surname',
+  'name',
+  'birthday',
+  'nationality',
+  'passport_no',
+  'passport_expire_date',
+  'phone',
+  'phone_code',
+  'country_code',
+  'city',
+  'visa_center',
+  'category',
+  'subcategory',
+  'visa_category',
+  'visa_subcategory',
+  'notes',
+];
+
+interface PaymentQrDetail {
+  id: number;
+  qr_code_url?: string;
+  image_url?: string;
+  notes?: string;
+  description?: string;
+  [key: string]: any;
+}
 
 interface OrderDetailDrawerProps {
   isOpen: boolean;
   onClose: () => void;
   order: ExtendedOrderDetail | null;
-  onAdjustPrice?: (order: OrderDetail) => void;
-  onCheckPayments?: (order: OrderDetail) => void;
-  onEdit?: (order: OrderDetail) => void;
+  onEdit?: (order: any) => void;
   onCancel?: (orderId: string) => void;
+  onCancelOrder?: (orderId: string) => void;
+  onAdjustPrice?: (order: any) => void;
+  onCheckPayments?: (order: any) => void;
 }
 
-const FIELD_DISPLAY_ORDER = [
-  'first_name',
-  'last_name',
-  'name',
-  'applicant_name',
-  'passport_no',
-  'birthday',
-  'gender',
-  'email',
-  'phone_country_code',
-  'phone',
-  'destination_country',
-  'visa_type',
-  'departure_date',
-  'social_media_account',
-];
-
 export default function OrderDetailDrawer({
   isOpen,
   onClose,
   order,
-  onAdjustPrice,
-  onCheckPayments,
   onEdit,
   onCancel,
+  onCancelOrder,
+  onAdjustPrice,
+  onCheckPayments,
 }: OrderDetailDrawerProps) {
-  const [paymentList, setPaymentList] = useState<PaymentRecord[]>([]);
-  const [loadingPayments, setLoadingPayments] = useState(false);
-  const [userData, setUserData] = useState<UserDetail | null>(null);
-  const [loadingUser, setLoadingUser] = useState(false);
+  const handleCancelClick = (orderId: string) => {
+    if (onCancel) onCancel(orderId);
+    else if (onCancelOrder) onCancelOrder(orderId);
+  };
+  const [paymentList, setPaymentList] = useState<any[]>([]);
+  const [loadingPayments, setLoadingPayments] = useState<boolean>(false);
+  const [events, setEvents] = useState<any[]>([]);
+  const [loadingEvents, setLoadingEvents] = useState<boolean>(false);
+  const [userData, setUserData] = useState<any>(null);
+  const [loadingUser, setLoadingUser] = useState<boolean>(false);
   const [qrDetails, setQrDetails] = useState<Record<number, PaymentQrDetail>>({});
-  const [events, setEvents] = useState<OrderEvent[]>([]);
-  const [loadingEvents, setLoadingEvents] = useState(false);
-
   const [copiedKey, setCopiedKey] = useState<string | null>(null);
-  const [copiedAllInputs, setCopiedAllInputs] = useState(false);
+  const [copiedAllInputs, setCopiedAllInputs] = useState<boolean>(false);
 
   useEffect(() => {
-    if (isOpen && order?.id) {
+    if (isOpen && order) {
       fetchPayments(order.id);
       fetchEvents(order.id);
       if (order.user_id) {
         fetchUserDetails(order.user_id);
-      } else {
-        setUserData(null);
       }
     } else {
       setPaymentList([]);
@@ -91,8 +106,8 @@ export default function OrderDetailDrawer({
   const fetchPayments = async (orderId: string) => {
     setLoadingPayments(true);
     try {
-      const res = await api.get('/api/vas/payment/list_by_order', { params: { order_id: orderId } });
-      const list = Array.isArray(res.data?.data) ? res.data.data : Array.isArray(res.data) ? res.data : [];
+      const res = await paymentService.listByOrder(Number(orderId));
+      const list = Array.isArray(res?.data) ? res.data : Array.isArray(res) ? res : [];
       setPaymentList(list);
     } catch {
       setPaymentList([]);
@@ -104,8 +119,8 @@ export default function OrderDetailDrawer({
   const fetchEvents = async (orderId: string) => {
     setLoadingEvents(true);
     try {
-      const res = await api.get('/api/vas/order-event/list', { params: { order_id: orderId } });
-      const list = Array.isArray(res.data?.data) ? res.data.data : [];
+      const res = await orderService.getEvents(Number(orderId));
+      const list = Array.isArray(res?.data) ? res.data : [];
       setEvents(list);
     } catch {
       setEvents([]);
@@ -117,8 +132,8 @@ export default function OrderDetailDrawer({
   const fetchUserDetails = async (userId: string) => {
     setLoadingUser(true);
     try {
-      const res = await api.get('/api/user/get_by_id', { params: { user_id: userId } });
-      setUserData(res.data?.data || null);
+      const res = await userService.getDetail(Number(userId));
+      setUserData(res?.data || null);
     } catch {
       setUserData(null);
     } finally {
@@ -147,9 +162,9 @@ export default function OrderDetailDrawer({
       await Promise.all(
         Array.from(new Set(qrIds)).map(async (qrId) => {
           try {
-            const res = await api.get('/api/vas/payment-qr/get', { params: { qr_id: qrId } });
-            if (res.data?.data) {
-              detailMap[qrId] = res.data.data;
+            const res = await paymentService.getQrDetail(qrId);
+            if (res?.data) {
+              detailMap[qrId] = res.data;
             }
           } catch {
             // ignore
@@ -281,9 +296,9 @@ export default function OrderDetailDrawer({
                 [ 编辑 ]
               </button>
             )}
-            {isPending && onCancel && (
+            {isPending && (onCancel || onCancelOrder) && (
               <button
-                onClick={() => onCancel(order.id)}
+                onClick={() => handleCancelClick(String(order.id))}
                 className="px-2.5 py-1 bg-rose-100 hover:bg-rose-200 text-rose-800 border border-black text-xs font-bold shadow-[1px_1px_0px_#000] active:translate-x-0.5 active:translate-y-0.5 uppercase"
               >
                 [ 取消 ]

+ 14 - 15
src/components/admin/orders/OrderDetailModal.tsx

@@ -1,10 +1,10 @@
 'use client';
 
 import { useState, useEffect, useMemo } from 'react';
-import api from '@/lib/api'; 
 import { X, CreditCard, User, FileText, Package, Loader2, Phone, Mail } from 'lucide-react';
 import LocalTime from '@/components/common/LocalTime';
 import { OrderDetail, PaymentRecord, PaymentQrDetail, UserDetail, OrderEvent } from '@/types';
+import { paymentService, userService, orderService } from '@/lib/services';
 
 interface OrderDetailModalProps {
   isOpen: boolean;
@@ -23,24 +23,23 @@ const FIELD_DISPLAY_ORDER = [
 ];
 
 export default function OrderDetailModal({ isOpen, onClose, order }: OrderDetailModalProps) {
+  const [activeTab, setActiveTab] = useState<'info' | 'payments' | 'user' | 'events'>('info');
   const [paymentList, setPaymentList] = useState<PaymentRecord[]>([]);
   const [loadingPayments, setLoadingPayments] = useState(false);
   const [userData, setUserData] = useState<UserDetail | null>(null);
   const [loadingUser, setLoadingUser] = useState(false);
-  const [qrDetails, setQrDetails] = useState<Record<number, PaymentQrDetail>>({});
-  const [loadingQrDetails, setLoadingQrDetails] = useState(false);
   const [events, setEvents] = useState<OrderEvent[]>([]);
   const [loadingEvents, setLoadingEvents] = useState(false);
+  const [qrDetails, setQrDetails] = useState<Record<number, PaymentQrDetail>>({});
+  const [loadingQrDetails, setLoadingQrDetails] = useState(false);
 
   useEffect(() => {
-    if (isOpen && order?.id) {
+    if (isOpen && order) {
       fetchPayments(order.id);
-      fetchEvents(order.id);
       if (order.user_id) {
         fetchUserDetails(order.user_id);
-      } else {
-        setUserData(null);
       }
+      fetchEvents(order.id);
     } else {
       setPaymentList([]);
       setEvents([]);
@@ -51,8 +50,8 @@ export default function OrderDetailModal({ isOpen, onClose, order }: OrderDetail
   const fetchPayments = async (orderId: string) => {
     setLoadingPayments(true);
     try {
-      const res = await api.get('/api/vas/payment/list_by_order', { params: { order_id: orderId } });
-      const list = Array.isArray(res.data.data) ? res.data.data : [];
+      const res = await paymentService.listByOrder(Number(orderId));
+      const list = Array.isArray(res?.data) ? res.data : [];
       setPaymentList(list);
     } catch {
       if (order?.payments) setPaymentList(order.payments);
@@ -64,8 +63,8 @@ export default function OrderDetailModal({ isOpen, onClose, order }: OrderDetail
   const fetchUserDetails = async (userId: string) => {
     setLoadingUser(true);
     try {
-      const res = await api.get('/api/user/detail', { params: { user_id: userId } });
-      if (res.data.data) setUserData(res.data.data);
+      const res = await userService.getDetail(Number(userId));
+      if (res?.data) setUserData(res.data);
     } catch {
       // ignore
     } finally {
@@ -76,8 +75,8 @@ export default function OrderDetailModal({ isOpen, onClose, order }: OrderDetail
   const fetchEvents = async (orderId: string) => {
     setLoadingEvents(true);
     try {
-      const res = await api.get('/api/order/events', { params: { order_id: orderId } });
-      const list = Array.isArray(res.data.data) ? res.data.data : [];
+      const res = await orderService.getEvents(Number(orderId));
+      const list = Array.isArray(res?.data) ? res.data : [];
       setEvents(list);
     } catch {
       setEvents([]);
@@ -112,8 +111,8 @@ export default function OrderDetailModal({ isOpen, onClose, order }: OrderDetail
         const results = await Promise.all(
           qrIds.map(async (id) => {
             try {
-              const res = await api.get(`/api/vas/payment_qr/get`, { params: { id } });
-              return { id, data: res.data?.data as PaymentQrDetail };
+              const res = await paymentService.getQrDetail(id);
+              return { id, data: (res?.data || res) as PaymentQrDetail };
             } catch {
               return { id, data: null };
             }

+ 5 - 22
src/components/admin/orders/OrderPaymentModal.tsx

@@ -4,7 +4,7 @@ import { useState, useEffect } from 'react';
 import { X, CreditCard, CheckCircle, AlertCircle, Loader2, Ban, ShieldAlert, Check } from 'lucide-react';
 import { toast } from 'react-hot-toast';
 import { retroConfirm } from '@/lib/dialog';
-import api from '@/lib/api';
+import { paymentService } from '@/lib/services';
 import LocalTime from '@/components/common/LocalTime';
 import { getPaymentProviderIcon } from '@/components/admin/payments/paymentIcons';
 import { OrderDetail, PaymentRecord } from '@/types';
@@ -35,10 +35,8 @@ export default function OrderPaymentModal({
   const fetchPayments = async () => {
     setLoading(true);
     try {
-      const res = await api.get('/api/vas/payment/list_by_order', {
-        params: { order_id: order?.id },
-      });
-      const list = Array.isArray(res.data?.data) ? res.data.data : Array.isArray(res.data) ? res.data : [];
+      const res = await paymentService.listByOrder(Number(order?.id));
+      const list = Array.isArray(res?.data) ? res.data : Array.isArray(res) ? res : [];
       setPayments(list);
     } catch {
       setPayments([]);
@@ -60,16 +58,7 @@ export default function OrderPaymentModal({
 
     setProcessingId(payment.id);
     try {
-      await api.post(
-        '/api/vas/payment/admin_update_status',
-        {
-          status: 'succeeded',
-          remark: 'Admin manually confirmed via Order Console',
-        },
-        {
-          params: { payment_id: payment.id },
-        }
-      );
+      await paymentService.updatePaymentStatus(payment.id, 'succeeded');
 
       toast.success('操作成功:支付单已核销入账,订单状态将同步更新。');
       onSuccess();
@@ -92,13 +81,7 @@ export default function OrderPaymentModal({
 
     setProcessingId(payment.id);
     try {
-      await api.post(
-        '/api/vas/payment/admin_update_status',
-        { status: 'failed' },
-        {
-          params: { payment_id: payment.id },
-        }
-      );
+      await paymentService.updatePaymentStatus(payment.id, 'failed');
       toast.success('支付单已标记为废弃');
       fetchPayments();
     } catch {

+ 11 - 12
src/components/admin/orders/OrderPriceAdjustModal.tsx

@@ -3,7 +3,7 @@
 import { useState, useEffect } from 'react';
 import { X, Loader2, Save, ArrowRight } from 'lucide-react';
 import { toast } from 'react-hot-toast';
-import api from '@/lib/api';
+import { orderService } from '@/lib/services';
 import { OrderDetail } from '@/types';
 
 interface OrderPriceAdjustModalProps {
@@ -27,13 +27,16 @@ export default function OrderPriceAdjustModal({
 
   useEffect(() => {
     if (isOpen) {
-      setFormData({ adjustment_delta: '', reason: '管理员手动调价' });
+      setFormData({
+        adjustment_delta: '',
+        reason: '管理员手动调价',
+      });
     }
-  }, [isOpen]);
+  }, [isOpen, order]);
 
   if (!isOpen || !order) return null;
 
-  const baseAmount = order.base_amount || 0;
+  const baseAmount = order ? (order.base_amount ?? order.total_amount ?? order.amount ?? 0) : 0;
   const currency = order.base_currency || 'CNY';
   const symbol = currency === 'CNY' ? '¥' : currency === 'USD' ? '$' : `${currency} `;
 
@@ -56,14 +59,10 @@ export default function OrderPriceAdjustModal({
 
     setLoading(true);
     try {
-      await api.post(
-        '/api/vas/order/adjust-price',
-        {
-          adjustment_delta: deltaCents,
-          reason: formData.reason,
-        },
-        { params: { order_id: order.id } }
-      );
+      await orderService.adjustPrice(Number(order.id), {
+        adjustment_delta: deltaCents,
+        reason: formData.reason,
+      });
 
       toast.success('价格调整成功');
       onSuccess();

+ 6 - 4
src/components/admin/orders/ProductSearchSelector.tsx

@@ -3,7 +3,7 @@
 import { useState, useEffect } from 'react';
 import { Search, Loader2, CheckCircle, Package } from 'lucide-react';
 import { useDebounce } from 'use-debounce';
-import api from '@/lib/api';
+import { productService } from '@/lib/services';
 
 interface ProductSearchSelectorProps {
   selectedProduct: any | null;
@@ -28,10 +28,12 @@ export default function ProductSearchSelector({
     async function searchProducts() {
       setIsSearchingProduct(true);
       try {
-        const res = await api.get('/api/vas/product/list', {
-          params: { keyword: debouncedKeyword, page: 1, size: 20 },
+        const res = await productService.listAll({
+          keyword: debouncedKeyword,
+          page: 1,
+          size: 20,
         });
-        const data = res.data.data;
+        const data = res?.data;
         if (Array.isArray(data)) setProductList(data);
         else if (data?.items) setProductList(data.items);
       } catch (e) {

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

@@ -1,10 +1,10 @@
 'use client';
 
 import { useState, useEffect } from 'react';
-import api from '@/lib/api';
 import { X, Save, RefreshCw, Loader2, ArrowRight, AlertTriangle, Lock } from 'lucide-react';
 import { toast } from 'react-hot-toast';
 import { RateConfig } from '@/types';
+import { configService } from '@/lib/services';
 
 interface ExchangeRateModalProps {
   isOpen: boolean;
@@ -36,8 +36,8 @@ export default function ExchangeRateModal({ isOpen, onClose }: ExchangeRateModal
   const fetchRates = async () => {
     setLoading(true);
     try {
-      const res = await api.get('/api/dynamic-configurations/key/EXCHANGE_RATES');
-      const val = res.data.data?.config_value;
+      const res = await configService.getByKey('EXCHANGE_RATES');
+      const val = res?.data?.config_value;
       if (val && typeof val === 'object') {
         setConfig(val);
       } else if (typeof val === 'string') {
@@ -85,14 +85,14 @@ export default function ExchangeRateModal({ isOpen, onClose }: ExchangeRateModal
     };
     try {
       try {
-        await api.put('/api/dynamic-configurations/key/EXCHANGE_RATES', {
+        await configService.updateByKey('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);
+          await configService.create(payload);
         } else {
           throw err;
         }

+ 6 - 8
src/components/admin/payments/QrManager.tsx

@@ -1,7 +1,6 @@
 'use client';
 
 import { useState, useEffect, useRef } from 'react';
-import api from '@/lib/api';
 import { 
   Loader2, 
   Trash2, 
@@ -16,6 +15,7 @@ import LocalTime from '@/components/common/LocalTime';
 import { toast } from 'react-hot-toast';
 import { retroConfirm } from '@/lib/dialog';
 import { PaymentQr } from '@/types';
+import { paymentService } from '@/lib/services';
 
 interface QrManagerProps {
   providerId: number | null; 
@@ -52,10 +52,8 @@ export default function QrManager({ providerId, providerName, isOpen, onClose }:
   const fetchQrs = async () => {
     setLoading(true);
     try {
-      const res = await api.get('/api/vas/payment_qr/list_by_provider', { 
-        params: { provider_id: providerId } 
-      });
-      const list = Array.isArray(res.data.data) ? res.data.data : [];
+      const res = await paymentService.listQrsByProvider(Number(providerId));
+      const list = Array.isArray(res?.data) ? res.data : [];
       setQrs(list);
     } catch {
       setQrs([]);
@@ -82,7 +80,7 @@ export default function QrManager({ providerId, providerName, isOpen, onClose }:
     if (!form.qr_code) return toast.error("请上传静态收款二维码图片");
     setSubmitting(true);
     try {
-      await api.post('/api/vas/payment_qr/create', {
+      await paymentService.createQr({
         provider: providerName,
         ...form,
         is_active: Number(form.is_active),
@@ -109,7 +107,7 @@ export default function QrManager({ providerId, providerName, isOpen, onClose }:
     });
     if (!ok) return;
     try {
-      await api.delete('/api/vas/payment_qr/delete', { params: { id } });
+      await paymentService.deleteQr(id);
       toast.success('收款码已成功删除');
       fetchQrs();
     } catch {
@@ -120,7 +118,7 @@ export default function QrManager({ providerId, providerName, isOpen, onClose }:
   const handleToggleActive = async (qr: PaymentQr) => {
     setTogglingId(qr.id);
     try {
-      await api.post('/api/vas/payment_qr/set_enable', { is_active: !qr.is_active }, { params: { id: qr.id } });
+      await paymentService.setQrEnable(qr.id, !qr.is_active);
       toast.success(qr.is_active ? '已停用收款码' : '已启用收款码');
       fetchQrs();
     } catch {

+ 29 - 17
src/components/admin/products/ProductDetailDrawer.tsx

@@ -23,36 +23,50 @@ import {
   Calendar,
   Layers,
   Sparkles,
-  Info
+  Loader2,
+  AlertCircle
 } from 'lucide-react';
 import { toast } from 'react-hot-toast';
 import LocalTime from '@/components/common/LocalTime';
 import JsonEditor from '@/components/common/JsonEditor';
-import { Product, ProductRouting, SchemaItem } from '@/types';
-import api from '@/lib/api';
+import { Product, SchemaItem, ProductRouting } from '@/types';
+import { productService } from '@/lib/services';
 
 interface ProductDetailDrawerProps {
   isOpen: boolean;
   onClose: () => void;
   product: Product | null;
-  schemas: SchemaItem[];
+  schemas?: SchemaItem[];
   onEdit: (product: Product) => void;
-  onManageRouting: (product: Product) => void;
-  onManageSchemas: () => void;
   onToggleStatus: (product: Product) => Promise<void>;
+  onOpenRouting?: (product: Product) => void;
+  onManageRouting?: (product: Product) => void;
+  onOpenSchemaManager?: () => void;
+  onManageSchemas?: () => void;
 }
 
 export default function ProductDetailDrawer({
   isOpen,
   onClose,
   product,
-  schemas,
+  schemas = [],
   onEdit,
+  onToggleStatus,
+  onOpenRouting,
   onManageRouting,
+  onOpenSchemaManager,
   onManageSchemas,
-  onToggleStatus,
 }: ProductDetailDrawerProps) {
-  const [activeTab, setActiveTab] = useState<'overview' | 'schema' | 'routing'>('overview');
+  const handleRoutingClick = (p: Product) => {
+    if (onManageRouting) onManageRouting(p);
+    else if (onOpenRouting) onOpenRouting(p);
+  };
+
+  const handleSchemaClick = () => {
+    if (onManageSchemas) onManageSchemas();
+    else if (onOpenSchemaManager) onOpenSchemaManager();
+  };
+  const [activeTab, setActiveTab] = useState<'overview' | 'routing' | 'schema' | 'raw'>('overview');
   const [routings, setRoutings] = useState<ProductRouting[]>([]);
   const [loadingRoutings, setLoadingRoutings] = useState(false);
   const [schemaDetail, setSchemaDetail] = useState<any | null>(null);
@@ -75,10 +89,8 @@ export default function ProductDetailDrawer({
   const fetchRoutings = async (productId: number) => {
     setLoadingRoutings(true);
     try {
-      const res = await api.get('/api/vas/product_routing/list_by_product', {
-        params: { product_id: productId },
-      });
-      setRoutings(Array.isArray(res.data?.data) ? res.data.data : []);
+      const res = await productService.listRoutings(productId);
+      setRoutings(Array.isArray(res?.data) ? res.data : []);
     } catch {
       setRoutings([]);
     } finally {
@@ -89,8 +101,8 @@ export default function ProductDetailDrawer({
   const fetchSchemaDetail = async (schemaId: number) => {
     setLoadingSchema(true);
     try {
-      const res = await api.get('/api/vas/schema/get', { params: { id: schemaId } });
-      setSchemaDetail(res.data?.data || null);
+      const res = await productService.getSchemaDetail(schemaId);
+      setSchemaDetail(res?.data || null);
     } catch {
       setSchemaDetail(null);
     } finally {
@@ -278,7 +290,7 @@ export default function ProductDetailDrawer({
                       [ 02 // 动态表单 SCHEMA 绑定 ]
                     </span>
                     <button
-                      onClick={onManageSchemas}
+                      onClick={handleSchemaClick}
                       className="text-[10px] font-bold text-black hover:underline uppercase"
                     >
                       [ SCHEMA 库 → ]
@@ -323,7 +335,7 @@ export default function ProductDetailDrawer({
                       [ 03 // 自动化路由策略 ({routings.length}) ]
                     </span>
                     <button
-                      onClick={() => onManageRouting(product)}
+                      onClick={() => handleRoutingClick(product)}
                       className="text-[10px] font-bold text-black hover:underline uppercase"
                     >
                       [ 管理路由 → ]

+ 5 - 5
src/components/admin/products/ProductModal.tsx

@@ -1,7 +1,6 @@
 'use client';
 
 import { useState, useEffect, useMemo } from 'react';
-import api from '@/lib/api';
 import {
   Loader2,
   X,
@@ -20,6 +19,7 @@ import {
 } from 'lucide-react';
 import { SchemaItem } from '@/types';
 import { toast } from 'react-hot-toast';
+import { productService } from '@/lib/services';
 
 interface ProductModalProps {
   isOpen: boolean;
@@ -88,8 +88,8 @@ export default function ProductModal({
 
   const fetchSchemas = async () => {
     try {
-      const res = await api.get('/api/vas/schema/list');
-      const data = res.data?.data;
+      const res = await productService.listSchemas();
+      const data = res?.data;
       setSchemas(Array.isArray(data) ? data : []);
     } catch {
       setSchemas([]);
@@ -143,8 +143,8 @@ export default function ProductModal({
     }
     setLoadingSchemaDetail(true);
     try {
-      const res = await api.get(`/api/vas/schema/get`, { params: { id: schemaId } });
-      setSelectedSchemaDetail(res.data?.data || null);
+      const res = await productService.getSchemaDetail(schemaId);
+      setSelectedSchemaDetail(res?.data || null);
     } catch {
       setSelectedSchemaDetail(null);
     } finally {

+ 19 - 23
src/components/admin/products/RoutingManager.tsx

@@ -1,7 +1,7 @@
 'use client';
 
 import { useState, useEffect, useMemo } from 'react';
-import api from '@/lib/api';
+import { productService } from '@/lib/services';
 import {
   Loader2,
   Trash2,
@@ -70,8 +70,8 @@ const ROUTING_PRESETS = [
     priority: 10,
     config: JSON.stringify(
       {
-        polling_rate_ms: 5000,
-        enable_captcha_solver: true,
+        concurrency: 2,
+        headless: true,
       },
       null,
       2
@@ -91,21 +91,23 @@ export default function RoutingManager({
   const [deletingId, setDeletingId] = useState<number | null>(null);
 
   const [editingId, setEditingId] = useState<number | null>(null);
-
   const [form, setForm] = useState({
     routing_key: '',
     script_version: '',
     priority: 10,
-    config: '{}',
+    config: '{\n  "max_concurrency": 2\n}',
   });
 
-  const [mobileTab, setMobileTab] = useState<'editor' | 'list'>('list');
   const [copiedId, setCopiedId] = useState<number | null>(null);
+  const [mobileTab, setMobileTab] = useState<'list' | 'editor'>('list');
 
   useEffect(() => {
     if (isOpen && productId) {
       fetchRoutings();
       handleResetForm();
+      setMobileTab('list');
+    } else {
+      setRoutings([]);
     }
   }, [isOpen, productId]);
 
@@ -113,10 +115,8 @@ export default function RoutingManager({
     if (!productId) return;
     setLoading(true);
     try {
-      const res = await api.get('/api/vas/product_routing/list_by_product', {
-        params: { product_id: productId },
-      });
-      const list = Array.isArray(res.data?.data) ? res.data.data : [];
+      const res = await productService.listRoutings(productId);
+      const list = Array.isArray(res?.data) ? res.data : [];
       setRoutings(list);
     } catch {
       setRoutings([]);
@@ -194,20 +194,16 @@ export default function RoutingManager({
     setSubmitting(true);
     try {
       if (editingId) {
-        await api.post(
-          '/api/vas/product_routing/update',
-          {
-            product_id: productId,
-            routing_key: form.routing_key,
-            script_version: form.script_version || null,
-            priority: Number(form.priority) || 0,
-            config: parsedConfig,
-          },
-          { params: { id: editingId } }
-        );
+        await productService.updateRouting(editingId, {
+          product_id: productId,
+          routing_key: form.routing_key,
+          script_version: form.script_version || null,
+          priority: Number(form.priority) || 0,
+          config: parsedConfig,
+        });
         toast.success(`路由规则 #${editingId} 更新成功`);
       } else {
-        await api.post('/api/vas/product_routing/create', {
+        await productService.createRouting({
           product_id: productId,
           routing_key: form.routing_key,
           script_version: form.script_version || null,
@@ -237,7 +233,7 @@ export default function RoutingManager({
     if (!ok) return;
     setDeletingId(id);
     try {
-      await api.delete('/api/vas/product_routing/delete', { params: { id } });
+      await productService.deleteRouting(id);
       toast.success('路由规则已删除');
       if (editingId === id) handleResetForm();
       fetchRoutings();

+ 145 - 59
src/components/admin/products/SchemaManager.tsx

@@ -1,7 +1,6 @@
 'use client';
 
 import { useState, useEffect, useMemo } from 'react';
-import api from '@/lib/api';
 import {
   Loader2,
   Plus,
@@ -24,60 +23,120 @@ import {
 import Editor from '@monaco-editor/react';
 import { toast } from 'react-hot-toast';
 import { retroConfirm } from '@/lib/dialog';
-import JsonEditor from '@/components/common/JsonEditor';
 import { SchemaItem } from '@/types';
-
-interface SchemaManagerProps {
-  isOpen: boolean;
-  onClose: () => void;
-}
+import DynamicOrderSchemaForm from '@/components/admin/orders/DynamicOrderSchemaForm';
+import JsonEditor from '@/components/common/JsonEditor';
+import { productService } from '@/lib/services';
 
 const SCHEMA_TEMPLATES = [
   {
-    name: '标准签证申请人材料模板',
-    description: '包含姓名、护照号、出生日期、签证中心等常用字段',
+    name: '申根签证通用表单 (完整版)',
+    description: '标准申根国签证基础申请表,包含护照、联系方式、出行目的等标准字段。',
     schema_json: JSON.stringify(
       {
+        title: '申根签证申请基础资料',
+        description: '请如实填写申请人的护照与基本身份信息,带 * 为必填项。',
         type: 'object',
-        title: '签证申请人基础资料',
-        description: '请准确填写申请人护照信息与预约需求',
-        required: ['applicant_name', 'passport_number', 'nationality', 'visa_center'],
+        required: [
+          'surname',
+          'name',
+          'birthday',
+          'passport_no',
+          'passport_expire_date',
+          'phone',
+          'email',
+        ],
+        'ui:order': [
+          'surname',
+          'name',
+          'birthday',
+          'nationality',
+          'passport_no',
+          'passport_expire_date',
+          'phone_code',
+          'phone',
+          'email',
+          'visa_center',
+          'category',
+          'subcategory',
+          'notes',
+        ],
         properties: {
-          applicant_name: {
+          surname: {
             type: 'string',
-            title: '申请人全名 (拼音)',
-            placeholder: '如: ZHANG SAN',
+            title: '姓氏 (Surname / Pinyin)',
+            description: '例如: WANG',
+            'x-order': 1,
           },
-          passport_number: {
+          name: {
             type: 'string',
-            title: '护照号码',
-            placeholder: '如: E12345678',
+            title: '名字 (Given Name / Pinyin)',
+            description: '例如: XIAOMING',
+            'x-order': 2,
+          },
+          birthday: {
+            type: 'string',
+            title: '出生日期',
+            format: 'date',
+            'x-order': 3,
           },
           nationality: {
             type: 'string',
             title: '国籍',
-            default: 'China',
-            enum: ['China', 'Hong Kong', 'Taiwan', 'Other'],
+            default: 'CHN',
+            'x-order': 4,
+          },
+          passport_no: {
+            type: 'string',
+            title: '护照号码',
+            description: '如: E12345678',
+            'x-order': 5,
           },
-          birth_date: {
+          passport_expire_date: {
             type: 'string',
+            title: '护照有效期至',
             format: 'date',
-            title: '出生日期',
+            'x-order': 6,
+          },
+          phone_code: {
+            type: 'string',
+            title: '国家区号',
+            default: '+86',
+            'x-order': 7,
+          },
+          phone: {
+            type: 'string',
+            title: '联系手机号',
+            'x-order': 8,
+          },
+          email: {
+            type: 'string',
+            title: '电子邮箱 (用于接收预约确认信)',
+            format: 'email',
+            'x-order': 9,
           },
           visa_center: {
             type: 'string',
             title: '递签中心',
             enum: ['Beijing', 'Shanghai', 'Guangzhou', 'Chengdu', 'Wuhan', 'Shenyang'],
+            'x-order': 10,
           },
-          expected_date_start: {
+          category: {
             type: 'string',
-            format: 'date',
-            title: '期望最早出发/预约日期',
+            title: '大类 (Category)',
+            default: 'Short Stay',
+            'x-order': 11,
+          },
+          subcategory: {
+            type: 'string',
+            title: '子类别 (Subcategory)',
+            default: 'Tourism',
+            'x-order': 12,
           },
-          remarks: {
+          notes: {
             type: 'string',
-            title: '备注说明 / 特殊诉求',
-            placeholder: '如有同行人或特殊加急需求可填写',
+            title: '特殊备注 / 出行计划简要',
+            'x-order': 13,
           },
         },
       },
@@ -86,23 +145,49 @@ const SCHEMA_TEMPLATES = [
     ),
   },
   {
-    name: '极简预约信息模板 (仅核心两项)',
-    description: '仅收集护照号和目标城市,适合快捷抢单',
+    name: '抢号监控简化表单 (仅预约关键信息)',
+    description: '适用于极速抢位或自动监控,仅收集账号密码及中心代码。',
     schema_json: JSON.stringify(
       {
+        title: '自动化抢位关键配置',
         type: 'object',
-        title: '极速抢单关键参数',
-        required: ['passport_number', 'city'],
+        required: ['target_center', 'preferred_date_start', 'preferred_date_end'],
+        'ui:order': [
+          'target_center',
+          'preferred_date_start',
+          'preferred_date_end',
+          'vfs_login_email',
+          'auto_pay',
+        ],
         properties: {
-          passport_number: {
+          target_center: {
             type: 'string',
-            title: '护照号码',
-            placeholder: 'E12345678',
+            title: '目标签证中心代码',
+            enum: ['FRA-SHA', 'FRA-BJS', 'ITA-SHA', 'ESP-CAN'],
+            'x-order': 1,
           },
-          city: {
+          preferred_date_start: {
             type: 'string',
-            title: '意向递签城市',
-            placeholder: 'Paris / London / Rome',
+            title: '期望预约开始日期',
+            format: 'date',
+            'x-order': 2,
+          },
+          preferred_date_end: {
+            type: 'string',
+            title: '期望预约截止日期',
+            format: 'date',
+            'x-order': 3,
+          },
+          vfs_login_email: {
+            type: 'string',
+            title: '官方申请账号 (选填)',
+            'x-order': 4,
+          },
+          auto_pay: {
+            type: 'boolean',
+            title: '刷出名额后是否自动锁定 (默认是)',
+            default: true,
+            'x-order': 5,
           },
         },
       },
@@ -112,19 +197,24 @@ const SCHEMA_TEMPLATES = [
   },
 ];
 
+interface SchemaManagerProps {
+  isOpen: boolean;
+  onClose: () => void;
+}
+
 export default function SchemaManager({ isOpen, onClose }: SchemaManagerProps) {
   const [schemas, setSchemas] = useState<SchemaItem[]>([]);
   const [loading, setLoading] = useState(false);
   const [saving, setSaving] = useState(false);
+  const [keyword, setKeyword] = useState('');
 
   const [editingId, setEditingId] = useState<number | null>(null);
   const [formData, setFormData] = useState({
     name: '',
     description: '',
-    schema_json: '{}',
+    schema_json: SCHEMA_TEMPLATES[0].schema_json,
   });
 
-  const [searchKey, setSearchKey] = useState('');
   const [viewMode, setViewMode] = useState<'split' | 'code' | 'preview'>('split');
   const [previewTab, setPreviewTab] = useState<'form' | 'tree' | 'raw'>('form');
   const [mobileTab, setMobileTab] = useState<'list' | 'editor'>('list');
@@ -140,8 +230,8 @@ export default function SchemaManager({ isOpen, onClose }: SchemaManagerProps) {
   const fetchSchemas = async () => {
     setLoading(true);
     try {
-      const res = await api.get('/api/vas/schema/list');
-      const list = Array.isArray(res.data?.data) ? res.data.data : [];
+      const res = await productService.listSchemas();
+      const list = Array.isArray(res?.data) ? res.data : [];
       setSchemas(list);
     } catch {
       setSchemas([]);
@@ -240,23 +330,19 @@ export default function SchemaManager({ isOpen, onClose }: SchemaManagerProps) {
     setSaving(true);
     try {
       if (editingId) {
-        await api.post(
-          '/api/vas/schema/update',
-          {
-            name: formData.name,
-            description: formData.description,
-            schema_json: parsedSchema,
-          },
-          { params: { id: editingId } }
-        );
+        await productService.updateSchema(editingId, {
+          name: formData.name,
+          description: formData.description,
+          schema_json: parsedSchema,
+        });
         toast.success(`Schema #${editingId} 更新成功`);
       } else {
-        const res = await api.post('/api/vas/schema/create', {
+        const res = await productService.createSchema({
           name: formData.name,
           description: formData.description,
           schema_json: parsedSchema,
         });
-        const createdId = res.data?.data?.id;
+        const createdId = res?.data?.id || res?.id;
         toast.success('新建表单 Schema 成功');
         if (createdId) setEditingId(createdId);
       }
@@ -277,7 +363,7 @@ export default function SchemaManager({ isOpen, onClose }: SchemaManagerProps) {
     });
     if (!ok) return;
     try {
-      await api.delete('/api/vas/schema/delete', { params: { id } });
+      await productService.deleteSchema(id);
       toast.success('Schema 已删除');
       if (editingId === id) handleCreateNew();
       fetchSchemas();
@@ -307,15 +393,15 @@ export default function SchemaManager({ isOpen, onClose }: SchemaManagerProps) {
   }, [formData.schema_json, formData.name, formData.description]);
 
   const filteredSchemas = useMemo(() => {
-    if (!searchKey.trim()) return schemas;
-    const lower = searchKey.trim().toLowerCase();
+    if (!keyword.trim()) return schemas;
+    const lower = keyword.trim().toLowerCase();
     return schemas.filter(
       (s) =>
         s.name.toLowerCase().includes(lower) ||
         (s.description || '').toLowerCase().includes(lower) ||
         String(s.id).includes(lower)
     );
-  }, [schemas, searchKey]);
+  }, [schemas, keyword]);
 
   if (!isOpen) return null;
 
@@ -391,8 +477,8 @@ export default function SchemaManager({ isOpen, onClose }: SchemaManagerProps) {
                 type="text"
                 placeholder="搜索 Schema 名称 / ID..."
                 className="w-full pl-8 pr-3 py-1.5 border-2 border-black bg-white text-xs font-mono outline-none shadow-[2px_2px_0px_#000] text-black"
-                value={searchKey}
-                onChange={(e) => setSearchKey(e.target.value)}
+                value={keyword}
+                onChange={(e) => setKeyword(e.target.value)}
               />
               <Search size={13} className="absolute left-2.5 top-2 text-black pointer-events-none" />
             </div>

+ 6 - 6
src/components/admin/proxies/ProxyAddModal.tsx

@@ -3,7 +3,7 @@
 import { useState, useEffect } from 'react';
 import { X, Plus, FileText, Sparkles, Check, AlertCircle } from 'lucide-react';
 import { toast } from 'react-hot-toast';
-import api from '@/lib/api';
+import { proxyService } from '@/lib/services';
 import { ProxyStatus } from '@/types';
 
 interface ProxyAddModalProps {
@@ -154,7 +154,7 @@ export default function ProxyAddModal({
 
     setSubmitting(true);
     try {
-      const res = await api.post('/api/proxy/create', {
+      const res = await proxyService.create({
         pool_name: singleForm.pool_name.trim(),
         proto: singleForm.proto,
         ip: singleForm.ip.trim(),
@@ -164,12 +164,12 @@ export default function ProxyAddModal({
         status: singleForm.status,
       });
 
-      if (res.data?.code === 0 || res.status === 200) {
+      if (res?.code === 0 || res?.data) {
         toast.success(`代理 ${singleForm.ip}:${singleForm.port} 添加成功`);
         onSuccess();
         onClose();
       } else {
-        toast.error(res.data?.msg || '添加失败');
+        toast.error(res?.msg || '添加失败');
       }
     } catch (e: any) {
       toast.error('添加失败: ' + (e.response?.data?.msg || e.message || '网络错误'));
@@ -191,7 +191,7 @@ export default function ProxyAddModal({
     try {
       for (const item of parsedBatchList) {
         try {
-          const res = await api.post('/api/proxy/create', {
+          const res = await proxyService.create({
             pool_name: item.pool_name,
             proto: item.proto,
             ip: item.ip,
@@ -200,7 +200,7 @@ export default function ProxyAddModal({
             password: item.password || undefined,
             status: item.status,
           });
-          if (res.data?.code === 0 || res.status === 200) {
+          if (res?.code === 0 || res?.data) {
             successCount++;
           } else {
             failCount++;

+ 10 - 11
src/components/admin/proxies/ProxyEditModal.tsx

@@ -3,7 +3,7 @@
 import { useState, useEffect } from 'react';
 import { X, Pencil, Eye, EyeOff } from 'lucide-react';
 import { toast } from 'react-hot-toast';
-import api from '@/lib/api';
+import { proxyService } from '@/lib/services';
 import LocalTime from '@/components/common/LocalTime';
 import { ProxyItem, ProxyStatus } from '@/types';
 
@@ -52,7 +52,7 @@ export default function ProxyEditModal({
     pool_name: '',
     proto: 'http',
     ip: '',
-    port: 8080,
+    port: '',
     username: '',
     password: '',
     status: 'active' as ProxyStatus,
@@ -67,7 +67,7 @@ export default function ProxyEditModal({
         pool_name: proxy.pool_name,
         proto: proxy.proto || 'http',
         ip: proxy.ip,
-        port: proxy.port,
+        port: String(proxy.port),
         username: proxy.username || '',
         password: proxy.password || '',
         status: proxy.status || 'active',
@@ -81,24 +81,23 @@ export default function ProxyEditModal({
 
   const handleSubmit = async () => {
     if (!form.pool_name.trim()) {
-      toast.error('请填写代理池名称');
+      toast.error('请填写所属代理池 (Pool Name)');
       return;
     }
     if (!form.ip.trim()) {
       toast.error('请填写代理 IP 地址');
       return;
     }
-    if (!form.port || form.port <= 0 || form.port > 65535) {
+    if (!form.port || Number(form.port) <= 0 || Number(form.port) > 65535) {
       toast.error('端口号必须在 1-65535 之间');
       return;
     }
 
-    const nextUseTimeIso = toApiDateTime(form.next_use_time);
+    const nextUseTimeIso = toApiDateTime(form.next_use_time) || new Date().toISOString();
 
     setSubmitting(true);
     try {
-      const res = await api.post('/api/proxies/update', {
-        id: proxy.id,
+      const res = await proxyService.update(proxy.id, {
         pool_name: form.pool_name.trim(),
         proto: form.proto,
         ip: form.ip.trim(),
@@ -109,12 +108,12 @@ export default function ProxyEditModal({
         next_use_time: nextUseTimeIso,
       });
 
-      if (res.data?.code === 0 || res.status === 200) {
+      if (res?.code === 0 || res?.data) {
         toast.success(`代理 #${proxy.id} 更新成功`);
         onSuccess();
         onClose();
       } else {
-        toast.error(res.data?.msg || '修改失败');
+        toast.error(res?.msg || '修改失败');
       }
     } catch (e: any) {
       toast.error('修改失败: ' + (e.response?.data?.msg || e.message || '网络错误'));
@@ -213,7 +212,7 @@ export default function ProxyEditModal({
                 type="number"
                 className="w-full px-2 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono font-bold text-black outline-none shadow-[2px_2px_0px_#000]"
                 value={form.port}
-                onChange={(e) => setForm({ ...form, port: Number(e.target.value) })}
+                onChange={(e) => setForm({ ...form, port: e.target.value })}
               />
             </div>
           </div>

+ 10 - 10
src/components/admin/tasks/TaskTable.tsx

@@ -32,7 +32,7 @@ import {
   Code2,
 } from 'lucide-react';
 import LocalTime from '@/components/common/LocalTime';
-import api from '@/lib/api';
+import { taskService } from '@/lib/services';
 import { VasTask } from '@/types';
 
 interface TaskTableProps {
@@ -169,50 +169,50 @@ export default function TaskTable({
       if (messageChannel === 'sms') {
         const phone = getRecipientPhone(messageTask);
         const sender = getSmsSender(messageTask);
-        const res = await api.post('/api/vas/notification/send_sms', {
+        const res = await taskService.sendSms({
           task_id: messageTask.id,
           order_id: messageTask.order_id,
           to: phone,
           message: messageText,
           sender: sender,
         });
-        if (res.data.code === 0 || res.status === 200) {
+        if (res?.code === 0 || res?.status === 200) {
           setMessageResult('success');
           setMessageResultText('短信发送成功!');
         } else {
           setMessageResult('fail');
-          setMessageResultText(res.data.msg || '短信发送失败');
+          setMessageResultText(res?.msg || '短信发送失败');
         }
       } else if (messageChannel === 'whatsapp') {
         const phone = getRecipientPhone(messageTask);
-        const res = await api.post('/api/vas/notification/send_whatsapp', {
+        const res = await taskService.sendWhatsapp({
           task_id: messageTask.id,
           order_id: messageTask.order_id,
           to: phone,
           message: messageText,
         });
-        if (res.data.code === 0 || res.status === 200) {
+        if (res?.code === 0 || res?.status === 200) {
           setMessageResult('success');
           setMessageResultText('WhatsApp 消息发送成功!');
         } else {
           setMessageResult('fail');
-          setMessageResultText(res.data.msg || 'WhatsApp 消息发送失败');
+          setMessageResultText(res?.msg || 'WhatsApp 消息发送失败');
         }
       } else {
         const email = getRecipientEmail(messageTask);
-        const res = await api.post('/api/vas/notification/send_email', {
+        const res = await taskService.sendEmail({
           task_id: messageTask.id,
           order_id: messageTask.order_id,
           to: email,
           subject: `签证订单 #${messageTask.order_id} 状态通知`,
           content: messageText,
         });
-        if (res.data.code === 0 || res.status === 200) {
+        if (res?.code === 0 || res?.status === 200) {
           setMessageResult('success');
           setMessageResultText('邮件发送成功!');
         } else {
           setMessageResult('fail');
-          setMessageResultText(res.data.msg || '邮件发送失败');
+          setMessageResultText(res?.msg || '邮件发送失败');
         }
       }
     } catch (e: any) {

+ 6 - 12
src/components/admin/tickets/TicketDetailModal.tsx

@@ -1,12 +1,12 @@
 'use client';
 
 import { useState, useEffect, useRef } from 'react';
-import api from '@/lib/api';
 import { X, Send, User, Shield, Check, Ban, RefreshCw, Loader2, MessageSquare, Info, MessageCircle } from 'lucide-react';
 import LocalTime from '@/components/common/LocalTime';
 import { toast } from 'react-hot-toast';
 import TicketActionModal from '@/components/admin/TicketActionModal';
 import { AdminTicket, TicketMessage, ActionType } from '@/types';
+import { ticketService } from '@/lib/services';
 
 interface TicketDetailModalProps {
   isOpen: boolean;
@@ -30,11 +30,9 @@ export default function TicketDetailModal({ isOpen, onClose, ticket, onUpdate }:
     if (!ticket) return;
     setLoadingMsg(true);
     try {
-      const res = await api.get('/api/vas/tickets/fetch_message', {
-        params: { ticket_id: ticket.id, page: 1, size: 50 }
-      });
-      if (res.data.data?.items) {
-        const sorted = res.data.data.items.sort((a: any, b: any) => 
+      const res = await ticketService.fetchMessages(ticket.id, { page: 1, size: 50 });
+      if (res?.data?.items) {
+        const sorted = res.data.items.sort((a: any, b: any) => 
           new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
         );
         setMessages(sorted);
@@ -60,11 +58,9 @@ export default function TicketDetailModal({ isOpen, onClose, ticket, onUpdate }:
 
     setSending(true);
     try {
-      await api.post(`/api/vas/tickets/send_message`, {
+      await ticketService.sendMessage(ticket.id, {
         content: reply,
         attachments: null
-      }, {
-        params: { ticket_id: ticket.id }
       });
       setReply('');
       fetchMessages(); 
@@ -83,11 +79,9 @@ export default function TicketDetailModal({ isOpen, onClose, ticket, onUpdate }:
     };
     const status = statusMap[type] || type;
 
-    await api.post(`/api/vas/tickets/status`, {
+    await ticketService.updateStatus(ticketId, {
       status,
       comment
-    }, {
-      params: { ticket_id: ticketId }
     });
     
     toast.success("工单状态更新成功");

+ 12 - 9
src/components/dashboard/ChangePasswordModal.tsx

@@ -1,10 +1,10 @@
 'use client';
 
 import { useState, useEffect } from 'react';
-import api from '@/lib/api';
 import { X, Lock, Loader2, Save, Mail, KeyRound, Eye, EyeOff } from 'lucide-react';
 import { useLanguage } from '@/lib/i18n/LanguageContext';
 import MessageModal from '@/components/common/MessageModal';
+import { authService } from '@/lib/services';
 
 interface ChangePasswordModalProps {
   isOpen: boolean;
@@ -23,6 +23,7 @@ export default function ChangePasswordModal({ isOpen, onClose }: ChangePasswordM
   const [confirmPassword, setConfirmPassword] = useState('');
   
   const [showPassword, setShowPassword] = useState(false);
+  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
 
   const [msgModal, setMsgModal] = useState({
     isOpen: false,
@@ -32,11 +33,11 @@ export default function ChangePasswordModal({ isOpen, onClose }: ChangePasswordM
     onOk: null as (() => void) | null,
   });
 
-  const showMessage = (msg: string, type: 'info' | 'error' | 'success' = 'info', onOk?: () => void) => {
+  const showMessage = (message: string, type: 'info' | 'error' | 'success' = 'info', onOk?: () => void) => {
     setMsgModal({
       isOpen: true,
       title: type === 'error' ? t('common.error') : t('common.notice'),
-      message: msg,
+      message,
       type,
       onOk: onOk || null,
     });
@@ -54,8 +55,10 @@ export default function ChangePasswordModal({ isOpen, onClose }: ChangePasswordM
       if (userStr) {
         try {
           const user = JSON.parse(userStr);
-          setEmail(user.email || '');
-        } catch (e) {}
+          if (user.email) setEmail(user.email);
+        } catch (e) {
+          console.error(e);
+        }
       }
       setCode('');
       setNewPassword('');
@@ -64,9 +67,9 @@ export default function ChangePasswordModal({ isOpen, onClose }: ChangePasswordM
   }, [isOpen]);
 
   useEffect(() => {
-    let timer: NodeJS.Timeout;
+    let timer: any;
     if (countdown > 0) {
-      timer = setTimeout(() => setCountdown(c => c - 1), 1000);
+      timer = setTimeout(() => setCountdown(countdown - 1), 1000);
     }
     return () => clearTimeout(timer);
   }, [countdown]);
@@ -75,7 +78,7 @@ export default function ChangePasswordModal({ isOpen, onClose }: ChangePasswordM
     if (!email) return showMessage(t('settings.email_not_found') || '未检测到绑定邮箱', 'error');
     
     try {
-      await api.post('/api/auth/send-reset-code', { email });
+      await authService.sendResetCode(email);
       
       showMessage(`${t('settings.code_sent') || '验证码已发送至'} ${email}`, 'success');
       setCountdown(60);
@@ -94,7 +97,7 @@ export default function ChangePasswordModal({ isOpen, onClose }: ChangePasswordM
 
     setLoading(true);
     try {
-      await api.post('/api/auth/reset-password', { 
+      await authService.resetPassword({ 
         email, 
         code, 
         new_password: newPassword 

+ 6 - 8
src/components/dashboard/OrderList.tsx

@@ -2,12 +2,12 @@
 
 import { useEffect, useState } from 'react';
 import { useRouter } from 'next/navigation';
-import api from '@/lib/api';
 import { CreditCard, Loader2, AlertCircle, Package, Clock, Hash, Eye, Search, Sparkles, MessageSquare } from 'lucide-react';
 import Pagination from '@/components/common/Pagination';
 import { useLanguage } from '@/lib/i18n/LanguageContext';
 import LocalTime from '@/components/common/LocalTime';
 import { Order } from '@/types';
+import { orderService } from '@/lib/services';
 
 interface OrderListProps {
   onRequestTicket: (orderId: string) => void;
@@ -32,15 +32,13 @@ export default function OrderList({ onRequestTicket, onViewDetail }: OrderListPr
   const fetchOrders = async (targetPage: number) => {
     setLoading(true);
     try {
-      const res = await api.get('/api/vas/order/list_by_user', {
-        params: {
-          page: targetPage,
-          size: pageSize,
-          keyword: keyword
-        }
+      const res = await orderService.listByUser({
+        page: targetPage,
+        size: pageSize,
+        keyword: keyword
       });
 
-      const data = res.data.data || {};
+      const data = res?.data || {};
       
       if (Array.isArray(data)) {
         setOrders(data);

+ 4 - 10
src/components/dashboard/ProfileSettings.tsx

@@ -1,12 +1,12 @@
 'use client';
 
 import { useState, useEffect, useRef } from 'react';
-import api from '@/lib/api';
 import { getCurrentUser } from '@/lib/auth';
 import { Loader2, Save, Camera, User, Mail, Shield, Lock, ChevronRight, Edit2, Phone } from 'lucide-react';
 import ChangePasswordModal from '@/components/dashboard/ChangePasswordModal';
 import { useLanguage } from '@/lib/i18n/LanguageContext';
 import MessageModal from '@/components/common/MessageModal';
+import { userService } from '@/lib/services';
 
 export default function ProfileSettings() {
   const { t } = useLanguage();
@@ -71,14 +71,8 @@ export default function ProfileSettings() {
   };
 
   const uploadImage = async (file: File): Promise<string> => {
-    const formData = new FormData();
-    formData.append('file', file); 
-
-    const res = await api.post('/api/resource/upload_file', formData, {
-      headers: { 'Content-Type': 'multipart/form-data' },
-    });
-
-    const data = res.data.data;
+    const res = await userService.uploadFile(file);
+    const data = res?.data;
     if (typeof data === 'string') return data;
     if (data && data.url) return data.url;
     
@@ -110,7 +104,7 @@ export default function ProfileSettings() {
         avatar_url: finalAvatarUrl
       };
 
-      await api.post('/api/user/set_profiles', payload);
+      await userService.setProfiles(payload);
 
       const newUserInfo = { 
         ...user, 

+ 6 - 8
src/components/dashboard/TicketList.tsx

@@ -1,12 +1,12 @@
 'use client';
 
 import { useEffect, useState } from 'react';
-import api from '@/lib/api';
 import { Loader2, MessageSquare, Clock, Search, Eye } from 'lucide-react';
 import Pagination from '@/components/common/Pagination'; 
 import { useLanguage } from '@/lib/i18n/LanguageContext';
 import LocalTime from '@/components/common/LocalTime';
 import { UserTicket, TicketData } from '@/types';
+import { ticketService } from '@/lib/services';
 
 interface TicketListProps {
   onViewDetail: (ticket: UserTicket) => void;
@@ -31,15 +31,13 @@ export default function TicketList({ onViewDetail, refreshTrigger }: TicketListP
   const fetchTickets = async (targetPage: number) => {
     try {
       setLoading(true);
-      const res = await api.get('/api/vas/ticket/list_by_user', {
-        params: {
-          page: targetPage,
-          size: pageSize,
-          keyword: keyword
-        }
+      const res = await ticketService.listByUser({
+        page: targetPage,
+        size: pageSize,
+        keyword: keyword
       });
 
-      const data = res.data.data;
+      const data = res?.data;
       if (data && Array.isArray(data.items)) {
         setTickets(data.items);
         setTotal(data.total || 0);

+ 2 - 2
src/components/dashboard/TicketModal.tsx

@@ -1,10 +1,10 @@
 'use client';
 
 import { useState, useEffect } from 'react';
-import api from '@/lib/api';
 import { Loader2, X, AlertTriangle, Send } from 'lucide-react';
 import { useLanguage } from '@/lib/i18n/LanguageContext';
 import MessageModal from '@/components/common/MessageModal';
+import { ticketService } from '@/lib/services';
 
 interface TicketModalProps {
   isOpen: boolean;
@@ -66,7 +66,7 @@ export default function TicketModal({ isOpen, onClose, onSuccess, defaultOrderId
     setErrorMsg('');
 
     try {
-      await api.post('/api/vas/ticket/create', form);
+      await ticketService.create(form);
       
       showMessage(t('ticket.create_success') || '工单创建成功!', 'success', () => {
         if (onSuccess) onSuccess(); 

+ 5 - 5
src/components/dashboard/UserOrderDetailModal.tsx

@@ -2,10 +2,10 @@
 
 import { useState, useEffect, useMemo } from 'react';
 import { X, CreditCard, FileText, Package, Check, Clock, Loader2 } from 'lucide-react';
-import api from '@/lib/api';
 import { useLanguage } from '@/lib/i18n/LanguageContext';
 import LocalTime from '@/components/common/LocalTime';
 import { Order } from '@/types';
+import { paymentService, orderService } from '@/lib/services';
 
 interface UserOrderDetailModalProps {
   isOpen: boolean;
@@ -58,8 +58,8 @@ export default function UserOrderDetailModal({ isOpen, onClose, order }: UserOrd
   const fetchPayments = async (orderId: string) => {
     setLoadingPayments(true);
     try {
-      const res = await api.get('/api/vas/payment/list_by_order', { params: { order_id: orderId } });
-      const list = Array.isArray(res.data.data) ? res.data.data : [];
+      const res = await paymentService.listByOrder(Number(orderId));
+      const list = Array.isArray(res?.data) ? res.data : [];
       setPayments(list);
     } catch (e) {
       // ignore error
@@ -71,8 +71,8 @@ export default function UserOrderDetailModal({ isOpen, onClose, order }: UserOrd
   const fetchEvents = async (orderId: string) => {
     setLoadingEvents(true);
     try {
-      const res = await api.get('/api/vas/order-event/list', { params: { order_id: orderId } });
-      const list = Array.isArray(res.data.data) ? res.data.data : [];
+      const res = await orderService.getEvents(Number(orderId));
+      const list = Array.isArray(res?.data) ? res.data : [];
       setEvents(list);
     } catch (e) {
       // ignore errors

+ 6 - 11
src/components/dashboard/UserTicketDetailModal.tsx

@@ -1,12 +1,12 @@
 'use client';
 
 import { useState, useEffect, useRef } from 'react';
-import api from '@/lib/api';
 import { X, Send, User, Headset, Paperclip, Loader2, Clock } from 'lucide-react';
 import { useLanguage } from '@/lib/i18n/LanguageContext';
 import LocalTime from '@/components/common/LocalTime';
 import MessageModal from '@/components/common/MessageModal';
 import { UserTicket, TicketMessage } from '@/types';
+import { ticketService } from '@/lib/services';
 
 interface UserTicketDetailModalProps {
   isOpen: boolean;
@@ -58,15 +58,12 @@ export default function UserTicketDetailModal({ isOpen, onClose, ticket }: UserT
     if (!ticket) return;
     try {
       setLoadingMsg(true);
-      const res = await api.get('/api/vas/tickets/fetch_message', {
-        params: { 
-          ticket_id: ticket.id,
-          page: 1,
-          size: 100 
-        }
+      const res = await ticketService.fetchMessages(ticket.id, { 
+        page: 1,
+        size: 100 
       });
       
-      const items = res.data.data?.items || [];
+      const items = res?.data?.items || [];
       const sorted = items.sort((a: TicketMessage, b: TicketMessage) => 
         new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
       );
@@ -84,11 +81,9 @@ export default function UserTicketDetailModal({ isOpen, onClose, ticket }: UserT
 
     setSending(true);
     try {
-      await api.post(`/api/vas/tickets/send_message`, {
+      await ticketService.sendMessage(ticket.id, {
         content: replyContent,
         attachments: null
-      }, {
-        params: { ticket_id: ticket.id }
       });
 
       setReplyContent('');

+ 2 - 7
src/components/payment/PaymentConfirmCard.tsx

@@ -2,8 +2,8 @@
 
 import { useEffect, useState, useRef } from 'react';
 import { useSearchParams, useRouter } from 'next/navigation';
-import api from '@/lib/api';
 import { Loader2, ArrowLeft } from 'lucide-react';
+import { paymentService } from '@/lib/services';
 
 export function PaymentConfirmFallback() {
   return (
@@ -41,12 +41,7 @@ export default function PaymentConfirmCard() {
       hasFetched.current = true;
 
       try {
-        await api.get('/api/vas/payment/confirm', {
-          params: {
-            payment_id: pid,
-            token: token,
-          },
-        });
+        await paymentService.checkConfirm(Number(pid));
 
         setStatus('success');
         setMessage('支付已成功确认核销!自动化监控系统已启动后续流程。');

+ 5 - 7
src/hooks/useAutoRegister.ts

@@ -1,5 +1,5 @@
 import { useEffect } from 'react';
-import api from '@/lib/api';
+import { authService } from '@/lib/services';
 
 export function useAutoRegister() {
   useEffect(() => {
@@ -10,15 +10,13 @@ export function useAutoRegister() {
 
       try {
         // 2. 调用自动注册
-        // 根据之前的 OpenAPI: POST /api/auth/auto-register
-        // Body: { register_ip: '...' } (如果不传IP,后端通常会自动获取)
-        const res = await api.post('/api/auth/auto-register', {
-          register_ip: '127.0.0.1' // 这里的IP后端通常会重写,传个占位符即可
+        const res = await authService.autoRegister({
+          register_ip: '127.0.0.1',
         });
 
         // 3. 保存 Token 和用户信息
-        const data = res.data.data || res.data;
-        if (data.token) {
+        const data = res?.data || res;
+        if (data?.token) {
           localStorage.setItem('rsid', data.token);
           if (data.user) {
             localStorage.setItem('user_info', JSON.stringify(data.user));

+ 96 - 0
src/lib/services/accountService.ts

@@ -0,0 +1,96 @@
+// src/lib/services/accountService.ts
+
+import api from '@/lib/api';
+import { Account } from '@/types';
+
+export interface AccountListParams {
+  page?: number;
+  size?: number;
+  keyword?: string;
+}
+
+export interface AccountCreatePayload {
+  pool_name: string;
+  username: string;
+  password?: string;
+  extra_data?: Record<string, any>;
+  status?: string;
+  next_use_time?: string | null;
+}
+
+export interface AccountUpdatePayload {
+  pool_name?: string;
+  username?: string;
+  password?: string;
+  extra_data?: Record<string, any>;
+  status?: string;
+  next_use_time?: string | null;
+}
+
+export const accountService = {
+  /**
+   * 分页查询账号列表
+   */
+  async listAll(params?: AccountListParams) {
+    const res = await api.get('/api/account/list_all', { params });
+    return res.data;
+  },
+
+  /**
+   * 新增账号
+   */
+  async add(payload: AccountCreatePayload) {
+    const res = await api.post('/api/account/add', payload);
+    return res.data;
+  },
+
+  /**
+   * 更新账号信息
+   */
+  async update(accountId: number, payload: AccountUpdatePayload) {
+    const res = await api.put('/api/account/update', payload, {
+      params: { account_id: accountId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 设定/切换账号启用状态
+   */
+  async setStatus(accountId: number, status: 'active' | 'disable') {
+    return this.update(accountId, { status });
+  },
+
+  /**
+   * 设置冷却锁定时间 (传入锁定秒数)
+   */
+  async lock(accountId: number, durationSeconds: number) {
+    const nextUseTimeIso = new Date(Date.now() + durationSeconds * 1000).toISOString();
+    return this.update(accountId, { next_use_time: nextUseTimeIso });
+  },
+
+  /**
+   * 解除锁定
+   */
+  async unlock(accountId: number) {
+    return this.update(accountId, { next_use_time: new Date().toISOString() });
+  },
+
+  /**
+   * 删除账号
+   */
+  async delete(accountId: number) {
+    const res = await api.delete('/api/account/delete', {
+      params: { account_id: accountId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 获取下一个可用账号 (消费端)
+   */
+  async getNext(payload: { pool_name: string; account_cd: number }) {
+    const res = await api.post('/api/account/next', payload);
+    return res.data;
+  },
+};

+ 71 - 0
src/lib/services/authService.ts

@@ -0,0 +1,71 @@
+// src/lib/services/authService.ts
+
+import api from '@/lib/api';
+
+export interface LoginPayload {
+  username?: string;
+  password?: string;
+  [key: string]: any;
+}
+
+export interface BindEmailPayload {
+  email: string;
+  code: string;
+}
+
+export interface ResetPasswordPayload {
+  email: string;
+  code: string;
+  new_password?: string;
+  password?: string;
+}
+
+export const authService = {
+  /**
+   * 用户登录
+   */
+  async login(payload: LoginPayload) {
+    const res = await api.post('/api/auth/login', payload);
+    return res.data;
+  },
+
+  /**
+   * 快速免密自动注册
+   */
+  async autoRegister(payload: Record<string, any> = {}) {
+    const res = await api.post('/api/auth/auto-register', payload);
+    return res.data;
+  },
+
+  /**
+   * 发送绑定邮箱验证码
+   */
+  async sendBindCode(email: string) {
+    const res = await api.post('/api/auth/send-bind-code', { email });
+    return res.data;
+  },
+
+  /**
+   * 提交绑定邮箱与验证码
+   */
+  async bindEmail(payload: BindEmailPayload) {
+    const res = await api.post('/api/auth/bind-email', payload);
+    return res.data;
+  },
+
+  /**
+   * 发送重置密码验证码
+   */
+  async sendResetCode(email: string) {
+    const res = await api.post('/api/auth/send-reset-code', { email });
+    return res.data;
+  },
+
+  /**
+   * 提交重置密码
+   */
+  async resetPassword(payload: ResetPasswordPayload) {
+    const res = await api.post('/api/auth/reset-password', payload);
+    return res.data;
+  },
+};

+ 61 - 0
src/lib/services/configService.ts

@@ -0,0 +1,61 @@
+// src/lib/services/configService.ts
+
+import api from '@/lib/api';
+
+export const configService = {
+  /**
+   * 获取全量动态配置项列表
+   */
+  async getAll() {
+    const res = await api.get('/api/dynamic-configurations/all');
+    return res.data;
+  },
+
+  /**
+   * 按 Key 获取动态配置项详情
+   */
+  async getByKey(configKey: string) {
+    const res = await api.get(`/api/dynamic-configurations/key/${encodeURIComponent(configKey)}`);
+    return res.data;
+  },
+
+  /**
+   * 按 Key 更新动态配置
+   */
+  async updateByKey(configKey: string, payload: Record<string, any>) {
+    const res = await api.put(
+      `/api/dynamic-configurations/key/${encodeURIComponent(configKey)}`,
+      payload
+    );
+    return res.data;
+  },
+
+  /**
+   * 新增动态配置
+   */
+  async create(payload: Record<string, any>) {
+    const res = await api.post('/api/dynamic-configurations', payload);
+    return res.data;
+  },
+
+  /**
+   * 新增或更新动态配置 (Upsert)
+   */
+  async upsert(configKey: string, payload: Record<string, any>) {
+    const res = await api.post(
+      `/api/dynamic-configurations/key/${encodeURIComponent(configKey)}`,
+      payload
+    );
+    return res.data;
+  },
+
+  /**
+   * 删除指定动态配置项
+   */
+  async delete(configKey: string) {
+    const res = await api.delete(
+      `/api/dynamic-configurations/key/${encodeURIComponent(configKey)}`
+    );
+    return res.data;
+  },
+};

+ 16 - 0
src/lib/services/index.ts

@@ -0,0 +1,16 @@
+// src/lib/services/index.ts
+
+export * from './accountService';
+export * from './proxyService';
+export * from './authService';
+export * from './orderService';
+export * from './paymentService';
+export * from './productService';
+export * from './taskService';
+export * from './userService';
+export * from './ticketService';
+export * from './configService';
+export * from './statsService';
+export * from './pluginService';
+export * from './nodeConfigService';
+export * from './providerService';

+ 121 - 0
src/lib/services/orderService.ts

@@ -0,0 +1,121 @@
+// src/lib/services/orderService.ts
+
+import api from '@/lib/api';
+
+export interface OrderListParams {
+  page?: number;
+  page_size?: number;
+  size?: number;
+  keyword?: string;
+  status?: string;
+  [key: string]: any;
+}
+
+export const orderService = {
+  /**
+   * 分页查询订单列表
+   */
+  async listAll(params?: OrderListParams) {
+    const res = await api.get('/api/vas/order/list_all', { params });
+    return res.data;
+  },
+
+  /**
+   * 分页查询当前用户的订单列表 (前台用户)
+   */
+  async listByUser(params?: OrderListParams) {
+    const res = await api.get('/api/vas/order/list_by_user', { params });
+    return res.data;
+  },
+
+  /**
+   * 获取订单详情
+   */
+  async getDetail(orderId: number) {
+    const res = await api.get('/api/vas/order/detail', {
+      params: { order_id: orderId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 前台用户创建订单
+   */
+  async create(payload: Record<string, any>) {
+    const res = await api.post('/api/vas/order/create', payload);
+    return res.data;
+  },
+
+  /**
+   * 管理员后台直接创建订单
+   */
+  async createByAdmin(payload: Record<string, any>) {
+    const res = await api.post('/api/vas/order/create_by_admin', payload);
+    return res.data;
+  },
+
+  /**
+   * 取消订单
+   */
+  async cancel(orderId: number) {
+    const res = await api.post('/api/vas/order/cancel', null, {
+      params: { order_id: orderId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 管理员更新订单状态
+   */
+  async updateStatus(orderId: number, payload: { status: string; [key: string]: any }) {
+    const res = await api.post('/api/vas/order/admin_update_status', payload, {
+      params: { order_id: orderId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 修改订单用户输入数据 (JSON Patch)
+   */
+  async patchUserInputs(orderId: number, payload: Record<string, any>) {
+    const res = await api.post('/api/vas/order/patch_user_inputs', payload, {
+      params: { order_id: orderId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 后台调整订单价格 (优惠 / 减免 / 附加费)
+   */
+  async adjustPrice(orderId: number, payload: Record<string, any>) {
+    const res = await api.post('/api/vas/order/adjust_price', payload, {
+      params: { order_id: orderId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 获取订单生命周期事件日志
+   */
+  async getEvents(orderId: number) {
+    try {
+      const res = await api.get('/api/vas/order-event/list', {
+        params: { order_id: orderId },
+      });
+      return res.data;
+    } catch {
+      const res = await api.get('/api/order/events', {
+        params: { order_id: orderId },
+      });
+      return res.data;
+    }
+  },
+
+  /**
+   * AI 智能解析表单数据 (LLM Data Parsing)
+   */
+  async parseDataWithLlm(payload: { raw_text?: string; input_raw_str?: string; schema_id?: string | number; [key: string]: any }) {
+    const res = await api.post('/api/vas/llm/data_parsing', payload);
+    return res.data;
+  },
+};

+ 186 - 0
src/lib/services/paymentService.ts

@@ -0,0 +1,186 @@
+// src/lib/services/paymentService.ts
+
+import api from '@/lib/api';
+
+export const paymentService = {
+  /**
+   * 创建支付单
+   */
+  async createPayment(payload: Record<string, any>) {
+    const res = await api.post('/api/vas/payment/create', payload);
+    return res.data;
+  },
+
+  /**
+   * 获取支付详情
+   */
+  async getPaymentDetail(paymentId: number) {
+    const res = await api.get('/api/vas/payment/detail', {
+      params: { payment_id: paymentId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 用户端确认已付款
+   */
+  async confirmByUser(payload: Record<string, any>) {
+    const res = await api.post('/api/vas/payment/confirm_by_user', payload);
+    return res.data;
+  },
+
+  /**
+   * 检查支付单确认状态
+   */
+  async checkConfirm(paymentId: number) {
+    const res = await api.get('/api/vas/payment/confirm', {
+      params: { payment_id: paymentId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 管理员确认收到款项
+   */
+  async confirmByAdmin(payload: Record<string, any>, params?: { payment_id?: number }) {
+    const res = await api.post('/api/vas/payment/confirm_by_admin', payload, { params });
+    return res.data;
+  },
+
+  /**
+   * 管理员直接修改支付单状态
+   */
+  async updatePaymentStatus(paymentId: number, status: string) {
+    const res = await api.post(
+      '/api/vas/payment/admin_update_status',
+      { status },
+      { params: { payment_id: paymentId } }
+    );
+    return res.data;
+  },
+
+  /**
+   * 查询指定订单下的所有支付记录
+   */
+  async listByOrder(orderId: number) {
+    const res = await api.get('/api/vas/payment/list_by_order', {
+      params: { order_id: orderId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 查询所有待确认支付记录列表
+   */
+  async listPendingConfirmations(params?: { page?: number; page_size?: number; [key: string]: any }) {
+    const res = await api.post('/api/vas/payment_confirmation/list_all', params || {});
+    return res.data;
+  },
+
+  /**
+   * 获取所有启用的支付提供商
+   */
+  async listEnabledProviders() {
+    const res = await api.get('/api/vas/payment_provider/list_enabled');
+    return res.data;
+  },
+
+  /**
+   * 获取全部支付提供商列表 (后台)
+   */
+  async listAllProviders() {
+    const res = await api.get('/api/vas/payment_provider/list_all');
+    return res.data;
+  },
+
+  /**
+   * 新增支付服务提供商
+   */
+  async createProvider(payload: Record<string, any>) {
+    const res = await api.post('/api/vas/payment_provider/create', payload);
+    return res.data;
+  },
+
+  /**
+   * 更新支付服务提供商
+   */
+  async updateProvider(payload: Record<string, any>) {
+    const res = await api.post('/api/vas/payment_provider/update', payload);
+    return res.data;
+  },
+
+  /**
+   * 删除支付服务提供商
+   */
+  async deleteProvider(providerId: number) {
+    const res = await api.delete('/api/vas/payment_provider/delete', {
+      params: { id: providerId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 获取支付二维码信息
+   */
+  async getPaymentQrCode(params: { payment_id?: number; qr_id?: number }) {
+    const res = await api.get('/api/vas/payment_qr/qrcode', { params });
+    return res.data;
+  },
+
+  /**
+   * 查询某服务商下的收款码列表
+   */
+  async listQrsByProvider(providerId: number) {
+    const res = await api.get('/api/vas/payment_qr/list_by_provider', {
+      params: { provider_id: providerId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 新增收款码
+   */
+  async createQr(payload: Record<string, any>) {
+    const res = await api.post('/api/vas/payment_qr/create', payload);
+    return res.data;
+  },
+
+  /**
+   * 切换收款码启禁用状态
+   */
+  async setQrEnable(qrId: number, isActive: boolean) {
+    const res = await api.post(
+      '/api/vas/payment_qr/set_enable',
+      { is_active: isActive },
+      { params: { id: qrId } }
+    );
+    return res.data;
+  },
+
+  /**
+   * 删除收款码
+   */
+  async deleteQr(qrId: number) {
+    const res = await api.delete('/api/vas/payment_qr/delete', {
+      params: { id: qrId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 获取收款码详情
+   */
+  async getQrDetail(qrId: number) {
+    try {
+      const res = await api.get('/api/vas/payment-qr/get', {
+        params: { qr_id: qrId },
+      });
+      return res.data;
+    } catch {
+      const res = await api.get('/api/vas/payment_qr/get', {
+        params: { id: qrId },
+      });
+      return res.data;
+    }
+  },
+};

+ 153 - 0
src/lib/services/productService.ts

@@ -0,0 +1,153 @@
+// src/lib/services/productService.ts
+
+import api from '@/lib/api';
+
+export interface ProductListParams {
+  page?: number;
+  size?: number;
+  page_size?: number;
+  keyword?: string;
+  is_active?: boolean;
+  category?: string;
+  [key: string]: any;
+}
+
+export const productService = {
+  /**
+   * 获取已启用的产品列表 (客户端前台)
+   */
+  async listEnabled(params?: ProductListParams) {
+    const res = await api.get('/api/vas/product/list-enable', { params });
+    return res.data;
+  },
+
+  /**
+   * 分页查询产品列表 (后台)
+   */
+  async listAll(params?: ProductListParams) {
+    const res = await api.get('/api/vas/product/list', { params });
+    return res.data;
+  },
+
+  /**
+   * 获取产品详情
+   */
+  async getDetail(productId: number) {
+    const res = await api.get('/api/vas/product/detail', {
+      params: { product_id: productId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 新建产品
+   */
+  async create(payload: Record<string, any>) {
+    const res = await api.post('/api/vas/product/create', payload);
+    return res.data;
+  },
+
+  /**
+   * 更新产品
+   */
+  async update(productId: number, payload: Record<string, any>) {
+    const res = await api.post('/api/vas/product/update', payload, {
+      params: { product_id: productId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 删除产品
+   */
+  async delete(productId: number) {
+    const res = await api.delete('/api/vas/product/delete', {
+      params: { product_id: productId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 查询所有表单 Schema 列表
+   */
+  async listSchemas(params?: { page?: number; size?: number; page_size?: number; keyword?: string }) {
+    const res = await api.get('/api/vas/schema/list', { params });
+    return res.data;
+  },
+
+  /**
+   * 获取指定 Schema 详情
+   */
+  async getSchemaDetail(schemaId: number) {
+    const res = await api.get('/api/vas/schema/detail', {
+      params: { schema_id: schemaId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 新增动态表单 Schema
+   */
+  async createSchema(payload: Record<string, any>) {
+    const res = await api.post('/api/vas/schema/create', payload);
+    return res.data;
+  },
+
+  /**
+   * 更新动态表单 Schema
+   */
+  async updateSchema(schemaId: number, payload: Record<string, any>) {
+    const res = await api.post('/api/vas/schema/update', payload, {
+      params: { schema_id: schemaId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 删除表单 Schema
+   */
+  async deleteSchema(schemaId: number) {
+    const res = await api.delete('/api/vas/schema/delete', {
+      params: { id: schemaId, schema_id: schemaId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 获取产品的路由配置列表
+   */
+  async listRoutings(productId: number) {
+    const res = await api.get('/api/vas/product_routing/list_by_product', {
+      params: { product_id: productId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 创建产品路由配置
+   */
+  async createRouting(payload: Record<string, any>) {
+    const res = await api.post('/api/vas/product_routing/create', payload);
+    return res.data;
+  },
+
+  /**
+   * 更新产品路由配置
+   */
+  async updateRouting(id: number, payload: Record<string, any>) {
+    const res = await api.post('/api/vas/product_routing/update', payload, {
+      params: { id },
+    });
+    return res.data;
+  },
+
+  /**
+   * 删除产品路由配置
+   */
+  async deleteRouting(id: number) {
+    const res = await api.delete('/api/vas/product_routing/delete', {
+      params: { id },
+    });
+    return res.data;
+  },
+};

+ 100 - 0
src/lib/services/proxyService.ts

@@ -0,0 +1,100 @@
+// src/lib/services/proxyService.ts
+
+import api from '@/lib/api';
+import { ProxyItem } from '@/types';
+
+export interface ProxyListParams {
+  page?: number;
+  size?: number;
+  keyword?: string;
+}
+
+export interface ProxyCreatePayload {
+  pool_name: string;
+  proto: string;
+  ip: string;
+  port: number;
+  username?: string | null;
+  password?: string | null;
+  status?: string;
+  next_use_time?: string | null;
+}
+
+export interface ProxyUpdatePayload {
+  pool_name?: string;
+  proto?: string;
+  ip?: string;
+  port?: number;
+  username?: string | null;
+  password?: string | null;
+  status?: string;
+  next_use_time?: string | null;
+}
+
+export const proxyService = {
+  /**
+   * 分页查询代理节点列表
+   */
+  async listAll(params?: ProxyListParams) {
+    const res = await api.get('/api/proxy/list_all', { params });
+    return res.data;
+  },
+
+  /**
+   * 创建代理节点
+   */
+  async create(payload: ProxyCreatePayload) {
+    const res = await api.post('/api/proxy/create', payload);
+    return res.data;
+  },
+
+  /**
+   * 更新代理节点
+   */
+  async update(proxyId: number, payload: ProxyUpdatePayload) {
+    const res = await api.put('/api/proxy/update', payload, {
+      params: { proxy_id: proxyId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 设定/切换代理节点启用状态
+   */
+  async setStatus(proxyId: number, status: 'active' | 'disable') {
+    return this.update(proxyId, { status });
+  },
+
+  /**
+   * 设置冷却锁定时间 (传入锁定秒数)
+   */
+  async lock(proxyId: number, durationSeconds: number) {
+    const nextUseTimeIso = new Date(Date.now() + durationSeconds * 1000).toISOString();
+    return this.update(proxyId, { next_use_time: nextUseTimeIso });
+  },
+
+  /**
+   * 解除锁定
+   */
+  async unlock(proxyId: number) {
+    return this.update(proxyId, { next_use_time: new Date().toISOString() });
+  },
+
+  /**
+   * 删除代理节点
+   */
+  async delete(proxyId: number) {
+    const res = await api.delete('/api/proxy/delete', {
+      params: { proxy_id: proxyId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 获取下一个可用代理 IP (消费端)
+   */
+  async getNextIp(payload: { pools: string[]; proxy_cd: number }) {
+    const res = await api.post('/api/proxy/next-ip', payload);
+    return res.data;
+  },
+};

+ 23 - 0
src/lib/services/statsService.ts

@@ -0,0 +1,23 @@
+// src/lib/services/statsService.ts
+
+import api from '@/lib/api';
+
+export const statsService = {
+  /**
+   * 获取控制台运营统计数据概览 (总订单、总收入、成功率等)
+   */
+  async getOverview() {
+    const res = await api.get('/api/vas/statistics/overview');
+    return res.data;
+  },
+
+  /**
+   * 获取预约放号槽位监控概览
+   */
+  async getSlotsOverview(city?: string) {
+    const res = await api.get('/api/slots/overview', {
+      params: city ? { city } : undefined,
+    });
+    return res.data;
+  },
+};

+ 125 - 0
src/lib/services/taskService.ts

@@ -0,0 +1,125 @@
+// src/lib/services/taskService.ts
+
+import api from '@/lib/api';
+
+export interface TaskListParams {
+  page?: number;
+  size?: number;
+  status?: string;
+  keyword?: string;
+  [key: string]: any;
+}
+
+export const taskService = {
+  /**
+   * 查询任务队列列表
+   */
+  async listAll(params?: TaskListParams) {
+    const res = await api.get('/api/vas/task/list', { params });
+    return res.data;
+  },
+
+  /**
+   * 获取任务详情
+   */
+  async getDetail(taskId: number) {
+    const res = await api.get('/api/vas/task/detail', {
+      params: { task_id: taskId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 将任务重新放回调度队列
+   */
+  async returnToQueue(taskId: number) {
+    const res = await api.post('/api/vas/task/return_to_queue', null, {
+      params: { task_id: taskId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 人工手动确认任务执行完成
+   */
+  async manualConfirm(taskId: number) {
+    const res = await api.post('/api/vas/task/manual_confirm', null, {
+      params: { task_id: taskId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 暂停任务
+   */
+  async pause(taskId: number) {
+    const res = await api.post('/api/vas/task/pause', null, {
+      params: { task_id: taskId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 恢复任务执行
+   */
+  async resume(taskId: number) {
+    const res = await api.post('/api/vas/task/resume', null, {
+      params: { task_id: taskId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 重试失败的任务
+   */
+  async retry(taskId: number) {
+    const res = await api.post('/api/vas/task/retry', null, {
+      params: { task_id: taskId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 取消任务
+   */
+  async cancel(taskId: number) {
+    const res = await api.post('/api/vas/task/cancel', null, {
+      params: { task_id: taskId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 更新任务信息
+   */
+  async update(taskId: number, payload: Record<string, any>) {
+    const res = await api.post('/api/vas/task/update', payload, {
+      params: { id: taskId, task_id: taskId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 发送短信通知 (SMS)
+   */
+  async sendSms(payload: Record<string, any>) {
+    const res = await api.post('/api/vas/notification/send_sms', payload);
+    return res.data;
+  },
+
+  /**
+   * 发送 WhatsApp 消息通知
+   */
+  async sendWhatsapp(payload: Record<string, any>) {
+    const res = await api.post('/api/vas/notification/send_whatsapp', payload);
+    return res.data;
+  },
+
+  /**
+   * 发送邮件通知
+   */
+  async sendEmail(payload: Record<string, any>) {
+    const res = await api.post('/api/vas/notification/send_email', payload);
+    return res.data;
+  },
+};

+ 85 - 0
src/lib/services/ticketService.ts

@@ -0,0 +1,85 @@
+// src/lib/services/ticketService.ts
+
+import api from '@/lib/api';
+
+export interface TicketListParams {
+  page?: number;
+  size?: number;
+  keyword?: string;
+  status?: string;
+  [key: string]: any;
+}
+
+export const ticketService = {
+  /**
+   * 分页查询所有工单列表 (后台管理)
+   */
+  async listAll(params?: TicketListParams) {
+    const res = await api.get('/api/vas/ticket/list_all', { params });
+    return res.data;
+  },
+
+  /**
+   * 分页查询当前用户的工单列表 (客户端前台)
+   */
+  async listByUser(params?: TicketListParams) {
+    const res = await api.get('/api/vas/ticket/list_by_user', { params });
+    return res.data;
+  },
+
+  /**
+   * 提交/创建新工单
+   */
+  async create(payload: { order_id?: string | number; type: string; reason: string; [key: string]: any }) {
+    const res = await api.post('/api/vas/ticket/create', payload);
+    return res.data;
+  },
+
+  /**
+   * 拉取工单对话消息历史
+   */
+  async fetchMessages(ticketId: number | string, params?: { page?: number; size?: number; [key: string]: any }) {
+    const res = await api.get('/api/vas/tickets/fetch_message', {
+      params: { ticket_id: ticketId, ...params },
+    });
+    return res.data;
+  },
+
+  /**
+   * 发送工单回复消息
+   */
+  async sendMessage(
+    ticketIdOrPayload: number | string | { ticket_id: number; message?: string; content?: string; attachments?: any; [key: string]: any },
+    payload?: { content?: string; message?: string; attachments?: any; [key: string]: any }
+  ) {
+    if (typeof ticketIdOrPayload === 'object') {
+      const res = await api.post('/api/vas/tickets/send_message', ticketIdOrPayload, {
+        params: { ticket_id: ticketIdOrPayload.ticket_id },
+      });
+      return res.data;
+    }
+    const res = await api.post('/api/vas/tickets/send_message', payload, {
+      params: { ticket_id: ticketIdOrPayload },
+    });
+    return res.data;
+  },
+
+  /**
+   * 更新工单处理状态
+   */
+  async updateStatus(
+    ticketIdOrPayload: number | string | { ticket_id: number; status: string; comment?: string; [key: string]: any },
+    payload?: { status: string; comment?: string; [key: string]: any }
+  ) {
+    if (typeof ticketIdOrPayload === 'object') {
+      const res = await api.post('/api/vas/tickets/status', ticketIdOrPayload, {
+        params: { ticket_id: ticketIdOrPayload.ticket_id },
+      });
+      return res.data;
+    }
+    const res = await api.post('/api/vas/tickets/status', payload, {
+      params: { ticket_id: ticketIdOrPayload },
+    });
+    return res.data;
+  },
+};

+ 68 - 0
src/lib/services/userService.ts

@@ -0,0 +1,68 @@
+// src/lib/services/userService.ts
+
+import api from '@/lib/api';
+
+export interface UserListParams {
+  page?: number;
+  page_size?: number;
+  size?: number;
+  keyword?: string;
+  [key: string]: any;
+}
+
+export const userService = {
+  /**
+   * 分页查询用户列表
+   */
+  async listAll(params?: UserListParams) {
+    const res = await api.get('/api/user/list_all', { params });
+    return res.data;
+  },
+
+  /**
+   * 获取用户详情
+   */
+  async getDetail(userId: number) {
+    try {
+      const res = await api.get('/api/user/get_by_id', {
+        params: { user_id: userId },
+      });
+      return res.data;
+    } catch {
+      const res = await api.get('/api/user/detail', {
+        params: { user_id: userId },
+      });
+      return res.data;
+    }
+  },
+
+  /**
+   * 更新用户信息 / 权限
+   */
+  async update(userId: number | string, payload: Record<string, any>) {
+    const res = await api.post('/api/user/update', payload, {
+      params: { user_id: userId, uid: userId },
+    });
+    return res.data;
+  },
+
+  /**
+   * 用户修改个人资料 (前台)
+   */
+  async setProfiles(payload: { phone?: string; nickname?: string; avatar_url?: string; [key: string]: any }) {
+    const res = await api.post('/api/user/set_profiles', payload);
+    return res.data;
+  },
+
+  /**
+   * 上传文件 / 头像资源
+   */
+  async uploadFile(file: File) {
+    const formData = new FormData();
+    formData.append('file', file);
+    const res = await api.post('/api/resource/upload_file', formData, {
+      headers: { 'Content-Type': 'multipart/form-data' },
+    });
+    return res.data;
+  },
+};

+ 1 - 0
src/types/order.ts

@@ -65,6 +65,7 @@ export interface Order {
   base_currency: string;
   final_amount?: number;
   adjustment_delta?: number;
+  total_amount?: number; // 兼容字段
   amount?: number; // 兼容字段
   currency?: string;
   product_title?: string;

+ 2 - 0
src/types/product.ts

@@ -50,6 +50,8 @@ export interface SchemaItem {
   updated_at?: string;
 }
 
+export type FormSchema = SchemaItem;
+
 /**
  * 商品路由规则 (One Product -> Many Routings)
  */