Commit d600c335 by imwangxiaozhou

refactor(backend): 统一API响应格式,新增企业微信同步模块

- 标准化所有后端JSON接口的响应格式,统一使用`{code, message, data}`结构
- 统一错误响应格式,所有异常返回标准化错误结构
- 为列表接口补充page/page_size字段,规范分页响应格式
- 新增企业微信数据同步全模块,包含数据库模型、同步客户端、服务层与API端点
- 优化SQLite配置,启用WAL模式并增加连接超时设置
- 重构Agent相关Schema,简化响应模型结构
- 补充对应OpenSpec文档与测试用例
1 parent ce44519e
Showing 66 changed files with 4180 additions and 244 deletions
...@@ -2,6 +2,7 @@ from fastapi import APIRouter, Depends, HTTPException ...@@ -2,6 +2,7 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.infrastructure.database import get_db from app.infrastructure.database import get_db
from app.schema.common import ApiResponse
from app.schema.agent_group import EmployeeQrcodesResponse, PositionEmployeesResponse from app.schema.agent_group import EmployeeQrcodesResponse, PositionEmployeesResponse
from app.service.agent_group_helper_service import ( from app.service.agent_group_helper_service import (
AgentGroupHelperService, AgentGroupHelperService,
...@@ -19,7 +20,7 @@ def get_wecom_client(): ...@@ -19,7 +20,7 @@ def get_wecom_client():
@router.get( @router.get(
"/position/{position_code}/employees", "/position/{position_code}/employees",
response_model=PositionEmployeesResponse, response_model=ApiResponse[PositionEmployeesResponse],
) )
def get_position_employees( def get_position_employees(
position_code: str, position_code: str,
...@@ -37,7 +38,7 @@ def get_position_employees( ...@@ -37,7 +38,7 @@ def get_position_employees(
@router.get( @router.get(
"/employee/{employee_id}/qrcodes", "/employee/{employee_id}/qrcodes",
response_model=EmployeeQrcodesResponse, response_model=ApiResponse[EmployeeQrcodesResponse],
) )
def get_employee_qrcodes( def get_employee_qrcodes(
employee_id: str, employee_id: str,
......
...@@ -3,6 +3,7 @@ from pydantic import BaseModel, Field ...@@ -3,6 +3,7 @@ from pydantic import BaseModel, Field
from typing import Optional from typing import Optional
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.infrastructure.database import get_db from app.infrastructure.database import get_db
from app.schema.common import ApiResponse
from app.service.agent_hub import AgentHub, AgentHubError from app.service.agent_hub import AgentHub, AgentHubError
router = APIRouter() router = APIRouter()
...@@ -31,7 +32,7 @@ def get_agent_hub(db: Session = Depends(get_db)): ...@@ -31,7 +32,7 @@ def get_agent_hub(db: Session = Depends(get_db)):
return agent_hub_instance return agent_hub_instance
@router.post("/completions", response_model=ChatResponse) @router.post("/completions", response_model=ApiResponse[ChatResponse])
async def chat(request: ChatRequest, agent_hub: AgentHub = Depends(get_agent_hub)): async def chat(request: ChatRequest, agent_hub: AgentHub = Depends(get_agent_hub)):
try: try:
result = await agent_hub.process_message( result = await agent_hub.process_message(
......
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import Optional
from app.infrastructure.database import get_db
from app.schema.agent import ( from app.schema.agent import (
AgentCreate, AgentUpdate, AgentStatusUpdate, AgentCreate,
AgentDetailResponse, AgentSimpleResponse, AgentListResponse AgentDetailResponse,
AgentListResponse,
AgentResponse,
AgentStatusUpdate,
AgentUpdate,
)
from app.schema.common import (
ApiResponse,
DeleteSuccessData,
StatusSuccessData,
SuccessFlagData,
success_response_payload,
) )
from app.service.agent_service import AgentService from app.service.agent_service import AgentService
from app.infrastructure.database import get_db
router = APIRouter(prefix="/api/v1/agents") router = APIRouter(prefix="/api/v1/agents")
@router.post("", response_model=AgentSimpleResponse, status_code=201) def _to_response(agent) -> AgentResponse:
return AgentResponse(
agent_id=agent.id,
name=agent.name,
code=agent.code,
position_ids=sorted(ap.position_id for ap in agent.positions),
skill_codes=sorted(sk.skill_code for sk in agent.skills),
created_at=agent.created_at,
)
@router.post("", response_model=ApiResponse[AgentResponse], status_code=201)
def create_agent(req: AgentCreate, db: Session = Depends(get_db)): def create_agent(req: AgentCreate, db: Session = Depends(get_db)):
svc = AgentService(db) svc = AgentService(db)
try: try:
agent = svc.create(req) agent = svc.create(req)
return AgentSimpleResponse.model_validate(agent) return success_response_payload(201, _to_response(agent).model_dump(mode="json"))
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) raise HTTPException(status_code=400, detail=str(e))
@router.put("/{agent_id}", response_model=AgentSimpleResponse) @router.put("/{agent_id}", response_model=ApiResponse[AgentResponse])
def update_agent(agent_id: int, req: AgentUpdate, db: Session = Depends(get_db)): def update_agent(agent_id: int, req: AgentUpdate, db: Session = Depends(get_db)):
svc = AgentService(db) svc = AgentService(db)
try: try:
agent = svc.update(agent_id, req) agent = svc.update(agent_id, req)
return AgentSimpleResponse.model_validate(agent) return success_response_payload(200, _to_response(agent).model_dump(mode="json"))
except ValueError as e: except ValueError as e:
msg = str(e) msg = str(e)
if "不存在" in msg: if "不存在" in msg:
...@@ -34,45 +58,40 @@ def update_agent(agent_id: int, req: AgentUpdate, db: Session = Depends(get_db)) ...@@ -34,45 +58,40 @@ def update_agent(agent_id: int, req: AgentUpdate, db: Session = Depends(get_db))
raise HTTPException(status_code=409, detail=msg) raise HTTPException(status_code=409, detail=msg)
@router.delete("/{agent_id}") @router.delete("/{agent_id}", response_model=ApiResponse[DeleteSuccessData])
def delete_agent(agent_id: int, db: Session = Depends(get_db)): def delete_agent(agent_id: int, db: Session = Depends(get_db)):
svc = AgentService(db) svc = AgentService(db)
try: try:
svc.delete(agent_id) agent = svc.delete(agent_id)
return {"success": True} return success_response_payload(
200,
{
"success": True,
"deleted_at": agent.deleted_at.isoformat().replace("+00:00", "Z"),
},
)
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=404, detail=str(e)) raise HTTPException(status_code=404, detail=str(e))
@router.get("/{agent_id}", response_model=AgentDetailResponse) @router.get("/{agent_id}", response_model=ApiResponse[AgentDetailResponse])
def get_agent_detail(agent_id: int, db: Session = Depends(get_db)): def get_agent_detail(agent_id: int, db: Session = Depends(get_db)):
svc = AgentService(db) svc = AgentService(db)
try: try:
agent = svc.get_detail(agent_id) agent = svc.get_detail(agent_id)
return AgentDetailResponse( return success_response_payload(200, agent.model_dump(mode="json"))
id=agent.id,
code=agent.code,
name=agent.name,
description=agent.description,
status=agent.status,
position_ids=[ap.position_id for ap in agent.positions],
skill_codes=[sk.skill_code for sk in agent.skills],
version=agent.version,
created_at=agent.created_at,
updated_at=agent.updated_at
)
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=404, detail=str(e)) raise HTTPException(status_code=404, detail=str(e))
@router.get("", response_model=AgentListResponse) @router.get("", response_model=ApiResponse[AgentListResponse])
def list_agents( def list_agents(
page: int = Query(1, ge=1), page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100), page_size: int = Query(20, ge=1, le=100),
keyword: Optional[str] = Query(None), keyword: Optional[str] = Query(None),
position_id: Optional[int] = Query(None), position_id: Optional[int] = Query(None),
status: Optional[str] = Query(None), status: Optional[str] = Query(None),
db: Session = Depends(get_db) db: Session = Depends(get_db),
): ):
svc = AgentService(db) svc = AgentService(db)
total, items = svc.list_agents( total, items = svc.list_agents(
...@@ -80,19 +99,27 @@ def list_agents( ...@@ -80,19 +99,27 @@ def list_agents(
page_size=page_size, page_size=page_size,
keyword=keyword, keyword=keyword,
position_id=position_id, position_id=position_id,
status=status status=status,
) )
return AgentListResponse( return success_response_payload(
200,
AgentListResponse(
total=total, total=total,
list=[AgentSimpleResponse.model_validate(item) for item in items] page=page,
page_size=page_size,
list=[_to_response(item) for item in items],
).model_dump(mode="json"),
) )
@router.put("/{agent_id}/status") @router.put("/{agent_id}/status", response_model=ApiResponse[StatusSuccessData])
def update_agent_status(agent_id: int, req: AgentStatusUpdate, db: Session = Depends(get_db)): def update_agent_status(agent_id: int, req: AgentStatusUpdate, db: Session = Depends(get_db)):
svc = AgentService(db) svc = AgentService(db)
try: try:
svc.update_status(agent_id, req) svc.update_status(agent_id, req)
return {"success": True, "status": req.status.value} return success_response_payload(
200,
{"success": True, "status": req.status.value},
)
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=404, detail=str(e)) raise HTTPException(status_code=404, detail=str(e))
...@@ -3,13 +3,14 @@ from sqlalchemy.orm import Session ...@@ -3,13 +3,14 @@ from sqlalchemy.orm import Session
from app.infrastructure.database import get_db from app.infrastructure.database import get_db
from app.infrastructure.shared_cache import shared_h5_cache from app.infrastructure.shared_cache import shared_h5_cache
from app.schema.common import ApiResponse
from app.schema.official_site_home import H5HomeResponse from app.schema.official_site_home import H5HomeResponse
from app.service.official_site_home_service import H5HomeService from app.service.official_site_home_service import H5HomeService
router = APIRouter() router = APIRouter()
@router.get("/api/v1/official-site/home", response_model=H5HomeResponse) @router.get("/api/v1/official-site/home", response_model=ApiResponse[H5HomeResponse])
def get_home_data(db: Session = Depends(get_db)): def get_home_data(db: Session = Depends(get_db)):
svc = H5HomeService(db, shared_h5_cache) svc = H5HomeService(db, shared_h5_cache)
return svc.get_home_data() return svc.get_home_data()
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form
from app.infrastructure.file_parser import InMemoryOSSClient, OSSClient from app.infrastructure.file_parser import InMemoryOSSClient, OSSClient
from app.schema.common import ApiResponse
from app.schema.official_site_upload import UploadMediaResponse from app.schema.official_site_upload import UploadMediaResponse
from app.service.official_site_upload_service import OfficialSiteUploadService from app.service.official_site_upload_service import OfficialSiteUploadService
...@@ -13,7 +14,7 @@ def get_oss() -> OSSClient: ...@@ -13,7 +14,7 @@ def get_oss() -> OSSClient:
return _oss return _oss
@router.post("/api/v1/official-site/upload", response_model=UploadMediaResponse) @router.post("/api/v1/official-site/upload", response_model=ApiResponse[UploadMediaResponse])
async def upload_media( async def upload_media(
usage_type: str = Form(...), usage_type: str = Form(...),
file: UploadFile = File(...), file: UploadFile = File(...),
......
...@@ -9,18 +9,22 @@ from app.schema.position_tag import ( ...@@ -9,18 +9,22 @@ from app.schema.position_tag import (
ReferenceCheckResponse, ReferenceCheckResponse,
PositionTagAgentStatistics, PositionTagAgentStatistics,
) )
from app.schema.common import ApiResponse, SuccessFlagData, success_response_payload
from app.service.position_tag_service import PositionTagService from app.service.position_tag_service import PositionTagService
from app.infrastructure.database import get_db from app.infrastructure.database import get_db
router = APIRouter(prefix="/api/v1/position-tags") router = APIRouter(prefix="/api/v1/position-tags")
@router.post("", response_model=PositionTagResponse, status_code=201) @router.post("", response_model=ApiResponse[PositionTagResponse], status_code=201)
def create_position_tag(req: PositionTagCreate, db: Session = Depends(get_db)): def create_position_tag(req: PositionTagCreate, db: Session = Depends(get_db)):
svc = PositionTagService(db) svc = PositionTagService(db)
try: try:
tag = svc.create(req) tag = svc.create(req)
return PositionTagResponse.model_validate(tag) return success_response_payload(
201,
PositionTagResponse.model_validate(tag).model_dump(mode="json"),
)
except ValueError as e: except ValueError as e:
msg = str(e) msg = str(e)
if "编码已存在" in msg: if "编码已存在" in msg:
...@@ -28,26 +32,32 @@ def create_position_tag(req: PositionTagCreate, db: Session = Depends(get_db)): ...@@ -28,26 +32,32 @@ def create_position_tag(req: PositionTagCreate, db: Session = Depends(get_db)):
raise HTTPException(status_code=400, detail=msg) raise HTTPException(status_code=400, detail=msg)
@router.put("/{tag_id}", response_model=PositionTagResponse) @router.put("/{tag_id}", response_model=ApiResponse[PositionTagResponse])
def update_position_tag(tag_id: int, req: PositionTagUpdate, db: Session = Depends(get_db)): def update_position_tag(tag_id: int, req: PositionTagUpdate, db: Session = Depends(get_db)):
svc = PositionTagService(db) svc = PositionTagService(db)
try: try:
tag = svc.update(tag_id, req) tag = svc.update(tag_id, req)
return PositionTagResponse.model_validate(tag) return success_response_payload(
200,
PositionTagResponse.model_validate(tag).model_dump(mode="json"),
)
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=404, detail=str(e)) raise HTTPException(status_code=404, detail=str(e))
@router.get("/{tag_id}/references", response_model=ReferenceCheckResponse) @router.get("/{tag_id}/references", response_model=ApiResponse[ReferenceCheckResponse])
def check_references(tag_id: int, db: Session = Depends(get_db)): def check_references(tag_id: int, db: Session = Depends(get_db)):
svc = PositionTagService(db) svc = PositionTagService(db)
try: try:
return svc.check_references(tag_id) return success_response_payload(
200,
ReferenceCheckResponse.model_validate(svc.check_references(tag_id)).model_dump(mode="json"),
)
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=404, detail=str(e)) raise HTTPException(status_code=404, detail=str(e))
@router.delete("/{tag_id}") @router.delete("/{tag_id}", response_model=ApiResponse[SuccessFlagData])
def delete_position_tag( def delete_position_tag(
tag_id: int, tag_id: int,
confirm_detach_agents: bool = Query(False), confirm_detach_agents: bool = Query(False),
...@@ -56,7 +66,7 @@ def delete_position_tag( ...@@ -56,7 +66,7 @@ def delete_position_tag(
svc = PositionTagService(db) svc = PositionTagService(db)
try: try:
svc.delete(tag_id, confirm_detach_agents) svc.delete(tag_id, confirm_detach_agents)
return {"success": True} return success_response_payload(200, {"success": True})
except ValueError as e: except ValueError as e:
msg = str(e) msg = str(e)
if "阻塞性引用" in msg: if "阻塞性引用" in msg:
...@@ -66,7 +76,7 @@ def delete_position_tag( ...@@ -66,7 +76,7 @@ def delete_position_tag(
raise HTTPException(status_code=404, detail=msg) raise HTTPException(status_code=404, detail=msg)
@router.get("", response_model=PositionTagListResponse) @router.get("", response_model=ApiResponse[PositionTagListResponse])
def list_position_tags( def list_position_tags(
page: int = Query(1, ge=1), page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100), page_size: int = Query(20, ge=1, le=100),
...@@ -75,16 +85,24 @@ def list_position_tags( ...@@ -75,16 +85,24 @@ def list_position_tags(
): ):
svc = PositionTagService(db) svc = PositionTagService(db)
total, items = svc.list_tags(page=page, page_size=page_size, keyword=keyword) total, items = svc.list_tags(page=page, page_size=page_size, keyword=keyword)
return PositionTagListResponse( return success_response_payload(
200,
PositionTagListResponse(
total=total, total=total,
page=page,
page_size=page_size,
list=[PositionTagResponse.model_validate(item) for item in items], list=[PositionTagResponse.model_validate(item) for item in items],
).model_dump(mode="json"),
) )
@router.get("/{tag_id}/agents/statistics", response_model=PositionTagAgentStatistics) @router.get("/{tag_id}/agents/statistics", response_model=ApiResponse[PositionTagAgentStatistics])
def get_agent_statistics(tag_id: int, db: Session = Depends(get_db)): def get_agent_statistics(tag_id: int, db: Session = Depends(get_db)):
svc = PositionTagService(db) svc = PositionTagService(db)
try: try:
return svc.get_agent_statistics(tag_id) return success_response_payload(
200,
PositionTagAgentStatistics.model_validate(svc.get_agent_statistics(tag_id)).model_dump(mode="json"),
)
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=404, detail=str(e)) raise HTTPException(status_code=404, detail=str(e))
...@@ -7,6 +7,7 @@ from app.infrastructure.database import get_db ...@@ -7,6 +7,7 @@ from app.infrastructure.database import get_db
from app.infrastructure.session_store import SessionStore from app.infrastructure.session_store import SessionStore
from app.infrastructure.llm_client import InMemoryLLMClient, LLMClient from app.infrastructure.llm_client import InMemoryLLMClient, LLMClient
from app.infrastructure.file_parser import InMemoryFileParser, InMemoryOSSClient, FileParser, OSSClient from app.infrastructure.file_parser import InMemoryFileParser, InMemoryOSSClient, FileParser, OSSClient
from app.schema.common import ApiResponse
router = APIRouter(prefix="/api/v1") router = APIRouter(prefix="/api/v1")
...@@ -27,7 +28,7 @@ def get_parser() -> FileParser: ...@@ -27,7 +28,7 @@ def get_parser() -> FileParser:
return _parser return _parser
@router.post("/chat/completions", response_model=ChatCompletionResponse) @router.post("/chat/completions", response_model=ApiResponse[ChatCompletionResponse])
def chat_completions(req: ChatCompletionRequest, db: Session = Depends(get_db)): def chat_completions(req: ChatCompletionRequest, db: Session = Depends(get_db)):
session_store = SessionStore() session_store = SessionStore()
llm = get_llm() llm = get_llm()
...@@ -44,7 +45,7 @@ def chat_completions(req: ChatCompletionRequest, db: Session = Depends(get_db)): ...@@ -44,7 +45,7 @@ def chat_completions(req: ChatCompletionRequest, db: Session = Depends(get_db)):
raise HTTPException(status_code=400, detail=str(e)) raise HTTPException(status_code=400, detail=str(e))
@router.post("/files/upload", response_model=FileUploadResponse) @router.post("/files/upload", response_model=ApiResponse[FileUploadResponse])
async def upload_file( async def upload_file(
session_id: str = Form(...), session_id: str = Form(...),
file: UploadFile = File(...), file: UploadFile = File(...),
......
...@@ -4,6 +4,7 @@ from fastapi import APIRouter, Depends, HTTPException ...@@ -4,6 +4,7 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.infrastructure.database import get_db from app.infrastructure.database import get_db
from app.schema.common import ApiResponse, success_response_payload
from app.schema.session import ( from app.schema.session import (
SessionArchiveResponse, SessionArchiveResponse,
SessionContextResponse, SessionContextResponse,
...@@ -19,41 +20,40 @@ from app.service.session_service import SessionService ...@@ -19,41 +20,40 @@ from app.service.session_service import SessionService
router = APIRouter(prefix="/api/v1/sessions") router = APIRouter(prefix="/api/v1/sessions")
@router.post("", response_model=SessionCreateResponse, status_code=201) @router.post("", response_model=ApiResponse[SessionCreateResponse], status_code=201)
def create_session(req: SessionCreateRequest, db: Session = Depends(get_db)): def create_session(req: SessionCreateRequest, db: Session = Depends(get_db)):
svc = SessionService(db) svc = SessionService(db)
return svc.create(req) return success_response_payload(201, svc.create(req).model_dump(mode="json"))
@router.put("/{session_id}", response_model=SessionUpdateResponse) @router.put("/{session_id}", response_model=ApiResponse[SessionUpdateResponse])
def update_session(session_id: str, req: SessionUpdateRequest, db: Session = Depends(get_db)): def update_session(session_id: str, req: SessionUpdateRequest, db: Session = Depends(get_db)):
svc = SessionService(db) svc = SessionService(db)
try: try:
return svc.append_and_merge(session_id, req) return success_response_payload(200, svc.append_and_merge(session_id, req).model_dump(mode="json"))
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=404, detail=str(e)) raise HTTPException(status_code=404, detail=str(e))
@router.get("/{session_id}", response_model=SessionDetailResponse) @router.get("/{session_id}", response_model=ApiResponse[SessionDetailResponse])
def get_session_detail(session_id: str, db: Session = Depends(get_db)): def get_session_detail(session_id: str, db: Session = Depends(get_db)):
svc = SessionService(db) svc = SessionService(db)
try: try:
return svc.get_detail(session_id) return success_response_payload(200, svc.get_detail(session_id).model_dump(mode="json"))
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=404, detail=str(e)) raise HTTPException(status_code=404, detail=str(e))
@router.get("/{session_id}/context", response_model=SessionContextResponse) @router.get("/{session_id}/context", response_model=ApiResponse[SessionContextResponse])
def get_session_context(session_id: str, db: Session = Depends(get_db)): def get_session_context(session_id: str, db: Session = Depends(get_db)):
svc = SessionService(db) svc = SessionService(db)
return svc.get_context(session_id) return success_response_payload(200, svc.get_context(session_id).model_dump(mode="json"))
@router.post("/{session_id}/archive", response_model=SessionArchiveResponse) @router.post("/{session_id}/archive", response_model=ApiResponse[SessionArchiveResponse])
def archive_session(session_id: str, db: Session = Depends(get_db)): def archive_session(session_id: str, db: Session = Depends(get_db)):
svc = SessionService(db) svc = SessionService(db)
try: try:
return svc.archive(session_id) return success_response_payload(200, svc.archive(session_id).model_dump(mode="json"))
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=404, detail=str(e)) raise HTTPException(status_code=404, detail=str(e))
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.schema.common import ApiResponse
from app.schema.skill import SkillListResponse, SkillDetailResponse from app.schema.skill import SkillListResponse, SkillDetailResponse
from app.service.skill_service import SkillService from app.service.skill_service import SkillService
from app.infrastructure.database import get_db from app.infrastructure.database import get_db
...@@ -14,14 +15,14 @@ def get_cache() -> SkillCache: ...@@ -14,14 +15,14 @@ def get_cache() -> SkillCache:
return _default_cache return _default_cache
@router.get("", response_model=SkillListResponse) @router.get("", response_model=ApiResponse[SkillListResponse])
def list_skills(db: Session = Depends(get_db), cache: SkillCache = Depends(get_cache)): def list_skills(db: Session = Depends(get_db), cache: SkillCache = Depends(get_cache)):
svc = SkillService(db, cache) svc = SkillService(db, cache)
items = svc.list_skills() items = svc.list_skills()
return SkillListResponse(list=items) return SkillListResponse(list=items)
@router.get("/{skill_code}", response_model=SkillDetailResponse) @router.get("/{skill_code}", response_model=ApiResponse[SkillDetailResponse])
def get_skill_detail(skill_code: str, db: Session = Depends(get_db), cache: SkillCache = Depends(get_cache)): def get_skill_detail(skill_code: str, db: Session = Depends(get_db), cache: SkillCache = Depends(get_cache)):
svc = SkillService(db, cache) svc = SkillService(db, cache)
try: try:
......
from __future__ import annotations
from datetime import datetime, timezone
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from app.infrastructure.database import get_db
from app.infrastructure.wecom_sync_client import HttpWeComSyncClient, WeComSyncClientError
from app.model.wecom_sync import WeComBot, WeComSyncCheckpoint
from app.schema.common import ApiResponse, PageData, success_response_payload
from app.schema.wecom_sync import (
WeComSyncCheckpointItem,
WeComSyncCheckpointListResponse,
WeComSyncRunRequest,
WeComSyncRunResponse,
)
from app.service.wecom_sync_service import NoopWeComMessageDispatcher, WeComSyncService
router = APIRouter(prefix="/api/v1/wecom-sync")
def get_wecom_sync_service(db: Session = Depends(get_db)) -> WeComSyncService:
client = HttpWeComSyncClient()
dispatcher = NoopWeComMessageDispatcher()
return WeComSyncService(db, client, dispatcher)
@router.post("/run", response_model=ApiResponse[WeComSyncRunResponse])
def run_wecom_sync(req: WeComSyncRunRequest, svc: WeComSyncService = Depends(get_wecom_sync_service), db: Session = Depends(get_db)):
try:
if req.mode == "full":
result = svc.sync_all_full(
message_start_time=req.message_start_time,
message_end_time=req.message_end_time,
)
else:
bot_ids = req.bot_ids
if not bot_ids:
bot_ids = [item.bot_id for item in db.query(WeComBot).order_by(WeComBot.id.asc()).all()]
result = {
"bots": 0,
"contacts": 0,
"groups": 0,
"messages": svc.sync_messages_incremental(
bot_ids=bot_ids,
start_time=req.message_start_time,
end_time=req.message_end_time,
),
}
payload = WeComSyncRunResponse(
mode=req.mode,
bots=result["bots"],
contacts=result["contacts"],
groups=result["groups"],
messages=result["messages"],
triggered_at=datetime.now(timezone.utc),
)
return success_response_payload(200, payload.model_dump(mode="json"))
except WeComSyncClientError as exc:
raise HTTPException(status_code=503, detail=str(exc))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
@router.get("/checkpoints", response_model=ApiResponse[WeComSyncCheckpointListResponse])
def list_wecom_sync_checkpoints(
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
db: Session = Depends(get_db),
):
query = db.query(WeComSyncCheckpoint).order_by(
WeComSyncCheckpoint.resource_type.asc(),
WeComSyncCheckpoint.scope_key.asc(),
)
total = query.count()
rows = query.offset((page - 1) * page_size).limit(page_size).all()
payload = WeComSyncCheckpointListResponse(
total=total,
page=page,
page_size=page_size,
list=[
WeComSyncCheckpointItem(
resource_type=item.resource_type,
scope_key=item.scope_key,
last_sync_time=item.last_sync_time,
last_external_id=item.last_external_id,
last_status=item.last_status,
last_error=item.last_error,
last_started_at=item.last_started_at,
last_finished_at=item.last_finished_at,
)
for item in rows
],
)
return success_response_payload(200, payload.model_dump(mode="json"))
from fastapi import APIRouter from fastapi import APIRouter
from app.api.v1.endpoints import agent_group_helper, agents, position_tags, skills, sessions, routing, analytics, qrcode_channel, customer_group, official_site_tab, official_site_agent_display, official_site_upload, official_site_home, methodology from app.api.v1.endpoints import agent_group_helper, agent_hub, agents, position_tags, skills, sessions, routing, analytics, qrcode_channel, customer_group, official_site_tab, official_site_agent_display, official_site_upload, official_site_home, methodology, wecom_sync
api_router = APIRouter() api_router = APIRouter()
api_router.include_router(agent_group_helper.router, tags=["agent-group-helper"]) api_router.include_router(agent_group_helper.router, tags=["agent-group-helper"])
...@@ -16,4 +16,5 @@ api_router.include_router(official_site_agent_display.router, tags=["official-si ...@@ -16,4 +16,5 @@ api_router.include_router(official_site_agent_display.router, tags=["official-si
api_router.include_router(official_site_upload.router, tags=["official-site-upload"]) api_router.include_router(official_site_upload.router, tags=["official-site-upload"])
api_router.include_router(official_site_home.router, tags=["official-site-home"]) api_router.include_router(official_site_home.router, tags=["official-site-home"])
api_router.include_router(methodology.router, tags=["methodology"]) api_router.include_router(methodology.router, tags=["methodology"])
api_router.include_router(wecom_sync.router, tags=["wecom-sync"])
api_router.include_router(agent_hub.router, prefix="/api/v1/chat", tags=["chat"]) api_router.include_router(agent_hub.router, prefix="/api/v1/chat", tags=["chat"])
from sqlalchemy.orm import declarative_base, sessionmaker from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy import create_engine from sqlalchemy import create_engine, event
import os import os
# 数据库连接配置,实际开发中应从 config 读取 # 数据库连接配置,实际开发中应从 config 读取
...@@ -10,12 +10,29 @@ SQLALCHEMY_DATABASE_URL = os.getenv( ...@@ -10,12 +10,29 @@ SQLALCHEMY_DATABASE_URL = os.getenv(
engine = create_engine( engine = create_engine(
SQLALCHEMY_DATABASE_URL, SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False} if SQLALCHEMY_DATABASE_URL.startswith("sqlite") else {} connect_args=(
{
"check_same_thread": False,
"timeout": 30,
}
if SQLALCHEMY_DATABASE_URL.startswith("sqlite")
else {}
),
) )
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base() Base = declarative_base()
if SQLALCHEMY_DATABASE_URL.startswith("sqlite"):
@event.listens_for(engine, "connect")
def set_sqlite_pragma(dbapi_connection, _connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA journal_mode=WAL;")
cursor.execute("PRAGMA busy_timeout=30000;")
cursor.execute("PRAGMA synchronous=NORMAL;")
cursor.close()
def get_db(): def get_db():
db = SessionLocal() db = SessionLocal()
try: try:
......
from __future__ import annotations
import os
from datetime import datetime
from typing import Any
import httpx
from app.service.wecom_sync_service import WeComSyncClient
class WeComSyncClientError(Exception):
pass
class HttpWeComSyncClient(WeComSyncClient):
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
timeout_seconds: float = 30.0,
) -> None:
self.base_url = (base_url or os.getenv("WECOM_SYNC_BASE_URL", "http://yjy.dev.glsx.com.cn/webim")).rstrip("/")
self.api_key = api_key or os.getenv("BUSINESS_API_KEY", "")
self.timeout_seconds = timeout_seconds
def list_bots(self, *, page: int, page_size: int) -> dict[str, Any]:
return self._get("/api/v1/business/bots", {"page": page, "page_size": page_size})
def list_contacts(self, *, bot_id: str, page: int, page_size: int) -> dict[str, Any]:
return self._get(
"/api/v1/business/contacts",
{"bot_id": bot_id, "page": page, "page_size": page_size},
)
def list_groups(self, *, bot_id: str, page: int, page_size: int) -> dict[str, Any]:
return self._get(
"/api/v1/business/groups",
{"bot_id": bot_id, "page": page, "page_size": page_size},
)
def list_messages(
self,
*,
bot_id: str,
start_time: datetime | None,
end_time: datetime | None,
page: int,
page_size: int,
order: str = "asc",
) -> dict[str, Any]:
params: dict[str, Any] = {
"bot_id": bot_id,
"page": page,
"page_size": page_size,
"order": order,
}
if start_time is not None:
params["start_time"] = start_time.isoformat().replace("+00:00", "Z")
if end_time is not None:
params["end_time"] = end_time.isoformat().replace("+00:00", "Z")
return self._get("/api/v1/business/messages", params)
def _get(self, path: str, params: dict[str, Any]) -> dict[str, Any]:
headers = {"Content-Type": "application/json"}
if self.api_key:
headers["X-Api-Key"] = self.api_key
try:
with httpx.Client(timeout=self.timeout_seconds) as client:
response = client.get(f"{self.base_url}{path}", params=params, headers=headers)
response.raise_for_status()
payload = response.json()
except httpx.HTTPError as exc:
raise WeComSyncClientError(str(exc)) from exc
if not isinstance(payload, dict):
raise WeComSyncClientError("Unexpected response payload")
data = payload.get("data", payload)
if not isinstance(data, dict):
raise WeComSyncClientError("Unexpected response data")
return data
import json
import os import os
from pathlib import Path
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from fastapi import FastAPI from pathlib import Path
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from app.api.v1.router import api_router from app.api.v1.router import api_router
from app.config.loader import ConfigLoader from app.config.loader import ConfigLoader
from app.service.session_service import SessionService
from app.service.im_service import IMService
from app.service.console_im_service import ConsoleIMService
from app.service.agent_hub import AgentHub
from app.service.skill_scanner import update_skills_json
from app.infrastructure.database import SessionLocal, engine from app.infrastructure.database import SessionLocal, engine
from app.model.session import Base from app.model.session import Base
from app.schema.common import error_response_payload, is_wrapped_payload, success_response_payload
from app.service.agent_hub import AgentHub
from app.service.console_im_service import ConsoleIMService
from app.service.im_service import IMService
from app.service.session_service import SessionService
from app.service.skill_scanner import update_skills_json
agent_hub_instance = None agent_hub_instance = None
...@@ -21,7 +27,6 @@ async def lifespan(app: FastAPI): ...@@ -21,7 +27,6 @@ async def lifespan(app: FastAPI):
Base.metadata.create_all(bind=engine) Base.metadata.create_all(bind=engine)
# 启动时扫描 skills 目录,生成 skills.json 索引缓存
skills_dir = Path(__file__).parent.parent / "skills" skills_dir = Path(__file__).parent.parent / "skills"
config_dir = Path(__file__).parent.parent / "config" config_dir = Path(__file__).parent.parent / "config"
update_skills_json(skills_dir, config_dir) update_skills_json(skills_dir, config_dir)
...@@ -32,18 +37,16 @@ async def lifespan(app: FastAPI): ...@@ -32,18 +37,16 @@ async def lifespan(app: FastAPI):
if os.getenv("USE_CONSOLE_IM", "true").lower() == "true": if os.getenv("USE_CONSOLE_IM", "true").lower() == "true":
im_service = ConsoleIMService() im_service = ConsoleIMService()
print("[startup] 使用 ConsoleIMService — hook 输出将打印到控制台")
else: else:
im_service = IMService( im_service = IMService(
base_url=os.getenv("IM_BASE_URL", "http://localhost:8080"), base_url=os.getenv("IM_BASE_URL", "http://localhost:8080"),
api_key=os.getenv("IM_API_KEY", "your-api-key") api_key=os.getenv("IM_API_KEY", "your-api-key"),
) )
print(f"[startup] 使用 IMService → {os.getenv('IM_BASE_URL', 'http://localhost:8080')}")
agent_hub_instance = AgentHub( agent_hub_instance = AgentHub(
config_loader=config_loader, config_loader=config_loader,
session_service=session_service, session_service=session_service,
im_service=im_service im_service=im_service,
) )
yield yield
...@@ -52,7 +55,82 @@ async def lifespan(app: FastAPI): ...@@ -52,7 +55,82 @@ async def lifespan(app: FastAPI):
await agent_hub_instance.close() await agent_hub_instance.close()
app = FastAPI(title="Agent管理后台 API", version="1.0.0", lifespan=lifespan) app = FastAPI(title="Agent Admin API", version="1.0.0", lifespan=lifespan)
@app.exception_handler(HTTPException)
async def http_exception_handler(_: Request, exc: HTTPException):
message = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
return JSONResponse(
status_code=exc.status_code,
content=error_response_payload(exc.status_code, message),
)
@app.exception_handler(RequestValidationError)
async def request_validation_exception_handler(_: Request, exc: RequestValidationError):
first_error = exc.errors()[0] if exc.errors() else {}
loc = ".".join(str(part) for part in first_error.get("loc", []) if part != "body")
msg = first_error.get("msg", "请求参数不合法")
detail = f"参数校验失败:{loc} {msg}".strip()
return JSONResponse(
status_code=400,
content=error_response_payload(400, detail),
)
@app.exception_handler(Exception)
async def unhandled_exception_handler(_: Request, exc: Exception):
return JSONResponse(
status_code=500,
content=error_response_payload(500, str(exc) or "服务器内部错误"),
)
@app.middleware("http")
async def wrap_json_response(request: Request, call_next):
response = await call_next(request)
if request.url.path in {"/openapi.json", "/docs", "/docs/oauth2-redirect", "/redoc"}:
return response
content_type = response.headers.get("content-type", "")
if "application/json" not in content_type.lower():
return response
if response.status_code >= 400:
return response
body = b""
async for chunk in response.body_iterator:
body += chunk
if not body:
return Response(
content=body,
status_code=response.status_code,
headers=dict(response.headers),
media_type=response.media_type,
)
payload = json.loads(body)
if is_wrapped_payload(payload):
wrapped = payload
else:
wrapped = success_response_payload(response.status_code, payload)
headers = {
key: value
for key, value in response.headers.items()
if key.lower() != "content-length"
}
return JSONResponse(
status_code=response.status_code,
content=wrapped,
headers=headers,
)
app.include_router(api_router) app.include_router(api_router)
...@@ -63,4 +141,5 @@ def health_check(): ...@@ -63,4 +141,5 @@ def health_check():
if __name__ == "__main__": if __name__ == "__main__":
import uvicorn import uvicorn
uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True) uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True)
from app.model.agent import Agent, AgentPosition, AgentSkill, AgentStatus from app.model.agent import Agent, AgentPosition, AgentSkill, AgentStatus
from app.model.session import Session, SessionMessage, SessionStatus from app.model.session import Session, SessionStatus
from app.model.wecom_sync import WeComBot, WeComContact, WeComGroup, WeComMessage, WeComSyncCheckpoint
__all__ = [ __all__ = [
"Agent", "AgentPosition", "AgentSkill", "AgentStatus", "Agent", "AgentPosition", "AgentSkill", "AgentStatus",
"Session", "SessionMessage", "SessionStatus" "Session", "SessionStatus",
"WeComBot", "WeComContact", "WeComGroup", "WeComMessage", "WeComSyncCheckpoint",
] ]
from __future__ import annotations
from sqlalchemy import Boolean, Column, DateTime, Integer, JSON, String, Text, UniqueConstraint, func
from app.infrastructure.database import Base
class WeComBot(Base):
__tablename__ = "wecom_bots"
id = Column(Integer, primary_key=True, index=True)
channel = Column(String(64), nullable=False)
bot_id = Column(String(128), nullable=False)
bot_code = Column(String(191), nullable=False, unique=True, index=True)
bot_name = Column(String(255), nullable=False)
corp_name = Column(String(255), nullable=True)
online = Column(Boolean, nullable=True)
status = Column(String(64), nullable=True)
config = Column(JSON, nullable=True)
queue_count = Column(Integer, nullable=True)
pending_count = Column(Integer, nullable=True)
last_active = Column(DateTime, nullable=True)
last_fail = Column(DateTime, nullable=True)
external_created_at = Column(DateTime, nullable=True)
external_updated_at = Column(DateTime, nullable=True)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
class WeComContact(Base):
__tablename__ = "wecom_contacts"
id = Column(Integer, primary_key=True, index=True)
bot_code = Column(String(191), nullable=False, index=True)
channel = Column(String(64), nullable=False)
bot_id = Column(String(128), nullable=False)
contact_id = Column(String(191), nullable=False)
contact_type = Column(String(64), nullable=True)
account_type = Column(String(64), nullable=True)
contact_name = Column(String(255), nullable=False)
contact_remark = Column(String(255), nullable=True)
display_name = Column(String(255), nullable=True)
avatar_url = Column(String(500), nullable=True)
status = Column(String(64), nullable=True)
extra = Column(JSON, nullable=True)
last_active = Column(DateTime, nullable=True)
last_fail = Column(DateTime, nullable=True)
external_created_at = Column(DateTime, nullable=True)
external_updated_at = Column(DateTime, nullable=True)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
__table_args__ = (UniqueConstraint("bot_code", "contact_id", name="uk_wecom_contact_bot_contact"),)
class WeComGroup(Base):
__tablename__ = "wecom_groups"
id = Column(Integer, primary_key=True, index=True)
bot_code = Column(String(191), nullable=False, index=True)
channel = Column(String(64), nullable=False)
bot_id = Column(String(128), nullable=False)
group_id = Column(String(191), nullable=False)
group_name = Column(String(255), nullable=False)
group_type = Column(String(64), nullable=True)
avatar_url = Column(String(500), nullable=True)
status = Column(String(64), nullable=True)
extra = Column(JSON, nullable=True)
last_active = Column(DateTime, nullable=True)
external_created_at = Column(DateTime, nullable=True)
external_updated_at = Column(DateTime, nullable=True)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
__table_args__ = (UniqueConstraint("bot_code", "group_id", name="uk_wecom_group_bot_group"),)
class WeComMessage(Base):
__tablename__ = "wecom_messages"
id = Column(Integer, primary_key=True, index=True)
bot_code = Column(String(191), nullable=False, index=True)
channel = Column(String(64), nullable=False)
bot_id = Column(String(128), nullable=False)
msg_id = Column(String(191), nullable=False)
msg_time = Column(DateTime, nullable=False, index=True)
msg_type = Column(String(64), nullable=True)
msg_content = Column(Text, nullable=True)
sender_id = Column(String(191), nullable=True)
sender_name = Column(String(255), nullable=True)
contact_id = Column(String(191), nullable=True)
session_title = Column(String(255), nullable=True)
bot_send = Column(Boolean, nullable=False, default=False)
payload = Column(JSON, nullable=False)
dispatch_status = Column(String(32), nullable=True)
dispatch_error = Column(Text, nullable=True)
dispatch_at = Column(DateTime, nullable=True)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
__table_args__ = (UniqueConstraint("bot_code", "msg_id", name="uk_wecom_message_bot_msg"),)
class WeComSyncCheckpoint(Base):
__tablename__ = "wecom_sync_checkpoints"
id = Column(Integer, primary_key=True, index=True)
resource_type = Column(String(32), nullable=False)
scope_key = Column(String(191), nullable=False)
last_sync_time = Column(DateTime, nullable=True)
last_external_id = Column(String(191), nullable=True)
last_sync_cursor = Column(String(191), nullable=True)
last_status = Column(String(32), nullable=True)
last_error = Column(Text, nullable=True)
last_started_at = Column(DateTime, nullable=True)
last_finished_at = Column(DateTime, nullable=True)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
__table_args__ = (UniqueConstraint("resource_type", "scope_key", name="uk_wecom_sync_checkpoint_scope"),)
from app.schema.agent import AgentCreate, AgentUpdate, AgentStatusUpdate, AgentDetailResponse from app.schema.agent import AgentCreate, AgentUpdate, AgentStatusUpdate, AgentResponse
from app.schema.session import SessionResponse, MessageSchema
__all__ = [ __all__ = [
"AgentCreate", "AgentUpdate", "AgentStatusUpdate", "AgentDetailResponse", "AgentCreate", "AgentUpdate", "AgentStatusUpdate", "AgentResponse",
"SessionResponse", "MessageSchema"
] ]
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, Field
from typing import List, Optional from typing import List, Optional
from datetime import datetime from datetime import datetime
from app.model.agent import AgentStatus from app.model.agent import AgentStatus
...@@ -9,34 +9,52 @@ class AgentBase(BaseModel): ...@@ -9,34 +9,52 @@ class AgentBase(BaseModel):
status: AgentStatus = AgentStatus.enable status: AgentStatus = AgentStatus.enable
class AgentCreate(AgentBase): class AgentCreate(AgentBase):
code: str = Field(..., pattern=r"^[a-zA-Z_][a-zA-Z0-9_]*$")
position_ids: List[int] position_ids: List[int]
skill_codes: List[str] skill_codes: List[str]
class AgentUpdate(AgentBase): class AgentUpdate(AgentBase):
position_ids: Optional[List[int]] = None position_ids: Optional[List[int]] = None
skill_codes: Optional[List[str]] = None skill_codes: Optional[List[str]] = None
version: int
class AgentStatusUpdate(BaseModel): class AgentStatusUpdate(BaseModel):
status: AgentStatus status: AgentStatus
reason: Optional[str] = None reason: Optional[str] = None
class AgentSimpleResponse(AgentBase):
class AgentPositionItem(BaseModel):
id: int id: int
code: str name: str
created_at: datetime
updated_at: datetime
model_config = ConfigDict(from_attributes=True)
class AgentDetailResponse(AgentSimpleResponse): class AgentSkillItem(BaseModel):
skill_code: str
skill_name: str
class AgentResponse(BaseModel):
agent_id: int
name: str
code: str
position_ids: List[int] position_ids: List[int]
skill_codes: List[str] skill_codes: List[str]
version: int created_at: datetime
class AgentDetailResponse(BaseModel):
agent_id: int
name: str
code: str
description: Optional[str]
positions: List[AgentPositionItem]
skills: List[AgentSkillItem]
status: AgentStatus
session_count: int
created_at: datetime
updated_at: datetime
model_config = ConfigDict(from_attributes=True)
class AgentListResponse(BaseModel): class AgentListResponse(BaseModel):
total: int total: int
list: List[AgentSimpleResponse] page: int
page_size: int
list: List[AgentResponse]
from __future__ import annotations
from typing import Generic, List, TypeVar
from pydantic import BaseModel
T = TypeVar("T")
class ApiResponse(BaseModel, Generic[T]):
code: int
message: str
data: T
class ErrorResponse(BaseModel):
code: int
message: str
data: None = None
class PageData(BaseModel, Generic[T]):
total: int
page: int
page_size: int
list: List[T]
class SuccessFlagData(BaseModel):
success: bool
class DeleteSuccessData(BaseModel):
success: bool
deleted_at: str
class StatusSuccessData(BaseModel):
success: bool
status: str
def success_response_payload(status_code: int, data):
return {
"code": status_code,
"message": "success",
"data": data,
}
def error_response_payload(status_code: int, message: str):
return {
"code": status_code,
"message": message,
"data": None,
}
def is_wrapped_payload(payload) -> bool:
return isinstance(payload, dict) and set(payload.keys()) == {"code", "message", "data"}
...@@ -27,6 +27,8 @@ class PositionTagResponse(BaseModel): ...@@ -27,6 +27,8 @@ class PositionTagResponse(BaseModel):
class PositionTagListResponse(BaseModel): class PositionTagListResponse(BaseModel):
total: int total: int
page: int
page_size: int
list: List[PositionTagResponse] list: List[PositionTagResponse]
......
from __future__ import annotations
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field
class WeComSyncRunRequest(BaseModel):
mode: str = Field(..., pattern="^(full|incremental)$")
bot_ids: Optional[List[str]] = None
message_start_time: Optional[datetime] = None
message_end_time: Optional[datetime] = None
class WeComSyncRunResponse(BaseModel):
mode: str
bots: int
contacts: int
groups: int
messages: int
triggered_at: datetime
class WeComSyncCheckpointItem(BaseModel):
resource_type: str
scope_key: str
last_sync_time: Optional[datetime]
last_external_id: Optional[str]
last_status: Optional[str]
last_error: Optional[str]
last_started_at: Optional[datetime]
last_finished_at: Optional[datetime]
class WeComSyncCheckpointListResponse(BaseModel):
total: int
page: int
page_size: int
list: List[WeComSyncCheckpointItem]
import secrets
from typing import Optional
from sqlalchemy import and_, func
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from sqlalchemy import and_
from app.model.agent import Agent, AgentPosition, AgentSkill, AgentStatus from app.model.agent import Agent, AgentPosition, AgentSkill, AgentStatus
from app.schema.agent import AgentCreate, AgentUpdate, AgentStatusUpdate from app.model.position_tag import PositionTag
from typing import Optional from app.model.session import Session as AgentSession
from app.model.skill import Skill
from app.schema.agent import (
AgentCreate,
AgentDetailResponse,
AgentPositionItem,
AgentSkillItem,
AgentStatusUpdate,
AgentUpdate,
)
class AgentService: class AgentService:
def __init__(self, db: Session): def __init__(self, db: Session):
self.db = db self.db = db
def create(self, data: AgentCreate) -> Agent: def create(self, data: AgentCreate) -> Agent:
existing = self.db.query(Agent).filter(
Agent.code == data.code,
Agent.is_deleted == False
).first()
if existing:
raise ValueError("Agent编码已存在,请使用其他编码")
agent = Agent( agent = Agent(
name=data.name, name=data.name,
code=data.code, code=self._generate_unique_code(),
description=data.description, description=data.description,
status=data.status, status=data.status,
) )
...@@ -26,11 +33,9 @@ class AgentService: ...@@ -26,11 +33,9 @@ class AgentService:
self.db.flush() self.db.flush()
for pid in data.position_ids: for pid in data.position_ids:
ap = AgentPosition(agent_id=agent.id, position_id=pid) self.db.add(AgentPosition(agent_id=agent.id, position_id=pid))
self.db.add(ap)
for sc in data.skill_codes: for sc in data.skill_codes:
sk = AgentSkill(agent_id=agent.id, skill_code=sc) self.db.add(AgentSkill(agent_id=agent.id, skill_code=sc))
self.db.add(sk)
self.db.commit() self.db.commit()
self.db.refresh(agent) self.db.refresh(agent)
...@@ -39,40 +44,82 @@ class AgentService: ...@@ -39,40 +44,82 @@ class AgentService:
def update(self, agent_id: int, data: AgentUpdate) -> Agent: def update(self, agent_id: int, data: AgentUpdate) -> Agent:
agent = self._get_agent_or_404(agent_id) agent = self._get_agent_or_404(agent_id)
if agent.version != data.version:
raise ValueError("数据已被修改,请刷新后重试")
agent.name = data.name agent.name = data.name
agent.description = data.description agent.description = data.description
agent.status = data.status agent.status = data.status
agent.version += 1
if data.position_ids is not None: if data.position_ids is not None:
self.db.query(AgentPosition).filter(AgentPosition.agent_id == agent_id).delete() self.db.query(AgentPosition).filter(AgentPosition.agent_id == agent_id).delete()
for pid in data.position_ids: for pid in data.position_ids:
ap = AgentPosition(agent_id=agent_id, position_id=pid) self.db.add(AgentPosition(agent_id=agent_id, position_id=pid))
self.db.add(ap)
if data.skill_codes is not None: if data.skill_codes is not None:
self.db.query(AgentSkill).filter(AgentSkill.agent_id == agent_id).delete() self.db.query(AgentSkill).filter(AgentSkill.agent_id == agent_id).delete()
for sc in data.skill_codes: for sc in data.skill_codes:
sk = AgentSkill(agent_id=agent_id, skill_code=sc) self.db.add(AgentSkill(agent_id=agent_id, skill_code=sc))
self.db.add(sk)
self.db.commit() self.db.commit()
self.db.refresh(agent) self.db.refresh(agent)
return agent return agent
def delete(self, agent_id: int) -> None: def delete(self, agent_id: int) -> Agent:
agent = self._get_agent_or_404(agent_id) agent = self._get_agent_or_404(agent_id)
from datetime import datetime, timezone from datetime import datetime, timezone
agent.is_deleted = True agent.is_deleted = True
agent.deleted_at = datetime.now(timezone.utc) agent.deleted_at = datetime.now(timezone.utc)
self.db.commit() self.db.commit()
self.db.refresh(agent)
return agent
def get_detail(self, agent_id: int) -> Agent: def get_detail(self, agent_id: int) -> AgentDetailResponse:
return self._get_agent_or_404(agent_id) agent = self._get_agent_or_404(agent_id)
position_ids = sorted(ap.position_id for ap in agent.positions)
skill_codes = sorted(sk.skill_code for sk in agent.skills)
positions = []
if position_ids:
position_map = {
item.id: item.name
for item in self.db.query(PositionTag).filter(PositionTag.id.in_(position_ids)).all()
}
positions = [
AgentPositionItem(id=position_id, name=position_map.get(position_id, ""))
for position_id in position_ids
]
skills = []
if skill_codes:
skill_map = {
item.skill_code: item.skill_name
for item in self.db.query(Skill).filter(Skill.skill_code.in_(skill_codes)).all()
}
skills = [
AgentSkillItem(skill_code=skill_code, skill_name=skill_map.get(skill_code, ""))
for skill_code in skill_codes
]
session_count = (
self.db.query(func.count(AgentSession.id))
.filter(AgentSession.current_agent_id == agent.id)
.scalar()
or 0
)
return AgentDetailResponse(
agent_id=agent.id,
name=agent.name,
code=agent.code,
description=agent.description,
positions=positions,
skills=skills,
status=agent.status,
session_count=session_count,
created_at=agent.created_at,
updated_at=agent.updated_at,
)
def list_agents( def list_agents(
self, self,
...@@ -80,7 +127,7 @@ class AgentService: ...@@ -80,7 +127,7 @@ class AgentService:
page_size: int = 20, page_size: int = 20,
keyword: Optional[str] = None, keyword: Optional[str] = None,
position_id: Optional[int] = None, position_id: Optional[int] = None,
status: Optional[AgentStatus] = None status: Optional[AgentStatus] = None,
): ):
query = self.db.query(Agent).filter(Agent.is_deleted == False) query = self.db.query(Agent).filter(Agent.is_deleted == False)
...@@ -88,14 +135,14 @@ class AgentService: ...@@ -88,14 +135,14 @@ class AgentService:
query = query.filter( query = query.filter(
and_( and_(
Agent.is_deleted == False, Agent.is_deleted == False,
(Agent.name.like(f"%{keyword}%")) | (Agent.code.like(f"%{keyword}%")) (Agent.name.like(f"%{keyword}%")) | (Agent.code.like(f"%{keyword}%")),
) )
) )
if position_id is not None: if position_id is not None:
query = query.join(AgentPosition).filter( query = query.join(AgentPosition).filter(
AgentPosition.position_id == position_id, AgentPosition.position_id == position_id,
Agent.is_deleted == False Agent.is_deleted == False,
) )
if status is not None: if status is not None:
...@@ -114,10 +161,29 @@ class AgentService: ...@@ -114,10 +161,29 @@ class AgentService:
return agent return agent
def _get_agent_or_404(self, agent_id: int) -> Agent: def _get_agent_or_404(self, agent_id: int) -> Agent:
agent = self.db.query(Agent).filter( agent = (
self.db.query(Agent)
.filter(
Agent.id == agent_id, Agent.id == agent_id,
Agent.is_deleted == False Agent.is_deleted == False,
).first() )
.first()
)
if not agent: if not agent:
raise ValueError("Agent不存在") raise ValueError("Agent不存在")
return agent return agent
def _generate_unique_code(self) -> str:
for _ in range(20):
candidate = f"agent_{secrets.token_hex(4)}"
exists = (
self.db.query(Agent)
.filter(
Agent.code == candidate,
Agent.is_deleted == False,
)
.first()
)
if not exists:
return candidate
raise ValueError("自动生成Agent编码失败,请稍后重试")
No preview for this file type
No preview for this file type
# Backend Unified API Response Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 为 `workspace/agent-admin/backend` 现有 JSON 接口统一引入 `{code,message,data}` 响应结构,并让所有分页接口统一返回 `data.total/page/page_size/list`。
**Architecture:** 在 `app/main.py` 引入全局成功包装与全局异常处理,避免逐接口手工拼装外层结构;同时补充统一响应 schema/辅助工具,并逐步修正分页接口的内部数据结构与测试断言。文件流和非 JSON 响应保留豁免边界,避免破坏上传下载行为。
**Tech Stack:** FastAPI, Pydantic, Starlette `Response`, pytest, TestClient
---
### Task 1: 统一响应基础设施
**Files:**
- Modify: `workspace/agent-admin/backend/app/main.py`
- Create: `workspace/agent-admin/backend/app/schema/common.py`
- Test: `workspace/agent-admin/backend/tests/test_agents_api.py`
- Test: `workspace/agent-admin/backend/tests/test_sessions_api.py`
- [ ] **Step 1: 写失败测试,证明当前成功响应没有统一外层**
在 `workspace/agent-admin/backend/tests/test_agents_api.py` 中把创建接口断言改成:
```python
assert resp.status_code == 201
payload = resp.json()
assert payload["code"] == 201
assert payload["message"] == "success"
assert payload["data"]["code"] == "review_agent"
```
- [ ] **Step 2: 运行单测,确认红灯**
Run: `pytest tests/test_agents_api.py::TestCreateAgent::test_create_agent_success -q`
Expected: FAIL,提示响应体不存在 `code/message/data` 外层。
- [ ] **Step 3: 写失败测试,证明当前错误响应没有统一外层**
在 `workspace/agent-admin/backend/tests/test_agents_api.py` 的冲突场景中加入:
```python
assert resp.status_code == 400
payload = resp.json()
assert payload["code"] == 400
assert payload["data"] is None
assert isinstance(payload["message"], str)
```
- [ ] **Step 4: 运行单测,确认红灯**
Run: `pytest tests/test_agents_api.py::TestCreateAgent::test_create_agent_code_conflict -q`
Expected: FAIL,提示错误响应体仍是 FastAPI 默认结构。
- [ ] **Step 5: 实现统一成功包装与统一错误处理**
在 `workspace/agent-admin/backend/app/schema/common.py` 中新增统一响应模型和分页数据模型;在 `workspace/agent-admin/backend/app/main.py` 中增加:
- 普通 JSON 成功响应包装
- `HTTPException` 统一错误包装
- `RequestValidationError` 统一错误包装
- 未捕获异常统一错误包装
- 非 JSON / 原始 `Response` / 流式响应豁免逻辑
- [ ] **Step 6: 运行最小测试,确认转绿**
Run: `pytest tests/test_agents_api.py::TestCreateAgent::test_create_agent_success tests/test_agents_api.py::TestCreateAgent::test_create_agent_code_conflict -q`
Expected: PASS
### Task 2: 改造分页响应契约
**Files:**
- Modify: `workspace/agent-admin/backend/app/schema/agent.py`
- Modify: `workspace/agent-admin/backend/app/schema/position_tag.py`
- Modify: `workspace/agent-admin/backend/app/schema/qrcode_channel.py`
- Modify: `workspace/agent-admin/backend/app/schema/customer_group.py`
- Modify: `workspace/agent-admin/backend/app/schema/analytics.py`
- Modify: `workspace/agent-admin/backend/app/schema/official_site_tab.py`
- Modify: `workspace/agent-admin/backend/app/schema/skill.py`
- Modify: `workspace/agent-admin/backend/app/api/v1/endpoints/agents.py`
- Modify: `workspace/agent-admin/backend/app/api/v1/endpoints/position_tags.py`
- Modify: `workspace/agent-admin/backend/app/api/v1/endpoints/analytics.py`
- Modify: `workspace/agent-admin/backend/app/service/customer_group_service.py`
- Test: `workspace/agent-admin/backend/tests/test_agents_api.py`
- Test: `workspace/agent-admin/backend/tests/test_position_tag_api.py`
- Test: `workspace/agent-admin/backend/tests/test_skill_api.py`
- [ ] **Step 1: 写失败测试,证明分页接口缺少 `page/page_size` 或缺少统一 `data` 内结构**
优先改 `tests/test_agents_api.py` 和 `tests/test_position_tag_api.py`:
```python
payload = resp.json()
assert payload["code"] == 200
assert payload["message"] == "success"
assert payload["data"]["page"] == 1
assert payload["data"]["page_size"] == 20
assert isinstance(payload["data"]["list"], list)
```
- [ ] **Step 2: 运行单测,确认红灯**
Run: `pytest tests/test_agents_api.py::TestListAgents::test_list_agents_success tests/test_position_tag_api.py::TestListPositionTags::test_list_success -q`
Expected: FAIL
- [ ] **Step 3: 为分页模型补齐统一内部结构**
将分页相关 schema 改为统一包含:
```python
total: int
page: int
page_size: int
list: list[...]
```
缺失 `page/page_size` 的分页模型必须补齐。
- [ ] **Step 4: 修正分页 endpoint/service 返回**
确保分页接口返回的原始业务对象在进入统一包装前,已经是:
```python
{"total": total, "page": page, "page_size": page_size, "list": items}
```
- [ ] **Step 5: 运行分页相关测试,确认转绿**
Run: `pytest tests/test_agents_api.py tests/test_position_tag_api.py tests/test_skill_api.py -q`
Expected: PASS
### Task 3: 改造其余 JSON 接口测试
**Files:**
- Modify: `workspace/agent-admin/backend/tests/test_sessions_api.py`
- Modify: `workspace/agent-admin/backend/tests/test_skill_api.py`
- Modify: `workspace/agent-admin/backend/tests/test_agent_hub.py`
- Modify: `workspace/agent-admin/backend/tests/test_qrcode_channel_api.py`
- Modify: `workspace/agent-admin/backend/tests/test_customer_group_api.py`
- Modify: `workspace/agent-admin/backend/tests/test_analytics_api.py`
- Modify: `workspace/agent-admin/backend/tests/test_methodology_api.py`
- Modify: `workspace/agent-admin/backend/tests/test_official_site_*`
- [ ] **Step 1: 批量把测试改为统一读取 `payload = resp.json()` 再断言 `payload["data"]`**
示例:
```python
payload = resp.json()
assert payload["code"] == 200
assert payload["message"] == "success"
data = payload["data"]
```
- [ ] **Step 2: 对错误场景统一断言**
```python
payload = resp.json()
assert payload["code"] == resp.status_code
assert payload["data"] is None
assert isinstance(payload["message"], str)
```
- [ ] **Step 3: 运行相关测试,确认红灯来源仅为未改造实现**
Run: `pytest tests/test_sessions_api.py tests/test_skill_api.py tests/test_agent_hub.py -q`
Expected: 如果实现已覆盖,应 PASS;若仍 FAIL,失败点应是漏改接口。
- [ ] **Step 4: 补齐漏改接口实现**
根据失败测试补齐 endpoint / service / schema 中遗漏的普通 JSON 接口。
- [ ] **Step 5: 再次运行测试,确认转绿**
Run: `pytest tests/test_sessions_api.py tests/test_skill_api.py tests/test_agent_hub.py tests/test_qrcode_channel_api.py tests/test_customer_group_api.py tests/test_analytics_api.py -q`
Expected: PASS
### Task 4: 校验特殊接口与 `/health`
**Files:**
- Modify: `workspace/agent-admin/backend/app/main.py`
- Test: `workspace/agent-admin/backend/tests/test_official_site_upload_api.py`
- Test: `workspace/agent-admin/backend/tests/test_routing_api.py`
- [ ] **Step 1: 写失败测试,确认上传返回 JSON 仍需统一包装**
在上传相关测试中新增断言:
```python
payload = resp.json()
assert payload["code"] == 200
assert payload["message"] == "success"
assert payload["data"]["url"]
```
- [ ] **Step 2: 若存在文件流/特殊响应,写保护性测试**
若接口返回原始 `Response` 或文件流,断言媒体类型与原行为不变。
- [ ] **Step 3: 运行专项测试**
Run: `pytest tests/test_official_site_upload_api.py tests/test_routing_api.py -q`
Expected: PASS
### Task 5: 更新测试文档
**Files:**
- Modify: `workspace/agent-admin/backend/docs/wangxz/*.md`
- [ ] **Step 1: 更新成功响应示例**
所有成功示例统一改成:
```json
{
"code": 200,
"message": "success",
"data": {}
}
```
分页接口改成:
```json
{
"code": 200,
"message": "success",
"data": {
"total": 0,
"page": 1,
"page_size": 20,
"list": []
}
}
```
- [ ] **Step 2: 更新错误响应示例和断言文字**
统一说明错误结构为:
```json
{
"code": 400,
"message": "错误说明",
"data": null
}
```
- [ ] **Step 3: 更新测试预期描述**
把文档里类似 `data["name"]` 的描述,调整为 `payload["data"]["name"]` 语义。
### Task 6: 最终验证
**Files:**
- Modify: `workspace/agent-admin/backend/openspec/changes/backend-unified-api-response/tasks.md`
- [ ] **Step 1: 运行 backend 全量测试**
Run: `pytest tests -q`
Expected: PASS
- [ ] **Step 2: 运行编译检查**
Run: `python -m compileall app tests -q`
Expected: 无报错
- [ ] **Step 3: 回填 OpenSpec tasks 状态**
把 `backend-unified-api-response/tasks.md` 中已完成项勾选完成。
# 后端接口测试文档: agents
## 1. 模块说明
| 项 | 值 |
|------|-----|
| 模块名 | agents |
| 基础路径 | `/api/v1/agents` |
| 说明 | Agent 基础管理,包含创建、更新、删除、详情、列表和状态更新 |
## 2. 通用响应规范
成功响应:
```json
{
"code": 200,
"message": "success",
"data": {}
}
```
错误响应:
```json
{
"code": 400,
"message": "错误信息",
"data": null
}
```
分页响应:
```json
{
"code": 200,
"message": "success",
"data": {
"total": 2,
"page": 1,
"page_size": 20,
"list": []
}
}
```
## 3. 接口说明
### 3.1 创建 Agent
- 方法: `POST`
- 路径: `/api/v1/agents`
- 说明: 请求体不再传 `code`,由后端自动生成 `agent_` 前缀唯一编码
请求体:
```json
{
"name": "复盘 Agent",
"description": "智能复盘助手",
"position_ids": [1],
"skill_codes": ["query-metric"],
"status": "enable"
}
```
成功响应示例:
```json
{
"code": 201,
"message": "success",
"data": {
"agent_id": 101,
"name": "复盘 Agent",
"code": "agent_a7k29xqp",
"position_ids": [1],
"skill_codes": ["query-metric"],
"created_at": "2026-05-15T10:30:00Z"
}
}
```
### 3.2 更新 Agent
- 方法: `PUT`
- 路径: `/api/v1/agents/{agent_id}`
请求体:
```json
{
"name": "更新后 Agent",
"description": "更新后的描述",
"status": "enable",
"position_ids": [1, 2],
"skill_codes": ["query-metric", "query-detail"]
}
```
成功响应示例:
```json
{
"code": 200,
"message": "success",
"data": {
"agent_id": 101,
"name": "更新后 Agent",
"code": "agent_a7k29xqp",
"position_ids": [1, 2],
"skill_codes": ["query-detail", "query-metric"],
"created_at": "2026-05-15T10:30:00Z"
}
}
```
### 3.3 删除 Agent
- 方法: `DELETE`
- 路径: `/api/v1/agents/{agent_id}`
成功响应示例:
```json
{
"code": 200,
"message": "success",
"data": {
"success": true,
"deleted_at": "2026-05-15T14:30:00Z"
}
}
```
### 3.4 查询 Agent 详情
- 方法: `GET`
- 路径: `/api/v1/agents/{agent_id}`
成功响应示例:
```json
{
"code": 200,
"message": "success",
"data": {
"agent_id": 101,
"name": "复盘 Agent",
"code": "agent_a7k29xqp",
"description": "智能复盘助手",
"positions": [
{"id": 1, "name": "驻店销售岗"},
{"id": 3, "name": "客服岗"}
],
"skills": [
{"skill_code": "query-metric", "skill_name": "指标查询"},
{"skill_code": "query-detail", "skill_name": "明细查询"},
{"skill_code": "attribution-analysis", "skill_name": "归因分析"}
],
"status": "enable",
"session_count": 156,
"created_at": "2026-05-10T09:00:00Z",
"updated_at": "2026-05-15T10:00:00Z"
}
}
```
### 3.5 查询 Agent 列表
- 方法: `GET`
- 路径: `/api/v1/agents`
- 查询参数:
- `page`
- `page_size`
- `keyword`
- `position_id`
- `status`
成功响应示例:
```json
{
"code": 200,
"message": "success",
"data": {
"total": 2,
"page": 1,
"page_size": 20,
"list": [
{
"agent_id": 1,
"name": "Agent1",
"code": "agent_1abc23de",
"position_ids": [1],
"skill_codes": ["query-metric"],
"created_at": "2026-05-21T10:00:00"
},
{
"agent_id": 2,
"name": "Agent2",
"code": "agent_9f0c12ab",
"position_ids": [2],
"skill_codes": ["query-detail"],
"created_at": "2026-05-21T10:01:00"
}
]
}
}
```
### 3.6 更新 Agent 状态
- 方法: `PUT`
- 路径: `/api/v1/agents/{agent_id}/status`
请求体:
```json
{
"status": "disable",
"reason": "手动禁用"
}
```
成功响应示例:
```json
{
"code": 200,
"message": "success",
"data": {
"success": true,
"status": "disable"
}
}
```
## 4. 测试覆盖
文档对应测试文件: `backend/tests/test_agents_api.py`
| 测试类 | 测试方法 |
|------|------|
| `TestCreateAgent` | `test_create_agent_success` |
| `TestCreateAgent` | `test_create_agent_generates_unique_code` |
| `TestUpdateAgent` | `test_update_agent_success` |
| `TestUpdateAgent` | `test_update_agent_without_version` |
| `TestDeleteAgent` | `test_delete_agent_success` |
| `TestGetAgentDetail` | `test_get_agent_detail_success` |
| `TestListAgents` | `test_list_agents_success` |
| `TestListAgents` | `test_list_agents_with_keyword` |
| `TestUpdateStatus` | `test_disable_agent` |
# 接口测试文档 — customer-group
---
## 1. 模块概览
| 字段 | 值 |
|------|-----|
| 模块名称 | customer-group |
| 模块说明 | 一客一群自动化 — 群创建、Agent入群、群解散、回调处理、幂等+分布式锁 |
| 路由前缀 | `/api/v1/agent-group` |
| 数据库表 | `customer_groups` |
| 外部依赖 | WeComGroupClient(企微建群API)、DistributedLock、IdempotencyStore |
---
## 2. 接口列表
| 序号 | 方法 | 路径 | 说明 |
|------|------|------|------|
| 1 | POST | `/api/v1/agent-group/group/create` | 创建一客一群 |
| 2 | POST | `/api/v1/agent-group/group/{group_id}/agent-join` | Agent加入群 |
| 3 | GET | `/api/v1/agent-group/group/list` | 查询群列表 |
| 4 | POST | `/api/v1/agent-group/callback/scan` | 扫码回调 |
| 5 | POST | `/api/v1/agent-group/callback/member-exit` | 成员退出回调 |
---
## 3. 接口详细说明
### 3.1 创建一客一群
**基本信息**
| 字段 | 值 |
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/agent-group/group/create` |
| 说明 | 为客户创建专属服务群,已存在活跃群时复用 |
| Content-Type | application/json |
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| customer_user_id | body | string | 是 | 客户企微ID,最长64 |
| channel_code | body | string | 是 | 渠道编码,最长128 |
| position_code | body | string | 是 | 岗位编码,最长100 |
| employee_wechat_user_ids | body | string[] | 是 | 员工企微ID列表,至少1人 |
| agent_ids | body | integer[] | 否 | Agent ID列表 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| group_id | string | 群ID |
| group_name | string | 群名(格式:"客户昵称 的专属服务群") |
| creator_employee_id | string | 创建者员工ID |
| created_at | string | 创建时间 |
| members | array | 成员列表 |
| members[].user_id | string | 用户ID |
| members[].name | string | 用户名 |
| members[].type | string | 成员类型 |
**成功响应示例**
```json
{
"group_id": "group_abc",
"group_name": "张先生 的专属服务群",
"creator_employee_id": null,
"created_at": "2026-05-21T10:00:00",
"members": [
{"user_id": "wo_external_123", "name": "张先生", "type": "customer"},
{"user_id": "zhangsan", "name": "张三", "type": "employee"},
{"user_id": "lisi", "name": "李四", "type": "employee"}
]
}
```
---
### 3.2 Agent加入群
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| group_id | path | string | 是 | 群ID |
| agent_ids | body | integer[] | 是 | Agent ID列表,至少1个 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| success | boolean | 是否全部成功 |
| joined_agents | array | 成功加入的Agent列表 |
| joined_agents[].agent_id | integer | Agent ID |
| joined_agents[].agent_name | string | Agent名称 |
| failed_agents | array | 失败的Agent列表 |
**错误码**
| HTTP 状态码 | 触发条件 | 错误信息示例 |
|-------------|----------|-------------|
| 404 | 群不存在 | 不存在 |
---
### 3.3 查询群列表
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| page | query | integer | 否 | 页码,默认1 |
| page_size | query | integer | 否 | 每页条数,默认20 |
| customer_user_id | query | string | 否 | 按客户筛选 |
| status | query | string | 否 | 按状态筛选:active / dissolved |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| total | integer | 总条数 |
| list | array | 群列表 |
| list[].group_id | string | 群ID |
| list[].group_name | string | 群名 |
| list[].status | string | 状态 |
| list[].customer_info | object | 客户信息 |
| list[].employee_list | array | 员工列表 |
| list[].agent_list | array | Agent列表 |
---
### 3.4 扫码回调
**基本信息**
| 字段 | 值 |
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/agent-group/callback/scan` |
| 说明 | 企微扫码事件回调,幂等处理 |
| Content-Type | application/xml |
**响应**:XML 格式 `<Success>SUCCESS</Success>`
---
### 3.5 成员退出回调
**基本信息**
| 字段 | 值 |
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/agent-group/callback/member-exit` |
| 说明 | 企微成员退出回调,客户退出则自动解散群 |
| Content-Type | application/xml |
**逻辑**:is_customer=True → 解散群;is_customer=False → 不解散
---
## 4. 测试场景
### 4.1 创建群
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 创建成功 | 正常 | group_id 非空,group_name 含"专属服务群",members=3 |
| 2 | 复用已有活跃群 | 正常 | 两次创建返回同一 group_id |
| 3 | 群名格式验证 | 正常 | group_name=="张先生 的专属服务群" |
### 4.2 Agent入群
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 全部成功 | 正常 | success=True, joined_agents=1, failed_agents=0 |
| 2 | 部分失败 | 异常 | success=False, failed_agents=1 |
| 3 | 群不存在 | 异常 | ValueError "不存在" |
### 4.3 解散群
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 解散成功 | 正常 | status=="dissolved", dissolved_at 非空 |
| 2 | 群不存在 | 异常 | ValueError |
| 3 | 重复解散 | 异常 | ValueError "已解散" |
### 4.4 群列表
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 查询全部 | 正常 | total=2 |
| 2 | 按状态筛选 | 正常 | status=active → 0; status=dissolved → 1 |
| 3 | 按客户筛选 | 正常 | total=1 |
| 4 | 空结果 | 边界 | total=0, list=[] |
### 4.5 幂等与分布式锁
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 幂等防重 | 同一 event_id 第二次 check_and_mark 返回 False |
| 2 | 锁获取释放 | acquire → True, release 后可再次 acquire |
### 4.6 回调处理
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 扫码回调 | 返回 "SUCCESS" |
| 2 | 扫码幂等 | 重复 event_id 仍返回 "SUCCESS" |
| 3 | 客户退群触发解散 | 群 status=="dissolved" |
| 4 | 员工退群不解散 | 群 status=="active" |
### 4.7 集成流程
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 扫码→建群→Agent入群→查询→退群解散 | 全流程通过 |
---
## 5. 对应测试代码
测试文件:`backend/tests/test_customer_group_api.py`
| 测试类 | 测试方法 | 对应场景 |
|--------|----------|----------|
| TestCreateGroup | test_create_success | 4.1-1 |
| TestCreateGroup | test_create_reuse_existing_active_group | 4.1-2 |
| TestCreateGroup | test_create_group_name_format | 4.1-3 |
| TestAgentJoin | test_agent_join_success | 4.2-1 |
| TestAgentJoin | test_agent_join_partial_failure | 4.2-2 |
| TestAgentJoin | test_agent_join_group_not_found | 4.2-3 |
| TestDissolveGroup | test_dissolve_success | 4.3-1 |
| TestDissolveGroup | test_dissolve_not_found | 4.3-2 |
| TestDissolveGroup | test_dissolve_already_dissolved | 4.3-3 |
| TestListGroups | test_list_all | 4.4-1 |
| TestListGroups | test_list_filter_by_status | 4.4-2 |
| TestListGroups | test_list_filter_by_customer | 4.4-3 |
| TestListGroups | test_list_empty | 4.4-4 |
| TestIdempotencyAndLock | test_idempotency_prevents_duplicate_processing | 4.5-1 |
| TestIdempotencyAndLock | test_distributed_lock_acquire_release | 4.5-2 |
| TestCallbackHandling | test_scan_callback_returns_success_immediately | 4.6-1 |
| TestCallbackHandling | test_scan_callback_idempotent | 4.6-2 |
| TestCallbackHandling | test_member_exit_callback_customer_triggers_dissolve | 4.6-3 |
| TestCallbackHandling | test_member_exit_callback_employee_no_dissolve | 4.6-4 |
| TestIntegrationFlow | test_scan_create_join_exit_dissolve | 4.7-1 |
# 接口测试文档 — methodology
---
## 1. 模块概览
| 字段 | 值 |
|------|-----|
| 模块名称 | methodology |
| 模块说明 | 方法论展示配置管理 — 查询/保存方法论,步骤数4~10,序号连续 |
| 路由前缀 | `/api/v1/official-site/methodology` |
| 数据库表 | `official_site_methodology`, `official_site_methodology_steps` |
| 外部依赖 | H5CacheManager(缓存失效) |
---
## 2. 接口列表
| 序号 | 方法 | 路径 | 说明 |
|------|------|------|------|
| 1 | GET | `/api/v1/official-site/methodology` | 查询方法论配置 |
| 2 | POST | `/api/v1/official-site/methodology` | 保存方法论配置 |
---
## 3. 接口详细说明
### 3.1 查询方法论配置
**基本信息**
| 字段 | 值 |
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/official-site/methodology` |
| 说明 | 查询当前方法论配置,无数据时返回默认值 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| config_id | integer | 配置ID,无数据时为0 |
| display_status | string | 展示状态:enable/disable |
| main_title | string | 主标题,默认"方法论" |
| sub_title | string | 副标题 |
| steps | array | 步骤列表,按 step_order 排序 |
| steps[].step_id | integer | 步骤ID |
| steps[].step_icon | string | 步骤图标URL |
| steps[].step_name | string | 步骤名称 |
| steps[].step_order | integer | 步骤序号 |
| steps[].step_image | string | 步骤图片URL |
| updated_at | string | 更新时间 |
---
### 3.2 保存方法论配置
**基本信息**
| 字段 | 值 |
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/official-site/methodology` |
| 说明 | 保存/更新方法论配置,自动替换旧数据 |
| Content-Type | application/json |
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| display_status | body | string | 否 | 默认"enable" |
| main_title | body | string | 是 | 主标题,最长100 |
| sub_title | body | string | 是 | 副标题,最长200 |
| steps | body | array | 否 | 步骤列表,数量4~10 |
| steps[].step_icon | body | string | 是 | 图标URL,最长500 |
| steps[].step_name | body | string | 是 | 步骤名称,最长20 |
| steps[].step_order | body | integer | 是 | 序号,从1开始连续 |
| steps[].step_image | body | string | 是 | 步骤图片URL,最长500 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| config_id | integer | 配置ID,同一配置更新后 ID 不变 |
| updated_at | string | 更新时间 |
**错误码**
| HTTP 状态码 | 触发条件 | 错误信息示例 |
|-------------|----------|-------------|
| 400 | 步骤数 <4 或 >10 | "4.*10" |
| 400 | 步骤序号不连续 | "序号" |
| 400 | 步骤序号重复 | "序号" |
---
## 4. 测试场景
### 4.1 查询方法论
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 空数据返回默认 | 正常 | config_id=0, main_title="方法论", steps=[] |
| 2 | 有数据正确返回 | 正常 | config_id>0, steps按step_order排序 |
| 3 | 步骤按序号排序 | 正常 | 乱序插入后返回有序 |
### 4.2 保存方法论
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 新建成功 | 正常 | config_id>0, 查询确认4条步骤 |
| 2 | 更新已有配置 | 正常 | config_id不变, main_title更新为"新标题", steps=6条 |
| 3 | 步骤数不足(<4) | 异常 | ValueError 匹配 "4.*10" |
| 4 | 步骤序号不连续 | 异常 | ValueError 匹配 "序号" |
| 5 | 步骤序号重复 | 异常 | ValueError 匹配 "序号" |
| 6 | 保存后缓存失效 | 正常 | cache.was_invalidated()==True |
### 4.3 集成流程
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 查询空→保存→查询有数据 | config_id从0变为>0, steps=4条, orders=[1,2,3,4] |
---
## 5. 对应测试代码
测试文件:`backend/tests/test_methodology_api.py`
| 测试类 | 测试方法 | 对应场景 |
|--------|----------|----------|
| TestGetMethodology | test_query_empty_returns_default | 4.1-1 |
| TestGetMethodology | test_query_with_data | 4.1-2 |
| TestGetMethodology | test_steps_sorted_by_order | 4.1-3 |
| TestSaveMethodology | test_save_new | 4.2-1 |
| TestSaveMethodology | test_save_updates_existing | 4.2-2 |
| TestSaveMethodology | test_step_count_too_few | 4.2-3 |
| TestSaveMethodology | test_step_order_non_sequential | 4.2-4 |
| TestSaveMethodology | test_step_order_duplicate | 4.2-5 |
| TestSaveMethodology | test_save_invalidates_cache | 4.2-6 |
| TestIntegrationFlow | test_query_save_query | 4.3-1 |
# 接口测试文档 — official-site-agent-display
---
## 1. 模块概览
| 字段 | 值 |
|------|-----|
| 模块名称 | official-site-agent-display |
| 模块说明 | 官网Agent展示配置 — 可用Agent列表、配置保存、已配置列表、删除配置 |
| 路由前缀 | `/api/v1/official-site/tabs` |
| 数据库表 | `official_site_agent_display` |
| 外部依赖 | H5CacheManager(缓存失效) |
---
## 2. 接口列表
| 序号 | 方法 | 路径 | 说明 |
|------|------|------|------|
| 1 | GET | `/api/v1/official-site/tabs/{tab_id}/agents/available` | 查询可用Agent列表 |
| 2 | POST | `/api/v1/official-site/tabs/{tab_id}/agents/{agent_id}/config` | 保存Agent配置 |
| 3 | GET | `/api/v1/official-site/tabs/{tab_id}/agents/configured` | 查询已配置Agent列表 |
| 4 | DELETE | `/api/v1/official-site/tabs/{tab_id}/agents/{agent_id}/config` | 删除Agent配置 |
---
## 3. 接口详细说明
### 3.1 查询可用Agent列表
| 字段 | 值 |
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/official-site/tabs/{tab_id}/agents/available` |
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| tab_id | path | integer | 是 | Tab ID |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| tab_id | integer | Tab ID |
| position_name | string | 岗位名称 |
| qrcode_id | integer | 活码ID |
| available_agents | array | 可配置Agent列表(排除管家Agent) |
| available_agents[].agent_id | integer | Agent ID |
| available_agents[].agent_name | string | Agent名称 |
| available_agents[].agent_code | string | Agent编码 |
| available_agents[].is_configured | boolean | 是否已配置 |
| available_agents[].is_steward | boolean | 是否管家Agent |
| steward_agent | object | 管家Agent信息 |
| steward_agent.agent_id | integer | Agent ID |
| steward_agent.note | string | 说明文本 |
**错误码**
| HTTP 状态码 | 触发条件 |
|-------------|----------|
| 404 | Tab不存在 |
---
### 3.2 保存Agent配置
| 字段 | 值 |
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/official-site/tabs/{tab_id}/agents/{agent_id}/config` |
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| tab_id | path | integer | 是 | Tab ID |
| agent_id | path | integer | 是 | Agent ID |
| media_url | body | string | 是 | 素材URL,最长500 |
| media_type | body | string | 是 | 素材格式:gif/mp4 |
| media_size | body | integer | 否 | 素材大小(bytes) |
| speech_title | body | string | 是 | 话术标题 |
| speech_content | body | string | 是 | 话术正文 |
| display_status | body | string | 否 | 默认"enable" |
| sort_order | body | integer | 否 | 排序,默认0 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| config_id | integer | 配置ID,更新时不变 |
| tab_id | integer | Tab ID |
| agent_id | integer | Agent ID |
| updated_at | string | 更新时间 |
**错误码**
| HTTP 状态码 | 触发条件 |
|-------------|----------|
| 400 | Agent不在可配置列表中 / 素材格式无效 / 素材过大 / 话术标题过长 |
| 404 | Tab不存在 |
---
### 3.3 查询已配置Agent列表
| 字段 | 值 |
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/official-site/tabs/{tab_id}/agents/configured` |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| tab_id | integer | Tab ID |
| configured_agents | array | 已配置Agent列表,按sort_order排序 |
| configured_agents[].config_id | integer | 配置ID |
| configured_agents[].agent_id | integer | Agent ID |
| configured_agents[].agent_name | string | Agent名称 |
| configured_agents[].display_status | string | 展示状态 |
| configured_agents[].sort_order | integer | 排序 |
| configured_agents[].agent_status | string | Agent启用状态 |
---
### 3.4 删除Agent配置
| 字段 | 值 |
|------|-----|
| 方法 | DELETE |
| 路径 | `/api/v1/official-site/tabs/{tab_id}/agents/{agent_id}/config` |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| success | boolean | 是否成功 |
| deleted_at | string | 删除时间 |
**错误码**
| HTTP 状态码 | 触发条件 |
|-------------|----------|
| 400/404 | 配置不存在 |
---
## 4. 测试场景
### 4.1 可用Agent列表
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 排除管家Agent | steward.id 不在 available_agents 的 agent_ids 中 |
| 2 | 管家Agent信息返回 | steward_agent 含"管家" |
| 3 | is_configured标记正确 | 已配置的agent is_configured=True |
| 4 | Tab不存在 | ValueError "Tab不存在" |
### 4.2 保存配置
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 新建成功 | config_id>0 |
| 2 | 更新已有配置 | config_id不变,DB中仅1条记录 |
| 3 | Agent不在可配置列表 | ValueError "不在可配置列表中" |
| 4 | 素材格式无效(png) | ValueError "素材格式" |
| 5 | 素材过大 | ValueError "大小" |
| 6 | 话术标题过长 | ValueError "话术" |
| 7 | 保存后缓存失效 | cache.was_invalidated() |
### 4.3 已配置Agent列表
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 正常列出 | configured_agents 长度=1, agent_status="enable" |
| 2 | 按sort_order排序 | sort_order小的在前 |
| 3 | Tab不存在 | ValueError |
### 4.4 删除配置
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 删除成功 | success=True, DB中该配置已移除, Agent本身未删除 |
| 2 | 配置不存在 | ValueError "配置不存在" |
| 3 | 删除后缓存失效 | cache.was_invalidated() |
### 4.5 集成流程
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 查可用→保存→查已配置→删除→查已配置空 | 全流程通过 |
---
## 5. 对应测试代码
测试文件:`backend/tests/test_official_site_agent_display_api.py`
| 测试类 | 测试方法 | 对应场景 |
|--------|----------|----------|
| TestAvailableAgents | test_returns_available_agents_excluding_steward | 4.1-1 |
| TestAvailableAgents | test_steward_info_returned | 4.1-2 |
| TestAvailableAgents | test_is_configured_marked_correctly | 4.1-3 |
| TestAvailableAgents | test_tab_not_found | 4.1-4 |
| TestSaveAgentConfig | test_save_new_config | 4.2-1 |
| TestSaveAgentConfig | test_update_existing_config | 4.2-2 |
| TestSaveAgentConfig | test_agent_not_in_available_list | 4.2-3 |
| TestSaveAgentConfig | test_invalid_media_format | 4.2-4 |
| TestSaveAgentConfig | test_media_too_large | 4.2-5 |
| TestSaveAgentConfig | test_speech_title_too_long | 4.2-6 |
| TestSaveAgentConfig | test_save_invalidates_cache | 4.2-7 |
| TestConfiguredAgents | test_list_configured | 4.3-1 |
| TestConfiguredAgents | test_sort_order_respected | 4.3-2 |
| TestConfiguredAgents | test_tab_not_found | 4.3-3 |
| TestDeleteAgentConfig | test_delete_config | 4.4-1 |
| TestDeleteAgentConfig | test_agent_not_deleted | 4.4-1 |
| TestDeleteAgentConfig | test_config_not_found | 4.4-2 |
| TestDeleteAgentConfig | test_delete_invalidates_cache | 4.4-3 |
| TestIntegrationFlow | test_full_flow | 4.5-1 |
# 接口测试文档 — official-site-home
---
## 1. 模块概览
| 字段 | 值 |
|------|-----|
| 模块名称 | official-site-home |
| 模块说明 | H5首页聚合接口 — 一次返回Tab+Agent+方法论+缓存 |
| 路由前缀 | `/api/v1/official-site/home` |
| 数据库表 | `official_tabs`, `official_site_agent_display`, `official_site_methodology` 等 |
| 外部依赖 | H5CacheManager(TTL缓存) |
---
## 2. 接口列表
| 序号 | 方法 | 路径 | 说明 |
|------|------|------|------|
| 1 | GET | `/api/v1/official-site/home` | 获取H5首页数据 |
---
## 3. 接口详细说明
### 3.1 获取H5首页数据
**基本信息**
| 字段 | 值 |
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/official-site/home` |
| 说明 | 聚合Tab、Agent展示、方法论数据,支持缓存(TTL=300s) |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| site_title | string | 站点标题 |
| site_subtitle | string | 站点副标题 |
| background_image | string | 背景图 |
| tabs | array | Tab列表 |
| tabs[].tab_id | integer | Tab ID |
| tabs[].position_code | string | 岗位编码 |
| tabs[].position_name | string | 岗位名称 |
| tabs[].qrcode_url | string | 活码URL |
| tabs[].agents | array | Agent列表 |
| tabs[].agents[].agent_id | integer | Agent ID |
| tabs[].agents[].agent_name | string | Agent名称 |
| tabs[].agents[].media_url | string | 素材URL |
| tabs[].agents[].speech_title | string | 话术标题 |
| tabs[].agents[].speech_content | string | 话术正文 |
| methodology | object | 方法论 |
| methodology.display_status | string | enable/disable |
| methodology.main_title | string | 主标题 |
| methodology.sub_title | string | 副标题 |
| methodology.steps | array | 步骤列表 |
**过滤规则**:disable的Tab不返回,disable的Agent配置不返回,Agent本身disable也不返回
---
## 4. 测试场景
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 缓存未命中从DB构建 | 正常 | site_title非空,tabs有1条,agents有1条 |
| 2 | 缓存命中返回缓存数据 | 正常 | DB修改后仍返回旧数据 |
| 3 | disable的Tab不返回 | 正常 | tabs长度=0 |
| 4 | disable的Agent配置不返回 | 正常 | tabs有1条但agents为空 |
| 5 | Agent本身disable不返回 | 正常 | agents为空 |
| 6 | sort_order排序 | 正常 | sort_order小的Agent在前 |
| 7 | 缓存未命中时写入 | 正常 | cache.get_home_page()非空 |
| 8 | 缓存失效后刷新 | 正常 | 修改Agent名后invalidate再查,返回新名称 |
| 9 | 方法论数据返回 | 正常 | methodology.display_status="enable", steps=2 |
| 10 | 空站点 | 边界 | tabs=[], methodology.display_status="disable" |
---
## 5. 对应测试代码
测试文件:`backend/tests/test_official_site_home_api.py`
| 测试方法 | 对应场景 |
|----------|----------|
| test_cache_miss_builds_from_db | 1 |
| test_cache_hit_returns_cached_data | 2 |
| test_disabled_tab_excluded | 3 |
| test_disabled_agent_excluded | 4 |
| test_agent_disabled_status_excluded | 5 |
| test_sort_order_respected | 6 |
| test_cache_write_on_miss | 7 |
| test_cache_invalidate_then_refresh | 8 |
| test_methodology_returned | 9 |
| test_empty_site | 10 |
# 接口测试文档 — official-site-tab
---
## 1. 模块概览
| 字段 | 值 |
|------|-----|
| 模块名称 | official-site-tab |
| 模块说明 | 官网岗位Tab配置 — Tab增删改查 + 状态切换 + 可用活码列表 |
| 路由前缀 | `/api/v1/official-site/tabs` |
| 数据库表 | `official_tabs` |
| 外部依赖 | H5CacheManager(缓存失效) |
---
## 2. 接口列表
| 序号 | 方法 | 路径 | 说明 |
|------|------|------|------|
| 1 | POST | `/api/v1/official-site/tabs` | 创建Tab |
| 2 | PUT | `/api/v1/official-site/tabs/{tab_id}` | 更新Tab |
| 3 | DELETE | `/api/v1/official-site/tabs/{tab_id}` | 删除Tab(软删除) |
| 4 | PUT | `/api/v1/official-site/tabs/{tab_id}/status` | 更新Tab状态 |
| 5 | GET | `/api/v1/official-site/tabs` | 分页查询Tab列表 |
| 6 | GET | `/api/v1/official-site/tabs/qrcodes/available` | 查询可用活码列表 |
---
## 3. 接口详细说明
### 3.1 创建Tab
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| position_code | body | string | 是 | 岗位编码 |
| position_name | body | string | 是 | 岗位名称 |
| qrcode_id | body | integer | 是 | 活码ID |
| display_status | body | string | 否 | enable/disable,默认enable |
| sort_order | body | integer | 否 | 排序,默认0 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| tab_id | integer | Tab ID |
| position_code | string | 岗位编码 |
| position_name | string | 岗位名称 |
| qrcode_id | integer | 活码ID |
| created_at | string | 创建时间 |
**错误码**
| HTTP 状态码 | 触发条件 |
|-------------|----------|
| 400 | 岗位不存在 / 活码已停用 |
---
### 3.2 更新Tab
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| tab_id | path | integer | 是 | Tab ID |
| position_name | body | string | 是 | 岗位名称 |
| qrcode_id | body | integer | 是 | 活码ID |
| display_status | body | string | 否 | enable/disable |
| sort_order | body | integer | 否 | 排序 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| success | boolean | 是否成功 |
| updated_at | string | 更新时间 |
---
### 3.3 删除Tab
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| success | boolean | 是否成功 |
| deleted_at | string | 删除时间 |
| cleaned_agent_configs | integer | 清理的Agent配置数 |
---
### 3.4 更新Tab状态
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| display_status | body | string | 是 | enable/disable |
| reason | body | string | 否 | 原因 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| success | boolean | 是否成功 |
| previous_status | string | 变更前状态 |
| updated_at | string | 更新时间 |
---
### 3.5 分页查询Tab列表
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| page | query | integer | 否 | 默认1 |
| page_size | query | integer | 否 | 默认20 |
| keyword | query | string | 否 | 搜索关键词 |
| display_status | query | string | 否 | 按状态筛选 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| total | integer | 总条数 |
| list | array | Tab列表 |
| list[].tab_id | integer | Tab ID |
| list[].position_name | string | 岗位名称 |
| list[].display_status | string | 状态 |
| list[].sort_order | integer | 排序 |
| list[].agent_count | integer | Agent数量 |
---
### 3.6 查询可用活码列表
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| position_code | query | string | 否 | 按岗位筛选 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| list | array | 活码列表 |
| list[].qrcode_id | integer | 活码ID |
| list[].channel_code | string | 渠道编码 |
| list[].employee_name | string | 员工姓名 |
| list[].status | string | 状态 |
---
## 4. 测试场景
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 创建成功 | 正常 | tab_id>0, position_code正确 |
| 2 | 岗位不存在 | 异常 | ValueError "岗位不存在" |
| 3 | 活码已停用 | 异常 | ValueError "活码.*停用" |
| 4 | 创建后缓存失效 | 正常 | cache.was_invalidated() |
| 5 | 更新成功 | 正常 | success=True |
| 6 | 更新不存在Tab | 异常 | ValueError "不存在" |
| 7 | 更新后缓存失效 | 正常 | cache.was_invalidated() |
| 8 | 删除成功(软删除) | 正常 | success=True, deleted_at非空, DB中deleted_at非空 |
| 9 | 删除不存在Tab | 异常 | ValueError |
| 10 | 删除后缓存失效 | 正常 | cache.was_invalidated() |
| 11 | 禁用Tab | 正常 | success=True, previous_status="enable" |
| 12 | 启用Tab | 正常 | previous_status="disable" |
| 13 | 状态变更不影响活码 | 正常 | qr.status仍为"enable" |
| 14 | 查询全部 | 正常 | total=2, 按sort_order排序 |
| 15 | 按状态筛选 | 正常 | enable→0, disable→1 |
| 16 | 关键词搜索 | 正常 | keyword="驻店" → total=1 |
| 17 | 可用活码列表 | 正常 | 仅返回enable状态的活码 |
| 18 | 按岗位筛选活码 | 正常 | 仅返回指定岗位活码 |
| 19 | 集成流程 | 集成 | 创建→列表→更新→状态→删除 全通过 |
---
## 5. 对应测试代码
测试文件:`backend/tests/test_official_site_tab_api.py`
| 测试类 | 测试方法 | 对应场景 |
|--------|----------|----------|
| TestCreateTab | test_create_success | 1 |
| TestCreateTab | test_create_position_not_found | 2 |
| TestCreateTab | test_create_qrcode_disabled | 3 |
| TestCreateTab | test_create_invalidates_cache | 4 |
| TestUpdateTab | test_update_success | 5 |
| TestUpdateTab | test_update_not_found | 6 |
| TestUpdateTab | test_update_invalidates_cache | 7 |
| TestDeleteTab | test_delete_success | 8 |
| TestDeleteTab | test_delete_not_found | 9 |
| TestDeleteTab | test_delete_invalidates_cache | 10 |
| TestUpdateTabStatus | test_disable_tab | 11 |
| TestUpdateTabStatus | test_enable_tab | 12 |
| TestUpdateTabStatus | test_status_change_does_not_affect_qrcode | 13 |
| TestListTabs | test_list_all | 14 |
| TestListTabs | test_list_filter_by_status | 15 |
| TestListTabs | test_list_keyword_search | 16 |
| TestAvailableQrcodes | test_list_available | 17 |
| TestAvailableQrcodes | test_list_available_by_position | 18 |
| TestIntegrationFlow | test_create_list_update_status_delete | 19 |
# 接口测试文档 — official-site-upload
---
## 1. 模块概览
| 字段 | 值 |
|------|-----|
| 模块名称 | official-site-upload |
| 模块说明 | 官网素材上传 — 格式/大小校验 + OSS存储 + 图片宽高解析 + CDN URL |
| 路由前缀 | `/api/v1/official-site/upload` |
| 数据库表 | 无 |
| 外部依赖 | OSSClient(对象存储) |
---
## 2. 接口列表
| 序号 | 方法 | 路径 | 说明 |
|------|------|------|------|
| 1 | POST | `/api/v1/official-site/upload` | 上传素材文件 |
---
## 3. 接口详细说明
### 3.1 上传素材文件
**基本信息**
| 字段 | 值 |
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/official-site/upload` |
| 说明 | 上传Agent素材或方法论图片,支持 gif/mp4/png/jpg |
| Content-Type | multipart/form-data |
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| usage_type | form | string | 是 | 用途类型:agent_media / methodology_icon / methodology_image |
| file | form | file | 是 | 上传文件 |
**usage_type 对应校验规则**
| usage_type | 允许格式 | 大小限制 | 解析宽高 |
|------------|----------|----------|----------|
| agent_media | gif, mp4 | 20MB | 否 |
| methodology_icon | png, jpg | 2MB | 是 |
| methodology_image | png, jpg | 2MB | 是 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| file_url | string | OSS存储路径 |
| file_type | string | 文件格式(gif/mp4/png/jpg) |
| file_size | integer | 文件大小(bytes) |
| width | integer | 图片宽度,非图片为null |
| height | integer | 图片高度,非图片为null |
| cdn_url | string | CDN访问URL,含版本号 `?v=2026` |
**成功响应示例**
```json
{
"file_url": "https://oss.example.com/agent/2026/05/demo.gif",
"file_type": "gif",
"file_size": 1024,
"width": null,
"height": null,
"cdn_url": "https://cdn.example.com/agent/2026/05/demo.gif?v=2026"
}
```
**错误码**
| HTTP 状态码 | 触发条件 |
|-------------|----------|
| 400 | 文件格式不支持 / 文件过大 / usage_type无效 |
---
## 4. 测试场景
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | Agent素材gif上传 | 正常 | file_type="gif", file_url含"agent/", cdn_url含"?v=" |
| 2 | Agent素材mp4上传 | 正常 | file_type="mp4", width/height为null |
| 3 | 方法论图标png上传 | 正常 | file_type="png", file_url含"methodology/icon/", width=200, height=200 |
| 4 | 方法论图片jpg上传 | 正常 | file_type="jpg", file_url含"methodology/image/", width=800, height=600 |
| 5 | 格式不支持(pdf) | 异常 | ValueError "格式" |
| 6 | Agent素材超20MB | 异常 | ValueError "20MB" |
| 7 | 方法论图标超2MB | 异常 | ValueError "2MB" |
| 8 | CDN URL含版本号 | 正常 | cdn_url含"?v=2026" |
| 9 | 非图片无宽高 | 正常 | mp4的width/height为null |
| 10 | 无效usage_type | 异常 | ValueError "类型" |
| 11 | OSS集成验证 | 正常 | 通过OSS客户端可读取已上传文件 |
---
## 5. 对应测试代码
测试文件:`backend/tests/test_official_site_upload_api.py`
| 测试方法 | 对应场景 |
|----------|----------|
| test_agent_media_gif_success | 1 |
| test_agent_media_mp4_success | 2 |
| test_methodology_icon_png_success | 3 |
| test_methodology_image_jpg_success | 4 |
| test_invalid_format_rejected | 5 |
| test_agent_media_size_exceeded | 6 |
| test_methodology_icon_size_exceeded | 7 |
| test_cdn_url_has_version | 8 |
| test_width_height_optional_for_non_image | 9 |
| test_invalid_usage_type | 10 |
| test_oss_upload_integration | 11 |
# 接口测试文档 — position-tag
---
## 1. 模块概览
| 字段 | 值 |
|------|-----|
| 模块名称 | position-tag |
| 模块说明 | 岗位标签管理 — 增删改查 + 引用检测 + Agent统计 |
| 路由前缀 | `/api/v1/position-tags` |
| 数据库表 | `position_tags` |
| 外部依赖 | 无 |
---
## 2. 接口列表
| 序号 | 方法 | 路径 | 说明 |
|------|------|------|------|
| 1 | POST | `/api/v1/position-tags` | 创建岗位标签 |
| 2 | PUT | `/api/v1/position-tags/{tag_id}` | 更新岗位标签 |
| 3 | GET | `/api/v1/position-tags/{tag_id}/references` | 引用检测 |
| 4 | DELETE | `/api/v1/position-tags/{tag_id}` | 删除岗位标签 |
| 5 | GET | `/api/v1/position-tags` | 分页查询岗位标签列表 |
| 6 | GET | `/api/v1/position-tags/{tag_id}/agents/statistics` | Agent统计 |
---
## 3. 接口详细说明
### 3.1 创建岗位标签
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| name | body | string | 是 | 名称,最长20 |
| code | body | string | 是 | 编码,格式 `[a-zA-Z_][a-zA-Z0-9_]*`,唯一 |
| description | body | string | 否 | 描述,最长100 |
**错误码**
| HTTP 状态码 | 触发条件 |
|-------------|----------|
| 409 | code已存在 |
| 422 | code格式不合法 |
---
### 3.2 更新岗位标签
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| name | body | string | 是 | 名称 |
| description | body | string | 否 | 描述 |
**错误码**
| HTTP 状态码 | 触发条件 |
|-------------|----------|
| 404 | 标签不存在 |
---
### 3.3 引用检测
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| can_delete | boolean | 是否可删除 |
| blocking_references | array | 阻塞性引用(qrcode_channel, official_tab) |
| blocking_references[].type | string | 引用类型 |
| blocking_references[].id | integer | 引用ID |
| detachable_references | array | 可解除引用(agent) |
| hints | string[] | 提示信息 |
**逻辑**:有阻塞性引用 → can_delete=False;仅有agent引用 → can_delete=True(需confirm_detach)
---
### 3.4 删除岗位标签
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| tag_id | path | integer | 是 | 标签ID |
| confirm_detach_agents | query | boolean | 否 | 确认解除Agent关联,默认false |
**错误码**
| HTTP 状态码 | 触发条件 |
|-------------|----------|
| 409 | 有阻塞性引用 / 有Agent引用但未confirm |
| 404 | 标签不存在 |
---
### 3.5 分页查询
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| page | query | integer | 否 | 默认1 |
| page_size | query | integer | 否 | 默认20 |
| keyword | query | string | 否 | 搜索名称或编码 |
---
### 3.6 Agent统计
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| position_id | integer | 岗位ID |
| agent_count | integer | Agent总数 |
| active_agent_count | integer | 启用Agent数 |
| agents | array | Agent列表 |
| agents[].id | integer | Agent ID |
| agents[].name | string | Agent名称 |
| agents[].status | string | Agent状态 |
---
## 4. 测试场景
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 创建成功 | 正常 | HTTP 201, name/code正确 |
| 2 | code重复返回409 | 异常 | HTTP 409 |
| 3 | code格式不合法返回422 | 异常 | HTTP 422 |
| 4 | 更新成功 | 正常 | name更新, code不变 |
| 5 | 更新不存在返回404 | 异常 | HTTP 404 |
| 6 | 无引用可删除 | 正常 | can_delete=True |
| 7 | 活码阻塞引用 | 正常 | can_delete=False, blocking含qrcode_channel |
| 8 | Tab阻塞引用 | 正常 | can_delete=False, blocking含official_tab |
| 9 | Agent可解除引用 | 正常 | can_delete=True, detachable含agent |
| 10 | 引用检测不存在 | 异常 | HTTP 404 |
| 11 | 无引用删除成功 | 正常 | HTTP 200 |
| 12 | 阻塞引用删除返回409 | 异常 | HTTP 409 |
| 13 | Agent引用+confirm删除 | 正常 | HTTP 200 |
| 14 | Agent引用无confirm返回409 | 异常 | HTTP 409 |
| 15 | 删除不存在返回404 | 异常 | HTTP 404 |
| 16 | 分页查询 | 正常 | total>=2 |
| 17 | 关键词搜索 | 正常 | keyword="销售" → 命中 |
| 18 | 关键词匹配code | 正常 | keyword含code片段 → 命中 |
| 19 | 空列表 | 边界 | total=0, list=[] |
| 20 | Agent统计 | 正常 | agent_count=2, active_agent_count=1 |
| 21 | 无Agent统计 | 边界 | agent_count=0 |
| 22 | 统计不存在标签 | 异常 | HTTP 404 |
---
## 5. 对应测试代码
测试文件:`backend/tests/test_position_tag_api.py`
| 测试类 | 测试方法 | 对应场景 |
|--------|----------|----------|
| TestCreatePositionTag | test_create_success | 1 |
| TestCreatePositionTag | test_create_code_conflict_returns_409 | 2 |
| TestCreatePositionTag | test_create_invalid_code_format | 3 |
| TestUpdatePositionTag | test_update_success | 4 |
| TestUpdatePositionTag | test_update_nonexistent_returns_404 | 5 |
| TestReferenceCheck | test_no_references_can_delete | 6 |
| TestReferenceCheck | test_blocking_reference_from_qrcode_channel | 7 |
| TestReferenceCheck | test_blocking_reference_from_official_tab | 8 |
| TestReferenceCheck | test_detachable_reference_from_agent | 9 |
| TestReferenceCheck | test_nonexistent_tag_returns_404 | 10 |
| TestDeletePositionTag | test_delete_no_references | 11 |
| TestDeletePositionTag | test_delete_with_blocking_reference_returns_409 | 12 |
| TestDeletePositionTag | test_delete_with_agent_reference_and_confirm | 13 |
| TestDeletePositionTag | test_delete_with_agent_reference_without_confirm_returns_409 | 14 |
| TestDeletePositionTag | test_delete_nonexistent_returns_404 | 15 |
| TestListPositionTags | test_list_success | 16 |
| TestListPositionTags | test_list_with_keyword | 17 |
| TestListPositionTags | test_list_keyword_matches_code | 18 |
| TestListPositionTags | test_list_empty | 19 |
| TestPositionTagAgentStatistics | test_statistics_success | 20 |
| TestPositionTagAgentStatistics | test_statistics_no_agents | 21 |
| TestPositionTagAgentStatistics | test_statistics_nonexistent_tag_returns_404 | 22 |
# 接口测试文档 — qrcode-channel
---
## 1. 模块概览
| 字段 | 值 |
|------|-----|
| 模块名称 | qrcode-channel |
| 模块说明 | 渠道活码配置管理 — 增删改查 + 启用/禁用 + 批量操作 + 导出 |
| 路由前缀 | `/api/v1/agent-group/qrcode` |
| 数据库表 | `qrcode_channels` |
| 外部依赖 | WeComClient(创建活码)、OSSClient(导出) |
---
## 2. 接口列表
| 序号 | 方法 | 路径 | 说明 |
|------|------|------|------|
| 1 | POST | `/api/v1/agent-group/qrcode/create` | 创建渠道活码 |
| 2 | PUT | `/api/v1/agent-group/qrcode/{qrcode_id}` | 更新活码 |
| 3 | GET | `/api/v1/agent-group/qrcode/{qrcode_id}` | 查询活码详情 |
| 4 | GET | `/api/v1/agent-group/qrcode/list` | 分页查询活码列表 |
| 5 | POST | `/api/v1/agent-group/qrcode/export` | 导出活码 |
| 6 | PUT | `/api/v1/agent-group/qrcode/{qrcode_id}/disable` | 禁用活码 |
| 7 | PUT | `/api/v1/agent-group/qrcode/{qrcode_id}/enable` | 启用活码 |
| 8 | POST | `/api/v1/agent-group/qrcode/batch-status` | 批量启用/禁用 |
---
## 3. 接口详细说明
### 3.1 创建渠道活码
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| qrcode_name | body | string | 是 | 活码名称,最长50 |
| position_code | body | string | 是 | 岗位编码 |
| employee_id | body | string | 是 | 员工ID |
| employee_name | body | string | 是 | 员工姓名 |
| wechat_user_id | body | string | 是 | 企微用户ID |
| remark | body | string | 否 | 备注 |
| welcome_message | body | string | 否 | 欢迎语 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| qrcode_id | integer | 活码ID |
| qrcode_name | string | 活码名称 |
| qrcode_url | string | 企微活码URL |
| channel_code | string | 渠道编码(格式:zdxs_{position_code}_{employee_id}) |
| status | string | 状态,默认enable |
| agent_ids | integer[] | 关联Agent ID列表 |
| agent_names | string[] | 关联Agent名称列表 |
| created_at | string | 创建时间 |
**错误码**
| HTTP 状态码 | 触发条件 |
|-------------|----------|
| 400 | 岗位不存在 |
| 409 | 同岗位同员工活码已存在 |
---
### 3.2 更新活码
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| qrcode_name | body | string | 是 | 活码名称 |
| remark | body | string | 否 | 备注 |
| welcome_message | body | string | 否 | 欢迎语 |
---
### 3.3 活码详情
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| qrcode_id | integer | 活码ID |
| qrcode_name | string | 活码名称 |
| employee_id | string | 员工ID |
| employee_name | string | 员工姓名 |
| position_name | string | 岗位名称 |
| channel_code | string | 渠道编码 |
| qrcode_url | string | 活码URL |
| agent_ids | integer[] | Agent ID列表 |
| welcome_message | string | 欢迎语 |
| status | string | 状态 |
---
### 3.4 禁用/启用活码
**禁用请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| reason | body | string | 是 | 停用原因 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| success | boolean | 是否成功 |
| previous_status | string | 变更前状态 |
---
### 3.5 批量状态变更
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| qrcode_ids | body | integer[] | 是 | 活码ID列表,至少1个 |
| target_status | body | string | 是 | enable/disable |
| reason | body | string | 否 | 原因 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| success_count | integer | 成功数 |
| failed_count | integer | 失败数 |
| failed_list | array | 失败列表 |
---
## 4. 测试场景
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 创建成功 | 正常 | qrcode_id>0, channel_code格式正确, 含管家+岗位Agent |
| 2 | 岗位不存在 | 异常 | ValueError "岗位不存在" |
| 3 | 重复创建返回冲突 | 异常 | ValueError "已存在同岗位活码" |
| 4 | channel_code格式 | 正常 | zdxs_{code}_{emp_id} |
| 5 | 自动包含管家+岗位Agent | 正常 | agent_ids含steward和metric |
| 6 | 更新成功 | 正常 | success=True |
| 7 | 更新不存在 | 异常 | ValueError |
| 8 | 详情查询 | 正常 | qrcode_name, welcome_message正确 |
| 9 | 详情不存在 | 异常 | ValueError |
| 10 | 列表按员工名筛选 | 正常 | total=1 |
| 11 | 列表按状态筛选 | 正常 | status=enable → total=1 |
| 12 | 列表关键词搜索 | 正常 | keyword匹配channel_code |
| 13 | 列表空结果 | 边界 | total=0, list=[] |
| 14 | 导出成功 | 正常 | total_count=1, file_url非空 |
| 15 | 禁用成功 | 正常 | success=True, previous_status="enable" |
| 16 | 启用成功 | 正常 | previous_status="disable" |
| 17 | 禁用不存在 | 异常 | ValueError |
| 18 | 批量禁用 | 正常 | success_count=2, failed_count=0 |
| 19 | 批量部分失败 | 正常 | success_count=1, failed_count=1 |
| 20 | 集成:创建→查询→更新→禁用→启用 | 集成 | 全流程通过 |
---
## 5. 对应测试代码
测试文件:`backend/tests/test_qrcode_channel_api.py`
| 测试类 | 测试方法 | 对应场景 |
|--------|----------|----------|
| TestCreateQrcode | test_create_success | 1 |
| TestCreateQrcode | test_create_position_not_found | 2 |
| TestCreateQrcode | test_create_duplicate_returns_409 | 3 |
| TestCreateQrcode | test_create_channel_code_format | 4 |
| TestCreateQrcode | test_create_auto_includes_steward_and_position_agents | 5 |
| TestUpdateQrcode | test_update_success | 6 |
| TestUpdateQrcode | test_update_nonexistent | 7 |
| TestGetDetail | test_detail_success | 8 |
| TestGetDetail | test_detail_not_found | 9 |
| TestListQrcodes | test_list_with_employee_name_filter | 10 |
| TestListQrcodes | test_list_by_status | 11 |
| TestListQrcodes | test_list_keyword_search | 12 |
| TestListQrcodes | test_list_empty | 13 |
| TestExport | test_export_success | 14 |
| TestDisableEnable | test_disable_success | 15 |
| TestDisableEnable | test_enable_success | 16 |
| TestDisableEnable | test_disable_not_found | 17 |
| TestBatchStatus | test_batch_disable | 18 |
| TestBatchStatus | test_batch_with_failures | 19 |
| TestIntegrationFlow | test_create_query_update_disable_enable | 20 |
# 接口测试文档 — routing
---
## 1. 模块概览
| 字段 | 值 |
|------|-----|
| 模块名称 | routing |
| 模块说明 | 路由与意图识别 — 消息路由(mention/inheritance/default) + 意图识别 + Agent交接 + 文件上传 |
| 路由前缀 | `/api/v1` |
| 数据库表 | `ai_agents` |
| 外部依赖 | LLMClient(意图识别)、SessionStore(会话状态)、FileParser、OSSClient |
---
## 2. 接口列表
| 序号 | 方法 | 路径 | 说明 |
|------|------|------|------|
| 1 | POST | `/api/v1/chat/completions` | 路由决策接口 |
| 2 | POST | `/api/v1/files/upload` | 文件上传与文本提取 |
---
## 3. 接口详细说明
### 3.1 路由决策接口
**基本信息**
| 字段 | 值 |
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/chat/completions` |
| 说明 | 根据mention/继承/默认策略路由消息,执行意图识别和Agent交接 |
| Content-Type | application/json |
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| session_id | body | string | 是 | 会话ID,最长64 |
| user_id | body | string | 是 | 用户ID,最长64 |
| channel | body | string | 是 | 消息渠道,最长64 |
| query | body | string | 是 | 用户问题,1~5000字符 |
| mentioned_agent_code | body | string | 否 | @提及的Agent编码 |
| file_url | body | string | 否 | 文件URL |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| session_id | string | 会话ID |
| routing | object | 路由信息 |
| routing.agent_id | integer | Agent ID |
| routing.agent_code | string | Agent编码 |
| routing.agent_name | string | Agent名称 |
| routing.routing_reason | string | 路由原因:mention/inheritance/default |
| intent | object | 意图信息(mention时为null) |
| intent.intent | string | 意图名 |
| intent.confidence | float | 置信度 |
| handoff | object | 交接信息(同Agent或首次对话时为null) |
| handoff.from_agent_id | integer | 源Agent ID |
| handoff.to_agent_id | integer | 目标Agent ID |
| handoff.to_agent_name | string | 目标Agent名称 |
| handoff.handoff_message | string | 交接消息 |
| response_content | string | 回复内容 |
| created_at | string | 创建时间 |
**错误码**
| HTTP 状态码 | 触发条件 |
|-------------|----------|
| 400 | mentioned_agent不存在 / 管家Agent未配置 |
---
### 3.2 文件上传与文本提取
**基本信息**
| 字段 | 值 |
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/files/upload` |
| Content-Type | multipart/form-data |
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| session_id | form | string | 是 | 关联会话ID |
| file | form | file | 是 | 上传文件 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| file_url | string | 文件URL |
| file_name | string | 文件名 |
| file_size | integer | 文件大小 |
| extracted_text | string | 提取的文本(图片为null) |
| session_id | string | 会话ID |
**错误码**
| HTTP 状态码 | 触发条件 |
|-------------|----------|
| 400 | 不支持的文件格式 / 文件过大 |
---
## 4. 测试场景
### 4.1 路由决策
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | @mention路由到指定Agent | 正常 | agent_code="metric-agent", reason="mention" |
| 2 | 继承路由到当前Agent | 正常 | agent_code="metric-agent", reason="inheritance" |
| 3 | 默认路由到管家Agent | 正常 | agent_code="steward", reason="default" |
| 4 | @mention覆盖继承 | 正常 | reason="mention", agent_code="detail-agent" |
### 4.2 意图识别
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 查询类意图 | 正常 | intent="query-metric", confidence>0 |
| 2 | 未知意图归为general-qa | 正常 | intent="general-qa" |
| 3 | @mention跳过意图识别 | 正常 | intent=None |
### 4.3 Agent交接
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | Agent切换生成交接 | 正常 | handoff非null, 含from/to/handoff_message |
| 2 | 同Agent无交接 | 正常 | handoff=None |
| 3 | 首次对话无交接 | 正常 | handoff=None |
### 4.4 文件上传
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | PDF上传提取文本 | 正常 | extracted_text非空 |
| 2 | 不支持的格式 | 异常 | ValueError "不支持的文件格式" |
| 3 | 文件过大 | 异常 | ValueError "文件大小超过限制" |
| 4 | 图片上传无文本提取 | 正常 | extracted_text=None |
### 4.5 集成与异常
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 默认→mention完整流程 | 集成 | 先default后mention, 生成handoff |
| 2 | mentioned Agent不存在 | 异常 | ValueError "Agent不存在" |
| 3 | 管家Agent未配置 | 异常 | ValueError "管家Agent" |
---
## 5. 对应测试代码
测试文件:`backend/tests/test_routing_api.py`
| 测试类 | 测试方法 | 对应场景 |
|--------|----------|----------|
| TestRoutingDecision | test_mention_routes_to_mentioned_agent | 4.1-1 |
| TestRoutingDecision | test_inheritance_routes_to_current_agent | 4.1-2 |
| TestRoutingDecision | test_default_routes_to_steward | 4.1-3 |
| TestRoutingDecision | test_mention_overrides_inheritance | 4.1-4 |
| TestIntentRecognition | test_intent_recognized_for_query | 4.2-1 |
| TestIntentRecognition | test_intent_general_for_unknown_query | 4.2-2 |
| TestIntentRecognition | test_mention_skips_intent_recognition | 4.2-3 |
| TestHandoff | test_handoff_generated_on_agent_switch | 4.3-1 |
| TestHandoff | test_no_handoff_when_same_agent | 4.3-2 |
| TestHandoff | test_no_handoff_on_default_first_message | 4.3-3 |
| TestFileUpload | test_upload_and_extract_text | 4.4-1 |
| TestFileUpload | test_unsupported_format_returns_error | 4.4-2 |
| TestFileUpload | test_file_too_large_returns_error | 4.4-3 |
| TestFileUpload | test_upload_without_extraction | 4.4-4 |
| TestRoutingServiceIntegration | test_full_flow_default_then_mention | 4.5-1 |
| TestRoutingServiceIntegration | test_mentioned_agent_not_found | 4.5-2 |
| TestRoutingServiceIntegration | test_steward_agent_not_found | 4.5-3 |
# 接口测试文档 — sessions
---
## 1. 模块概览
| 字段 | 值 |
|------|-----|
| 模块名称 | sessions |
| 模块说明 | 会话管理 — 创建、追加入档、查询详情、上下文继承、归档 |
| 路由前缀 | `/api/v1/sessions` |
| 数据库表 | `sessions`, `conversation_history` |
| 外部依赖 | 无 |
---
## 2. 接口列表
| 序号 | 方法 | 路径 | 说明 |
|------|------|------|------|
| 1 | POST | `/api/v1/sessions` | 创建会话 |
| 2 | PUT | `/api/v1/sessions/{session_id}` | 追加对话并合并实体 |
| 3 | GET | `/api/v1/sessions/{session_id}` | 查询会话详情 |
| 4 | GET | `/api/v1/sessions/{session_id}/context` | 查询会话上下文 |
| 5 | POST | `/api/v1/sessions/{session_id}/archive` | 归档会话 |
---
## 3. 接口详细说明
### 3.1 创建会话
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| user_id | body | string | 是 | 用户ID,最长64 |
| channel | body | string | 是 | 渠道,最长64 |
| initial_query | body | string | 是 | 初始问题,1~5000字符 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| session_id | string | 会话ID |
| user_id | string | 用户ID |
| channel | string | 渠道 |
| current_agent_id | integer | 当前Agent ID |
| created_at | string | 创建时间 |
---
### 3.2 追加对话
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| session_id | path | string | 是 | 会话ID |
| role | body | string | 是 | 角色,最长32 |
| content | body | string | 是 | 内容,1~5000字符 |
| agent_id | body | integer | 是 | Agent ID |
| intent | body | string | 否 | 意图 |
| entities | body | object | 否 | 实体JSON |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| success | boolean | 是否成功 |
| updated_at | string | 更新时间 |
| turn_count | integer | 当前轮次 |
---
### 3.3 查询会话详情
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| session_id | string | 会话ID |
| user_id | string | 用户ID |
| channel | string | 渠道 |
| current_agent_id | integer | 当前Agent ID |
| current_agent_name | string | Agent名称 |
| conversation_history | array | 对话历史 |
| conversation_history[].role | string | 角色 |
| conversation_history[].content | string | 内容 |
| conversation_history[].agent_id | integer | Agent ID |
| conversation_history[].intent | string | 意图 |
| context_entities | object | 合并后的实体 |
---
### 3.4 查询会话上下文
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| session_id | string | 会话ID |
| current_agent_id | integer | 当前Agent ID |
| last_entities | object | 最近实体 |
| inheritance_valid | boolean | 继承是否有效 |
| expires_at | string | 过期时间 |
---
### 3.5 归档会话
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| success | boolean | 是否成功 |
| archived_at | string | 归档时间 |
---
## 4. 测试场景
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 创建→追加→详情→上下文 | 正常 | 创建201, 追加success+turn_count=1, 详情含history+entities, 上下文inheritance_valid=True |
| 2 | 归档会话 | 正常 | success=True, 归档后详情仍可读, 上下文inheritance_valid=False |
---
## 5. 对应测试代码
测试文件:`backend/tests/test_sessions_api.py`
| 测试类 | 测试方法 | 对应场景 |
|--------|----------|----------|
| TestSessionsApi | test_create_update_get_and_context | 1 |
| TestSessionsApi | test_archive_session | 2 |
# 接口测试文档 — skill-scanner
---
## 1. 模块概览
| 字段 | 值 |
|------|-----|
| 模块名称 | skill-scanner |
| 模块说明 | Skill目录扫描器 — 从文件系统SKILL.md读取技能配置并生成skills.json |
| 路由前缀 | 无(非HTTP接口,工具类) |
| 数据库表 | 无 |
| 外部依赖 | 文件系统 |
---
## 2. 组件列表
| 序号 | 函数/方法 | 说明 |
|------|-----------|------|
| 1 | `_parse_frontmatter(content)` | 解析SKILL.md的YAML frontmatter |
| 2 | `scan_skills(skills_dir)` | 扫描目录下所有SKILL.md,返回技能字典 |
| 3 | `update_skills_json(skills_dir, config_dir)` | 全量扫描并写入config/skills.json |
---
## 3. 组件详细说明
### 3.1 _parse_frontmatter
**输入**:SKILL.md 文件内容字符串
**输出**:`(meta: dict, body: str)` — frontmatter 字典 + 正文
**逻辑**:识别 `---` 分隔符,解析为 YAML 键值对;无 frontmatter 时返回 `({}, 原文)`
### 3.2 scan_skills
**输入**:`skills_dir: Path` — 技能根目录
**输出**:`dict[str, SkillConfig]` — 技能编码到配置的映射
**过滤规则**:
- 跳过无 SKILL.md 的子目录
- 跳过隐藏目录(`.` 开头)
- 空目录/不存在目录返回 `{}`
**SkillConfig 字段**:
| 字段 | 类型 | 说明 |
|------|------|------|
| name | string | 技能名称 |
| description | string | 描述 |
| instruction | string | SKILL.md 正文 |
| location | string | 相对路径(如 `skills/meeting_minutes`) |
### 3.3 update_skills_json
**输入**:`skills_dir: Path`, `config_dir: Path`
**输出**:写入 `config_dir/skills.json`
**JSON 结构**:
```json
{
"skills": {
"alpha": {
"code": "alpha",
"name": "alpha",
"location": "skills/alpha",
"instruction": "技能 alpha 的说明"
}
}
}
```
---
## 4. 测试场景
### 4.1 Frontmatter解析
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 解析有效frontmatter | meta含name/description, body含正文 |
| 2 | 无frontmatter | meta={}, body=原文 |
### 4.2 scan_skills
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 正常扫描2个技能 | 长度=2, 含meeting_minutes和support |
| 2 | 跳过无SKILL.md的目录 | 长度=1 |
| 3 | 跳过隐藏目录 | 长度=0 |
| 4 | 空目录 | 返回{} |
| 5 | 不存在的目录 | 返回{} |
### 4.3 update_skills_json
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 全量扫描并写入 | skills.json存在, 含2个技能, location/code/name/instruction正确 |
---
## 5. 对应测试代码
测试文件:`backend/tests/test_skill_scanner.py`
| 测试类 | 测试方法 | 对应场景 |
|--------|----------|----------|
| TestParseFrontmatter | test_parses_valid_frontmatter | 4.1-1 |
| TestParseFrontmatter | test_handles_missing_frontmatter | 4.1-2 |
| TestScanSkills | test_scan_skills_normal | 4.2-1 |
| TestScanSkills | test_skip_directory_without_skill_md | 4.2-2 |
| TestScanSkills | test_skip_hidden_directory | 4.2-3 |
| TestScanSkills | test_empty_skills_dir | 4.2-4 |
| TestScanSkills | test_nonexistent_dir | 4.2-5 |
| TestUpdateSkillsJson | test_full_scan_and_write | 4.3-1 |
# 接口测试文档 — skill
---
## 1. 模块概览
| 字段 | 值 |
|------|-----|
| 模块名称 | skill |
| 模块说明 | Skill目录 — 列表查询 + 详情查询 + Redis缓存 |
| 路由前缀 | `/api/v1/skills` |
| 数据库表 | `skills` |
| 外部依赖 | SkillCache(内存缓存) |
---
## 2. 接口列表
| 序号 | 方法 | 路径 | 说明 |
|------|------|------|------|
| 1 | GET | `/api/v1/skills` | 查询Skill列表 |
| 2 | GET | `/api/v1/skills/{skill_code}` | 查询Skill详情 |
---
## 3. 接口详细说明
### 3.1 查询Skill列表
**基本信息**
| 字段 | 值 |
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/skills` |
| 说明 | 返回所有Skill列表,按priority升序,列表项不含doc_markdown |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| list | array | Skill列表 |
| list[].skill_code | string | 技能编码 |
| list[].skill_name | string | 技能名称 |
| list[].description | string | 描述 |
---
### 3.2 查询Skill详情
**基本信息**
| 字段 | 值 |
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/skills/{skill_code}` |
| 说明 | 返回Skill详情,包含doc_markdown;支持缓存 |
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| skill_code | path | string | 是 | 技能编码 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| skill_code | string | 技能编码 |
| skill_name | string | 技能名称 |
| description | string | 描述 |
| doc_markdown | string | Markdown格式文档 |
**错误码**
| HTTP 状态码 | 触发条件 |
|-------------|----------|
| 404 | Skill不存在 |
---
## 4. 测试场景
### 4.1 Skill列表
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 返回所有Skill | 正常 | list长度=2 |
| 2 | 列表项字段验证 | 正常 | 含skill_code/skill_name/description,不含doc_markdown |
| 3 | 空列表 | 边界 | list=[] |
| 4 | 按priority排序 | 正常 | 高优先级在前 |
### 4.2 Skill详情
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 详情查询成功 | 正常 | 含doc_markdown |
| 2 | 不存在返回404 | 异常 | HTTP 404 |
| 3 | doc_markdown内容完整 | 正常 | markdown内容原样返回 |
### 4.3 缓存行为
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 缓存命中避免DB查询 | 正常 | 删除DB记录后仍返回缓存数据 |
| 2 | 缓存未命中查DB | 正常 | 返回DB最新数据 |
| 3 | 详情查询后缓存填充 | 正常 | 缓存中可读取到skill数据 |
### 4.4 服务层
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | Service层列表查询 | 正常 | 返回skill_code正确的列表 |
| 2 | Service层详情查询 | 正常 | 含doc_markdown |
| 3 | Service层不存在 | 异常 | ValueError "不存在" |
---
## 5. 对应测试代码
测试文件:`backend/tests/test_skill_api.py`
| 测试类 | 测试方法 | 对应场景 |
|--------|----------|----------|
| TestListSkills | test_list_returns_all_skills | 4.1-1 |
| TestListSkills | test_list_item_fields | 4.1-2 |
| TestListSkills | test_list_empty | 4.1-3 |
| TestListSkills | test_list_ordered_by_priority | 4.1-4 |
| TestGetSkillDetail | test_detail_success | 4.2-1 |
| TestGetSkillDetail | test_detail_not_found | 4.2-2 |
| TestGetSkillDetail | test_detail_contains_doc_markdown | 4.2-3 |
| TestSkillCacheBehavior | test_cache_hit_avoids_db_query | 4.3-1 |
| TestSkillCacheBehavior | test_cache_miss_fetches_from_db | 4.3-2 |
| TestServiceLayer | test_cache_is_populated_after_detail_fetch | 4.3-3 |
| TestServiceLayer | test_list_skills_service | 4.4-1 |
| TestServiceLayer | test_get_detail_service | 4.4-2 |
| TestServiceLayer | test_get_detail_service_not_found | 4.4-3 |
# 接口测试文档 — tool-manager
---
## 1. 模块概览
| 字段 | 值 |
|------|-----|
| 模块名称 | tool-manager |
| 模块说明 | 工具管理器 — 注册/调用工具,支持分组、激活/停用、OpenAI兼容Schema |
| 路由前缀 | 无(非HTTP接口,Service组件) |
| 数据库表 | 无 |
| 外部依赖 | 无 |
---
## 2. 组件列表
| 序号 | 方法 | 说明 |
|------|------|------|
| 1 | `register_tool(func, name, group, description)` | 注册工具函数 |
| 2 | `register(group)` | 装饰器方式注册 |
| 3 | `call_tool({"name": ..., "input": ...})` | 调用工具 |
| 4 | `get_tool_schemas()` | 获取激活工具的OpenAI兼容Schema |
| 5 | `reset_equipped_tools(**groups)` | 重置工具组激活状态 |
| 6 | `groups` | 工具组字典 |
---
## 3. 组件详细说明
### 3.1 工具注册
**方式一:函数调用**
```python
tm.register_tool(get_weather, name="custom", group="admin", description="自定义描述")
```
**方式二:装饰器**
```python
@tm.register(group="vision")
def analyze_image(image_url: str) -> str:
"""分析图片内容"""
...
```
**规则**:
- `basic` 组默认激活,其他组默认未激活
- 自动从函数签名生成 `input_schema`(OpenAI function calling 格式)
- 自动提取 docstring 作为 description
### 3.2 工具调用
**输入**:
```python
{"name": "add", "input": {"a": 1, "b": 2}}
```
**输出**:
- 成功:`{"result": 3}`
- 未注册:`{"error": "未注册..."}`
- 组未激活:`{"error": "未激活..."}`
- 执行异常:`{"error": "...boom..."}`
### 3.3 Schema生成
**格式**:OpenAI function calling 兼容
```json
{
"type": "function",
"function": {
"name": "search",
"description": "搜索知识库",
"parameters": {
"type": "object",
"properties": {"query": {"type": "string"}, "limit": {"type": "integer"}},
"required": ["query"]
}
}
}
```
**规则**:仅返回激活组(默认basic)的工具Schema
### 3.4 分组管理
- `basic` 组默认存在且激活
- `reset_equipped_tools(basic=False, vision=True)` 切换激活组
---
## 4. 测试场景
### 4.1 工具注册
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 函数注册 | 名称/description/group正确 |
| 2 | 自定义name/group/description | 覆盖默认值 |
| 3 | 装饰器注册 | group="vision"未激活, input_schema含参数 |
### 4.2 工具调用
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 调用成功 | {"result": 3} |
| 2 | 工具未注册 | {"error": "未注册"} |
| 3 | 组未激活 | {"error": "未激活"} |
| 4 | 执行异常 | {"error": 含"boom"} |
### 4.3 Schema生成
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 仅返回激活组 | 1个schema(basic组) |
| 2 | 空管理器 | [] |
| 3 | OpenAI兼容格式 | type/function/parameters结构正确 |
### 4.4 分组管理
| 序号 | 场景名称 | 预期结果 |
|------|----------|----------|
| 1 | 切换激活组 | reset后vision激活,basic停用 |
| 2 | 默认组 | basic存在且激活 |
---
## 5. 对应测试代码
测试文件:`backend/tests/test_tool_manager.py`
| 测试类 | 测试方法 | 对应场景 |
|--------|----------|----------|
| TestToolManagerRegister | test_register_function | 4.1-1 |
| TestToolManagerRegister | test_register_with_custom_name_and_group | 4.1-2 |
| TestToolManagerRegister | test_register_decorator | 4.1-3 |
| TestToolManagerCall | test_call_tool_success | 4.2-1 |
| TestToolManagerCall | test_call_tool_not_found | 4.2-2 |
| TestToolManagerCall | test_call_tool_inactive_group | 4.2-3 |
| TestToolManagerCall | test_call_tool_execution_error | 4.2-4 |
| TestToolManagerSchemas | test_get_tool_schemas_only_active_groups | 4.3-1 |
| TestToolManagerSchemas | test_get_tool_schemas_empty | 4.3-2 |
| TestToolManagerSchemas | test_schema_format_openai_compatible | 4.3-3 |
| TestToolManagerGroups | test_reset_equipped_tools | 4.4-1 |
| TestToolManagerGroups | test_default_groups | 4.4-2 |
# 接口测试文档 - wecom-sync
---
## 1. 模块概览
| 字段 | 值 |
|------|-----|
| 模块名称 | wecom-sync |
| 模块说明 | 企业微信机器人、联系人、群、消息同步与检查点查询 |
| 路由前缀 | `/api/v1/wecom-sync` |
| 数据库表 | `wecom_bots`, `wecom_contacts`, `wecom_groups`, `wecom_messages`, `wecom_sync_checkpoints` |
| 外部依赖 | Business API: `/api/v1/business/bots`, `/contacts`, `/groups`, `/messages` |
---
## 2. 接口列表
| 序号 | 方法 | 路径 | 说明 |
|------|------|------|------|
| 1 | POST | `/api/v1/wecom-sync/run` | 手动触发同步 |
| 2 | GET | `/api/v1/wecom-sync/checkpoints` | 分页查询同步检查点 |
---
## 3. 接口详细说明
### 3.1 手动触发同步
**基本信息**
| 字段 | 值 |
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/wecom-sync/run` |
| 说明 | 支持首次全量同步或后续增量同步 |
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| mode | body | string | 是 | `full` 或 `incremental` |
| bot_ids | body | string[] | 否 | 增量模式下指定机器人列表;不传时默认使用本地已同步机器人 |
| message_start_time | body | string | 否 | 消息同步起始时间,ISO 8601 |
| message_end_time | body | string | 否 | 消息同步结束时间,ISO 8601 |
**请求示例:全量同步**
```json
{
"mode": "full",
"message_start_time": "2026-05-21T09:00:00Z",
"message_end_time": "2026-05-21T10:00:00Z"
}
```
**请求示例:增量同步**
```json
{
"mode": "incremental",
"bot_ids": ["RBT001"],
"message_end_time": "2026-05-21T10:00:00Z"
}
```
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| code | integer | 统一响应码,成功为 200 |
| message | string | 固定为 `success` |
| data.mode | string | 本次执行模式 |
| data.bots | integer | 本次同步的机器人记录数 |
| data.contacts | integer | 本次同步的联系人记录数 |
| data.groups | integer | 本次同步的群记录数 |
| data.messages | integer | 本次同步的消息记录数 |
| data.triggered_at | string | 触发时间 |
**成功响应示例**
```json
{
"code": 200,
"message": "success",
"data": {
"mode": "full",
"bots": 1,
"contacts": 12,
"groups": 8,
"messages": 156,
"triggered_at": "2026-05-21T16:30:00Z"
}
}
```
**错误码**
| HTTP / Code | 场景 | 说明 |
|-------------|------|------|
| 400 | 请求参数错误 | `mode` 非法或时间参数格式错误 |
| 503 | 外部 Business API 不可用 | 拉取外部数据失败 |
---
### 3.2 查询同步检查点
**基本信息**
| 字段 | 值 |
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/wecom-sync/checkpoints` |
| 说明 | 分页查看机器人、联系人、群、消息各类同步检查点 |
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
|--------|------|------|------|------|
| page | query | integer | 否 | 页码,默认 1 |
| page_size | query | integer | 否 | 每页数量,默认 20,最大 100 |
**响应参数**
| 字段路径 | 类型 | 说明 |
|----------|------|------|
| code | integer | 统一响应码 |
| message | string | 固定为 `success` |
| data.total | integer | 检查点总数 |
| data.page | integer | 当前页 |
| data.page_size | integer | 每页数量 |
| data.list[].resource_type | string | 资源类型:`bots` / `contacts` / `groups` / `messages` |
| data.list[].scope_key | string | 范围键,例如 `global`、`bot:wt_ww:RBT001` |
| data.list[].last_sync_time | string | 最近同步时间 |
| data.list[].last_external_id | string | 最近同步到的外部主键 |
| data.list[].last_status | string | 最近同步状态 |
| data.list[].last_error | string | 最近错误信息 |
| data.list[].last_started_at | string | 最近启动时间 |
| data.list[].last_finished_at | string | 最近完成时间 |
**成功响应示例**
```json
{
"code": 200,
"message": "success",
"data": {
"total": 1,
"page": 1,
"page_size": 20,
"list": [
{
"resource_type": "messages",
"scope_key": "bot:wt_ww:RBT001",
"last_sync_time": "2026-05-21T09:03:00Z",
"last_external_id": "msg_003",
"last_status": "success",
"last_error": null,
"last_started_at": "2026-05-21T16:29:58Z",
"last_finished_at": "2026-05-21T16:30:00Z"
}
]
}
}
```
---
## 4. 测试场景
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------|
| 1 | 手动触发全量同步 | 正常 | 返回统一结构,`mode=full`,并返回各资源同步数量 |
| 2 | 手动触发增量同步且未传 bot_ids | 正常 | 自动读取本地机器人列表并执行增量消息同步 |
| 3 | 查询同步检查点分页列表 | 正常 | 返回分页结构,包含 `resource_type`、`scope_key`、`last_sync_time` 等字段 |
---
## 5. 对应测试代码
测试文件:`backend/tests/test_wecom_sync_api.py`、`backend/tests/test_wecom_sync_service.py`
| 测试类/文件 | 测试方法 | 对应场景 |
|------------|----------|----------|
| test_wecom_sync_api.py | `test_run_full_sync_returns_wrapped_response` | 1 |
| test_wecom_sync_api.py | `test_run_incremental_sync_uses_existing_bots_when_bot_ids_missing` | 2 |
| test_wecom_sync_api.py | `test_list_checkpoints_returns_paginated_data` | 3 |
| test_wecom_sync_service.py | `test_full_sync_persists_resources_and_dispatches_non_bot_messages` | 同步服务全链路 |
| test_wecom_sync_service.py | `test_incremental_sync_uses_time_and_msg_id_boundary_without_duplicates` | 增量边界 |
| test_wecom_sync_service.py | `test_dispatch_failure_marks_message_failed_without_losing_payload` | 分发失败不丢原始消息 |
CREATE TABLE IF NOT EXISTS wecom_bots (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel VARCHAR(64) NOT NULL,
bot_id VARCHAR(128) NOT NULL,
bot_code VARCHAR(191) NOT NULL UNIQUE,
bot_name VARCHAR(255) NOT NULL,
corp_name VARCHAR(255),
online BOOLEAN,
status VARCHAR(64),
config JSON,
queue_count INTEGER,
pending_count INTEGER,
last_active DATETIME,
last_fail DATETIME,
external_created_at DATETIME,
external_updated_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
);
CREATE TABLE IF NOT EXISTS wecom_contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
bot_code VARCHAR(191) NOT NULL,
channel VARCHAR(64) NOT NULL,
bot_id VARCHAR(128) NOT NULL,
contact_id VARCHAR(191) NOT NULL,
contact_type VARCHAR(64),
account_type VARCHAR(64),
contact_name VARCHAR(255) NOT NULL,
contact_remark VARCHAR(255),
display_name VARCHAR(255),
avatar_url VARCHAR(500),
status VARCHAR(64),
extra JSON,
last_active DATETIME,
last_fail DATETIME,
external_created_at DATETIME,
external_updated_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
CONSTRAINT uk_wecom_contact_bot_contact UNIQUE (bot_code, contact_id)
);
CREATE TABLE IF NOT EXISTS wecom_groups (
id INTEGER PRIMARY KEY AUTOINCREMENT,
bot_code VARCHAR(191) NOT NULL,
channel VARCHAR(64) NOT NULL,
bot_id VARCHAR(128) NOT NULL,
group_id VARCHAR(191) NOT NULL,
group_name VARCHAR(255) NOT NULL,
group_type VARCHAR(64),
avatar_url VARCHAR(500),
status VARCHAR(64),
extra JSON,
last_active DATETIME,
external_created_at DATETIME,
external_updated_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
CONSTRAINT uk_wecom_group_bot_group UNIQUE (bot_code, group_id)
);
CREATE TABLE IF NOT EXISTS wecom_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
bot_code VARCHAR(191) NOT NULL,
channel VARCHAR(64) NOT NULL,
bot_id VARCHAR(128) NOT NULL,
msg_id VARCHAR(191) NOT NULL,
msg_time DATETIME NOT NULL,
msg_type VARCHAR(64),
msg_content TEXT,
sender_id VARCHAR(191),
sender_name VARCHAR(255),
contact_id VARCHAR(191),
session_title VARCHAR(255),
bot_send BOOLEAN NOT NULL DEFAULT 0,
payload JSON NOT NULL,
dispatch_status VARCHAR(32),
dispatch_error TEXT,
dispatch_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
CONSTRAINT uk_wecom_message_bot_msg UNIQUE (bot_code, msg_id)
);
CREATE TABLE IF NOT EXISTS wecom_sync_checkpoints (
id INTEGER PRIMARY KEY AUTOINCREMENT,
resource_type VARCHAR(32) NOT NULL,
scope_key VARCHAR(191) NOT NULL,
last_sync_time DATETIME,
last_external_id VARCHAR(191),
last_sync_cursor VARCHAR(191),
last_status VARCHAR(32),
last_error TEXT,
last_started_at DATETIME,
last_finished_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
CONSTRAINT uk_wecom_sync_checkpoint_scope UNIQUE (resource_type, scope_key)
);
## Context ## Context
当前项目需要为管理员提供一套完整的 Agent 生命周期管理功能。后端采用 FastAPI + SQLAlchemy 2.0,数据库为 MySQL 8.0。 当前后端需要提供 Agent 的基础管理能力,包括创建、更新、删除、详情、列表与状态更新。实现基于 FastAPI + SQLAlchemy,创建接口需要由后端自动生成业务编码,详情接口需要聚合岗位、技能和会话统计。
## Goals / Non-Goals ## Goals / Non-Goals
**Goals:** **Goals**
- 实现 Agent 的增删改查及状态切换接口。 - 提供完整的 Agent CRUD 与状态管理接口
- 确保 Agent 编码的全局唯一性。 - 统一使用 `{code, message, data}` 响应结构
- 维护 Agent 与岗位、Skill 的关联关系。 - 列表接口遵循统一分页格式
- 实现安全删除逻辑(软删除及引用校验)。 - 创建接口自动生成唯一 `code`
- Agent 详情接口返回完整展示数据
**Non-Goals:** **Non-Goals**
- 不涉及 Skill 本身的定义管理(属于 Skill 目录功能)。 - 当前阶段不实现 Agent 编辑并发锁定
- 不涉及具体的 AI 会话实现逻辑。 - 当前阶段不扩展列表接口为重详情结构
- 当前阶段不让前端自定义 Agent 编码
## Decisions ## Decisions
### 1. 数据库模型设计 ### 1. 数据模型
- **Agent 表**: 存储基本信息(name, code, description, status, is_deleted, version 等)。 - `ai_agents` 存储 Agent 主体信息:`name`、`code`、`description`、`status`、`is_deleted`、`version`
- **关联表**: 使用 `agent_positions` 和 `agent_skills` 存储多对多关系。 - `ai_agent_positions` 存储 Agent 与岗位标签的关联
- **乐观锁**: 在 `agents` 表中引入 `version` 字段,用于编辑接口的并发控制。 - `ai_agent_skills` 存储 Agent 与技能的关联
### 2. 软删除策略 ### 2. 自动编码策略
- 使用 `is_deleted` (boolean) 和 `deleted_at` (datetime) 字段。 - 创建接口请求体不再接收 `code`
- 删除前校验 `session` 和 `route` 表的引用情况,若存在引用则拒绝删除并返回 409。 - 后端在创建时生成 `agent_<8位随机十六进制串>`
- 写入前查询现有未删除 Agent,若冲突则重试
### 3. 状态管理与缓存 ### 3. 删除策略
- Agent 状态切换时,需要使 `agent:status:{agent_id}` 的 Redis 缓存失效(如果后续引入缓存层)。 - Agent 使用软删除
- 状态变更需触发对路由层的通知机制。 - 删除接口返回 `success` 和 `deleted_at`
### 4. 列表与详情分离
- 列表接口保持轻量,仅返回基础信息、岗位 ID 列表和技能编码列表
- 详情接口返回完整结构,用于详情页和 Swagger 调试
### 5. 详情聚合策略
- `positions` 从 `position_tags` 表补齐 `{id, name}`
- `skills` 从 `skills` 表补齐 `{skill_code, skill_name}`
- `session_count` 统计 `sessions.current_agent_id = agent_id` 的全部会话数
- `status`、`description`、`created_at`、`updated_at` 直接来自 Agent 主表
## Risks / Trade-offs ## Risks / Trade-offs
- **[Risk] 并发更新导致数据不一致** → **Mitigation**: 使用 SQLAlchemy 的乐观锁机制(version 字段)。 - **并发更新可能被后写覆盖**
- **[Risk] 软删除后的编码冲突** → **Mitigation**: 唯一索引需包含 `is_deleted` 字段,或在创建校验逻辑中显式检查未删除的记录。 当前不做乐观锁拦截,后续如进入多人高频协作场景,再评估恢复版本校验或改为显式锁定机制。
- **详情接口查询更重**
通过保持列表接口轻量化,把额外聚合成本收敛在单条详情接口上。
- **自动编码不可读性一般**
当前优先保证稳定唯一和实现简单,如后续需要更强业务语义,再评估引入前缀映射规则。
## ADDED Requirements ## ADDED Requirements
### Requirement: 创建 Agent ### Requirement: 创建 Agent
管理员 SHALL 能够通过 API 创建新的 Agent。系统 MUST 校验编码唯一性,并确保关联的岗位和 Skill 存在。 系统 SHALL 提供创建 Agent 的接口,并由后端自动生成唯一编码。
**接口参数**:
- `name`: 字符串,最多 50 字
- `code`: 字符串,英文 + 下划线,全局唯一
- `position_ids`: 整数列表,关联岗位 ID
- `skill_codes`: 字符串列表,Skill 编码列表(至少选 1 个)
- `description`: 字符串,最多 500 字
- `status`: 枚举 `enable`/`disable`,默认 `enable`
#### Scenario: 成功创建 Agent
- **WHEN** 提供有效的名称、唯一的编码、存在的岗位 ID 列表和有效的 Skill 编码列表
- **THEN** 系统创建 Agent 记录及关联关系,并返回新创建的 Agent ID
#### Scenario: 编码冲突导致创建失败
- **WHEN** 提供的编码已存在于未删除的 Agent 中
- **THEN** 系统返回 409 冲突错误
### Requirement: 编辑 Agent
管理员 SHALL 能够修改现有 Agent 的信息。系统 MUST 禁止修改 Agent 编码,并支持全量替换关联的岗位和 Skill。
**接口参数**:
- `name`: 字符串,最多 50 字
- `position_ids`: 整数列表,全量替换
- `skill_codes`: 字符串列表,全量替换
- `description`: 字符串,最多 500 字
- `status`: 枚举 `enable`/`disable`
- `version`: 整数,用于乐观锁并发控制
#### Scenario: 成功更新 Agent
- **WHEN** 修改名称、岗位列表或 Skill 列表,且版本号匹配
- **THEN** 系统更新 Agent 记录并重置关联关系,返回成功状态
#### Scenario: 并发更新冲突
- **WHEN** 提供的版本号与数据库中当前版本号不一致
- **THEN** 系统返回 409 冲突或 412 前提条件失败错误
### Requirement: 删除 Agent #### Scenario: 创建成功
管理员 SHALL 能够删除不再使用的 Agent。系统 MUST 采用软删除方式,并在执行前校验引用关系。 - **WHEN** 请求提供合法的 `name`、`position_ids`、`skill_codes`、`description`、`status`
- **THEN** 系统创建 Agent 并返回统一成功响应
- **AND** `data.code` 由后端自动生成
#### Scenario: 成功软删除 #### Scenario: 自动编码规则
- **WHEN** Agent 未被会话或路由配置引用 - **WHEN** 系统创建 Agent
- **THEN** 系统设置 `is_deleted=true` 并记录删除时间 - **THEN** 自动生成的 `code` 使用固定前缀 `agent_`
- **AND** 后缀为随机字符串
- **AND** 最终写入前必须校验与现有未删除 Agent 编码不重复
#### Scenario: 存在引用无法删除 ### Requirement: 更新 Agent
- **WHEN** Agent 仍被活跃会话引用 系统 SHALL 提供更新 Agent 的接口,用于修改名称、描述、状态、岗位关联和技能关联。
- **THEN** 系统拒绝删除并返回 409 错误,提示引用详情
### Requirement: 查询 Agent 列表 #### Scenario: 更新成功
系统 SHALL 提供 Agent 列表查询接口,支持分页、模糊搜索和条件筛选。 - **WHEN** 请求提供合法的 `name`、`position_ids`、`skill_codes`、`description`、`status`
- **THEN** 系统更新目标 Agent,并返回统一成功响应
**查询参数**: #### Scenario: 更新不存在的 Agent
- `page`: 页码 - **WHEN** 请求中的 `agent_id` 不存在或已软删除
- `page_size`: 每页数量 - **THEN** 系统返回 404 错误响应
- `keyword`: 模糊搜索(匹配名称/编码)
- `position_id`: 按岗位筛选
- `status`: 状态筛选 (`enable`/`disable`)
#### Scenario: 关键词搜索 ### Requirement: 删除 Agent
- **WHEN** 提供 `keyword` 参数 系统 SHALL 提供软删除 Agent 的接口。
- **THEN** 返回名称或编码匹配该关键词的 Agent 列表
#### Scenario: 删除成功
- **WHEN** 请求中的 `agent_id` 存在
- **THEN** 系统将记录标记为软删除,并返回统一成功响应,`data` 中包含 `success` 和 `deleted_at`
### Requirement: 查询 Agent 详情 ### Requirement: 查询 Agent 详情
系统 SHALL 返回指定 Agent 的完整信息,包括关联的岗位详情和 Skill 列表。 系统 SHALL 提供查询单个 Agent 详情的接口,并返回完整展示信息。
#### Scenario: 查询成功
- **WHEN** 请求中的 `agent_id` 存在
- **THEN** 系统返回统一成功响应,`data` 中包含 `agent_id`、`name`、`code`、`description`、`positions`、`skills`、`status`、`session_count`、`created_at`、`updated_at`
#### Scenario: 详情中的岗位和技能信息
- **WHEN** Agent 已关联岗位和技能
- **THEN** `positions` 返回 `{id, name}` 列表,`skills` 返回 `{skill_code, skill_name}` 列表
#### Scenario: 详情中的会话统计
- **WHEN** Agent 已关联会话
- **THEN** `session_count` 返回该 Agent 的全部会话总数
### Requirement: 查询 Agent 列表
系统 SHALL 提供 Agent 列表接口,并支持分页和筛选。
#### Scenario: 获取完整详情 #### Scenario: 分页查询
- **WHEN** 提供有效的 Agent ID - **WHEN** 请求提供 `page`、`page_size`
- **THEN** 返回包含岗位名称、Skill 名称、状态、会话统计及更新时间的完整 JSON 数据 - **THEN** 系统返回统一成功响应,`data` 中包含 `total`、`page`、`page_size`、`list`
### Requirement: 启用/停用 Agent #### Scenario: 条件筛选
管理员 SHALL 能够快速切换 Agent 的启用状态。 - **WHEN** 请求提供 `keyword`、`position_id` 或 `status`
- **THEN** 系统按条件过滤返回结果
**请求参数**: ### Requirement: 更新 Agent 状态
- `status`: 枚举 `enable`/`disable` 系统 SHALL 提供单独的 Agent 状态更新接口。
- `reason`: 字符串,变更原因
#### Scenario: 停用 Agent #### Scenario: 状态更新成功
- **WHEN** 将状态设置为 `disable` - **WHEN** 请求提供合法的 `status`
- **THEN** 系统更新状态,并使相关缓存失效,通知路由层停止分发请求 - **THEN** 系统更新 Agent 状态,并返回统一成功响应
## 1. 数据库准备 ## 1. 数据库准备
- [x] 1.1 创建 `agents` 表的迁移脚本,包含 `is_deleted` 和 `version` 字段 - [x] 1.1 创建 `agents` 表迁移,包含 `is_deleted` 和 `version` 字段
- [x] 1.2 创建 `agent_positions` 和 `agent_skills` 关联表的迁移脚本 - [x] 1.2 创建 `agent_positions` 和 `agent_skills` 关联表迁移
- [ ] 1.3 运行迁移脚本并验证表结构 - [ ] 1.3 补充索引与约束校验
## 2. 模型与数据层 (Model & Schema) ## 2. 模型与 Schema
- [x] 2.1 定义 SQLAlchemy ORM 模型 `Agent`, `AgentPosition`, `AgentSkill` - [x] 2.1 实现 SQLAlchemy ORM:`Agent`、`AgentPosition`、`AgentSkill`
- [x] 2.2 定义 Pydantic 请求模型 (Create/Update DTO) - [x] 2.2 实现创建/更新请求 Schema
- [x] 2.3 定义 Pydantic 响应模型 (List/Detail DTO) - [x] 2.3 实现列表/详情响应 Schema
## 3. 业务逻辑层 (Service Layer) ## 3. 服务层
- [x] 3.1 实现 Agent 创建逻辑,包含编码唯一性和关联校验 - [x] 3.1 实现 Agent 创建逻辑,创建时自动生成唯一 `code`
- [x] 3.2 实现 Agent 编辑逻辑,支持乐观锁和全量替换关联关系 - [x] 3.2 实现 Agent 编辑逻辑,支持全量替换岗位与技能关联
- [x] 3.3 实现 Agent 软删除逻辑(当前未包含会话/路由引用检查,待相关模块实现后补充) - [x] 3.3 实现 Agent 软删除逻辑
- [x] 3.4 实现列表查询逻辑,支持关键词搜索和条件过滤 - [x] 3.4 实现 Agent 列表查询逻辑,支持分页和条件筛选
- [x] 3.5 实现状态切换逻辑(缓存失效和路由通知待相关基础设施就绪后补充) - [x] 3.5 实现 Agent 状态更新逻辑
- [x] 3.6 实现 Agent 详情聚合逻辑,返回岗位名称、技能名称和全部会话总数
## 4. 接口层 (API Layer) ## 4. API 层
- [x] 4.1 挂载 `POST /api/v1/agents` 创建接口 - [x] 4.1 挂载 `POST /api/v1/agents` 创建接口
- 请求参数:`name`(50字), `code`(唯一), `position_ids`([]), `skill_codes`([]), `description`(500字), `status`(`enable`/`disable`) - 请求参数:`name`、`description`、`position_ids`、`skill_codes`、`status`
- [x] 4.2 挂载 `PUT /api/v1/agents/{agent_id}` 编辑接口 - 响应中的 `code` 由后端自动生成
- 请求参数:`name`, `position_ids`, `skill_codes`, `description`, `status` (code 不可改,带 version 乐观锁) - [x] 4.2 挂载 `PUT /api/v1/agents/{agent_id}` 更新接口
- [x] 4.3 挂载 `DELETE /api/v1/agents/{agent_id}` 删除接口 - [x] 4.3 挂载 `DELETE /api/v1/agents/{agent_id}` 删除接口
- 当前实现:软删除(设置 is_deleted=true + deleted_at),引用检查待会话/路由模块就绪后补充
- [x] 4.4 挂载 `GET /api/v1/agents` 列表接口 - [x] 4.4 挂载 `GET /api/v1/agents` 列表接口
- 查询参数:`page`, `page_size`, `keyword`, `position_id`, `status`
- [x] 4.5 挂载 `GET /api/v1/agents/{agent_id}` 详情接口 - [x] 4.5 挂载 `GET /api/v1/agents/{agent_id}` 详情接口
- 当前响应:包含基础信息、岗位 ID 列表、Skill 编码列表;会话统计待相关模块实现后补充 - 返回:`agent_id`、`name`、`code`、`description`、`positions`、`skills`、`status`、`session_count`、`created_at`、`updated_at`
- [x] 4.6 挂载 `PUT /api/v1/agents/{agent_id}/status` 状态管理接口 - [x] 4.6 挂载 `PUT /api/v1/agents/{agent_id}/status` 状态接口
- 请求参数:`status`, `reason`
## 5. 测试与验证 ## 5. 测试
- [x] 5.1 编写 Agent 创建与唯一性校验的单元测试 - [x] 5.1 创建接口测试
- [x] 5.2 编写编辑接口及并发冲突的单元测试 - [x] 5.2 更新接口测试
- [x] 5.3 编写删除逻辑的单元测试(引用限制测试待会话模块实现后补充) - [x] 5.3 删除接口测试
- [x] 5.4 运行所有测试并确保通过 - [x] 5.4 列表接口测试
- [x] 5.5 详情接口测试
- [x] 5.6 状态接口测试
## Overview
本次变更在 `workspace/agent-admin/backend` 引入统一响应层,对现有业务接口进行一次性收敛,并将该规范作为后续新增接口的默认约束。
设计目标:
1. 不改变业务 `data` 的语义,只在外层统一包装。
2. 保留真实 HTTP 状态码,同时在响应体中写入相同的 `code`。
3. 让后续新增接口默认继承规范,避免再次逐接口重复实现。
4. 为文件流、下载等非 JSON 场景保留明确豁免边界。
## Response Model Design
### Success Response
普通 JSON 成功响应统一为:
```json
{
"code": 200,
"message": "success",
"data": { }
}
```
说明:
- `code` 取实际 HTTP 状态码。
- `message` 成功场景统一为 `"success"`。
- `data` 放原始业务内容。
- 创建类接口若 HTTP 状态码为 `201`,则响应体 `code` 也应为 `201`。
### Error Response
普通 JSON 错误响应统一为:
```json
{
"code": 400,
"message": "参数校验失败:employee_id 不能为空",
"data": null
}
```
说明:
- `code` 取实际 HTTP 状态码。
- `message` 为可直接展示或记录的错误说明。
- `data` 固定为 `null`。
## Pagination Design
所有列表接口继续统一使用:
- `page`: 默认 1
- `page_size`: 默认 20,最大 100
所有分页列表接口统一返回:
```json
{
"code": 200,
"message": "success",
"data": {
"total": 156,
"page": 1,
"page_size": 20,
"list": []
}
}
```
说明:
- `total/page/page_size/list` 必须位于 `data` 内部。
- 原先只返回 `total/list` 的接口,需要补齐 `page/page_size`。
- 非分页读取接口不强行增加 `page/page_size` 字段。
## Implementation Strategy
### 1. Global Wrapper
在应用入口增加统一响应包装层,负责将普通 JSON 成功响应包装为 `{code,message,data}`。
适用范围:
- 返回字典、Pydantic 模型、列表、分页对象的普通 JSON 接口。
不适用范围:
- 文件流
- 二进制响应
- 明确返回原始 `Response` 的特殊场景
### 2. Global Exception Handling
在应用入口增加统一异常处理:
- `HTTPException`
- `RequestValidationError`
- 未捕获异常
统一输出错误结构 `{code,message,data:null}`。
### 3. Pagination Contract Normalization
逐个修正当前列表接口的返回模型和实现,确保分页数据落到:
- `data.total`
- `data.page`
- `data.page_size`
- `data.list`
### 4. Test and Documentation Alignment
同步修改:
- `tests/` 中所有受影响接口的成功/失败断言
- `docs/wangxz/` 中所有响应示例、字段说明、测试预期
## Special Cases
以下响应允许不走统一 JSON 包装,但必须显式保留:
- 文件上传后若返回 JSON 结果,仍需包装
- 文件下载、流式响应、非 JSON 媒体类型可豁免
- `/health` 这类基础健康检查接口可按实现需要决定是否纳入本次范围;若纳入,则也应统一包装
## Risks
### Existing Tests Break Broadly
这是一次横切全项目接口层的行为变更,短期内会导致大量测试断言失效,需要集中更新。
### Swagger Schema Drift
如果仅运行时包装而不调整响应模型声明,OpenAPI 文档会与真实返回不一致,因此需要同步调整 schema 或统一响应模型定义。
### Special Response Regression
若统一包装层未正确排除文件流或原始 `Response`,可能破坏上传下载等接口行为,因此必须在测试中覆盖这些场景。
## Why
当前 `workspace/agent-admin/backend` 各接口返回结构不一致:
- 大部分成功响应直接返回业务对象,没有统一的 `code/message/data` 外层。
- 错误响应主要依赖 FastAPI 默认 `HTTPException` 结构,不符合项目统一约定。
- 列表接口虽然大多已使用 `page`、`page_size` 请求参数,但返回体不统一,部分仅返回 `total/list`,缺少 `page/page_size`。
- `tests/` 与 `docs/wangxz/` 也都是基于当前“裸业务响应”编写,无法作为统一接口契约长期复用。
这会导致前端接入、测试断言、文档维护和后续新增接口实现都缺少一致标准。
## What Changes
- 新增后端统一响应规范:
- 成功响应统一为 `{code, message, data}`。
- 错误响应统一为 `{code, message, data: null}`。
- 新增后端统一分页规范:
- 所有列表接口统一使用 `page`、`page_size` 请求参数。
- 所有分页响应统一将 `total/page/page_size/list` 放入 `data`。
- 明确特殊响应边界:
- 普通 JSON 接口必须自动套用统一响应结构。
- 文件流、二进制下载等非 JSON 响应允许豁免,但需要显式定义。
- 同步更新:
- 后端接口实现
- `tests/` 目录下相关测试
- `docs/wangxz/` 下测试文档示例与断言说明
## Capabilities
### New Capabilities
- `backend-unified-api-response`: 为 agent-admin backend 提供统一 JSON 响应包装和统一分页契约。
### Modified Capabilities
- `agent-management`
- `agent-group-helper`
- `session-management`
- `routing-intent`
- `logging-analytics`
- `position-tag-management`
- `skill-catalog`
- `qrcode-channel-management`
- `one-customer-one-group`
- `official-site-tab-management`
- `official-site-agent-display`
- `official-site-upload`
- `official-site-home`
- `official-site-methodology`
## Impact
- **API 行为变更**:所有现有 JSON 接口的成功与失败响应结构将统一变化。
- **测试变更**:现有接口测试断言需要改为校验外层 `code/message/data`。
- **文档变更**:`docs/wangxz/` 中所有返回示例与预期结果需要按统一结构重写。
- **后续约束**:此变更完成后,backend 新增接口默认必须遵循该规范。
## ADDED Requirements
### Requirement: 统一成功响应包装
系统 SHALL 为 agent-admin backend 的普通 JSON 成功响应统一返回以下结构:
```json
{
"code": 200,
"message": "success",
"data": {}
}
```
说明:
- `data` 必须承载原始业务响应内容。
- `code` 必须等于实际 HTTP 状态码。
- `message` 在成功场景固定为 `"success"`。
#### Scenario: 查询详情接口返回统一成功结构
- **WHEN** 客户端调用任意普通 JSON 详情接口且请求成功
- **THEN** 响应体顶层必须包含 `code`、`message`、`data`
- **AND** `message` 必须为 `"success"`
- **AND** 原始业务字段必须位于 `data` 内
#### Scenario: 创建接口返回 201 成功结构
- **WHEN** 客户端调用创建类接口且资源创建成功
- **THEN** HTTP 状态码必须为 `201`
- **AND** 响应体 `code` 必须为 `201`
- **AND** 响应体 `data` 必须包含原始创建结果
### Requirement: 统一错误响应包装
系统 SHALL 为 agent-admin backend 的普通 JSON 错误响应统一返回以下结构:
```json
{
"code": 400,
"message": "参数校验失败:employee_id 不能为空",
"data": null
}
```
说明:
- `code` 必须等于实际 HTTP 状态码。
- `message` 必须提供可读错误说明。
- `data` 必须固定为 `null`。
#### Scenario: 业务校验错误返回统一结构
- **WHEN** 接口因业务校验失败返回 400、404、409 等错误
- **THEN** 响应体必须包含 `code`、`message`、`data`
- **AND** `code` 必须等于对应 HTTP 状态码
- **AND** `data` 必须为 `null`
#### Scenario: 请求参数校验失败返回统一结构
- **WHEN** 请求参数不合法导致校验失败
- **THEN** 响应体必须返回统一错误结构
- **AND** `message` 必须说明参数校验失败原因
#### Scenario: 未捕获异常返回统一结构
- **WHEN** 服务端发生未捕获异常
- **THEN** 响应体必须返回统一错误结构
- **AND** `code` 必须为 `500`
- **AND** `data` 必须为 `null`
### Requirement: 统一分页请求参数
系统 SHALL 对所有分页列表接口统一使用以下请求参数:
- `page`: 页码,默认 1
- `page_size`: 每页数量,默认 20,最大 100
#### Scenario: 客户端未传分页参数
- **WHEN** 客户端调用分页列表接口且未显式传入 `page`、`page_size`
- **THEN** 系统必须按 `page=1`、`page_size=20` 处理
#### Scenario: 客户端传入超限 page_size
- **WHEN** 客户端调用分页列表接口且 `page_size > 100`
- **THEN** 系统必须拒绝该请求并返回统一错误结构
### Requirement: 统一分页响应结构
系统 SHALL 对所有分页列表接口统一返回以下结构:
```json
{
"code": 200,
"message": "success",
"data": {
"total": 156,
"page": 1,
"page_size": 20,
"list": []
}
}
```
说明:
- `total/page/page_size/list` 必须位于 `data` 内。
- `list` 可以为空数组,但字段不得省略。
#### Scenario: 分页列表成功返回
- **WHEN** 客户端调用任意分页列表接口成功
- **THEN** 响应体必须返回统一成功结构
- **AND** `data` 中必须包含 `total`、`page`、`page_size`、`list`
#### Scenario: 分页列表为空
- **WHEN** 客户端调用分页列表接口且无匹配数据
- **THEN** 响应体 `data.total` 必须为 `0`
- **AND** `data.list` 必须为 `[]`
- **AND** `data.page`、`data.page_size` 必须仍然返回
### Requirement: 特殊响应豁免边界
系统 SHALL 允许非 JSON 响应不使用统一包装,但必须显式识别为特殊响应类型。
#### Scenario: 文件下载响应豁免统一包装
- **WHEN** 接口返回文件流、二进制内容或其他非 JSON 响应
- **THEN** 系统 MAY 不对响应体追加 `{code,message,data}` 包装
- **AND** 不得因此破坏原始响应媒体类型与内容
#### Scenario: 文件上传后的 JSON 结果仍使用统一包装
- **WHEN** 接口处理上传请求但最终返回 JSON 结果
- **THEN** 该返回结果仍必须使用统一成功或错误结构
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!