ソースを参照

feat: add provider templates and refactor node configuration endpoints

jerry 2 ヶ月 前
親
コミット
fbb82bb807

+ 197 - 101
app/api/endpoints/node_configuration.py

@@ -1,163 +1,259 @@
-from typing import Optional
+import json
+from datetime import datetime
+from typing import Optional, Dict, Any, List
 from fastapi import APIRouter, Depends, Query, Body
 from sqlalchemy.ext.asyncio import AsyncSession
+from redis.asyncio import Redis
 
 from app.core.database import get_db
+from app.core.redis import get_redis_client
 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
 from app.schemas.node_configuration import (
-    NodeConfigurationSaveRequest,
-    NodeConfigurationToggleRequest,
-    NodeConfigurationCloneRequest,
-    NodeConfigurationDeleteRequest,
-    NodeConfigurationDetailOut,
-    NodeConfigurationListItem,
+    NodeConfigurationSparseUpdateRequest,
+    NodeConfigurationEnableRequest,
+    NodeConfigurationRollbackRequest,
     NodeConfigurationListResponse,
-    NodeConfigAuditLogItem,
-    NodeConfigAuditLogListResponse,
 )
 from app.services.node_configuration_service import NodeConfigurationService
 
-admin_required_router = APIRouter()
+public_router = APIRouter()
+protected_router = APIRouter()
+admin_required_router = APIRouter(prefix="/node-configurations", tags=["节点配置管理"])
 
 
 @admin_required_router.get(
-    "/node_configurations/detail",
-    summary="获取节点配置详情(Worker 轮询与详情查询)",
-    tags=["节点配置管理"],
-    response_model=ApiResponse[NodeConfigurationDetailOut],
+    "/runtime-status",
+    summary="获取各Worker节点实时上报状态与心跳",
+    response_model=ApiResponse[Dict[str, Any]],
 )
