hujiarui пре 1 месец
родитељ
комит
88241d02f9
80 измењених фајлова са 3296 додато и 82 уклоњено
  1. 47 0
      .agents/skills/creem-api/SKILL.md
  2. 4 0
      .env
  3. 6 0
      app/api/endpoints/account.py
  4. 58 0
      app/api/endpoints/agency.py
  5. 52 0
      app/api/endpoints/cost.py
  6. 38 0
      app/api/endpoints/fault.py
  7. 65 0
      app/api/endpoints/node_configuration.py
  8. 41 10
      app/api/endpoints/order.py
  9. 13 0
      app/api/endpoints/plugin.py
  10. 20 2
      app/api/endpoints/product.py
  11. 6 0
      app/api/endpoints/proxy.py
  12. 73 0
      app/api/endpoints/settlement.py
  13. 7 0
      app/api/endpoints/user.py
  14. 48 3
      app/api/endpoints/webhook.py
  15. 8 0
      app/api/router.py
  16. 4 0
      app/core/config.py
  17. 158 0
      app/core/creem.py
  18. 68 0
      app/core/migration.py
  19. 17 7
      app/main.py
  20. 5 0
      app/models/__init__.py
  21. 16 0
      app/models/account.py
  22. 42 0
      app/models/agency.py
  23. 13 0
      app/models/configuration.py
  24. 43 0
      app/models/cost.py
  25. 19 0
      app/models/email_authorizations.py
  26. 13 0
      app/models/emails.py
  27. 37 0
      app/models/fault.py
  28. 13 0
      app/models/http_session.py
  29. 139 0
      app/models/node_configuration.py
  30. 17 0
      app/models/notification_outbox.py
  31. 56 0
      app/models/order.py
  32. 14 0
      app/models/order_event.py
  33. 31 0
      app/models/payment.py
  34. 18 0
      app/models/payment_confirmation.py
  35. 23 0
      app/models/payment_event.py
  36. 15 0
      app/models/payment_provider.py
  37. 13 0
      app/models/payment_qr.py
  38. 38 0
      app/models/plugin.py
  39. 32 0
      app/models/product.py
  40. 15 0
      app/models/product_routing.py
  41. 17 0
      app/models/provider.py
  42. 19 0
      app/models/proxy_pool.py
  43. 42 0
      app/models/proxy_reputation.py
  44. 11 0
      app/models/schema.py
  45. 14 0
      app/models/session.py
  46. 111 0
      app/models/settlement.py
  47. 10 0
      app/models/short_url.py
  48. 16 0
      app/models/slot_refresh_status.py
  49. 18 0
      app/models/slot_snapshot.py
  50. 12 0
      app/models/task.py
  51. 18 0
      app/models/ticket.py
  52. 13 0
      app/models/ticket_message.py
  53. 21 0
      app/models/user.py
  54. 24 0
      app/models/vas_task.py
  55. 11 0
      app/models/verification_token.py
  56. 39 0
      app/schemas/agency.py
  57. 30 0
      app/schemas/cost.py
  58. 26 0
      app/schemas/fault.py
  59. 29 0
      app/schemas/node_configuration.py
  60. 42 3
      app/schemas/order.py
  61. 18 0
      app/schemas/plugin.py
  62. 4 0
      app/schemas/product.py
  63. 74 0
      app/schemas/settlement.py
  64. 19 0
      app/services/account_service.py
  65. 62 0
      app/services/agency_service.py
  66. 70 0
      app/services/cost_service.py
  67. 49 0
      app/services/fault_service.py
  68. 109 0
      app/services/node_configuration_service.py
  69. 185 52
      app/services/order_service.py
  70. 114 0
      app/services/payment_service.py
  71. 47 4
      app/services/plugin_service.py
  72. 13 0
      app/services/product_service.py
  73. 20 1
      app/services/proxy_service.py
  74. 366 0
      app/services/settlement_service.py
  75. 19 0
      app/services/user_service.py
  76. 126 0
      app/services/webhook_service.py
  77. 32 0
      migrate_plugin_cols.py
  78. 34 0
      scripts/init_settlement_tables.py
  79. 43 0
      scripts/inspect_web_ui.py
  80. 24 0
      scripts/link_web_ui.py

+ 47 - 0
.agents/skills/creem-api/SKILL.md

@@ -0,0 +1,47 @@
+---
+name: creem-api
+description: Integrate Creem payment infrastructure for checkouts, subscriptions, free products, licenses, and webhooks. Supports one-time payments, recurring billing, free products, and MoR compliance. Use when the user mentions Creem, or asks to add payments, billing, subscriptions, checkout, license keys, or a customer portal to their app.
+---
+
+# Creem Payment API Skill
+
+Creem is a Merchant of Record (MoR) payment platform. Creem is the legal seller, so it owns tax compliance, payment processing, chargebacks, and refunds.
+
+## Core Rules
+- **Production API**: `https://api.creem.io`
+- **Test API**: `https://test-api.creem.io`
+- **Authentication**: `x-api-key: <api_key>` header.
+- **Prices**: Integers in **cents** (`1000` = $10.00). Use `0` for free products.
+- **Currencies**: Uppercase three-letter ISO codes (`USD`, `EUR`).
+- **Access is granted by webhook, not by the success redirect.**
+
+## Webhook Signature Verification
+The signature is sent in the `creem-signature` header as a HMAC-SHA256 hex digest of the raw request body.
+
+```python
+import hmac
+import hashlib
+
+def verify_creem_signature(payload_bytes: bytes, signature: str, secret: str) -> bool:
+    if not signature or not secret:
+        return False
+    computed = hmac.new(secret.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()
+    return hmac.compare_digest(computed.lower(), signature.lower())
+```
+
+## Creating Checkout Session
+`POST /v1/checkouts`
+```json
+{
+  "product_id": "prod_...",
+  "request_id": "order_123_pay_456",
+  "customer": { "email": "user@example.com" },
+  "success_url": "https://example.com/payment/success",
+  "metadata": {
+    "order_id": "123",
+    "payment_id": "456",
+    "user_id": "789"
+  }
+}
+```
+Response returns `{ "id": "ch_...", "checkout_url": "https://checkout.creem.io/ch_..." }`.

+ 4 - 0
.env

@@ -7,6 +7,10 @@ LLM_BASE_URL=https://api.deepseek.com
 LLM_MODEL=deepseek-v4-flash
 LLM_MODEL=deepseek-v4-flash
 STRIPE_API_KEY=sk_live_xxxx
 STRIPE_API_KEY=sk_live_xxxx
 STRIPE_WEBHOOK_SECRET=whsec_xxxx
 STRIPE_WEBHOOK_SECRET=whsec_xxxx
+CREEM_API_KEY=
+CREEM_WEBHOOK_SECRET=
+CREEM_BASE_URL=https://test-api.creem.io
+CREEM_PRODUCT_ID=
 TELEGRAM_API_TOKEN=xxxxx
 TELEGRAM_API_TOKEN=xxxxx
 WECHAT_API_TOKEN=a28233ef-80b6-4131-96c0-4cda1d06cefb
 WECHAT_API_TOKEN=a28233ef-80b6-4131-96c0-4cda1d06cefb
 WHATSAPP_API_BASE_URL=https://waha.text.skin
 WHATSAPP_API_BASE_URL=https://waha.text.skin

+ 6 - 0
app/api/endpoints/account.py

@@ -11,6 +11,12 @@ protected_router = APIRouter()
 admin_required_router = APIRouter()
 admin_required_router = APIRouter()
 
 
 
 
+@admin_required_router.get("/account/pools", summary="获取所有使馆账号池列表", tags=["账号管理"], response_model=ApiResponse)
+async def account_pools(db: AsyncSession = Depends(get_db)):
+    pools = await AccountService.get_pools(db)
+    return success(data=pools)
+
+
 @admin_required_router.get("/account/list_all", summary="分页查询账号", tags=["账号管理"], response_model=ApiResponse[PageResponse[AccountOut]])
 @admin_required_router.get("/account/list_all", summary="分页查询账号", tags=["账号管理"], response_model=ApiResponse[PageResponse[AccountOut]])
 async def account_list(
 async def account_list(
     page: int = Query(0, description="第几页"),
     page: int = Query(0, description="第几页"),

+ 58 - 0
app/api/endpoints/agency.py

@@ -0,0 +1,58 @@
+# app/api/endpoints/agency.py
+from typing import Optional
+from fastapi import APIRouter, Query, Depends
+from sqlalchemy.ext.asyncio import AsyncSession
+from app.core.database import get_db
+from app.core.auth import get_current_user
+from app.models.user import VasUser
+from app.utils.response import success
+from app.schemas.common import ApiResponse, PageResponse
+from app.schemas.agency import VasAgencyCreate, VasAgencyUpdate, VasAgencyOut
+from app.services.agency_service import AgencyService
+
+public_router = APIRouter()
+protected_router = APIRouter()
+admin_required_router = APIRouter()
+
+
+@admin_required_router.post("/vas/agency/create", summary="创建合作中介", tags=["settlement"], response_model=ApiResponse[VasAgencyOut])
+async def agency_create(
+    payload: VasAgencyCreate,
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user)
+):
+    agency = await AgencyService.create(db, payload)
+    return success(data=agency)
+
+
+@admin_required_router.get("/vas/agency/list", summary="查询合作中介列表", tags=["settlement"], response_model=ApiResponse[PageResponse[VasAgencyOut]])
+async def agency_list(
+    page: int = Query(0, description="页码"),
+    size: int = Query(20, description="每页条数"),
+    active_only: bool = Query(False, description="仅看有效"),
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user)
+):
+    agencies = await AgencyService.list_all(db, page, size, active_only)
+    return success(data=agencies)
+
+
+@admin_required_router.get("/vas/agency/{agency_id}", summary="获取中介详情", tags=["settlement"], response_model=ApiResponse[VasAgencyOut])
+async def agency_detail(
+    agency_id: str,
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user)
+):
+    agency = await AgencyService.get(db, agency_id)
+    return success(data=agency)
+
+
+@admin_required_router.put("/vas/agency/{agency_id}", summary="更新中介信息/底价", tags=["settlement"], response_model=ApiResponse[VasAgencyOut])
+async def agency_update(
+    agency_id: str,
+    payload: VasAgencyUpdate,
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user)
+):
+    updated = await AgencyService.update(db, agency_id, payload)
+    return success(data=updated)

+ 52 - 0
app/api/endpoints/cost.py

@@ -0,0 +1,52 @@
+# app/api/endpoints/cost.py
+from datetime import datetime
+from typing import Optional, Dict
+from fastapi import APIRouter, Query, Depends
+from sqlalchemy.ext.asyncio import AsyncSession
+from app.core.database import get_db
+from app.core.auth import get_current_user
+from app.models.user import VasUser
+from app.utils.response import success
+from app.schemas.common import ApiResponse, PageResponse
+from app.schemas.cost import VasCostCreate, VasCostOut
+from app.services.cost_service import CostService
+
+public_router = APIRouter()
+protected_router = APIRouter()
+admin_required_router = APIRouter()
+
+
+@admin_required_router.post("/vas/cost/create", summary="录入运行耗材成本", tags=["settlement"], response_model=ApiResponse[VasCostOut])
+async def cost_create(
+    payload: VasCostCreate,
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user)
+):
+    cost = await CostService.create(db, payload, current_user.id)
+    return success(data=cost)
+
+
+@admin_required_router.get("/vas/cost/list", summary="查询耗材成本流水", tags=["settlement"], response_model=ApiResponse[PageResponse[VasCostOut]])
+async def cost_list(
+    period_id: Optional[str] = Query(None, description="账期ID"),
+    category: Optional[str] = Query(None, description="类别: vps/proxy_ip/captcha_api/sms_api/other"),
+    start_date: Optional[datetime] = Query(None, description="起始时间"),
+    end_date: Optional[datetime] = Query(None, description="结束时间"),
+    page: int = Query(0, description="页码"),
+    size: int = Query(20, description="每页条数"),
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user)
+):
+    costs = await CostService.list_costs(db, period_id, category, start_date, end_date, page, size)
+    return success(data=costs)
+
+
+@admin_required_router.get("/vas/cost/summary", summary="耗材成本分类统计", tags=["settlement"], response_model=ApiResponse[Dict[str, int]])
+async def cost_summary(
+    start_date: datetime = Query(..., description="统计起始时间"),
+    end_date: datetime = Query(..., description="统计结束时间"),
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user)
+):
+    summary = await CostService.get_costs_summary_by_date(db, start_date, end_date)
+    return success(data=summary)

+ 38 - 0
app/api/endpoints/fault.py

@@ -0,0 +1,38 @@
+# app/api/endpoints/fault.py
+from typing import Optional
+from fastapi import APIRouter, Query, Depends
+from sqlalchemy.ext.asyncio import AsyncSession
+from app.core.database import get_db
+from app.core.auth import get_current_user
+from app.models.user import VasUser
+from app.utils.response import success
+from app.schemas.common import ApiResponse, PageResponse
+from app.schemas.fault import VasFaultCreate, VasFaultOut
+from app.services.fault_service import FaultService
+
+public_router = APIRouter()
+protected_router = APIRouter()
+admin_required_router = APIRouter()
+
+
+@admin_required_router.post("/vas/fault/create", summary="登记个人录错赔偿事件", tags=["settlement"], response_model=ApiResponse[VasFaultOut])
+async def fault_create(
+    payload: VasFaultCreate,
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user)
+):
+    fault = await FaultService.create(db, payload)
+    return success(data=fault)
+
+
+@admin_required_router.get("/vas/fault/list", summary="查询过错赔偿扣款记录", tags=["settlement"], response_model=ApiResponse[PageResponse[VasFaultOut]])
+async def fault_list(
+    user_id: Optional[str] = Query(None, description="责任人ID"),
+    deducted_status: Optional[int] = Query(None, description="扣款状态: 0待扣, 1已扣"),
+    page: int = Query(0, description="页码"),
+    size: int = Query(20, description="每页条数"),
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user)
+):
+    records = await FaultService.list_all(db, user_id, deducted_status, page, size)
+    return success(data=records)

+ 65 - 0
app/api/endpoints/node_configuration.py

@@ -16,6 +16,9 @@ from app.schemas.node_configuration import (
     NodeConfigurationEnableRequest,
     NodeConfigurationEnableRequest,
     NodeConfigurationRollbackRequest,
     NodeConfigurationRollbackRequest,
     NodeConfigurationListResponse,
     NodeConfigurationListResponse,
+    ClusterNodeCreate,
+    ClusterNodeUpdate,
+    ClusterNodeOut,
 )
 )
 from app.services.node_configuration_service import NodeConfigurationService
 from app.services.node_configuration_service import NodeConfigurationService
 
 