-async def get_node_configuration_detail(
-    role: str = Query(..., description="角色类型: sentinel / booker / standalone"),
-    node_id: str = Query(..., description="节点唯一标识,如 node01"),
-    db: AsyncSession = Depends(get_db),
+async def get_runtime_status(
+    role: Optional[str] = Query(None, description="角色筛选: standalone / booker / sentinel"),
+    node_id: Optional[str] = Query(None, description="节点 ID 筛选"),
+    redis_client: Redis = Depends(get_redis_client),
 ):
-    node_config = await NodeConfigurationService.get_detail(db, role=role, node_id=node_id)
-    return success(data=node_config)
+    pattern = f"vs:status:{role or '*'}:{node_id or '*'}"
+    keys = await redis_client.keys(pattern)
+    nodes = []
+    now = datetime.utcnow()
+
+    for k in keys:
+        try:
+            raw = await redis_client.get(k)
+            if not raw:
+                continue
+            data = json.loads(raw)
+            collected_at_str = data.get("collected_at", "")
+            is_online = False
+            age_sec = 999999
+            if collected_at_str:
+                try:
+                    dt = datetime.strptime(collected_at_str, "%Y-%m-%d %H:%M:%S")
+                    age_sec = max(0, int((now - dt).total_seconds()))
+                    is_online = age_sec <= 60
+                except Exception:
+                    is_online = True
+
+            nodes.append({
+                "role": data.get("role") or (k.split(":")[2] if len(k.split(":")) > 2 else ""),
+                "node_id": data.get("node_id") or (k.split(":")[3] if len(k.split(":")) > 3 else ""),
+                "is_online": is_online,
+                "age_sec": age_sec,
+                "installed_plugins": data.get("installed_plugins", []),
+                "groups": data.get("groups", []),
+                "collected_at": collected_at_str,
+            })
+        except Exception:
+            continue
+
+    nodes.sort(key=lambda x: (x.get("role", ""), x.get("node_id", "")))
+    return success(data={"nodes": nodes, "timestamp": now.strftime("%Y-%m-%d %H:%M:%S")})
 
 
 @admin_required_router.get(
-    "/node_configurations/list",
-    summary="查询节点配置列表(支持多条件过滤与分页)",
-    tags=["节点配置管理"],
+    "/{entry_type}",
+    summary="分页查询配置条目列表",
     response_model=ApiResponse[NodeConfigurationListResponse],
 )
 async def list_node_configurations(
-    role: Optional[str] = Query(None, description="过滤角色类型"),
-    node_id: Optional[str] = Query(None, description="过滤节点标识 (支持模糊搜索)"),
-    is_enabled: Optional[int] = Query(None, description="过滤启用状态: 1-启用, 0-禁用"),
+    entry_type: str,
     page: int = Query(1, ge=1, description="页码"),
-    page_size: int = Query(20, ge=1, le=100, description="每页条数"),
+    pageSize: int = Query(20, ge=1, le=100, description="每页数量", alias="pageSize"),
+    identifier: Optional[str] = Query(None, description="任务标识模糊搜索"),
+    node_id: Optional[str] = Query(None, description="节点唯一标识精确搜索"),
+    order_id: Optional[str] = Query(None, description="订单ID (仅 standalone)"),
     db: AsyncSession = Depends(get_db),
 ):
-    total, items = await NodeConfigurationService.list_configs(
-        db,
-        role=role,
-        node_id=node_id,
-        is_enabled=is_enabled,
+    total, items = await NodeConfigurationService.list_entries(
+        db=db,
+        entry_type=entry_type,
         page=page,
-        page_size=page_size,
+        page_size=pageSize,
+        identifier=identifier,
+        node_id=node_id,
+        order_id=order_id,
     )
     return success(
-        data=NodeConfigurationListResponse(
-            total=total,
-            items=[NodeConfigurationListItem.model_validate(item) for item in items],
-        )
+        data={
+            "total": total,
+            "page": page,
+            "page_size": pageSize,
+            "items": items,
+        }
     )
 
 
-@admin_required_router.post(
-    "/node_configurations/save",
-    summary="保存/更新节点配置 (Save / Upsert)",
-    tags=["节点配置管理"],
-    response_model=ApiResponse[NodeConfigurationDetailOut],
+@admin_required_router.get(
+    "/{entry_type}/{entry_id}",
+    summary="获取指定配置条目详情",
+    response_model=ApiResponse[Dict[str, Any]],
 )
-async def save_node_configuration(
-    payload: NodeConfigurationSaveRequest = Body(...),
-    current_user: VasUser = Depends(get_current_user),
+async def get_node_configuration_detail(
+    entry_type: str,
+    entry_id: int,
     db: AsyncSession = Depends(get_db),
 ):
-    operator = (current_user.email or current_user.nickname or current_user.id) if current_user else "system"
-    saved = await NodeConfigurationService.save_config(db, payload, operator=operator)
-    return success(data=saved, message="Configuration saved successfully")
+    entry = await NodeConfigurationService.get_entry(
+        db=db, entry_type=entry_type, entry_id=entry_id
+    )
+    return success(data=entry)
 
 
 @admin_required_router.post(
-    "/node_configurations/toggle",
-    summary="快速启用/禁用节点配置",
-    tags=["节点配置管理"],
-    response_model=ApiResponse[NodeConfigurationDetailOut],
+    "/{entry_type}",
+    summary="新建配置条目 (默认停用落库)",
+    response_model=ApiResponse[Dict[str, Any]],
 )
-async def toggle_node_configuration(
-    payload: NodeConfigurationToggleRequest = Body(...),
-    current_user: VasUser = Depends(get_current_user),
+async def create_node_configuration(
+    entry_type: str,
+    data: Dict[str, Any] = Body(...),
+    current_user: Optional[VasUser] = Depends(get_current_user),
     db: AsyncSession = Depends(get_db),
 ):
-    operator = (current_user.email or current_user.nickname or current_user.id) if current_user else "system"
-    updated = await NodeConfigurationService.toggle_config(db, payload, operator=operator)
-    return success(data=updated, message="Configuration status updated successfully")
+    operator = (
+        current_user.email or current_user.nickname if current_user else "admin"
+    )
+    entry = await NodeConfigurationService.create_entry(
+        db=db,
+        entry_type=entry_type,
+        data=data,
+        operator=operator,
+    )
+    return success(data=entry, message="Node configuration created successfully")
 
 
-@admin_required_router.post(
-    "/node_configurations/clone",
-    summary="从源节点复制克隆配置",
-    tags=["节点配置管理"],
-    response_model=ApiResponse[NodeConfigurationDetailOut],
+@admin_required_router.put(
+    "/{entry_type}/{entry_id}",
+    summary="稀疏更新配置条目 (支持点路径更新与字段清空)",
+    response_model=ApiResponse[Dict[str, Any]],
 )
-async def clone_node_configuration(
-    payload: NodeConfigurationCloneRequest = Body(...),
-    current_user: VasUser = Depends(get_current_user),
+async def sparse_update_node_configuration(
+    entry_type: str,
+    entry_id: int,
+    payload: NodeConfigurationSparseUpdateRequest = Body(...),
+    current_user: Optional[VasUser] = Depends(get_current_user),
     db: AsyncSession = Depends(get_db),
 ):
-    operator = (current_user.email or current_user.nickname or current_user.id) if current_user else "system"
-    cloned = await NodeConfigurationService.clone_config(db, payload, operator=operator)
-    return success(data=cloned, message="Configuration cloned successfully")
+    operator = (
+        current_user.email or current_user.nickname if current_user else "admin"
+    )
+    entry = await NodeConfigurationService.sparse_update_entry(
+        db=db,
+        entry_type=entry_type,
+        entry_id=entry_id,
+        set_data=payload.set,
+        clear_fields=payload.clear,
+        base_version=payload.base_version,
+        operator=operator,
+    )
+    return success(data=entry, message="Node configuration updated successfully")
+
+
+@admin_required_router.put(
+    "/{entry_type}/{entry_id}/enable",
+    summary="启用 / 停用配置条目",
+    response_model=ApiResponse[Dict[str, Any]],
+)
+async def toggle_node_configuration_enable(
+    entry_type: str,
+    entry_id: int,
+    payload: NodeConfigurationEnableRequest = Body(...),
+    current_user: Optional[VasUser] = Depends(get_current_user),
+    db: AsyncSession = Depends(get_db),
+):
+    operator = (
+        current_user.email or current_user.nickname if current_user else "admin"
+    )
+    entry = await NodeConfigurationService.toggle_enable(
+        db=db,
+        entry_type=entry_type,
+        entry_id=entry_id,
+        enable=payload.enable,
+        base_version=payload.base_version,
+        operator=operator,
+    )
+    return success(data=entry, message="Node configuration status toggled")
 
 
 @admin_required_router.delete(
-    "/node_configurations/delete",
-    summary="删除节点配置",
-    tags=["节点配置管理"],
-    response_model=ApiResponse[dict],
+    "/{entry_type}/{entry_id}",
+    summary="删除配置条目 (最后一条需 confirm_purge=true)",
+    response_model=ApiResponse[bool],
 )
 async def delete_node_configuration(
-    role: str = Query(..., description="角色类型"),
-    node_id: str = Query(..., description="节点标识"),
-    remark: Optional[str] = Query("", description="删除原因"),
-    current_user: VasUser = Depends(get_current_user),
+    entry_type: str,
+    entry_id: int,
+    confirm_purge: bool = Query(False, description="最后一条数据确认删除标记"),
     db: AsyncSession = Depends(get_db),
 ):
-    operator = (current_user.email or current_user.nickname or current_user.id) if current_user else "system"
-    req = NodeConfigurationDeleteRequest(role=role, node_id=node_id, operator=operator, remark=remark)
-    await NodeConfigurationService.delete_config(db, req, operator=operator)
-    return success(data={"role": role, "node_id": node_id, "deleted": True}, message="Configuration deleted successfully")
+    await NodeConfigurationService.delete_entry(
+        db=db,
+        entry_type=entry_type,
+        entry_id=entry_id,
+        confirm_purge=confirm_purge,
+    )
+    return success(data=True, message="Node configuration deleted successfully")
 
 
 @admin_required_router.get(
-    "/node_configurations/audit-logs",
-    summary="查询配置修改审计日志",
-    tags=["节点配置管理"],
-    response_model=ApiResponse[NodeConfigAuditLogListResponse],
+    "/{entry_type}/{entry_id}/revisions",
+    summary="获取配置条目修订历史记录",
+    response_model=ApiResponse[List[Dict[str, Any]]],
 )
-async def list_node_config_audit_logs(
-    role: Optional[str] = Query(None, description="过滤角色类型"),
-    node_id: Optional[str] = Query(None, description="过滤节点标识"),
-    page: int = Query(1, ge=1, description="页码"),
-    page_size: int = Query(20, ge=1, le=100, description="每页条数"),
+async def get_node_configuration_revisions(
+    entry_type: str,
+    entry_id: int,
     db: AsyncSession = Depends(get_db),
 ):
-    total, logs = await NodeConfigurationService.get_audit_logs(
-        db,
-        role=role,
-        node_id=node_id,
-        page=page,
-        page_size=page_size,
+    revisions = await NodeConfigurationService.get_revisions(
+        db=db, entry_type=entry_type, entry_id=entry_id
     )
-    return success(
-        data=NodeConfigAuditLogListResponse(
-            total=total,
-            items=[NodeConfigAuditLogItem.model_validate(log) for log in logs],
-        )
+    return success(data=revisions)
+
+
+@admin_required_router.post(
+    "/{entry_type}/{entry_id}/rollback",
+    summary="回滚配置条目至指定历史修订版本",
+    response_model=ApiResponse[Dict[str, Any]],
+)
+async def rollback_node_configuration(
+    entry_type: str,
+    entry_id: int,
+    payload: NodeConfigurationRollbackRequest = Body(...),
+    current_user: Optional[VasUser] = Depends(get_current_user),
+    db: AsyncSession = Depends(get_db),
+):
+    operator = (
+        current_user.email or current_user.nickname if current_user else "admin"
+    )
+    entry = await NodeConfigurationService.rollback_revision(
+        db=db,
+        entry_type=entry_type,
+        entry_id=entry_id,
+        revision_id=payload.revision_id,
+        base_version=payload.base_version,
+        operator=operator,
     )
+    return success(data=entry, message="Node configuration rolled back successfully")

+ 98 - 0
app/api/endpoints/provider.py

@@ -0,0 +1,98 @@
+from typing import List, Optional
+from fastapi import APIRouter, Depends, Query, Body
+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
+from app.schemas.provider import (
+    ProviderCreate,
+    ProviderUpdate,
+    ProviderOut,
+    ProviderListItemOut,
+)
+from app.services.provider_service import ProviderService
+
+public_router = APIRouter()
+protected_router = APIRouter()
+admin_required_router = APIRouter(prefix="/providers", tags=["服务商模板管理"])
+
+
+@admin_required_router.get(
+    "",
+    summary="获取服务商目录列表",
+    response_model=ApiResponse[List[ProviderListItemOut]],
+)
+async def list_providers(
+    enabled_only: bool = Query(False, description="仅返回启用状态的服务商 (向导下拉使用)"),
+    db: AsyncSession = Depends(get_db),
+):
+    providers = await ProviderService.list_providers(db=db, enabled_only=enabled_only)
+    return success(data=providers)
+
+
+@admin_required_router.get(
+    "/{name}",
+    summary="获取服务商详情",
+    response_model=ApiResponse[ProviderOut],
+)
+async def get_provider_detail(
+    name: str,
+    db: AsyncSession = Depends(get_db),
+):
+    provider = await ProviderService.get_provider_by_name(db=db, name=name)
+    return success(data=provider)
+
+
+@admin_required_router.post(
+    "",
+    summary="新建服务商模板",
+    response_model=ApiResponse[ProviderOut],
+)
+async def create_provider(
+    payload: ProviderCreate = Body(...),
+    current_user: Optional[VasUser] = Depends(get_current_user),
+    db: AsyncSession = Depends(get_db),
+):
+    operator = (
+        current_user.email or current_user.nickname if current_user else "admin"
+    )
+    provider = await ProviderService.create_provider(
+        db=db, payload=payload, operator=operator
+    )
+    return success(data=provider, message="Provider created successfully")
+
+
+@admin_required_router.put(
+    "/{name}",
+    summary="编辑服务商模板 (稀疏更新)",
+    response_model=ApiResponse[ProviderOut],
+)
+async def update_provider(
+    name: str,
+    payload: ProviderUpdate = Body(...),
+    current_user: Optional[VasUser] = Depends(get_current_user),
+    db: AsyncSession = Depends(get_db),
+):
+    operator = (
+        current_user.email or current_user.nickname if current_user else "admin"
+    )
+    provider = await ProviderService.update_provider(
+        db=db, name=name, payload=payload, operator=operator
+    )
+    return success(data=provider, message="Provider updated successfully")
+
+
+@admin_required_router.delete(
+    "/{name}",
+    summary="删除服务商模板",
+    response_model=ApiResponse[bool],
+)
+async def delete_provider(
+    name: str,
+    db: AsyncSession = Depends(get_db),
+):
+    await ProviderService.delete_provider(db=db, name=name)
+    return success(data=True, message="Provider deleted successfully")

+ 4 - 2
app/api/router.py

@@ -5,13 +5,14 @@ from app.api.endpoints import (
     auth,
     common,
     config,
+    node_configuration,
     email,
     notification,
     order,
     payment,
     plugin,
-    node_configuration,
     product,
+    provider,
     proxy,
     slot,
     sms,
@@ -35,13 +36,14 @@ _modules = [
     auth,
     common,
     config,
+    node_configuration,
     email,
     notification,
     order,
     payment,
     plugin,
-    node_configuration,
     product,
+    provider,
     proxy,
     slot,
     sms,

+ 7 - 1
app/models/__init__.py

@@ -7,5 +7,11 @@ from .configuration import Configuration
 from .notification_outbox import NotificationOutbox
 from .emails import VasEmail
 from .plugin import Plugin, PluginVersion
-from .node_configuration import NodeConfiguration, NodeConfigAuditLog
+from .node_configuration import (
+    BookerEntry,
+    SentinelEntry,
+    StandaloneEntry,
+    NodeConfigurationRevision,
+)
+from .provider import Provider
 

+ 109 - 33
app/models/node_configuration.py

@@ -1,57 +1,133 @@
 from datetime import datetime
 from sqlalchemy import (
     Column,
+    Integer,
     BigInteger,
-    String,
-    JSON,
     SmallInteger,
+    String,
     DateTime,
+    JSON,
     UniqueConstraint,
     Index,
 )
 from app.core.database import Base
 
 
-class NodeConfiguration(Base):
-    """
-    节点角色配置主表
-    """
-    __tablename__ = "node_configurations"
+class BookerEntry(Base):
+    __tablename__ = "booker_entries"
 
     id = Column(BigInteger, primary_key=True, autoincrement=True)
-    role = Column(String(32), nullable=False, comment="角色类型: sentinel / booker / standalone")
-    node_id = Column(String(64), nullable=False, comment="节点唯一标识,如: node01")
-    config_content = Column(JSON, nullable=False, comment="完整配置内容 (JSON 数组或 JSON 对象)")
-    config_hash = Column(String(32), nullable=False, index=True, comment="配置内容 MD5 哈希,用于节点秒级比对")
-    is_enabled = Column(SmallInteger, nullable=False, default=1, index=True, comment="是否启用: 1-启用, 0-禁用")
-    description = Column(String(255), nullable=True, default="", comment="配置用途/备注说明")
-    created_by = Column(String(64), nullable=True, default="system", comment="创建人")
-    updated_by = Column(String(64), nullable=True, default="system", comment="最后更新人")
-    created_at = Column(DateTime, default=datetime.utcnow, nullable=False, comment="创建时间")
-    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, comment="更新时间")
+    node_id = Column(String(64), nullable=False)
+    identifier = Column(String(64), nullable=False)
+    enable = Column(SmallInteger, nullable=False, default=0)
+    debug = Column(SmallInteger, nullable=False, default=0)
+    need_account = Column(SmallInteger, nullable=False, default=1)
+    need_proxy = Column(SmallInteger, nullable=False, default=1)
+    proxy_pool = Column(JSON, nullable=False, default=list)
+    proxy_cd = Column(Integer, nullable=False, default=300)
+    session_max_life = Column(Integer, nullable=False, default=1800)
+    active_time_start = Column(String(5), nullable=False, default="00:00")
+    active_time_end = Column(String(5), nullable=False, default="23:59")
+    website = Column(String(512), nullable=False, default="")
+    booker = Column(JSON, nullable=False, default=dict)
+    plugin_config = Column(JSON, nullable=False, default=dict)
+    appointment_types = Column(JSON, nullable=False, default=list)
+    free_config = Column(JSON, nullable=False, default=dict)
+    version = Column(Integer, nullable=False, default=0)
+    updated_by = Column(String(64), nullable=True, default="system")
+    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", "identifier", name="uk_booker_node_identifier"),
+        Index("idx_booker_identifier", "identifier"),
+        Index("idx_booker_updated_at", "updated_at"),
+    )
+
+
+class SentinelEntry(Base):
+    __tablename__ = "sentinel_entries"
+
+    id = Column(BigInteger, primary_key=True, autoincrement=True)
+    node_id = Column(String(64), nullable=False)
+    identifier = Column(String(64), nullable=False)
+    enable = Column(SmallInteger, nullable=False, default=0)
+    debug = Column(SmallInteger, nullable=False, default=0)
+    need_account = Column(SmallInteger, nullable=False, default=1)
+    need_proxy = Column(SmallInteger, nullable=False, default=1)
+    proxy_pool = Column(JSON, nullable=False, default=list)
+    proxy_cd = Column(Integer, nullable=False, default=300)
+    session_max_life = Column(Integer, nullable=False, default=1800)
+    active_time_start = Column(String(5), nullable=False, default="00:00")
+    active_time_end = Column(String(5), nullable=False, default="23:59")
+    website = Column(String(512), nullable=False, default="")
+    sentinel = Column(JSON, nullable=False, default=dict)
+    plugin_config = Column(JSON, nullable=False, default=dict)
+    appointment_types = Column(JSON, nullable=False, default=list)
+    free_config = Column(JSON, nullable=False, default=dict)
+    version = Column(Integer, nullable=False, default=0)
+    updated_by = Column(String(64), nullable=True, default="system")
+    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", "identifier", name="uk_sentinel_node_identifier"),
+        Index("idx_sentinel_identifier", "identifier"),
+        Index("idx_sentinel_updated_at", "updated_at"),
+    )
+
+
+class StandaloneEntry(Base):
+    __tablename__ = "standalone_entries"
+
+    id = Column(BigInteger, primary_key=True, autoincrement=True)
+    node_id = Column(String(64), nullable=False)
+    order_id = Column(String(64), nullable=True)
+    identifier = Column(String(64), nullable=False)
+    enable = Column(SmallInteger, nullable=False, default=1)
+    debug = Column(SmallInteger, nullable=False, default=0)
+    plugin_config = Column(JSON, nullable=False, default=dict)
+    account = Column(JSON, nullable=False, default=dict)
+    proxy_pool = Column(JSON, nullable=False, default=list)
+    query_wait = Column(JSON, nullable=False, default=dict)
+    login_interval = Column(Integer, nullable=False, default=1800)
+    session_max_life = Column(Integer, nullable=False, default=1800)
+    active_time_start = Column(String(5), nullable=False, default="00:00")
+    active_time_end = Column(String(5), nullable=False, default="23:59")
+    appointment_types = Column(JSON, nullable=False, default=list)
+    user_preferences = Column(JSON, nullable=False, default=dict)
+    free_config = Column(JSON, nullable=False, default=dict)
+    version = Column(Integer, nullable=False, default=0)
+    updated_by = Column(String(64), nullable=True, default="system")
+    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
+    updated_at = Column(
+        DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
+    )
 
     __table_args__ = (
-        UniqueConstraint("role", "node_id", name="uk_role_node"),
-        Index("idx_node_config_updated_at", "updated_at"),
+        UniqueConstraint("node_id", "identifier", name="uk_standalone_node_identifier"),
+        Index("idx_standalone_identifier", "identifier"),
+        Index("idx_standalone_order_id", "order_id"),
+        Index("idx_standalone_updated_at", "updated_at"),
     )
 
 
-class NodeConfigAuditLog(Base):
-    """
-    配置修改审计日志表
-    """
-    __tablename__ = "node_config_audit_logs"
+class NodeConfigurationRevision(Base):
+    __tablename__ = "node_configuration_revisions"
 
     id = Column(BigInteger, primary_key=True, autoincrement=True)
-    role = Column(String(32), nullable=False, comment="角色类型")
-    node_id = Column(String(64), nullable=False, comment="节点标识")
-    action = Column(String(32), nullable=False, comment="操作类型: CREATE / UPDATE / TOGGLE / DELETE / CLONE")
-    before_hash = Column(String(32), nullable=True, comment="修改前配置 Hash")
-    after_hash = Column(String(32), nullable=True, comment="修改后配置 Hash")
-    operator = Column(String(64), nullable=False, default="system", comment="操作人")
-    remark = Column(String(500), nullable=True, default="", comment="修改原因或备注说明")
-    created_at = Column(DateTime, default=datetime.utcnow, nullable=False, comment="操作时间")
+    entry_type = Column(String(32), nullable=False, index=True)
+    entry_id = Column(BigInteger, nullable=False, index=True)
+    version = Column(Integer, nullable=False, default=0)
+    action = Column(String(32), nullable=False, default="update")
+    snapshot = Column(JSON, nullable=False, default=dict)
+    updated_by = Column(String(64), nullable=True, default="system")
+    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
 
     __table_args__ = (
-        Index("idx_role_node_time", "role", "node_id", "created_at"),
+        Index("idx_node_config_rev_type_id", "entry_type", "entry_id"),
     )

+ 35 - 0
app/models/provider.py

@@ -0,0 +1,35 @@
+from datetime import datetime
+from sqlalchemy import (
+    Column,
+    Integer,
+    BigInteger,
+    SmallInteger,
+    String,
+    DateTime,
+    JSON,
+    UniqueConstraint,
+    Index,
+)
+from app.core.database import Base
+
+
+class Provider(Base):
+    __tablename__ = "providers"
+
+    id = Column(BigInteger, primary_key=True, autoincrement=True)
+    name = Column(String(128), nullable=False, unique=True, index=True)
+    enabled = Column(SmallInteger, nullable=False, default=1)
+    plugin_config = Column(JSON, nullable=False, default=dict)
+    role_templates = Column(JSON, nullable=False, default=dict)
+    version = Column(Integer, nullable=False, default=0)
+    updated_by = Column(String(64), nullable=True, default="system")
+    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
+    updated_at = Column(
+        DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
+    )
+
+    __table_args__ = (
+        UniqueConstraint("name", name="uk_providers_name"),
+        Index("idx_providers_enabled", "enabled"),
+        Index("idx_providers_updated_at", "updated_at"),
+    )

+ 169 - 89
app/schemas/node_configuration.py

@@ -1,100 +1,180 @@
 from datetime import datetime
-from typing import Optional, Any, List, Union
-from pydantic import BaseModel, Field, field_validator
-
-
-class NodeConfigurationSaveRequest(BaseModel):
-    role: str = Field(..., description="角色类型,如 sentinel / booker / standalone")
-    node_id: str = Field(..., description="节点唯一标识,如 node01")
-    config_content: Union[List[Any], dict] = Field(..., description="完整配置内容 (JSON 数组或 JSON 对象)")
-    is_enabled: Optional[int] = Field(1, description="是否启用: 1-启用, 0-禁用")
-    description: Optional[str] = Field("", description="配置用途/备注说明")
-    operator: Optional[str] = Field("system", description="操作人")
-    remark: Optional[str] = Field("", description="修改原因或备注说明")
-
-    @field_validator("config_content")
-    @classmethod
-    def validate_config_content(cls, v):
-        if not isinstance(v, (list, dict)):
-            raise ValueError("config_content 必须是 JSON 对象 (dict) 或 JSON 数组 (list)")
-        return v
-
-
-class NodeConfigurationToggleRequest(BaseModel):
-    role: str = Field(..., description="角色类型")
-    node_id: str = Field(..., description="节点标识")
-    is_enabled: int = Field(..., description="是否启用: 1-启用, 0-禁用")
-    operator: Optional[str] = Field("system", description="操作人")
-    remark: Optional[str] = Field("", description="操作备注")
-
-
-class NodeConfigurationCloneRequest(BaseModel):
-    source_role: str = Field(..., description="源角色类型")
-    source_node_id: str = Field(..., description="源节点标识")
-    target_role: str = Field(..., description="目标角色类型")
-    target_node_id: str = Field(..., description="目标节点标识")
-    operator: Optional[str] = Field("system", description="操作人")
-    remark: Optional[str] = Field("", description="操作备注")
-
-
-class NodeConfigurationDeleteRequest(BaseModel):
-    role: str = Field(..., description="角色类型")
-    node_id: str = Field(..., description="节点标识")
-    operator: Optional[str] = Field("system", description="操作人")
-    remark: Optional[str] = Field("", description="操作备注")
-
-
-class NodeConfigurationDetailOut(BaseModel):
+from enum import Enum
+from typing import Optional, List, Dict, Any
+from pydantic import BaseModel, Field, ConfigDict
+
+
+class EntryTypeEnum(str, Enum):
+    booker = "booker"
+    sentinel = "sentinel"
+    standalone = "standalone"
+
+
+class BaseEntrySchema(BaseModel):
+    model_config = ConfigDict(from_attributes=True)
+
+
+class BookerEntryCreate(BaseModel):
+    node_id: Optional[str] = "default"
+    identifier: str
+    enable: Optional[int] = 0
+    debug: Optional[int] = 0
+    need_account: Optional[int] = 1
+    need_proxy: Optional[int] = 1
+    proxy_pool: Optional[List[str]] = Field(default_factory=list)
+    proxy_cd: Optional[int] = 300
+    session_max_life: Optional[int] = 1800
+    active_time_start: Optional[str] = "00:00"
+    active_time_end: Optional[str] = "23:59"
+    website: Optional[str] = ""
+    booker: Optional[Dict[str, Any]] = Field(default_factory=dict)
+    plugin_config: Optional[Dict[str, Any]] = Field(default_factory=dict)
+    appointment_types: Optional[List[Dict[str, Any]]] = Field(default_factory=list)
+    free_config: Optional[Dict[str, Any]] = Field(default_factory=dict)
+    updated_by: Optional[str] = "system"
+
+
+class BookerEntryOut(BaseEntrySchema):
     id: int
-    role: str
     node_id: str
-    is_enabled: int
-    config_hash: str
-    config_content: Any
-    description: Optional[str] = ""
-    created_by: Optional[str] = None
-    updated_by: Optional[str] = None
-    created_at: Optional[datetime] = None
-    updated_at: Optional[datetime] = None
-
-    model_config = {"from_attributes": True}
-
-
-class NodeConfigurationListItem(BaseModel):
+    identifier: str
+    enable: int
+    debug: int
+    need_account: int
+    need_proxy: int
+    proxy_pool: List[Any]
+    proxy_cd: int
+    session_max_life: int
+    active_time_start: str
+    active_time_end: str
+    website: str
+    booker: Dict[str, Any]
+    plugin_config: Dict[str, Any]
+    appointment_types: List[Any]
+    free_config: Dict[str, Any]
+    version: int
+    updated_by: Optional[str] = "system"
+    created_at: datetime
+    updated_at: datetime
+
+
+class SentinelEntryCreate(BaseModel):
+    node_id: Optional[str] = "default"
+    identifier: str
+    enable: Optional[int] = 0
+    debug: Optional[int] = 0
+    need_account: Optional[int] = 1
+    need_proxy: Optional[int] = 1
+    proxy_pool: Optional[List[str]] = Field(default_factory=list)
+    proxy_cd: Optional[int] = 300
+    session_max_life: Optional[int] = 1800
+    active_time_start: Optional[str] = "00:00"
+    active_time_end: Optional[str] = "23:59"
+    website: Optional[str] = ""
+    sentinel: Optional[Dict[str, Any]] = Field(default_factory=dict)
+    plugin_config: Optional[Dict[str, Any]] = Field(default_factory=dict)
+    appointment_types: Optional[List[Dict[str, Any]]] = Field(default_factory=list)
+    free_config: Optional[Dict[str, Any]] = Field(default_factory=dict)
+    updated_by: Optional[str] = "system"
+
+
+class SentinelEntryOut(BaseEntrySchema):
     id: int
-    role: str
     node_id: str
-    is_enabled: int
-    config_hash: str
-    description: Optional[str] = ""
-    created_by: Optional[str] = None
-    updated_by: Optional[str] = None
-    created_at: Optional[datetime] = None
-    updated_at: Optional[datetime] = None
-
-    model_config = {"from_attributes": True}
-
-
-class NodeConfigurationListResponse(BaseModel):
-    total: int
-    items: List[NodeConfigurationListItem]
-
-
-class NodeConfigAuditLogItem(BaseModel):
+    identifier: str
+    enable: int
+    debug: int
+    need_account: int
+    need_proxy: int
+    proxy_pool: List[Any]
+    proxy_cd: int
+    session_max_life: int
+    active_time_start: str
+    active_time_end: str
+    website: str
+    sentinel: Dict[str, Any]
+    plugin_config: Dict[str, Any]
+    appointment_types: List[Any]
+    free_config: Dict[str, Any]
+    version: int
+    updated_by: Optional[str] = "system"
+    created_at: datetime
+    updated_at: datetime
+
+
+class StandaloneEntryCreate(BaseModel):
+    node_id: Optional[str] = "default"
+    order_id: Optional[str] = None
+    identifier: str
+    enable: Optional[int] = 0
+    debug: Optional[int] = 0
+    plugin_config: Optional[Dict[str, Any]] = Field(default_factory=dict)
+    account: Optional[Dict[str, Any]] = Field(default_factory=dict)
+    proxy_pool: Optional[List[str]] = Field(default_factory=list)
+    query_wait: Optional[Dict[str, Any]] = Field(default_factory=dict)
+    login_interval: Optional[int] = 1800
+    session_max_life: Optional[int] = 1800
+    active_time_start: Optional[str] = "00:00"
+    active_time_end: Optional[str] = "23:59"
+    appointment_types: Optional[List[Dict[str, Any]]] = Field(default_factory=list)
+    user_preferences: Optional[Dict[str, Any]] = Field(default_factory=dict)
+    free_config: Optional[Dict[str, Any]] = Field(default_factory=dict)
+    updated_by: Optional[str] = "system"
+
+
+class StandaloneEntryOut(BaseEntrySchema):
     id: int
-    role: str
     node_id: str
+    order_id: Optional[str] = None
+    identifier: str
+    enable: int
+    debug: int
+    plugin_config: Dict[str, Any]
+    account: Dict[str, Any]
+    proxy_pool: List[Any]
+    query_wait: Dict[str, Any]
+    login_interval: int
+    session_max_life: int
+    active_time_start: str
+    active_time_end: str
+    appointment_types: List[Any]
+    user_preferences: Dict[str, Any]
+    free_config: Dict[str, Any]
+    version: int
+    updated_by: Optional[str] = "system"
+    created_at: datetime
+    updated_at: datetime
+
+
+class NodeConfigurationSparseUpdateRequest(BaseModel):
+    base_version: Optional[int] = None
+    set: Optional[Dict[str, Any]] = Field(default_factory=dict)
+    clear: Optional[List[str]] = Field(default_factory=list)
+
+
+class NodeConfigurationEnableRequest(BaseModel):
+    enable: bool
+    base_version: Optional[int] = None
+
+
+class NodeConfigurationRollbackRequest(BaseModel):
+    revision_id: int
+    base_version: Optional[int] = None
+
+
+class NodeConfigurationRevisionOut(BaseEntrySchema):
+    id: int
+    entry_type: str
+    entry_id: int
+    version: int
     action: str
-    before_hash: Optional[str] = None
-    after_hash: Optional[str] = None
-    operator: str
-    remark: Optional[str] = ""
-    created_at: Optional[datetime] = None
+    snapshot: Dict[str, Any]
+    updated_by: Optional[str] = "system"
+    created_at: datetime
 
-    model_config = {"from_attributes": True}
 
-
-
-class NodeConfigAuditLogListResponse(BaseModel):
+class NodeConfigurationListResponse(BaseModel):
     total: int
-    items: List[NodeConfigAuditLogItem]
+    page: int
+    page_size: int
+    items: List[Dict[str, Any]]

+ 107 - 0
app/schemas/provider.py

@@ -0,0 +1,107 @@
+from datetime import datetime
+from typing import Optional, Dict, Any, List
+from pydantic import BaseModel, Field, ConfigDict, field_validator
+
+ALLOWED_ROLES = {"sentinel", "booker", "standalone"}
+
+
+def check_no_mask(val: Any, path: str = "") -> None:
+    """Recursively checks that no '__MASKED__' string placeholders exist."""
+    if isinstance(val, str):
+        if "__MASKED__" in val:
+            raise ValueError(f"Masked placeholder rejected in field '{path}'")
+    elif isinstance(val, dict):
+        for k, v in val.items():
+            check_no_mask(v, f"{path}.{k}" if path else str(k))
+    elif isinstance(val, list):
+        for idx, item in enumerate(val):
+            check_no_mask(item, f"{path}[{idx}]")
+
+
+class BaseProviderSchema(BaseModel):
+    model_config = ConfigDict(from_attributes=True)
+
+
+class ProviderCreate(BaseModel):
+    name: str = Field(..., min_length=1, description="服务商唯一标识/名称")
+    enabled: bool = True
+    plugin_config: Dict[str, Any] = Field(default_factory=dict)
+    role_templates: Dict[str, Any] = Field(default_factory=dict)
+
+    @field_validator("name")
+    @classmethod
+    def validate_name(cls, v: str) -> str:
+        v = v.strip()
+        if not v:
+            raise ValueError("Provider name must not be empty")
+        return v
+
+    @field_validator("role_templates")
+    @classmethod
+    def validate_role_templates(cls, v: Dict[str, Any]) -> Dict[str, Any]:
+        invalid_keys = set(v.keys()) - ALLOWED_ROLES
+        if invalid_keys:
+            raise ValueError(
+                f"Invalid keys in role_templates: {invalid_keys}. Allowed keys are {ALLOWED_ROLES}"
+            )
+        check_no_mask(v, "role_templates")
+        return v
+
+    @field_validator("plugin_config")
+    @classmethod
+    def validate_plugin_config(cls, v: Dict[str, Any]) -> Dict[str, Any]:
+        check_no_mask(v, "plugin_config")
+        return v
+
+
+class ProviderUpdate(BaseModel):
+    enabled: Optional[bool] = None
+    plugin_config: Optional[Dict[str, Any]] = None
+    role_templates: Optional[Dict[str, Any]] = None
+
+    @field_validator("role_templates")
+    @classmethod
+    def validate_role_templates(
+        cls, v: Optional[Dict[str, Any]]
+    ) -> Optional[Dict[str, Any]]:
+        if v is not None:
+            invalid_keys = set(v.keys()) - ALLOWED_ROLES
+            if invalid_keys:
+                raise ValueError(
+                    f"Invalid keys in role_templates: {invalid_keys}. Allowed keys are {ALLOWED_ROLES}"
+                )
+            check_no_mask(v, "role_templates")
+        return v
+
+    @field_validator("plugin_config")
+    @classmethod
+    def validate_plugin_config(
+        cls, v: Optional[Dict[str, Any]]
+    ) -> Optional[Dict[str, Any]]:
+        if v is not None:
+            check_no_mask(v, "plugin_config")
+        return v
+
+
+class ProviderOut(BaseProviderSchema):
+    id: int
+    name: str
+    enabled: int
+    plugin_config: Dict[str, Any]
+    role_templates: Dict[str, Any]
+    version: int
+    updated_by: Optional[str] = "system"
+    created_at: datetime
+    updated_at: datetime
+
+
+class ProviderListItemOut(BaseProviderSchema):
+    id: int
+    name: str
+    enabled: int
+    plugin_config: Dict[str, Any]
+    role_templates: Dict[str, Any]
+    version: int
+    updated_by: Optional[str] = "system"
+    created_at: datetime
+    updated_at: datetime

+ 341 - 231
app/services/node_configuration_service.py

@@ -1,286 +1,396 @@
-import json
-import hashlib
-from typing import Optional, List, Tuple, Any
-from sqlalchemy import select, func, desc, delete
+import copy
+from typing import Dict, Any, List, Optional, Tuple, Type
 from sqlalchemy.ext.asyncio import AsyncSession
-
-from app.core.biz_exception import NotFoundError, BizLogicError
-from app.core.logger import logger
-from app.models.node_configuration import NodeConfiguration, NodeConfigAuditLog
-from app.schemas.node_configuration import (
-    NodeConfigurationSaveRequest,
-    NodeConfigurationToggleRequest,
-    NodeConfigurationCloneRequest,
-    NodeConfigurationDeleteRequest,
+from sqlalchemy import select, func, desc
+from sqlalchemy.orm.attributes import flag_modified
+
+from app.core.biz_exception import BizException
+from app.models.node_configuration import (
+    BookerEntry,
+    SentinelEntry,
+    StandaloneEntry,
+    NodeConfigurationRevision,
 )
 
 
-def calculate_config_hash(content: Any) -> str:
-    """
-    使用 Canonical JSON (键排序、紧凑分隔符) 统一计算 MD5 哈希
-    保证与 Python Coordinate 节点客户端计算完全一致
-    """
-    if isinstance(content, str):
-        try:
-            content = json.loads(content)
-        except Exception:
-            pass
-    canonical_json_str = json.dumps(content, sort_keys=True, separators=(',', ':'), ensure_ascii=False)
-    return hashlib.md5(canonical_json_str.encode('utf-8')).hexdigest()
-
-
 class NodeConfigurationService:
+    ENTRY_MODEL_MAP: Dict[str, Type[Any]] = {
+        "booker": BookerEntry,
+        "sentinel": SentinelEntry,
+        "standalone": StandaloneEntry,
+    }
+
+    @classmethod
+    def get_model(cls, entry_type: str) -> Type[Any]:
+        model = cls.ENTRY_MODEL_MAP.get(entry_type.lower())
+        if not model:
+            raise BizException(
+                code=40000,
+                message=f"Invalid entry_type: '{entry_type}'. Must be one of {list(cls.ENTRY_MODEL_MAP.keys())}",
+                http_status=400,
+            )
+        return model
 
-    @staticmethod
-    def compute_hash(content: Any) -> str:
-        return calculate_config_hash(content)
+    @classmethod
+    def _to_snapshot(cls, obj: Any) -> Dict[str, Any]:
+        """Serialize SQLAlchemy model columns to dict snapshot"""
+        snapshot = {}
+        for column in obj.__table__.columns:
+            val = getattr(obj, column.name)
+            if hasattr(val, "isoformat"):
+                val = val.isoformat()
+            snapshot[column.name] = copy.deepcopy(val)
+        return snapshot
 
     @classmethod
-    async def get_detail(
+    async def _record_revision(
         cls,
         db: AsyncSession,
-        role: str,
-        node_id: str,
-    ) -> NodeConfiguration:
-        """
-        获取指定角色与节点的配置详情(供 Worker 轮询与详情展示)
-        """
-        stmt = select(NodeConfiguration).where(
-            NodeConfiguration.role == role,
-            NodeConfiguration.node_id == node_id,
+        entry_type: str,
+        entry_id: int,
+        version: int,
+        action: str,
+        snapshot: Dict[str, Any],
+        updated_by: str,
+    ) -> NodeConfigurationRevision:
+        rev = NodeConfigurationRevision(
+            entry_type=entry_type,
+            entry_id=entry_id,
+            version=version,
+            action=action,
+            snapshot=snapshot,
+            updated_by=updated_by or "system",
         )
-        res = (await db.execute(stmt)).scalar_one_or_none()
-        if not res:
-            raise NotFoundError(f"Node configuration for role='{role}' and node_id='{node_id}' not found")
-        return res
+        db.add(rev)
+        await db.flush()
+        return rev
 
     @classmethod
-    async def list_configs(
+    async def list_entries(
         cls,
         db: AsyncSession,
-        role: Optional[str] = None,
-        node_id: Optional[str] = None,
-        is_enabled: Optional[int] = None,
+        entry_type: str,
         page: int = 1,
         page_size: int = 20,
-    ) -> Tuple[int, List[NodeConfiguration]]:
-        """
-        分页查询配置列表
-        """
-        stmt = select(NodeConfiguration)
-        count_stmt = select(func.count(NodeConfiguration.id))
-
-        if role:
-            stmt = stmt.where(NodeConfiguration.role == role)
-            count_stmt = count_stmt.where(NodeConfiguration.role == role)
+        identifier: Optional[str] = None,
+        node_id: Optional[str] = None,
+        order_id: Optional[str] = None,
+    ) -> Tuple[int, List[Any]]:
+        model = cls.get_model(entry_type)
+        stmt = select(model)
+        count_stmt = select(func.count(model.id))
+
+        if identifier:
+            stmt = stmt.where(model.identifier.like(f"%{identifier}%"))
+            count_stmt = count_stmt.where(model.identifier.like(f"%{identifier}%"))
         if node_id:
-            stmt = stmt.where(NodeConfiguration.node_id.like(f"%{node_id}%"))
-            count_stmt = count_stmt.where(NodeConfiguration.node_id.like(f"%{node_id}%"))
-        if is_enabled is not None:
-            stmt = stmt.where(NodeConfiguration.is_enabled == is_enabled)
-            count_stmt = count_stmt.where(NodeConfiguration.is_enabled == is_enabled)
+            stmt = stmt.where(model.node_id == node_id)
+            count_stmt = count_stmt.where(model.node_id == node_id)
+        if order_id and hasattr(model, "order_id"):
+            stmt = stmt.where(model.order_id == order_id)
+            count_stmt = count_stmt.where(model.order_id == order_id)
+
+        total = await db.scalar(count_stmt) or 0
+        offset = (page - 1) * page_size
+        stmt = stmt.order_by(desc(model.updated_at), desc(model.id)).offset(offset).limit(page_size)
+        result = await db.execute(stmt)
+        items = list(result.scalars().all())
+        return total, items
 
-        total = (await db.execute(count_stmt)).scalar() or 0
-
-        offset = max(0, (page - 1) * page_size)
-        stmt = stmt.order_by(desc(NodeConfiguration.updated_at), desc(NodeConfiguration.id)).offset(offset).limit(page_size)
-        result = (await db.execute(stmt)).scalars().all()
-
-        return total, list(result)
+    @classmethod
+    async def get_entry(
+        cls, db: AsyncSession, entry_type: str, entry_id: int
+    ) -> Any:
+        model = cls.get_model(entry_type)
+        stmt = select(model).where(model.id == entry_id)
+        entry = (await db.execute(stmt)).scalar_one_or_none()
+        if not entry:
+            raise BizException(
+                code=40400,
+                message=f"Configuration entry ({entry_type} ID: {entry_id}) not found",
+                http_status=404,
+            )
+        return entry
 
     @classmethod
-    async def save_config(
+    async def create_entry(
         cls,
         db: AsyncSession,
-        req: NodeConfigurationSaveRequest,
-        operator: Optional[str] = None,
-    ) -> NodeConfiguration:
-        """
-        新增或更新节点配置,并自动写入审计日志
-        """
-        op_user = operator or req.operator or "system"
-        calculated_hash = calculate_config_hash(req.config_content)
-
-        stmt = select(NodeConfiguration).where(
-            NodeConfiguration.role == req.role,
-            NodeConfiguration.node_id == req.node_id,
-        )
-        existing = (await db.execute(stmt)).scalar_one_or_none()
+        entry_type: str,
+        data: Dict[str, Any],
+        operator: str = "system",
+    ) -> Any:
+        model = cls.get_model(entry_type)
+        node_id = data.get("node_id") or "default"
+        identifier = data.get("identifier")
+        if not identifier:
+            raise BizException(
+                code=40000,
+                message="Field 'identifier' is required",
+                http_status=400,
+            )
 
+        # Check duplicate (node_id, identifier)
+        check_stmt = select(model).where(
+            model.node_id == node_id, model.identifier == identifier
+        )
+        existing = (await db.execute(check_stmt)).scalar_one_or_none()
         if existing:
-            action = "UPDATE"
-            before_hash = existing.config_hash
-            after_hash = calculated_hash
-
-            existing.config_content = req.config_content
-            existing.config_hash = calculated_hash
-            if req.is_enabled is not None:
-                existing.is_enabled = req.is_enabled
-            if req.description is not None:
-                existing.description = req.description
-            existing.updated_by = op_user
-
-            target_obj = existing
-        else:
-            action = "CREATE"
-            before_hash = None
-            after_hash = calculated_hash
-
-            target_obj = NodeConfiguration(
-                role=req.role,
-                node_id=req.node_id,
-                config_content=req.config_content,
-                config_hash=calculated_hash,
-                is_enabled=req.is_enabled if req.is_enabled is not None else 1,
-                description=req.description or "",
-                created_by=op_user,
-                updated_by=op_user,
+            raise BizException(
+                code=40902,
+                message=f"Identifier '{identifier}' on node '{node_id}' already exists",
+                http_status=409,
             )
-            db.add(target_obj)
 
-        audit_log = NodeConfigAuditLog(
-            role=req.role,
-            node_id=req.node_id,
-            action=action,
-            before_hash=before_hash,
-            after_hash=after_hash,
-            operator=op_user,
-            remark=req.remark or f"{action} configuration for {req.role}:{req.node_id}",
+        # Prepare model payload
+        entry_data = data.copy()
+        entry_data["node_id"] = node_id
+        entry_data["enable"] = 0  # Force disabled upon creation
+        entry_data["updated_by"] = operator
+        entry_data["version"] = 1
+
+        # Instantiate
+        valid_cols = {c.name for c in model.__table__.columns}
+        filtered_data = {k: v for k, v in entry_data.items() if k in valid_cols}
+        entry = model(**filtered_data)
+        db.add(entry)
+        await db.flush()
+
+        # Record revision
+        snapshot = cls._to_snapshot(entry)
+        await cls._record_revision(
+            db=db,
+            entry_type=entry_type,
+            entry_id=entry.id,
+            version=entry.version,
+            action="create",
+            snapshot=snapshot,
+            updated_by=operator,
         )
-        db.add(audit_log)
-
         await db.commit()
-        await db.refresh(target_obj)
-        logger.info(f"✅ Node configuration saved: role={req.role}, node_id={req.node_id}, hash={calculated_hash}, action={action}")
-        return target_obj
+        await db.refresh(entry)
+        return entry
 
     @classmethod
-    async def toggle_config(
+    async def sparse_update_entry(
         cls,
         db: AsyncSession,
-        req: NodeConfigurationToggleRequest,
-        operator: Optional[str] = None,
-    ) -> NodeConfiguration:
-        """
-        切换启用/禁用状态
-        """
-        op_user = operator or req.operator or "system"
-        stmt = select(NodeConfiguration).where(
-            NodeConfiguration.role == req.role,
-            NodeConfiguration.node_id == req.node_id,
-        )
-        existing = (await db.execute(stmt)).scalar_one_or_none()
-        if not existing:
-            raise NotFoundError(f"Node configuration for role='{req.role}' and node_id='{req.node_id}' not found")
-
-        old_status = existing.is_enabled
-        existing.is_enabled = 1 if req.is_enabled else 0
-        existing.updated_by = op_user
-
-        audit_log = NodeConfigAuditLog(
-            role=req.role,
-            node_id=req.node_id,
-            action="TOGGLE",
-            before_hash=existing.config_hash,
-            after_hash=existing.config_hash,
-            operator=op_user,
-            remark=req.remark or f"Toggle is_enabled from {old_status} to {existing.is_enabled}",
+        entry_type: str,
+        entry_id: int,
+        set_data: Optional[Dict[str, Any]] = None,
+        clear_fields: Optional[List[str]] = None,
+        base_version: Optional[int] = None,
+        operator: str = "system",
+    ) -> Any:
+        entry = await cls.get_entry(db, entry_type, entry_id)
+
+        set_data = set_data or {}
+        clear_fields = clear_fields or []
+
+        # 1. Apply set_data with dot-path support
+        for path_key, val in set_data.items():
+            # Strip leading 'payload.' if present
+            clean_key = path_key[8:] if path_key.startswith("payload.") else path_key
+
+            if "." in clean_key:
+                root_field, *nested_keys = clean_key.split(".")
+                if hasattr(entry, root_field):
+                    root_val = getattr(entry, root_field)
+                    if not isinstance(root_val, dict):
+                        root_val = {}
+                    else:
+                        root_val = copy.deepcopy(root_val)
+
+                    curr = root_val
+                    for nk in nested_keys[:-1]:
+                        if nk not in curr or not isinstance(curr[nk], dict):
+                            curr[nk] = {}
+                        curr = curr[nk]
+                    curr[nested_keys[-1]] = val
+
+                    setattr(entry, root_field, root_val)
+                    flag_modified(entry, root_field)
+            else:
+                if hasattr(entry, clean_key) and clean_key not in ("id", "created_at"):
+                    if isinstance(val, (dict, list)):
+                        val = copy.deepcopy(val)
+                        setattr(entry, clean_key, val)
+                        flag_modified(entry, clean_key)
+                    else:
+                        setattr(entry, clean_key, val)
+
+        # 2. Apply clear_fields
+        default_empty_map = {
+            "proxy_pool": [],
+            "appointment_types": [],
+            "booker": {},
+            "sentinel": {},
+            "account": {},
+            "query_wait": {},
+            "user_preferences": {},
+            "plugin_config": {},
+            "free_config": {},
+            "website": "",
+            "order_id": None,
+        }
+        for field in clear_fields:
+            clean_field = field[8:] if field.startswith("payload.") else field
+            if hasattr(entry, clean_field) and clean_field not in ("id", "created_at", "version"):
+                default_val = default_empty_map.get(clean_field, None)
+                setattr(entry, clean_field, default_val)
+                if isinstance(default_val, (dict, list)):
+                    flag_modified(entry, clean_field)
+
+        # Increment version and update operator
+        entry.version = (entry.version or 0) + 1
+        entry.updated_by = operator
+        await db.flush()
+
+        # Record revision snapshot
+        snapshot = cls._to_snapshot(entry)
+        await cls._record_revision(
+            db=db,
+            entry_type=entry_type,
+            entry_id=entry.id,
+            version=entry.version,
+            action="update",
+            snapshot=snapshot,
+            updated_by=operator,
         )
-        db.add(audit_log)
 
         await db.commit()
-        await db.refresh(existing)
-        return existing
+        await db.refresh(entry)
+        return entry
 
     @classmethod
-    async def clone_config(
+    async def toggle_enable(
         cls,
         db: AsyncSession,
-        req: NodeConfigurationCloneRequest,
-        operator: Optional[str] = None,
-    ) -> NodeConfiguration:
-        """
-        从源节点复制配置到目标节点
-        """
-        op_user = operator or req.operator or "system"
-        stmt = select(NodeConfiguration).where(
-            NodeConfiguration.role == req.source_role,
-            NodeConfiguration.node_id == req.source_node_id,
+        entry_type: str,
+        entry_id: int,
+        enable: bool,
+        base_version: Optional[int] = None,
+        operator: str = "system",
+    ) -> Any:
+        entry = await cls.get_entry(db, entry_type, entry_id)
+        entry.enable = 1 if enable else 0
+        entry.version = (entry.version or 0) + 1
+        entry.updated_by = operator
+        await db.flush()
+
+        snapshot = cls._to_snapshot(entry)
+        await cls._record_revision(
+            db=db,
+            entry_type=entry_type,
+            entry_id=entry.id,
+            version=entry.version,
+            action="enable" if enable else "disable",
+            snapshot=snapshot,
+            updated_by=operator,
         )
-        source = (await db.execute(stmt)).scalar_one_or_none()
-        if not source:
-            raise NotFoundError(f"Source configuration for role='{req.source_role}' and node_id='{req.source_node_id}' not found")
-
-        save_req = NodeConfigurationSaveRequest(
-            role=req.target_role,
-            node_id=req.target_node_id,
-            config_content=source.config_content,
-            is_enabled=source.is_enabled,
-            description=f"Cloned from {req.source_role}:{req.source_node_id}. {source.description or ''}".strip(),
-            operator=op_user,
-            remark=req.remark or f"Cloned from {req.source_role}:{req.source_node_id}",
-        )
-        return await cls.save_config(db, save_req, operator=op_user)
+
+        await db.commit()
+        await db.refresh(entry)
+        return entry
 
     @classmethod
-    async def delete_config(
+    async def delete_entry(
         cls,
         db: AsyncSession,
-        req: NodeConfigurationDeleteRequest,
-        operator: Optional[str] = None,
+        entry_type: str,
+        entry_id: int,
+        confirm_purge: bool = False,
     ) -> bool:
-        """
-        删除节点配置,并记录审计日志
-        """
-        op_user = operator or req.operator or "system"
-        stmt = select(NodeConfiguration).where(
-            NodeConfiguration.role == req.role,
-            NodeConfiguration.node_id == req.node_id,
-        )
-        existing = (await db.execute(stmt)).scalar_one_or_none()
-        if not existing:
-            raise NotFoundError(f"Node configuration for role='{req.role}' and node_id='{req.node_id}' not found")
-
-        audit_log = NodeConfigAuditLog(
-            role=req.role,
-            node_id=req.node_id,
-            action="DELETE",
-            before_hash=existing.config_hash,
-            after_hash=None,
-            operator=op_user,
-            remark=req.remark or f"Deleted configuration for {req.role}:{req.node_id}",
-        )
-        db.add(audit_log)
-        await db.delete(existing)
+        model = cls.get_model(entry_type)
+        entry = await cls.get_entry(db, entry_type, entry_id)
+
+        # Deletion guard: count remaining entries for this entry_type
+        total_count = await db.scalar(select(func.count(model.id))) or 0
+        if total_count <= 1 and not confirm_purge:
+            raise BizException(
+                code=40000,
+                message="Deleting the last entry requires confirm_purge=true",
+                http_status=400,
+            )
+
+        await db.delete(entry)
         await db.commit()
         return True
 
     @classmethod
-    async def get_audit_logs(
+    async def get_revisions(
         cls,
         db: AsyncSession,
-        role: Optional[str] = None,
-        node_id: Optional[str] = None,
-        page: int = 1,
-        page_size: int = 20,
-    ) -> Tuple[int, List[NodeConfigAuditLog]]:
-        """
-        查询审计日志
-        """
-        stmt = select(NodeConfigAuditLog)
-        count_stmt = select(func.count(NodeConfigAuditLog.id))
-
-        if role:
-            stmt = stmt.where(NodeConfigAuditLog.role == role)
-            count_stmt = count_stmt.where(NodeConfigAuditLog.role == role)
-        if node_id:
-            stmt = stmt.where(NodeConfigAuditLog.node_id == node_id)
-            count_stmt = count_stmt.where(NodeConfigAuditLog.node_id == node_id)
+        entry_type: str,
+        entry_id: int,
+    ) -> List[NodeConfigurationRevision]:
+        # Validate existence
+        await cls.get_entry(db, entry_type, entry_id)
+
+        stmt = (
+            select(NodeConfigurationRevision)
+            .where(
+                NodeConfigurationRevision.entry_type == entry_type,
+                NodeConfigurationRevision.entry_id == entry_id,
+            )
+            .order_by(desc(NodeConfigurationRevision.id))
+        )
+        result = await db.execute(stmt)
+        return list(result.scalars().all())
 
-        total = (await db.execute(count_stmt)).scalar() or 0
+    @classmethod
+    async def rollback_revision(
+        cls,
+        db: AsyncSession,
+        entry_type: str,
+        entry_id: int,
+        revision_id: int,
+        base_version: Optional[int] = None,
+        operator: str = "system",
+    ) -> Any:
+        entry = await cls.get_entry(db, entry_type, entry_id)
+
+        rev_stmt = select(NodeConfigurationRevision).where(
+            NodeConfigurationRevision.id == revision_id,
+            NodeConfigurationRevision.entry_type == entry_type,
+            NodeConfigurationRevision.entry_id == entry_id,
+        )
+        rev = (await db.execute(rev_stmt)).scalar_one_or_none()
+        if not rev:
+            raise BizException(
+                code=40400,
+                message=f"Revision {revision_id} for {entry_type} entry {entry_id} not found",
+                http_status=404,
+            )
 
-        offset = max(0, (page - 1) * page_size)
-        stmt = stmt.order_by(desc(NodeConfigAuditLog.created_at), desc(NodeConfigAuditLog.id)).offset(offset).limit(page_size)
-        result = (await db.execute(stmt)).scalars().all()
+        snapshot = rev.snapshot or {}
+        model = cls.get_model(entry_type)
+        ignore_cols = {"id", "created_at", "updated_at", "version"}
+        for col in model.__table__.columns:
+            if col.name not in ignore_cols and col.name in snapshot:
+                val = snapshot[col.name]
+                if isinstance(val, (dict, list)):
+                    val = copy.deepcopy(val)
+                    setattr(entry, col.name, val)
+                    flag_modified(entry, col.name)
+                else:
+                    setattr(entry, col.name, val)
+
+        entry.version = (entry.version or 0) + 1
+        entry.updated_by = operator
+        await db.flush()
+
+        new_snapshot = cls._to_snapshot(entry)
+        await cls._record_revision(
+            db=db,
+            entry_type=entry_type,
+            entry_id=entry.id,
+            version=entry.version,
+            action="rollback",
+            snapshot=new_snapshot,
+            updated_by=operator,
+        )
 
-        return total, list(result)
+        await db.commit()
+        await db.refresh(entry)
+        return entry

+ 108 - 0
app/services/provider_service.py

@@ -0,0 +1,108 @@
+from typing import List, Optional
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select
+from sqlalchemy.orm.attributes import flag_modified
+
+from app.core.biz_exception import BizException
+from app.models.provider import Provider
+from app.schemas.provider import ProviderCreate, ProviderUpdate
+
+
+class ProviderService:
+    @classmethod
+    async def list_providers(
+        cls,
+        db: AsyncSession,
+        enabled_only: bool = False,
+    ) -> List[Provider]:
+        stmt = select(Provider)
+        if enabled_only:
+            stmt = stmt.where(Provider.enabled == 1)
+        stmt = stmt.order_by(Provider.name)
+        result = await db.execute(stmt)
+        return list(result.scalars().all())
+
+    @classmethod
+    async def get_provider_by_name(
+        cls,
+        db: AsyncSession,
+        name: str,
+    ) -> Provider:
+        name = name.strip()
+        stmt = select(Provider).where(Provider.name == name)
+        provider = (await db.execute(stmt)).scalar_one_or_none()
+        if not provider:
+            raise BizException(
+                code=40400,
+                message=f"Provider '{name}' not found",
+                http_status=404,
+            )
+        return provider
+
+    @classmethod
+    async def create_provider(
+        cls,
+        db: AsyncSession,
+        payload: ProviderCreate,
+        operator: str = "system",
+    ) -> Provider:
+        name = payload.name.strip()
+        # Check duplicate name
+        stmt = select(Provider).where(Provider.name == name)
+        existing = (await db.execute(stmt)).scalar_one_or_none()
+        if existing:
+            raise BizException(
+                code=40900,
+                message=f"Provider name '{name}' already exists",
+                http_status=409,
+            )
+
+        provider = Provider(
+            name=name,
+            enabled=1 if payload.enabled else 0,
+            plugin_config=payload.plugin_config or {},
+            role_templates=payload.role_templates or {},
+            version=1,
+            updated_by=operator,
+        )
+        db.add(provider)
+        await db.commit()
+        await db.refresh(provider)
+        return provider
+
+    @classmethod
+    async def update_provider(
+        cls,
+        db: AsyncSession,
+        name: str,
+        payload: ProviderUpdate,
+        operator: str = "system",
+    ) -> Provider:
+        provider = await cls.get_provider_by_name(db, name)
+
+        if payload.enabled is not None:
+            provider.enabled = 1 if payload.enabled else 0
+        if payload.plugin_config is not None:
+            provider.plugin_config = payload.plugin_config
+            flag_modified(provider, "plugin_config")
+        if payload.role_templates is not None:
+            provider.role_templates = payload.role_templates
+            flag_modified(provider, "role_templates")
+
+        provider.version = (provider.version or 0) + 1
+        provider.updated_by = operator
+
+        await db.commit()
+        await db.refresh(provider)
+        return provider
+
+    @classmethod
+    async def delete_provider(
+        cls,
+        db: AsyncSession,
+        name: str,
+    ) -> bool:
+        provider = await cls.get_provider_by_name(db, name)
+        await db.delete(provider)
+        await db.commit()
+        return True

+ 2 - 0
app/utils/response.py

@@ -12,6 +12,8 @@ def _to_serializable(data: Any):
             c.name: getattr(data, c.name)
             for c in data.__table__.columns
         }
+    if isinstance(data, dict):
+        return {k: _to_serializable(v) for k, v in data.items()}
     if isinstance(data, list):
         return [_to_serializable(i) for i in data]
     return data

+ 0 - 393
docs/node_configuration.md

@@ -1,393 +0,0 @@
-# 节点配置管理服务 (Node Configuration) HTTP API 接口文档
-
-本文档为 Coordinate 节点配置管理服务(`node_configurations`)的后端 HTTP RESTful API 接口规范。
-
----
-
-## 1. 接口通用规范
-
-- **协议规范**: `HTTP/1.1` 或 `HTTP/2`
-- **基础路径 (Base URL)**: `/api`
-- **数据交互格式**: `application/json`
-- **字符编码**: `UTF-8`
-- **认证方式**: Bearer Token 鉴权(管理员权限):
-  ```http
-  Authorization: Bearer <token>
-  ```
-
-### 统一响应结构
-
-所有接口均返回标准 JSON 结构:
-
-```json
-{
-  "code": 0,          // 0 为成功,非 0 为错误码
-  "message": "success",
-  "data": {}          // 响应数据对象
-}
-```
-
----
-
-## 2. API 接口列表
-
-| 方法 | 接口路径 | 说明 |
-| :--- | :--- | :--- |
-| `GET` | `/api/node_configurations/list` | 分页查询节点配置列表 |
-| `GET` | `/api/node_configurations/detail` | 获取指定节点配置详情 |
-| `POST` | `/api/node_configurations/save` | 新增或更新节点配置 (Save/Upsert) |
-| `POST` | `/api/node_configurations/toggle` | 快速启用 / 禁用节点配置 |
-| `POST` | `/api/node_configurations/clone` | 节点配置克隆复制 |
-| `DELETE` | `/api/node_configurations/delete` | 删除指定节点配置 |
-| `GET` | `/api/node_configurations/audit-logs` | 查询配置修改审计日志 |
-
----
-
-## 3. 接口详细说明
-
-### 3.1 查询节点配置列表
-
-- **接口地址**: `GET /api/node_configurations/list`
-- **Query 参数**:
-  | 参数名 | 类型 | 必填 | 默认值 | 说明 |
-  | :--- | :--- | :--- | :--- | :--- |
-  | `role` | string | 否 | `null` | 过滤角色: `sentinel` / `booker` / `standalone` |
-  | `node_id` | string | 否 | `null` | 过滤节点标识 (支持模糊搜索) |
-  | `is_enabled` | int | 否 | `null` | 过滤启用状态: `1` (启用), `0` (禁用) |
-  | `page` | int | 否 | `1` | 当前页码 (>= 1) |
-  | `page_size` | int | 否 | `20` | 每页数量 (1 ~ 100) |
-
-- **响应报文 (Response)**:
-  ```json
-  {
-    "code": 0,
-    "message": "success",
-    "data": {
-      "total": 2,
-      "items": [
-        {
-          "id": 1,
-          "role": "sentinel",
-          "node_id": "node01",
-          "is_enabled": 1,
-          "config_hash": "6cbc001d68b050867db78f262a884ca6",
-          "description": "节点01 哨兵监控配置",
-          "created_by": "admin",
-          "updated_by": "admin",
-          "created_at": "2026-08-23T00:30:00",
-          "updated_at": "2026-08-23T00:45:00"
-        }
-      ]
-    }
-  }
-  ```
-
----
-
-### 3.2 获取指定节点配置详情
-
-- **接口地址**: `GET /api/node_configurations/detail`
-- **Query 参数**:
-  | 参数名 | 类型 | 必填 | 说明 |
-  | :--- | :--- | :--- | :--- |
-  | `role` | string | 是 | 角色类型: `sentinel` / `booker` / `standalone` |
-  | `node_id` | string | 是 | 节点唯一标识,如 `node01` |
-
-- **响应报文 (Response)**:
-  ```json
-  {
-    "code": 0,
-    "message": "success",
-    "data": {
-      "id": 1,
-      "role": "sentinel",
-      "node_id": "node01",
-      "is_enabled": 1,
-      "config_hash": "6cbc001d68b050867db78f262a884ca6",
-      "config_content": [
-        {
-          "identifier": "vfs.ie.nl",
-          "debug": false,
-          "enable": true,
-          "need_account": true,
-          "need_proxy": true,
-          "proxy_pool": ["proxy-cheap"],
-          "proxy_cd": 300,
-          "session_max_life": 1800,
-          "active_time_start": "00:00",
-          "active_time_end": "23:59",
-          "sentinel": {
-            "account_source": "built-in",
-            "account_pool_id": "ie.nl.sentinel",
-            "target_instances": 1,
-            "account_cd": 10800,
-            "signal_ttl": 30,
-            "query_wait": {
-              "mode": "Random",
-              "fixed_wait": 10,
-              "random_min": 60,
-              "random_max": 300
-            }
-          },
-          "plugin_config": {
-            "lib_path": "plugins",
-            "plugin_name": "vfs_plugin",
-            "plugin_bin": "vfs_plugin.py",
-            "plugin_proto": "IVSPlg"
-          },
-          "appointment_types": [
-            {
-              "weight": 10,
-              "routing_key": "slot.dub.nl.tourist",
-              "city": "Dublin",
-              "visa_type": "Tourist",
-              "country": "Netherlands"
-            }
-          ],
-          "website": "https://visa.vfsglobal.com/irl/en/nld/login",
-          "free_config": {
-            "mission_code": "nld",
-            "mission_name": "Netherlands",
-            "country_code": "irl",
-            "country_name": "Ireland",
-            "culture_code": "en-US",
-            "language": "en"
-          }
-        }
-      ],
-      "description": "节点01 哨兵监控配置",
-      "created_by": "admin",
-      "updated_by": "admin",
-      "created_at": "2026-08-23T00:30:00",
-      "updated_at": "2026-08-23T00:45:00"
-    }
-  }
-  ```
-
----
-
-### 3.3 保存 / 更新节点配置 (Save / Upsert)
-
-- **接口地址**: `POST /api/node_configurations/save`
-- **请求头**: `Content-Type: application/json`
-- **请求体 (Body)**:
-  | 字段名 | 类型 | 必填 | 默认值 | 说明 |
-  | :--- | :--- | :--- | :--- | :--- |
-  | `role` | string | 是 | - | 角色类型: `sentinel` / `booker` / `standalone` |
-  | `node_id` | string | 是 | - | 节点标识,如 `node01` |
-  | `config_content` | array / object | 是 | - | 完整的配置 JSON 内容 |
-  | `is_enabled` | int | 否 | `1` | 启用状态: `1` (启用), `0` (禁用) |
-  | `description` | string | 否 | `""` | 配置描述/用途说明 |
-  | `remark` | string | 否 | `""` | 修改原因/变更备注(记录到审计日志) |
-
-- **请求示例**:
-  ```json
-  {
-    "role": "sentinel",
-    "node_id": "node01",
-    "config_content": [
-      {
-        "identifier": "vfs.ie.nl",
-        "debug": true,
-        "enable": true
-      }
-    ],
-    "is_enabled": 1,
-    "description": "更新为调试模式",
-    "remark": "排查爱尔兰荷兰节点抓取问题"
-  }
-  ```
-
-- **响应报文 (Response)**:
-  ```json
-  {
-    "code": 0,
-    "message": "Configuration saved successfully",
-    "data": {
-      "id": 1,
-      "role": "sentinel",
-      "node_id": "node01",
-      "is_enabled": 1,
-      "config_hash": "779854f7892e9bacc6e73f32e4fa830a",
-      "config_content": [ ... ],
-      "description": "更新为调试模式",
-      "created_by": "admin",
-      "updated_by": "admin",
-      "created_at": "2026-08-23T00:30:00",
-      "updated_at": "2026-08-23T01:00:00"
-    }
-  }
-  ```
-
----
-
-### 3.4 快速启用 / 禁用节点配置
-
-- **接口地址**: `POST /api/node_configurations/toggle`
-- **请求头**: `Content-Type: application/json`
-- **请求体 (Body)**:
-  | 字段名 | 类型 | 必填 | 说明 |
-  | :--- | :--- | :--- | :--- |
-  | `role` | string | 是 | 角色类型: `sentinel` / `booker` / `standalone` |
-  | `node_id` | string | 是 | 节点标识,如 `node01` |
-  | `is_enabled` | int | 是 | 状态: `1` (启用), `0` (禁用) |
-  | `remark` | string | 否 | 操作备注说明 |
-
-- **请求示例**:
-  ```json
-  {
-    "role": "sentinel",
-    "node_id": "node01",
-    "is_enabled": 0,
-    "remark": "临时下线维护"
-  }
-  ```
-
-- **响应报文 (Response)**:
-  ```json
-  {
-    "code": 0,
-    "message": "Configuration status updated successfully",
-    "data": {
-      "id": 1,
-      "role": "sentinel",
-      "node_id": "node01",
-      "is_enabled": 0,
-      "config_hash": "779854f7892e9bacc6e73f32e4fa830a",
-      "description": "节点01 哨兵监控配置",
-      "updated_by": "admin",
-      "updated_at": "2026-08-23T01:05:00"
-    }
-  }
-  ```
-
----
-
-### 3.5 跨节点克隆 / 复制配置
-
-- **接口地址**: `POST /api/node_configurations/clone`
-- **请求头**: `Content-Type: application/json`
-- **请求体 (Body)**:
-  | 字段名 | 类型 | 必填 | 说明 |
-  | :--- | :--- | :--- | :--- |
-  | `source_role` | string | 是 | 源角色类型 |
-  | `source_node_id` | string | 是 | 源节点标识 |
-  | `target_role` | string | 是 | 目标角色类型 |
-  | `target_node_id` | string | 是 | 目标节点标识 |
-  | `remark` | string | 否 | 克隆操作备注 |
-
-- **请求示例**:
-  ```json
-  {
-    "source_role": "sentinel",
-    "source_node_id": "node01",
-    "target_role": "sentinel",
-    "target_node_id": "node02",
-    "remark": "扩容新节点"
-  }
-  ```
-
-- **响应报文 (Response)**:
-  ```json
-  {
-    "code": 0,
-    "message": "Configuration cloned successfully",
-    "data": {
-      "id": 2,
-      "role": "sentinel",
-      "node_id": "node02",
-      "is_enabled": 1,
-      "config_hash": "779854f7892e9bacc6e73f32e4fa830a",
-      "config_content": [ ... ],
-      "description": "Cloned from sentinel:node01. 节点01 哨兵监控配置",
-      "created_by": "admin",
-      "updated_by": "admin",
-      "created_at": "2026-08-23T01:10:00",
-      "updated_at": "2026-08-23T01:10:00"
-    }
-  }
-  ```
-
----
-
-### 3.6 删除节点配置
-
-- **接口地址**: `DELETE /api/node_configurations/delete`
-- **Query 参数**:
-  | 参数名 | 类型 | 必填 | 说明 |
-  | :--- | :--- | :--- | :--- |
-  | `role` | string | 是 | 角色类型: `sentinel` / `booker` / `standalone` |
-  | `node_id` | string | 是 | 节点标识 |
-  | `remark` | string | 否 | 删除原因说明 |
-
-- **响应报文 (Response)**:
-  ```json
-  {
-    "code": 0,
-    "message": "Configuration deleted successfully",
-    "data": {
-      "role": "sentinel",
-      "node_id": "node02",
-      "deleted": true
-    }
-  }
-  ```
-
----
-
-### 3.7 查询配置修改审计日志
-
-- **接口地址**: `GET /api/node_configurations/audit-logs`
-- **Query 参数**:
-  | 参数名 | 类型 | 必填 | 默认值 | 说明 |
-  | :--- | :--- | :--- | :--- | :--- |
-  | `role` | string | 否 | `null` | 过滤角色类型 |
-  | `node_id` | string | 否 | `null` | 过滤节点标识 |
-  | `page` | int | 否 | `1` | 页码 (>= 1) |
-  | `page_size` | int | 否 | `20` | 每页数量 (1 ~ 100) |
-
-- **响应报文 (Response)**:
-  ```json
-  {
-    "code": 0,
-    "message": "success",
-    "data": {
-      "total": 3,
-      "items": [
-        {
-          "id": 3,
-          "role": "sentinel",
-          "node_id": "node01",
-          "action": "UPDATE",
-          "before_hash": "6cbc001d68b050867db78f262a884ca6",
-          "after_hash": "779854f7892e9bacc6e73f32e4fa830a",
-          "operator": "admin@example.com",
-          "remark": "排查爱尔兰荷兰节点抓取问题",
-          "created_at": "2026-08-23T01:00:00"
-        },
-        {
-          "id": 2,
-          "role": "sentinel",
-          "node_id": "node01",
-          "action": "TOGGLE",
-          "before_hash": "6cbc001d68b050867db78f262a884ca6",
-          "after_hash": "6cbc001d68b050867db78f262a884ca6",
-          "operator": "admin@example.com",
-          "remark": "临时下线维护",
-          "created_at": "2026-08-23T00:50:00"
-        },
-        {
-          "id": 1,
-          "role": "sentinel",
-          "node_id": "node01",
-          "action": "CREATE",
-          "before_hash": null,
-          "after_hash": "6cbc001d68b050867db78f262a884ca6",
-          "operator": "system",
-          "remark": "Initial import from config_sentinel.json",
-          "created_at": "2026-08-23T00:30:00"
-        }
-      ]
-    }
-  }
-  ```

+ 0 - 95
scripts/import_node_configurations.py

@@ -1,95 +0,0 @@
-"""
-将 Coordinate 项目的本地 JSON 配置文件 (config_sentinel.json, config_booker.json, config_standalone.json)
-批量或按节点导入到 webapp 的 node_configurations 表中。
-
-用法示例:
-  python3 scripts/import_node_configurations.py --node-id node01 \
-      --sentinel /path/to/config_sentinel.json \
-      --booker /path/to/config_booker.json \
-      --standalone /path/to/config_standalone.json
-"""
-
-import os
-import sys
-import json
-import asyncio
-import argparse
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
-
-from app.core.database import AsyncSessionLocal
-from app.services.node_configuration_service import NodeConfigurationService
-from app.schemas.node_configuration import NodeConfigurationSaveRequest
-
-
-async def import_configs(
-    node_id: str,
-    sentinel_file: str = None,
-    booker_file: str = None,
-    standalone_file: str = None,
-    description: str = None,
-    operator: str = "import_script",
-):
-    if not node_id:
-        print("❌ Error: --node-id is required")
-        return
-
-    items = [
-        ("sentinel", sentinel_file, "哨兵轮询配置"),
-        ("booker", booker_file, "预约抢单配置"),
-        ("standalone", standalone_file, "独立 Booker 配置"),
-    ]
-
-    async with AsyncSessionLocal() as db:
-        for role, file_path, default_desc in items:
-            if not file_path:
-                continue
-
-            if not os.path.exists(file_path):
-                print(f"⚠️ [SKIP] File not found: {file_path}")
-                continue
-
-            try:
-                with open(file_path, "r", encoding="utf-8") as f:
-                    content = json.load(f)
-            except Exception as e:
-                print(f"❌ [ERROR] Failed to parse JSON file '{file_path}': {e}")
-                continue
-
-            req = NodeConfigurationSaveRequest(
-                role=role,
-                node_id=node_id,
-                config_content=content,
-                is_enabled=1,
-                description=description or f"{node_id} {default_desc} (imported from {os.path.basename(file_path)})",
-                operator=operator,
-                remark=f"Initial import from {file_path}",
-            )
-
-            try:
-                saved = await NodeConfigurationService.save_config(db, req, operator=operator)
-                print(f"✅ [SUCCESS] Imported {role} for node '{node_id}' | hash={saved.config_hash} (id={saved.id})")
-            except Exception as e:
-                print(f"❌ [ERROR] Failed to save {role} config for node '{node_id}': {e}")
-
-
-if __name__ == "__main__":
-    parser = argparse.ArgumentParser(description="Import Coordinate JSON configs to node_configurations table")
-    parser.add_argument("--node-id", type=str, required=True, help="Target node ID, e.g. node01")
-    parser.add_argument("--sentinel", type=str, help="Path to config_sentinel.json")
-    parser.add_argument("--booker", type=str, help="Path to config_booker.json")
-    parser.add_argument("--standalone", type=str, help="Path to config_standalone.json")
-    parser.add_argument("--description", type=str, help="Custom description")
-    parser.add_argument("--operator", type=str, default="migration_script", help="Operator name for audit log")
-    args = parser.parse_args()
-
-    asyncio.run(
-        import_configs(
-            node_id=args.node_id,
-            sentinel_file=args.sentinel,
-            booker_file=args.booker,
-            standalone_file=args.standalone,
-            description=args.description,
-            operator=args.operator,
-        )
-    )

+ 265 - 239
tests/test_node_configuration.py

@@ -1,257 +1,283 @@
-from datetime import datetime
-import json
-import pytest
+# -*- coding: utf-8 -*-
+import asyncio
+import unittest
 from unittest.mock import AsyncMock, MagicMock, patch
 from fastapi.testclient import TestClient
 
-
-from app.core.auth import get_current_user, require_min_role, RoleLevel
-from app.core.database import get_db
-from app.models.user import VasUser
-from app.models.node_configuration import NodeConfiguration, NodeConfigAuditLog
-from app.services.node_configuration_service import (
-    NodeConfigurationService,
-    calculate_config_hash,
-)
-from app.schemas.node_configuration import (
-    NodeConfigurationSaveRequest,
-    NodeConfigurationToggleRequest,
-    NodeConfigurationCloneRequest,
-    NodeConfigurationDeleteRequest,
+from app.models.node_configuration import (
+    BookerEntry,
+    SentinelEntry,
+    StandaloneEntry,
+    NodeConfigurationRevision,
 )
-from app.core.biz_exception import NotFoundError
+from app.services.node_configuration_service import NodeConfigurationService
+from app.core.biz_exception import BizException
 from app.main import app
+from app.core.auth import get_current_user, require_min_role, RoleLevel
 
 
 class DummyAdminUser:
-    id = "admin_01"
+    id = "admin-user-id"
     role = "admin"
     email = "admin@example.com"
-    nickname = "SuperAdmin"
-
-
-def test_calculate_config_hash_idempotency():
-    """
-    测试不同键顺序与格式下,Canonical Hash 的幂等一致性
-    """
-    content_a = {
-        "identifier": "vfs.ie.nl",
-        "debug": False,
-        "sentinel": {"target_instances": 1, "account_pool_id": "ie.nl"},
-    }
-    content_b = {
-        "debug": False,
-        "sentinel": {"account_pool_id": "ie.nl", "target_instances": 1},
-        "identifier": "vfs.ie.nl",
-    }
-    hash_a = calculate_config_hash(content_a)
-    hash_b = calculate_config_hash(content_b)
-    assert hash_a == hash_b
-    assert len(hash_a) == 32
-
-
-@pytest.mark.anyio
-async def test_node_configuration_service_unit():
-    mock_db = AsyncMock()
-
-    # 1. Test save_config (Create)
-    mock_exec_res = MagicMock()
-    mock_exec_res.scalar_one_or_none.return_value = None
-    mock_db.execute.return_value = mock_exec_res
-
-    payload = NodeConfigurationSaveRequest(
-        role="sentinel",
-        node_id="node01",
-        config_content=[{"identifier": "vfs.ie.nl", "enable": True}],
-        is_enabled=1,
-        description="Sentinel test node",
-        operator="admin",
-        remark="Initial create",
-    )
-
-    created = await NodeConfigurationService.save_config(mock_db, payload, operator="admin")
-    assert created.role == "sentinel"
-    assert created.node_id == "node01"
-    assert len(created.config_hash) == 32
-    assert mock_db.add.call_count == 2  # config + audit_log
-    assert mock_db.commit.called
-
-    # 2. Test save_config (Update)
-    existing_obj = NodeConfiguration(
-        id=1,
-        role="sentinel",
-        node_id="node01",
-        config_content=[{"identifier": "vfs.ie.nl", "enable": True}],
-        config_hash="old_hash_1234567890123456789012",
-        is_enabled=1,
-        description="Old description",
-    )
-    mock_exec_res.scalar_one_or_none.return_value = existing_obj
-
-    update_payload = NodeConfigurationSaveRequest(
-        role="sentinel",
-        node_id="node01",
-        config_content=[{"identifier": "vfs.ie.nl", "enable": False}],
-        is_enabled=1,
-        description="Updated description",
-        operator="admin",
-        remark="Update config",
-    )
-
-    updated = await NodeConfigurationService.save_config(mock_db, update_payload, operator="admin")
-    assert updated.id == 1
-    assert updated.description == "Updated description"
-    assert updated.config_hash != "old_hash_1234567890123456789012"
-
-    # 3. Test toggle_config
-    toggled = await NodeConfigurationService.toggle_config(
-        mock_db,
-        NodeConfigurationToggleRequest(role="sentinel", node_id="node01", is_enabled=0, remark="disable"),
-        operator="admin",
-    )
-    assert toggled.is_enabled == 0
-
-    # 4. Test delete_config
-    deleted = await NodeConfigurationService.delete_config(
-        mock_db,
-        NodeConfigurationDeleteRequest(role="sentinel", node_id="node01", remark="delete"),
-        operator="admin",
-    )
-    assert deleted is True
-
-    # 5. Test get_detail not found
-    mock_exec_res.scalar_one_or_none.return_value = None
-    with pytest.raises(NotFoundError):
-        await NodeConfigurationService.get_detail(mock_db, role="sentinel", node_id="not_exist")
-
-
-def test_node_configuration_api_endpoints():
-    mock_db = AsyncMock()
-    mock_user = DummyAdminUser()
-
-    async def override_get_db():
-        yield mock_db
-
-    async def override_current_user():
-        return mock_user
-
-    app.dependency_overrides[get_db] = override_get_db
-    app.dependency_overrides[get_current_user] = override_current_user
-
-    # Mock service methods
-    sample_node = NodeConfiguration(
-        id=10,
-        role="booker",
-        node_id="worker01",
-        config_content=[{"identifier": "tls.uk.fr", "enable": True}],
-        config_hash="abc12345678901234567890123456789",
-        is_enabled=1,
-        description="Test node",
-        created_by="admin",
-        updated_by="admin",
-        created_at=datetime.utcnow(),
-        updated_at=datetime.utcnow(),
-    )
-
-    sample_log = NodeConfigAuditLog(
-        id=1,
-        role="booker",
-        node_id="worker01",
-        action="CREATE",
-        before_hash=None,
-        after_hash="abc12345678901234567890123456789",
-        operator="admin",
-        remark="Test creation",
-        created_at=datetime.utcnow(),
-    )
-
-
-    with patch.object(NodeConfigurationService, "save_config", return_value=sample_node), \
-         patch.object(NodeConfigurationService, "get_detail", return_value=sample_node), \
-         patch.object(NodeConfigurationService, "list_configs", return_value=(1, [sample_node])), \
-         patch.object(NodeConfigurationService, "toggle_config", return_value=sample_node), \
-         patch.object(NodeConfigurationService, "clone_config", return_value=sample_node), \
-         patch.object(NodeConfigurationService, "delete_config", return_value=True), \
-         patch.object(NodeConfigurationService, "get_audit_logs", return_value=(1, [sample_log])):
-
-        with TestClient(app) as client:
-            headers = {"Authorization": "Bearer test_token"}
-
-            # 1. Save
-            res_save = client.post(
-                "/api/node_configurations/save",
-                json={
-                    "role": "booker",
-                    "node_id": "worker01",
-                    "config_content": [{"identifier": "tls.uk.fr", "enable": True}],
-                    "is_enabled": 1,
-                    "description": "Test node",
-                },
-                headers=headers,
-            )
-            assert res_save.status_code == 200
-            assert res_save.json()["code"] == 0
-            assert res_save.json()["data"]["role"] == "booker"
-            assert res_save.json()["data"]["config_hash"] == "abc12345678901234567890123456789"
-
-            # 2. Detail
-            res_detail = client.get(
-                "/api/node_configurations/detail?role=booker&node_id=worker01",
-                headers=headers,
+    nickname = "Super Admin"
+
+
+class TestNodeConfigurationService(unittest.TestCase):
+    def test_get_model_mapping(self):
+        self.assertEqual(NodeConfigurationService.get_model("booker"), BookerEntry)
+        self.assertEqual(NodeConfigurationService.get_model("sentinel"), SentinelEntry)
+        self.assertEqual(NodeConfigurationService.get_model("standalone"), StandaloneEntry)
+        with self.assertRaises(BizException):
+            NodeConfigurationService.get_model("unknown")
+
+    def test_create_duplicate_identifier(self):
+        async def run_test():
+            mock_db = AsyncMock()
+            mock_existing = BookerEntry(id=1, node_id="node01", identifier="vfs.ie.nl")
+            mock_result = MagicMock()
+            mock_result.scalar_one_or_none.return_value = mock_existing
+            mock_db.execute.return_value = mock_result
+
+            with self.assertRaises(BizException) as cm:
+                await NodeConfigurationService.create_entry(
+                    mock_db,
+                    "booker",
+                    {"node_id": "node01", "identifier": "vfs.ie.nl"},
+                )
+            self.assertEqual(cm.exception.code, 40902)
+
+        asyncio.run(run_test())
+
+    def test_sparse_update_and_dot_path(self):
+        async def run_test():
+            mock_db = AsyncMock()
+            entry = BookerEntry(
+                id=1,
+                node_id="node01",
+                identifier="vfs.ie.nl",
+                enable=0,
+                version=1,
+                proxy_cd=300,
+                booker={"account_cd": 10800, "pool": "p1"},
+                plugin_config={"lib_path": "plugins"},
+                website="https://old.url",
             )
-            assert res_detail.status_code == 200
-            assert res_detail.json()["code"] == 0
-            assert res_detail.json()["data"]["node_id"] == "worker01"
-
-            # 3. List
-            res_list = client.get(
-                "/api/node_configurations/list?role=booker&page=1&page_size=10",
-                headers=headers,
+            with patch.object(NodeConfigurationService, "get_entry", return_value=entry):
+                updated = await NodeConfigurationService.sparse_update_entry(
+                    db=mock_db,
+                    entry_type="booker",
+                    entry_id=1,
+                    set_data={
+                        "booker.account_cd": 9000,
+                        "plugin_config.plugin_name": "vfs_plugin",
+                        "proxy_cd": 600,
+                    },
+                    clear_fields=["website"],
+                    operator="test-admin",
+                )
+                self.assertEqual(updated.booker["account_cd"], 9000)
+                self.assertEqual(updated.booker["pool"], "p1")
+                self.assertEqual(updated.plugin_config["plugin_name"], "vfs_plugin")
+                self.assertEqual(updated.proxy_cd, 600)
+                self.assertEqual(updated.website, "")
+                self.assertEqual(updated.version, 2)
+                self.assertEqual(updated.updated_by, "test-admin")
+                mock_db.commit.assert_awaited_once()
+
+        asyncio.run(run_test())
+
+    def test_toggle_enable(self):
+        async def run_test():
+            mock_db = AsyncMock()
+            entry = SentinelEntry(
+                id=1,
+                node_id="node01",
+                identifier="vfs.ie.nl",
+                enable=0,
+                version=1,
             )
-            assert res_list.status_code == 200
-            assert res_list.json()["code"] == 0
-            assert res_list.json()["data"]["total"] == 1
-            assert len(res_list.json()["data"]["items"]) == 1
-
-            # 4. Toggle
-            res_toggle = client.post(
-                "/api/node_configurations/toggle",
-                json={"role": "booker", "node_id": "worker01", "is_enabled": 0},
-                headers=headers,
+            with patch.object(NodeConfigurationService, "get_entry", return_value=entry):
+                toggled = await NodeConfigurationService.toggle_enable(
+                    mock_db, "sentinel", 1, enable=True, operator="test-admin"
+                )
+                self.assertEqual(toggled.enable, 1)
+                self.assertEqual(toggled.version, 2)
+                self.assertEqual(toggled.updated_by, "test-admin")
+                mock_db.commit.assert_awaited_once()
+
+        asyncio.run(run_test())
+
+    def test_delete_guard(self):
+        async def run_test():
+            mock_db = AsyncMock()
+            entry = StandaloneEntry(id=1, node_id="node01", identifier="tls")
+            with patch.object(NodeConfigurationService, "get_entry", return_value=entry):
+                # 1. Total count is 1 and confirm_purge=False -> should raise BizException(40000)
+                mock_db.scalar.return_value = 1
+                with self.assertRaises(BizException) as cm:
+                    await NodeConfigurationService.delete_entry(
+                        mock_db, "standalone", 1, confirm_purge=False
+                    )
+                self.assertEqual(cm.exception.code, 40000)
+
+                # 2. Total count is 1 and confirm_purge=True -> should succeed
+                res = await NodeConfigurationService.delete_entry(
+                    mock_db, "standalone", 1, confirm_purge=True
+                )
+                self.assertTrue(res)
+                mock_db.delete.assert_awaited_once_with(entry)
+
+        asyncio.run(run_test())
+
+    def test_rollback_revision(self):
+        async def run_test():
+            mock_db = AsyncMock()
+            entry = BookerEntry(
+                id=1,
+                node_id="node01",
+                identifier="vfs.ie.nl",
+                enable=1,
+                version=3,
+                booker={"account_cd": 9000},
             )
-            assert res_toggle.status_code == 200
-            assert res_toggle.json()["code"] == 0
-
-            # 5. Clone
-            res_clone = client.post(
-                "/api/node_configurations/clone",
-                json={
-                    "source_role": "booker",
-                    "source_node_id": "worker01",
-                    "target_role": "booker",
-                    "target_node_id": "worker02",
+            mock_rev = NodeConfigurationRevision(
+                id=10,
+                entry_type="booker",
+                entry_id=1,
+                version=1,
+                action="create",
+                snapshot={
+                    "node_id": "node01",
+                    "identifier": "vfs.ie.nl",
+                    "enable": 0,
+                    "booker": {"account_cd": 10800},
                 },
-                headers=headers,
             )
-            assert res_clone.status_code == 200
-            assert res_clone.json()["code"] == 0
-
-            # 6. Audit Logs
-            res_logs = client.get(
-                "/api/node_configurations/audit-logs?role=booker&node_id=worker01",
-                headers=headers,
+            rev_result = MagicMock()
+            rev_result.scalar_one_or_none.return_value = mock_rev
+            mock_db.execute.return_value = rev_result
+
+            with patch.object(NodeConfigurationService, "get_entry", return_value=entry):
+                rolled = await NodeConfigurationService.rollback_revision(
+                    db=mock_db,
+                    entry_type="booker",
+                    entry_id=1,
+                    revision_id=10,
+                    operator="admin",
+                )
+                self.assertEqual(rolled.enable, 0)
+                self.assertEqual(rolled.booker["account_cd"], 10800)
+                self.assertEqual(rolled.version, 4)
+                mock_db.commit.assert_awaited_once()
+
+        asyncio.run(run_test())
+
+
+class TestNodeConfigurationHttpEndpoints(unittest.TestCase):
+    def setUp(self):
+        self.dummy_user = DummyAdminUser()
+        app.dependency_overrides[get_current_user] = lambda: self.dummy_user
+        app.dependency_overrides[require_min_role(RoleLevel.admin)] = lambda: self.dummy_user
+        self.client = TestClient(app)
+
+    def tearDown(self):
+        app.dependency_overrides.clear()
+
+    def test_crud_endpoints(self):
+        sample_booker = BookerEntry(
+            id=101,
+            node_id="node01",
+            identifier="vfs.ie.nl",
+            enable=0,
+            debug=0,
+            need_account=1,
+            need_proxy=1,
+            proxy_pool=["proxy-cheap"],
+            proxy_cd=300,
+            session_max_life=1800,
+            active_time_start="00:00",
+            active_time_end="23:59",
+            website="https://visa.vfsglobal.com",
+            booker={"account_source": "built-in"},
+            plugin_config={"lib_path": "plugins"},
+            appointment_types=[],
+            free_config={},
+            version=1,
+            updated_by="admin",
+        )
+
+        sample_rev = NodeConfigurationRevision(
+            id=1,
+            entry_type="booker",
+            entry_id=101,
+            version=1,
+            action="create",
+            snapshot={},
+            updated_by="admin",
+        )
+
+        # 1. POST /api/node-configurations/booker
+        with patch.object(NodeConfigurationService, "create_entry", return_value=sample_booker):
+            resp = self.client.post(
+                "/api/node-configurations/booker",
+                json={"node_id": "node01", "identifier": "vfs.ie.nl"},
+            )
+            self.assertEqual(resp.status_code, 200)
+            self.assertEqual(resp.json()["code"], 0)
+            self.assertEqual(resp.json()["data"]["id"], 101)
+
+        # 2. GET /api/node-configurations/booker/101
+        with patch.object(NodeConfigurationService, "get_entry", return_value=sample_booker):
+            resp = self.client.get("/api/node-configurations/booker/101")
+            self.assertEqual(resp.status_code, 200)
+            self.assertEqual(resp.json()["data"]["identifier"], "vfs.ie.nl")
+
+        # 3. GET /api/node-configurations/booker (list)
+        with patch.object(NodeConfigurationService, "list_entries", return_value=(1, [sample_booker])):
+            resp = self.client.get("/api/node-configurations/booker?page=1&pageSize=10")
+            self.assertEqual(resp.status_code, 200)
+            self.assertEqual(resp.json()["data"]["total"], 1)
+
+        # 4. PUT /api/node-configurations/booker/101 (sparse update)
+        with patch.object(NodeConfigurationService, "sparse_update_entry", return_value=sample_booker):
+            resp = self.client.put(
+                "/api/node-configurations/booker/101",
+                json={"set": {"proxy_cd": 400}, "clear": ["website"]},
+            )
+            self.assertEqual(resp.status_code, 200)
+            self.assertEqual(resp.json()["code"], 0)
+
+        # 5. PUT /api/node-configurations/booker/101/enable
+        with patch.object(NodeConfigurationService, "toggle_enable", return_value=sample_booker):
+            resp = self.client.put(
+                "/api/node-configurations/booker/101/enable",
+                json={"enable": True},
             )
-            assert res_logs.status_code == 200
-            assert res_logs.json()["code"] == 0
-            assert res_logs.json()["data"]["total"] == 1
-
-            # 7. Delete
-            res_del = client.delete(
-                "/api/node_configurations/delete?role=booker&node_id=worker01",
-                headers=headers,
+            self.assertEqual(resp.status_code, 200)
+            self.assertEqual(resp.json()["code"], 0)
+
+        # 6. GET /api/node-configurations/booker/101/revisions
+        with patch.object(NodeConfigurationService, "get_revisions", return_value=[sample_rev]):
+            resp = self.client.get("/api/node-configurations/booker/101/revisions")
+            self.assertEqual(resp.status_code, 200)
+            self.assertEqual(len(resp.json()["data"]), 1)
+
+        # 7. POST /api/node-configurations/booker/101/rollback
+        with patch.object(NodeConfigurationService, "rollback_revision", return_value=sample_booker):
+            resp = self.client.post(
+                "/api/node-configurations/booker/101/rollback",
+                json={"revision_id": 1},
             )
-            assert res_del.status_code == 200
-            assert res_del.json()["code"] == 0
-            assert res_del.json()["data"]["deleted"] is True
+            self.assertEqual(resp.status_code, 200)
+            self.assertEqual(resp.json()["code"], 0)
+
+        # 8. DELETE /api/node-configurations/booker/101
+        with patch.object(NodeConfigurationService, "delete_entry", return_value=True):
+            resp = self.client.delete("/api/node-configurations/booker/101?confirm_purge=true")
+            self.assertEqual(resp.status_code, 200)
+            self.assertEqual(resp.json()["data"], True)
+
 
-    app.dependency_overrides.clear()
+if __name__ == "__main__":
+    unittest.main()

+ 178 - 0
tests/test_provider.py

@@ -0,0 +1,178 @@
+# -*- coding: utf-8 -*-
+import asyncio
+import unittest
+from unittest.mock import AsyncMock, MagicMock, patch
+from pydantic import ValidationError
+from fastapi.testclient import TestClient
+
+from app.models.provider import Provider
+from app.schemas.provider import ProviderCreate, ProviderUpdate
+from app.services.provider_service import ProviderService
+from app.core.biz_exception import BizException
+from app.main import app
+from app.core.auth import get_current_user, require_min_role, RoleLevel
+
+
+class DummyAdminUser:
+    id = "admin-user-id"
+    role = "admin"
+    email = "admin@example.com"
+    nickname = "Super Admin"
+
+
+class TestProviderService(unittest.TestCase):
+    def test_schema_name_and_role_template_validation(self):
+        # 1. Valid name
+        p = ProviderCreate(
+            name="vfs",
+            role_templates={"booker": {"account_cd": 10800}},
+        )
+        self.assertEqual(p.name, "vfs")
+
+        # 2. Empty name not allowed
+        with self.assertRaises(ValidationError):
+            ProviderCreate(name="   ")
+
+        # 3. Invalid role_templates key
+        with self.assertRaises(ValidationError):
+            ProviderCreate(
+                name="vfs",
+                role_templates={"invalid_role": {}},
+            )
+
+        # 4. Masked placeholder rejection
+        with self.assertRaises(ValidationError):
+            ProviderCreate(
+                name="vfs",
+                role_templates={"booker": {"secret": "__MASKED__"}},
+            )
+
+    def test_create_duplicate_name(self):
+        async def run_test():
+            mock_db = AsyncMock()
+            mock_existing = Provider(id=1, name="vfs")
+            mock_result = MagicMock()
+            mock_result.scalar_one_or_none.return_value = mock_existing
+            mock_db.execute.return_value = mock_result
+
+            with self.assertRaises(BizException) as cm:
+                await ProviderService.create_provider(
+                    mock_db,
+                    ProviderCreate(name="vfs"),
+                )
+            self.assertEqual(cm.exception.code, 40900)
+
+        asyncio.run(run_test())
+
+    def test_update_provider(self):
+        async def run_test():
+            mock_db = AsyncMock()
+            provider = Provider(
+                id=1,
+                name="vfs",
+                enabled=1,
+                version=1,
+                plugin_config={"lib_path": "plugins"},
+                role_templates={"booker": {"cd": 300}},
+            )
+            with patch.object(ProviderService, "get_provider_by_name", return_value=provider):
+                updated = await ProviderService.update_provider(
+                    db=mock_db,
+                    name="vfs",
+                    payload=ProviderUpdate(
+                        enabled=False,
+                        role_templates={"sentinel": {"ttl": 30}},
+                    ),
+                    operator="admin",
+                )
+                self.assertEqual(updated.enabled, 0)
+                self.assertEqual(updated.role_templates, {"sentinel": {"ttl": 30}})
+                self.assertEqual(updated.version, 2)
+                self.assertEqual(updated.updated_by, "admin")
+                mock_db.commit.assert_awaited_once()
+
+        asyncio.run(run_test())
+
+    def test_delete_provider(self):
+        async def run_test():
+            mock_db = AsyncMock()
+            provider = Provider(id=1, name="vfs")
+            with patch.object(ProviderService, "get_provider_by_name", return_value=provider):
+                res = await ProviderService.delete_provider(mock_db, "vfs")
+                self.assertTrue(res)
+                mock_db.delete.assert_awaited_once_with(provider)
+                mock_db.commit.assert_awaited_once()
+
+        asyncio.run(run_test())
+
+
+class TestProviderHttpEndpoints(unittest.TestCase):
+    def setUp(self):
+        self.dummy_user = DummyAdminUser()
+        app.dependency_overrides[get_current_user] = lambda: self.dummy_user
+        app.dependency_overrides[require_min_role(RoleLevel.admin)] = lambda: self.dummy_user
+        self.client = TestClient(app)
+
+    def tearDown(self):
+        app.dependency_overrides.clear()
+
+    def test_provider_crud_endpoints(self):
+        from datetime import datetime
+        now = datetime.utcnow()
+        sample_provider = Provider(
+            id=1,
+            name="vfs",
+            enabled=1,
+            plugin_config={"lib_path": "plugins"},
+            role_templates={"booker": {}},
+            version=1,
+            updated_by="admin",
+            created_at=now,
+            updated_at=now,
+        )
+
+        # 1. POST /api/providers
+        with patch.object(ProviderService, "create_provider", return_value=sample_provider):
+            resp = self.client.post(
+                "/api/providers",
+                json={
+                    "name": "vfs",
+                    "enabled": True,
+                    "plugin_config": {"lib_path": "plugins"},
+                    "role_templates": {"booker": {}},
+                },
+            )
+            self.assertEqual(resp.status_code, 200)
+            self.assertEqual(resp.json()["code"], 0)
+            self.assertEqual(resp.json()["data"]["name"], "vfs")
+
+        # 2. GET /api/providers/{name}
+        with patch.object(ProviderService, "get_provider_by_name", return_value=sample_provider):
+            resp = self.client.get("/api/providers/vfs")
+            self.assertEqual(resp.status_code, 200)
+            self.assertEqual(resp.json()["data"]["name"], "vfs")
+
+        # 3. GET /api/providers
+        with patch.object(ProviderService, "list_providers", return_value=[sample_provider]):
+            resp = self.client.get("/api/providers?enabled_only=true")
+            self.assertEqual(resp.status_code, 200)
+            self.assertEqual(len(resp.json()["data"]), 1)
+
+        # 4. PUT /api/providers/{name}
+        with patch.object(ProviderService, "update_provider", return_value=sample_provider):
+            resp = self.client.put(
+                "/api/providers/vfs",
+                json={"enabled": False},
+            )
+            self.assertEqual(resp.status_code, 200)
+            self.assertEqual(resp.json()["code"], 0)
+
+        # 5. DELETE /api/providers/{name}
+        with patch.object(ProviderService, "delete_provider", return_value=True):
+            resp = self.client.delete("/api/providers/vfs")
+            self.assertEqual(resp.status_code, 200)
+            self.assertEqual(resp.json()["data"], True)
+
+
+if __name__ == "__main__":
+    unittest.main()