@@ -72,6 +75,68 @@ async def get_runtime_status(
     return success(data={"nodes": nodes, "timestamp": now.strftime("%Y-%m-%d %H:%M:%S")})
     return success(data={"nodes": nodes, "timestamp": now.strftime("%Y-%m-%d %H:%M:%S")})
 
 
 
 
+# ==================== 集群节点档案注册接口 (优先于 /{entry_type} 匹配) ====================
+@admin_required_router.get(
+    "/nodes/list",
+    summary="获取已注册集群节点档案列表",
+    response_model=ApiResponse[List[ClusterNodeOut]],
+)
+async def list_cluster_nodes(
+    status: Optional[int] = Query(None, description="状态筛选: 1启用 0停用"),
+    keyword: Optional[str] = Query(None, description="关键词搜索 node_id / name / ip / region"),
+    db: AsyncSession = Depends(get_db),
+):
+    nodes = await NodeConfigurationService.list_cluster_nodes(
+        db=db, status=status, keyword=keyword
+    )
+    return success(data=nodes)
+
+
+@admin_required_router.post(
+    "/nodes/create",
+    summary="登记/注册新集群节点档案",
+    response_model=ApiResponse[ClusterNodeOut],
+)
+async def create_cluster_node(
+    payload: ClusterNodeCreate = Body(...),
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user),
+):
+    node = await NodeConfigurationService.create_cluster_node(db=db, data=payload)
+    return success(data=node, message="节点档案登记成功")
+
+
+@admin_required_router.post(
+    "/nodes/update",
+    summary="更新已注册集群节点档案",
+    response_model=ApiResponse[ClusterNodeOut],
+)
+async def update_cluster_node(
+    node_id: str = Query(..., description="目标节点ID"),
+    payload: ClusterNodeUpdate = Body(...),
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user),
+):
+    node = await NodeConfigurationService.update_cluster_node(
+        db=db, node_id=node_id, data=payload
+    )
+    return success(data=node, message="节点档案更新成功")
+
+
+@admin_required_router.post(
+    "/nodes/delete",
+    summary="注销/删除集群节点档案",
+    response_model=ApiResponse[bool],
+)
+async def delete_cluster_node(
+    node_id: str = Query(..., description="目标节点ID"),
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user),
+):
+    result = await NodeConfigurationService.delete_cluster_node(db=db, node_id=node_id)
+    return success(data=result, message="节点注销成功")
+
+
 @admin_required_router.get(
 @admin_required_router.get(
     "/{entry_type}",
     "/{entry_type}",
     summary="分页查询配置条目列表",
     summary="分页查询配置条目列表",

+ 41 - 10
app/api/endpoints/order.py

@@ -1,4 +1,4 @@
-from typing import List
+from typing import List, Optional
 from fastapi import APIRouter, Query, Depends
 from fastapi import APIRouter, Query, Depends
 from sqlalchemy.ext.asyncio import AsyncSession
 from sqlalchemy.ext.asyncio import AsyncSession
 from app.utils.validation_utils import validate_user_inputs
 from app.utils.validation_utils import validate_user_inputs
@@ -9,7 +9,14 @@ from redis.asyncio import Redis
 from app.utils.response import success
 from app.utils.response import success
 from app.models.user import VasUser
 from app.models.user import VasUser
 from app.schemas.common import ApiResponse, PageResponse
 from app.schemas.common import ApiResponse, PageResponse
-from app.schemas.order import VasOrderAdjustPrice, VasOrderCreate, VasOrderOut, VasOrderPatchUserInputs
+from app.schemas.order import (
+    VasOrderAdjustPrice,
+    VasOrderCreate,
+    VasOrderCreateAdmin,
+    VasOrderOut,
+    VasOrderPatchUserInputs,
+    VasOrderUpdate,
+)
 from app.schemas.order_event import VasOrderEventCreate, VasOrderEventOut
 from app.schemas.order_event import VasOrderEventCreate, VasOrderEventOut
 from app.services.order_event_service import OrderEventService
 from app.services.order_event_service import OrderEventService
 from app.services.order_service import OrderService
 from app.services.order_service import OrderService
@@ -21,7 +28,7 @@ protected_router = APIRouter()
 admin_required_router = APIRouter()
 admin_required_router = APIRouter()
 
 
 
 
-@protected_router.post("/vas/order/create", summary="创建订单", tags=["textskin"], response_model=ApiResponse[VasOrderOut])
+@protected_router.post("/vas/order/create", summary="创建订单(散客自主下单)", tags=["textskin"], response_model=ApiResponse[VasOrderOut])
 async def vas_order_create(
 async def vas_order_create(
     payload: VasOrderCreate,
     payload: VasOrderCreate,
     current_user: VasUser = Depends(get_current_user),
     current_user: VasUser = Depends(get_current_user),
@@ -40,9 +47,9 @@ async def vas_order_create(
     return success(data=created_order)
     return success(data=created_order)
 
 
 
 
-@admin_required_router.post("/vas/order/create_by_admin", summary="管理员创建订单", tags=["textskin"], response_model=ApiResponse[VasOrderOut])
+@admin_required_router.post("/vas/order/create_by_admin", summary="管理员/客服代客录单(直客/中介单)", tags=["textskin"], response_model=ApiResponse[VasOrderOut])
 async def vas_order_create_by_admin(
 async def vas_order_create_by_admin(
-    payload: VasOrderCreate,
+    payload: VasOrderCreateAdmin,
     current_user: VasUser = Depends(get_current_user),
     current_user: VasUser = Depends(get_current_user),
     db: AsyncSession = Depends(get_db)
     db: AsyncSession = Depends(get_db)
 ):
 ):
@@ -58,6 +65,17 @@ async def vas_order_create_by_admin(
     return success(data=created_order)
     return success(data=created_order)
 
 
 
 
+@admin_required_router.post("/vas/order/mark_completed", summary="标记订单履约完成并开启退款风险期", tags=["textskin"], response_model=ApiResponse[VasOrderOut])
+async def vas_order_mark_completed(
+    order_id: str,
+    risk_days: int = Query(7, description="退款风险期天数,默认7天"),
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user)
+):
+    order = await OrderService.mark_completed(db, order_id, risk_days)
+    return success(data=order)
+
+
 @admin_required_router.post("/vas/order/adjust-price", summary="管理员调整订单价格", tags=["textskin"], response_model=ApiResponse[VasOrderOut])
 @admin_required_router.post("/vas/order/adjust-price", summary="管理员调整订单价格", tags=["textskin"], response_model=ApiResponse[VasOrderOut])
 async def vas_order_adjust_price(
 async def vas_order_adjust_price(
     order_id: str,
     order_id: str,
@@ -70,7 +88,7 @@ async def vas_order_adjust_price(
 
 
 
 
 @admin_required_router.get("/vas/order/detail", summary="查询订单", tags=["textskin"], response_model=ApiResponse[VasOrderOut])
 @admin_required_router.get("/vas/order/detail", summary="查询订单", tags=["textskin"], response_model=ApiResponse[VasOrderOut])
-async def vas_order_create(
+async def vas_order_get_detail(
     order_id: str,
     order_id: str,
     db: AsyncSession = Depends(get_db),
     db: AsyncSession = Depends(get_db),
 ):
 ):
@@ -88,7 +106,18 @@ async def vas_order_patch_user_inputs(
     return success(data=order)
     return success(data=order)
 
 
 
 
-@protected_router.get("/vas/order/list_by_user", summary="查看所有订单", tags=["textskin"], response_model=ApiResponse[PageResponse[VasOrderOut]])
+@admin_required_router.post("/vas/order/update", summary="管理员配置与更新订单属性(渠道/对接人/中介/申报参数)", tags=["textskin"], response_model=ApiResponse[VasOrderOut])
+async def vas_order_update(
+    order_id: str,
+    payload: VasOrderUpdate,
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user),
+):
+    order = await OrderService.update_order(db, order_id, payload)
+    return success(data=order)
+
+
+@protected_router.get("/vas/order/list_by_user", summary="查看当前用户的所有订单", tags=["textskin"], response_model=ApiResponse[PageResponse[VasOrderOut]])
 async def vas_order_list_by_user(
 async def vas_order_list_by_user(
     page: int = Query(0, description="第几页"),
     page: int = Query(0, description="第几页"),
     size: int = Query(10, description="分页大小"),
     size: int = Query(10, description="分页大小"),
@@ -100,14 +129,17 @@ async def vas_order_list_by_user(
     return success(data=orders)
     return success(data=orders)
 
 
 
 
-@protected_router.get("/vas/order/list_all", summary="查看所有订单", tags=["textskin"], response_model=ApiResponse[PageResponse[VasOrderOut]])
+@protected_router.get("/vas/order/list_all", summary="查看所有订单(支持渠道/对接人/结算状态筛选)", tags=["textskin"], response_model=ApiResponse[PageResponse[VasOrderOut]])
 async def vas_order_list_all(
 async def vas_order_list_all(
     page: int = Query(0, description="第几页"),
     page: int = Query(0, description="第几页"),
     size: int = Query(10, description="分页大小"),
     size: int = Query(10, description="分页大小"),
     keyword: str = Query("", description="查询条件"),
     keyword: str = Query("", description="查询条件"),
+    channel_type: Optional[str] = Query(None, description="渠道类型: direct(社交自收直客), agency(中介渠道), website(官网公海)"),
+    handler_id: Optional[str] = Query(None, description="对接人用户ID"),
+    settlement_status: Optional[str] = Query(None, description="结算状态: unsettled/eligible/settled"),
     db: AsyncSession = Depends(get_db)
     db: AsyncSession = Depends(get_db)
 ):
 ):
-    orders = await OrderService.list_all(db, page, size, keyword)
+    orders = await OrderService.list_all(db, page, size, keyword, channel_type, handler_id, settlement_status)
     return success(data=orders)
     return success(data=orders)
 
 
 
 
@@ -138,4 +170,3 @@ async def vas_list_order_events_by_order(
 ):
 ):
     events = await OrderEventService.get_by_order_id(db, order_id)
     events = await OrderEventService.get_by_order_id(db, order_id)
     return success(data=events)
     return success(data=events)
-

+ 13 - 0
app/api/endpoints/plugin.py

@@ -33,11 +33,15 @@ async def publish_plugin(
     name: Optional[str] = Form(None),
     name: Optional[str] = Form(None),
     version: Optional[str] = Form(None),
     version: Optional[str] = Form(None),
     display_name: Optional[str] = Form(""),
     display_name: Optional[str] = Form(""),
+    filename: Optional[str] = Form(""),
+    class_name: Optional[str] = Form(""),
+    protocol: Optional[str] = Form("IPlugin"),
     description: Optional[str] = Form(""),
     description: Optional[str] = Form(""),
     download_url: Optional[str] = Form(None),
     download_url: Optional[str] = Form(None),
     sha256: Optional[str] = Form(""),
     sha256: Optional[str] = Form(""),
     changelog: Optional[str] = Form(None),
     changelog: Optional[str] = Form(None),
     set_as_latest: bool = Form(True),
     set_as_latest: bool = Form(True),
+    developer_id: Optional[str] = Form(None),
     file: Optional[UploadFile] = File(None),
     file: Optional[UploadFile] = File(None),
     db: AsyncSession = Depends(get_db),
     db: AsyncSession = Depends(get_db),
 ):
 ):
@@ -53,11 +57,16 @@ async def publish_plugin(
             name = body.get("name")
             name = body.get("name")
             version = body.get("version")
             version = body.get("version")
             display_name = body.get("display_name", "")
             display_name = body.get("display_name", "")
+            filename = body.get("filename", "")
+            class_name = body.get("class_name", "")
+            protocol = body.get("protocol", "IPlugin")
             description = body.get("description", "")
             description = body.get("description", "")
             download_url = body.get("download_url")
             download_url = body.get("download_url")
             sha256 = body.get("sha256", "")
             sha256 = body.get("sha256", "")
             changelog = body.get("changelog")
             changelog = body.get("changelog")
             set_as_latest = body.get("set_as_latest", True)
             set_as_latest = body.get("set_as_latest", True)
+            if "developer_id" in body:
+                developer_id = body.get("developer_id")
         except Exception:
         except Exception:
             pass
             pass
 
 
@@ -66,12 +75,16 @@ async def publish_plugin(
         name=name,
         name=name,
         version=version,
         version=version,
         display_name=display_name,
         display_name=display_name,
+        filename=filename,
+        class_name=class_name,
+        protocol=protocol,
         description=description,
         description=description,
         file=file,
         file=file,
         download_url=download_url,
         download_url=download_url,
         sha256=sha256,
         sha256=sha256,
         changelog=changelog,
         changelog=changelog,
         set_as_latest=set_as_latest,
         set_as_latest=set_as_latest,
+        developer_id=developer_id,
     )
     )
     return success(data=res, message="Plugin published successfully")
     return success(data=res, message="Plugin published successfully")
 
 

+ 20 - 2
app/api/endpoints/product.py

@@ -2,6 +2,7 @@ from typing import List
 from fastapi import APIRouter, Query, Depends
 from fastapi import APIRouter, Query, Depends
 from sqlalchemy.ext.asyncio import AsyncSession
 from sqlalchemy.ext.asyncio import AsyncSession
 from app.core.database import get_db
 from app.core.database import get_db
+from app.core.biz_exception import BizException
 from app.utils.response import success
 from app.utils.response import success
 from app.schemas.common import ApiResponse, PageResponse
 from app.schemas.common import ApiResponse, PageResponse
 from app.schemas.product import VasProductCreate, VasProductOut, VasProductUpdate
 from app.schemas.product import VasProductCreate, VasProductOut, VasProductUpdate
@@ -27,14 +28,31 @@ async def vas_product_create(
 
 
 @admin_required_router.post("/vas/product/update", summary="更新商品", tags=["textskin"], response_model=ApiResponse[VasProductOut])
 @admin_required_router.post("/vas/product/update", summary="更新商品", tags=["textskin"], response_model=ApiResponse[VasProductOut])
 async def vas_product_update(
 async def vas_product_update(
-    id: int,
     payload: VasProductUpdate,
     payload: VasProductUpdate,
+    id: int = Query(None, description="商品ID"),
+    product_id: int = Query(None, description="商品ID别名"),
     db: AsyncSession = Depends(get_db)
     db: AsyncSession = Depends(get_db)
 ):
 ):
-    product = await ProductService.update(db, id, payload)
+    target_id = id if id is not None else product_id
+    if target_id is None:
+        raise BizException(code=40001, message="商品ID不能为空")
+    product = await ProductService.update(db, target_id, payload)
     return success(data=product)
     return success(data=product)
 
 
 
 
+@admin_required_router.delete("/vas/product/delete", summary="删除商品", tags=["textskin"], response_model=ApiResponse)
+async def vas_product_delete(
+    id: int = Query(None, description="商品ID"),
+    product_id: int = Query(None, description="商品ID别名"),
+    db: AsyncSession = Depends(get_db)
+):
+    target_id = id if id is not None else product_id
+    if target_id is None:
+        raise BizException(code=40001, message="商品ID不能为空")
+    await ProductService.delete(db, target_id)
+    return success()
+
+
 @public_router.get("/vas/product/list-enable", summary="获取商品列表", tags=["textskin"], response_model=ApiResponse[PageResponse[VasProductOut]])
 @public_router.get("/vas/product/list-enable", summary="获取商品列表", tags=["textskin"], response_model=ApiResponse[PageResponse[VasProductOut]])
 async def vas_product_list(
 async def vas_product_list(
     country: str = Query("", description="目的国家"),
     country: str = Query("", description="目的国家"),

+ 6 - 0
app/api/endpoints/proxy.py

@@ -79,6 +79,12 @@ async def proxy_remove(
     return success()
     return success()
 
 
 
 
+@admin_required_router.get("/proxy/pools", summary="获取所有云端代理池列表", tags=["代理管理"], response_model=ApiResponse)
+async def proxy_pools(db: AsyncSession = Depends(get_db)):
+    pools = await ProxyService.get_pools(db)
+    return success(data=pools)
+
+
 @admin_required_router.get("/proxy/list_all", summary="查询代理", tags=["代理管理"], response_model=ApiResponse[PageResponse[ProxyOut]])
 @admin_required_router.get("/proxy/list_all", summary="查询代理", tags=["代理管理"], response_model=ApiResponse[PageResponse[ProxyOut]])
 async def proxy_list(
 async def proxy_list(
     page: int = Query(0, description="第几页"),
     page: int = Query(0, description="第几页"),

+ 73 - 0
app/api/endpoints/settlement.py

@@ -0,0 +1,73 @@
+# app/api/endpoints/settlement.py
+from typing import Optional
+from fastapi import APIRouter, Query, Depends
+from sqlalchemy.ext.asyncio import AsyncSession
+from app.core.database import get_db
+from app.core.auth import get_current_user
+from app.models.user import VasUser
+from app.utils.response import success
+from app.schemas.common import ApiResponse, PageResponse
+from app.schemas.settlement import (
+    SettlementPreviewRequest,
+    SettlementConfirmRequest,
+    SettlementPreviewResponse,
+    SettlementPeriodOut,
+    SettlementOrderDetailOut,
+)
+from app.services.settlement_service import SettlementService
+
+public_router = APIRouter()
+protected_router = APIRouter()
+admin_required_router = APIRouter()
+
+
+@admin_required_router.post("/vas/settlement/preview", summary="试算账期分润(预览)", tags=["settlement"], response_model=ApiResponse[SettlementPreviewResponse])
+async def settlement_preview(
+    payload: SettlementPreviewRequest,
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user)
+):
+    result = await SettlementService.preview_settlement(db, payload)
+    return success(data=result)
+
+
+@admin_required_router.post("/vas/settlement/confirm", summary="正式确认并冻结账期分润", tags=["settlement"], response_model=ApiResponse[dict])
+async def settlement_confirm(
+    payload: SettlementConfirmRequest,
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user)
+):
+    period = await SettlementService.confirm_settlement(db, payload, confirmed_by=current_user.id)
+    return success(data={
+        "period_id": period.id,
+        "name": period.name,
+        "total_revenue": period.total_revenue,
+        "total_cost": period.total_cost,
+        "net_profit": period.net_profit,
+        "status": period.status,
+        "confirmed_at": period.confirmed_at.isoformat() if period.confirmed_at else None,
+        "summary": period.summary_data
+    })
+
+
+@admin_required_router.get("/vas/settlement/periods", summary="查询所有结算账期", tags=["settlement"], response_model=ApiResponse[PageResponse[SettlementPeriodOut]])
+async def settlement_list_periods(
+    page: int = Query(0, description="页码"),
+    size: int = Query(20, description="每页条数"),
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user)
+):
+    periods = await SettlementService.list_periods(db, page, size)
+    return success(data=periods)
+
+
+@admin_required_router.get("/vas/settlement/period/{period_id}/details", summary="查询账期内订单分润明细快照", tags=["settlement"], response_model=ApiResponse[PageResponse[SettlementOrderDetailOut]])
+async def settlement_period_details(
+    period_id: str,
+    page: int = Query(0, description="页码"),
+    size: int = Query(50, description="每页条数"),
+    db: AsyncSession = Depends(get_db),
+    current_user: VasUser = Depends(get_current_user)
+):
+    details = await SettlementService.list_period_details(db, period_id, page, size)
+    return success(data=details)

+ 7 - 0
app/api/endpoints/user.py

@@ -1,3 +1,4 @@
+from typing import List
 from fastapi import APIRouter, Query, Depends
 from fastapi import APIRouter, Query, Depends
 from sqlalchemy.ext.asyncio import AsyncSession
 from sqlalchemy.ext.asyncio import AsyncSession
 from app.core.database import get_db
 from app.core.database import get_db
@@ -13,6 +14,12 @@ protected_router = APIRouter()
 admin_required_router = APIRouter()
 admin_required_router = APIRouter()
 
 
 
 
+@admin_required_router.get("/user/admins", summary="获取所有系统管理员用户列表(合伙人与开发者候选)", tags=["用户管理"], response_model=ApiResponse[List[VasUserOut]])
+async def vas_user_list_admins(db: AsyncSession = Depends(get_db)):
+    admins = await UserService.list_admins(db)
+    return success(data=admins)
+
+
 @admin_required_router.get("/user/list_all", summary="获取所有用户", tags=["用户管理"], response_model=ApiResponse[PageResponse[VasUserOut]])
 @admin_required_router.get("/user/list_all", summary="获取所有用户", tags=["用户管理"], response_model=ApiResponse[PageResponse[VasUserOut]])
 async def vas_user_list_all(
 async def vas_user_list_all(
     page: int = Query(0, description="第几页"),
     page: int = Query(0, description="第几页"),

+ 48 - 3
app/api/endpoints/webhook.py

@@ -1,8 +1,10 @@
 import stripe
 import stripe
+import json
 from app.core.logger import logger
 from app.core.logger import logger
 from app.core.config import settings
 from app.core.config import settings
-from fastapi import APIRouter, Request, Depends
+from fastapi import APIRouter, Request, Depends, HTTPException
 from sqlalchemy.ext.asyncio import AsyncSession
 from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select
 from app.core.redis import get_redis_client
 from app.core.redis import get_redis_client
 from app.core.database import get_db
 from app.core.database import get_db
 from redis.asyncio import Redis
 from redis.asyncio import Redis
@@ -10,6 +12,8 @@ from app.utils.response import success
 from app.schemas.common import ApiResponse
 from app.schemas.common import ApiResponse
 from app.schemas.webhook import SMSHelperWebhookPayload
 from app.schemas.webhook import SMSHelperWebhookPayload
 from app.services.webhook_service import WebhookService
 from app.services.webhook_service import WebhookService
+from app.models.payment_provider import VasPaymentProvider
+from app.core.creem import verify_creem_signature
 
 
 public_router = APIRouter()
 public_router = APIRouter()
 protected_router = APIRouter()
 protected_router = APIRouter()
@@ -37,8 +41,6 @@ async def webhook_stripe(
     payload = await request.body()
     payload = await request.body()
     sig_header = request.headers.get("stripe-signature")
     sig_header = request.headers.get("stripe-signature")
     
     
-    
-    # 3️⃣ 打调试日志(安全,不要打 secret)
     logger.info("Stripe webhook received")
     logger.info("Stripe webhook received")
     logger.info("Stripe-Signature: %s", sig_header)
     logger.info("Stripe-Signature: %s", sig_header)
     logger.info("Payload bytes length: %s", len(payload))
     logger.info("Payload bytes length: %s", len(payload))
@@ -56,3 +58,46 @@ async def webhook_stripe(
     res = await WebhookService.stripe_payment_webhook(db, event)
     res = await WebhookService.stripe_payment_webhook(db, event)
     return success()
     return success()
 
 
+
+@public_router.post("/webhook/creem", summary="Creem Webhook", tags=["webhook"], response_model=ApiResponse)
+async def webhook_creem(
+    request: Request,
+    db: AsyncSession = Depends(get_db),
+    redis_client: Redis = Depends(get_redis_client)
+):
+    """
+    接收并处理 Creem 官方 Webhook 支付完成通知
+    支持 HMAC-SHA256 creem-signature 验签与幂等核销
+    """
+    payload = await request.body()
+    sig_header = request.headers.get("creem-signature") or request.headers.get("x-creem-signature") or ""
+
+    logger.info("💳 [CREEM] Webhook received, signature=%s, bytes_len=%d", sig_header, len(payload))
+
+    # 获取 Provider 配置的 secret 或全局设置
+    stmt = select(VasPaymentProvider).where(VasPaymentProvider.name == "creem")
+    provider = (await db.execute(stmt)).scalar_one_or_none()
+    webhook_secret = ""
+    if provider and provider.config and isinstance(provider.config, dict):
+        webhook_secret = provider.config.get("webhook_secret", "")
+    if not webhook_secret:
+        webhook_secret = settings.creem_webhook_secret
+
+    # 如果配置了 secret 则进行防篡改验签
+    if webhook_secret:
+        if not verify_creem_signature(payload, sig_header, webhook_secret):
+            logger.error("❌ [CREEM] Webhook signature invalid: signature=%s", sig_header)
+            raise HTTPException(status_code=400, detail="Invalid Creem signature")
+    else:
+        logger.warning("⚠️ [CREEM] Webhook secret not set, skipping signature verification in current mode")
+
+    try:
+        event = json.loads(payload.decode("utf-8"))
+    except Exception as e:
+        logger.error(f"❌ [CREEM] Failed to decode JSON payload: {e}")
+        raise HTTPException(status_code=400, detail="Invalid JSON payload")
+
+    await WebhookService.creem_payment_webhook(db, event)
+    return success()
+
+

+ 8 - 0
app/api/router.py

@@ -2,12 +2,15 @@ from fastapi import APIRouter
 
 
 from app.api.endpoints import (
 from app.api.endpoints import (
     account,
     account,
+    agency,
     agent,
     agent,
     auth,
     auth,
     common,
     common,
     config,
     config,
+    cost,
     node_configuration,
     node_configuration,
     email,
     email,
+    fault,
     notification,
     notification,
     order,
     order,
     payment,
     payment,
@@ -15,6 +18,7 @@ from app.api.endpoints import (
     product,
     product,
     provider,
     provider,
     proxy,
     proxy,
+    settlement,
     slot,
     slot,
     sms,
     sms,
     task,
     task,
@@ -34,12 +38,15 @@ admin_required_router = APIRouter()
 # 模块列表
 # 模块列表
 _modules = [
 _modules = [
     account,
     account,
+    agency,
     agent,
     agent,
     auth,
     auth,
     common,
     common,
     config,
     config,
+    cost,
     node_configuration,
     node_configuration,
     email,
     email,
+    fault,
     notification,
     notification,
     order,
     order,
     payment,
     payment,
@@ -47,6 +54,7 @@ _modules = [
     product,
     product,
     provider,
     provider,
     proxy,
     proxy,
+    settlement,
     slot,
     slot,
     sms,
     sms,
     task,
     task,

+ 4 - 0
app/core/config.py

@@ -22,6 +22,10 @@ class Settings(BaseSettings):
     # -----------------------
     # -----------------------
     stripe_api_key: str
     stripe_api_key: str
     stripe_webhook_secret: str
     stripe_webhook_secret: str
+    creem_api_key: str = Field("", description="Creem API Key")
+    creem_webhook_secret: str = Field("", description="Creem Webhook Secret")
+    creem_base_url: str = Field("https://test-api.creem.io", description="Creem Base URL (or https://api.creem.io)")
+    creem_product_id: str = Field("", description="Default Creem Product ID (optional)")
     telegram_api_token: str = Field("", description="Telegram bot API token")
     telegram_api_token: str = Field("", description="Telegram bot API token")
     wechat_api_token: str = Field("", description="Wechat webhook API token")
     wechat_api_token: str = Field("", description="Wechat webhook API token")
     whatsapp_api_base_url: str = Field("https://waha.text.skin", description="Whatsapp API base url")
     whatsapp_api_base_url: str = Field("https://waha.text.skin", description="Whatsapp API base url")

+ 158 - 0
app/core/creem.py

@@ -0,0 +1,158 @@
+# app/core/creem.py
+
+import hmac
+import hashlib
+import json
+from typing import Dict, Any, Optional
+import aiohttp
+
+from app.core.config import settings
+from app.core.logger import logger
+from app.core.biz_exception import BizLogicError
+
+
+def verify_creem_signature(payload_bytes: bytes, signature: str, secret: str) -> bool:
+    """
+    验证 Creem Webhook 签名 (HMAC-SHA256)
+    Creem 发送 creem-signature 头部,为 HEX 格式
+    """
+    if not signature or not secret:
+        return False
+    try:
+        computed = hmac.new(secret.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()
+        return hmac.compare_digest(computed.lower(), signature.strip().lower())
+    except Exception as e:
+        logger.error(f"❌ [CREEM] Webhook signature verification error: {e}")
+        return False
+
+
+class CreemClient:
+    """
+    Creem Payment API Client
+    Official documentation: https://docs.creem.io/code/sdks/ai-agents
+    """
+
+    @classmethod
+    def get_api_key(cls, provider_config: Optional[Dict[str, Any]] = None) -> str:
+        if provider_config and provider_config.get("api_key"):
+            return provider_config["api_key"]
+        return settings.creem_api_key
+
+    @classmethod
+    def get_base_url(cls, provider_config: Optional[Dict[str, Any]] = None) -> str:
+        if provider_config and provider_config.get("base_url"):
+            return provider_config["base_url"].rstrip("/")
+        if provider_config and provider_config.get("test_mode") is False:
+            return "https://api.creem.io"
+        return settings.creem_base_url.rstrip("/") or "https://test-api.creem.io"
+
+    @classmethod
+    def get_webhook_secret(cls, provider_config: Optional[Dict[str, Any]] = None) -> str:
+        if provider_config and provider_config.get("webhook_secret"):
+            return provider_config["webhook_secret"]
+        return settings.creem_webhook_secret
+
+    @classmethod
+    async def create_product(
+        cls,
+        name: str,
+        price_cents: int,
+        currency: str = "USD",
+        description: Optional[str] = None,
+        billing_type: str = "one_time",
+        provider_config: Optional[Dict[str, Any]] = None,
+    ) -> Dict[str, Any]:
+        """
+        在 Creem 创建商品
+        POST /v1/products
+        """
+        api_key = cls.get_api_key(provider_config)
+        base_url = cls.get_base_url(provider_config)
+
+        if not api_key:
+            raise BizLogicError("Creem API Key is not configured")
+
+        url = f"{base_url}/v1/products"
+        headers = {
+            "x-api-key": api_key,
+            "Content-Type": "application/json",
+        }
+        payload = {
+            "name": name,
+            "price": price_cents,
+            "currency": currency.upper(),
+            "billing_type": billing_type,
+        }
+        if description:
+            payload["description"] = description[:500]
+
+        logger.info(f"💳 [CREEM] Creating product on {url}: name={name} price={price_cents} {currency}")
+
+        timeout = aiohttp.ClientTimeout(total=15)
+        async with aiohttp.ClientSession(timeout=timeout) as session:
+            async with session.post(url, headers=headers, json=payload) as resp:
+                resp_text = await resp.text()
+                if resp.status >= 400:
+                    logger.error(f"❌ [CREEM] Product creation failed ({resp.status}): {resp_text}")
+                    raise BizLogicError(f"Creem create product failed: {resp_text}")
+                
+                try:
+                    data = json.loads(resp_text)
+                    logger.info(f"✅ [CREEM] Product created: id={data.get('id')}")
+                    return data
+                except Exception as e:
+                    logger.error(f"❌ [CREEM] Parse product response error: {e}")
+                    raise BizLogicError("Invalid response from Creem API")
+
+    @classmethod
+    async def create_checkout_session(
+        cls,
+        product_id: str,
+        request_id: str,
+        success_url: str,
+        customer_email: Optional[str] = None,
+        metadata: Optional[Dict[str, Any]] = None,
+        provider_config: Optional[Dict[str, Any]] = None,
+    ) -> Dict[str, Any]:
+        """
+        创建 Creem 收银台 Checkout Session
+        POST /v1/checkouts
+        """
+        api_key = cls.get_api_key(provider_config)
+        base_url = cls.get_base_url(provider_config)
+
+        if not api_key:
+            raise BizLogicError("Creem API Key is not configured")
+
+        url = f"{base_url}/v1/checkouts"
+        headers = {
+            "x-api-key": api_key,
+            "Content-Type": "application/json",
+        }
+        payload: Dict[str, Any] = {
+            "product_id": product_id,
+            "request_id": request_id,
+            "success_url": success_url,
+        }
+        if customer_email:
+            payload["customer"] = {"email": customer_email}
+        if metadata:
+            payload["metadata"] = metadata
+
+        logger.info(f"💳 [CREEM] Creating checkout on {url} for product={product_id} request_id={request_id}")
+
+        timeout = aiohttp.ClientTimeout(total=15)
+        async with aiohttp.ClientSession(timeout=timeout) as session:
+            async with session.post(url, headers=headers, json=payload) as resp:
+                resp_text = await resp.text()
+                if resp.status >= 400:
+                    logger.error(f"❌ [CREEM] Checkout creation failed ({resp.status}): {resp_text}")
+                    raise BizLogicError(f"Creem create checkout failed: {resp_text}")
+
+                try:
+                    data = json.loads(resp_text)
+                    logger.info(f"✅ [CREEM] Checkout created: id={data.get('id')} url={data.get('checkout_url')}")
+                    return data
+                except Exception as e:
+                    logger.error(f"❌ [CREEM] Parse checkout response error: {e}")
+                    raise BizLogicError("Invalid response from Creem API")

+ 68 - 0
app/core/migration.py

@@ -0,0 +1,68 @@
+# app/core/migration.py
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncConnection
+from app.core.logger import logger
+
+
+async def run_settlement_migrations(conn: AsyncConnection):
+    """
+    检查并为已有数据表增量添加字段,保证已有生产/开发数据库无缝平滑升级
+    """
+    logger.info("⏳ [MIGRATION] Checking database schema for settlement fields...")
+    try:
+        # 1. 检查 vas_order 表的列
+        res = await conn.execute(text("SHOW COLUMNS FROM vas_order"))
+        existing_order_cols = {row[0] for row in res.fetchall()}
+
+        # 待添加字段及其 DDL
+        order_cols_to_add = [
+            ("channel_type", "ALTER TABLE vas_order ADD COLUMN channel_type VARCHAR(32) NOT NULL DEFAULT 'direct' COMMENT 'direct:社交自收直客, agency:中介渠道, website:官网公海'"),
+            ("agency_id", "ALTER TABLE vas_order ADD COLUMN agency_id VARCHAR(64) NULL COMMENT '中介机构ID'"),
+            ("handler_id", "ALTER TABLE vas_order ADD COLUMN handler_id VARCHAR(128) NULL COMMENT '40%销售提成归属人ID'"),
+            ("developer_id", "ALTER TABLE vas_order ADD COLUMN developer_id VARCHAR(128) NULL COMMENT '20%技术版权归属人ID'"),
+            ("settlement_status", "ALTER TABLE vas_order ADD COLUMN settlement_status VARCHAR(32) NOT NULL DEFAULT 'unsettled' COMMENT '结算状态: unsettled, risk_period, eligible, settled'"),
+            ("completed_at", "ALTER TABLE vas_order ADD COLUMN completed_at DATETIME NULL COMMENT '履约完成时间'"),
+            ("risk_cleared_at", "ALTER TABLE vas_order ADD COLUMN risk_cleared_at DATETIME NULL COMMENT '退款风险期截止时间'"),
+            ("settlement_period_id", "ALTER TABLE vas_order ADD COLUMN settlement_period_id VARCHAR(32) NULL COMMENT '结算账期ID'"),
+        ]
+
+        for col_name, ddl in order_cols_to_add:
+            if col_name not in existing_order_cols:
+                logger.info(f"➕ [MIGRATION] Adding column '{col_name}' to table 'vas_order'...")
+                await conn.execute(text(ddl))
+
+        # 为 handler_id 补建索引(若未建)
+        try:
+            await conn.execute(text("CREATE INDEX idx_vas_order_handler ON vas_order (handler_id)"))
+        except Exception:
+            pass  # 索引已存在时忽略
+
+        # 为 settlement_status 补建索引
+        try:
+            await conn.execute(text("CREATE INDEX idx_vas_order_settlement_status ON vas_order (settlement_status)"))
+        except Exception:
+            pass
+
+        # 2. 检查 vas_product 是否有 min_floor_price
+        res_prod = await conn.execute(text("SHOW COLUMNS FROM vas_product"))
+        existing_prod_cols = {row[0] for row in res_prod.fetchall()}
+        if "min_floor_price" not in existing_prod_cols:
+            logger.info("➕ [MIGRATION] Adding column 'min_floor_price' to table 'vas_product'...")
+            await conn.execute(text("ALTER TABLE vas_product ADD COLUMN min_floor_price INT NOT NULL DEFAULT 0 COMMENT '内部最低底价(分)'"))
+        if "developer_id" not in existing_prod_cols:
+            logger.info("➕ [MIGRATION] Adding column 'developer_id' to table 'vas_product'...")
+            await conn.execute(text("ALTER TABLE vas_product ADD COLUMN developer_id VARCHAR(128) NULL COMMENT '该产品默认脚本开发者'"))
+
+        # 3. 检查 plugins 是否有 class_name 和 protocol
+        res_plug = await conn.execute(text("SHOW COLUMNS FROM plugins"))
+        existing_plug_cols = {row[0] for row in res_plug.fetchall()}
+        if "class_name" not in existing_plug_cols:
+            logger.info("➕ [MIGRATION] Adding column 'class_name' to table 'plugins'...")
+            await conn.execute(text("ALTER TABLE plugins ADD COLUMN class_name VARCHAR(128) NOT NULL DEFAULT '' COMMENT '插件入口类名' AFTER filename"))
+        if "protocol" not in existing_plug_cols:
+            logger.info("➕ [MIGRATION] Adding column 'protocol' to table 'plugins'...")
+            await conn.execute(text("ALTER TABLE plugins ADD COLUMN protocol VARCHAR(64) NOT NULL DEFAULT 'IPlugin' COMMENT '插件协议标识' AFTER class_name"))
+
+        logger.info("✅ [MIGRATION] Settlement & Plugin schema migration completed successfully.")
+    except Exception as e:
+        logger.error(f"❌ [MIGRATION ERROR] Failed to run settlement migrations: {e}", exc_info=True)

+ 17 - 7
app/main.py

@@ -17,18 +17,28 @@ from app.core.biz_exception import BizException
 from app.core.logger import logger, access_logger
 from app.core.logger import logger, access_logger
 
 
 
 
+from app.core.migration import run_settlement_migrations
+
+
 @asynccontextmanager
 @asynccontextmanager
 async def lifespan(app: FastAPI):
 async def lifespan(app: FastAPI):
     init_stripe()
     init_stripe()
     logger.info("🟢 Stripe config done")
     logger.info("🟢 Stripe config done")
 
 
-    # 自动校验/创建缺失的数据表
-    try:
-        async with engine.begin() as conn:
-            await conn.run_sync(Base.metadata.create_all)
-        logger.info("🟢 Database tables checked/created")
-    except Exception as e:
-        logger.error(f"⚠️ Database tables init error: {e}")
+    async def init_db_async():
+        try:
+            logger.info("⏳ [LIFESPAN] Asynchronously checking database & migrations in background...")
+            import asyncio
+            async with asyncio.timeout(30):
+                async with engine.begin() as conn:
+                    await conn.run_sync(Base.metadata.create_all)
+                    await run_settlement_migrations(conn)
+            logger.info("🟢 Database tables & settlement schema checked/updated")
+        except Exception as e:
+            logger.error(f"⚠️ Database tables init error: {e}")
+
+    import asyncio
+    asyncio.create_task(init_db_async())
 
 
     yield
     yield
 
 

+ 5 - 0
app/models/__init__.py

@@ -12,6 +12,11 @@ from .node_configuration import (
     SentinelEntry,
     SentinelEntry,
     StandaloneEntry,
     StandaloneEntry,
     NodeConfigurationRevision,
     NodeConfigurationRevision,
+    ClusterNodeEntry,
 )
 )
 from .provider import Provider
 from .provider import Provider
 from .proxy_reputation import ProxyReputation, ProxyTelemetryLog
 from .proxy_reputation import ProxyReputation, ProxyTelemetryLog
+from .agency import VasAgency
+from .cost import VasCostRecord
+from .fault import VasFaultCompensation
+from .settlement import VasSettlementPeriod, VasSettlementDetail

+ 16 - 0
app/models/account.py

@@ -6,6 +6,22 @@ from app.core.database import Base
 
 
 class Account(Base):
 class Account(Base):
     __tablename__ = "account"
     __tablename__ = "account"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `account` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `pool_name` VARCHAR(50) NOT NULL,
+      `username` VARCHAR(100) NOT NULL,
+      `password` VARCHAR(255) NULL,
+      `extra_data` JSON NULL,
+      `next_use_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '下次允许使用的时间',
+      `status` ENUM('active','disable') NOT NULL DEFAULT 'active',
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      KEY `idx_account_pool_name` (`pool_name`),
+      KEY `idx_account_status` (`status`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='账号池表';
+    """
 
 
     id = Column(Integer, primary_key=True, index=True)
     id = Column(Integer, primary_key=True, index=True)
     pool_name = Column(String(50), nullable=False, index=True)
     pool_name = Column(String(50), nullable=False, index=True)

+ 42 - 0
app/models/agency.py

@@ -0,0 +1,42 @@
+# app/models/agency.py
+from datetime import datetime
+from sqlalchemy import Column, String, Integer, SmallInteger, DateTime, Text
+from app.core.database import Base
+
+
+class VasAgency(Base):
+    __tablename__ = "vas_agency"
+    __ddl__ = """
+CREATE TABLE IF NOT EXISTS `vas_agency` (
+  `id` VARCHAR(64) NOT NULL,
+  `name` VARCHAR(128) NOT NULL,
+  `contact_name` VARCHAR(64) NULL,
+  `contact_phone` VARCHAR(32) NULL,
+  `owner_id` VARCHAR(128) NOT NULL COMMENT '中介对接拓展人 (独享40%提成)',
+  `min_floor_price` INT NOT NULL DEFAULT 0 COMMENT '协议底价(分)',
+  `status` SMALLINT NOT NULL DEFAULT 1 COMMENT '1:合作中, 0:停用',
+  `notes` TEXT NULL,
+  `created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `uk_vas_agency_name` (`name`),
+  INDEX `idx_vas_agency_owner` (`owner_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='合作中介机构表';
+"""
+
+    id = Column(String(64), primary_key=True)
+    name = Column(String(128), nullable=False, unique=True, index=True)
+    contact_name = Column(String(64), nullable=True)
+    contact_phone = Column(String(32), nullable=True)
+    
+    # 该中介归属的专属拓展/维系人 (40%销售提成归其个人)
+    owner_id = Column(String(128), nullable=False, index=True)
+    
+    # 该中介默认协议最低底价 (分),若为0则沿用产品默认底价
+    min_floor_price = Column(Integer, default=0, nullable=False)
+    
+    status = Column(SmallInteger, default=1, nullable=False)  # 1:合作中, 0:终止合作
+    notes = Column(Text, nullable=True)
+
+    created_at = Column(DateTime, default=datetime.utcnow)
+    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

+ 13 - 0
app/models/configuration.py

@@ -4,6 +4,19 @@ from app.core.database import Base
 
 
 class Configuration(Base):
 class Configuration(Base):
     __tablename__ = "configuration"
     __tablename__ = "configuration"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `configuration` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `config_key` VARCHAR(255) NOT NULL COMMENT '配置键',
+      `config_value` MEDIUMTEXT NOT NULL COMMENT '配置值',
+      `description` TEXT NULL COMMENT '描述',
+      `type` VARCHAR(50) NULL COMMENT '类型',
+      `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+      `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
+      PRIMARY KEY (`id`),
+      UNIQUE KEY `uq_configuration_config_key` (`config_key`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统配置字典表';
+    """
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     config_key = Column(String(255), unique=True, nullable=False, comment="配置键")
     config_key = Column(String(255), unique=True, nullable=False, comment="配置键")

+ 43 - 0
app/models/cost.py

@@ -0,0 +1,43 @@
+# app/models/cost.py
+from datetime import datetime
+from sqlalchemy import Column, Integer, String, DateTime, Text, Enum
+from app.core.database import Base
+
+
+class VasCostRecord(Base):
+    __tablename__ = "vas_cost_record"
+    __ddl__ = """
+CREATE TABLE IF NOT EXISTS `vas_cost_record` (
+  `id` INT NOT NULL AUTO_INCREMENT,
+  `period_id` VARCHAR(32) NULL COMMENT '绑定的结算账期',
+  `category` ENUM('vps', 'proxy_ip', 'captcha_api', 'sms_api', 'other') NOT NULL,
+  `amount` INT NOT NULL COMMENT '金额 (分)',
+  `currency` VARCHAR(8) NOT NULL DEFAULT 'CNY',
+  `description` VARCHAR(255) NULL,
+  `voucher_url` VARCHAR(512) NULL,
+  `paid_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `created_by` VARCHAR(128) NOT NULL,
+  `created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  INDEX `idx_vas_cost_period_id` (`period_id`),
+  INDEX `idx_vas_cost_paid_at` (`paid_at`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='公共耗材支出表';
+"""
+
+    id = Column(Integer, primary_key=True, autoincrement=True)
+    # 归属的结算账期ID (未结算前可为NULL,期末结算时绑定)
+    period_id = Column(String(32), nullable=True, index=True)
+    
+    # 耗材类别
+    category = Column(
+        Enum('vps', 'proxy_ip', 'captcha_api', 'sms_api', 'other', name='cost_category_enum'),
+        nullable=False
+    )
+    amount = Column(Integer, nullable=False)  # 支出金额 (单位: 分)
+    currency = Column(String(8), default="CNY", nullable=False)
+    description = Column(String(255), nullable=True)
+    voucher_url = Column(String(512), nullable=True)  # 支付/充值截图凭证
+    paid_at = Column(DateTime, nullable=False, default=datetime.utcnow)  # 实际支出时间
+    created_by = Column(String(128), nullable=False)  # 录入人
+
+    created_at = Column(DateTime, default=datetime.utcnow)

+ 19 - 0
app/models/email_authorizations.py

@@ -4,6 +4,25 @@ from app.core.database import Base
 
 
 class EmailAuthorization(Base):
 class EmailAuthorization(Base):
     __tablename__ = "email_authorizations"
     __tablename__ = "email_authorizations"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `email_authorizations` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `email` VARCHAR(255) NOT NULL COMMENT '邮箱地址',
+      `authorization_code` VARCHAR(255) NOT NULL COMMENT '授权码',
+      `imap_server` VARCHAR(255) NULL COMMENT 'IMAP服务器地址',
+      `imap_port` INT NOT NULL DEFAULT 993 COMMENT 'IMAP端口',
+      `smtp_server` VARCHAR(255) NULL COMMENT 'SMTP服务器地址',
+      `smtp_port` INT NOT NULL DEFAULT 465 COMMENT 'SMTP端口',
+      `proxy_host` VARCHAR(255) NULL COMMENT '代理主机',
+      `proxy_port` INT NOT NULL DEFAULT 0 COMMENT '代理端口',
+      `proxy_username` VARCHAR(255) NULL COMMENT '代理用户名',
+      `proxy_password` VARCHAR(255) NULL COMMENT '代理密码',
+      `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+      `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
+      PRIMARY KEY (`id`),
+      UNIQUE KEY `uq_email_auth_email` (`email`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='邮箱IMAP/SMTP授权管理表';
+    """
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     email = Column(String(255), unique=True, nullable=False, comment="邮箱地址")
     email = Column(String(255), unique=True, nullable=False, comment="邮箱地址")

+ 13 - 0
app/models/emails.py

@@ -5,6 +5,19 @@ from app.core.database import Base
 
 
 class VasEmail(Base):
 class VasEmail(Base):
     __tablename__ = "emails"
     __tablename__ = "emails"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `emails` (
+      `uid` BIGINT NOT NULL COMMENT '邮件UID',
+      `subject` VARCHAR(1024) NULL COMMENT '邮件标题',
+      `sender` VARCHAR(255) NULL COMMENT '发件人',
+      `recipient` VARCHAR(500) NULL COMMENT '收件人(别名)',
+      `receive_time` VARCHAR(100) NULL COMMENT '接收时间字符串',
+      `body_text` LONGTEXT NULL COMMENT '邮件正文',
+      `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '入库时间',
+      PRIMARY KEY (`uid`),
+      KEY `idx_emails_recipient` (`recipient`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='邮箱抓取原始邮件存证表';
+    """
 
 
     uid = Column(BigInteger, primary_key=True, comment="邮件UID")
     uid = Column(BigInteger, primary_key=True, comment="邮件UID")
     subject = Column(String(1024), comment="邮件标题")
     subject = Column(String(1024), comment="邮件标题")

+ 37 - 0
app/models/fault.py

@@ -0,0 +1,37 @@
+# app/models/fault.py
+from datetime import datetime
+from sqlalchemy import Column, Integer, String, DateTime, SmallInteger, Text
+from app.core.database import Base
+
+
+class VasFaultCompensation(Base):
+    __tablename__ = "vas_fault_compensation"
+    __ddl__ = """
+CREATE TABLE IF NOT EXISTS `vas_fault_compensation` (
+  `id` INT NOT NULL AUTO_INCREMENT,
+  `order_id` VARCHAR(128) NOT NULL,
+  `liable_user_id` VARCHAR(128) NOT NULL COMMENT '责任人',
+  `penalty_amount` INT NOT NULL COMMENT '扣罚金额 (分)',
+  `reason` VARCHAR(255) NOT NULL,
+  `notes` TEXT NULL,
+  `period_id` VARCHAR(32) NULL COMMENT '冲销账期',
+  `deducted_status` SMALLINT NOT NULL DEFAULT 0 COMMENT '0:待扣除, 1:已从提成中扣除',
+  `created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  INDEX `idx_vas_fault_order_id` (`order_id`),
+  INDEX `idx_vas_fault_liable_user` (`liable_user_id`),
+  INDEX `idx_vas_fault_period_id` (`period_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='过失录错赔偿冲销表';
+"""
+
+    id = Column(Integer, primary_key=True, autoincrement=True)
+    order_id = Column(String(128), nullable=False, index=True)
+    liable_user_id = Column(String(128), nullable=False, index=True)  # 录错/过失责任人
+    penalty_amount = Column(Integer, nullable=False)  # 应由个人全额承担的赔偿金额 (分)
+    reason = Column(String(255), nullable=False)      # 过错原因(如: 护照号录错导致废单)
+    notes = Column(Text, nullable=True)
+    
+    period_id = Column(String(32), nullable=True, index=True) # 在哪个结算账期冲销
+    deducted_status = Column(SmallInteger, default=0, nullable=False)  # 0:待扣除, 1:已从提成中扣除
+
+    created_at = Column(DateTime, default=datetime.utcnow)

+ 13 - 0
app/models/http_session.py

@@ -4,6 +4,19 @@ from datetime import datetime
 
 
 class HttpSession(Base):
 class HttpSession(Base):
     __tablename__ = "http_session"
     __tablename__ = "http_session"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `http_session` (
+      `session_id` VARCHAR(128) NOT NULL,
+      `local_storage` MEDIUMTEXT NULL,
+      `session_storage` MEDIUMTEXT NULL,
+      `cookies` MEDIUMTEXT NULL,
+      `user_agent` VARCHAR(512) NULL,
+      `proxy` VARCHAR(256) NULL,
+      `page` MEDIUMTEXT NULL,
+      `create_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      PRIMARY KEY (`session_id`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='自动化执行浏览器会话状态表';
+    """
 
 
     session_id = Column(String(128), primary_key=True)
     session_id = Column(String(128), primary_key=True)
     local_storage = Column(Text)
     local_storage = Column(Text)

+ 139 - 0
app/models/node_configuration.py

@@ -15,6 +15,35 @@ from app.core.database import Base
 
 
 class BookerEntry(Base):
 class BookerEntry(Base):
     __tablename__ = "booker_entries"
     __tablename__ = "booker_entries"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `booker_entries` (
+      `id` BIGINT NOT NULL AUTO_INCREMENT,
+      `node_id` VARCHAR(64) NOT NULL,
+      `identifier` VARCHAR(64) NOT NULL,
+      `enable` SMALLINT NOT NULL DEFAULT 0,
+      `debug` SMALLINT NOT NULL DEFAULT 0,
+      `need_account` SMALLINT NOT NULL DEFAULT 1,
+      `need_proxy` SMALLINT NOT NULL DEFAULT 1,
+      `proxy_pool` JSON NOT NULL,
+      `proxy_cd` INT NOT NULL DEFAULT 300,
+      `session_max_life` INT NOT NULL DEFAULT 1800,
+      `active_time_start` VARCHAR(5) NOT NULL DEFAULT '00:00',
+      `active_time_end` VARCHAR(5) NOT NULL DEFAULT '23:59',
+      `website` VARCHAR(512) NOT NULL DEFAULT '',
+      `booker` JSON NOT NULL,
+      `plugin_config` JSON NOT NULL,
+      `appointment_types` JSON NOT NULL,
+      `free_config` JSON NOT NULL,
+      `version` INT NOT NULL DEFAULT 0,
+      `updated_by` VARCHAR(64) NULL DEFAULT 'system',
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      UNIQUE KEY `uk_booker_node_identifier` (`node_id`,`identifier`),
+      KEY `idx_booker_identifier` (`identifier`),
+      KEY `idx_booker_updated_at` (`updated_at`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Booker节点配置表';
+    """
 
 
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     node_id = Column(String(64), nullable=False)
     node_id = Column(String(64), nullable=False)
@@ -49,6 +78,35 @@ class BookerEntry(Base):
 
 
 class SentinelEntry(Base):
 class SentinelEntry(Base):
     __tablename__ = "sentinel_entries"
     __tablename__ = "sentinel_entries"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `sentinel_entries` (
+      `id` BIGINT NOT NULL AUTO_INCREMENT,
+      `node_id` VARCHAR(64) NOT NULL,
+      `identifier` VARCHAR(64) NOT NULL,
+      `enable` SMALLINT NOT NULL DEFAULT 0,
+      `debug` SMALLINT NOT NULL DEFAULT 0,
+      `need_account` SMALLINT NOT NULL DEFAULT 1,
+      `need_proxy` SMALLINT NOT NULL DEFAULT 1,
+      `proxy_pool` JSON NOT NULL,
+      `proxy_cd` INT NOT NULL DEFAULT 300,
+      `session_max_life` INT NOT NULL DEFAULT 1800,
+      `active_time_start` VARCHAR(5) NOT NULL DEFAULT '00:00',
+      `active_time_end` VARCHAR(5) NOT NULL DEFAULT '23:59',
+      `website` VARCHAR(512) NOT NULL DEFAULT '',
+      `sentinel` JSON NOT NULL,
+      `plugin_config` JSON NOT NULL,
+      `appointment_types` JSON NOT NULL,
+      `free_config` JSON NOT NULL,
+      `version` INT NOT NULL DEFAULT 0,
+      `updated_by` VARCHAR(64) NULL DEFAULT 'system',
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      UNIQUE KEY `uk_sentinel_node_identifier` (`node_id`,`identifier`),
+      KEY `idx_sentinel_identifier` (`identifier`),
+      KEY `idx_sentinel_updated_at` (`updated_at`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Sentinel监听节点配置表';
+    """
 
 
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     node_id = Column(String(64), nullable=False)
     node_id = Column(String(64), nullable=False)
@@ -83,6 +141,36 @@ class SentinelEntry(Base):
 
 
 class StandaloneEntry(Base):
 class StandaloneEntry(Base):
     __tablename__ = "standalone_entries"
     __tablename__ = "standalone_entries"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `standalone_entries` (
+      `id` BIGINT NOT NULL AUTO_INCREMENT,
+      `node_id` VARCHAR(64) NOT NULL,
+      `order_id` VARCHAR(64) NULL,
+      `identifier` VARCHAR(64) NOT NULL,
+      `enable` SMALLINT NOT NULL DEFAULT 1,
+      `debug` SMALLINT NOT NULL DEFAULT 0,
+      `plugin_config` JSON NOT NULL,
+      `account` JSON NOT NULL,
+      `proxy_pool` JSON NOT NULL,
+      `query_wait` JSON NOT NULL,
+      `login_interval` INT NOT NULL DEFAULT 1800,
+      `session_max_life` INT NOT NULL DEFAULT 1800,
+      `active_time_start` VARCHAR(5) NOT NULL DEFAULT '00:00',
+      `active_time_end` VARCHAR(5) NOT NULL DEFAULT '23:59',
+      `appointment_types` JSON NOT NULL,
+      `user_preferences` JSON NOT NULL,
+      `free_config` JSON NOT NULL,
+      `version` INT NOT NULL DEFAULT 0,
+      `updated_by` VARCHAR(64) NULL DEFAULT 'system',
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      UNIQUE KEY `uk_standalone_node_identifier` (`node_id`,`identifier`),
+      KEY `idx_standalone_identifier` (`identifier`),
+      KEY `idx_standalone_order_id` (`order_id`),
+      KEY `idx_standalone_updated_at` (`updated_at`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='独立节点配置表';
+    """
 
 
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     node_id = Column(String(64), nullable=False)
     node_id = Column(String(64), nullable=False)
@@ -118,6 +206,20 @@ class StandaloneEntry(Base):
 
 
 class NodeConfigurationRevision(Base):
 class NodeConfigurationRevision(Base):
     __tablename__ = "node_configuration_revisions"
     __tablename__ = "node_configuration_revisions"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `node_configuration_revisions` (
+      `id` BIGINT NOT NULL AUTO_INCREMENT,
+      `entry_type` VARCHAR(32) NOT NULL,
+      `entry_id` BIGINT NOT NULL,
+      `version` INT NOT NULL DEFAULT 0,
+      `action` VARCHAR(32) NOT NULL DEFAULT 'update',
+      `snapshot` JSON NOT NULL,
+      `updated_by` VARCHAR(64) NULL DEFAULT 'system',
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      KEY `idx_node_config_rev_type_id` (`entry_type`,`entry_id`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='节点配置版本历史表';
+    """
 
 
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     entry_type = Column(String(32), nullable=False, index=True)
     entry_type = Column(String(32), nullable=False, index=True)
@@ -131,3 +233,40 @@ class NodeConfigurationRevision(Base):
     __table_args__ = (
     __table_args__ = (
         Index("idx_node_config_rev_type_id", "entry_type", "entry_id"),
         Index("idx_node_config_rev_type_id", "entry_type", "entry_id"),
     )
     )
+
+
+class ClusterNodeEntry(Base):
+    __tablename__ = "cluster_nodes"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `cluster_nodes` (
+      `id` BIGINT NOT NULL AUTO_INCREMENT,
+      `node_id` VARCHAR(64) NOT NULL,
+      `name` VARCHAR(128) NOT NULL,
+      `ip_address` VARCHAR(64) NULL,
+      `region` VARCHAR(64) NULL,
+      `status` SMALLINT NOT NULL DEFAULT 1 COMMENT '1:启用, 0:停用',
+      `notes` VARCHAR(512) NULL,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      UNIQUE KEY `uk_cluster_node_id` (`node_id`),
+      KEY `idx_cluster_node_status` (`status`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='集群节点注册档案表';
+    """
+
+    id = Column(BigInteger, primary_key=True, autoincrement=True)
+    node_id = Column(String(64), nullable=False)
+    name = Column(String(128), nullable=False)
+    ip_address = Column(String(64), nullable=True)
+    region = Column(String(64), nullable=True)
+    status = Column(SmallInteger, nullable=False, default=1)
+    notes = Column(String(512), nullable=True)
+    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
+    updated_at = Column(
+        DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
+    )
+
+    __table_args__ = (
+        UniqueConstraint("node_id", name="uk_cluster_node_id"),
+        Index("idx_cluster_node_status", "status"),
+    )

+ 17 - 0
app/models/notification_outbox.py

@@ -5,6 +5,23 @@ from app.core.database import Base
 
 
 class NotificationOutbox(Base):
 class NotificationOutbox(Base):
     __tablename__ = "notification_outbox"
     __tablename__ = "notification_outbox"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `notification_outbox` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `msg_id` VARCHAR(64) NOT NULL,
+      `channel` VARCHAR(32) NOT NULL,
+      `payload` JSON NOT NULL,
+      `priority` INT NOT NULL DEFAULT 10,
+      `status` VARCHAR(16) NOT NULL DEFAULT 'pending',
+      `attempts` INT NOT NULL DEFAULT 0,
+      `next_retry_at` DATETIME NULL,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      UNIQUE KEY `uq_notif_outbox_msg_id` (`msg_id`),
+      KEY `idx_notif_outbox_status_next_retry` (`status`,`next_retry_at`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='通知发件箱/重试队列';
+    """
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     msg_id = Column(String(64), nullable=False, unique=True)
     msg_id = Column(String(64), nullable=False, unique=True)

+ 56 - 0
app/models/order.py

@@ -5,6 +5,38 @@ from app.core.database import Base
 
 
 class VasOrder(Base):
 class VasOrder(Base):
     __tablename__ = "vas_order"
     __tablename__ = "vas_order"
+    __ddl__ = """
+CREATE TABLE IF NOT EXISTS `vas_order` (
+  `id` VARCHAR(128) NOT NULL,
+  `user_id` VARCHAR(128) NOT NULL,
+  `product_id` INT NOT NULL,
+  `product_name` VARCHAR(100) NULL,
+  `user_name` VARCHAR(100) NULL,
+  `base_amount` INT NOT NULL,
+  `adjustment_delta` INT NOT NULL DEFAULT 0,
+  `final_amount` INT NOT NULL,
+  `base_currency` VARCHAR(10) NOT NULL,
+  `status` ENUM('pending', 'paid', 'completed', 'closed') NOT NULL DEFAULT 'pending',
+  `channel_type` VARCHAR(32) NOT NULL DEFAULT 'direct' COMMENT 'direct:社交自收直客, agency:中介渠道, website:官网公海',
+  `agency_id` VARCHAR(64) NULL COMMENT '中介机构ID',
+  `handler_id` VARCHAR(128) NULL COMMENT '40%销售提成对接人ID',
+  `developer_id` VARCHAR(128) NULL COMMENT '20%技术版权脚本开发者ID',
+  `settlement_status` VARCHAR(32) NOT NULL DEFAULT 'unsettled' COMMENT '结算状态: unsettled, risk_period, eligible, settled',
+  `completed_at` DATETIME NULL,
+  `risk_cleared_at` DATETIME NULL,
+  `settlement_period_id` VARCHAR(32) NULL,
+  `user_inputs` JSON NULL,
+  `created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  INDEX `idx_vas_order_user_id` (`user_id`),
+  INDEX `idx_vas_order_product_id` (`product_id`),
+  INDEX `idx_vas_order_status` (`status`),
+  INDEX `idx_vas_order_handler_id` (`handler_id`),
+  INDEX `idx_vas_order_settlement_status` (`settlement_status`),
+  INDEX `idx_vas_order_completed_at` (`completed_at`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='主订单表';
+"""
 
 
     id = Column(String(128), primary_key=True)
     id = Column(String(128), primary_key=True)
     user_id = Column(String(128), nullable=False)
     user_id = Column(String(128), nullable=False)
@@ -27,6 +59,30 @@ class VasOrder(Base):
         nullable=False
         nullable=False
     )
     )
 
 
+    # 渠道来源: direct(社交自收直客), agency(中介渠道), website(官网公海)
+    channel_type = Column(
+        String(32),
+        default='direct',
+        nullable=False
+    )
+    # 中介机构ID (仅中介单时有值)
+    agency_id = Column(String(64), nullable=True)
+    # 40%销售提成对接人 (直客为录单对接人,中介单为该中介拓展人,公海单为NULL)
+    handler_id = Column(String(128), nullable=True, index=True)
+    # 20%技术版权脚本开发者ID
+    developer_id = Column(String(128), nullable=True)
+
+    # 结算状态: unsettled(未结算), risk_period(风险期冻结), eligible(待结算), settled(已结算)
+    settlement_status = Column(
+        String(32),
+        default='unsettled',
+        nullable=False,
+        index=True
+    )
+    completed_at = Column(DateTime, nullable=True)
+    risk_cleared_at = Column(DateTime, nullable=True)
+    settlement_period_id = Column(String(32), nullable=True)
+
     user_inputs = Column(JSON)
     user_inputs = Column(JSON)
 
 
     created_at = Column(DateTime, default=datetime.utcnow)
     created_at = Column(DateTime, default=datetime.utcnow)

+ 14 - 0
app/models/order_event.py

@@ -3,6 +3,20 @@ from app.core.database import Base
 
 
 class VasOrderEvent(Base):
 class VasOrderEvent(Base):
     __tablename__ = "vas_order_events"
     __tablename__ = "vas_order_events"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_order_events` (
+      `id` BIGINT NOT NULL AUTO_INCREMENT,
+      `order_no` VARCHAR(100) NOT NULL,
+      `event_title` VARCHAR(255) NOT NULL,
+      `event_message` TEXT NULL,
+      `email_uid` BIGINT NOT NULL,
+      `event_time` DATETIME NULL,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      UNIQUE KEY `uq_vas_order_events_email_uid` (`email_uid`),
+      KEY `idx_vas_order_events_order_no` (`order_no`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单邮箱与外部追踪事件表';
+    """
 
 
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     order_no = Column(String(100), nullable=False)
     order_no = Column(String(100), nullable=False)

+ 31 - 0
app/models/payment.py

@@ -4,6 +4,37 @@ from app.core.database import Base
 
 
 class VasPayment(Base):
 class VasPayment(Base):
     __tablename__ = "vas_payment"
     __tablename__ = "vas_payment"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_payment` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `order_id` VARCHAR(128) NOT NULL,
+      `provider` ENUM('stripe','wechat','alipay') NOT NULL,
+      `channel` VARCHAR(50) NOT NULL,
+      `payment_intent_id` VARCHAR(255) NULL,
+      `external_trade_no` VARCHAR(255) NULL,
+      `status` ENUM('pending','succeeded','failed','expired','late_paid','refunded') NOT NULL DEFAULT 'pending',
+      `base_amount` INT NOT NULL,
+      `adjustment_delta` INT NOT NULL DEFAULT 0,
+      `final_amount` INT NOT NULL,
+      `base_currency` VARCHAR(10) NOT NULL,
+      `amount` INT NOT NULL,
+      `currency` VARCHAR(10) NOT NULL,
+      `random_offset` INT NOT NULL,
+      `exchange_rate` DECIMAL(18,8) NOT NULL,
+      `qr_id` INT NULL,
+      `payment_url` TEXT NULL,
+      `expire_at` DATETIME NULL,
+      `provider_payload` JSON NULL,
+      `external_refund_no` VARCHAR(255) NULL,
+      `refunded_at` DATETIME NULL,
+      `refund_reason` VARCHAR(255) NULL,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      KEY `idx_vas_payment_order_id` (`order_id`),
+      KEY `idx_vas_payment_status` (`status`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='支付交易记录表';
+    """
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     order_id = Column(String(128), nullable=False)
     order_id = Column(String(128), nullable=False)

+ 18 - 0
app/models/payment_confirmation.py

@@ -4,6 +4,24 @@ from app.core.database import Base
 
 
 class VasPaymentConfirmation(Base):
 class VasPaymentConfirmation(Base):
     __tablename__ = "vas_payment_confirm"
     __tablename__ = "vas_payment_confirm"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_payment_confirm` (
+      `id` BIGINT NOT NULL AUTO_INCREMENT,
+      `payment_id` BIGINT NOT NULL,
+      `amount` INT NOT NULL,
+      `currency` VARCHAR(10) NOT NULL,
+      `random_offset` INT NOT NULL,
+      `user_id` VARCHAR(128) NOT NULL,
+      `status` ENUM('pending','confirmed','ignored') NOT NULL DEFAULT 'pending',
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `confirmed_at` DATETIME NULL,
+      `admin_id` VARCHAR(128) NULL,
+      `admin_confirmed_at` DATETIME NULL,
+      PRIMARY KEY (`id`),
+      KEY `idx_vas_pay_conf_payment` (`payment_id`),
+      KEY `idx_vas_pay_conf_user` (`user_id`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='人工支付确认审核记录表';
+    """
 
 
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     payment_id = Column(BigInteger, nullable=False)
     payment_id = Column(BigInteger, nullable=False)

+ 23 - 0
app/models/payment_event.py

@@ -8,6 +8,29 @@ from app.core.database import Base
 
 
 class VasPaymentEvent(Base):
 class VasPaymentEvent(Base):
     __tablename__ = "vas_payment_event"
     __tablename__ = "vas_payment_event"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_payment_event` (
+      `id` BIGINT NOT NULL AUTO_INCREMENT,
+      `provider` VARCHAR(32) NOT NULL,
+      `event_type` VARCHAR(64) NULL,
+      `event_id` VARCHAR(128) NULL,
+      `title` TEXT NULL,
+      `content` TEXT NULL,
+      `raw_payload` JSON NULL,
+      `parsed_amount` BIGINT NULL,
+      `parsed_currency` VARCHAR(8) NULL,
+      `parsed_device` VARCHAR(64) NULL,
+      `matched_payment_id` BIGINT NULL,
+      `matched_order_id` VARCHAR(128) NULL,
+      `status` VARCHAR(32) NOT NULL DEFAULT 'received',
+      `error_message` TEXT NULL,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      UNIQUE KEY `uq_vas_pay_event_id` (`event_id`),
+      KEY `idx_vas_pay_event_matched_order` (`matched_order_id`),
+      KEY `idx_vas_pay_event_status` (`status`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='网关支付原始异步事件通知记录表';
+    """
 
 
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     id = Column(BigInteger, primary_key=True, autoincrement=True)
 
 

+ 15 - 0
app/models/payment_provider.py

@@ -5,6 +5,21 @@ from app.core.database import Base
 
 
 class VasPaymentProvider(Base):
 class VasPaymentProvider(Base):
     __tablename__ = "vas_payment_provider"
     __tablename__ = "vas_payment_provider"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_payment_provider` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `name` VARCHAR(64) NOT NULL,
+      `title` VARCHAR(100) NULL,
+      `channel` VARCHAR(64) NOT NULL,
+      `currency` VARCHAR(3) NOT NULL,
+      `icon` TEXT NULL,
+      `enabled` INT NOT NULL DEFAULT 1,
+      `config` JSON NULL,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='支付服务商配置表';
+    """
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     name = Column(String(64), nullable=False)
     name = Column(String(64), nullable=False)

+ 13 - 0
app/models/payment_qr.py

@@ -5,6 +5,19 @@ from app.core.database import Base
 
 
 class VasPaymentQR(Base):
 class VasPaymentQR(Base):
     __tablename__ = "vas_payment_qr"
     __tablename__ = "vas_payment_qr"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_payment_qr` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `provider` ENUM('wechat','alipay') NOT NULL,
+      `device` VARCHAR(50) NOT NULL,
+      `qr_code` TEXT NOT NULL,
+      `description` TEXT NOT NULL,
+      `is_active` INT NOT NULL DEFAULT 1,
+      `priority` INT NOT NULL DEFAULT 10,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='静态/固态聚合收款码轮转表';
+    """
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     provider = Column(Enum('wechat', 'alipay'), nullable=False)
     provider = Column(Enum('wechat', 'alipay'), nullable=False)

+ 38 - 0
app/models/plugin.py

@@ -5,20 +5,58 @@ from app.core.database import Base
 
 
 class Plugin(Base):
 class Plugin(Base):
     __tablename__ = "plugins"
     __tablename__ = "plugins"
+    __ddl__ = """
+CREATE TABLE IF NOT EXISTS `plugins` (
+  `id` INT NOT NULL AUTO_INCREMENT,
+  `name` VARCHAR(64) NOT NULL COMMENT '插件唯一英文标识',
+  `display_name` VARCHAR(128) NOT NULL DEFAULT '',
+  `filename` VARCHAR(128) NOT NULL DEFAULT '' COMMENT '插件二进制脚本文件',
+  `class_name` VARCHAR(128) NOT NULL DEFAULT '' COMMENT '插件入口类名',
+  `protocol` VARCHAR(64) NOT NULL DEFAULT 'IPlugin' COMMENT '插件协议标识',
+  `latest_version` VARCHAR(32) NOT NULL DEFAULT '1.0.0',
+  `description` VARCHAR(512) NOT NULL DEFAULT '',
+  `status` SMALLINT NOT NULL DEFAULT 1 COMMENT '1:启用, 0:停用',
+  `developer_id` VARCHAR(128) NULL COMMENT '插件开发管理者ID (享有20%技术分成)',
+  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `uk_plugin_name` (`name`),
+  INDEX `idx_plugins_developer_id` (`developer_id`),
+  INDEX `idx_plugins_status` (`status`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='核心履约插件表';
+"""
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     name = Column(String(64), unique=True, nullable=False, index=True)
     name = Column(String(64), unique=True, nullable=False, index=True)
     display_name = Column(String(128), nullable=False, default="")
     display_name = Column(String(128), nullable=False, default="")
     filename = Column(String(128), nullable=False, default="")
     filename = Column(String(128), nullable=False, default="")
+    class_name = Column(String(128), nullable=False, default="")
+    protocol = Column(String(64), nullable=False, default="IPlugin")
     latest_version = Column(String(32), nullable=False, default="1.0.0")
     latest_version = Column(String(32), nullable=False, default="1.0.0")
     description = Column(String(512), nullable=False, default="")
     description = Column(String(512), nullable=False, default="")
     status = Column(SmallInteger, nullable=False, default=1, index=True)
     status = Column(SmallInteger, nullable=False, default=1, index=True)
+    developer_id = Column(String(128), nullable=True, index=True, comment="插件开发管理者ID")
     created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
     created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
     updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
     updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
 
 
 
 
 class PluginVersion(Base):
 class PluginVersion(Base):
     __tablename__ = "plugin_versions"
     __tablename__ = "plugin_versions"
+    __ddl__ = """
+CREATE TABLE IF NOT EXISTS `plugin_versions` (
+  `id` INT NOT NULL AUTO_INCREMENT,
+  `plugin_id` INT NOT NULL DEFAULT 0,
+  `plugin_name` VARCHAR(64) NOT NULL,
+  `version` VARCHAR(32) NOT NULL,
+  `download_url` VARCHAR(512) NOT NULL,
+  `sha256` VARCHAR(64) NOT NULL DEFAULT '',
+  `changelog` TEXT NULL,
+  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `uk_plugin_version` (`plugin_id`, `version`),
+  INDEX `idx_pv_plugin_name` (`plugin_name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件版本历史表';
+"""
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     plugin_id = Column(Integer, nullable=False, default=0, index=True)
     plugin_id = Column(Integer, nullable=False, default=0, index=True)

+ 32 - 0
app/models/product.py

@@ -5,6 +5,34 @@ from app.core.database import Base
 
 
 class VasProduct(Base):
 class VasProduct(Base):
     __tablename__ = "vas_product"
     __tablename__ = "vas_product"
+    __ddl__ = """
+CREATE TABLE IF NOT EXISTS `vas_product` (
+  `id` INT NOT NULL AUTO_INCREMENT,
+  `country` VARCHAR(64) NOT NULL,
+  `city` VARCHAR(64) NOT NULL,
+  `visa_type` VARCHAR(64) NULL,
+  `provider` VARCHAR(32) NOT NULL,
+  `plugin_id` INT NULL COMMENT '绑定的处理插件ID',
+  `plugin_name` VARCHAR(64) NULL COMMENT '绑定的处理插件英文标识',
+  `title` VARCHAR(255) NOT NULL,
+  `description` TEXT NULL,
+  `extra_fields` JSON NULL,
+  `price_amount` INT NOT NULL COMMENT '标价金额 (分)',
+  `price_currency` VARCHAR(8) NOT NULL DEFAULT 'CNY',
+  `min_floor_price` INT NOT NULL DEFAULT 0 COMMENT '内部最低协议底价(分)',
+  `developer_id` VARCHAR(128) NULL COMMENT '对应底层脚本技术开发者ID (可由插件自动解析)',
+  `schema_id` INT NULL,
+  `enabled` INT NOT NULL DEFAULT 1,
+  `recommend_score` INT NOT NULL DEFAULT 0,
+  `created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  INDEX `idx_vas_product_provider` (`provider`),
+  INDEX `idx_vas_product_plugin_id` (`plugin_id`),
+  INDEX `idx_vas_product_plugin_name` (`plugin_name`),
+  INDEX `idx_vas_product_country_city` (`country`, `city`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商品主表';
+"""
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     country = Column(String(64), nullable=False)
     country = Column(String(64), nullable=False)
@@ -18,6 +46,10 @@ class VasProduct(Base):
 
 
     price_amount = Column(Integer, nullable=False)
     price_amount = Column(Integer, nullable=False)
     price_currency = Column(String(8), nullable=False)
     price_currency = Column(String(8), nullable=False)
+    min_floor_price = Column(Integer, default=0, nullable=False)  # 内部最低协议底价(分)
+    plugin_id = Column(Integer, nullable=True, index=True, comment="绑定的处理插件ID")
+    plugin_name = Column(String(64), nullable=True, index=True, comment="绑定的处理插件名称")
+    developer_id = Column(String(128), nullable=True)             # 对应底层脚本技术开发者ID (可由插件自动解析)
 
 
     schema_id = Column(Integer)
     schema_id = Column(Integer)
     enabled = Column(Integer, default=1)
     enabled = Column(Integer, default=1)

+ 15 - 0
app/models/product_routing.py

@@ -5,6 +5,21 @@ from app.core.database import Base
 
 
 class VasProductRouting(Base):
 class VasProductRouting(Base):
     __tablename__ = "vas_product_routing"
     __tablename__ = "vas_product_routing"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_product_routing` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `product_id` INT NOT NULL,
+      `routing_key` VARCHAR(255) NOT NULL,
+      `script_version` VARCHAR(50) NOT NULL,
+      `is_active` INT NOT NULL DEFAULT 1,
+      `priority` INT NOT NULL DEFAULT 10,
+      `config` JSON NULL,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      KEY `idx_vas_routing_product_id` (`product_id`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='产品路由分流配置表';
+    """
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     product_id = Column(Integer, nullable=False)
     product_id = Column(Integer, nullable=False)

+ 17 - 0
app/models/provider.py

@@ -15,6 +15,23 @@ from app.core.database import Base
 
 
 class Provider(Base):
 class Provider(Base):
     __tablename__ = "providers"
     __tablename__ = "providers"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `providers` (
+      `id` BIGINT NOT NULL AUTO_INCREMENT,
+      `name` VARCHAR(128) NOT NULL,
+      `enabled` SMALLINT NOT NULL DEFAULT 1,
+      `plugin_config` JSON NOT NULL,
+      `role_templates` JSON NOT NULL,
+      `version` INT NOT NULL DEFAULT 0,
+      `updated_by` VARCHAR(64) NULL DEFAULT 'system',
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      UNIQUE KEY `uk_providers_name` (`name`),
+      KEY `idx_providers_enabled` (`enabled`),
+      KEY `idx_providers_updated_at` (`updated_at`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='服务商凭据与配置表';
+    """
 
 
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     name = Column(String(128), nullable=False, unique=True, index=True)
     name = Column(String(128), nullable=False, unique=True, index=True)

+ 19 - 0
app/models/proxy_pool.py

@@ -5,6 +5,25 @@ from app.core.database import Base
 
 
 class ProxyPool(Base):
 class ProxyPool(Base):
     __tablename__ = "proxy_pool"
     __tablename__ = "proxy_pool"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `proxy_pool` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `pool_name` VARCHAR(32) NOT NULL COMMENT '所属代理池',
+      `proto` VARCHAR(10) NOT NULL DEFAULT 'http' COMMENT '代理协议',
+      `ip` VARCHAR(39) NOT NULL COMMENT '代理IP',
+      `port` INT NOT NULL COMMENT '端口',
+      `username` VARCHAR(64) NULL DEFAULT NULL COMMENT '代理用户名',
+      `password` VARCHAR(64) NULL DEFAULT NULL COMMENT '代理密码',
+      `next_use_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '下次允许使用的时间',
+      `status` VARCHAR(16) NOT NULL DEFAULT 'active' COMMENT 'active=可用, disable=禁用',
+      `time_zone` VARCHAR(100) NULL COMMENT '时区',
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      KEY `idx_proxy_pool_pool_name` (`pool_name`),
+      KEY `idx_proxy_pool_status` (`status`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='网络代理资源池表';
+    """
 
 
     id = Column(Integer, primary_key=True, index=True, autoincrement=True)
     id = Column(Integer, primary_key=True, index=True, autoincrement=True)
     pool_name = Column(String(32), nullable=False, comment="所属代理池")
     pool_name = Column(String(32), nullable=False, comment="所属代理池")

+ 42 - 0
app/models/proxy_reputation.py

@@ -18,6 +18,28 @@ class ProxyReputation(Base):
     以 (plugin_name, egress_ip) 为主键聚合分析各 IP 的健康度与信誉分
     以 (plugin_name, egress_ip) 为主键聚合分析各 IP 的健康度与信誉分
     """
     """
     __tablename__ = "proxy_reputation"
     __tablename__ = "proxy_reputation"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `proxy_reputation` (
+      `id` BIGINT NOT NULL AUTO_INCREMENT,
+      `plugin_name` VARCHAR(64) NOT NULL COMMENT '插件名称,如 vfs_plugin',
+      `egress_ip` VARCHAR(64) NOT NULL COMMENT '公网出口IP',
+      `score` INT NOT NULL DEFAULT 60 COMMENT '信誉分 0-100',
+      `state` VARCHAR(16) NOT NULL DEFAULT 'probation' COMMENT 'trusted, probation, blocked',
+      `total_calls` INT NOT NULL DEFAULT 0 COMMENT '总调用次数',
+      `success_calls` INT NOT NULL DEFAULT 0 COMMENT '成功调用次数',
+      `consecutive_successes` INT NOT NULL DEFAULT 0 COMMENT '连续成功次数',
+      `consecutive_fails` INT NOT NULL DEFAULT 0 COMMENT '连续失败次数',
+      `last_http_code` INT NULL COMMENT '最近一次 HTTP 响应码',
+      `last_error_type` VARCHAR(128) NULL COMMENT '最近一次错误类型',
+      `last_seen` INT NULL COMMENT '最近一次调用秒级时间戳',
+      `unblock_time` DATETIME NULL COMMENT '封禁解封时间点',
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      UNIQUE KEY `uk_plugin_ip` (`plugin_name`,`egress_ip`),
+      KEY `idx_plugin_state` (`plugin_name`,`state`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='代理出口IP信誉状态表';
+    """
 
 
     id = Column(BigInteger().with_variant(Integer, "sqlite"), primary_key=True, autoincrement=True)
     id = Column(BigInteger().with_variant(Integer, "sqlite"), primary_key=True, autoincrement=True)
     plugin_name = Column(String(64), nullable=False, comment="插件名称,如 vfs_plugin")
     plugin_name = Column(String(64), nullable=False, comment="插件名称,如 vfs_plugin")
@@ -47,6 +69,26 @@ class ProxyTelemetryLog(Base):
     用于原始调用记录留存及全局故障率滑动窗口统计
     用于原始调用记录留存及全局故障率滑动窗口统计
     """
     """
     __tablename__ = "proxy_telemetry_log"
     __tablename__ = "proxy_telemetry_log"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `proxy_telemetry_log` (
+      `id` BIGINT NOT NULL AUTO_INCREMENT,
+      `client_id` VARCHAR(64) NOT NULL COMMENT '上报客户端ID',
+      `plugin_name` VARCHAR(64) NOT NULL COMMENT '插件名称',
+      `egress_ip` VARCHAR(64) NOT NULL COMMENT '出口IP',
+      `local_port` INT NULL COMMENT '客户端本地代理端口',
+      `node_name` VARCHAR(128) NULL COMMENT '节点标签名称',
+      `action` VARCHAR(32) NOT NULL COMMENT '调用场景: spawn, query, book 等',
+      `success` TINYINT(1) NOT NULL COMMENT '是否成功',
+      `http_code` INT NOT NULL COMMENT 'HTTP状态码',
+      `error_type` VARCHAR(128) NULL COMMENT '错误描述',
+      `latency_ms` INT NOT NULL DEFAULT 0 COMMENT '耗时毫秒',
+      `timestamp` INT NOT NULL COMMENT '客户端上报时间戳',
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      KEY `idx_telemetry_created_at` (`created_at`),
+      KEY `idx_telemetry_plugin_created` (`plugin_name`,`created_at`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='代理调用流水日志表';
+    """
 
 
     id = Column(BigInteger().with_variant(Integer, "sqlite"), primary_key=True, autoincrement=True)
     id = Column(BigInteger().with_variant(Integer, "sqlite"), primary_key=True, autoincrement=True)
     client_id = Column(String(64), nullable=False, comment="上报客户端ID")
     client_id = Column(String(64), nullable=False, comment="上报客户端ID")

+ 11 - 0
app/models/schema.py

@@ -5,6 +5,17 @@ from app.core.database import Base
 
 
 class VasSchema(Base):
 class VasSchema(Base):
     __tablename__ = "vas_schema"
     __tablename__ = "vas_schema"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_schema` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `name` VARCHAR(255) NOT NULL,
+      `description` TEXT NULL,
+      `schema_json` JSON NOT NULL,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='表单数据结构定义表';
+    """
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     name = Column(String(255), nullable=False)
     name = Column(String(255), nullable=False)

+ 14 - 0
app/models/session.py

@@ -5,6 +5,20 @@ from app.core.database import Base
 
 
 class VasSession(Base):
 class VasSession(Base):
     __tablename__ = "vas_session"
     __tablename__ = "vas_session"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_session` (
+      `id` VARCHAR(128) NOT NULL,
+      `user_id` VARCHAR(128) NOT NULL,
+      `user_agent` VARCHAR(255) NOT NULL,
+      `ip` VARCHAR(128) NOT NULL,
+      `expire_at` DATETIME NOT NULL,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      KEY `idx_vas_session_user_id` (`user_id`),
+      KEY `idx_vas_session_expire_at` (`expire_at`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户会话Token表';
+    """
 
 
     id = Column(String(128), primary_key=True)   # token
     id = Column(String(128), primary_key=True)   # token
     user_id = Column(String(128), nullable=False)
     user_id = Column(String(128), nullable=False)

+ 111 - 0
app/models/settlement.py

@@ -0,0 +1,111 @@
+# app/models/settlement.py
+from datetime import datetime
+from sqlalchemy import Column, Integer, String, DateTime, JSON, Enum, Text
+from app.core.database import Base
+
+
+class VasSettlementPeriod(Base):
+    __tablename__ = "vas_settlement_period"
+    __ddl__ = """
+CREATE TABLE IF NOT EXISTS `vas_settlement_period` (
+  `id` VARCHAR(32) NOT NULL COMMENT '账期ID如 2026-10',
+  `name` VARCHAR(128) NOT NULL,
+  `start_date` DATETIME NOT NULL,
+  `end_date` DATETIME NOT NULL,
+  `total_orders` INT NOT NULL DEFAULT 0,
+  `total_revenue` INT NOT NULL DEFAULT 0,
+  `total_cost` INT NOT NULL DEFAULT 0,
+  `avg_cost` INT NOT NULL DEFAULT 0,
+  `net_profit` INT NOT NULL DEFAULT 0,
+  `status` ENUM('draft', 'confirmed', 'paid') NOT NULL DEFAULT 'draft',
+  `summary_data` JSON NULL,
+  `confirmed_by` VARCHAR(128) NULL,
+  `confirmed_at` DATETIME NULL,
+  `paid_at` DATETIME NULL,
+  `notes` TEXT NULL,
+  `created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
+  `updated_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='结算账期总表';
+"""
+
+    id = Column(String(32), primary_key=True)  # 账期ID,如 2026-10 或 2026-10-Q1
+    name = Column(String(128), nullable=False) # 账期显示名称
+    start_date = Column(DateTime, nullable=False)
+    end_date = Column(DateTime, nullable=False)
+    
+    total_orders = Column(Integer, default=0, nullable=False)    # 本账期履约完成订单总数
+    total_revenue = Column(Integer, default=0, nullable=False)   # 本期实收总额 (分)
+    total_cost = Column(Integer, default=0, nullable=False)      # 本期耗材总成本 (分)
+    avg_cost = Column(Integer, default=0, nullable=False)        # 单均摊薄耗材 (分)
+    net_profit = Column(Integer, default=0, nullable=False)      # 本期总净毛利 (分)
+
+    status = Column(
+        Enum('draft', 'confirmed', 'paid', name='settlement_period_status'),
+        default='draft',
+        nullable=False
+    )
+
+    # 包含甲乙分红、各对接人提成总计、开发者版权总计、过失扣除明细的完整汇总 JSON
+    summary_data = Column(JSON, nullable=True)
+
+    confirmed_by = Column(String(128), nullable=True)
+    confirmed_at = Column(DateTime, nullable=True)
+    paid_at = Column(DateTime, nullable=True)
+    notes = Column(Text, nullable=True)
+
+    created_at = Column(DateTime, default=datetime.utcnow)
+    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+
+class VasSettlementDetail(Base):
+    __tablename__ = "vas_settlement_detail"
+    __ddl__ = """
+CREATE TABLE IF NOT EXISTS `vas_settlement_detail` (
+  `id` INT NOT NULL AUTO_INCREMENT,
+  `period_id` VARCHAR(32) NOT NULL,
+  `order_id` VARCHAR(128) NOT NULL,
+  `channel_type` VARCHAR(32) NOT NULL,
+  `agency_id` VARCHAR(64) NULL,
+  `handler_id` VARCHAR(128) NULL,
+  `developer_id` VARCHAR(128) NULL,
+  `order_amount` INT NOT NULL,
+  `avg_cost` INT NOT NULL,
+  `net_profit` INT NOT NULL,
+  `tech_fee` INT NOT NULL DEFAULT 0,
+  `sales_fee` INT NOT NULL DEFAULT 0,
+  `pool_fee` INT NOT NULL DEFAULT 0,
+  `partner_a_amount` INT NOT NULL DEFAULT 0,
+  `partner_b_amount` INT NOT NULL DEFAULT 0,
+  `snapshot` JSON NULL,
+  `created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
+  PRIMARY KEY (`id`),
+  INDEX `idx_vas_settle_det_period` (`period_id`),
+  INDEX `idx_vas_settle_det_order` (`order_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='单笔订单分润快照表';
+"""
+
+    id = Column(Integer, primary_key=True, autoincrement=True)
+    period_id = Column(String(32), nullable=False, index=True)
+    order_id = Column(String(128), nullable=False, index=True)
+    
+    channel_type = Column(String(32), nullable=False)
+    agency_id = Column(String(64), nullable=True)
+    handler_id = Column(String(128), nullable=True)  # 40%提成归属人
+    developer_id = Column(String(128), nullable=True) # 20%技术版权归属人
+
+    order_amount = Column(Integer, nullable=False) # 订单实收
+    avg_cost = Column(Integer, nullable=False)     # 均摊耗材
+    net_profit = Column(Integer, nullable=False)   # 单单毛利
+
+    tech_fee = Column(Integer, default=0, nullable=False)   # 20% 技术版权费
+    sales_fee = Column(Integer, default=0, nullable=False)  # 40% 销售包干提成
+    pool_fee = Column(Integer, default=0, nullable=False)   # 40% 合伙分红池
+
+    partner_a_amount = Column(Integer, default=0, nullable=False) # 甲应得金额
+    partner_b_amount = Column(Integer, default=0, nullable=False) # 乙应得金额
+
+    # 包含该单完整计算快照
+    snapshot = Column(JSON, nullable=True)
+
+    created_at = Column(DateTime, default=datetime.utcnow)

+ 10 - 0
app/models/short_url.py

@@ -4,6 +4,16 @@ from app.core.database import Base
 
 
 class ShortUrl(Base):
 class ShortUrl(Base):
     __tablename__ = "short_url"
     __tablename__ = "short_url"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `short_url` (
+      `id` BIGINT NOT NULL AUTO_INCREMENT,
+      `short_key` VARCHAR(10) NOT NULL COMMENT '短链接Key',
+      `long_url` TEXT NOT NULL COMMENT '原始长链接',
+      `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+      PRIMARY KEY (`id`),
+      UNIQUE KEY `uq_short_url_short_key` (`short_key`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='短链接映射表';
+    """
 
 
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     id = Column(BigInteger, primary_key=True, autoincrement=True)
     short_key = Column(String(10), unique=True, nullable=False, comment="短链接Key")
     short_key = Column(String(10), unique=True, nullable=False, comment="短链接Key")

+ 16 - 0
app/models/slot_refresh_status.py

@@ -5,6 +5,22 @@ from app.core.database import Base
 
 
 class VasSlotRefreshStatus(Base):
 class VasSlotRefreshStatus(Base):
     __tablename__ = "vas_slot_refresh_status"
     __tablename__ = "vas_slot_refresh_status"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_slot_refresh_status` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `routing_key` VARCHAR(255) NOT NULL,
+      `snapshot_source` ENUM('worker','manual','sync') NOT NULL,
+      `country` VARCHAR(100) NOT NULL,
+      `city` VARCHAR(100) NOT NULL,
+      `visa_type` VARCHAR(100) NOT NULL,
+      `last_refresh_at` DATETIME NOT NULL,
+      `last_success_at` DATETIME NULL,
+      `last_error` TEXT NULL,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      UNIQUE KEY `uq_vas_slot_refresh_routing` (`routing_key`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='签证考位刷新监控汇总表';
+    """
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
 
 

+ 18 - 0
app/models/slot_snapshot.py

@@ -5,6 +5,24 @@ from app.core.database import Base
 
 
 class VasSlotSnapshot(Base):
 class VasSlotSnapshot(Base):
     __tablename__ = "vas_slot_snapshot"
     __tablename__ = "vas_slot_snapshot"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_slot_snapshot` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `country` VARCHAR(100) NOT NULL,
+      `city` VARCHAR(100) NOT NULL,
+      `visa_type` VARCHAR(100) NOT NULL,
+      `routing_key` VARCHAR(255) NOT NULL,
+      `availability_status` ENUM('None','Available','Waitlist') NOT NULL,
+      `website` TEXT NOT NULL,
+      `earliest_date` DATETIME NULL,
+      `availability` JSON NOT NULL,
+      `snapshot_source` ENUM('worker','manual','sync') NOT NULL,
+      `snapshot_at` DATETIME NOT NULL,
+      PRIMARY KEY (`id`),
+      KEY `idx_vas_slot_snap_routing` (`routing_key`),
+      KEY `idx_vas_slot_snap_snapshot_at` (`snapshot_at`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='考位可用状态历史快照表';
+    """
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
 
 

+ 12 - 0
app/models/task.py

@@ -5,6 +5,18 @@ from app.core.database import Base
 
 
 class Task(Base):
 class Task(Base):
     __tablename__ = "task"
     __tablename__ = "task"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `task` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `command` VARCHAR(255) NOT NULL,
+      `args` JSON NOT NULL,
+      `result` JSON NULL,
+      `status` SMALLINT NOT NULL DEFAULT 0 COMMENT '任务状态:0待执行 1执行中 2完成 3失败',
+      `create_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `update_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='通用异步指令任务表';
+    """
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     command = Column(String(255), nullable=False)
     command = Column(String(255), nullable=False)

+ 18 - 0
app/models/ticket.py

@@ -5,6 +5,24 @@ from app.core.database import Base
 
 
 class VasTicket(Base):
 class VasTicket(Base):
     __tablename__ = "vas_ticket"
     __tablename__ = "vas_ticket"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_ticket` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `order_id` VARCHAR(128) NOT NULL,
+      `user_id` VARCHAR(128) NOT NULL,
+      `type` ENUM('refund','dispute','change_request') NOT NULL,
+      `status` ENUM('pending','info_required','resolved','rejected') NOT NULL DEFAULT 'pending',
+      `reason` TEXT NULL,
+      `admin_comment` TEXT NULL,
+      `extra_fields` JSON NULL,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      KEY `idx_vas_ticket_order_id` (`order_id`),
+      KEY `idx_vas_ticket_user_id` (`user_id`),
+      KEY `idx_vas_ticket_status` (`status`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='工单与售后仲裁表';
+    """
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     order_id = Column(String(128), nullable=False)
     order_id = Column(String(128), nullable=False)

+ 13 - 0
app/models/ticket_message.py

@@ -15,6 +15,19 @@ from app.core.database import Base
 
 
 class VasTicketMessage(Base):
 class VasTicketMessage(Base):
     __tablename__ = "vas_ticket_message"
     __tablename__ = "vas_ticket_message"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_ticket_message` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `ticket_id` INT NOT NULL,
+      `sender_type` ENUM('user','admin','system') NOT NULL,
+      `sender_id` VARCHAR(128) NULL,
+      `content` TEXT NOT NULL,
+      `attachments` JSON NULL,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      KEY `idx_vas_ticket_msg_ticket_id` (`ticket_id`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='工单沟通对话消息表';
+    """
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
 
 

+ 21 - 0
app/models/user.py

@@ -5,6 +5,27 @@ from app.core.database import Base
 
 
 class VasUser(Base):
 class VasUser(Base):
     __tablename__ = "vas_user"
     __tablename__ = "vas_user"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_user` (
+      `id` VARCHAR(128) NOT NULL,
+      `role` VARCHAR(32) NULL,
+      `email` VARCHAR(128) NULL,
+      `phone` VARCHAR(32) NULL,
+      `nickname` VARCHAR(64) NULL,
+      `avatar_url` VARCHAR(255) NULL,
+      `preferred_language` VARCHAR(8) NULL,
+      `timezone` VARCHAR(32) NULL,
+      `register_ip` VARCHAR(64) NULL,
+      `last_login_ip` VARCHAR(64) NULL,
+      `password_hash` VARCHAR(255) NULL,
+      `email_verified` INT NOT NULL DEFAULT 0,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      KEY `idx_vas_user_email` (`email`),
+      KEY `idx_vas_user_role` (`role`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户基础表';
+    """
 
 
     id = Column(String(128), primary_key=True)
     id = Column(String(128), primary_key=True)
     role = Column(String(32))
     role = Column(String(32))

+ 24 - 0
app/models/vas_task.py

@@ -6,6 +6,29 @@ from app.core.database import Base
 class VasTask(Base):
 class VasTask(Base):
     __tablename__ = "vas_task"
     __tablename__ = "vas_task"
 
 
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_task` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `order_id` VARCHAR(128) NOT NULL,
+      `routing_key` VARCHAR(255) NOT NULL,
+      `priority` INT NOT NULL DEFAULT 0,
+      `script_version` VARCHAR(50) NULL,
+      `config` JSON NULL,
+      `status` ENUM('pending','grabbed','running','pause','cancelled','completed') NOT NULL DEFAULT 'pending',
+      `user_inputs` JSON NULL,
+      `grabbed_history` JSON NULL,
+      `meta` JSON NULL,
+      `attempt_count` INT NOT NULL DEFAULT 0,
+      `notify_count` INT NOT NULL DEFAULT 0,
+      `expire_at` DATETIME NULL,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      KEY `idx_vas_task_order_id` (`order_id`),
+      KEY `idx_vas_task_status` (`status`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='预约自动化执行任务表';
+    """
+
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     order_id = Column(String(128), nullable=False)
     order_id = Column(String(128), nullable=False)
 
 
@@ -30,3 +53,4 @@ class VasTask(Base):
 
 
     created_at = Column(DateTime, default=datetime.utcnow)
     created_at = Column(DateTime, default=datetime.utcnow)
     updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
     updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+

+ 11 - 0
app/models/verification_token.py

@@ -5,6 +5,17 @@ from app.core.database import Base
 
 
 class VasVerificationToken(Base):
 class VasVerificationToken(Base):
     __tablename__ = "vas_verification_token"
     __tablename__ = "vas_verification_token"
+    __ddl__ = """
+    CREATE TABLE IF NOT EXISTS `vas_verification_token` (
+      `id` INT NOT NULL AUTO_INCREMENT,
+      `token` VARCHAR(128) NOT NULL,
+      `used` INT NOT NULL DEFAULT 0,
+      `expire_at` DATETIME NOT NULL,
+      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+      PRIMARY KEY (`id`),
+      KEY `idx_vas_verif_token` (`token`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='验证Token表';
+    """
 
 
     id = Column(Integer, primary_key=True, autoincrement=True)
     id = Column(Integer, primary_key=True, autoincrement=True)
     token = Column(String(128), nullable=False)
     token = Column(String(128), nullable=False)

+ 39 - 0
app/schemas/agency.py

@@ -0,0 +1,39 @@
+# app/schemas/agency.py
+from datetime import datetime
+from typing import Optional
+from pydantic import BaseModel, Field
+
+
+class VasAgencyCreate(BaseModel):
+    id: Optional[str] = Field(None, description="中介唯一标识,为空时自动生成")
+    name: str = Field(..., description="中介机构名称/旅行社名称")
+    contact_name: Optional[str] = Field(None, description="联系人姓名")
+    contact_phone: Optional[str] = Field(None, description="联系电话/微信")
+    owner_id: str = Field(..., description="专属拓展人/维系人用户ID (拿40%销售提成)")
+    min_floor_price: int = Field(0, description="协议最低结算底价(分)")
+    notes: Optional[str] = Field(None, description="合作备注")
+
+
+class VasAgencyUpdate(BaseModel):
+    name: Optional[str] = None
+    contact_name: Optional[str] = None
+    contact_phone: Optional[str] = None
+    owner_id: Optional[str] = None
+    min_floor_price: Optional[int] = None
+    status: Optional[int] = None
+    notes: Optional[str] = None
+
+
+class VasAgencyOut(BaseModel):
+    id: str
+    name: str
+    contact_name: Optional[str]
+    contact_phone: Optional[str]
+    owner_id: str
+    min_floor_price: int
+    status: int
+    notes: Optional[str]
+    created_at: datetime
+    updated_at: datetime
+
+    model_config = {"from_attributes": True}

+ 30 - 0
app/schemas/cost.py

@@ -0,0 +1,30 @@
+# app/schemas/cost.py
+from datetime import datetime
+from typing import Optional, Literal
+from pydantic import BaseModel, Field
+
+
+class VasCostCreate(BaseModel):
+    category: Literal['vps', 'proxy_ip', 'captcha_api', 'sms_api', 'other'] = Field(
+        ..., description="耗材类型: vps(海外服务器), proxy_ip(代理IP池), captcha_api(打码平台), sms_api(接码API), other(其他)"
+    )
+    amount: int = Field(..., gt=0, description="支出金额(单位:分)")
+    currency: str = Field("CNY", description="币种")
+    description: Optional[str] = Field(None, description="支出说明/用途")
+    voucher_url: Optional[str] = Field(None, description="支付或充值截图凭证URL")
+    paid_at: Optional[datetime] = Field(None, description="实际发生支出时间,默认当前时间")
+
+
+class VasCostOut(BaseModel):
+    id: int
+    period_id: Optional[str]
+    category: str
+    amount: int
+    currency: str
+    description: Optional[str]
+    voucher_url: Optional[str]
+    paid_at: datetime
+    created_by: str
+    created_at: datetime
+
+    model_config = {"from_attributes": True}

+ 26 - 0
app/schemas/fault.py

@@ -0,0 +1,26 @@
+# app/schemas/fault.py
+from datetime import datetime
+from typing import Optional
+from pydantic import BaseModel, Field
+
+
+class VasFaultCreate(BaseModel):
+    order_id: str = Field(..., description="关联的订单ID")
+    liable_user_id: str = Field(..., description="责任人用户ID (从该人销售提成中全额扣减)")
+    penalty_amount: int = Field(..., gt=0, description="个人全额承担的赔偿/废单损失金额(单位:分)")
+    reason: str = Field(..., description="过错原因,如: 护照号录错/姓名拼写错误")
+    notes: Optional[str] = Field(None, description="补充说明")
+
+
+class VasFaultOut(BaseModel):
+    id: int
+    order_id: str
+    liable_user_id: str
+    penalty_amount: int
+    reason: str
+    notes: Optional[str]
+    period_id: Optional[str]
+    deducted_status: int
+    created_at: datetime
+
+    model_config = {"from_attributes": True}

+ 29 - 0
app/schemas/node_configuration.py

@@ -178,3 +178,32 @@ class NodeConfigurationListResponse(BaseModel):
     page: int
     page: int
     page_size: int
     page_size: int
     items: List[Dict[str, Any]]
     items: List[Dict[str, Any]]
+
+
+class ClusterNodeCreate(BaseModel):
+    node_id: str = Field(..., min_length=1, max_length=64, description="节点唯一标识,如 node01")
+    name: str = Field(..., min_length=1, max_length=128, description="节点别名,如 东京1号机")
+    ip_address: Optional[str] = Field(None, max_length=64, description="主机/服务器IP")
+    region: Optional[str] = Field(None, max_length=64, description="地区/机房")
+    status: Optional[int] = Field(1, description="1:启用, 0:停用")
+    notes: Optional[str] = Field(None, max_length=512, description="备注说明")
+
+
+class ClusterNodeUpdate(BaseModel):
+    name: Optional[str] = Field(None, min_length=1, max_length=128)
+    ip_address: Optional[str] = Field(None, max_length=64)
+    region: Optional[str] = Field(None, max_length=64)
+    status: Optional[int] = Field(None)
+    notes: Optional[str] = Field(None, max_length=512)
+
+
+class ClusterNodeOut(BaseEntrySchema):
+    id: int
+    node_id: str
+    name: str
+    ip_address: Optional[str] = None
+    region: Optional[str] = None
+    status: int
+    notes: Optional[str] = None
+    created_at: datetime
+    updated_at: datetime

+ 42 - 3
app/schemas/order.py

@@ -4,6 +4,7 @@ from pydantic import BaseModel, field_validator
 from typing import Optional, Dict, Any, Literal, List
 from typing import Optional, Dict, Any, Literal, List
 from datetime import datetime
 from datetime import datetime
 
 
+
 class VasOrderBase(BaseModel):
 class VasOrderBase(BaseModel):
     status: Optional[Literal['pending','paid','completed','closed']] = None
     status: Optional[Literal['pending','paid','completed','closed']] = None
     user_inputs: Optional[Dict[str, Any]] = None
     user_inputs: Optional[Dict[str, Any]] = None
@@ -19,20 +20,49 @@ class VasOrderBase(BaseModel):
                 return {}
                 return {}
         return v
         return v
 
 
+
 class VasOrderCreate(BaseModel):
 class VasOrderCreate(BaseModel):
     product_id: int
     product_id: int
     user_inputs: Dict[str, Any]
     user_inputs: Dict[str, Any]
-    
-class VasOrderUpdate(VasOrderBase):
-    pass
+
+
+class VasOrderCreateAdmin(BaseModel):
+    product_id: int
+    user_inputs: Dict[str, Any]
+    channel_type: Optional[Literal['direct', 'agency', 'website']] = 'direct'
+    agency_id: Optional[str] = None
+    handler_id: Optional[str] = None
+    final_amount: Optional[int] = None  # 管理员若自定义价格(分)
+
+
+class VasOrderUpdate(BaseModel):
+    channel_type: Optional[Literal['direct', 'agency', 'website']] = None
+    agency_id: Optional[str] = None
+    handler_id: Optional[str] = None
+    status: Optional[Literal['pending', 'paid', 'completed', 'closed']] = None
+    user_inputs: Optional[Dict[str, Any]] = None
+
+    @field_validator("user_inputs", mode="before")
+    def normalize_json_field(cls, v):
+        if v is None:
+            return None
+        if isinstance(v, str):
+            try:
+                return json.loads(v)
+            except Exception:
+                return {}
+        return v
+
 
 
 class VasOrderAdjustPrice(BaseModel):
 class VasOrderAdjustPrice(BaseModel):
     adjustment_delta: int
     adjustment_delta: int
     reason: Optional[str] = None
     reason: Optional[str] = None
 
 
+
 class VasOrderPatchUserInputs(BaseModel):
 class VasOrderPatchUserInputs(BaseModel):
     user_inputs: Dict[str, Any]
     user_inputs: Dict[str, Any]
 
 
+
 class VasOrderOut(VasOrderBase):
 class VasOrderOut(VasOrderBase):
     id: str
     id: str
     user_id: str
     user_id: str
@@ -42,8 +72,17 @@ class VasOrderOut(VasOrderBase):
     adjustment_delta: int
     adjustment_delta: int
     final_amount: int
     final_amount: int
     base_currency: str
     base_currency: str
+    channel_type: Optional[str] = "direct"
+    agency_id: Optional[str] = None
+    handler_id: Optional[str] = None
+    developer_id: Optional[str] = None
+    settlement_status: Optional[str] = "unsettled"
+    completed_at: Optional[datetime] = None
+    risk_cleared_at: Optional[datetime] = None
+    settlement_period_id: Optional[str] = None
     created_at: datetime
     created_at: datetime
     updated_at: datetime
     updated_at: datetime
+
     model_config = {
     model_config = {
         "from_attributes": True
         "from_attributes": True
     }
     }

+ 18 - 0
app/schemas/plugin.py

@@ -7,11 +7,15 @@ class PluginPublishRequest(BaseModel):
     name: str = Field(..., description="插件唯一英文标识,如: tls_plugin")
     name: str = Field(..., description="插件唯一英文标识,如: tls_plugin")
     version: str = Field(..., description="版本号,如: 1.0.1")
     version: str = Field(..., description="版本号,如: 1.0.1")
     display_name: Optional[str] = Field("", description="插件中文展示名")
     display_name: Optional[str] = Field("", description="插件中文展示名")
+    filename: Optional[str] = Field("", description="插件二进制脚本文件名,如 tls_plugin.py")
+    class_name: Optional[str] = Field("", description="插件入口类名,如 TLSPlugin")
+    protocol: Optional[str] = Field("IPlugin", description="插件协议标识,如 IPlugin")
     description: Optional[str] = Field("", description="插件功能描述")
     description: Optional[str] = Field("", description="插件功能描述")
     download_url: Optional[str] = Field(None, description="已有文件下载地址")
     download_url: Optional[str] = Field(None, description="已有文件下载地址")
     sha256: Optional[str] = Field("", description="文件 SHA256 校验和")
     sha256: Optional[str] = Field("", description="文件 SHA256 校验和")
     changelog: Optional[str] = Field(None, description="本次版本更新日志")
     changelog: Optional[str] = Field(None, description="本次版本更新日志")
     set_as_latest: bool = Field(True, description="是否立即将该版本设为插件最新版本")
     set_as_latest: bool = Field(True, description="是否立即将该版本设为插件最新版本")
+    developer_id: Optional[str] = Field(None, description="插件开发管理者ID")
 
 
 
 
 class PluginPublishOut(BaseModel):
 class PluginPublishOut(BaseModel):
@@ -20,6 +24,8 @@ class PluginPublishOut(BaseModel):
     version: str
     version: str
     download_url: str
     download_url: str
     sha256: str
     sha256: str
+    class_name: Optional[str] = ""
+    protocol: Optional[str] = "IPlugin"
 
 
 
 
 class PluginOut(BaseModel):
 class PluginOut(BaseModel):
@@ -27,9 +33,12 @@ class PluginOut(BaseModel):
     name: str
     name: str
     display_name: str
     display_name: str
     filename: str
     filename: str
+    class_name: str = ""
+    protocol: str = "IPlugin"
     latest_version: str
     latest_version: str
     description: str
     description: str
     status: int
     status: int
+    developer_id: Optional[str] = None
     created_at: Optional[datetime] = None
     created_at: Optional[datetime] = None
     updated_at: Optional[datetime] = None
     updated_at: Optional[datetime] = None
 
 
@@ -59,9 +68,12 @@ class PluginDetailOut(BaseModel):
     name: str
     name: str
     display_name: str
     display_name: str
     filename: str
     filename: str
+    class_name: str = ""
+    protocol: str = "IPlugin"
     latest_version: str
     latest_version: str
     description: str
     description: str
     status: int
     status: int
+    developer_id: Optional[str] = None
     versions: List[PluginVersionOut] = []
     versions: List[PluginVersionOut] = []
 
 
     class Config:
     class Config:
@@ -70,8 +82,12 @@ class PluginDetailOut(BaseModel):
 
 
 class PluginUpdate(BaseModel):
 class PluginUpdate(BaseModel):
     display_name: Optional[str] = Field(None, description="插件展示名")
     display_name: Optional[str] = Field(None, description="插件展示名")
+    filename: Optional[str] = Field(None, description="插件脚本文件名")
+    class_name: Optional[str] = Field(None, description="插件入口类名")
+    protocol: Optional[str] = Field(None, description="插件协议标识")
     description: Optional[str] = Field(None, description="功能描述")
     description: Optional[str] = Field(None, description="功能描述")
     status: Optional[int] = Field(None, description="状态: 1-启用, 0-停用")
     status: Optional[int] = Field(None, description="状态: 1-启用, 0-停用")
+    developer_id: Optional[str] = Field(None, description="插件开发管理者ID")
 
 
 
 
 class PluginSwitchVersion(BaseModel):
 class PluginSwitchVersion(BaseModel):
@@ -88,6 +104,8 @@ class PluginLatestItemOut(BaseModel):
     name: str
     name: str
     display_name: str
     display_name: str
     filename: str
     filename: str
+    class_name: str = ""
+    protocol: str = "IPlugin"
     version: str
     version: str
     description: str
     description: str
     download_url: str
     download_url: str

+ 4 - 0
app/schemas/product.py

@@ -17,6 +17,10 @@ class VasProductBase(BaseModel):
     schema_id: Optional[int] = None
     schema_id: Optional[int] = None
     enabled: Optional[int] = None
     enabled: Optional[int] = None
     recommend_score: Optional[int] = None
     recommend_score: Optional[int] = None
+    min_floor_price: Optional[int] = 0
+    plugin_id: Optional[int] = None
+    plugin_name: Optional[str] = None
+    developer_id: Optional[str] = None
 
 
     @field_validator("extra_fields", mode="before")
     @field_validator("extra_fields", mode="before")
     def normalize_json_field(cls, v):
     def normalize_json_field(cls, v):

+ 74 - 0
app/schemas/settlement.py

@@ -0,0 +1,74 @@
+# app/schemas/settlement.py
+from datetime import datetime
+from typing import Optional, List, Dict, Any
+from pydantic import BaseModel, Field
+
+
+class SettlementPreviewRequest(BaseModel):
+    start_date: datetime = Field(..., description="统计账期起始时间")
+    end_date: datetime = Field(..., description="统计账期结束时间")
+    partner_a_id: Optional[str] = Field("partner_a", description="合伙人甲方用户ID")
+    partner_b_id: Optional[str] = Field("partner_b", description="合伙人乙方用户ID")
+    default_developer_id: Optional[str] = Field(None, description="已废弃:技术分成已改为根据订单关联商品对应的插件开发管理者自动归属,无需手动指定")
+
+
+class SettlementConfirmRequest(SettlementPreviewRequest):
+    period_id: str = Field(..., description="账期ID,如 2026-10")
+    period_name: str = Field(..., description="账期显示名称,如 2026年10月月结")
+    notes: Optional[str] = Field(None, description="结算备注")
+
+
+class SettlementPayoutItem(BaseModel):
+    user_id: str
+    role_description: str # 如: 合伙人分红 / 社交直客提成 / 中介渠道提成 / 技术版权费
+    gross_amount: int     # 应得分润(分)
+    fault_penalty: int    # 过错赔偿冲销扣减(分)
+    net_payout: int       # 实际最终应支付转账金额(分)
+
+
+class SettlementOrderDetailOut(BaseModel):
+    order_id: str
+    channel_type: str
+    agency_id: Optional[str]
+    handler_id: Optional[str]
+    developer_id: Optional[str]
+    order_amount: int
+    avg_cost: int
+    net_profit: int
+    tech_fee: int
+    sales_fee: int
+    pool_fee: int
+    partner_a_amount: int
+    partner_b_amount: int
+
+
+class SettlementPeriodOut(BaseModel):
+    id: str
+    name: str
+    start_date: datetime
+    end_date: datetime
+    total_orders: int
+    total_revenue: int
+    total_cost: int
+    avg_cost: int
+    net_profit: int
+    status: str
+    summary_data: Optional[Dict[str, Any]]
+    confirmed_by: Optional[str]
+    confirmed_at: Optional[datetime]
+    paid_at: Optional[datetime]
+    created_at: datetime
+
+    model_config = {"from_attributes": True}
+
+
+class SettlementPreviewResponse(BaseModel):
+    period_range: str
+    total_orders: int
+    total_revenue: int
+    total_cost: int
+    avg_cost: int
+    net_profit: int
+    payout_summary: List[SettlementPayoutItem]
+    cost_breakdown: Dict[str, int]
+    details: List[SettlementOrderDetailOut]

+ 19 - 0
app/services/account_service.py

@@ -88,3 +88,22 @@ class AccountService:
         await db.commit()
         await db.commit()
         await db.refresh(obj)
         await db.refresh(obj)
         return obj
         return obj
+
+    @staticmethod
+    async def get_pools(db: AsyncSession):
+        """
+        获取数据库中所有去重的使馆账号池及统计
+        """
+        stmt = (
+            select(
+                Account.pool_name,
+                func.count(Account.id).label("total_count")
+            )
+            .group_by(Account.pool_name)
+            .order_by(Account.pool_name.asc())
+        )
+        res = await db.execute(stmt)
+        return [
+            {"pool_name": row[0], "total_count": row[1]}
+            for row in res.fetchall()
+        ]

+ 62 - 0
app/services/agency_service.py

@@ -0,0 +1,62 @@
+# app/services/agency_service.py
+import uuid
+from typing import List, Optional
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select
+from app.models.agency import VasAgency
+from app.schemas.agency import VasAgencyCreate, VasAgencyUpdate
+from app.core.biz_exception import NotFoundError, BizLogicError
+from app.utils.pagination import paginate
+
+
+class AgencyService:
+
+    @staticmethod
+    async def create(db: AsyncSession, data: VasAgencyCreate) -> VasAgency:
+        # 检查重名
+        stmt = select(VasAgency).where(VasAgency.name == data.name)
+        existing = (await db.execute(stmt)).scalar_one_or_none()
+        if existing:
+            raise BizLogicError(f"中介名称 '{data.name}' 已存在")
+
+        agency_id = data.id or f"AG-{uuid.uuid4().hex[:8].upper()}"
+        agency = VasAgency(
+            id=agency_id,
+            name=data.name,
+            contact_name=data.contact_name,
+            contact_phone=data.contact_phone,
+            owner_id=data.owner_id,
+            min_floor_price=data.min_floor_price,
+            notes=data.notes,
+        )
+        db.add(agency)
+        await db.commit()
+        await db.refresh(agency)
+        return agency
+
+    @staticmethod
+    async def get(db: AsyncSession, agency_id: str) -> Optional[VasAgency]:
+        stmt = select(VasAgency).where(VasAgency.id == agency_id)
+        return (await db.execute(stmt)).scalar_one_or_none()
+
+    @staticmethod
+    async def update(db: AsyncSession, agency_id: str, data: VasAgencyUpdate) -> VasAgency:
+        agency = await AgencyService.get(db, agency_id)
+        if not agency:
+            raise NotFoundError("合作中介机构不存在")
+
+        update_dict = data.dict(exclude_unset=True)
+        for key, value in update_dict.items():
+            setattr(agency, key, value)
+
+        await db.commit()
+        await db.refresh(agency)
+        return agency
+
+    @staticmethod
+    async def list_all(db: AsyncSession, page: int = 0, size: int = 20, active_only: bool = False):
+        stmt = select(VasAgency)
+        if active_only:
+            stmt = stmt.where(VasAgency.status == 1)
+        stmt = stmt.order_by(VasAgency.created_at.desc())
+        return await paginate(db, stmt, page, size)

+ 70 - 0
app/services/cost_service.py

@@ -0,0 +1,70 @@
+# app/services/cost_service.py
+from datetime import datetime
+from typing import Optional, List, Dict
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select, func
+from app.models.cost import VasCostRecord
+from app.schemas.cost import VasCostCreate
+from app.utils.pagination import paginate
+
+
+class CostService:
+
+    @staticmethod
+    async def create(db: AsyncSession, data: VasCostCreate, user_id: str) -> VasCostRecord:
+        record = VasCostRecord(
+            category=data.category,
+            amount=data.amount,
+            currency=data.currency,
+            description=data.description,
+            voucher_url=data.voucher_url,
+            paid_at=data.paid_at or datetime.utcnow(),
+            created_by=user_id,
+        )
+        db.add(record)
+        await db.commit()
+        await db.refresh(record)
+        return record
+
+    @staticmethod
+    async def list_costs(
+        db: AsyncSession,
+        period_id: Optional[str] = None,
+        category: Optional[str] = None,
+        start_date: Optional[datetime] = None,
+        end_date: Optional[datetime] = None,
+        page: int = 0,
+        size: int = 20,
+    ):
+        stmt = select(VasCostRecord)
+        if period_id:
+            stmt = stmt.where(VasCostRecord.period_id == period_id)
+        if category:
+            stmt = stmt.where(VasCostRecord.category == category)
+        if start_date:
+            stmt = stmt.where(VasCostRecord.paid_at >= start_date)
+        if end_date:
+            stmt = stmt.where(VasCostRecord.paid_at <= end_date)
+
+        stmt = stmt.order_by(VasCostRecord.paid_at.desc())
+        return await paginate(db, stmt, page, size)
+
+    @staticmethod
+    async def get_costs_summary_by_date(
+        db: AsyncSession,
+        start_date: datetime,
+        end_date: datetime
+    ) -> Dict[str, int]:
+        """
+        统计时间段内各项耗材的总支出 (分)
+        """
+        stmt = (
+            select(VasCostRecord.category, func.sum(VasCostRecord.amount))
+            .where(VasCostRecord.paid_at >= start_date, VasCostRecord.paid_at <= end_date)
+            .group_by(VasCostRecord.category)
+        )
+        res = await db.execute(stmt)
+        summary = {cat: 0 for cat in ['vps', 'proxy_ip', 'captcha_api', 'sms_api', 'other']}
+        for cat, total in res.fetchall():
+            summary[cat] = int(total or 0)
+        return summary

+ 49 - 0
app/services/fault_service.py

@@ -0,0 +1,49 @@
+# app/services/fault_service.py
+from typing import Optional, List
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select, func
+from app.models.fault import VasFaultCompensation
+from app.schemas.fault import VasFaultCreate
+from app.utils.pagination import paginate
+
+
+class FaultService:
+
+    @staticmethod
+    async def create(db: AsyncSession, data: VasFaultCreate) -> VasFaultCompensation:
+        record = VasFaultCompensation(
+            order_id=data.order_id,
+            liable_user_id=data.liable_user_id,
+            penalty_amount=data.penalty_amount,
+            reason=data.reason,
+            notes=data.notes,
+            deducted_status=0,
+        )
+        db.add(record)
+        await db.commit()
+        await db.refresh(record)
+        return record
+
+    @staticmethod
+    async def list_pending_by_user(db: AsyncSession, user_id: str) -> List[VasFaultCompensation]:
+        stmt = select(VasFaultCompensation).where(
+            VasFaultCompensation.liable_user_id == user_id,
+            VasFaultCompensation.deducted_status == 0
+        )
+        return (await db.execute(stmt)).scalars().all()
+
+    @staticmethod
+    async def list_all(
+        db: AsyncSession,
+        user_id: Optional[str] = None,
+        deducted_status: Optional[int] = None,
+        page: int = 0,
+        size: int = 20
+    ):
+        stmt = select(VasFaultCompensation)
+        if user_id:
+            stmt = stmt.where(VasFaultCompensation.liable_user_id == user_id)
+        if deducted_status is not None:
+            stmt = stmt.where(VasFaultCompensation.deducted_status == deducted_status)
+        stmt = stmt.order_by(VasFaultCompensation.created_at.desc())
+        return await paginate(db, stmt, page, size)

+ 109 - 0
app/services/node_configuration_service.py

@@ -10,6 +10,11 @@ from app.models.node_configuration import (
     SentinelEntry,
     SentinelEntry,
     StandaloneEntry,
     StandaloneEntry,
     NodeConfigurationRevision,
     NodeConfigurationRevision,
+    ClusterNodeEntry,
+)
+from app.schemas.node_configuration import (
+    ClusterNodeCreate,
+    ClusterNodeUpdate,
 )
 )
 
 
 
 
@@ -398,3 +403,107 @@ class NodeConfigurationService:
         await db.commit()
         await db.commit()
         await db.refresh(entry)
         await db.refresh(entry)
         return entry
         return entry
+
+    # ==================== 集群节点档案注册管理 ====================
+    @classmethod
+    async def list_cluster_nodes(
+        cls,
+        db: AsyncSession,
+        status: Optional[int] = None,
+        keyword: Optional[str] = None,
+    ) -> List[ClusterNodeEntry]:
+        stmt = select(ClusterNodeEntry)
+        if status is not None:
+            stmt = stmt.where(ClusterNodeEntry.status == status)
+        if keyword and keyword.strip():
+            k = f"%{keyword.strip()}%"
+            stmt = stmt.where(
+                (ClusterNodeEntry.node_id.ilike(k))
+                | (ClusterNodeEntry.name.ilike(k))
+                | (ClusterNodeEntry.ip_address.ilike(k))
+                | (ClusterNodeEntry.region.ilike(k))
+            )
+        stmt = stmt.order_by(ClusterNodeEntry.created_at.desc())
+        res = await db.execute(stmt)
+        return res.scalars().all()
+
+    @classmethod
+    async def get_cluster_node(
+        cls,
+        db: AsyncSession,
+        node_id: str,
+    ) -> Optional[ClusterNodeEntry]:
+        stmt = select(ClusterNodeEntry).where(ClusterNodeEntry.node_id == node_id)
+        return (await db.execute(stmt)).scalar_one_or_none()
+
+    @classmethod
+    async def create_cluster_node(
+        cls,
+        db: AsyncSession,
+        data: ClusterNodeCreate,
+    ) -> ClusterNodeEntry:
+        existing = await cls.get_cluster_node(db, data.node_id.strip())
+        if existing:
+            raise BizException(
+                code=40001,
+                message=f"节点标识 '{data.node_id.strip()}' 已存在,请勿重复注册",
+                http_status=400,
+            )
+        node = ClusterNodeEntry(
+            node_id=data.node_id.strip(),
+            name=data.name.strip(),
+            ip_address=data.ip_address.strip() if data.ip_address else None,
+            region=data.region.strip() if data.region else None,
+            status=data.status if data.status is not None else 1,
+            notes=data.notes.strip() if data.notes else None,
+        )
+        db.add(node)
+        await db.commit()
+        await db.refresh(node)
+        return node
+
+    @classmethod
+    async def update_cluster_node(
+        cls,
+        db: AsyncSession,
+        node_id: str,
+        data: ClusterNodeUpdate,
+    ) -> ClusterNodeEntry:
+        node = await cls.get_cluster_node(db, node_id)
+        if not node:
+            raise BizException(
+                code=40401,
+                message=f"未找到节点: '{node_id}'",
+                http_status=404,
+            )
+        if data.name is not None:
+            node.name = data.name.strip()
+        if data.ip_address is not None:
+            node.ip_address = data.ip_address.strip() if data.ip_address else None
+        if data.region is not None:
+            node.region = data.region.strip() if data.region else None
+        if data.status is not None:
+            node.status = data.status
+        if data.notes is not None:
+            node.notes = data.notes.strip() if data.notes else None
+
+        await db.commit()
+        await db.refresh(node)
+        return node
+
+    @classmethod
+    async def delete_cluster_node(
+        cls,
+        db: AsyncSession,
+        node_id: str,
+    ) -> bool:
+        node = await cls.get_cluster_node(db, node_id)
+        if not node:
+            raise BizException(
+                code=40401,
+                message=f"未找到节点: '{node_id}'",
+                http_status=404,
+            )
+        await db.delete(node)
+        await db.commit()
+        return True

+ 185 - 52
app/services/order_service.py

@@ -17,9 +17,10 @@ from app.models.order import VasOrder
 from app.models.vas_task import VasTask
 from app.models.vas_task import VasTask
 from app.models.product import VasProduct
 from app.models.product import VasProduct
 from app.models.payment import VasPayment
 from app.models.payment import VasPayment
-from app.models.product_routing import VasProductRouting
-from app.schemas.order import VasOrderCreate, VasOrderAdjustPrice, VasOrderPatchUserInputs
+from app.models.agency import VasAgency
+from app.schemas.order import VasOrderCreate, VasOrderCreateAdmin, VasOrderAdjustPrice, VasOrderPatchUserInputs, VasOrderUpdate
 from app.services.webhook_service import WebhookService
 from app.services.webhook_service import WebhookService
+from app.services.agency_service import AgencyService
 
 
 
 
 class OrderService:
 class OrderService:
@@ -32,7 +33,9 @@ class OrderService:
         auth_user: VasUser,
         auth_user: VasUser,
         redis_client: Redis,
         redis_client: Redis,
     ) -> VasOrder:
     ) -> VasOrder:
-
+        """
+        前台散客自主下单 (公海订单)
+        """
         if not auth_user.email:
         if not auth_user.email:
             raise BizLogicError(
             raise BizLogicError(
                 "Your account must be linked to an email address before you can place an order."
                 "Your account must be linked to an email address before you can place an order."
@@ -49,65 +52,78 @@ class OrderService:
             adjustment_delta=0,
             adjustment_delta=0,
             final_amount=product.price_amount,
             final_amount=product.price_amount,
             user_id=auth_user.id,
             user_id=auth_user.id,
+            channel_type='website',  # 官网公海
+            handler_id=None,         # 无专人对接,销售提成甲乙双方对半平分
+            developer_id=None,  # 订单不硬绑开发者ID,由商品绑定插件动态解析技术分成归属
+            settlement_status='unsettled',
         )
         )
 
 
         db.add(order)
         db.add(order)
         await db.commit()
         await db.commit()
         await db.refresh(order)
         await db.refresh(order)
 
 
-        logger.info(f"📦 [ORDER] Created order: id={order.id} product={product.id} user={auth_user.id} amount={order.final_amount} {order.base_currency}")
+        logger.info(f"📦 [ORDER] Created website order: id={order.id} product={product.id} user={auth_user.id} amount={order.final_amount} {order.base_currency}")
         return order
         return order
 
 
-    
-    @staticmethod
-    async def cancel(
-        db: AsyncSession,
-        order_id,
-    ) -> VasOrder:
-        stmt = select(VasOrder).where(VasOrder.id == order_id)
-        order = (await db.execute(stmt)).scalar_one_or_none()
-
-        if not order:
-            raise NotFoundError("Order not exist")
-        
-        order.status = "closed"
-        task_res = await db.execute(
-            select(VasTask).where(
-                VasTask.order_id == order.id,
-                VasTask.status.in_(["pending", "grabbed", "running", "pause", "completed"]),
-            )
-        )
-        for task in task_res.scalars().all():
-            task.status = "cancelled"
-            
-        await db.commit()
-        await db.refresh(order)
-        logger.info(f"🚫 [ORDER] Cancelled order: id={order.id} and its associated tasks")
-        return order
-    
     @staticmethod
     @staticmethod
     async def create_by_admin(
     async def create_by_admin(
         db: AsyncSession,
         db: AsyncSession,
-        data: VasOrderCreate,
+        data: VasOrderCreateAdmin,
         product: VasProduct,
         product: VasProduct,
         auth_user: VasUser
         auth_user: VasUser
     ) -> VasOrder:
     ) -> VasOrder:
+        """
+        后台管理员/客服代客录单 (支持社交自收直客 与 中介渠道同行单)
+        """
+        channel_type = data.channel_type or "direct"
+        agency_id = data.agency_id if channel_type == "agency" else None
+        
+        # 确定金额
+        final_amount = data.final_amount if (data.final_amount is not None and data.final_amount > 0) else product.price_amount
+
+        # 渠道判定与底价拦截
+        if channel_type == "agency":
+            if not agency_id:
+                raise BizLogicError("中介渠道单必须指定合作中介 agency_id")
+            agency = await AgencyService.get(db, agency_id)
+            if not agency:
+                raise BizLogicError(f"未找到中介机构: {agency_id}")
+            if agency.status != 1:
+                raise BizLogicError(f"中介机构 '{agency.name}' 已暂停合作")
+            
+            # 专属对接人绑定 (中介拓展人独享40%提成)
+            handler_id = agency.owner_id
+
+            # 底价校验
+            effective_floor = agency.min_floor_price if agency.min_floor_price > 0 else (getattr(product, 'min_floor_price', 0) or 0)
+            if effective_floor > 0 and final_amount < effective_floor:
+                raise BizLogicError(f"中介下单金额({final_amount/100:.2f}元)不得低于内部最低协议底价({effective_floor/100:.2f}元)")
+        else:
+            # 社交账号自收直客单 (小红书/微信私域): 默认录单人自己,亦可指定团队接单人
+            handler_id = data.handler_id or auth_user.id
+
         order_id = f"ORD-{datetime.utcnow():%Y%m%d%H%M%S}-{uuid.uuid4().hex[:8]}"
         order_id = f"ORD-{datetime.utcnow():%Y%m%d%H%M%S}-{uuid.uuid4().hex[:8]}"
         safe_product_name = (product.title[:100]) if product.title else ""
         safe_product_name = (product.title[:100]) if product.title else ""
         order = VasOrder(
         order = VasOrder(
             id=order_id,
             id=order_id,
-            **data.dict(),
+            product_id=data.product_id,
+            user_inputs=data.user_inputs,
             status="paid",
             status="paid",
             product_name=safe_product_name,
             product_name=safe_product_name,
             base_amount=product.price_amount,
             base_amount=product.price_amount,
             base_currency=product.price_currency,
             base_currency=product.price_currency,
-            adjustment_delta=0,
-            final_amount=product.price_amount,
+            adjustment_delta=final_amount - product.price_amount,
+            final_amount=final_amount,
             user_id=auth_user.id,
             user_id=auth_user.id,
+            channel_type=channel_type,
+            agency_id=agency_id,
+            handler_id=handler_id,
+            developer_id=None,  # 订单不硬绑开发者ID,由商品绑定插件动态解析技术分成归属
+            settlement_status='unsettled',
         )
         )
+
         # ===== user_inputs 安全修复 =====
         # ===== user_inputs 安全修复 =====
         raw_inputs = order.user_inputs
         raw_inputs = order.user_inputs
-
         if isinstance(raw_inputs, str):
         if isinstance(raw_inputs, str):
             try:
             try:
                 order.user_inputs = json.loads(raw_inputs)
                 order.user_inputs = json.loads(raw_inputs)
@@ -121,19 +137,72 @@ class OrderService:
             "by": auth_user.id,
             "by": auth_user.id,
             "at": datetime.utcnow().isoformat(),
             "at": datetime.utcnow().isoformat(),
             "reason": "admin manual order",
             "reason": "admin manual order",
+            "channel_type": channel_type,
+            "handler_id": handler_id,
         }
         }
         
         
         db.add(order)
         db.add(order)
-        
         await WebhookService._create_task_if_not_exists(db, order)
         await WebhookService._create_task_if_not_exists(db, order)
         
         
         await db.commit()
         await db.commit()
         await db.refresh(order)
         await db.refresh(order)
-        logger.info(f"👑 [ORDER] Admin created order: id={order.id} product={product.id} user={auth_user.id} status=paid")
+        logger.info(f"👑 [ORDER] Admin created order: id={order.id} product={product.id} channel={channel_type} handler={handler_id} amount={final_amount}")
+        return order
+
+    @staticmethod
+    async def cancel(
+        db: AsyncSession,
+        order_id: str,
+    ) -> VasOrder:
+        stmt = select(VasOrder).where(VasOrder.id == order_id)
+        order = (await db.execute(stmt)).scalar_one_or_none()
+
+        if not order:
+            raise NotFoundError("Order not exist")
+        
+        order.status = "closed"
+        order.settlement_status = "unsettled"
+        task_res = await db.execute(
+            select(VasTask).where(
+                VasTask.order_id == order.id,
+                VasTask.status.in_(["pending", "grabbed", "running", "pause", "completed"]),
+            )
+        )
+        for task in task_res.scalars().all():
+            task.status = "cancelled"
+            
+        await db.commit()
+        await db.refresh(order)
+        logger.info(f"🚫 [ORDER] Cancelled order: id={order.id} and its associated tasks")
         return order
         return order
-    
+
     @staticmethod
     @staticmethod
-    async def adjust_order_price(db: AsyncSession, order_id: str,  payload: VasOrderAdjustPrice) -> VasOrder:
+    async def mark_completed(
+        db: AsyncSession,
+        order_id: str,
+        risk_days: int = 7
+    ) -> VasOrder:
+        """
+        履约成功完成订单,并自动开启 T+N 退款风险期
+        """
+        stmt = select(VasOrder).where(VasOrder.id == order_id)
+        order = (await db.execute(stmt)).scalar_one_or_none()
+        if not order:
+            raise NotFoundError("Order not exist")
+
+        now = datetime.utcnow()
+        order.status = "completed"
+        order.completed_at = now
+        order.risk_cleared_at = now + timedelta(days=risk_days)
+        order.settlement_status = "eligible"
+
+        await db.commit()
+        await db.refresh(order)
+        logger.info(f"🎉 [ORDER] Order completed: id={order.id}, risk cleared at: {order.risk_cleared_at}")
+        return order
+
+    @staticmethod
+    async def adjust_order_price(db: AsyncSession, order_id: str, payload: VasOrderAdjustPrice) -> VasOrder:
         stmt = select(VasOrder).where(VasOrder.id == order_id)
         stmt = select(VasOrder).where(VasOrder.id == order_id)
         order = (await db.execute(stmt)).scalar_one_or_none()
         order = (await db.execute(stmt)).scalar_one_or_none()
 
 
@@ -145,27 +214,25 @@ class OrderService:
             logger.warning(f"⚠️ [ORDER] Price adjust failed: Order {order_id} status is {order.status} (expected pending)")
             logger.warning(f"⚠️ [ORDER] Price adjust failed: Order {order_id} status is {order.status} (expected pending)")
             raise BizLogicError(message="Order not adjustable")
             raise BizLogicError(message="Order not adjustable")
 
 
-        # 2. 更新订单价格
-        old_amount = order.final_amount
-        order.adjustment_delta = payload.adjustment_delta
-        order.final_amount = order.base_amount + payload.adjustment_delta
-
-        if order.final_amount <= 0:
+        new_final = order.base_amount + payload.adjustment_delta
+        if new_final <= 0:
             raise BizLogicError(message="final_amount must be > 0")
             raise BizLogicError(message="final_amount must be > 0")
 
 
-        # ② 是否已有 pending payment(幂等)
+        order.adjustment_delta = payload.adjustment_delta
+        order.final_amount = new_final
+
+        # 是否已有 pending payment
         stmt = select(VasPayment).where(
         stmt = select(VasPayment).where(
             VasPayment.order_id == order.id,
             VasPayment.order_id == order.id,
             VasPayment.status == "pending",
             VasPayment.status == "pending",
         )
         )
         active_payment = (await db.execute(stmt)).scalar_one_or_none()
         active_payment = (await db.execute(stmt)).scalar_one_or_none()
-
         if active_payment:
         if active_payment:
             active_payment.status = "expired"
             active_payment.status = "expired"
 
 
         await db.commit()
         await db.commit()
         await db.refresh(order)
         await db.refresh(order)
-        logger.info(f"💰 [ORDER] Adjusted order price: id={order.id} old={old_amount} new={order.final_amount} delta={payload.adjustment_delta}")
+        logger.info(f"💰 [ORDER] Adjusted order price: id={order.id} new={order.final_amount} delta={payload.adjustment_delta}")
         return order
         return order
 
 
     @staticmethod
     @staticmethod
@@ -197,13 +264,23 @@ class OrderService:
         page: int = 0,
         page: int = 0,
         size: int = 10,
         size: int = 10,
         keyword: Optional[str] = None,
         keyword: Optional[str] = None,
+        channel_type: Optional[str] = None,
+        handler_id: Optional[str] = None,
+        settlement_status: Optional[str] = None,
     ):
     ):
         stmt = select(VasOrder)
         stmt = select(VasOrder)
+        if channel_type:
+            stmt = stmt.where(VasOrder.channel_type == channel_type)
+        if handler_id:
+            stmt = stmt.where(VasOrder.handler_id == handler_id)
+        if settlement_status:
+            stmt = stmt.where(VasOrder.settlement_status == settlement_status)
+
         query = apply_keyword_search_stmt(
         query = apply_keyword_search_stmt(
             stmt=stmt,
             stmt=stmt,
             model=VasOrder,
             model=VasOrder,
             keyword=keyword,
             keyword=keyword,
-            fields=["id", "user_id", "user_name", "product_name", "user_inputs"],
+            fields=["id", "user_id", "user_name", "product_name", "user_inputs", "handler_id", "agency_id"],
         ).order_by(VasOrder.created_at.desc())
         ).order_by(VasOrder.created_at.desc())
 
 
         return await paginate(db, query, page, size)
         return await paginate(db, query, page, size)
@@ -214,7 +291,6 @@ class OrderService:
         order_id: str,
         order_id: str,
         payload: VasOrderPatchUserInputs,
         payload: VasOrderPatchUserInputs,
     ) -> VasOrder:
     ) -> VasOrder:
-
         stmt = select(VasOrder).where(VasOrder.id == order_id)
         stmt = select(VasOrder).where(VasOrder.id == order_id)
         order = (await db.execute(stmt)).scalar_one_or_none()
         order = (await db.execute(stmt)).scalar_one_or_none()
 
 
@@ -224,7 +300,7 @@ class OrderService:
 
 
         order.user_inputs = payload.user_inputs
         order.user_inputs = payload.user_inputs
 
 
-        # 1️⃣ 取消旧任务
+        # 取消旧任务
         task_res = await db.execute(
         task_res = await db.execute(
             select(VasTask).where(
             select(VasTask).where(
                 VasTask.order_id == order.id,
                 VasTask.order_id == order.id,
@@ -243,3 +319,60 @@ class OrderService:
         logger.info(f"🔄 [ORDER] Patched user inputs for order {order.id}, recreated tasks")
         logger.info(f"🔄 [ORDER] Patched user inputs for order {order.id}, recreated tasks")
         return order
         return order
 
 
+    @staticmethod
+    async def update_order(
+        db: AsyncSession,
+        order_id: str,
+        data: VasOrderUpdate,
+    ) -> VasOrder:
+        stmt = select(VasOrder).where(VasOrder.id == order_id)
+        order = (await db.execute(stmt)).scalar_one_or_none()
+        if not order:
+            logger.warning(f"⚠️ [ORDER] Update failed: Order {order_id} not found")
+            raise NotFoundError("Order not exist")
+
+        if data.channel_type is not None:
+            order.channel_type = data.channel_type
+            if data.channel_type == "agency":
+                if data.agency_id is not None:
+                    order.agency_id = data.agency_id.strip() if data.agency_id else None
+                if data.handler_id is not None:
+                    order.handler_id = data.handler_id.strip() if data.handler_id else None
+                elif order.agency_id:
+                    agency = await AgencyService.get(db, order.agency_id)
+                    if agency and agency.owner_id:
+                        order.handler_id = agency.owner_id
+            elif data.channel_type == "direct":
+                order.agency_id = None
+                if data.handler_id is not None:
+                    order.handler_id = data.handler_id.strip() if data.handler_id else None
+            elif data.channel_type == "website":
+                order.agency_id = None
+                if data.handler_id is not None:
+                    order.handler_id = data.handler_id.strip() if data.handler_id else None
+        else:
+            if data.agency_id is not None:
+                order.agency_id = data.agency_id.strip() if data.agency_id else None
+            if data.handler_id is not None:
+                order.handler_id = data.handler_id.strip() if data.handler_id else None
+
+        if data.status is not None:
+            order.status = data.status
+
+        if data.user_inputs is not None:
+            order.user_inputs = data.user_inputs
+            task_res = await db.execute(
+                select(VasTask).where(
+                    VasTask.order_id == order.id,
+                    VasTask.status.in_(["pending", "grabbed", "running", "pause", "completed"]),
+                )
+            )
+            for task in task_res.scalars().all():
+                task.status = "cancelled"
+            await db.flush()
+            await WebhookService._create_task_if_not_exists(db, order)
+
+        await db.commit()
+        await db.refresh(order)
+        logger.info(f"🔄 [ORDER] Admin updated order: id={order.id} channel={order.channel_type} handler={order.handler_id} agency={order.agency_id}")
+        return order

+ 114 - 0
app/services/payment_service.py

@@ -14,6 +14,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
 from sqlalchemy import select
 from sqlalchemy import select
 
 
 from app.core.logger import logger
 from app.core.logger import logger
+from app.core.config import settings
+from app.core.creem import CreemClient
 from app.utils.search import apply_keyword_search_stmt
 from app.utils.search import apply_keyword_search_stmt
 from app.utils.pagination import paginate
 from app.utils.pagination import paginate
 from app.core.biz_exception import NotFoundError, BizLogicError
 from app.core.biz_exception import NotFoundError, BizLogicError
@@ -153,6 +155,15 @@ class PaymentService:
             await db.commit()
             await db.commit()
             return payment
             return payment
 
 
+        if payload.provider == "creem":
+            payment = await PaymentService.create_creem_payment(
+                db=db,
+                order=order,
+                exchange_config=exchange_config,
+            )
+            await db.commit()
+            return payment
+
         raise BizLogicError("Unsupported provider")
         raise BizLogicError("Unsupported provider")
     
     
     @staticmethod
     @staticmethod
@@ -503,6 +514,85 @@ class PaymentService:
 
 
         return payment
         return payment
 
 
+    @staticmethod
+    async def create_creem_payment(
+        db: AsyncSession,
+        order: VasOrder,
+        exchange_config: Dict,
+    ) -> VasPayment:
+        payment = await PaymentService._create_creem_payment(db, order)
+
+        stmt = select(VasPaymentProvider).where(
+            VasPaymentProvider.enabled == 1,
+            VasPaymentProvider.name == "creem",
+        )
+        provider = (await db.execute(stmt)).scalar_one_or_none()
+        if not provider:
+            raise BizLogicError("Creem provider not enabled")
+
+        provider_config = provider.config if provider.config else {}
+        target_currency = provider.currency or "USD"
+
+        amount_converted = convert_currency(
+            amount=payment.final_amount,
+            from_currency=order.base_currency,
+            to_currency=target_currency,
+            exchange_config=exchange_config,
+        )
+
+        rates = exchange_config.get("rates", {})
+        rate_from = Decimal(str(rates.get(order.base_currency, 1.0)))
+        rate_to = Decimal(str(rates.get(target_currency, 1.0)))
+        if rate_to == 0:
+            raise BizLogicError("Invalid target currency rate (0)")
+        current_exchange_rate = rate_from / rate_to
+
+        payment.exchange_rate = current_exchange_rate
+        payment.amount = int(amount_converted)
+        payment.currency = target_currency
+        payment.random_offset = 0
+
+        # 获取用户邮箱
+        user_email = None
+        user_stmt = select(VasUser).where(VasUser.id == order.user_id)
+        user = (await db.execute(user_stmt)).scalar_one_or_none()
+        if user:
+            user_email = user.email
+
+        # 检查是否已有配置好的 product_id,没有则向 Creem 动态创建
+        creem_product_id = provider_config.get("product_id") or settings.creem_product_id
+        if not creem_product_id:
+            product_name = f"Visa Service #{order.id}"
+            prod_data = await CreemClient.create_product(
+                name=product_name,
+                price_cents=payment.amount,
+                currency=payment.currency,
+                description=f"Visa Application Service Order #{order.id}",
+                billing_type="one_time",
+                provider_config=provider_config,
+            )
+            creem_product_id = prod_data.get("id")
+
+        success_url = f"https://text.skin/dashboard?order_id={order.id}&paid=1"
+
+        checkout_session = await CreemClient.create_checkout_session(
+            product_id=creem_product_id,
+            request_id=f"order_{order.id}_pay_{payment.id}",
+            success_url=success_url,
+            customer_email=user_email,
+            metadata={
+                "order_id": str(order.id),
+                "payment_id": str(payment.id),
+                "user_id": str(order.user_id),
+            },
+            provider_config=provider_config,
+        )
+
+        payment.payment_intent_id = checkout_session.get("id")
+        payment.payment_url = checkout_session.get("checkout_url")
+
+        return payment
+
     @staticmethod
     @staticmethod
     def create_checkout_session(
     def create_checkout_session(
         order: VasOrder,
         order: VasOrder,
@@ -618,6 +708,30 @@ class PaymentService:
         await db.flush()
         await db.flush()
         return payment
         return payment
 
 
+    @staticmethod
+    async def _create_creem_payment(
+        db: AsyncSession,
+        order: VasOrder,
+    ) -> VasPayment:
+        payment = VasPayment(
+            order_id=order.id,
+            provider="creem",
+            channel="online_link",
+            base_amount=order.base_amount,
+            adjustment_delta=order.adjustment_delta,
+            final_amount=order.final_amount,
+            base_currency=order.base_currency,
+            amount=0,
+            currency="USD",
+            random_offset=0,
+            exchange_rate=0,
+            status="pending",
+            expire_at=datetime.utcnow() + timedelta(minutes=30),
+        )
+        db.add(payment)
+        await db.flush()
+        return payment
+
     @staticmethod
     @staticmethod
     async def list_by_order(
     async def list_by_order(
         db: AsyncSession,
         db: AsyncSession,

+ 47 - 4
app/services/plugin_service.py

@@ -22,17 +22,21 @@ class PluginService:
         name: str,
         name: str,
         version: str,
         version: str,
         display_name: Optional[str] = "",
         display_name: Optional[str] = "",
+        filename: Optional[str] = "",
+        class_name: Optional[str] = "",
+        protocol: Optional[str] = "IPlugin",
         description: Optional[str] = "",
         description: Optional[str] = "",
         file: Optional[UploadFile] = None,
         file: Optional[UploadFile] = None,
         download_url: Optional[str] = None,
         download_url: Optional[str] = None,
         sha256: Optional[str] = "",
         sha256: Optional[str] = "",
         changelog: Optional[str] = None,
         changelog: Optional[str] = None,
         set_as_latest: bool = True,
         set_as_latest: bool = True,
+        developer_id: Optional[str] = None,
     ) -> Dict[str, Any]:
     ) -> Dict[str, Any]:
         """
         """
         发布插件新版本:
         发布插件新版本:
         1. 支持直接上传 .py 文件(通过 SeaweedFSService 存储并计算 sha256)或直接传入 download_url
         1. 支持直接上传 .py 文件(通过 SeaweedFSService 存储并计算 sha256)或直接传入 download_url
-        2. 自动更新/创建 plugins 基础信息
+        2. 自动更新/创建 plugins 基础信息(记录开发管理者 developer_id、脚本文件名 filename、入口类名 class_name、协议 protocol)
         3. 记录 plugin_versions 发布历史
         3. 记录 plugin_versions 发布历史
         """
         """
         if not name or not version:
         if not name or not version:
@@ -41,7 +45,11 @@ class PluginService:
         final_download_url = download_url
         final_download_url = download_url
         final_sha256 = (sha256 or "").strip()
         final_sha256 = (sha256 or "").strip()
 
 
+        # 计算并推导文件名
+        resolved_filename = (filename or "").strip()
         if file is not None and file.filename:
         if file is not None and file.filename:
+            if not resolved_filename:
+                resolved_filename = file.filename
             file_bytes = await file.read()
             file_bytes = await file.read()
             if not file_bytes:
             if not file_bytes:
                 raise BizLogicError("Uploaded file is empty")
                 raise BizLogicError("Uploaded file is empty")
@@ -58,20 +66,34 @@ class PluginService:
         if not final_download_url:
         if not final_download_url:
             raise BizLogicError("Either file upload or download_url must be provided")
             raise BizLogicError("Either file upload or download_url must be provided")
 
 
-        filename = f"{name}.py"
+        if not resolved_filename:
+            resolved_filename = f"{name}.py"
+
+        resolved_class_name = (class_name or "").strip()
+        resolved_protocol = (protocol or "").strip() or "IPlugin"
 
 
         # 1. 查找或创建 Plugin 基础记录
         # 1. 查找或创建 Plugin 基础记录
         stmt = select(Plugin).where(Plugin.name == name)
         stmt = select(Plugin).where(Plugin.name == name)
         res = await db.execute(stmt)
         res = await db.execute(stmt)
         plugin = res.scalar_one_or_none()
         plugin = res.scalar_one_or_none()
 
 
+        dev_id = developer_id.strip() if (developer_id and developer_id.strip()) else None
+
         if plugin is None:
         if plugin is None:
+            # 若初次创建且类名未指定,智能推导驼峰类名,如 vfs_plugin -> VFSPlugin
+            if not resolved_class_name:
+                parts = [p.capitalize() for p in name.split("_") if p]
+                resolved_class_name = "".join(parts) or name
+
             plugin = Plugin(
             plugin = Plugin(
                 name=name,
                 name=name,
                 display_name=display_name or name,
                 display_name=display_name or name,
-                filename=filename,
+                filename=resolved_filename,
+                class_name=resolved_class_name,
+                protocol=resolved_protocol,
                 latest_version=version,
                 latest_version=version,
                 description=description or "",
                 description=description or "",
+                developer_id=dev_id,
                 status=1,
                 status=1,
             )
             )
             db.add(plugin)
             db.add(plugin)
@@ -81,7 +103,14 @@ class PluginService:
                 plugin.display_name = display_name
                 plugin.display_name = display_name
             if description is not None and description != "":
             if description is not None and description != "":
                 plugin.description = description
                 plugin.description = description
-            plugin.filename = filename
+            if developer_id is not None:
+                plugin.developer_id = dev_id
+            if resolved_filename:
+                plugin.filename = resolved_filename
+            if resolved_class_name:
+                plugin.class_name = resolved_class_name
+            if resolved_protocol:
+                plugin.protocol = resolved_protocol
             if set_as_latest:
             if set_as_latest:
                 plugin.latest_version = version
                 plugin.latest_version = version
 
 
@@ -122,6 +151,8 @@ class PluginService:
             "version": pv.version,
             "version": pv.version,
             "download_url": pv.download_url,
             "download_url": pv.download_url,
             "sha256": pv.sha256,
             "sha256": pv.sha256,
+            "class_name": plugin.class_name,
+            "protocol": plugin.protocol,
         }
         }
 
 
     @classmethod
     @classmethod
@@ -175,6 +206,7 @@ class PluginService:
             "latest_version": plugin.latest_version,
             "latest_version": plugin.latest_version,
             "description": plugin.description,
             "description": plugin.description,
             "status": plugin.status,
             "status": plugin.status,
+            "developer_id": plugin.developer_id,
             "versions": versions,
             "versions": versions,
         }
         }
 
 
@@ -194,10 +226,19 @@ class PluginService:
 
 
         if plugin_in.display_name is not None:
         if plugin_in.display_name is not None:
             plugin.display_name = plugin_in.display_name
             plugin.display_name = plugin_in.display_name
+        if plugin_in.filename is not None:
+            plugin.filename = plugin_in.filename.strip()
+        if plugin_in.class_name is not None:
+            plugin.class_name = plugin_in.class_name.strip()
+        if plugin_in.protocol is not None:
+            plugin.protocol = plugin_in.protocol.strip()
         if plugin_in.description is not None:
         if plugin_in.description is not None:
             plugin.description = plugin_in.description
             plugin.description = plugin_in.description
         if plugin_in.status is not None:
         if plugin_in.status is not None:
             plugin.status = plugin_in.status
             plugin.status = plugin_in.status
+        if plugin_in.developer_id is not None:
+            dev_id = plugin_in.developer_id.strip()
+            plugin.developer_id = dev_id if dev_id else None
 
 
         await db.commit()
         await db.commit()
         await db.refresh(plugin)
         await db.refresh(plugin)
@@ -350,6 +391,8 @@ class PluginService:
                 "name": p.name,
                 "name": p.name,
                 "display_name": p.display_name,
                 "display_name": p.display_name,
                 "filename": p.filename or f"{p.name}.py",
                 "filename": p.filename or f"{p.name}.py",
+                "class_name": p.class_name or "",
+                "protocol": p.protocol or "IPlugin",
                 "version": p.latest_version,
                 "version": p.latest_version,
                 "description": p.description,
                 "description": p.description,
                 "download_url": pv.download_url if pv else "",
                 "download_url": pv.download_url if pv else "",

+ 13 - 0
app/services/product_service.py

@@ -53,6 +53,19 @@ class ProductService:
         await db.refresh(rec)
         await db.refresh(rec)
         return rec
         return rec
 
 
+    @staticmethod
+    async def delete(
+        db: AsyncSession,
+        id: int,
+    ) -> bool:
+        stmt = select(VasProduct).where(VasProduct.id == id)
+        rec = (await db.execute(stmt)).scalar_one_or_none()
+        if not rec:
+            raise NotFoundError("Product not exist")
+        await db.delete(rec)
+        await db.commit()
+        return True
+
     @staticmethod
     @staticmethod
     async def list_enable_product(
     async def list_enable_product(
         db: AsyncSession,
         db: AsyncSession,

+ 20 - 1
app/services/proxy_service.py

@@ -76,4 +76,23 @@ class ProxyService:
         obj.next_use_time = func.utc_timestamp() + text(f"INTERVAL {proxy_cd} SECOND")
         obj.next_use_time = func.utc_timestamp() + text(f"INTERVAL {proxy_cd} SECOND")
         await db.commit()
         await db.commit()
         await db.refresh(obj)
         await db.refresh(obj)
-        return obj
+        return obj
+
+    @staticmethod
+    async def get_pools(db: AsyncSession):
+        """
+        获取数据库中所有去重的云端代理池及统计
+        """
+        stmt = (
+            select(
+                ProxyPool.pool_name,
+                func.count(ProxyPool.id).label("total_count")
+            )
+            .group_by(ProxyPool.pool_name)
+            .order_by(ProxyPool.pool_name.asc())
+        )
+        res = await db.execute(stmt)
+        return [
+            {"pool_name": row[0], "total_count": row[1]}
+            for row in res.fetchall()
+        ]

+ 366 - 0
app/services/settlement_service.py

@@ -0,0 +1,366 @@
+# app/services/settlement_service.py
+from datetime import datetime
+from typing import List, Dict, Any, Optional
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select, update, and_, or_, func
+from app.models.order import VasOrder
+from app.models.product import VasProduct
+from app.models.plugin import Plugin
+from app.models.cost import VasCostRecord
+from app.models.fault import VasFaultCompensation
+from app.models.settlement import VasSettlementPeriod, VasSettlementDetail
+from app.schemas.settlement import (
+    SettlementPreviewRequest,
+    SettlementConfirmRequest,
+    SettlementPreviewResponse,
+    SettlementPayoutItem,
+    SettlementOrderDetailOut,
+)
+from app.services.cost_service import CostService
+from app.core.biz_exception import BizLogicError, NotFoundError
+from app.utils.pagination import paginate
+
+
+class SettlementService:
+
+    @staticmethod
+    async def _query_eligible_orders(
+        db: AsyncSession,
+        start_date: datetime,
+        end_date: datetime,
+        enforce_risk_cleared: bool = False
+    ) -> List[VasOrder]:
+        """
+        获取账期内履约完成且具备结算资格的订单
+        """
+        # 使用 completed_at 作为履约完成时间,若为NULL则使用 updated_at
+        stmt = select(VasOrder).where(
+            VasOrder.status == 'completed',
+            VasOrder.settlement_status != 'settled',
+            func.coalesce(VasOrder.completed_at, VasOrder.updated_at) >= start_date,
+            func.coalesce(VasOrder.completed_at, VasOrder.updated_at) <= end_date,
+        )
+        if enforce_risk_cleared:
+            now = datetime.utcnow()
+            stmt = stmt.where(
+                (VasOrder.risk_cleared_at == None) | (VasOrder.risk_cleared_at <= now)
+            )
+
+        stmt = stmt.order_by(VasOrder.created_at.asc())
+        return (await db.execute(stmt)).scalars().all()
+
+    @staticmethod
+    async def preview_settlement(
+        db: AsyncSession,
+        req: SettlementPreviewRequest
+    ) -> SettlementPreviewResponse:
+        """
+        试算账期分润(不修改数据库,仅预览计算结果)
+        """
+        orders = await SettlementService._query_eligible_orders(db, req.start_date, req.end_date)
+        costs_summary = await CostService.get_costs_summary_by_date(db, req.start_date, req.end_date)
+        
+        total_revenue = sum(o.final_amount for o in orders)
+        total_cost = sum(costs_summary.values())
+        total_orders = len(orders)
+        avg_cost = (total_cost // total_orders) if total_orders > 0 else 0
+        net_profit = total_revenue - total_cost
+
+        partner_a = req.partner_a_id or "partner_a"
+        partner_b = req.partner_b_id or "partner_b"
+
+        # 预加载当前账期涉及的所有商品与插件,技术分成按订单绑定的商品及处理插件开发管理者自动归属
+        product_ids = {o.product_id for o in orders if o.product_id}
+        products_map: Dict[int, VasProduct] = {}
+        if product_ids:
+            p_stmt = select(VasProduct).where(VasProduct.id.in_(product_ids))
+            p_res = await db.execute(p_stmt)
+            for prod in p_res.scalars().all():
+                products_map[prod.id] = prod
+
+        # 收集商品关联的处理插件
+        plugin_ids = {prod.plugin_id for prod in products_map.values() if getattr(prod, 'plugin_id', None)}
+        plugin_names = set()
+        for prod in products_map.values():
+            if getattr(prod, 'plugin_name', None) and prod.plugin_name.strip():
+                plugin_names.add(prod.plugin_name.strip())
+            if getattr(prod, 'provider', None) and prod.provider.strip():
+                plugin_names.add(prod.provider.strip())
+
+        plugins_map: Dict[str, Plugin] = {}
+        if plugin_ids or plugin_names:
+            conditions = []
+            if plugin_ids:
+                conditions.append(Plugin.id.in_(plugin_ids))
+            if plugin_names:
+                conditions.append(Plugin.name.in_(plugin_names))
+            pl_stmt = select(Plugin).where(or_(*conditions))
+            pl_res = await db.execute(pl_stmt)
+            for pl in pl_res.scalars().all():
+                plugins_map[str(pl.id)] = pl
+                plugins_map[pl.name.lower()] = pl
+
+        def resolve_order_developer(o: VasOrder) -> str:
+            # 1. 订单本身若已记录明确的 developer_id
+            if o.developer_id and o.developer_id.strip():
+                return o.developer_id.strip()
+            # 2. 从订单绑定的商品推断
+            prod = products_map.get(o.product_id)
+            if prod:
+                # 2.1 商品直接指定了底层开发者
+                if getattr(prod, 'developer_id', None) and prod.developer_id.strip():
+                    return prod.developer_id.strip()
+                # 2.2 商品绑定了处理插件 -> 由插件开发管理者 (Plugin.developer_id) 获得技术分成
+                pl = None
+                if getattr(prod, 'plugin_id', None):
+                    pl = plugins_map.get(str(prod.plugin_id))
+                if not pl and getattr(prod, 'plugin_name', None):
+                    pl = plugins_map.get(prod.plugin_name.strip().lower())
+                if not pl and getattr(prod, 'provider', None):
+                    pl = plugins_map.get(prod.provider.strip().lower())
+
+                if pl and getattr(pl, 'developer_id', None) and pl.developer_id.strip():
+                    return pl.developer_id.strip()
+                if pl:
+                    return f"plugin_{pl.name}_dev"
+                if getattr(prod, 'provider', None):
+                    return f"{prod.provider.lower()}_dev"
+            # 3. 兜底
+            return req.default_developer_id or "unassigned_tech"
+
+        # 临时聚合各人的毛利润
+        user_gross_map: Dict[str, Dict[str, int]] = {
+            partner_a: {"pool": 0, "sales": 0, "tech": 0},
+            partner_b: {"pool": 0, "sales": 0, "tech": 0},
+        }
+
+        order_details: List[SettlementOrderDetailOut] = []
+
+        for o in orders:
+            order_profit = o.final_amount - avg_cost
+            dev_id = resolve_order_developer(o)
+
+            if order_profit <= 0:
+                # 亏损或保本单
+                order_details.append(SettlementOrderDetailOut(
+                    order_id=o.id,
+                    channel_type=o.channel_type or "direct",
+                    agency_id=o.agency_id,
+                    handler_id=o.handler_id,
+                    developer_id=dev_id,
+                    order_amount=o.final_amount,
+                    avg_cost=avg_cost,
+                    net_profit=order_profit,
+                    tech_fee=0,
+                    sales_fee=0,
+                    pool_fee=0,
+                    partner_a_amount=0,
+                    partner_b_amount=0,
+                ))
+                continue
+
+            tech_fee = int(order_profit * 0.20)
+            sales_fee = int(order_profit * 0.40)
+            pool_fee = order_profit - tech_fee - sales_fee
+
+            part_a = pool_fee // 2
+            part_b = pool_fee // 2
+
+            if dev_id not in user_gross_map:
+                user_gross_map[dev_id] = {"pool": 0, "sales": 0, "tech": 0}
+            user_gross_map[dev_id]["tech"] += tech_fee
+
+            # 销售提成归属逻辑
+            if o.handler_id:
+                # 社交自收直客单 / 中介单:归该对接人个人
+                h_id = o.handler_id
+                if h_id not in user_gross_map:
+                    user_gross_map[h_id] = {"pool": 0, "sales": 0, "tech": 0}
+                user_gross_map[h_id]["sales"] += sales_fee
+            else:
+                # 官网公海单:甲乙平分 40% 销售提成
+                part_a += sales_fee // 2
+                part_b += sales_fee // 2
+
+            user_gross_map[partner_a]["pool"] += part_a
+            user_gross_map[partner_b]["pool"] += part_b
+
+            order_details.append(SettlementOrderDetailOut(
+                order_id=o.id,
+                channel_type=o.channel_type or "direct",
+                agency_id=o.agency_id,
+                handler_id=o.handler_id,
+                developer_id=dev_id,
+                order_amount=o.final_amount,
+                avg_cost=avg_cost,
+                net_profit=order_profit,
+                tech_fee=tech_fee,
+                sales_fee=sales_fee,
+                pool_fee=pool_fee,
+                partner_a_amount=part_a,
+                partner_b_amount=part_b,
+            ))
+
+        # 查询未核销的个人过错罚单,并从提成中扣除
+        payout_summary: List[SettlementPayoutItem] = []
+        for uid, breakdown in user_gross_map.items():
+            total_user_gross = breakdown["pool"] + breakdown["sales"] + breakdown["tech"]
+            if total_user_gross == 0:
+                continue
+
+            # 查询该用户待扣罚单
+            fault_stmt = select(func.coalesce(func.sum(VasFaultCompensation.penalty_amount), 0)).where(
+                VasFaultCompensation.liable_user_id == uid,
+                VasFaultCompensation.deducted_status == 0
+            )
+            fault_penalty = int((await db.execute(fault_stmt)).scalar() or 0)
+            
+            roles = []
+            if breakdown["pool"] > 0:
+                roles.append(f"合伙分红:{breakdown['pool']/100:.2f}元")
+            if breakdown["sales"] > 0:
+                roles.append(f"销售提成:{breakdown['sales']/100:.2f}元")
+            if breakdown["tech"] > 0:
+                roles.append(f"技术版权:{breakdown['tech']/100:.2f}元")
+
+            net_payout = max(0, total_user_gross - fault_penalty)
+            payout_summary.append(SettlementPayoutItem(
+                user_id=uid,
+                role_description=" | ".join(roles),
+                gross_amount=total_user_gross,
+                fault_penalty=fault_penalty,
+                net_payout=net_payout,
+            ))
+
+        return SettlementPreviewResponse(
+            period_range=f"{req.start_date.strftime('%Y-%m-%d')} ~ {req.end_date.strftime('%Y-%m-%d')}",
+            total_orders=total_orders,
+            total_revenue=total_revenue,
+            total_cost=total_cost,
+            avg_cost=avg_cost,
+            net_profit=net_profit,
+            payout_summary=payout_summary,
+            cost_breakdown=costs_summary,
+            details=order_details,
+        )
+
+    @staticmethod
+    async def confirm_settlement(
+        db: AsyncSession,
+        req: SettlementConfirmRequest,
+        confirmed_by: str
+    ) -> VasSettlementPeriod:
+        """
+        正式确认并冻结账期分润(写入快照,锁定订单状态)
+        """
+        # 1. 检查账期ID是否已存在
+        stmt = select(VasSettlementPeriod).where(VasSettlementPeriod.id == req.period_id)
+        if (await db.execute(stmt)).scalar_one_or_none():
+            raise BizLogicError(f"账期ID '{req.period_id}' 已存在,不可重复生成")
+
+        # 2. 试算结果
+        preview = await SettlementService.preview_settlement(
+            db,
+            SettlementPreviewRequest(
+                start_date=req.start_date,
+                end_date=req.end_date,
+                partner_a_id=req.partner_a_id,
+                partner_b_id=req.partner_b_id,
+                default_developer_id=req.default_developer_id,
+            )
+        )
+
+        now = datetime.utcnow()
+        # 3. 创建账期总表
+        period = VasSettlementPeriod(
+            id=req.period_id,
+            name=req.period_name,
+            start_date=req.start_date,
+            end_date=req.end_date,
+            total_orders=preview.total_orders,
+            total_revenue=preview.total_revenue,
+            total_cost=preview.total_cost,
+            avg_cost=preview.avg_cost,
+            net_profit=preview.net_profit,
+            status='confirmed',
+            summary_data={
+                "payout_summary": [p.dict() for p in preview.payout_summary],
+                "cost_breakdown": preview.cost_breakdown,
+            },
+            confirmed_by=confirmed_by,
+            confirmed_at=now,
+            notes=req.notes,
+        )
+        db.add(period)
+
+        # 4. 插入每单分润快照,并将对应订单状态置为 settled
+        for d in preview.details:
+            detail = VasSettlementDetail(
+                period_id=req.period_id,
+                order_id=d.order_id,
+                channel_type=d.channel_type,
+                agency_id=d.agency_id,
+                handler_id=d.handler_id,
+                developer_id=d.developer_id,
+                order_amount=d.order_amount,
+                avg_cost=d.avg_cost,
+                net_profit=d.net_profit,
+                tech_fee=d.tech_fee,
+                sales_fee=d.sales_fee,
+                pool_fee=d.pool_fee,
+                partner_a_amount=d.partner_a_amount,
+                partner_b_amount=d.partner_b_amount,
+                snapshot=d.dict(),
+            )
+            db.add(detail)
+
+            # 更新订单的结算归属
+            await db.execute(
+                update(VasOrder)
+                .where(VasOrder.id == d.order_id)
+                .values(
+                    settlement_status='settled',
+                    settlement_period_id=req.period_id
+                )
+            )
+
+        # 5. 绑定当期耗材成本的 period_id
+        await db.execute(
+            update(VasCostRecord)
+            .where(
+                VasCostRecord.paid_at >= req.start_date,
+                VasCostRecord.paid_at <= req.end_date,
+                VasCostRecord.period_id == None
+            )
+            .values(period_id=req.period_id)
+        )
+
+        # 6. 将已参与结算扣除的过错记录置为已扣除
+        await db.execute(
+            update(VasFaultCompensation)
+            .where(VasFaultCompensation.deducted_status == 0)
+            .values(
+                deducted_status=1,
+                period_id=req.period_id
+            )
+        )
+
+        await db.commit()
+        await db.refresh(period)
+        return period
+
+    @staticmethod
+    async def get_period(db: AsyncSession, period_id: str) -> Optional[VasSettlementPeriod]:
+        stmt = select(VasSettlementPeriod).where(VasSettlementPeriod.id == period_id)
+        return (await db.execute(stmt)).scalar_one_or_none()
+
+    @staticmethod
+    async def list_periods(db: AsyncSession, page: int = 0, size: int = 20):
+        stmt = select(VasSettlementPeriod).order_by(VasSettlementPeriod.created_at.desc())
+        return await paginate(db, stmt, page, size)
+
+    @staticmethod
+    async def list_period_details(db: AsyncSession, period_id: str, page: int = 0, size: int = 50):
+        stmt = select(VasSettlementDetail).where(VasSettlementDetail.period_id == period_id)
+        stmt = stmt.order_by(VasSettlementDetail.created_at.asc())
+        return await paginate(db, stmt, page, size)

+ 19 - 0
app/services/user_service.py

@@ -115,3 +115,22 @@ class UserService:
         )
         )
 
 
         return await paginate(db, stmt, page, size)
         return await paginate(db, stmt, page, size)
+
+    @staticmethod
+    async def list_admins(db: AsyncSession) -> List[VasUser]:
+        """
+        获取系统管理员与可用合作者/开发者账户列表
+        """
+        stmt = (
+            select(VasUser)
+            .where(VasUser.role.in_(["admin", "super_admin"]))
+            .order_by(VasUser.created_at.asc())
+        )
+        result = await db.execute(stmt)
+        admins = result.scalars().all()
+        if not admins:
+            # 兜底:返回全部用户供选择
+            stmt_all = select(VasUser).order_by(VasUser.created_at.asc()).limit(50)
+            result_all = await db.execute(stmt_all)
+            admins = result_all.scalars().all()
+        return admins

+ 126 - 0
app/services/webhook_service.py

@@ -364,3 +364,129 @@ class WebhookService:
             notify=True,
             notify=True,
         )
         )
 
 
+    # =========================================================
+    # Creem webhook
+    # =========================================================
+    @staticmethod
+    async def creem_payment_webhook(
+        db: AsyncSession,
+        event: dict,
+    ) -> Optional[PaymentWebhookOut]:
+
+        event_id = event.get("id")
+        event_type = event.get("eventType")
+        obj = event.get("object", {})
+
+        if not event_id:
+            logger.error("❌ [WEBHOOK] Missing event id in Creem webhook")
+            return None
+
+        # 1. 幂等性去重
+        existed_stmt = select(VasPaymentEvent).where(
+            VasPaymentEvent.provider == "creem",
+            VasPaymentEvent.event_id == event_id,
+        )
+        existed_result = await db.execute(existed_stmt)
+        if existed_result.scalar_one_or_none():
+            logger.info(f"🔔 [WEBHOOK] Creem duplicate event ignored: {event_id}")
+            return None
+
+        # 2. 仅在 checkout.completed 或 subscription.paid 时核销支付
+        if event_type not in ("checkout.completed", "subscription.paid"):
+            db.add(
+                VasPaymentEvent(
+                    provider="creem",
+                    event_id=event_id,
+                    event_type=event_type or "unknown",
+                    raw_payload=event,
+                    created_at=datetime.utcnow(),
+                    status="ignored"
+                )
+            )
+            await db.commit()
+            return None
+
+        metadata = obj.get("metadata", {})
+        payment_id = metadata.get("payment_id")
+        order_id = metadata.get("order_id")
+
+        # 尝试从 request_id (例如 order_123_pay_456) 解析
+        if not payment_id or not order_id:
+            request_id = obj.get("request_id", "")
+            if request_id.startswith("order_") and "_pay_" in request_id:
+                parts = request_id.split("_")
+                try:
+                    order_id = parts[1]
+                    payment_id = parts[3]
+                except Exception:
+                    pass
+
+        if not payment_id or not order_id:
+            logger.error(f"❌ [WEBHOOK] Missing payment_id or order_id in Creem metadata for event {event_id}")
+            raise BizLogicError("Missing payment_id or order_id in metadata")
+
+        pay_stmt = select(VasPayment).where(VasPayment.id == int(payment_id))
+        pay_result = await db.execute(pay_stmt)
+        payment = pay_result.scalar_one_or_none()
+
+        if not payment:
+            logger.error(f"❌ [WEBHOOK] Creem payment {payment_id} not found")
+            raise NotFoundError("Payment not found")
+
+        if payment.status == "succeeded":
+            db.add(
+                VasPaymentEvent(
+                    provider="creem",
+                    event_id=event_id,
+                    event_type=event_type,
+                    matched_payment_id=payment.id,
+                    raw_payload=event,
+                    status="duplicate",
+                    created_at=datetime.utcnow(),
+                )
+            )
+            await db.commit()
+            logger.info(f"🔔 [WEBHOOK] Creem payment {payment_id} already succeeded (duplicate event)")
+            return None
+
+        now = datetime.utcnow()
+        payment.status = "late_paid" if payment.expire_at and now > payment.expire_at else "succeeded"
+        payment.provider_payload = event
+        payment.updated_at = now
+
+        order_stmt = select(VasOrder).where(VasOrder.id == int(order_id))
+        order_result = await db.execute(order_stmt)
+        order = order_result.scalar_one_or_none()
+
+        if order and order.status != "paid":
+            order.status = "paid"
+            order.updated_at = now
+
+        await WebhookService._create_task_if_not_exists(db, order)
+
+        db.add(
+            VasPaymentEvent(
+                provider="creem",
+                event_id=event_id,
+                event_type=event_type,
+                matched_payment_id=payment.id,
+                matched_order_id=int(order_id),
+                raw_payload=event,
+                status="applied",
+                created_at=now,
+            )
+        )
+
+        await db.commit()
+        await db.refresh(payment)
+
+        logger.info(f"🎉 [WEBHOOK] Creem checkout completed: order={order_id} payment={payment.id} status={payment.status}")
+
+        return PaymentWebhookOut(
+            status=True,
+            order_id=order.id,
+            user_id=order.user_id,
+            payment_id=payment.id,
+            notify=True,
+        )
+

+ 32 - 0
migrate_plugin_cols.py

@@ -0,0 +1,32 @@
+import asyncio
+from sqlalchemy import text
+from app.core.database import engine
+
+async def migrate():
+    async with engine.begin() as conn:
+        # Check existing columns
+        res = await conn.execute(text("""
+            SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
+            WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'plugins';
+        """))
+        cols = [r[0] for r in res.fetchall()]
+        print("Existing columns in plugins:", cols)
+
+        if "class_name" not in cols:
+            print("Adding class_name column...")
+            await conn.execute(text("ALTER TABLE plugins ADD COLUMN class_name VARCHAR(128) NOT NULL DEFAULT '' COMMENT '插件入口类名' AFTER filename;"))
+            print("Added class_name.")
+        else:
+            print("class_name column already exists.")
+
+        if "protocol" not in cols:
+            print("Adding protocol column...")
+            await conn.execute(text("ALTER TABLE plugins ADD COLUMN protocol VARCHAR(64) NOT NULL DEFAULT 'IPlugin' COMMENT '插件协议标识' AFTER class_name;"))
+            print("Added protocol.")
+        else:
+            print("protocol column already exists.")
+
+    print("Migration finished successfully.")
+
+if __name__ == "__main__":
+    asyncio.run(migrate())

+ 34 - 0
scripts/init_settlement_tables.py

@@ -0,0 +1,34 @@
+import asyncio
+import os
+import sys
+
+# 保证根目录在 sys.path
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from app.core.database import engine, Base
+import app.models  # 确保所有模型注册至 Base.metadata
+from app.core.migration import run_settlement_migrations
+
+
+async def init_tables():
+    print("⏳ 正在连接数据库并校验/创建财务结算相关数据表与字段...")
+    try:
+        async with engine.begin() as conn:
+            # 1. 创建新增表 (vas_agency, vas_cost_record, vas_fault_compensation, vas_settlement_period, vas_settlement_detail)
+            await conn.run_sync(Base.metadata.create_all)
+            print("✅ 新增表结构检查/创建完成!")
+
+            # 2. 检查并对原有表增量添加字段
+            await run_settlement_migrations(conn)
+            print("✅ 增量字段平滑迁移完成!")
+
+    except Exception as e:
+        print(f"❌ 初始化失败: {e}")
+        import traceback
+        traceback.print_exc()
+    finally:
+        await engine.dispose()
+
+
+if __name__ == "__main__":
+    asyncio.run(init_tables())

+ 43 - 0
scripts/inspect_web_ui.py

@@ -0,0 +1,43 @@
+import os
+import json
+
+base_dir = r"E:\workDir\web-ui"
+output_file = r"e:\workDir\webapp\web_ui_info.json"
+
+print(f"⏳ 正在扫描前端项目 {base_dir} ...")
+
+def scan_dir(path, max_depth=3, current_depth=0):
+    if current_depth > max_depth:
+        return {}
+    res = {}
+    try:
+        for item in os.listdir(path):
+            if item in ["node_modules", ".git", ".next", "dist", "build"]:
+                continue
+            item_path = os.path.join(path, item)
+            if os.path.isdir(item_path):
+                res[item] = scan_dir(item_path, max_depth, current_depth + 1)
+            else:
+                res[item] = "file"
+    except Exception as e:
+        res["_error"] = str(e)
+    return res
+
+info = {
+    "tree": scan_dir(base_dir),
+    "package_json": None,
+    "routes": None
+}
+
+pkg_path = os.path.join(base_dir, "package.json")
+if os.path.exists(pkg_path):
+    with open(pkg_path, "r", encoding="utf-8") as f:
+        try:
+            info["package_json"] = json.load(f)
+        except Exception:
+            info["package_json"] = f.read()
+
+with open(output_file, "w", encoding="utf-8") as f:
+    json.dump(info, f, ensure_ascii=False, indent=2)
+
+print(f"✅ 扫描完成,结果已保存至 {output_file}")

+ 24 - 0
scripts/link_web_ui.py

@@ -0,0 +1,24 @@
+import os
+import sys
+
+src = r"E:\workDir\web-ui"
+dst = r"e:\workDir\webapp\web-ui"
+
+print(f"⏳ 正在将 {src} 联接到 {dst} ...")
+
+if os.path.exists(dst):
+    print("✅ 目标链接已存在,无需重复创建!")
+    sys.exit(0)
+
+try:
+    # Python 3.8+ 支持在 Windows 上自动创建目录软链接 / Junction
+    os.symlink(src, dst, target_is_directory=True)
+    print("✅ 目录链接创建成功!")
+except Exception as e:
+    try:
+        import _winapi
+        _winapi.CreateJunction(src, dst)
+        print("✅ 通过 Windows Junction 链接创建成功!")
+    except Exception as e2:
+        print(f"❌ 创建失败: {e2}")
+        sys.exit(1)