Commit ff267171 by imwangxiaozhou

feat: 新增Agent企微员工绑定功能,优化数据库与接口

本次提交包含以下核心变更:
- 新增ai_agent_users与position_tag_users关联表,完善企微员工与Agent、岗位标签的绑定关系
- 在ai_agents表新增managed_user_id字段,支持单个托管员工绑定
- 重构qrcode_channels表结构,移除废弃字段并新增唯一约束,优化活码绑定逻辑
- 移除方法论服务的步骤数量限制,简化校验规则
- 统一API响应格式,完善接口文档与Pydantic Schema定义
- 新增员工挂载查询API与多组数据库迁移脚本
- 新增临时调试工具脚本,修正现有文档示例错误
1 parent f8db9a5e
Showing 63 changed files with 3752 additions and 2574 deletions
File mode changed
import sqlite3
conn = sqlite3.connect("dev.db")
cur = conn.cursor()
cur.execute("SELECT id, agent_id, position_id, created_at FROM ai_agent_positions WHERE id = ?", (10,))
before = cur.fetchall()
print("BEFORE:", before)
cur.execute("DELETE FROM ai_agent_positions WHERE id = ?", (10,))
print("rows_deleted:", cur.rowcount)
conn.commit()
cur.execute("SELECT id, agent_id, position_id, created_at FROM ai_agent_positions WHERE id = ?", (10,))
after = cur.fetchall()
print("AFTER:", after)
conn.close()
......@@ -2,8 +2,8 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.infrastructure.database import get_db
from app.schema.common import ApiResponse
from app.schema.agent_group import EmployeeQrcodesResponse, PositionEmployeesResponse
from app.schema.common import ApiResponse, success_response_payload
from app.schema.agent_group import EmployeeMountsResponse, EmployeeQrcodesResponse, PositionEmployeesResponse
from app.service.agent_group_helper_service import (
AgentGroupHelperService,
PositionNotFoundError,
......@@ -29,7 +29,10 @@ def get_position_employees(
):
svc = AgentGroupHelperService(db, wecom_client)
try:
return svc.list_position_employees(position_code)
return success_response_payload(
200,
svc.list_position_employees(position_code).model_dump(mode="json"),
)
except PositionNotFoundError as exc:
raise HTTPException(status_code=404, detail=str(exc))
except WeComUnavailableError as exc:
......@@ -45,4 +48,21 @@ def get_employee_qrcodes(
db: Session = Depends(get_db),
):
svc = AgentGroupHelperService(db, get_wecom_client())
return svc.list_employee_qrcodes(employee_id)
return success_response_payload(
200,
svc.list_employee_qrcodes(employee_id).model_dump(mode="json"),
)
@router.get(
"/employees/mounts",
response_model=ApiResponse[EmployeeMountsResponse],
)
def get_employee_mounts(
db: Session = Depends(get_db),
):
svc = AgentGroupHelperService(db, get_wecom_client())
return success_response_payload(
200,
svc.list_employee_mounts().model_dump(mode="json"),
)
......@@ -4,6 +4,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from app.infrastructure.database import get_db
from app.model.agent import AgentStatus
from app.schema.agent import (
AgentCreate,
AgentDetailResponse,
......@@ -16,7 +17,6 @@ from app.schema.common import (
ApiResponse,
DeleteSuccessData,
StatusSuccessData,
SuccessFlagData,
success_response_payload,
)
from app.service.agent_service import AgentService
......@@ -28,9 +28,10 @@ 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),
managed_user_id=agent.managed_user_id,
status=agent.status,
created_at=agent.created_at,
)
......@@ -53,9 +54,9 @@ def update_agent(agent_id: int, req: AgentUpdate, db: Session = Depends(get_db))
return success_response_payload(200, _to_response(agent).model_dump(mode="json"))
except ValueError as e:
msg = str(e)
if "不存在" in msg:
if msg == "Agent不存在":
raise HTTPException(status_code=404, detail=msg)
raise HTTPException(status_code=409, detail=msg)
raise HTTPException(status_code=400, detail=msg)
@router.delete("/{agent_id}", response_model=ApiResponse[DeleteSuccessData])
......@@ -86,11 +87,11 @@ def get_agent_detail(agent_id: int, db: Session = Depends(get_db)):
@router.get("", response_model=ApiResponse[AgentListResponse])
def list_agents(
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
keyword: Optional[str] = Query(None),
position_id: Optional[int] = Query(None),
status: Optional[str] = Query(None),
page: int = Query(1, ge=1, description="页码,默认 1。"),
page_size: int = Query(20, ge=1, le=100, description="每页数量,默认 20,最大 100。"),
keyword: Optional[str] = Query(None, description="按 Agent 名称或编码模糊搜索。"),
position_id: Optional[int] = Query(None, description="按岗位 ID 筛选。"),
status: Optional[str] = Query(None, description="按 Agent 状态筛选。"),
db: Session = Depends(get_db),
):
svc = AgentService(db)
......@@ -123,3 +124,31 @@ def update_agent_status(agent_id: int, req: AgentStatusUpdate, db: Session = Dep
)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.put("/{agent_id}/enable", response_model=ApiResponse[StatusSuccessData])
def enable_agent(agent_id: int, db: Session = Depends(get_db)):
svc = AgentService(db)
try:
req = AgentStatusUpdate(status=AgentStatus.enable, reason="manual enable")
svc.update_status(agent_id, req)
return success_response_payload(
200,
{"success": True, "status": AgentStatus.enable.value},
)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.put("/{agent_id}/disable", response_model=ApiResponse[StatusSuccessData])
def disable_agent(agent_id: int, db: Session = Depends(get_db)):
svc = AgentService(db)
try:
req = AgentStatusUpdate(status=AgentStatus.disable, reason="manual disable")
svc.update_status(agent_id, req)
return success_response_payload(
200,
{"success": True, "status": AgentStatus.disable.value},
)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
......@@ -3,7 +3,7 @@ from sqlalchemy.orm import Session
from app.infrastructure.database import get_db
from app.infrastructure.shared_cache import shared_h5_cache
from app.schema.common import ApiResponse
from app.schema.common import ApiResponse, success_response_payload
from app.schema.official_site_home import H5HomeResponse
from app.service.official_site_home_service import H5HomeService
......@@ -13,4 +13,4 @@ router = APIRouter()
@router.get("/api/v1/official-site/home", response_model=ApiResponse[H5HomeResponse])
def get_home_data(db: Session = Depends(get_db)):
svc = H5HomeService(db, shared_h5_cache)
return svc.get_home_data()
return success_response_payload(200, svc.get_home_data().model_dump(mode="json"))
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Optional
from app.infrastructure.database import get_db
from app.schema.common import ApiResponse, SuccessFlagData, success_response_payload
from app.schema.position_tag import (
PositionTagAgentStatistics,
PositionTagCreate,
PositionTagUpdate,
PositionTagResponse,
PositionTagListItem,
PositionTagListResponse,
PositionTagResponse,
PositionTagUpdate,
PositionTagUpdateResponse,
ReferenceCheckResponse,
PositionTagAgentStatistics,
)
from app.schema.common import ApiResponse, SuccessFlagData, success_response_payload
from app.service.position_tag_service import PositionTagService
from app.infrastructure.database import get_db
router = APIRouter(prefix="/api/v1/position-tags")
def _to_position_tag_response(tag) -> PositionTagResponse:
return PositionTagResponse(
tag_id=tag.id,
name=tag.name,
code=tag.code,
created_at=tag.created_at,
updated_at=tag.updated_at,
)
@router.post("", response_model=ApiResponse[PositionTagResponse], status_code=201)
def create_position_tag(req: PositionTagCreate, db: Session = Depends(get_db)):
svc = PositionTagService(db)
try:
tag = svc.create(req)
return success_response_payload(
201,
PositionTagResponse.model_validate(tag).model_dump(mode="json"),
)
return success_response_payload(201, _to_position_tag_response(tag).model_dump(mode="json"))
except ValueError as e:
msg = str(e)
if "编码已存在" in msg:
if msg == "岗位标签名称已存在":
raise HTTPException(status_code=409, detail=msg)
raise HTTPException(status_code=400, detail=msg)
@router.put("/{tag_id}", response_model=ApiResponse[PositionTagResponse])
@router.put("/{tag_id}", response_model=ApiResponse[PositionTagUpdateResponse])
def update_position_tag(tag_id: int, req: PositionTagUpdate, db: Session = Depends(get_db)):
svc = PositionTagService(db)
try:
tag = svc.update(tag_id, req)
return success_response_payload(
200,
PositionTagResponse.model_validate(tag).model_dump(mode="json"),
PositionTagUpdateResponse(success=True, updated_at=tag.updated_at).model_dump(mode="json"),
)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
msg = str(e)
if msg == "岗位标签名称已存在":
raise HTTPException(status_code=409, detail=msg)
if msg == "岗位标签不存在":
raise HTTPException(status_code=404, detail=msg)
raise HTTPException(status_code=400, detail=msg)
@router.get("/{tag_id}/references", response_model=ApiResponse[ReferenceCheckResponse])
......@@ -69,11 +85,13 @@ def delete_position_tag(
return success_response_payload(200, {"success": True})
except ValueError as e:
msg = str(e)
if "阻塞性引用" in msg:
raise HTTPException(status_code=409, detail=msg)
if "Agent 引用" in msg:
raise HTTPException(status_code=409, detail=msg)
raise HTTPException(status_code=404, detail=msg)
if msg == "岗位标签不存在":
raise HTTPException(status_code=404, detail=msg)
if msg == "存在阻塞性引用,无法删除该岗位标签":
raise HTTPException(status_code=409, detail="请先删除关联的渠道活码或官网 Tab 配置")
if msg == "该岗位标签被 Agent 引用,需确认解除关联后删除":
raise HTTPException(status_code=409, detail="删除后这些 Agent 将失去该标签,请确认后重试")
raise HTTPException(status_code=409, detail=msg)
@router.get("", response_model=ApiResponse[PositionTagListResponse])
......@@ -89,9 +107,17 @@ def list_position_tags(
200,
PositionTagListResponse(
total=total,
page=page,
page_size=page_size,
list=[PositionTagResponse.model_validate(item) for item in items],
list=[
PositionTagListItem(
tag_id=item.id,
name=item.name,
code=item.code,
agent_count=len(svc.get_agents_by_position(item.id)),
description=item.description,
created_at=item.created_at,
)
for item in items
],
).model_dump(mode="json"),
)
......
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Optional
from app.infrastructure.database import get_db
from app.infrastructure.file_parser import InMemoryOSSClient, OSSClient
......@@ -9,6 +10,7 @@ from app.schema.qrcode_channel import (
QrcodeBatchStatusResponse,
QrcodeCreateRequest,
QrcodeCreateResponse,
QrcodeDeleteResponse,
QrcodeDetailResponse,
QrcodeDisableRequest,
QrcodeDisableResponse,
......@@ -43,10 +45,16 @@ def create_qrcode(req: QrcodeCreateRequest, db: Session = Depends(get_db), wecom
return svc.create(req)
except ValueError as e:
msg = str(e)
if "岗位不存在" in msg:
if msg == "岗位不存在":
raise HTTPException(status_code=400, detail=msg)
if "已存在同岗位活码" in msg:
if msg == "该岗位已存在活码":
raise HTTPException(status_code=409, detail=msg)
if msg == "employee_id 和 wechat_user_id 不匹配":
raise HTTPException(status_code=400, detail=msg)
if msg == "该员工已绑定活码":
raise HTTPException(status_code=409, detail=msg)
if msg == "员工不存在":
raise HTTPException(status_code=400, detail=msg)
raise HTTPException(status_code=400, detail=msg)
......@@ -63,18 +71,12 @@ def update_qrcode(qrcode_id: int, req: QrcodeUpdateRequest, db: Session = Depend
def list_qrcodes(
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
employee_name: Optional[str] = Query(None),
position_code: Optional[str] = Query(None),
status: Optional[str] = Query(None),
keyword: Optional[str] = Query(None),
db: Session = Depends(get_db),
):
svc = QrcodeChannelService(db, _wecom)
return svc.list_qrcodes(
page=page, page_size=page_size,
employee_name=employee_name, position_code=position_code,
status=status, keyword=keyword,
)
return svc.list_qrcodes(page=page, page_size=page_size, status=status, keyword=keyword)
@router.get("/{qrcode_id}", response_model=QrcodeDetailResponse)
......@@ -114,3 +116,12 @@ def enable_qrcode(qrcode_id: int, db: Session = Depends(get_db)):
def batch_status(req: QrcodeBatchStatusRequest, db: Session = Depends(get_db)):
svc = QrcodeChannelService(db, _wecom)
return svc.batch_status(req.qrcode_ids, req.target_status, req.reason)
@router.delete("/{qrcode_id}", response_model=QrcodeDeleteResponse)
def delete_qrcode(qrcode_id: int, db: Session = Depends(get_db)):
svc = QrcodeChannelService(db, _wecom)
try:
return svc.delete(qrcode_id)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
from app.model.agent import Agent, AgentPosition, AgentSkill, AgentStatus
from app.model.agent_group import QrcodeChannel
from app.model.position_tag import PositionTag, OfficialTab, PositionTagUser
from app.model.session import Session, SessionStatus
from app.model.wecom_sync import WeComBot, WeComContact, WeComGroup, WeComMessage, WeComSyncCheckpoint
__all__ = [
"Agent", "AgentPosition", "AgentSkill", "AgentStatus",
"QrcodeChannel",
"PositionTag", "OfficialTab", "PositionTagUser",
"Session", "SessionStatus",
"WeComBot", "WeComContact", "WeComGroup", "WeComMessage", "WeComSyncCheckpoint",
]
......@@ -15,6 +15,7 @@ class Agent(Base):
id = Column(Integer, primary_key=True, index=True)
name = Column(String(50), nullable=False)
code = Column(String(100), nullable=False, unique=True, index=True)
managed_user_id = Column(Integer, nullable=True, index=True)
description = Column(String(500))
status = Column(Enum(AgentStatus), default=AgentStatus.enable)
version = Column(Integer, default=1, nullable=False)
......@@ -50,4 +51,5 @@ class AgentSkill(Base):
agent = relationship("Agent", back_populates="skills")
__table_args__ = (UniqueConstraint('agent_id', 'skill_code', name='uk_agent_skill'),)
\ No newline at end of file
__table_args__ = (UniqueConstraint('agent_id', 'skill_code', name='uk_agent_skill'),)
......@@ -7,11 +7,11 @@ class QrcodeChannel(Base):
id = Column(Integer, primary_key=True, index=True)
qrcode_name = Column(String(50), default=None)
position_code = Column(String(100), default=None, index=True)
position_id = Column(Integer, nullable=False, index=True)
position_name = Column(String(100), nullable=False, default="")
wecom_bot_id = Column(Integer, nullable=False, index=True)
employee_id = Column(String(100), nullable=False, index=True)
employee_name = Column(String(100), nullable=False, default="")
wechat_user_id = Column(String(100), default=None)
channel_code = Column(String(100), nullable=False, unique=True, index=True)
qrcode_url = Column(String(500), default=None)
agent_ids = Column(JSON, default=None)
......@@ -25,5 +25,6 @@ class QrcodeChannel(Base):
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
__table_args__ = (
UniqueConstraint('position_code', 'employee_id', name='uk_position_employee'),
UniqueConstraint("position_id", name="uk_qrcode_position_id"),
UniqueConstraint("wecom_bot_id", name="uk_qrcode_wecom_bot_id"),
)
from sqlalchemy import Column, Integer, String, DateTime, func
from sqlalchemy import Column, Integer, String, DateTime, JSON, ForeignKey, UniqueConstraint, func
from sqlalchemy.orm import relationship
from app.infrastructure.database import Base
......@@ -9,8 +10,10 @@ class PositionTag(Base):
name = Column(String(20), nullable=False)
code = Column(String(100), nullable=False, unique=True, index=True)
description = Column(String(100), default=None)
user_ids = Column(JSON, default=None)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
users = relationship("PositionTagUser", back_populates="position_tag", cascade="all, delete-orphan")
class OfficialTab(Base):
......@@ -28,3 +31,18 @@ class OfficialTab(Base):
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
deleted_at = Column(DateTime, default=None, index=True)
class PositionTagUser(Base):
__tablename__ = "position_tag_users"
id = Column(Integer, primary_key=True, index=True)
position_tag_id = Column(Integer, ForeignKey("position_tags.id", ondelete="CASCADE"), nullable=False, index=True)
wecom_bot_id = Column(Integer, nullable=False, index=True)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
position_tag = relationship("PositionTag", back_populates="users")
__table_args__ = (
UniqueConstraint("position_tag_id", "wecom_bot_id", name="uk_position_tag_user"),
)
from pydantic import BaseModel, Field
from typing import List, Optional
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field
from app.model.agent import AgentStatus
class AgentBase(BaseModel):
name: str = Field(..., max_length=50)
description: Optional[str] = Field(None, max_length=500)
status: AgentStatus = AgentStatus.enable
name: str = Field(..., max_length=50, description="Agent 名称。", examples=["复盘 Agent"])
description: Optional[str] = Field(
None,
max_length=500,
description="Agent 描述信息。",
examples=["智能复盘助手,帮助销售进行每日复盘"],
)
status: AgentStatus = Field(
default=AgentStatus.enable,
description="Agent 状态,可选 `enable` 或 `disable`。",
examples=["enable"],
)
class AgentCreate(AgentBase):
position_ids: List[int]
skill_codes: List[str]
position_ids: List[int] = Field(..., description="关联岗位 ID 列表。", examples=[[1, 3]])
skill_codes: List[str] = Field(..., description="关联技能编码列表。", examples=[["query-metric", "query-detail"]])
managed_user_id: int = Field(..., description="托管员工 ID,取值来自 `wecom_bots.id`。", examples=[5])
class AgentUpdate(AgentBase):
position_ids: Optional[List[int]] = None
skill_codes: Optional[List[str]] = None
position_ids: Optional[List[int]] = Field(default=None, description="更新后的岗位 ID 列表。", examples=[[1, 2]])
skill_codes: Optional[List[str]] = Field(default=None, description="更新后的技能编码列表。", examples=[["query-metric"]])
managed_user_id: Optional[int] = Field(default=None, description="更新后的托管员工 ID,取值来自 `wecom_bots.id`。", examples=[5])
class AgentStatusUpdate(BaseModel):
status: AgentStatus
reason: Optional[str] = None
status: AgentStatus = Field(..., description="目标状态。", examples=["disable"])
reason: Optional[str] = Field(default=None, description="状态变更原因。", examples=["manual disable"])
class AgentPositionItem(BaseModel):
id: int
name: str
id: int = Field(..., description="岗位 ID。", examples=[1])
name: str = Field(..., description="岗位名称。", examples=["驻店销售岗"])
class AgentSkillItem(BaseModel):
skill_code: str
skill_name: str
skill_code: str = Field(..., description="技能编码。", examples=["query-metric"])
skill_name: str = Field(..., description="技能名称。", examples=["指标查询"])
class AgentUserItem(BaseModel):
user_id: int = Field(..., description="员工 ID,对应 `wecom_bots.id`。", examples=[5])
user_name: str = Field(..., description="员工名称。", examples=["张三"])
class AgentResponse(BaseModel):
agent_id: int
name: str
code: str
position_ids: List[int]
skill_codes: List[str]
created_at: datetime
agent_id: int = Field(..., description="Agent ID。", examples=[101])
name: str = Field(..., description="Agent 名称。", examples=["复盘 Agent"])
position_ids: List[int] = Field(..., description="岗位 ID 列表。", examples=[[1, 3]])
skill_codes: List[str] = Field(..., description="技能编码列表。", examples=[["query-metric"]])
managed_user_id: Optional[int] = Field(default=None, description="托管员工 ID。", examples=[5])
status: AgentStatus = Field(..., description="Agent 状态。", examples=["enable"])
created_at: datetime = Field(..., description="创建时间。", examples=["2026-05-21T10:00:00Z"])
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
agent_id: int = Field(..., description="Agent ID。", examples=[101])
name: str = Field(..., description="Agent 名称。", examples=["复盘 Agent"])
description: Optional[str] = Field(default=None, description="Agent 描述信息。", examples=["智能复盘助手"])
positions: List[AgentPositionItem] = Field(..., description="关联岗位列表。")
skills: List[AgentSkillItem] = Field(..., description="关联技能列表。")
managed_user: Optional[AgentUserItem] = Field(default=None, description="托管员工。")
status: AgentStatus = Field(..., description="Agent 状态。", examples=["enable"])
created_at: datetime = Field(..., description="创建时间。", examples=["2026-05-10T09:00:00Z"])
updated_at: datetime = Field(..., description="更新时间。", examples=["2026-05-15T10:00:00Z"])
class AgentListResponse(BaseModel):
total: int
page: int
page_size: int
list: List[AgentResponse]
total: int = Field(..., description="总记录数。", examples=[2])
page: int = Field(..., description="当前页码。", examples=[1])
page_size: int = Field(..., description="每页数量。", examples=[20])
list: List[AgentResponse] = Field(..., description="Agent 列表。")
......@@ -8,7 +8,6 @@ class EmployeeInfo(BaseModel):
employee_id: str
employee_name: str
wechat_user_id: str
department: str
status: str
......@@ -30,3 +29,33 @@ class EmployeeQrcodesResponse(BaseModel):
employee_name: str
qrcode_count: int
qrcodes: List[EmployeeQrcode]
class EmployeeMountedAgent(BaseModel):
agent_id: int
agent_name: str
status: str
class EmployeeMountedQrcode(BaseModel):
qrcode_id: int
qrcode_name: str
channel_code: str
status: str
position_id: int | None = None
position_name: str | None = None
class EmployeeMountSummary(BaseModel):
employee_id: str
employee_name: str
wechat_user_id: str
agent_count: int
qrcode_count: int
agents: List[EmployeeMountedAgent]
qrcodes: List[EmployeeMountedQrcode]
class EmployeeMountsResponse(BaseModel):
employee_count: int
employees: List[EmployeeMountSummary]
......@@ -2,42 +2,42 @@ from __future__ import annotations
from typing import Generic, List, TypeVar
from pydantic import BaseModel
from pydantic import BaseModel, Field
T = TypeVar("T")
class ApiResponse(BaseModel, Generic[T]):
code: int
message: str
data: T
code: int = Field(..., description="业务响应码。通常 200 表示成功,其余值表示业务或请求错误。", examples=[200])
message: str = Field(..., description="响应说明。成功时固定为 success,失败时返回具体错误原因。", examples=["success"])
data: T = Field(..., description="实际业务数据。成功时为对象或分页结构。")
class ErrorResponse(BaseModel):
code: int
message: str
data: None = None
code: int = Field(..., description="业务响应码。", examples=[400])
message: str = Field(..., description="错误说明。", examples=["参数校验失败:employee_id 不能为空"])
data: None = Field(default=None, description="错误响应固定为 null。")
class PageData(BaseModel, Generic[T]):
total: int
page: int
page_size: int
list: List[T]
total: int = Field(..., description="总记录数。", examples=[156])
page: int = Field(..., description="当前页码,从 1 开始。", examples=[1])
page_size: int = Field(..., description="每页数量。默认 20,最大 100。", examples=[20])
list: List[T] = Field(..., description="当前页数据列表。")
class SuccessFlagData(BaseModel):
success: bool
success: bool = Field(..., description="操作是否成功。", examples=[True])
class DeleteSuccessData(BaseModel):
success: bool
deleted_at: str
success: bool = Field(..., description="删除操作是否成功。", examples=[True])
deleted_at: str = Field(..., description="删除时间,ISO 8601 格式。", examples=["2026-05-15T14:30:00Z"])
class StatusSuccessData(BaseModel):
success: bool
status: str
success: bool = Field(..., description="状态更新是否成功。", examples=[True])
status: str = Field(..., description="更新后的状态值。", examples=["disable"])
def success_response_payload(status_code: int, data):
......
......@@ -17,9 +17,11 @@ class CreateTabResponse(BaseModel):
position_name: str
qrcode_id: int
created_at: datetime
updated_at: datetime
class UpdateTabRequest(BaseModel):
position_code: str = Field(..., max_length=100)
position_name: str = Field(..., max_length=100)
qrcode_id: int
display_status: str = Field("enable", pattern=r"^(enable|disable)$")
......@@ -59,6 +61,7 @@ class TabListItem(BaseModel):
sort_order: int
agent_count: int
created_at: datetime
updated_at: Optional[datetime] = None
operations: List[str]
......
from pydantic import BaseModel, ConfigDict, Field
from typing import List, Optional
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field
class PositionTagCreate(BaseModel):
name: str = Field(..., max_length=20)
code: str = Field(..., pattern=r"^[a-zA-Z_][a-zA-Z0-9_]*$")
description: Optional[str] = Field(None, max_length=100)
......@@ -15,21 +15,30 @@ class PositionTagUpdate(BaseModel):
class PositionTagResponse(BaseModel):
id: int
tag_id: int
name: str
code: str
description: Optional[str]
created_at: datetime
updated_at: datetime
model_config = ConfigDict(from_attributes=True)
class PositionTagListResponse(BaseModel):
total: int
page: int
page_size: int
list: List[PositionTagResponse]
list: List["PositionTagListItem"]
class PositionTagListItem(BaseModel):
tag_id: int
name: str
code: str
agent_count: int
description: Optional[str]
created_at: datetime
class PositionTagUpdateResponse(BaseModel):
success: bool
updated_at: datetime
class BlockingReference(BaseModel):
......@@ -54,7 +63,6 @@ class ReferenceCheckResponse(BaseModel):
class AgentBrief(BaseModel):
id: int
name: str
code: str
status: str
......
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field
class QrcodeCreateRequest(BaseModel):
qrcode_name: str = Field(..., max_length=50)
position_code: str = Field(..., max_length=100)
employee_id: str = Field(..., max_length=100)
employee_name: str = Field(..., max_length=100)
wechat_user_id: str = Field(..., max_length=100)
employee_id: str = Field(..., max_length=128, description="承接员工ID,对应企微员工标识(映射到 wecom_bots.bot_id)")
wechat_user_id: str = Field(..., max_length=128, description="承接员工微信ID,与 employee_id 指向同一个员工")
remark: Optional[str] = Field(None, max_length=200)
welcome_message: Optional[str] = Field(None, max_length=500)
......@@ -40,12 +40,11 @@ class QrcodeDetailResponse(BaseModel):
qrcode_name: Optional[str]
employee_id: str
employee_name: str
position_code: Optional[str]
position_name: str
channel_code: str
qrcode_url: Optional[str]
agent_ids: Optional[List[int]]
agent_names: Optional[List[str]]
agent_ids: List[int]
agent_names: List[str]
remark: Optional[str]
welcome_message: Optional[str]
status: str
......@@ -64,6 +63,7 @@ class QrcodeListItem(BaseModel):
agent_names_preview: List[str]
status: str
created_at: datetime
operations: List[str]
class QrcodeListResponse(BaseModel):
......@@ -111,3 +111,8 @@ class QrcodeBatchStatusResponse(BaseModel):
success_count: int
failed_count: int
failed_list: List[dict]
class QrcodeDeleteResponse(BaseModel):
success: bool
deleted_at: datetime
......@@ -7,64 +7,64 @@ from pydantic import BaseModel, Field
class SessionCreateRequest(BaseModel):
user_id: str = Field(..., max_length=64)
channel: str = Field(..., max_length=64)
initial_query: str = Field(..., min_length=1, max_length=5000)
user_id: str = Field(..., max_length=64, description="用户 ID。", examples=["emp_12345"])
channel: str = Field(..., max_length=64, description="会话渠道。", examples=["wechat_group"])
initial_query: str = Field(..., min_length=1, max_length=5000, description="用户发起会话的首条问题。", examples=["query A"])
class SessionCreateResponse(BaseModel):
session_id: str
user_id: str
channel: str
current_agent_id: int
created_at: datetime
session_id: str = Field(..., description="会话 ID。", examples=["sess_abc123xyz"])
user_id: str = Field(..., description="用户 ID。", examples=["emp_12345"])
channel: str = Field(..., description="会话渠道。", examples=["wechat_group"])
current_agent_id: int = Field(..., description="当前接入的 Agent ID。", examples=[101])
created_at: datetime = Field(..., description="创建时间。", examples=["2026-05-15T10:00:00Z"])
class SessionUpdateRequest(BaseModel):
role: str = Field(..., max_length=32)
content: str = Field(..., min_length=1, max_length=5000)
agent_id: int
intent: Optional[str] = Field(None, max_length=128)
entities: Optional[Dict[str, Any]] = None
role: str = Field(..., max_length=32, description="当前消息角色,例如 user 或 assistant。", examples=["user"])
content: str = Field(..., min_length=1, max_length=5000, description="本轮消息内容。", examples=["继续查昨天的数据"])
agent_id: int = Field(..., description="当前处理消息的 Agent ID。", examples=[101])
intent: Optional[str] = Field(None, max_length=128, description="识别出的意图编码。", examples=["query-metric"])
entities: Optional[Dict[str, Any]] = Field(default=None, description="本轮抽取出的实体对象。", examples=[{"merchant_id": "store_A", "metric": "sales"}])
class SessionUpdateResponse(BaseModel):
success: bool
updated_at: datetime
turn_count: int
success: bool = Field(..., description="更新是否成功。", examples=[True])
updated_at: datetime = Field(..., description="更新时间。", examples=["2026-05-15T10:05:00Z"])
turn_count: int = Field(..., description="当前会话轮次数。", examples=[5])
class SessionHistoryTurn(BaseModel):
role: str
content: str
agent_id: Optional[int] = None
intent: Optional[str] = None
timestamp: datetime
role: str = Field(..., description="消息角色。", examples=["user"])
content: str = Field(..., description="消息内容。", examples=["A 店 3 月销量是多少?"])
agent_id: Optional[int] = Field(default=None, description="处理该轮消息的 Agent ID。", examples=[101])
intent: Optional[str] = Field(default=None, description="该轮消息识别出的意图。", examples=["query-metric"])
timestamp: datetime = Field(..., description="消息时间。", examples=["2026-05-15T10:00:00Z"])
class SessionDetailResponse(BaseModel):
session_id: str
user_id: str
channel: str
current_agent_id: int
current_agent_name: Optional[str] = None
conversation_history: List[SessionHistoryTurn]
context_entities: Dict[str, Any]
created_at: datetime
updated_at: datetime
session_id: str = Field(..., description="会话 ID。", examples=["sess_abc123xyz"])
user_id: str = Field(..., description="用户 ID。", examples=["emp_12345"])
channel: str = Field(..., description="会话渠道。", examples=["wechat_group"])
current_agent_id: int = Field(..., description="当前 Agent ID。", examples=[101])
current_agent_name: Optional[str] = Field(default=None, description="当前 Agent 名称。", examples=["澄清 Agent"])
conversation_history: List[SessionHistoryTurn] = Field(..., description="会话历史。")
context_entities: Dict[str, Any] = Field(..., description="当前上下文实体集合。", examples=[{"merchant_id": "store_A", "metric": "sales"}])
created_at: datetime = Field(..., description="创建时间。", examples=["2026-05-15T10:00:00Z"])
updated_at: datetime = Field(..., description="更新时间。", examples=["2026-05-15T10:05:00Z"])
class SessionContextResponse(BaseModel):
session_id: str
current_agent_id: int
last_entities: Dict[str, Any]
inheritance_valid: bool
expires_at: Optional[datetime] = None
session_id: str = Field(..., description="会话 ID。", examples=["sess_abc123xyz"])
current_agent_id: int = Field(..., description="当前 Agent ID。", examples=[101])
last_entities: Dict[str, Any] = Field(..., description="最近一轮可继承的实体对象。", examples=[{"merchant_id": "store_A", "metric": "sales"}])
inheritance_valid: bool = Field(..., description="当前上下文是否仍可继承。", examples=[True])
expires_at: Optional[datetime] = Field(default=None, description="上下文过期时间。", examples=["2026-05-15T10:30:00Z"])
class SessionArchiveResponse(BaseModel):
success: bool
archived_at: datetime
success: bool = Field(..., description="归档是否成功。", examples=[True])
archived_at: datetime = Field(..., description="归档时间。", examples=["2026-05-15T10:35:00Z"])
SessionCreateResponse.model_config = {"from_attributes": True}
......
......@@ -7,34 +7,51 @@ 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
mode: str = Field(
...,
pattern="^(full|incremental)$",
description="同步模式。full 表示首次或手动全量同步,incremental 表示按检查点做增量同步。",
examples=["full"],
)
bot_ids: Optional[List[str]] = Field(
default=None,
description="指定需要同步的机器人 bot_id 列表。仅增量模式下常用;不传时默认读取本地已同步机器人。",
examples=[["RBT001"]],
)
message_start_time: Optional[datetime] = Field(
default=None,
description="消息同步起始时间,ISO 8601 格式。全量或窗口重扫时使用。",
examples=["2026-05-21T00:00:00Z"],
)
message_end_time: Optional[datetime] = Field(
default=None,
description="消息同步结束时间,ISO 8601 格式。",
examples=["2026-05-21T23:59:59Z"],
)
class WeComSyncRunResponse(BaseModel):
mode: str
bots: int
contacts: int
groups: int
messages: int
triggered_at: datetime
mode: str = Field(..., description="本次执行模式。", examples=["full"])
bots: int = Field(..., description="本次同步处理的机器人记录数。", examples=[1])
contacts: int = Field(..., description="本次同步处理的联系人记录数。", examples=[12])
groups: int = Field(..., description="本次同步处理的群记录数。", examples=[8])
messages: int = Field(..., description="本次同步处理的消息记录数。", examples=[156])
triggered_at: datetime = Field(..., description="本次同步触发时间,ISO 8601 格式。", examples=["2026-05-21T16:30:00Z"])
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]
resource_type: str = Field(..., description="资源类型。可取 bots、contacts、groups、messages。", examples=["messages"])
scope_key: str = Field(..., description="同步范围键。global 表示全局资源,bot:xxx 表示某个机器人范围。", examples=["bot:wt_ww:RBT001"])
last_sync_time: Optional[datetime] = Field(default=None, description="最近一次成功同步到的时间点。", examples=["2026-05-21T09:03:00Z"])
last_external_id: Optional[str] = Field(default=None, description="最近一次成功同步到的外部主键。消息通常对应 msg_id。", examples=["msg_003"])
last_status: Optional[str] = Field(default=None, description="最近一次同步状态。通常为 success 或 failed。", examples=["success"])
last_error: Optional[str] = Field(default=None, description="最近一次同步失败时的错误信息。", examples=[None])
last_started_at: Optional[datetime] = Field(default=None, description="最近一次同步启动时间。", examples=["2026-05-21T16:29:58Z"])
last_finished_at: Optional[datetime] = Field(default=None, description="最近一次同步完成时间。", examples=["2026-05-21T16:30:00Z"])
class WeComSyncCheckpointListResponse(BaseModel):
total: int
page: int
page_size: int
list: List[WeComSyncCheckpointItem]
total: int = Field(..., description="检查点总数。", examples=[4])
page: int = Field(..., description="当前页码,从 1 开始。", examples=[1])
page_size: int = Field(..., description="每页数量。", examples=[20])
list: List[WeComSyncCheckpointItem] = Field(..., description="同步检查点列表。")
......@@ -2,9 +2,16 @@ from typing import Protocol
from sqlalchemy.orm import Session
from app.model.agent import Agent
from app.model.agent_group import QrcodeChannel
from app.model.position_tag import PositionTag, PositionTagUser
from app.model.wecom_sync import WeComBot
from app.schema.agent_group import (
EmployeeInfo,
EmployeeMountedAgent,
EmployeeMountedQrcode,
EmployeeMountSummary,
EmployeeMountsResponse,
EmployeeQrcode,
EmployeeQrcodesResponse,
PositionEmployeesResponse,
......@@ -66,25 +73,78 @@ class AgentGroupHelperService:
if not position_code.strip():
raise PositionNotFoundError("岗位不存在")
position = self.db.query(PositionTag).filter(PositionTag.code == position_code).first()
if not position:
raise PositionNotFoundError("岗位不存在")
try:
payload = self.wecom_client.list_position_employees(position_code)
except WeComUnavailableError:
raise
payload = None
except Exception as exc:
raise WeComUnavailableError("企微员工列表暂不可用") from exc
if payload is None:
raise PositionNotFoundError("岗位不存在")
return self._list_position_employees_from_db(position)
active_raw = [employee for employee in payload.get("employees", []) if employee.get("status") == "在职"]
employee_ids = [str(item.get("employee_id", "")) for item in active_raw if item.get("employee_id")]
bot_rows = self.db.query(WeComBot).filter(WeComBot.bot_id.in_(employee_ids)).all() if employee_ids else []
bot_id_map = {str(row.bot_id): row.id for row in bot_rows if row.bot_id}
managed_ids = {
row.managed_user_id
for row in self.db.query(Agent).filter(Agent.is_deleted == False).all()
if row.managed_user_id is not None
}
employees = []
for employee in active_raw:
eid = str(employee.get("employee_id", ""))
managed_user_id = bot_id_map.get(eid)
status = "已挂载Agent" if managed_user_id in managed_ids else "未挂载Agent"
employees.append(
EmployeeInfo(
employee_id=eid,
employee_name=employee.get("employee_name", ""),
wechat_user_id=employee.get("wechat_user_id", ""),
status=status,
)
)
return PositionEmployeesResponse(
position_name=position.name or payload.get("position_name", ""),
employee_count=len(employees),
employees=employees,
)
active_employees = [
EmployeeInfo(**employee)
for employee in payload.get("employees", [])
if employee.get("status") == "在职"
def _list_position_employees_from_db(self, position: PositionTag) -> PositionEmployeesResponse:
bot_ids = [
row.wecom_bot_id
for row in self.db.query(PositionTagUser)
.filter(PositionTagUser.position_tag_id == position.id)
.all()
]
bots = self.db.query(WeComBot).filter(WeComBot.id.in_(bot_ids)).all() if bot_ids else []
managed_ids = {
row.managed_user_id
for row in self.db.query(Agent).filter(Agent.is_deleted == False).all()
if row.managed_user_id is not None
}
employees = [
EmployeeInfo(
employee_id=str(bot.bot_id or ""),
employee_name=bot.bot_name or "",
wechat_user_id=str(bot.bot_id or ""),
status="已挂载Agent" if bot.id in managed_ids else "未挂载Agent",
)
for bot in bots
]
return PositionEmployeesResponse(
position_name=payload.get("position_name", ""),
employee_count=len(active_employees),
employees=active_employees,
position_name=position.name or "",
employee_count=len(employees),
employees=employees,
)
def list_employee_qrcodes(self, employee_id: str) -> EmployeeQrcodesResponse:
......@@ -111,3 +171,54 @@ class AgentGroupHelperService:
qrcode_count=len(qrcodes),
qrcodes=qrcodes,
)
def list_employee_mounts(self) -> EmployeeMountsResponse:
bots = self.db.query(WeComBot).order_by(WeComBot.id.asc()).all()
active_agents = self.db.query(Agent).filter(Agent.is_deleted == False).all()
agent_map: dict[int, list[Agent]] = {}
for agent in active_agents:
if agent.managed_user_id is None:
continue
agent_map.setdefault(agent.managed_user_id, []).append(agent)
qrcode_rows = self.db.query(QrcodeChannel).all()
qrcode_map: dict[int, list[QrcodeChannel]] = {}
for row in qrcode_rows:
if row.wecom_bot_id is None:
continue
qrcode_map.setdefault(row.wecom_bot_id, []).append(row)
summaries: list[EmployeeMountSummary] = []
for bot in bots:
mounted_agents = agent_map.get(bot.id, [])
mounted_qrcodes = qrcode_map.get(bot.id, [])
summaries.append(
EmployeeMountSummary(
employee_id=str(bot.bot_id or ""),
employee_name=bot.bot_name or "",
wechat_user_id=str(bot.bot_id or ""),
agent_count=len(mounted_agents),
qrcode_count=len(mounted_qrcodes),
agents=[
EmployeeMountedAgent(
agent_id=a.id,
agent_name=a.name,
status=a.status.value,
)
for a in mounted_agents
],
qrcodes=[
EmployeeMountedQrcode(
qrcode_id=q.id,
qrcode_name=q.qrcode_name or "",
channel_code=q.channel_code,
status=q.status,
position_id=q.position_id,
position_name=q.position_name,
)
for q in mounted_qrcodes
],
)
)
return EmployeeMountsResponse(employee_count=len(summaries), employees=summaries)
import secrets
from typing import Optional
from sqlalchemy import and_, func
from sqlalchemy import and_
from sqlalchemy.orm import Session
from app.model.agent import Agent, AgentPosition, AgentSkill, AgentStatus
from app.model.position_tag import PositionTag
from app.model.session import Session as AgentSession
from app.model.skill import Skill
from app.model.wecom_sync import WeComBot
from app.schema.agent import (
AgentCreate,
AgentDetailResponse,
......@@ -15,6 +15,7 @@ from app.schema.agent import (
AgentSkillItem,
AgentStatusUpdate,
AgentUpdate,
AgentUserItem,
)
......@@ -23,19 +24,22 @@ class AgentService:
self.db = db
def create(self, data: AgentCreate) -> Agent:
self._ensure_name_unique(data.name)
self._validate_references(data.position_ids, data.skill_codes, data.managed_user_id)
self._ensure_managed_user_available(data.managed_user_id)
agent = Agent(
name=data.name,
code=self._generate_unique_code(),
code=self._generate_internal_code(),
description=data.description,
status=data.status,
managed_user_id=data.managed_user_id,
)
self.db.add(agent)
self.db.flush()
for pid in data.position_ids:
self.db.add(AgentPosition(agent_id=agent.id, position_id=pid))
for sc in data.skill_codes:
self.db.add(AgentSkill(agent_id=agent.id, skill_code=sc))
self._replace_positions(agent.id, data.position_ids)
self._replace_skills(agent.id, data.skill_codes)
self.db.commit()
self.db.refresh(agent)
......@@ -43,20 +47,28 @@ class AgentService:
def update(self, agent_id: int, data: AgentUpdate) -> Agent:
agent = self._get_agent_or_404(agent_id)
self._ensure_name_unique(data.name, exclude_agent_id=agent_id)
target_position_ids = data.position_ids if data.position_ids is not None else sorted(item.position_id for item in agent.positions)
target_skill_codes = data.skill_codes if data.skill_codes is not None else sorted(item.skill_code for item in agent.skills)
target_managed_user_id = data.managed_user_id if data.managed_user_id is not None else agent.managed_user_id
self._validate_references(target_position_ids, target_skill_codes, target_managed_user_id)
if target_managed_user_id is not None:
self._ensure_managed_user_available(target_managed_user_id, exclude_agent_id=agent_id)
agent.name = data.name
agent.description = data.description
agent.status = data.status
agent.managed_user_id = target_managed_user_id
if data.position_ids is not None:
self.db.query(AgentPosition).filter(AgentPosition.agent_id == agent_id).delete()
for pid in data.position_ids:
self.db.add(AgentPosition(agent_id=agent_id, position_id=pid))
self._replace_positions(agent_id, data.position_ids)
if data.skill_codes is not None:
self.db.query(AgentSkill).filter(AgentSkill.agent_id == agent_id).delete()
for sc in data.skill_codes:
self.db.add(AgentSkill(agent_id=agent_id, skill_code=sc))
self._replace_skills(agent_id, data.skill_codes)
self.db.commit()
self.db.refresh(agent)
......@@ -64,9 +76,11 @@ class AgentService:
def delete(self, agent_id: int) -> Agent:
agent = self._get_agent_or_404(agent_id)
from datetime import datetime, timezone
self.db.query(AgentPosition).filter(AgentPosition.agent_id == agent_id).delete()
self.db.query(AgentSkill).filter(AgentSkill.agent_id == agent_id).delete()
agent.managed_user_id = None
agent.is_deleted = True
agent.deleted_at = datetime.now(timezone.utc)
self.db.commit()
......@@ -81,76 +95,42 @@ class AgentService:
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
]
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
)
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]
managed_user = None
if agent.managed_user_id is not None:
bot = self.db.query(WeComBot).filter(WeComBot.id == agent.managed_user_id).first()
if bot:
managed_user = AgentUserItem(user_id=bot.id, user_name=bot.bot_name)
return AgentDetailResponse(
agent_id=agent.id,
name=agent.name,
code=agent.code,
description=agent.description,
positions=positions,
skills=skills,
managed_user=managed_user,
status=agent.status,
session_count=session_count,
created_at=agent.created_at,
updated_at=agent.updated_at,
)
def list_agents(
self,
page: int = 1,
page_size: int = 20,
keyword: Optional[str] = None,
position_id: Optional[int] = None,
status: Optional[AgentStatus] = None,
):
def list_agents(self, page: int = 1, page_size: int = 20, keyword: Optional[str] = None, position_id: Optional[int] = None, status: Optional[AgentStatus] = None):
query = self.db.query(Agent).filter(Agent.is_deleted == False)
if keyword:
query = query.filter(
and_(
Agent.is_deleted == False,
(Agent.name.like(f"%{keyword}%")) | (Agent.code.like(f"%{keyword}%")),
)
)
query = query.filter(and_(Agent.is_deleted == False, Agent.name.like(f"%{keyword}%")))
if position_id is not None:
query = query.join(AgentPosition).filter(
AgentPosition.position_id == position_id,
Agent.is_deleted == False,
)
query = query.join(AgentPosition).filter(AgentPosition.position_id == position_id, Agent.is_deleted == False)
if status is not None:
query = query.filter(Agent.status == status)
total = query.count()
items = query.offset((page - 1) * page_size).limit(page_size).all()
return total, items
def update_status(self, agent_id: int, data: AgentStatusUpdate) -> Agent:
......@@ -160,30 +140,59 @@ class AgentService:
self.db.refresh(agent)
return agent
def _replace_positions(self, agent_id: int, position_ids: list[int]) -> None:
for pid in position_ids:
self.db.add(AgentPosition(agent_id=agent_id, position_id=pid))
def _replace_skills(self, agent_id: int, skill_codes: list[str]) -> None:
for sc in skill_codes:
self.db.add(AgentSkill(agent_id=agent_id, skill_code=sc))
def _validate_references(self, position_ids: list[int], skill_codes: list[str], managed_user_id: Optional[int]) -> None:
positions = self.db.query(PositionTag).filter(PositionTag.id.in_(position_ids)).all() if position_ids else []
found_position_ids = {item.id for item in positions}
missing_position_ids = sorted(set(position_ids) - found_position_ids)
if missing_position_ids:
raise ValueError(f"岗位不存在: {missing_position_ids}")
skills = self.db.query(Skill).filter(Skill.skill_code.in_(skill_codes)).all() if skill_codes else []
found_skill_codes = {item.skill_code for item in skills}
missing_skill_codes = sorted(set(skill_codes) - found_skill_codes)
if missing_skill_codes:
raise ValueError(f"技能不存在: {missing_skill_codes}")
if managed_user_id is not None:
bot = self.db.query(WeComBot).filter(WeComBot.id == managed_user_id).first()
if not bot:
raise ValueError(f"员工不存在: [{managed_user_id}]")
def _get_agent_or_404(self, agent_id: int) -> Agent:
agent = (
self.db.query(Agent)
.filter(
Agent.id == agent_id,
Agent.is_deleted == False,
)
.first()
)
agent = self.db.query(Agent).filter(Agent.id == agent_id, Agent.is_deleted == False).first()
if not agent:
raise ValueError("Agent不存在")
return agent
def _generate_unique_code(self) -> str:
def _ensure_name_unique(self, name: str, exclude_agent_id: Optional[int] = None) -> None:
query = self.db.query(Agent).filter(Agent.name == name, Agent.is_deleted == False)
if exclude_agent_id is not None:
query = query.filter(Agent.id != exclude_agent_id)
if query.first():
raise ValueError("Agent名称已存在")
def _ensure_managed_user_available(self, managed_user_id: int, exclude_agent_id: Optional[int] = None) -> None:
query = self.db.query(Agent).filter(
Agent.managed_user_id == managed_user_id,
Agent.is_deleted == False,
)
if exclude_agent_id is not None:
query = query.filter(Agent.id != exclude_agent_id)
occupied = query.first()
if occupied:
raise ValueError(f"该员工已绑定其他Agent: [{managed_user_id}]")
def _generate_internal_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:
candidate = f"agent_{secrets.token_hex(6)}"
if not self.db.query(Agent).filter(Agent.code == candidate).first():
return candidate
raise ValueError("自动生成Agent编码失败,请稍后重试")
raise ValueError("生成内部标识失败,请稍后重试")
......@@ -13,8 +13,6 @@ from app.schema.methodology import (
SaveMethodologyResponse,
)
_MIN_STEPS = 4
_MAX_STEPS = 10
_MAX_STEP_NAME_LEN = 20
_MAX_MAIN_TITLE_LEN = 100
_MAX_SUB_TITLE_LEN = 200
......@@ -64,9 +62,6 @@ class MethodologyService:
def save_methodology(self, req: SaveMethodologyRequest) -> SaveMethodologyResponse:
step_count = len(req.steps)
if step_count < _MIN_STEPS or step_count > _MAX_STEPS:
raise ValueError(f"步骤数量必须在 {_MIN_STEPS}-{_MAX_STEPS} 之间")
orders = sorted(s.step_order for s in req.steps)
expected = list(range(1, step_count + 1))
if orders != expected:
......
......@@ -7,6 +7,7 @@ from sqlalchemy import or_
from sqlalchemy.orm import Session as OrmSession
from app.infrastructure.h5_cache import H5CacheManager
from app.model.agent import Agent, AgentPosition
from app.model.agent_group import QrcodeChannel
from app.model.position_tag import PositionTag, OfficialTab
from app.schema.official_site_tab import (
......@@ -30,6 +31,7 @@ class OfficialSiteTabService:
self.cache = cache
def create(self, req: CreateTabRequest) -> CreateTabResponse:
now = datetime.now(timezone.utc)
position = self.db.query(PositionTag).filter(PositionTag.code == req.position_code).first()
if not position:
raise ValueError("岗位不存在")
......@@ -47,6 +49,8 @@ class OfficialSiteTabService:
display_status=req.display_status,
sort_order=req.sort_order,
created_by="admin",
created_at=now,
updated_at=now,
)
self.db.add(tab)
self.db.commit()
......@@ -60,6 +64,7 @@ class OfficialSiteTabService:
position_name=tab.position_name or "",
qrcode_id=tab.qrcode_id or 0,
created_at=tab.created_at,
updated_at=tab.updated_at,
)
def update(self, tab_id: int, req: UpdateTabRequest) -> UpdateTabResponse:
......@@ -159,6 +164,7 @@ class OfficialSiteTabService:
sort_order=r.sort_order,
agent_count=0,
created_at=r.created_at,
updated_at=r.updated_at,
operations=operations,
))
......@@ -170,7 +176,9 @@ class OfficialSiteTabService:
) -> AvailableQrcodeListResponse:
query = self.db.query(QrcodeChannel).filter(QrcodeChannel.status == "enable")
if position_code:
query = query.filter(QrcodeChannel.position_code == position_code)
query = query.join(PositionTag, QrcodeChannel.position_id == PositionTag.id).filter(
PositionTag.code == position_code
)
rows = query.order_by(QrcodeChannel.id.asc()).all()
items = [
......
from sqlalchemy.orm import Session
from sqlalchemy import or_
import re
import secrets
from typing import Optional
from app.model.position_tag import PositionTag, OfficialTab
from sqlalchemy.orm import Session
from app.model.agent import Agent, AgentPosition, AgentStatus
from app.model.agent_group import QrcodeChannel
from app.model.position_tag import OfficialTab, PositionTag
from app.schema.position_tag import (
PositionTagCreate,
PositionTagUpdate,
ReferenceCheckResponse,
AgentBrief,
BlockingReference,
DetachableReference,
PositionTagAgentStatistics,
AgentBrief,
PositionTagCreate,
PositionTagUpdate,
ReferenceCheckResponse,
)
......@@ -20,16 +23,15 @@ class PositionTagService:
self.db = db
def create(self, data: PositionTagCreate) -> PositionTag:
existing = self.db.query(PositionTag).filter(
PositionTag.code == data.code
).first()
existing = self.db.query(PositionTag).filter(PositionTag.name == data.name).first()
if existing:
raise ValueError("岗位标签编码已存在")
raise ValueError("岗位标签名称已存在")
tag = PositionTag(
name=data.name,
code=data.code,
code=self._generate_position_code(data.name),
description=data.description,
user_ids=[],
)
self.db.add(tag)
self.db.commit()
......@@ -38,8 +40,19 @@ class PositionTagService:
def update(self, tag_id: int, data: PositionTagUpdate) -> PositionTag:
tag = self._get_tag_or_404(tag_id)
existing = (
self.db.query(PositionTag)
.filter(PositionTag.name == data.name, PositionTag.id != tag_id)
.first()
)
if existing:
raise ValueError("岗位标签名称已存在")
tag.name = data.name
tag.description = data.description
tag.user_ids = self.resolve_tag_user_ids(tag)
self.db.commit()
self.db.refresh(tag)
return tag
......@@ -51,44 +64,25 @@ class PositionTagService:
detachable = []
hints = []
qrcode_refs = self.db.query(QrcodeChannel).filter(
QrcodeChannel.position_name == tag.name
).all()
qrcode_refs = self.db.query(QrcodeChannel).filter(QrcodeChannel.position_name == tag.name).all()
for qr in qrcode_refs:
blocking.append(BlockingReference(
type="qrcode_channel",
id=qr.id,
name=qr.channel_code,
))
tab_refs = self.db.query(OfficialTab).filter(
OfficialTab.position_id == tag_id
).all()
blocking.append(BlockingReference(type="qrcode_channel", id=qr.id, name=qr.channel_code))
tab_refs = self.db.query(OfficialTab).filter(OfficialTab.position_id == tag_id).all()
for tab in tab_refs:
blocking.append(BlockingReference(
type="official_tab",
id=tab.id,
name=tab.tab_name,
))
agent_positions = self.db.query(AgentPosition).filter(
AgentPosition.position_id == tag_id
).all()
blocking.append(BlockingReference(type="official_tab", id=tab.id, name=tab.tab_name))
agent_positions = self.db.query(AgentPosition).filter(AgentPosition.position_id == tag_id).all()
for ap in agent_positions:
agent = self.db.query(Agent).filter(Agent.id == ap.agent_id).first()
if agent:
detachable.append(DetachableReference(
type="agent",
id=agent.id,
name=agent.name,
))
detachable.append(DetachableReference(type="agent", id=agent.id, name=agent.name))
can_delete = len(blocking) == 0
if blocking:
hints.append("该岗位标签存在阻塞性引用,无法删除")
if detachable:
hints.append("该岗位标签被 Agent 引用,删除将解除与 Agent 的关联")
hints.append("该岗位标签被 Agent 引用,删除将解除相关 Agent 的岗位关联")
return ReferenceCheckResponse(
can_delete=can_delete,
......@@ -98,7 +92,7 @@ class PositionTagService:
)
def delete(self, tag_id: int, confirm_detach_agents: bool = False) -> None:
tag = self._get_tag_or_404(tag_id)
self._get_tag_or_404(tag_id)
ref_check = self.check_references(tag_id)
if ref_check.blocking_references:
......@@ -107,56 +101,62 @@ class PositionTagService:
if ref_check.detachable_references:
if not confirm_detach_agents:
raise ValueError("该岗位标签被 Agent 引用,需确认解除关联后删除")
self.db.query(AgentPosition).filter(
AgentPosition.position_id == tag_id
).delete()
self.db.query(AgentPosition).filter(AgentPosition.position_id == tag_id).delete()
tag = self._get_tag_or_404(tag_id)
self.db.delete(tag)
self.db.commit()
def list_tags(
self,
page: int = 1,
page_size: int = 20,
keyword: Optional[str] = None,
):
def list_tags(self, page: int = 1, page_size: int = 20, keyword: Optional[str] = None):
query = self.db.query(PositionTag)
if keyword:
query = query.filter(
or_(
PositionTag.name.like(f"%{keyword}%"),
PositionTag.code.like(f"%{keyword}%"),
)
)
query = query.filter(PositionTag.name.like(f"%{keyword}%"))
total = query.count()
items = query.offset((page - 1) * page_size).limit(page_size).all()
return total, items
def resolve_tag_user_ids(self, tag: PositionTag) -> list[int]:
agent_positions = self.db.query(AgentPosition).filter(AgentPosition.position_id == tag.id).all()
agent_ids = [ap.agent_id for ap in agent_positions]
if not agent_ids:
return []
agents = self.db.query(Agent).filter(Agent.id.in_(agent_ids), Agent.is_deleted == False).all()
return sorted({a.managed_user_id for a in agents if a.managed_user_id is not None})
def get_agent_statistics(self, tag_id: int) -> PositionTagAgentStatistics:
self._get_tag_or_404(tag_id)
agent_positions = self.db.query(AgentPosition).filter(
AgentPosition.position_id == tag_id
).all()
agent_positions = self.db.query(AgentPosition).filter(AgentPosition.position_id == tag_id).all()
agent_ids = [ap.agent_id for ap in agent_positions]
agents = self.db.query(Agent).filter(Agent.id.in_(agent_ids)).all() if agent_ids else []
active_count = sum(1 for a in agents if a.status == AgentStatus.enable)
return PositionTagAgentStatistics(
position_id=tag_id,
agent_count=len(agents),
active_agent_count=active_count,
agents=[
AgentBrief(id=a.id, name=a.name, code=a.code, status=a.status.value)
for a in agents
],
agents=[AgentBrief(id=a.id, name=a.name, status=a.status.value) for a in agents],
)
def get_agents_by_position(self, tag_id: int) -> list[AgentBrief]:
agent_positions = self.db.query(AgentPosition).filter(AgentPosition.position_id == tag_id).all()
agent_ids = [ap.agent_id for ap in agent_positions]
agents = self.db.query(Agent).filter(Agent.id.in_(agent_ids)).all() if agent_ids else []
return [AgentBrief(id=a.id, name=a.name, status=a.status.value) for a in agents]
def _generate_position_code(self, name: str) -> str:
base = re.sub(r"[^a-zA-Z]+", "_", name).strip("_").lower()
if not base:
base = "position"
base = re.sub(r"_+", "_", base)
if not re.fullmatch(r"[a-z_]+", base):
base = "position"
for _ in range(20):
candidate = f"{base}_{secrets.token_hex(3)}"
exists = self.db.query(PositionTag).filter(PositionTag.code == candidate).first()
if not exists:
return candidate
raise ValueError("岗位编码生成失败,请稍后重试")
def _get_tag_or_404(self, tag_id: int) -> PositionTag:
tag = self.db.query(PositionTag).filter(PositionTag.id == tag_id).first()
if not tag:
......
from __future__ import annotations
from datetime import datetime, timezone, timedelta
from datetime import datetime, timedelta, timezone
from typing import Optional
from sqlalchemy import or_
......@@ -10,16 +10,18 @@ from app.infrastructure.file_parser import OSSClient
from app.model.agent import Agent, AgentPosition, AgentStatus
from app.model.agent_group import QrcodeChannel
from app.model.position_tag import PositionTag
from app.model.wecom_sync import WeComBot
from app.schema.qrcode_channel import (
QrcodeBatchStatusResponse,
QrcodeCreateResponse,
QrcodeDeleteResponse,
QrcodeDetailResponse,
QrcodeDisableResponse,
QrcodeEnableResponse,
QrcodeExportResponse,
QrcodeListItem,
QrcodeListResponse,
QrcodeUpdateResponse,
QrcodeExportResponse,
)
from app.service.agent_group_helper_service import WeComClient
......@@ -31,31 +33,39 @@ class QrcodeChannelService:
self.oss = oss
def create(self, req) -> QrcodeCreateResponse:
position = self.db.query(PositionTag).filter(
PositionTag.code == req.position_code
).first()
position = self.db.query(PositionTag).filter(PositionTag.code == req.position_code).first()
if not position:
raise ValueError("岗位不存在")
existing = self.db.query(QrcodeChannel).filter(
QrcodeChannel.position_code == req.position_code,
QrcodeChannel.employee_id == req.employee_id,
).first()
if existing:
raise ValueError("该员工已存在同岗位活码")
if self.db.query(QrcodeChannel).filter(QrcodeChannel.position_id == position.id).first():
raise ValueError("该岗位已存在活码")
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == req.employee_id).first()
if bot is None:
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == req.wechat_user_id).first()
if bot is None or not bot.bot_id:
raise ValueError("员工不存在")
if req.wechat_user_id and str(req.wechat_user_id) != str(bot.bot_id):
raise ValueError("employee_id 和 wechat_user_id 不匹配")
if self.db.query(QrcodeChannel).filter(QrcodeChannel.wecom_bot_id == bot.id).first():
raise ValueError("该员工已绑定活码")
steward = self.db.query(Agent).filter(
Agent.code == "steward",
Agent.is_deleted == False,
).first()
employee_id = str(bot.bot_id)
employee_name = bot.bot_name or employee_id
steward = self.db.query(Agent).filter(Agent.code == "steward", Agent.is_deleted == False).first()
position_agents = (
self.db.query(Agent)
.join(AgentPosition, AgentPosition.agent_id == Agent.id)
.filter(AgentPosition.position_id == position.id, Agent.is_deleted == False, Agent.status == AgentStatus.enable)
.filter(
AgentPosition.position_id == position.id,
Agent.is_deleted == False,
Agent.status == AgentStatus.enable,
)
.all()
)
agent_list = list(position_agents)
if steward and steward not in agent_list:
agent_list.insert(0, steward)
......@@ -63,16 +73,16 @@ class QrcodeChannelService:
agent_ids = [a.id for a in agent_list]
agent_names = [a.name for a in agent_list]
channel_code = f"zdxs_{req.position_code}_{req.employee_id}"
channel_code = position.code
qrcode_url = self.wecom.create_qrcode(channel_code, req.welcome_message or "")
qr = QrcodeChannel(
qrcode_name=req.qrcode_name,
position_code=req.position_code,
position_id=position.id,
position_name=position.name,
employee_id=req.employee_id,
employee_name=req.employee_name,
wechat_user_id=req.wechat_user_id,
wecom_bot_id=bot.id,
employee_id=employee_id,
employee_name=employee_name,
channel_code=channel_code,
qrcode_url=qrcode_url,
agent_ids=agent_ids,
......@@ -107,22 +117,35 @@ class QrcodeChannelService:
def get_detail(self, qrcode_id: int) -> QrcodeDetailResponse:
qr = self._get_or_404(qrcode_id)
position_name = qr.position_name
if qr.position_code:
pos = self.db.query(PositionTag).filter(PositionTag.code == qr.position_code).first()
if pos:
position_name = pos.name
position_agents = (
self.db.query(Agent)
.join(AgentPosition, AgentPosition.agent_id == Agent.id)
.filter(
AgentPosition.position_id == qr.position_id,
Agent.is_deleted == False,
Agent.status == AgentStatus.enable,
)
.all()
if qr.position_id is not None
else []
)
steward = self.db.query(Agent).filter(Agent.code == "steward", Agent.is_deleted == False).first()
agent_list = list(position_agents)
if steward and steward not in agent_list:
agent_list.insert(0, steward)
agent_ids = [a.id for a in agent_list]
agent_names = [a.name for a in agent_list]
return QrcodeDetailResponse(
qrcode_id=qr.id,
qrcode_name=qr.qrcode_name,
employee_id=qr.employee_id,
employee_name=qr.employee_name,
position_code=qr.position_code,
position_name=position_name,
position_name=qr.position_name,
channel_code=qr.channel_code,
qrcode_url=qr.qrcode_url,
agent_ids=qr.agent_ids or [],
agent_names=qr.agent_names or [],
agent_ids=agent_ids,
agent_names=agent_names,
remark=qr.remark,
welcome_message=qr.welcome_message,
status=qr.status,
......@@ -135,17 +158,10 @@ class QrcodeChannelService:
self,
page: int = 1,
page_size: int = 20,
employee_name: Optional[str] = None,
position_code: Optional[str] = None,
status: Optional[str] = None,
keyword: Optional[str] = None,
) -> QrcodeListResponse:
query = self.db.query(QrcodeChannel)
if employee_name:
query = query.filter(QrcodeChannel.employee_name.like(f"%{employee_name}%"))
if position_code:
query = query.filter(QrcodeChannel.position_code == position_code)
if status:
query = query.filter(QrcodeChannel.status == status)
if keyword:
......@@ -159,37 +175,57 @@ class QrcodeChannelService:
total = query.count()
rows = query.order_by(QrcodeChannel.id.desc()).offset((page - 1) * page_size).limit(page_size).all()
items = []
for r in rows:
agent_ids = r.agent_ids or []
agent_names = r.agent_names or []
items.append(QrcodeListItem(
qrcode_id=r.id,
employee_name=r.employee_name,
position_name=r.position_name,
channel_code=r.channel_code,
qrcode_url=r.qrcode_url,
agent_count=len(agent_ids),
agent_names_preview=agent_names[:3],
status=r.status,
created_at=r.created_at,
))
position_agents = (
self.db.query(Agent)
.join(AgentPosition, AgentPosition.agent_id == Agent.id)
.filter(
AgentPosition.position_id == r.position_id,
Agent.is_deleted == False,
Agent.status == AgentStatus.enable,
)
.all()
if r.position_id is not None
else []
)
steward = self.db.query(Agent).filter(Agent.code == "steward", Agent.is_deleted == False).first()
agent_list = list(position_agents)
if steward and steward not in agent_list:
agent_list.insert(0, steward)
agent_names = [a.name for a in agent_list]
operations = ["查看", "编辑"]
if r.status == "enable":
operations.append("停用")
else:
operations.append("启用")
items.append(
QrcodeListItem(
qrcode_id=r.id,
employee_name=r.employee_name,
position_name=r.position_name,
channel_code=r.channel_code,
qrcode_url=r.qrcode_url,
agent_count=len(agent_list),
agent_names_preview=agent_names,
status=r.status,
created_at=r.created_at,
operations=operations,
)
)
return QrcodeListResponse(total=total, page=page, page_size=page_size, list=items)
def export(self, req) -> QrcodeExportResponse:
query = self.db.query(QrcodeChannel)
if req.filter_conditions:
if req.filter_conditions.get("position_code"):
query = query.filter(QrcodeChannel.position_code == req.filter_conditions["position_code"])
if req.filter_conditions.get("position_name"):
query = query.filter(QrcodeChannel.position_name == req.filter_conditions["position_name"])
if req.filter_conditions.get("status"):
query = query.filter(QrcodeChannel.status == req.filter_conditions["status"])
rows = query.order_by(QrcodeChannel.id.asc()).all()
fields = req.export_fields or ["employee_name", "position_name", "channel_code", "status"]
header = ",".join(fields)
lines = [header]
lines = [",".join(fields)]
for r in rows:
vals = []
for f in fields:
......@@ -210,19 +246,8 @@ class QrcodeChannelService:
csv_data = "\n".join(lines).encode("utf-8-sig")
now = datetime.now(timezone.utc)
file_name = f"qrcode_export_{now.strftime('%Y%m%d_%H%M%S')}.csv"
file_url = ""
if self.oss:
file_url = self.oss.upload(csv_data, file_name, "text/csv")
else:
file_url = f"https://oss.example.com/export/{file_name}"
return QrcodeExportResponse(
file_url=file_url,
file_name=file_name,
total_count=len(rows),
expires_at=now + timedelta(hours=24),
)
file_url = self.oss.upload(csv_data, file_name, "text/csv") if self.oss else f"https://oss.example.com/export/{file_name}"
return QrcodeExportResponse(file_url=file_url, file_name=file_name, total_count=len(rows), expires_at=now + timedelta(hours=24))
def disable(self, qrcode_id: int, reason: str) -> QrcodeDisableResponse:
qr = self._get_or_404(qrcode_id)
......@@ -254,8 +279,20 @@ class QrcodeChannelService:
failed.append({"qrcode_id": qid, "error": str(e)})
return QrcodeBatchStatusResponse(success_count=success, failed_count=len(failed), failed_list=failed)
def delete(self, qrcode_id: int) -> QrcodeDeleteResponse:
qr = self._get_or_404(qrcode_id)
self.db.delete(qr)
self.db.commit()
return QrcodeDeleteResponse(success=True, deleted_at=datetime.now(timezone.utc))
def _get_or_404(self, qrcode_id: int) -> QrcodeChannel:
qr = self.db.query(QrcodeChannel).filter(QrcodeChannel.id == qrcode_id).first()
if not qr:
raise ValueError("渠道活码不存在")
return qr
@staticmethod
def _merge_agents(agent_ids: Optional[list[int]], agent_names: Optional[list[str]]) -> list[dict]:
ids = agent_ids or []
names = agent_names or []
return [{"id": aid, "name": (names[idx] if idx < len(names) else "")} for idx, aid in enumerate(ids)]
Binary files a/workspace/agent-admin/backend/dev.db-wal and b/workspace/agent-admin/backend/dev.db-wal differ
# 后端接口测试文档: agents
## 1. 模块说明
## 1. 模块概览
| 项 | 值 |
|------|-----|
| 模块名 | agents |
| 基础路径 | `/api/v1/agents` |
| 说明 | Agent 基础管理,包含创建、更新、删除、详情、列表和状态更新 |
| 模块说明 | Agent 管理接口,支持创建、更新、删除、列表、详情、状态切换,以及岗位下企业微信员工绑定。 |
## 2. 通用响应规范
## 2. 通用响应结构
成功响应:
......@@ -25,7 +25,7 @@
```json
{
"code": 400,
"message": "错误信息",
"message": "参数校验失败",
"data": null
}
```
......@@ -51,16 +51,17 @@
- 方法: `POST`
- 路径: `/api/v1/agents`
- 说明: 请求体不再传 `code`,由后端自动生成 `agent_` 前缀唯一编码
- 说明: 创建时按 `name` 判重。`user_ids` 为员工记录 ID,取值来自 `qrcode_channels.id`,且必须属于所选岗位。响应中不再返回 `code` 字段。
请求体:
请求示例:
```json
{
"name": "复盘 Agent",
"description": "智能复盘助手",
"position_ids": [1],
"skill_codes": ["query-metric"],
"description": "智能复盘助手,帮助销售进行每日复盘",
"position_ids": [1, 3],
"skill_codes": ["query-metric", "query-detail", "attribution-analysis"],
"user_ids": [1, 5],
"status": "enable"
}
```
......@@ -74,28 +75,40 @@
"data": {
"agent_id": 101,
"name": "复盘 Agent",
"code": "agent_a7k29xqp",
"position_ids": [1],
"skill_codes": ["query-metric"],
"created_at": "2026-05-15T10:30:00Z"
"position_ids": [1, 3],
"skill_codes": ["attribution-analysis", "query-detail", "query-metric"],
"user_ids": [1, 5],
"created_at": "2026-05-21T10:30:00Z"
}
}
```
失败示例:
```json
{
"code": 400,
"message": "Agent名称已存在",
"data": null
}
```
### 3.2 更新 Agent
- 方法: `PUT`
- 路径: `/api/v1/agents/{agent_id}`
- 说明: 更新时如果改名,也会按 `name` 判重。响应中不返回 `code` 字段。
请求体:
请求示例:
```json
{
"name": "更新后 Agent",
"name": "复盘 Agent",
"description": "更新后的描述",
"status": "enable",
"position_ids": [1, 2],
"skill_codes": ["query-metric", "query-detail"]
"skill_codes": ["query-metric", "query-detail"],
"user_ids": [1, 2]
}
```
......@@ -107,11 +120,11 @@
"message": "success",
"data": {
"agent_id": 101,
"name": "更新后 Agent",
"code": "agent_a7k29xqp",
"name": "复盘 Agent",
"position_ids": [1, 2],
"skill_codes": ["query-detail", "query-metric"],
"created_at": "2026-05-15T10:30:00Z"
"user_ids": [1, 2],
"created_at": "2026-05-21T10:30:00Z"
}
}
```
......@@ -138,6 +151,7 @@
- 方法: `GET`
- 路径: `/api/v1/agents/{agent_id}`
- 说明: 详情响应不返回 `code` 字段。
成功响应示例:
......@@ -148,7 +162,6 @@
"data": {
"agent_id": 101,
"name": "复盘 Agent",
"code": "agent_a7k29xqp",
"description": "智能复盘助手",
"positions": [
{"id": 1, "name": "驻店销售岗"},
......@@ -159,6 +172,10 @@
{"skill_code": "query-detail", "skill_name": "明细查询"},
{"skill_code": "attribution-analysis", "skill_name": "归因分析"}
],
"users": [
{"user_id": 1, "user_name": "张三"},
{"user_id": 5, "user_name": "李四"}
],
"status": "enable",
"session_count": 156,
"created_at": "2026-05-10T09:00:00Z",
......@@ -177,6 +194,7 @@
- `keyword`
- `position_id`
- `status`
- 说明: `keyword` 只按 `name` 模糊搜索,不再按 `code` 搜索。列表响应不返回 `code` 字段。
成功响应示例:
......@@ -192,17 +210,17 @@
{
"agent_id": 1,
"name": "Agent1",
"code": "agent_1abc23de",
"position_ids": [1],
"skill_codes": ["query-metric"],
"user_ids": [1],
"created_at": "2026-05-21T10:00:00"
},
{
"agent_id": 2,
"name": "Agent2",
"code": "agent_9f0c12ab",
"position_ids": [2],
"skill_codes": ["query-detail"],
"user_ids": [2],
"created_at": "2026-05-21T10:01:00"
}
]
......@@ -215,12 +233,12 @@
- 方法: `PUT`
- 路径: `/api/v1/agents/{agent_id}/status`
请求体:
请求示例:
```json
{
"status": "disable",
"reason": "手动禁用"
"reason": "manual disable"
}
```
......@@ -239,12 +257,14 @@
## 4. 测试覆盖
文档对应测试文件: `backend/tests/test_agents_api.py`
对应测试文件: `backend/tests/test_agents_api.py`
| 测试类 | 测试方法 |
| 测试类 | 测试用例 |
|------|------|
| `TestCreateAgent` | `test_create_agent_success` |
| `TestCreateAgent` | `test_create_agent_generates_unique_code` |
| `TestCreateAgent` | `test_create_agent_name_conflict` |
| `TestCreateAgent` | `test_create_agent_rejects_unknown_user` |
| `TestCreateAgent` | `test_create_agent_rejects_user_outside_positions` |
| `TestUpdateAgent` | `test_update_agent_success` |
| `TestUpdateAgent` | `test_update_agent_without_version` |
| `TestDeleteAgent` | `test_delete_agent_success` |
......@@ -252,3 +272,38 @@
| `TestListAgents` | `test_list_agents_success` |
| `TestListAgents` | `test_list_agents_with_keyword` |
| `TestUpdateStatus` | `test_disable_agent` |
---
## 附录A 字段说明
### A.1 创建/更新请求字段
| 字段 | 类型 | 说明 |
|------|------|------|
| name | string | Agent 名称(唯一,按未删除数据判重)。 |
| description | string | Agent 描述信息。 |
| position_ids | integer[] | 岗位 ID 列表,取值来自岗位标签表。 |
| skill_codes | string[] | 技能编码列表,取值来自技能目录。 |
| user_ids | integer[] | 员工 ID 列表,取值来自 `qrcode_channels.id`,且必须属于所选岗位。 |
| status | string | Agent 状态,支持 `enable` / `disable`。 |
### A.2 列表响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| agent_id | integer | Agent 主键。 |
| name | string | Agent 名称。 |
| position_ids | integer[] | 已绑定岗位 ID 列表。 |
| skill_codes | string[] | 已绑定技能编码列表。 |
| user_ids | integer[] | 已绑定员工 ID 列表。 |
| created_at | string | 创建时间,ISO 8601。 |
### A.3 详情响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| positions | object[] | 岗位对象列表,结构为 `{id, name}`。 |
| skills | object[] | 技能对象列表,结构为 `{skill_code, skill_name}`。 |
| users | object[] | 员工对象列表,结构为 `{user_id, user_name}`。 |
| session_count | integer | 当前 Agent 关联会话数量。 |
# 接口测试文档 — analytics
# 鎺ュ彛娴嬭瘯鏂囨。 鈥?analytics
---
## 1. 模块概览
## 1. 妯″潡姒傝
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 模块名称 | analytics |
| 模块说明 | 日志与埋点 — 会话日志查询、事件上传、统计报表、页面浏览/扫码/入群追踪 |
| 路由前缀 | `/api/v1/logs`, `/api/v1/analytics`, `/api/v1/agent-group/analytics` |
| 数据库表 | `conversation_logs`, `analytics_events`, `analytics_statistics`, `page_views`, `scan_events`, `group_join_events` |
| 外部依赖 | 无 |
| 妯″潡鍚嶇О | analytics |
| 妯″潡璇存槑 | 鏃ュ織涓庡煁鐐?鈥?浼氳瘽鏃ュ織鏌ヨ銆佷簨浠朵笂浼犮€佺粺璁℃姤琛ㄣ€侀〉闈㈡祻瑙?鎵爜/鍏ョ兢杩借釜 |
| 璺敱鍓嶇紑 | `/api/v1/logs`, `/api/v1/analytics`, `/api/v1/agent-group/analytics` |
| 鏁版嵁搴撹〃 | `conversation_logs`, `analytics_events`, `analytics_statistics`, `page_views`, `scan_events`, `group_join_events` |
| 澶栭儴渚濊禆 | 鏃?|
---
## 2. 接口列表
## 2. 鎺ュ彛鍒楄〃
| 序号 | 方法 | 路径 | 说明 |
| 搴忓彿 | 鏂规硶 | 璺緞 | 璇存槑 |
|------|------|------|------|
| 1 | GET | `/api/v1/logs/conversations` | 查询会话日志列表 |
| 2 | POST | `/api/v1/analytics/events` | 上传埋点事件 |
| 3 | GET | `/api/v1/analytics/statistics` | 获取统计报表 |
| 4 | POST | `/api/v1/agent-group/analytics/page-view` | 记录页面浏览 |
| 5 | POST | `/api/v1/agent-group/analytics/scan-event` | 记录扫码事件 |
| 6 | POST | `/api/v1/agent-group/analytics/group-join-success` | 记录入群事件 |
| 1 | GET | `/api/v1/logs/conversations` | 鏌ヨ浼氳瘽鏃ュ織鍒楄〃 |
| 2 | POST | `/api/v1/analytics/events` | 涓婁紶鍩嬬偣浜嬩欢 |
| 3 | GET | `/api/v1/analytics/statistics` | 鑾峰彇缁熻鎶ヨ〃 |
| 4 | POST | `/api/v1/agent-group/analytics/page-view` | 璁板綍椤甸潰娴忚 |
| 5 | POST | `/api/v1/agent-group/analytics/scan-event` | 璁板綍鎵爜浜嬩欢 |
| 6 | POST | `/api/v1/agent-group/analytics/group-join-success` | 璁板綍鍏ョ兢浜嬩欢 |
---
## 3. 接口详细说明
## 3. 鎺ュ彛璇︾粏璇存槑
### 3.1 查询会话日志列表
### 3.1 鏌ヨ浼氳瘽鏃ュ織鍒楄〃
**基本信息**
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/logs/conversations` |
| 说明 | 分页查询会话日志,支持多维度筛选 |
| Content-Type | 无 |
| 鏂规硶 | GET |
| 璺緞 | `/api/v1/logs/conversations` |
| 璇存槑 | 鍒嗛〉鏌ヨ浼氳瘽鏃ュ織锛屾敮鎸佸缁村害绛涢€?|
| Content-Type | 鏃?|
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| page | query | integer | 否 | 页码,默认1 |
| page_size | query | integer | 否 | 每页条数,默认20,上限100 |
| user_id | query | string | 否 | 按用户ID筛选 |
| agent_id | query | integer | 否 | 按Agent ID筛选 |
| intent_type | query | string | 否 | 按意图类型筛选 |
| time_start | query | datetime | 否 | 起始时间 |
| time_end | query | datetime | 否 | 结束时间 |
| has_error | query | boolean | 否 | 是否有错误 |
**响应参数**
| 字段路径 | 类型 | 说明 |
| page | query | integer | 鍚?| 椤电爜锛岄粯璁? |
| page_size | query | integer | 鍚?| 姣忛〉鏉℃暟锛岄粯璁?0锛屼笂闄?00 |
| user_id | query | string | 鍚?| 鎸夌敤鎴稩D绛涢€?|
| agent_id | query | integer | 鍚?| 鎸堿gent ID绛涢€?|
| intent_type | query | string | 鍚?| 鎸夋剰鍥剧被鍨嬬瓫閫?|
| time_start | query | datetime | 鍚?| 璧峰鏃堕棿 |
| time_end | query | datetime | 鍚?| 缁撴潫鏃堕棿 |
| has_error | query | boolean | 鍚?| 鏄惁鏈夐敊璇?|
**鍝嶅簲鍙傛暟**
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| total | integer | 总条数 |
| list | array | 日志列表 |
| list[].id | integer | 日志ID |
| list[].session_id | string | 会话ID |
| list[].user_id | string | 用户ID |
| total | integer | 鎬绘潯鏁?|
| list | array | 鏃ュ織鍒楄〃 |
| list[].id | integer | 鏃ュ織ID |
| list[].session_id | string | 浼氳瘽ID |
| list[].user_id | string | 鐢ㄦ埛ID |
| list[].agent_id | integer | Agent ID |
| list[].agent_name | string | Agent名称 |
| list[].query | string | 用户查询 |
| list[].response | string | Agent回复 |
| list[].intent | string | 意图 |
| list[].entities | object | 实体JSON |
| list[].processing_time_ms | integer | 处理耗时(ms) |
| list[].has_error | boolean | 是否有错误 |
| list[].created_at | string | 创建时间 |
**错误码**
| HTTP 状态码 | 触发条件 | 错误信息示例 |
| list[].agent_name | string | Agent鍚嶇О |
| list[].query | string | 鐢ㄦ埛鏌ヨ |
| list[].response | string | Agent鍥炲 |
| list[].intent | string | 鎰忓浘 |
| list[].entities | object | 瀹炰綋JSON |
| list[].processing_time_ms | integer | 澶勭悊鑰楁椂(ms) |
| list[].has_error | boolean | 鏄惁鏈夐敊璇?|
| list[].created_at | string | 鍒涘缓鏃堕棿 |
**閿欒鐮?*
| HTTP 鐘舵€佺爜 | 瑙﹀彂鏉′欢 | 閿欒淇℃伅绀轰緥 |
|-------------|----------|-------------|
| 无 | 空结果不报错,返回 total=0, list=[] | — |
| 鏃?| 绌虹粨鏋滀笉鎶ラ敊锛岃繑鍥?total=0, list=[] | 鈥?|
---
### 3.2 上传埋点事件
### 3.2 涓婁紶鍩嬬偣浜嬩欢
**基本信息**
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/analytics/events` |
| 说明 | 批量上传埋点事件 |
| 鏂规硶 | POST |
| 璺緞 | `/api/v1/analytics/events` |
| 璇存槑 | 鎵归噺涓婁紶鍩嬬偣浜嬩欢 |
| Content-Type | application/json |
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| events | body | array | 是 | 事件列表,至少1条 |
| events[].event_type | body | string | 是 | 事件类型,最长64字符 |
| events[].event_data | body | object | 否 | 事件数据 |
| events[].timestamp | body | datetime | 否 | 事件时间 |
| events | body | array | 鏄?| 浜嬩欢鍒楄〃锛岃嚦灏?鏉?|
| events[].event_type | body | string | 鏄?| 浜嬩欢绫诲瀷锛屾渶闀?4瀛楃 |
| events[].event_data | body | object | 鍚?| 浜嬩欢鏁版嵁 |
| events[].timestamp | body | datetime | 鍚?| 浜嬩欢鏃堕棿 |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| success | boolean | 是否成功 |
| received_count | integer | 接收事件数 |
| success | boolean | 鏄惁鎴愬姛 |
| received_count | integer | 鎺ユ敹浜嬩欢鏁?|
---
### 3.3 获取统计报表
### 3.3 鑾峰彇缁熻鎶ヨ〃
**基本信息**
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/analytics/statistics` |
| 说明 | 获取预聚合统计数据 |
| Content-Type | 无 |
| 鏂规硶 | GET |
| 璺緞 | `/api/v1/analytics/statistics` |
| 璇存槑 | 鑾峰彇棰勮仛鍚堢粺璁℃暟鎹?|
| Content-Type | 鏃?|
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| date_range | query | string | 否 | 日期范围,默认 `last_7_days` |
| group_by | query | string | 否 | 分组维度 |
| date_range | query | string | 鍚?| 鏃ユ湡鑼冨洿锛岄粯璁?`last_7_days` |
| group_by | query | string | 鍚?| 鍒嗙粍缁村害 |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| total_agent_calls | integer | Agent调用总数 |
| total_sessions | integer | 会话总数 |
| avg_session_turns | float | 平均会话轮次 |
| intent_distribution | array | 意图分布 |
| intent_distribution[].intent | string | 意图名 |
| intent_distribution[].count | integer | 数量 |
| intent_distribution[].percentage | float | 百分比 |
| agent_call_ranking | array | Agent调用排行 |
| total_agent_calls | integer | Agent璋冪敤鎬绘暟 |
| total_sessions | integer | 浼氳瘽鎬绘暟 |
| avg_session_turns | float | 骞冲潎浼氳瘽杞 |
| intent_distribution | array | 鎰忓浘鍒嗗竷 |
| intent_distribution[].intent | string | 鎰忓浘鍚?|
| intent_distribution[].count | integer | 鏁伴噺 |
| intent_distribution[].percentage | float | 鐧惧垎姣?|
| agent_call_ranking | array | Agent璋冪敤鎺掕 |
| agent_call_ranking[].agent_id | integer | Agent ID |
| agent_call_ranking[].agent_name | string | Agent名称 |
| agent_call_ranking[].call_count | integer | 调用次数 |
| daily_trend | array | 每日趋势 |
| daily_trend[].date | string | 日期 |
| daily_trend[].calls | integer | 调用数 |
| daily_trend[].sessions | integer | 会话数 |
| agent_call_ranking[].agent_name | string | Agent鍚嶇О |
| agent_call_ranking[].call_count | integer | 璋冪敤娆℃暟 |
| daily_trend | array | 姣忔棩瓒嬪娍 |
| daily_trend[].date | string | 鏃ユ湡 |
| daily_trend[].calls | integer | 璋冪敤鏁?|
| daily_trend[].sessions | integer | 浼氳瘽鏁?|
---
### 3.4 记录页面浏览
### 3.4 璁板綍椤甸潰娴忚
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/agent-group/analytics/page-view` |
| 鏂规硶 | POST |
| 璺緞 | `/api/v1/agent-group/analytics/page-view` |
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| page_type | body | string | 是 | 页面类型,最长64 |
| user_id | body | string | 否 | 用户ID |
| session_id | body | string | 否 | 会话ID |
| device_type | body | string | 否 | 设备类型 |
| page_type | body | string | 鏄?| 椤甸潰绫诲瀷锛屾渶闀?4 |
| user_id | body | string | 鍚?| 鐢ㄦ埛ID |
| session_id | body | string | 鍚?| 浼氳瘽ID |
| device_type | body | string | 鍚?| 璁惧绫诲瀷 |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| success | boolean | 是否成功 |
| success | boolean | 鏄惁鎴愬姛 |
---
### 3.5 记录扫码事件
### 3.5 璁板綍鎵爜浜嬩欢
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/agent-group/analytics/scan-event` |
| 鏂规硶 | POST |
| 璺緞 | `/api/v1/agent-group/analytics/scan-event` |
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| qrcode_id | body | integer | 否 | 活码ID |
| channel_code | body | string | 否 | 渠道编码 |
| customer_user_id | body | string | 否 | 客户用户ID |
| position_code | body | string | 否 | 岗位编码 |
| employee_id | body | string | 否 | 员工ID |
| qrcode_id | body | integer | 鍚?| 娲荤爜ID |
| channel_code | body | string | 鍚?| 娓犻亾缂栫爜 |
| customer_user_id | body | string | 鍚?| 瀹㈡埛鐢ㄦ埛ID |
| position_code | body | string | 鍚?| 宀椾綅缂栫爜 |
| employee_id | body | string | 鍚?| 鍛樺伐ID |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| success | boolean | 是否成功 |
| success | boolean | 鏄惁鎴愬姛 |
---
### 3.6 记录入群事件
### 3.6 璁板綍鍏ョ兢浜嬩欢
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/agent-group/analytics/group-join-success` |
| 鏂规硶 | POST |
| 璺緞 | `/api/v1/agent-group/analytics/group-join-success` |
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| group_id | body | string | 否 | 群ID |
| customer_user_id | body | string | 否 | 客户用户ID |
| employee_count | body | integer | 否 | 员工数,默认0 |
| agent_count | body | integer | 否 | Agent数,默认0 |
| channel_code | body | string | 否 | 渠道编码 |
| group_id | body | string | 鍚?| 缇D |
| customer_user_id | body | string | 鍚?| 瀹㈡埛鐢ㄦ埛ID |
| employee_count | body | integer | 鍚?| 鍛樺伐鏁帮紝榛樿0 |
| agent_count | body | integer | 鍚?| Agent鏁帮紝榛樿0 |
| channel_code | body | string | 鍚?| 娓犻亾缂栫爜 |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| success | boolean | 是否成功 |
| success | boolean | 鏄惁鎴愬姛 |
---
## 4. 测试场景
## 4. 娴嬭瘯鍦烘櫙
### 4.1 会话日志查询
### 4.1 浼氳瘽鏃ュ織鏌ヨ
| 序号 | 场景名称 | 分类 | 前置条件 | 请求参数 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 鍓嶇疆鏉′欢 | 璇锋眰鍙傛暟 | 棰勬湡缁撴灉 |
|------|----------|------|----------|----------|----------|
| 1 | 无筛选查询 | 正常 | DB有2条日志 | 无筛选 | total=2 |
| 2 | 按user_id筛选 | 正常 | 2条不同user_id | user_id="emp_001" | total=1 |
| 3 | 按agent_id筛选 | 正常 | 2条不同agent_id | agent_id=102 | total=1 |
| 4 | 按intent筛选 | 正常 | 2条不同intent | intent_type="query-metric" | total=1 |
| 5 | 按has_error筛选 | 正常 | 1条有错误 | has_error=True | total=1, items[0].has_error=True |
| 6 | 按时间范围筛选 | 正常 | 1条10天前+1条近期 | time_start/time_end近1天 | total=1 |
| 7 | 组合筛选 | 正常 | 3条不同组合数据 | user_id+intent_type | total=1 |
| 8 | 空结果 | 边界 | DB无数据 | 无筛选 | total=0, list=[] |
### 4.2 事件上传
| 序号 | 场景名称 | 分类 | 前置条件 | 请求参数 | 预期结果 |
| 1 | 鏃犵瓫閫夋煡璇?| 姝e父 | DB鏈?鏉℃棩蹇?| 鏃犵瓫閫?| total=2 |
| 2 | 鎸塽ser_id绛涢€?| 姝e父 | 2鏉′笉鍚寀ser_id | user_id="emp_001" | total=1 |
| 3 | 鎸塧gent_id绛涢€?| 姝e父 | 2鏉′笉鍚宎gent_id | agent_id=102 | total=1 |
| 4 | 鎸塱ntent绛涢€?| 姝e父 | 2鏉′笉鍚宨ntent | intent_type="query-metric" | total=1 |
| 5 | 鎸塰as_error绛涢€?| 姝e父 | 1鏉℃湁閿欒 | has_error=True | total=1, items[0].has_error=True |
| 6 | 鎸夋椂闂磋寖鍥寸瓫閫?| 姝e父 | 1鏉?0澶╁墠+1鏉¤繎鏈?| time_start/time_end杩?澶?| total=1 |
| 7 | 缁勫悎绛涢€?| 姝e父 | 3鏉′笉鍚岀粍鍚堟暟鎹?| user_id+intent_type | total=1 |
| 8 | 绌虹粨鏋?| 杈圭晫 | DB鏃犳暟鎹?| 鏃犵瓫閫?| total=0, list=[] |
### 4.2 浜嬩欢涓婁紶
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 鍓嶇疆鏉′欢 | 璇锋眰鍙傛暟 | 棰勬湡缁撴灉 |
|------|----------|------|----------|----------|----------|
| 1 | 单条事件 | 正常 | — | 1条event | success=True, received_count=1, DB count=1 |
| 2 | 批量事件 | 正常 | — | 3条events | received_count=3, DB count=3 |
| 3 | event_data存储为JSON | 正常 | — | event_data含多个字段 | DB中可按key读取 |
| 1 | 鍗曟潯浜嬩欢 | 姝e父 | 鈥?| 1鏉vent | success=True, received_count=1, DB count=1 |
| 2 | 鎵归噺浜嬩欢 | 姝e父 | 鈥?| 3鏉vents | received_count=3, DB count=3 |
| 3 | event_data瀛樺偍涓篔SON | 姝e父 | 鈥?| event_data鍚涓瓧娈?| DB涓彲鎸塳ey璇诲彇 |
### 4.3 统计报表
### 4.3 缁熻鎶ヨ〃
| 序号 | 场景名称 | 分类 | 前置条件 | 请求参数 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 鍓嶇疆鏉′欢 | 璇锋眰鍙傛暟 | 棰勬湡缁撴灉 |
|------|----------|------|----------|----------|----------|
| 1 | 有预聚合数据 | 正常 | 插入AnalyticsStatistic | date_range="last_7_days" | total_agent_calls=100, intent_distribution长度=1 |
| 2 | 空数据 | 边界 | DB无统计数据 | — | total_agent_calls=0, intent_distribution=[] |
| 1 | 鏈夐鑱氬悎鏁版嵁 | 姝e父 | 鎻掑叆AnalyticsStatistic | date_range="last_7_days" | total_agent_calls=100, intent_distribution闀垮害=1 |
| 2 | 绌烘暟鎹?| 杈圭晫 | DB鏃犵粺璁℃暟鎹?| 鈥?| total_agent_calls=0, intent_distribution=[] |
### 4.4 页面浏览追踪
### 4.4 椤甸潰娴忚杩借釜
| 序号 | 场景名称 | 分类 | 前置条件 | 请求参数 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 鍓嶇疆鏉′欢 | 璇锋眰鍙傛暟 | 棰勬湡缁撴灉 |
|------|----------|------|----------|----------|----------|
| 1 | 记录页面浏览 | 正常 | — | page_type, user_id, device_type | success=True, DB count=1 |
| 2 | 字段持久化 | 正常 | — | page_type="数据分析页" | DB中page_type正确 |
| 1 | 璁板綍椤甸潰娴忚 | 姝e父 | 鈥?| page_type, user_id, device_type | success=True, DB count=1 |
| 2 | 瀛楁鎸佷箙鍖?| 姝e父 | 鈥?| page_type="鏁版嵁鍒嗘瀽椤? | DB涓璸age_type姝g‘ |
### 4.5 扫码事件追踪
### 4.5 鎵爜浜嬩欢杩借釜
| 序号 | 场景名称 | 分类 | 前置条件 | 请求参数 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 鍓嶇疆鏉′欢 | 璇锋眰鍙傛暟 | 棰勬湡缁撴灉 |
|------|----------|------|----------|----------|----------|
| 1 | 记录扫码 | 正常 | — | qrcode_id, channel_code | success=True, DB count=1 |
| 2 | 字段正确 | 正常 | — | qrcode_id=5 | DB中qrcode_id=5 |
| 1 | 璁板綍鎵爜 | 姝e父 | 鈥?| qrcode_id, channel_code | success=True, DB count=1 |
| 2 | 瀛楁姝g‘ | 姝e父 | 鈥?| qrcode_id=5 | DB涓璹rcode_id=5 |
### 4.6 入群事件追踪
### 4.6 鍏ョ兢浜嬩欢杩借釜
| 序号 | 场景名称 | 分类 | 前置条件 | 请求参数 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 鍓嶇疆鏉′欢 | 璇锋眰鍙傛暟 | 棰勬湡缁撴灉 |
|------|----------|------|----------|----------|----------|
| 1 | 记录入群 | 正常 | — | group_id, employee_count, agent_count | success=True, DB count=1 |
| 2 | 字段正确 | 正常 | — | employee_count=3 | DB中字段正确 |
| 1 | 璁板綍鍏ョ兢 | 姝e父 | 鈥?| group_id, employee_count, agent_count | success=True, DB count=1 |
| 2 | 瀛楁姝g‘ | 姝e父 | 鈥?| employee_count=3 | DB涓瓧娈垫纭?|
### 4.7 扫码→入群转化集成
### 4.7 鎵爜鈫掑叆缇よ浆鍖栭泦鎴?
| 序号 | 场景名称 | 分类 | 前置条件 | 请求参数 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 鍓嶇疆鏉′欢 | 璇锋眰鍙傛暟 | 棰勬湡缁撴灉 |
|------|----------|------|----------|----------|----------|
| 1 | 同客户扫码后入群 | 集成 | — | scan + join 同一customer_user_id | 2条记录channel_code一致 |
| 1 | 鍚屽鎴锋壂鐮佸悗鍏ョ兢 | 闆嗘垚 | 鈥?| scan + join 鍚屼竴customer_user_id | 2鏉¤褰昪hannel_code涓€鑷?|
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_analytics_api.py`
娴嬭瘯鏂囦欢锛歚backend/tests/test_analytics_api.py`
| 测试类 | 测试方法 | 对应场景 |
| 娴嬭瘯绫?| 娴嬭瘯鏂规硶 | 瀵瑰簲鍦烘櫙 |
|--------|----------|----------|
| TestConversationLogQuery | test_list_no_filters | 4.1-1 |
| TestConversationLogQuery | test_filter_by_user_id | 4.1-2 |
......@@ -308,3 +308,56 @@
| TestGroupJoinEventTracking | test_record_group_join | 4.6-1 |
| TestGroupJoinEventTracking | test_group_join_fields | 4.6-2 |
| TestIntegrationScanToGroupJoin | test_scan_then_join_conversion | 4.7-1 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
# 接口测试文档 — customer-group
# 鎺ュ彛娴嬭瘯鏂囨。 鈥?customer-group
---
## 1. 模块概览
## 1. 妯″潡姒傝
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 模块名称 | customer-group |
| 模块说明 | 一客一群自动化 — 群创建、Agent入群、群解散、回调处理、幂等+分布式锁 |
| 路由前缀 | `/api/v1/agent-group` |
| 数据库表 | `customer_groups` |
| 外部依赖 | WeComGroupClient(企微建群API)、DistributedLock、IdempotencyStore |
| 妯″潡鍚嶇О | customer-group |
| 妯″潡璇存槑 | 涓€瀹竴缇よ嚜鍔ㄥ寲 鈥?缇ゅ垱寤恒€丄gent鍏ョ兢銆佺兢瑙f暎銆佸洖璋冨鐞嗐€佸箓绛?鍒嗗竷寮忛攣 |
| 璺敱鍓嶇紑 | `/api/v1/agent-group` |
| 鏁版嵁搴撹〃 | `customer_groups` |
| 澶栭儴渚濊禆 | WeComGroupClient锛堜紒寰缓缇PI锛夈€丏istributedLock銆両dempotencyStore |
---
## 2. 接口列表
## 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` | 成员退出回调 |
| 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. 鎺ュ彛璇︾粏璇存槑
### 3.1 创建一客一群
### 3.1 鍒涘缓涓€瀹竴缇?
**鍩烘湰淇℃伅**
**基本信息**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/agent-group/group/create` |
| 说明 | 为客户创建专属服务群,已存在活跃群时复用 |
| 鏂规硶 | 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列表 |
| customer_user_id | body | string | 鏄?| 瀹㈡埛浼佸井ID锛屾渶闀?4 |
| channel_code | body | string | 鏄?| 娓犻亾缂栫爜锛屾渶闀?28 |
| position_code | body | string | 鏄?| 宀椾綅缂栫爜锛屾渶闀?00 |
| employee_wechat_user_ids | body | string[] | 鏄?| 鍛樺伐浼佸井ID鍒楄〃锛岃嚦灏?浜?|
| 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 | 成员类型 |
| group_id | string | 缇D |
| group_name | string | 缇ゅ悕锛堟牸寮忥細"瀹㈡埛鏄电О 鐨勪笓灞炴湇鍔$兢"锛?|
| creator_employee_id | string | 鍒涘缓鑰呭憳宸D |
| created_at | string | 鍒涘缓鏃堕棿 |
| members | array | 鎴愬憳鍒楄〃 |
| members[].user_id | string | 鐢ㄦ埛ID |
| members[].name | string | 鐢ㄦ埛鍚?|
| members[].type | string | 鎴愬憳绫诲瀷 |
**成功响应示例**
**鎴愬姛鍝嶅簲绀轰緥**
```json
{
"group_id": "group_abc",
"group_name": "张先生 的专属服务群",
"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"}
{"user_id": "wo_external_123", "name": "寮犲厛鐢?, "type": "customer"},
{"user_id": "zhangsan", "name": "寮犱笁", "type": "employee"},
{"user_id": "lisi", "name": "鏉庡洓", "type": "employee"}
]
}
```
---
### 3.2 Agent加入群
**请求参数**
### 3.2 Agent鍔犲叆缇?
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| group_id | path | string | 是 | 群ID |
| agent_ids | body | integer[] | 是 | Agent ID列表,至少1个 |
| group_id | path | string | 鏄?| 缇D |
| agent_ids | body | integer[] | 鏄?| Agent ID鍒楄〃锛岃嚦灏?涓?|
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| success | boolean | 是否全部成功 |
| joined_agents | array | 成功加入的Agent列表 |
| success | boolean | 鏄惁鍏ㄩ儴鎴愬姛 |
| joined_agents | array | 鎴愬姛鍔犲叆鐨凙gent鍒楄〃 |
| joined_agents[].agent_id | integer | Agent ID |
| joined_agents[].agent_name | string | Agent名称 |
| failed_agents | array | 失败的Agent列表 |
| joined_agents[].agent_name | string | Agent鍚嶇О |
| failed_agents | array | 澶辫触鐨凙gent鍒楄〃 |
**错误码**
**閿欒鐮?*
| HTTP 状态码 | 触发条件 | 错误信息示例 |
| HTTP 鐘舵€佺爜 | 瑙﹀彂鏉′欢 | 閿欒淇℃伅绀轰緥 |
|-------------|----------|-------------|
| 404 | 群不存在 | 不存在 |
| 404 | 缇や笉瀛樺湪 | 涓嶅瓨鍦?|
---
### 3.3 查询群列表
### 3.3 鏌ヨ缇ゅ垪琛?
**璇锋眰鍙傛暟**
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| page | query | integer | 否 | 页码,默认1 |
| page_size | query | integer | 否 | 每页条数,默认20 |
| customer_user_id | query | string | 否 | 按客户筛选 |
| status | query | string | 否 | 按状态筛选:active / dissolved |
| page | query | integer | 鍚?| 椤电爜锛岄粯璁? |
| page_size | query | integer | 鍚?| 姣忛〉鏉℃暟锛岄粯璁?0 |
| 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列表 |
| total | integer | 鎬绘潯鏁?|
| list | array | 缇ゅ垪琛?|
| list[].group_id | string | 缇D |
| list[].group_name | string | 缇ゅ悕 |
| list[].status | string | 鐘舵€?|
| list[].customer_info | object | 瀹㈡埛淇℃伅 |
| list[].employee_list | array | 鍛樺伐鍒楄〃 |
| list[].agent_list | array | Agent鍒楄〃 |
---
### 3.4 扫码回调
### 3.4 鎵爜鍥炶皟
**基本信息**
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/agent-group/callback/scan` |
| 说明 | 企微扫码事件回调,幂等处理 |
| 鏂规硶 | POST |
| 璺緞 | `/api/v1/agent-group/callback/scan` |
| 璇存槑 | 浼佸井鎵爜浜嬩欢鍥炶皟锛屽箓绛夊鐞?|
| Content-Type | application/xml |
**响应**:XML 格式 `<Success>SUCCESS</Success>`
**鍝嶅簲**锛歑ML 鏍煎紡 `<Success>SUCCESS</Success>`
---
### 3.5 成员退出回调
**基本信息**
### 3.5 鎴愬憳閫€鍑哄洖璋?
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/agent-group/callback/member-exit` |
| 说明 | 企微成员退出回调,客户退出则自动解散群 |
| 鏂规硶 | POST |
| 璺緞 | `/api/v1/agent-group/callback/member-exit` |
| 璇存槑 | 浼佸井鎴愬憳閫€鍑哄洖璋冿紝瀹㈡埛閫€鍑哄垯鑷姩瑙f暎缇?|
| Content-Type | application/xml |
**逻辑**:is_customer=True → 解散群;is_customer=False → 不解散
**閫昏緫**锛歩s_customer=True 鈫?瑙f暎缇わ紱is_customer=False 鈫?涓嶈В鏁?
---
## 4. 测试场景
### 4.1 创建群
## 4. 娴嬭瘯鍦烘櫙
| 序号 | 场景名称 | 分类 | 预期结果 |
### 4.1 鍒涘缓缇?
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | 创建成功 | 正常 | group_id 非空,group_name 含"专属服务群",members=3 |
| 2 | 复用已有活跃群 | 正常 | 两次创建返回同一 group_id |
| 3 | 群名格式验证 | 正常 | group_name=="张先生 的专属服务群" |
| 1 | 鍒涘缓鎴愬姛 | 姝e父 | group_id 闈炵┖锛実roup_name 鍚?涓撳睘鏈嶅姟缇?锛宮embers=3 |
| 2 | 澶嶇敤宸叉湁娲昏穬缇?| 姝e父 | 涓ゆ鍒涘缓杩斿洖鍚屼竴 group_id |
| 3 | 缇ゅ悕鏍煎紡楠岃瘉 | 姝e父 | group_name=="寮犲厛鐢?鐨勪笓灞炴湇鍔$兢" |
### 4.2 Agent入群
### 4.2 Agent鍏ョ兢
| 序号 | 场景名称 | 分类 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | 全部成功 | 正常 | success=True, joined_agents=1, failed_agents=0 |
| 2 | 部分失败 | 异常 | success=False, failed_agents=1 |
| 3 | 群不存在 | 异常 | ValueError "不存在" |
### 4.3 解散群
| 1 | 鍏ㄩ儴鎴愬姛 | 姝e父 | success=True, joined_agents=1, failed_agents=0 |
| 2 | 閮ㄥ垎澶辫触 | 寮傚父 | success=False, failed_agents=1 |
| 3 | 缇や笉瀛樺湪 | 寮傚父 | ValueError "涓嶅瓨鍦? |
| 序号 | 场景名称 | 分类 | 预期结果 |
### 4.3 瑙f暎缇?
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | 解散成功 | 正常 | status=="dissolved", dissolved_at 非空 |
| 2 | 群不存在 | 异常 | ValueError |
| 3 | 重复解散 | 异常 | ValueError "已解散" |
| 1 | 瑙f暎鎴愬姛 | 姝e父 | status=="dissolved", dissolved_at 闈炵┖ |
| 2 | 缇や笉瀛樺湪 | 寮傚父 | ValueError |
| 3 | 閲嶅瑙f暎 | 寮傚父 | ValueError "宸茶В鏁? |
### 4.4 群列表
| 序号 | 场景名称 | 分类 | 预期结果 |
### 4.4 缇ゅ垪琛?
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | 查询全部 | 正常 | total=2 |
| 2 | 按状态筛选 | 正常 | status=active → 0; status=dissolved → 1 |
| 3 | 按客户筛选 | 正常 | total=1 |
| 4 | 空结果 | 边界 | total=0, list=[] |
### 4.5 幂等与分布式锁
| 1 | 鏌ヨ鍏ㄩ儴 | 姝e父 | total=2 |
| 2 | 鎸夌姸鎬佺瓫閫?| 姝e父 | status=active 鈫?0; status=dissolved 鈫?1 |
| 3 | 鎸夊鎴风瓫閫?| 姝e父 | total=1 |
| 4 | 绌虹粨鏋?| 杈圭晫 | total=0, list=[] |
| 序号 | 场景名称 | 预期结果 |
### 4.5 骞傜瓑涓庡垎甯冨紡閿?
| 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------|
| 1 | 幂等防重 | 同一 event_id 第二次 check_and_mark 返回 False |
| 2 | 锁获取释放 | acquire → True, release 后可再次 acquire |
| 1 | 骞傜瓑闃查噸 | 鍚屼竴 event_id 绗簩娆?check_and_mark 杩斿洖 False |
| 2 | 閿佽幏鍙栭噴鏀?| acquire 鈫?True, release 鍚庡彲鍐嶆 acquire |
### 4.6 回调处理
### 4.6 鍥炶皟澶勭悊
| 序号 | 场景名称 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------|
| 1 | 扫码回调 | 返回 "SUCCESS" |
| 2 | 扫码幂等 | 重复 event_id 仍返回 "SUCCESS" |
| 3 | 客户退群触发解散 | 群 status=="dissolved" |
| 4 | 员工退群不解散 | 群 status=="active" |
| 1 | 鎵爜鍥炶皟 | 杩斿洖 "SUCCESS" |
| 2 | 鎵爜骞傜瓑 | 閲嶅 event_id 浠嶈繑鍥?"SUCCESS" |
| 3 | 瀹㈡埛閫€缇よЕ鍙戣В鏁?| 缇?status=="dissolved" |
| 4 | 鍛樺伐閫€缇や笉瑙f暎 | 缇?status=="active" |
### 4.7 集成流程
### 4.7 闆嗘垚娴佺▼
| 序号 | 场景名称 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------|
| 1 | 扫码→建群→Agent入群→查询→退群解散 | 全流程通过 |
| 1 | 鎵爜鈫掑缓缇も啋Agent鍏ョ兢鈫掓煡璇⑩啋閫€缇よВ鏁?| 鍏ㄦ祦绋嬮€氳繃 |
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_customer_group_api.py`
娴嬭瘯鏂囦欢锛歚backend/tests/test_customer_group_api.py`
| 测试类 | 测试方法 | 对应场景 |
| 娴嬭瘯绫?| 娴嬭瘯鏂规硶 | 瀵瑰簲鍦烘櫙 |
|--------|----------|----------|
| TestCreateGroup | test_create_success | 4.1-1 |
| TestCreateGroup | test_create_reuse_existing_active_group | 4.1-2 |
......@@ -248,3 +239,56 @@
| 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 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
# 接口测试文档 — methodology
# 鎺ュ彛娴嬭瘯鏂囨。 鈥?methodology
---
## 1. 模块概览
## 1. 妯″潡姒傝
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 模块名称 | methodology |
| 模块说明 | 方法论展示配置管理 — 查询/保存方法论,步骤数4~10,序号连续 |
| 路由前缀 | `/api/v1/official-site/methodology` |
| 数据库表 | `official_site_methodology`, `official_site_methodology_steps` |
| 外部依赖 | H5CacheManager(缓存失效) |
| 妯″潡鍚嶇О | methodology |
| 妯″潡璇存槑 | 鏂规硶璁哄睍绀洪厤缃鐞?鈥?鏌ヨ/淇濆瓨鏂规硶璁猴紝姝ラ鏁?~10锛屽簭鍙疯繛缁?|
| 璺敱鍓嶇紑 | `/api/v1/official-site/methodology` |
| 鏁版嵁搴撹〃 | `official_site_methodology`, `official_site_methodology_steps` |
| 澶栭儴渚濊禆 | H5CacheManager锛堢紦瀛樺け鏁堬級 |
---
## 2. 接口列表
## 2. 鎺ュ彛鍒楄〃
| 序号 | 方法 | 路径 | 说明 |
| 搴忓彿 | 鏂规硶 | 璺緞 | 璇存槑 |
|------|------|------|------|
| 1 | GET | `/api/v1/official-site/methodology` | 查询方法论配置 |
| 2 | POST | `/api/v1/official-site/methodology` | 保存方法论配置 |
| 1 | GET | `/api/v1/official-site/methodology` | 鏌ヨ鏂规硶璁洪厤缃?|
| 2 | POST | `/api/v1/official-site/methodology` | 淇濆瓨鏂规硶璁洪厤缃?|
---
## 3. 接口详细说明
## 3. 鎺ュ彛璇︾粏璇存槑
### 3.1 查询方法论配置
### 3.1 鏌ヨ鏂规硶璁洪厤缃?
**基本信息**
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/official-site/methodology` |
| 说明 | 查询当前方法论配置,无数据时返回默认值 |
| 鏂规硶 | 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 | 更新时间 |
| 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 保存方法论配置
### 3.2 淇濆瓨鏂规硶璁洪厤缃?
**基本信息**
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/official-site/methodology` |
| 说明 | 保存/更新方法论配置,自动替换旧数据 |
| 鏂规硶 | 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 |
**响应参数**
| 字段路径 | 类型 | 说明 |
| display_status | body | string | 鍚?| 榛樿"enable" |
| main_title | body | string | 鏄?| 涓绘爣棰橈紝鏈€闀?00 |
| sub_title | body | string | 鏄?| 鍓爣棰橈紝鏈€闀?00 |
| steps | body | array | 鍚?| 姝ラ鍒楄〃锛屾暟閲?~10 |
| steps[].step_icon | body | string | 鏄?| 鍥炬爣URL锛屾渶闀?00 |
| steps[].step_name | body | string | 鏄?| 姝ラ鍚嶇О锛屾渶闀?0 |
| steps[].step_order | body | integer | 鏄?| 搴忓彿锛屼粠1寮€濮嬭繛缁?|
| steps[].step_image | body | string | 鏄?| 姝ラ鍥剧墖URL锛屾渶闀?00 |
**鍝嶅簲鍙傛暟**
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| config_id | integer | 配置ID,同一配置更新后 ID 不变 |
| updated_at | string | 更新时间 |
| config_id | integer | 閰嶇疆ID锛屽悓涓€閰嶇疆鏇存柊鍚?ID 涓嶅彉 |
| updated_at | string | 鏇存柊鏃堕棿 |
**错误码**
**閿欒鐮?*
| HTTP 状态码 | 触发条件 | 错误信息示例 |
| HTTP 鐘舵€佺爜 | 瑙﹀彂鏉′欢 | 閿欒淇℃伅绀轰緥 |
|-------------|----------|-------------|
| 400 | 步骤数 <4 或 >10 | "4.*10" |
| 400 | 步骤序号不连续 | "序号" |
| 400 | 步骤序号重复 | "序号" |
| 400 | 姝ラ鏁?<4 鎴?>10 | "4.*10" |
| 400 | 姝ラ搴忓彿涓嶈繛缁?| "搴忓彿" |
| 400 | 姝ラ搴忓彿閲嶅 | "搴忓彿" |
---
## 4. 测试场景
## 4. 娴嬭瘯鍦烘櫙
### 4.1 查询方法论
### 4.1 鏌ヨ鏂规硶璁?
| 序号 | 场景名称 | 分类 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | 空数据返回默认 | 正常 | config_id=0, main_title="方法论", steps=[] |
| 2 | 有数据正确返回 | 正常 | config_id>0, steps按step_order排序 |
| 3 | 步骤按序号排序 | 正常 | 乱序插入后返回有序 |
| 1 | 绌烘暟鎹繑鍥為粯璁?| 姝e父 | config_id=0, main_title="鏂规硶璁?, steps=[] |
| 2 | 鏈夋暟鎹纭繑鍥?| 姝e父 | config_id>0, steps鎸塻tep_order鎺掑簭 |
| 3 | 姝ラ鎸夊簭鍙锋帓搴?| 姝e父 | 涔卞簭鎻掑叆鍚庤繑鍥炴湁搴?|
### 4.2 保存方法论
### 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 |
| 1 | 鏂板缓鎴愬姛 | 姝e父 | config_id>0, 鏌ヨ纭4鏉℃楠?|
| 2 | 鏇存柊宸叉湁閰嶇疆 | 姝e父 | config_id涓嶅彉, main_title鏇存柊涓?鏂版爣棰?, steps=6鏉?|
| 3 | 姝ラ鏁颁笉瓒?<4) | 寮傚父 | ValueError 鍖归厤 "4.*10" |
| 4 | 姝ラ搴忓彿涓嶈繛缁?| 寮傚父 | ValueError 鍖归厤 "搴忓彿" |
| 5 | 姝ラ搴忓彿閲嶅 | 寮傚父 | ValueError 鍖归厤 "搴忓彿" |
| 6 | 淇濆瓨鍚庣紦瀛樺け鏁?| 姝e父 | cache.was_invalidated()==True |
### 4.3 集成流程
### 4.3 闆嗘垚娴佺▼
| 序号 | 场景名称 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------|
| 1 | 查询空→保存→查询有数据 | config_id从0变为>0, steps=4条, orders=[1,2,3,4] |
| 1 | 鏌ヨ绌衡啋淇濆瓨鈫掓煡璇㈡湁鏁版嵁 | config_id浠?鍙樹负>0, steps=4鏉? orders=[1,2,3,4] |
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_methodology_api.py`
娴嬭瘯鏂囦欢锛歚backend/tests/test_methodology_api.py`
| 测试类 | 测试方法 | 对应场景 |
| 娴嬭瘯绫?| 娴嬭瘯鏂规硶 | 瀵瑰簲鍦烘櫙 |
|--------|----------|----------|
| TestGetMethodology | test_query_empty_returns_default | 4.1-1 |
| TestGetMethodology | test_query_with_data | 4.1-2 |
......@@ -139,3 +139,56 @@
| TestSaveMethodology | test_step_order_duplicate | 4.2-5 |
| TestSaveMethodology | test_save_invalidates_cache | 4.2-6 |
| TestIntegrationFlow | test_query_save_query | 4.3-1 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
# 接口测试文档 — official-site-agent-display
# 鎺ュ彛娴嬭瘯鏂囨。 鈥?official-site-agent-display
---
## 1. 模块概览
## 1. 妯″潡姒傝
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 模块名称 | official-site-agent-display |
| 模块说明 | 官网Agent展示配置 — 可用Agent列表、配置保存、已配置列表、删除配置 |
| 路由前缀 | `/api/v1/official-site/tabs` |
| 数据库表 | `official_site_agent_display` |
| 外部依赖 | H5CacheManager(缓存失效) |
| 妯″潡鍚嶇О | official-site-agent-display |
| 妯″潡璇存槑 | 瀹樼綉Agent灞曠ず閰嶇疆 鈥?鍙敤Agent鍒楄〃銆侀厤缃繚瀛樸€佸凡閰嶇疆鍒楄〃銆佸垹闄ら厤缃?|
| 璺敱鍓嶇紑 | `/api/v1/official-site/tabs` |
| 鏁版嵁搴撹〃 | `official_site_agent_display` |
| 澶栭儴渚濊禆 | H5CacheManager锛堢紦瀛樺け鏁堬級 |
---
## 2. 接口列表
## 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配置 |
| 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` | 鏌ヨ宸查厤缃瓵gent鍒楄〃 |
| 4 | DELETE | `/api/v1/official-site/tabs/{tab_id}/agents/{agent_id}/config` | 鍒犻櫎Agent閰嶇疆 |
---
## 3. 接口详细说明
## 3. 鎺ュ彛璇︾粏璇存槑
### 3.1 查询可用Agent列表
### 3.1 鏌ヨ鍙敤Agent鍒楄〃
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/official-site/tabs/{tab_id}/agents/available` |
| 鏂规硶 | GET |
| 璺緞 | `/api/v1/official-site/tabs/{tab_id}/agents/available` |
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| tab_id | path | integer | 是 | Tab ID |
| tab_id | path | integer | 鏄?| Tab ID |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| tab_id | integer | Tab ID |
| position_name | string | 岗位名称 |
| qrcode_id | integer | 活码ID |
| available_agents | array | 可配置Agent列表(排除管家Agent) |
| position_name | string | 宀椾綅鍚嶇О |
| qrcode_id | integer | 娲荤爜ID |
| available_agents | array | 鍙厤缃瓵gent鍒楄〃锛堟帓闄ょ瀹禔gent锛?|
| 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信息 |
| 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 | 说明文本 |
| steward_agent.note | string | 璇存槑鏂囨湰 |
**错误码**
**閿欒鐮?*
| HTTP 状态码 | 触发条件 |
| HTTP 鐘舵€佺爜 | 瑙﹀彂鏉′欢 |
|-------------|----------|
| 404 | Tab不存在 |
| 404 | Tab涓嶅瓨鍦?|
---
### 3.2 保存Agent配置
### 3.2 淇濆瓨Agent閰嶇疆
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/official-site/tabs/{tab_id}/agents/{agent_id}/config` |
| 鏂规硶 | 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 |
**响应参数**
| 字段路径 | 类型 | 说明 |
| tab_id | path | integer | 鏄?| Tab ID |
| agent_id | path | integer | 鏄?| Agent ID |
| media_url | body | string | 鏄?| 绱犳潗URL锛屾渶闀?00 |
| media_type | body | string | 鏄?| 绱犳潗鏍煎紡锛歡if/mp4 |
| media_size | body | integer | 鍚?| 绱犳潗澶у皬(bytes) |
| speech_title | body | string | 鏄?| 璇濇湳鏍囬 |
| speech_content | body | string | 鏄?| 璇濇湳姝f枃 |
| display_status | body | string | 鍚?| 榛樿"enable" |
| sort_order | body | integer | 鍚?| 鎺掑簭锛岄粯璁? |
**鍝嶅簲鍙傛暟**
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| config_id | integer | 配置ID,更新时不变 |
| config_id | integer | 閰嶇疆ID锛屾洿鏂版椂涓嶅彉 |
| tab_id | integer | Tab ID |
| agent_id | integer | Agent ID |
| updated_at | string | 更新时间 |
| updated_at | string | 鏇存柊鏃堕棿 |
**错误码**
**閿欒鐮?*
| HTTP 状态码 | 触发条件 |
| HTTP 鐘舵€佺爜 | 瑙﹀彂鏉′欢 |
|-------------|----------|
| 400 | Agent不在可配置列表中 / 素材格式无效 / 素材过大 / 话术标题过长 |
| 404 | Tab不存在 |
| 400 | Agent涓嶅湪鍙厤缃垪琛ㄤ腑 / 绱犳潗鏍煎紡鏃犳晥 / 绱犳潗杩囧ぇ / 璇濇湳鏍囬杩囬暱 |
| 404 | Tab涓嶅瓨鍦?|
---
### 3.3 查询已配置Agent列表
### 3.3 鏌ヨ宸查厤缃瓵gent鍒楄〃
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/official-site/tabs/{tab_id}/agents/configured` |
| 鏂规硶 | 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 | array | 宸查厤缃瓵gent鍒楄〃锛屾寜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启用状态 |
| 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配置
### 3.4 鍒犻櫎Agent閰嶇疆
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | DELETE |
| 路径 | `/api/v1/official-site/tabs/{tab_id}/agents/{agent_id}/config` |
| 鏂规硶 | DELETE |
| 璺緞 | `/api/v1/official-site/tabs/{tab_id}/agents/{agent_id}/config` |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| success | boolean | 是否成功 |
| deleted_at | string | 删除时间 |
| success | boolean | 鏄惁鎴愬姛 |
| deleted_at | string | 鍒犻櫎鏃堕棿 |
**错误码**
**閿欒鐮?*
| HTTP 状态码 | 触发条件 |
| HTTP 鐘舵€佺爜 | 瑙﹀彂鏉′欢 |
|-------------|----------|
| 400/404 | 配置不存在 |
| 400/404 | 閰嶇疆涓嶅瓨鍦?|
---
## 4. 测试场景
## 4. 娴嬭瘯鍦烘櫙
### 4.1 可用Agent列表
### 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不存在" |
| 1 | 鎺掗櫎绠″Agent | steward.id 涓嶅湪 available_agents 鐨?agent_ids 涓?|
| 2 | 绠″Agent淇℃伅杩斿洖 | steward_agent 鍚?绠″" |
| 3 | is_configured鏍囪姝g‘ | 宸查厤缃殑agent is_configured=True |
| 4 | Tab涓嶅瓨鍦?| ValueError "Tab涓嶅瓨鍦? |
### 4.2 保存配置
### 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() |
| 1 | 鏂板缓鎴愬姛 | config_id>0 |
| 2 | 鏇存柊宸叉湁閰嶇疆 | config_id涓嶅彉锛孌B涓粎1鏉¤褰?|
| 3 | Agent涓嶅湪鍙厤缃垪琛?| ValueError "涓嶅湪鍙厤缃垪琛ㄤ腑" |
| 4 | 绱犳潗鏍煎紡鏃犳晥(png) | ValueError "绱犳潗鏍煎紡" |
| 5 | 绱犳潗杩囧ぇ | ValueError "澶у皬" |
| 6 | 璇濇湳鏍囬杩囬暱 | ValueError "璇濇湳" |
| 7 | 淇濆瓨鍚庣紦瀛樺け鏁?| cache.was_invalidated() |
### 4.3 已配置Agent列表
### 4.3 宸查厤缃瓵gent鍒楄〃
| 序号 | 场景名称 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------|
| 1 | 正常列出 | configured_agents 长度=1, agent_status="enable" |
| 2 | 按sort_order排序 | sort_order小的在前 |
| 3 | Tab不存在 | ValueError |
| 1 | 姝e父鍒楀嚭 | configured_agents 闀垮害=1, agent_status="enable" |
| 2 | 鎸塻ort_order鎺掑簭 | sort_order灏忕殑鍦ㄥ墠 |
| 3 | Tab涓嶅瓨鍦?| ValueError |
### 4.4 删除配置
### 4.4 鍒犻櫎閰嶇疆
| 序号 | 场景名称 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------|
| 1 | 删除成功 | success=True, DB中该配置已移除, Agent本身未删除 |
| 2 | 配置不存在 | ValueError "配置不存在" |
| 3 | 删除后缓存失效 | cache.was_invalidated() |
| 1 | 鍒犻櫎鎴愬姛 | success=True, DB涓閰嶇疆宸茬Щ闄? Agent鏈韩鏈垹闄?|
| 2 | 閰嶇疆涓嶅瓨鍦?| ValueError "閰嶇疆涓嶅瓨鍦? |
| 3 | 鍒犻櫎鍚庣紦瀛樺け鏁?| cache.was_invalidated() |
### 4.5 集成流程
### 4.5 闆嗘垚娴佺▼
| 序号 | 场景名称 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------|
| 1 | 查可用→保存→查已配置→删除→查已配置空 | 全流程通过 |
| 1 | 鏌ュ彲鐢ㄢ啋淇濆瓨鈫掓煡宸查厤缃啋鍒犻櫎鈫掓煡宸查厤缃┖ | 鍏ㄦ祦绋嬮€氳繃 |
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_official_site_agent_display_api.py`
娴嬭瘯鏂囦欢锛歚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 |
......@@ -220,3 +220,56 @@
| TestDeleteAgentConfig | test_config_not_found | 4.4-2 |
| TestDeleteAgentConfig | test_delete_invalidates_cache | 4.4-3 |
| TestIntegrationFlow | test_full_flow | 4.5-1 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
# 接口测试文档 — official-site-home
# 鎺ュ彛娴嬭瘯鏂囨。 鈥?official-site-home
---
## 1. 模块概览
## 1. 妯″潡姒傝
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 模块名称 | official-site-home |
| 模块说明 | H5首页聚合接口 — 一次返回Tab+Agent+方法论+缓存 |
| 路由前缀 | `/api/v1/official-site/home` |
| 数据库表 | `official_tabs`, `official_site_agent_display`, `official_site_methodology` 等 |
| 外部依赖 | H5CacheManager(TTL缓存) |
| 妯″潡鍚嶇О | official-site-home |
| 妯″潡璇存槑 | H5棣栭〉鑱氬悎鎺ュ彛 鈥?涓€娆¤繑鍥濼ab+Agent+鏂规硶璁?缂撳瓨 |
| 璺敱鍓嶇紑 | `/api/v1/official-site/home` |
| 鏁版嵁搴撹〃 | `official_tabs`, `official_site_agent_display`, `official_site_methodology` 绛?|
| 澶栭儴渚濊禆 | H5CacheManager锛圱TL缂撳瓨锛?|
---
## 2. 接口列表
## 2. 鎺ュ彛鍒楄〃
| 序号 | 方法 | 路径 | 说明 |
| 搴忓彿 | 鏂规硶 | 璺緞 | 璇存槑 |
|------|------|------|------|
| 1 | GET | `/api/v1/official-site/home` | 获取H5首页数据 |
| 1 | GET | `/api/v1/official-site/home` | 鑾峰彇H5棣栭〉鏁版嵁 |
---
## 3. 接口详细说明
## 3. 鎺ュ彛璇︾粏璇存槑
### 3.1 获取H5首页数据
### 3.1 鑾峰彇H5棣栭〉鏁版嵁
**基本信息**
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/official-site/home` |
| 说明 | 聚合Tab、Agent展示、方法论数据,支持缓存(TTL=300s) |
| 鏂规硶 | GET |
| 璺緞 | `/api/v1/official-site/home` |
| 璇存槑 | 鑱氬悎Tab銆丄gent灞曠ず銆佹柟娉曡鏁版嵁锛屾敮鎸佺紦瀛?TTL=300s) |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| site_title | string | 站点标题 |
| site_subtitle | string | 站点副标题 |
| background_image | string | 背景图 |
| tabs | array | Tab列表 |
| 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[].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 | 方法论 |
| tabs[].agents[].agent_name | string | Agent鍚嶇О |
| tabs[].agents[].media_url | string | 绱犳潗URL |
| tabs[].agents[].speech_title | string | 璇濇湳鏍囬 |
| tabs[].agents[].speech_content | string | 璇濇湳姝f枃 |
| methodology | object | 鏂规硶璁?|
| methodology.display_status | string | enable/disable |
| methodology.main_title | string | 主标题 |
| methodology.sub_title | string | 副标题 |
| methodology.steps | array | 步骤列表 |
| methodology.main_title | string | 涓绘爣棰?|
| methodology.sub_title | string | 鍓爣棰?|
| methodology.steps | array | 姝ラ鍒楄〃 |
**过滤规则**:disable的Tab不返回,disable的Agent配置不返回,Agent本身disable也不返回
**杩囨护瑙勫垯**锛歞isable鐨凾ab涓嶈繑鍥烇紝disable鐨凙gent閰嶇疆涓嶈繑鍥烇紝Agent鏈韩disable涔熶笉杩斿洖
---
## 4. 测试场景
## 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" |
| 1 | 缂撳瓨鏈懡涓粠DB鏋勫缓 | 姝e父 | site_title闈炵┖锛宼abs鏈?鏉★紝agents鏈?鏉?|
| 2 | 缂撳瓨鍛戒腑杩斿洖缂撳瓨鏁版嵁 | 姝e父 | DB淇敼鍚庝粛杩斿洖鏃ф暟鎹?|
| 3 | disable鐨凾ab涓嶈繑鍥?| 姝e父 | tabs闀垮害=0 |
| 4 | disable鐨凙gent閰嶇疆涓嶈繑鍥?| 姝e父 | tabs鏈?鏉′絾agents涓虹┖ |
| 5 | Agent鏈韩disable涓嶈繑鍥?| 姝e父 | agents涓虹┖ |
| 6 | sort_order鎺掑簭 | 姝e父 | sort_order灏忕殑Agent鍦ㄥ墠 |
| 7 | 缂撳瓨鏈懡涓椂鍐欏叆 | 姝e父 | cache.get_home_page()闈炵┖ |
| 8 | 缂撳瓨澶辨晥鍚庡埛鏂?| 姝e父 | 淇敼Agent鍚嶅悗invalidate鍐嶆煡锛岃繑鍥炴柊鍚嶇О |
| 9 | 鏂规硶璁烘暟鎹繑鍥?| 姝e父 | methodology.display_status="enable", steps=2 |
| 10 | 绌虹珯鐐?| 杈圭晫 | tabs=[], methodology.display_status="disable" |
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_official_site_home_api.py`
娴嬭瘯鏂囦欢锛歚backend/tests/test_official_site_home_api.py`
| 测试方法 | 对应场景 |
| 娴嬭瘯鏂规硶 | 瀵瑰簲鍦烘櫙 |
|----------|----------|
| test_cache_miss_builds_from_db | 1 |
| test_cache_hit_returns_cached_data | 2 |
......@@ -95,3 +95,56 @@
| test_cache_invalidate_then_refresh | 8 |
| test_methodology_returned | 9 |
| test_empty_site | 10 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
# 接口测试文档 — official-site-tab
# 鎺ュ彛娴嬭瘯鏂囨。 鈥?official-site-tab
---
## 1. 模块概览
## 1. 妯″潡姒傝
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 模块名称 | official-site-tab |
| 模块说明 | 官网岗位Tab配置 — Tab增删改查 + 状态切换 + 可用活码列表 |
| 路由前缀 | `/api/v1/official-site/tabs` |
| 数据库表 | `official_tabs` |
| 外部依赖 | H5CacheManager(缓存失效) |
| 妯″潡鍚嶇О | official-site-tab |
| 妯″潡璇存槑 | 瀹樼綉宀椾綅Tab閰嶇疆 鈥?Tab澧炲垹鏀规煡 + 鐘舵€佸垏鎹?+ 鍙敤娲荤爜鍒楄〃 |
| 璺敱鍓嶇紑 | `/api/v1/official-site/tabs` |
| 鏁版嵁搴撹〃 | `official_tabs` |
| 澶栭儴渚濊禆 | H5CacheManager锛堢紦瀛樺け鏁堬級 |
---
## 2. 接口列表
## 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` | 查询可用活码列表 |
| 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. 鎺ュ彛璇︾粏璇存槑
### 3.1 创建Tab
### 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 |
| position_code | body | string | 鏄?| 宀椾綅缂栫爜 |
| position_name | body | string | 鏄?| 宀椾綅鍚嶇О |
| qrcode_id | body | integer | 鏄?| 娲荤爜ID |
| display_status | body | string | 鍚?| enable/disable锛岄粯璁nable |
| sort_order | body | integer | 鍚?| 鎺掑簭锛岄粯璁? |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| tab_id | integer | Tab ID |
| position_code | string | 岗位编码 |
| position_name | string | 岗位名称 |
| qrcode_id | integer | 活码ID |
| created_at | string | 创建时间 |
| position_code | string | 宀椾綅缂栫爜 |
| position_name | string | 宀椾綅鍚嶇О |
| qrcode_id | integer | 娲荤爜ID |
| created_at | string | 鍒涘缓鏃堕棿 |
**错误码**
**閿欒鐮?*
| HTTP 状态码 | 触发条件 |
| HTTP 鐘舵€佺爜 | 瑙﹀彂鏉′欢 |
|-------------|----------|
| 400 | 岗位不存在 / 活码已停用 |
| 400 | 宀椾綅涓嶅瓨鍦?/ 娲荤爜宸插仠鐢?|
---
### 3.2 更新Tab
### 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 | 否 | 排序 |
| 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 | 更新时间 |
| success | boolean | 鏄惁鎴愬姛 |
| updated_at | string | 鏇存柊鏃堕棿 |
---
### 3.3 删除Tab
### 3.3 鍒犻櫎Tab
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| success | boolean | 是否成功 |
| deleted_at | string | 删除时间 |
| cleaned_agent_configs | integer | 清理的Agent配置数 |
| success | boolean | 鏄惁鎴愬姛 |
| deleted_at | string | 鍒犻櫎鏃堕棿 |
| cleaned_agent_configs | integer | 娓呯悊鐨凙gent閰嶇疆鏁?|
---
### 3.4 更新Tab状态
### 3.4 鏇存柊Tab鐘舵€?
**璇锋眰鍙傛暟**
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| display_status | body | string | 是 | enable/disable |
| reason | body | string | 否 | 原因 |
| display_status | body | string | 鏄?| enable/disable |
| reason | body | string | 鍚?| 鍘熷洜 |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| success | boolean | 是否成功 |
| previous_status | string | 变更前状态 |
| updated_at | string | 更新时间 |
| success | boolean | 鏄惁鎴愬姛 |
| previous_status | string | 鍙樻洿鍓嶇姸鎬?|
| updated_at | string | 鏇存柊鏃堕棿 |
---
### 3.5 分页查询Tab列表
### 3.5 鍒嗛〉鏌ヨTab鍒楄〃
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| page | query | integer | 否 | 默认1 |
| page_size | query | integer | 否 | 默认20 |
| keyword | query | string | 否 | 搜索关键词 |
| display_status | query | string | 否 | 按状态筛选 |
| page | query | integer | 鍚?| 榛樿1 |
| page_size | query | integer | 鍚?| 榛樿20 |
| keyword | query | string | 鍚?| 鎼滅储鍏抽敭璇?|
| display_status | query | string | 鍚?| 鎸夌姸鎬佺瓫閫?|
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| total | integer | 总条数 |
| list | array | Tab列表 |
| 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数量 |
| list[].position_name | string | 宀椾綅鍚嶇О |
| list[].display_status | string | 鐘舵€?|
| list[].sort_order | integer | 鎺掑簭 |
| list[].agent_count | integer | Agent鏁伴噺 |
---
### 3.6 查询可用活码列表
### 3.6 鏌ヨ鍙敤娲荤爜鍒楄〃
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| position_code | query | string | 否 | 按岗位筛选 |
| position_code | query | string | 鍚?| 鎸夊矖浣嶇瓫閫?|
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| list | array | 活码列表 |
| list[].qrcode_id | integer | 活码ID |
| list[].channel_code | string | 渠道编码 |
| list[].employee_name | string | 员工姓名 |
| list[].status | string | 状态 |
| list | array | 娲荤爜鍒楄〃 |
| list[].qrcode_id | integer | 娲荤爜ID |
| list[].channel_code | string | 娓犻亾缂栫爜 |
| list[].employee_name | string | 鍛樺伐濮撳悕 |
| list[].status | string | 鐘舵€?|
---
## 4. 测试场景
## 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 | 集成流程 | 集成 | 创建→列表→更新→状态→删除 全通过 |
| 1 | 鍒涘缓鎴愬姛 | 姝e父 | tab_id>0, position_code姝g‘ |
| 2 | 宀椾綅涓嶅瓨鍦?| 寮傚父 | ValueError "宀椾綅涓嶅瓨鍦? |
| 3 | 娲荤爜宸插仠鐢?| 寮傚父 | ValueError "娲荤爜.*鍋滅敤" |
| 4 | 鍒涘缓鍚庣紦瀛樺け鏁?| 姝e父 | cache.was_invalidated() |
| 5 | 鏇存柊鎴愬姛 | 姝e父 | success=True |
| 6 | 鏇存柊涓嶅瓨鍦═ab | 寮傚父 | ValueError "涓嶅瓨鍦? |
| 7 | 鏇存柊鍚庣紦瀛樺け鏁?| 姝e父 | cache.was_invalidated() |
| 8 | 鍒犻櫎鎴愬姛锛堣蒋鍒犻櫎锛?| 姝e父 | success=True, deleted_at闈炵┖, DB涓璬eleted_at闈炵┖ |
| 9 | 鍒犻櫎涓嶅瓨鍦═ab | 寮傚父 | ValueError |
| 10 | 鍒犻櫎鍚庣紦瀛樺け鏁?| 姝e父 | cache.was_invalidated() |
| 11 | 绂佺敤Tab | 姝e父 | success=True, previous_status="enable" |
| 12 | 鍚敤Tab | 姝e父 | previous_status="disable" |
| 13 | 鐘舵€佸彉鏇翠笉褰卞搷娲荤爜 | 姝e父 | qr.status浠嶄负"enable" |
| 14 | 鏌ヨ鍏ㄩ儴 | 姝e父 | total=2, 鎸塻ort_order鎺掑簭 |
| 15 | 鎸夌姸鎬佺瓫閫?| 姝e父 | enable鈫?, disable鈫? |
| 16 | 鍏抽敭璇嶆悳绱?| 姝e父 | keyword="椹诲簵" 鈫?total=1 |
| 17 | 鍙敤娲荤爜鍒楄〃 | 姝e父 | 浠呰繑鍥瀍nable鐘舵€佺殑娲荤爜 |
| 18 | 鎸夊矖浣嶇瓫閫夋椿鐮?| 姝e父 | 浠呰繑鍥炴寚瀹氬矖浣嶆椿鐮?|
| 19 | 闆嗘垚娴佺▼ | 闆嗘垚 | 鍒涘缓鈫掑垪琛ㄢ啋鏇存柊鈫掔姸鎬佲啋鍒犻櫎 鍏ㄩ€氳繃 |
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_official_site_tab_api.py`
娴嬭瘯鏂囦欢锛歚backend/tests/test_official_site_tab_api.py`
| 测试类 | 测试方法 | 对应场景 |
| 娴嬭瘯绫?| 娴嬭瘯鏂规硶 | 瀵瑰簲鍦烘櫙 |
|--------|----------|----------|
| TestCreateTab | test_create_success | 1 |
| TestCreateTab | test_create_position_not_found | 2 |
......@@ -207,3 +206,56 @@
| TestAvailableQrcodes | test_list_available | 17 |
| TestAvailableQrcodes | test_list_available_by_position | 18 |
| TestIntegrationFlow | test_create_list_update_status_delete | 19 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
# 接口测试文档 — official-site-upload
# 鎺ュ彛娴嬭瘯鏂囨。 鈥?official-site-upload
---
## 1. 模块概览
## 1. 妯″潡姒傝
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 模块名称 | official-site-upload |
| 模块说明 | 官网素材上传 — 格式/大小校验 + OSS存储 + 图片宽高解析 + CDN URL |
| 路由前缀 | `/api/v1/official-site/upload` |
| 数据库表 | 无 |
| 外部依赖 | OSSClient(对象存储) |
| 妯″潡鍚嶇О | official-site-upload |
| 妯″潡璇存槑 | 瀹樼綉绱犳潗涓婁紶 鈥?鏍煎紡/澶у皬鏍¢獙 + OSS瀛樺偍 + 鍥剧墖瀹介珮瑙f瀽 + CDN URL |
| 璺敱鍓嶇紑 | `/api/v1/official-site/upload` |
| 鏁版嵁搴撹〃 | 鏃?|
| 澶栭儴渚濊禆 | OSSClient锛堝璞″瓨鍌級 |
---
## 2. 接口列表
## 2. 鎺ュ彛鍒楄〃
| 序号 | 方法 | 路径 | 说明 |
| 搴忓彿 | 鏂规硶 | 璺緞 | 璇存槑 |
|------|------|------|------|
| 1 | POST | `/api/v1/official-site/upload` | 上传素材文件 |
| 1 | POST | `/api/v1/official-site/upload` | 涓婁紶绱犳潗鏂囦欢 |
---
## 3. 接口详细说明
## 3. 鎺ュ彛璇︾粏璇存槑
### 3.1 上传素材文件
### 3.1 涓婁紶绱犳潗鏂囦欢
**基本信息**
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/official-site/upload` |
| 说明 | 上传Agent素材或方法论图片,支持 gif/mp4/png/jpg |
| 鏂规硶 | 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 | form | string | 鏄?| 鐢ㄩ€旂被鍨嬶細agent_media / methodology_icon / methodology_image |
| file | form | file | 鏄?| 涓婁紶鏂囦欢 |
**usage_type 对应校验规则**
**usage_type 瀵瑰簲鏍¢獙瑙勫垯**
| usage_type | 允许格式 | 大小限制 | 解析宽高 |
| usage_type | 鍏佽鏍煎紡 | 澶у皬闄愬埗 | 瑙f瀽瀹介珮 |
|------------|----------|----------|----------|
| agent_media | gif, mp4 | 20MB | 否 |
| methodology_icon | png, jpg | 2MB | 是 |
| methodology_image | png, jpg | 2MB | 是 |
| 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` |
| file_url | string | OSS瀛樺偍璺緞 |
| file_type | string | 鏂囦欢鏍煎紡(gif/mp4/png/jpg) |
| file_size | integer | 鏂囦欢澶у皬(bytes) |
| width | integer | 鍥剧墖瀹藉害锛岄潪鍥剧墖涓簄ull |
| height | integer | 鍥剧墖楂樺害锛岄潪鍥剧墖涓簄ull |
| cdn_url | string | CDN璁块棶URL锛屽惈鐗堟湰鍙?`?v=2026` |
**成功响应示例**
**鎴愬姛鍝嶅簲绀轰緥**
```json
{
......@@ -74,37 +74,37 @@
}
```
**错误码**
**閿欒鐮?*
| HTTP 状态码 | 触发条件 |
| HTTP 鐘舵€佺爜 | 瑙﹀彂鏉′欢 |
|-------------|----------|
| 400 | 文件格式不支持 / 文件过大 / usage_type无效 |
| 400 | 鏂囦欢鏍煎紡涓嶆敮鎸?/ 鏂囦欢杩囧ぇ / usage_type鏃犳晥 |
---
## 4. 测试场景
## 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客户端可读取已上传文件 |
| 1 | Agent绱犳潗gif涓婁紶 | 姝e父 | file_type="gif", file_url鍚?agent/", cdn_url鍚??v=" |
| 2 | Agent绱犳潗mp4涓婁紶 | 姝e父 | file_type="mp4", width/height涓簄ull |
| 3 | 鏂规硶璁哄浘鏍噋ng涓婁紶 | 姝e父 | file_type="png", file_url鍚?methodology/icon/", width=200, height=200 |
| 4 | 鏂规硶璁哄浘鐗噅pg涓婁紶 | 姝e父 | file_type="jpg", file_url鍚?methodology/image/", width=800, height=600 |
| 5 | 鏍煎紡涓嶆敮鎸?pdf) | 寮傚父 | ValueError "鏍煎紡" |
| 6 | Agent绱犳潗瓒?0MB | 寮傚父 | ValueError "20MB" |
| 7 | 鏂规硶璁哄浘鏍囪秴2MB | 寮傚父 | ValueError "2MB" |
| 8 | CDN URL鍚増鏈彿 | 姝e父 | cdn_url鍚??v=2026" |
| 9 | 闈炲浘鐗囨棤瀹介珮 | 姝e父 | mp4鐨剋idth/height涓簄ull |
| 10 | 鏃犳晥usage_type | 寮傚父 | ValueError "绫诲瀷" |
| 11 | OSS闆嗘垚楠岃瘉 | 姝e父 | 閫氳繃OSS瀹㈡埛绔彲璇诲彇宸蹭笂浼犳枃浠?|
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_official_site_upload_api.py`
娴嬭瘯鏂囦欢锛歚backend/tests/test_official_site_upload_api.py`
| 测试方法 | 对应场景 |
| 娴嬭瘯鏂规硶 | 瀵瑰簲鍦烘櫙 |
|----------|----------|
| test_agent_media_gif_success | 1 |
| test_agent_media_mp4_success | 2 |
......@@ -117,3 +117,56 @@
| test_width_height_optional_for_non_image | 9 |
| test_invalid_usage_type | 10 |
| test_oss_upload_integration | 11 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
# 接口测试文档 — position-tag
# 鎺ュ彛娴嬭瘯鏂囨。 鈥?position-tag
---
## 1. 模块概览
## 1. 妯″潡姒傝
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 模块名称 | position-tag |
| 模块说明 | 岗位标签管理 — 增删改查 + 引用检测 + Agent统计 |
| 路由前缀 | `/api/v1/position-tags` |
| 数据库表 | `position_tags` |
| 外部依赖 | 无 |
| 妯″潡鍚嶇О | position-tag |
| 妯″潡璇存槑 | 宀椾綅鏍囩绠$悊 鈥?澧炲垹鏀规煡 + 寮曠敤妫€娴?+ Agent缁熻 |
| 璺敱鍓嶇紑 | `/api/v1/position-tags` |
| 鏁版嵁搴撹〃 | `position_tags` |
| 澶栭儴渚濊禆 | 鏃?|
---
## 2. 接口列表
## 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统计 |
| 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. 鎺ュ彛璇︾粏璇存槑
### 3.1 创建岗位标签
### 3.1 鍒涘缓宀椾綅鏍囩
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| name | body | string | 是 | 名称,最长20 |
| code | body | string | 是 | 编码,格式 `[a-zA-Z_][a-zA-Z0-9_]*`,唯一 |
| description | body | string | 否 | 描述,最长100 |
| name | body | string | 鏄?| 鍚嶇О锛屾渶闀?0 |
| code | body | string | 鏄?| 缂栫爜锛屾牸寮?`[a-zA-Z_][a-zA-Z0-9_]*`锛屽敮涓€ |
| description | body | string | 鍚?| 鎻忚堪锛屾渶闀?00 |
**错误码**
**閿欒鐮?*
| HTTP 状态码 | 触发条件 |
| HTTP 鐘舵€佺爜 | 瑙﹀彂鏉′欢 |
|-------------|----------|
| 409 | code已存在 |
| 422 | code格式不合法 |
| 409 | code宸插瓨鍦?|
| 422 | code鏍煎紡涓嶅悎娉?|
---
### 3.2 更新岗位标签
### 3.2 鏇存柊宀椾綅鏍囩
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| name | body | string | 是 | 名称 |
| description | body | string | 否 | 描述 |
| name | body | string | 鏄?| 鍚嶇О |
| description | body | string | 鍚?| 鎻忚堪 |
**错误码**
**閿欒鐮?*
| HTTP 状态码 | 触发条件 |
| HTTP 鐘舵€佺爜 | 瑙﹀彂鏉′欢 |
|-------------|----------|
| 404 | 标签不存在 |
| 404 | 鏍囩涓嶅瓨鍦?|
---
### 3.3 引用检测
### 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)
| 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锛涗粎鏈塧gent寮曠敤 鈫?can_delete=True锛堥渶confirm_detach锛?
---
### 3.4 删除岗位标签
### 3.4 鍒犻櫎宀椾綅鏍囩
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| tag_id | path | integer | 是 | 标签ID |
| confirm_detach_agents | query | boolean | 否 | 确认解除Agent关联,默认false |
| tag_id | path | integer | 鏄?| 鏍囩ID |
| confirm_detach_agents | query | boolean | 鍚?| 纭瑙i櫎Agent鍏宠仈锛岄粯璁alse |
**错误码**
**閿欒鐮?*
| HTTP 状态码 | 触发条件 |
| HTTP 鐘舵€佺爜 | 瑙﹀彂鏉′欢 |
|-------------|----------|
| 409 | 有阻塞性引用 / 有Agent引用但未confirm |
| 404 | 标签不存在 |
| 409 | 鏈夐樆濉炴€у紩鐢?/ 鏈堿gent寮曠敤浣嗘湭confirm |
| 404 | 鏍囩涓嶅瓨鍦?|
---
### 3.5 分页查询
### 3.5 鍒嗛〉鏌ヨ
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| page | query | integer | 否 | 默认1 |
| page_size | query | integer | 否 | 默认20 |
| keyword | query | string | 否 | 搜索名称或编码 |
| page | query | integer | 鍚?| 榛樿1 |
| page_size | query | integer | 鍚?| 榛樿20 |
| keyword | query | string | 鍚?| 鎼滅储鍚嶇О鎴栫紪鐮?|
---
### 3.6 Agent统计
### 3.6 Agent缁熻
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| position_id | integer | 岗位ID |
| agent_count | integer | Agent总数 |
| active_agent_count | integer | 启用Agent数 |
| agents | array | 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状态 |
| agents[].name | string | Agent鍚嶇О |
| agents[].status | string | Agent鐘舵€?|
---
## 4. 测试场景
## 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 |
| 1 | 鍒涘缓鎴愬姛 | 姝e父 | HTTP 201, name/code姝g‘ |
| 2 | code閲嶅杩斿洖409 | 寮傚父 | HTTP 409 |
| 3 | code鏍煎紡涓嶅悎娉曡繑鍥?22 | 寮傚父 | HTTP 422 |
| 4 | 鏇存柊鎴愬姛 | 姝e父 | name鏇存柊, code涓嶅彉 |
| 5 | 鏇存柊涓嶅瓨鍦ㄨ繑鍥?04 | 寮傚父 | HTTP 404 |
| 6 | 鏃犲紩鐢ㄥ彲鍒犻櫎 | 姝e父 | can_delete=True |
| 7 | 娲荤爜闃诲寮曠敤 | 姝e父 | can_delete=False, blocking鍚玵rcode_channel |
| 8 | Tab闃诲寮曠敤 | 姝e父 | can_delete=False, blocking鍚玱fficial_tab |
| 9 | Agent鍙В闄ゅ紩鐢?| 姝e父 | can_delete=True, detachable鍚玜gent |
| 10 | 寮曠敤妫€娴嬩笉瀛樺湪 | 寮傚父 | HTTP 404 |
| 11 | 鏃犲紩鐢ㄥ垹闄ゆ垚鍔?| 姝e父 | HTTP 200 |
| 12 | 闃诲寮曠敤鍒犻櫎杩斿洖409 | 寮傚父 | HTTP 409 |
| 13 | Agent寮曠敤+confirm鍒犻櫎 | 姝e父 | HTTP 200 |
| 14 | Agent寮曠敤鏃燾onfirm杩斿洖409 | 寮傚父 | HTTP 409 |
| 15 | 鍒犻櫎涓嶅瓨鍦ㄨ繑鍥?04 | 寮傚父 | HTTP 404 |
| 16 | 鍒嗛〉鏌ヨ | 姝e父 | total>=2 |
| 17 | 鍏抽敭璇嶆悳绱?| 姝e父 | keyword="閿€鍞? 鈫?鍛戒腑 |
| 18 | 鍏抽敭璇嶅尮閰峜ode | 姝e父 | keyword鍚玞ode鐗囨 鈫?鍛戒腑 |
| 19 | 绌哄垪琛?| 杈圭晫 | total=0, list=[] |
| 20 | Agent缁熻 | 姝e父 | agent_count=2, active_agent_count=1 |
| 21 | 鏃燗gent缁熻 | 杈圭晫 | agent_count=0 |
| 22 | 缁熻涓嶅瓨鍦ㄦ爣绛?| 寮傚父 | HTTP 404 |
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_position_tag_api.py`
娴嬭瘯鏂囦欢锛歚backend/tests/test_position_tag_api.py`
| 测试类 | 测试方法 | 对应场景 |
| 娴嬭瘯绫?| 娴嬭瘯鏂规硶 | 瀵瑰簲鍦烘櫙 |
|--------|----------|----------|
| TestCreatePositionTag | test_create_success | 1 |
| TestCreatePositionTag | test_create_code_conflict_returns_409 | 2 |
......@@ -185,3 +183,56 @@
| TestPositionTagAgentStatistics | test_statistics_success | 20 |
| TestPositionTagAgentStatistics | test_statistics_no_agents | 21 |
| TestPositionTagAgentStatistics | test_statistics_nonexistent_tag_returns_404 | 22 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
# 接口测试文档 — qrcode-channel
# 鎺ュ彛娴嬭瘯鏂囨。 鈥?qrcode-channel
---
## 1. 模块概览
## 1. 妯″潡姒傝
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 模块名称 | qrcode-channel |
| 模块说明 | 渠道活码配置管理 — 增删改查 + 启用/禁用 + 批量操作 + 导出 |
| 路由前缀 | `/api/v1/agent-group/qrcode` |
| 数据库表 | `qrcode_channels` |
| 外部依赖 | WeComClient(创建活码)、OSSClient(导出) |
| 妯″潡鍚嶇О | qrcode-channel |
| 妯″潡璇存槑 | 娓犻亾娲荤爜閰嶇疆绠$悊 鈥?澧炲垹鏀规煡 + 鍚敤/绂佺敤 + 鎵归噺鎿嶄綔 + 瀵煎嚭 |
| 璺敱鍓嶇紑 | `/api/v1/agent-group/qrcode` |
| 鏁版嵁搴撹〃 | `qrcode_channels` |
| 澶栭儴渚濊禆 | WeComClient锛堝垱寤烘椿鐮侊級銆丱SSClient锛堝鍑猴級 |
---
## 2. 接口列表
## 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` | 批量启用/禁用 |
| 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. 鎺ュ彛璇︾粏璇存槑
### 3.1 创建渠道活码
### 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_name | body | string | 鏄?| 娲荤爜鍚嶇О锛屾渶闀?0 |
| 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 状态码 | 触发条件 |
| 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 | 同岗位同员工活码已存在 |
| 400 | 宀椾綅涓嶅瓨鍦?|
| 409 | 鍚屽矖浣嶅悓鍛樺伐娲荤爜宸插瓨鍦?|
---
### 3.2 更新活码
### 3.2 鏇存柊娲荤爜
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| qrcode_name | body | string | 是 | 活码名称 |
| remark | body | string | 否 | 备注 |
| welcome_message | body | string | 否 | 欢迎语 |
| qrcode_name | body | string | 鏄?| 娲荤爜鍚嶇О |
| remark | body | string | 鍚?| 澶囨敞 |
| welcome_message | body | string | 鍚?| 娆㈣繋璇?|
---
### 3.3 活码详情
### 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 | 状态 |
| 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 禁用/启用活码
### 3.4 绂佺敤/鍚敤娲荤爜
**禁用请求参数**
**绂佺敤璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| reason | body | string | 是 | 停用原因 |
| reason | body | string | 鏄?| 鍋滅敤鍘熷洜 |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| success | boolean | 是否成功 |
| previous_status | string | 变更前状态 |
| success | boolean | 鏄惁鎴愬姛 |
| previous_status | string | 鍙樻洿鍓嶇姸鎬?|
---
### 3.5 批量状态变更
### 3.5 鎵归噺鐘舵€佸彉鏇?
**璇锋眰鍙傛暟**
**请求参数**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| qrcode_ids | body | integer[] | 是 | 活码ID列表,至少1个 |
| target_status | body | string | 是 | enable/disable |
| reason | body | string | 否 | 原因 |
| qrcode_ids | body | integer[] | 鏄?| 娲荤爜ID鍒楄〃锛岃嚦灏?涓?|
| target_status | body | string | 鏄?| enable/disable |
| reason | body | string | 鍚?| 鍘熷洜 |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| success_count | integer | 成功数 |
| failed_count | integer | 失败数 |
| failed_list | array | 失败列表 |
| success_count | integer | 鎴愬姛鏁?|
| failed_count | integer | 澶辫触鏁?|
| failed_list | array | 澶辫触鍒楄〃 |
---
## 4. 测试场景
## 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 | 集成:创建→查询→更新→禁用→启用 | 集成 | 全流程通过 |
| 1 | 鍒涘缓鎴愬姛 | 姝e父 | qrcode_id>0, channel_code鏍煎紡姝g‘, 鍚瀹?宀椾綅Agent |
| 2 | 宀椾綅涓嶅瓨鍦?| 寮傚父 | ValueError "宀椾綅涓嶅瓨鍦? |
| 3 | 閲嶅鍒涘缓杩斿洖鍐茬獊 | 寮傚父 | ValueError "宸插瓨鍦ㄥ悓宀椾綅娲荤爜" |
| 4 | channel_code鏍煎紡 | 姝e父 | zdxs_{code}_{emp_id} |
| 5 | 鑷姩鍖呭惈绠″+宀椾綅Agent | 姝e父 | agent_ids鍚玸teward鍜宮etric |
| 6 | 鏇存柊鎴愬姛 | 姝e父 | success=True |
| 7 | 鏇存柊涓嶅瓨鍦?| 寮傚父 | ValueError |
| 8 | 璇︽儏鏌ヨ | 姝e父 | qrcode_name, welcome_message姝g‘ |
| 9 | 璇︽儏涓嶅瓨鍦?| 寮傚父 | ValueError |
| 10 | 鍒楄〃鎸夊憳宸ュ悕绛涢€?| 姝e父 | total=1 |
| 11 | 鍒楄〃鎸夌姸鎬佺瓫閫?| 姝e父 | status=enable 鈫?total=1 |
| 12 | 鍒楄〃鍏抽敭璇嶆悳绱?| 姝e父 | keyword鍖归厤channel_code |
| 13 | 鍒楄〃绌虹粨鏋?| 杈圭晫 | total=0, list=[] |
| 14 | 瀵煎嚭鎴愬姛 | 姝e父 | total_count=1, file_url闈炵┖ |
| 15 | 绂佺敤鎴愬姛 | 姝e父 | success=True, previous_status="enable" |
| 16 | 鍚敤鎴愬姛 | 姝e父 | previous_status="disable" |
| 17 | 绂佺敤涓嶅瓨鍦?| 寮傚父 | ValueError |
| 18 | 鎵归噺绂佺敤 | 姝e父 | success_count=2, failed_count=0 |
| 19 | 鎵归噺閮ㄥ垎澶辫触 | 姝e父 | success_count=1, failed_count=1 |
| 20 | 闆嗘垚锛氬垱寤衡啋鏌ヨ鈫掓洿鏂扳啋绂佺敤鈫掑惎鐢?| 闆嗘垚 | 鍏ㄦ祦绋嬮€氳繃 |
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_qrcode_channel_api.py`
娴嬭瘯鏂囦欢锛歚backend/tests/test_qrcode_channel_api.py`
| 测试类 | 测试方法 | 对应场景 |
| 娴嬭瘯绫?| 娴嬭瘯鏂规硶 | 瀵瑰簲鍦烘櫙 |
|--------|----------|----------|
| TestCreateQrcode | test_create_success | 1 |
| TestCreateQrcode | test_create_position_not_found | 2 |
......@@ -188,3 +187,56 @@
| TestBatchStatus | test_batch_disable | 18 |
| TestBatchStatus | test_batch_with_failures | 19 |
| TestIntegrationFlow | test_create_query_update_disable_enable | 20 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
# 接口测试文档 — routing
# 鎺ュ彛娴嬭瘯鏂囨。 鈥?routing
---
## 1. 模块概览
## 1. 妯″潡姒傝
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 模块名称 | routing |
| 模块说明 | 路由与意图识别 — 消息路由(mention/inheritance/default) + 意图识别 + Agent交接 + 文件上传 |
| 路由前缀 | `/api/v1` |
| 数据库表 | `ai_agents` |
| 外部依赖 | LLMClient(意图识别)、SessionStore(会话状态)、FileParser、OSSClient |
| 妯″潡鍚嶇О | routing |
| 妯″潡璇存槑 | 璺敱涓庢剰鍥捐瘑鍒?鈥?娑堟伅璺敱(mention/inheritance/default) + 鎰忓浘璇嗗埆 + Agent浜ゆ帴 + 鏂囦欢涓婁紶 |
| 璺敱鍓嶇紑 | `/api/v1` |
| 鏁版嵁搴撹〃 | `ai_agents` |
| 澶栭儴渚濊禆 | LLMClient锛堟剰鍥捐瘑鍒級銆丼essionStore锛堜細璇濈姸鎬侊級銆丗ileParser銆丱SSClient |
---
## 2. 接口列表
## 2. 鎺ュ彛鍒楄〃
| 序号 | 方法 | 路径 | 说明 |
| 搴忓彿 | 鏂规硶 | 璺緞 | 璇存槑 |
|------|------|------|------|
| 1 | POST | `/api/v1/chat/completions` | 路由决策接口 |
| 2 | POST | `/api/v1/files/upload` | 文件上传与文本提取 |
| 1 | POST | `/api/v1/chat/completions` | 璺敱鍐崇瓥鎺ュ彛 |
| 2 | POST | `/api/v1/files/upload` | 鏂囦欢涓婁紶涓庢枃鏈彁鍙?|
---
## 3. 接口详细说明
## 3. 鎺ュ彛璇︾粏璇存槑
### 3.1 路由决策接口
### 3.1 璺敱鍐崇瓥鎺ュ彛
**基本信息**
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/chat/completions` |
| 说明 | 根据mention/继承/默认策略路由消息,执行意图识别和Agent交接 |
| 鏂规硶 | 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 | body | string | 鏄?| 浼氳瘽ID锛屾渶闀?4 |
| user_id | body | string | 鏄?| 鐢ㄦ埛ID锛屾渶闀?4 |
| channel | body | string | 鏄?| 娑堟伅娓犻亾锛屾渶闀?4 |
| query | body | string | 鏄?| 鐢ㄦ埛闂锛?~5000瀛楃 |
| mentioned_agent_code | body | string | 鍚?| @鎻愬強鐨凙gent缂栫爜 |
| file_url | body | string | 鍚?| 鏂囦欢URL |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| session_id | string | 会话ID |
| routing | object | 路由信息 |
| 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 状态码 | 触发条件 |
| routing.agent_code | string | Agent缂栫爜 |
| routing.agent_name | string | Agent鍚嶇О |
| routing.routing_reason | string | 璺敱鍘熷洜锛歮ention/inheritance/default |
| intent | object | 鎰忓浘淇℃伅锛坢ention鏃朵负null锛?|
| intent.intent | string | 鎰忓浘鍚?|
| intent.confidence | float | 缃俊搴?|
| handoff | object | 浜ゆ帴淇℃伅锛堝悓Agent鎴栭娆″璇濇椂涓簄ull锛?|
| handoff.from_agent_id | integer | 婧怉gent 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未配置 |
| 400 | mentioned_agent涓嶅瓨鍦?/ 绠″Agent鏈厤缃?|
---
### 3.2 文件上传与文本提取
### 3.2 鏂囦欢涓婁紶涓庢枃鏈彁鍙?
**基本信息**
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/files/upload` |
| 鏂规硶 | POST |
| 璺緞 | `/api/v1/files/upload` |
| Content-Type | multipart/form-data |
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| session_id | form | string | 是 | 关联会话ID |
| file | form | file | 是 | 上传文件 |
| 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 |
| file_url | string | 鏂囦欢URL |
| file_name | string | 鏂囦欢鍚?|
| file_size | integer | 鏂囦欢澶у皬 |
| extracted_text | string | 鎻愬彇鐨勬枃鏈紙鍥剧墖涓簄ull锛?|
| session_id | string | 浼氳瘽ID |
**错误码**
**閿欒鐮?*
| HTTP 状态码 | 触发条件 |
| HTTP 鐘舵€佺爜 | 瑙﹀彂鏉′欢 |
|-------------|----------|
| 400 | 不支持的文件格式 / 文件过大 |
| 400 | 涓嶆敮鎸佺殑鏂囦欢鏍煎紡 / 鏂囦欢杩囧ぇ |
---
## 4. 测试场景
## 4. 娴嬭瘯鍦烘櫙
### 4.1 路由决策
### 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" |
| 1 | @mention璺敱鍒版寚瀹欰gent | 姝e父 | agent_code="metric-agent", reason="mention" |
| 2 | 缁ф壙璺敱鍒板綋鍓岮gent | 姝e父 | agent_code="metric-agent", reason="inheritance" |
| 3 | 榛樿璺敱鍒扮瀹禔gent | 姝e父 | agent_code="steward", reason="default" |
| 4 | @mention瑕嗙洊缁ф壙 | 姝e父 | reason="mention", agent_code="detail-agent" |
### 4.2 意图识别
### 4.2 鎰忓浘璇嗗埆
| 序号 | 场景名称 | 分类 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | 查询类意图 | 正常 | intent="query-metric", confidence>0 |
| 2 | 未知意图归为general-qa | 正常 | intent="general-qa" |
| 3 | @mention跳过意图识别 | 正常 | intent=None |
| 1 | 鏌ヨ绫绘剰鍥?| 姝e父 | intent="query-metric", confidence>0 |
| 2 | 鏈煡鎰忓浘褰掍负general-qa | 姝e父 | intent="general-qa" |
| 3 | @mention璺宠繃鎰忓浘璇嗗埆 | 姝e父 | intent=None |
### 4.3 Agent交接
### 4.3 Agent浜ゆ帴
| 序号 | 场景名称 | 分类 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | Agent切换生成交接 | 正常 | handoff非null, 含from/to/handoff_message |
| 2 | 同Agent无交接 | 正常 | handoff=None |
| 3 | 首次对话无交接 | 正常 | handoff=None |
| 1 | Agent鍒囨崲鐢熸垚浜ゆ帴 | 姝e父 | handoff闈瀗ull, 鍚玣rom/to/handoff_message |
| 2 | 鍚孉gent鏃犱氦鎺?| 姝e父 | handoff=None |
| 3 | 棣栨瀵硅瘽鏃犱氦鎺?| 姝e父 | handoff=None |
### 4.4 文件上传
### 4.4 鏂囦欢涓婁紶
| 序号 | 场景名称 | 分类 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | PDF上传提取文本 | 正常 | extracted_text非空 |
| 2 | 不支持的格式 | 异常 | ValueError "不支持的文件格式" |
| 3 | 文件过大 | 异常 | ValueError "文件大小超过限制" |
| 4 | 图片上传无文本提取 | 正常 | extracted_text=None |
| 1 | PDF涓婁紶鎻愬彇鏂囨湰 | 姝e父 | extracted_text闈炵┖ |
| 2 | 涓嶆敮鎸佺殑鏍煎紡 | 寮傚父 | ValueError "涓嶆敮鎸佺殑鏂囦欢鏍煎紡" |
| 3 | 鏂囦欢杩囧ぇ | 寮傚父 | ValueError "鏂囦欢澶у皬瓒呰繃闄愬埗" |
| 4 | 鍥剧墖涓婁紶鏃犳枃鏈彁鍙?| 姝e父 | extracted_text=None |
### 4.5 集成与异常
### 4.5 闆嗘垚涓庡紓甯?
| 序号 | 场景名称 | 分类 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | 默认→mention完整流程 | 集成 | 先default后mention, 生成handoff |
| 2 | mentioned Agent不存在 | 异常 | ValueError "Agent不存在" |
| 3 | 管家Agent未配置 | 异常 | ValueError "管家Agent" |
| 1 | 榛樿鈫抦ention瀹屾暣娴佺▼ | 闆嗘垚 | 鍏坉efault鍚巑ention, 鐢熸垚handoff |
| 2 | mentioned Agent涓嶅瓨鍦?| 寮傚父 | ValueError "Agent涓嶅瓨鍦? |
| 3 | 绠″Agent鏈厤缃?| 寮傚父 | ValueError "绠″Agent" |
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_routing_api.py`
娴嬭瘯鏂囦欢锛歚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 |
......@@ -180,3 +180,56 @@
| 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 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
# 接口测试文档 — sessions
# 鎺ュ彛娴嬭瘯鏂囨。 鈥?sessions
---
## 1. 模块概览
## 1. 妯″潡姒傝
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 模块名称 | sessions |
| 模块说明 | 会话管理 — 创建、追加入档、查询详情、上下文继承、归档 |
| 路由前缀 | `/api/v1/sessions` |
| 数据库表 | `sessions`, `conversation_history` |
| 外部依赖 | 无 |
| 妯″潡鍚嶇О | sessions |
| 妯″潡璇存槑 | 浼氳瘽绠$悊 鈥?鍒涘缓銆佽拷鍔犲叆妗c€佹煡璇㈣鎯呫€佷笂涓嬫枃缁ф壙銆佸綊妗?|
| 璺敱鍓嶇紑 | `/api/v1/sessions` |
| 鏁版嵁搴撹〃 | `sessions`, `conversation_history` |
| 澶栭儴渚濊禆 | 鏃?|
---
## 2. 接口列表
## 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` | 归档会话 |
| 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. 鎺ュ彛璇︾粏璇存槑
### 3.1 创建会话
### 3.1 鍒涘缓浼氳瘽
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| user_id | body | string | 是 | 用户ID,最长64 |
| channel | body | string | 是 | 渠道,最长64 |
| initial_query | body | string | 是 | 初始问题,1~5000字符 |
| user_id | body | string | 鏄?| 鐢ㄦ埛ID锛屾渶闀?4 |
| channel | body | string | 鏄?| 娓犻亾锛屾渶闀?4 |
| initial_query | body | string | 鏄?| 鍒濆闂锛?~5000瀛楃 |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| session_id | string | 会话ID |
| user_id | string | 用户ID |
| channel | string | 渠道 |
| current_agent_id | integer | 当前Agent ID |
| created_at | string | 创建时间 |
| session_id | string | 浼氳瘽ID |
| user_id | string | 鐢ㄦ埛ID |
| channel | string | 娓犻亾 |
| current_agent_id | integer | 褰撳墠Agent ID |
| created_at | string | 鍒涘缓鏃堕棿 |
---
### 3.2 追加对话
### 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 |
| session_id | path | string | 鏄?| 浼氳瘽ID |
| role | body | string | 鏄?| 瑙掕壊锛屾渶闀?2 |
| content | body | string | 鏄?| 鍐呭锛?~5000瀛楃 |
| agent_id | body | integer | 鏄?| Agent ID |
| intent | body | string | 鍚?| 鎰忓浘 |
| entities | body | object | 鍚?| 瀹炰綋JSON |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| success | boolean | 是否成功 |
| updated_at | string | 更新时间 |
| turn_count | integer | 当前轮次 |
| success | boolean | 鏄惁鎴愬姛 |
| updated_at | string | 鏇存柊鏃堕棿 |
| turn_count | integer | 褰撳墠杞 |
---
### 3.3 查询会话详情
### 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 | 内容 |
| 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 | 合并后的实体 |
| conversation_history[].intent | string | 鎰忓浘 |
| context_entities | object | 鍚堝苟鍚庣殑瀹炰綋 |
---
### 3.4 查询会话上下文
### 3.4 鏌ヨ浼氳瘽涓婁笅鏂?
**鍝嶅簲鍙傛暟**
**响应参数**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| session_id | string | 会话ID |
| current_agent_id | integer | 当前Agent ID |
| last_entities | object | 最近实体 |
| inheritance_valid | boolean | 继承是否有效 |
| expires_at | string | 过期时间 |
| session_id | string | 浼氳瘽ID |
| current_agent_id | integer | 褰撳墠Agent ID |
| last_entities | object | 鏈€杩戝疄浣?|
| inheritance_valid | boolean | 缁ф壙鏄惁鏈夋晥 |
| expires_at | string | 杩囨湡鏃堕棿 |
---
### 3.5 归档会话
### 3.5 褰掓。浼氳瘽
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| success | boolean | 是否成功 |
| archived_at | string | 归档时间 |
| success | boolean | 鏄惁鎴愬姛 |
| archived_at | string | 褰掓。鏃堕棿 |
---
## 4. 测试场景
## 4. 娴嬭瘯鍦烘櫙
| 序号 | 场景名称 | 分类 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | 创建→追加→详情→上下文 | 正常 | 创建201, 追加success+turn_count=1, 详情含history+entities, 上下文inheritance_valid=True |
| 2 | 归档会话 | 正常 | success=True, 归档后详情仍可读, 上下文inheritance_valid=False |
| 1 | 鍒涘缓鈫掕拷鍔犫啋璇︽儏鈫掍笂涓嬫枃 | 姝e父 | 鍒涘缓201, 杩藉姞success+turn_count=1, 璇︽儏鍚玥istory+entities, 涓婁笅鏂噄nheritance_valid=True |
| 2 | 褰掓。浼氳瘽 | 姝e父 | success=True, 褰掓。鍚庤鎯呬粛鍙, 涓婁笅鏂噄nheritance_valid=False |
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_sessions_api.py`
娴嬭瘯鏂囦欢锛歚backend/tests/test_sessions_api.py`
| 测试类 | 测试方法 | 对应场景 |
| 娴嬭瘯绫?| 娴嬭瘯鏂规硶 | 瀵瑰簲鍦烘櫙 |
|--------|----------|----------|
| TestSessionsApi | test_create_update_get_and_context | 1 |
| TestSessionsApi | test_archive_session | 2 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
# 接口测试文档 — skill-scanner
# 鎺ュ彛娴嬭瘯鏂囨。 鈥?skill-scanner
---
## 1. 模块概览
## 1. 妯″潡姒傝
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 模块名称 | skill-scanner |
| 模块说明 | Skill目录扫描器 — 从文件系统SKILL.md读取技能配置并生成skills.json |
| 路由前缀 | 无(非HTTP接口,工具类) |
| 数据库表 | 无 |
| 外部依赖 | 文件系统 |
| 妯″潡鍚嶇О | skill-scanner |
| 妯″潡璇存槑 | Skill鐩綍鎵弿鍣?鈥?浠庢枃浠剁郴缁烻KILL.md璇诲彇鎶€鑳介厤缃苟鐢熸垚skills.json |
| 璺敱鍓嶇紑 | 鏃狅紙闈濰TTP鎺ュ彛锛屽伐鍏风被锛?|
| 鏁版嵁搴撹〃 | 鏃?|
| 澶栭儴渚濊禆 | 鏂囦欢绯荤粺 |
---
## 2. 组件列表
## 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 |
| 1 | `_parse_frontmatter(content)` | 瑙f瀽SKILL.md鐨刌AML frontmatter |
| 2 | `scan_skills(skills_dir)` | 鎵弿鐩綍涓嬫墍鏈塖KILL.md锛岃繑鍥炴妧鑳藉瓧鍏?|
| 3 | `update_skills_json(skills_dir, config_dir)` | 鍏ㄩ噺鎵弿骞跺啓鍏onfig/skills.json |
---
## 3. 组件详细说明
## 3. 缁勪欢璇︾粏璇存槑
### 3.1 _parse_frontmatter
**输入**:SKILL.md 文件内容字符串
**杈撳叆**锛歋KILL.md 鏂囦欢鍐呭瀛楃涓?
**输出**:`(meta: dict, body: str)` — frontmatter 字典 + 正文
**杈撳嚭**锛歚(meta: dict, body: str)` 鈥?frontmatter 瀛楀吀 + 姝f枃
**逻辑**:识别 `---` 分隔符,解析为 YAML 键值对;无 frontmatter 时返回 `({}, 原文)`
**閫昏緫**锛氳瘑鍒?`---` 鍒嗛殧绗︼紝瑙f瀽涓?YAML 閿€煎锛涙棤 frontmatter 鏃惰繑鍥?`({}, 鍘熸枃)`
### 3.2 scan_skills
**输入**:`skills_dir: Path` — 技能根目录
**杈撳叆**锛歚skills_dir: Path` 鈥?鎶€鑳芥牴鐩綍
**输出**:`dict[str, SkillConfig]` — 技能编码到配置的映射
**杈撳嚭**锛歚dict[str, SkillConfig]` 鈥?鎶€鑳界紪鐮佸埌閰嶇疆鐨勬槧灏?
**过滤规则**:
- 跳过无 SKILL.md 的子目录
- 跳过隐藏目录(`.` 开头)
- 空目录/不存在目录返回 `{}`
**杩囨护瑙勫垯**锛?
- 璺宠繃鏃?SKILL.md 鐨勫瓙鐩綍
- 璺宠繃闅愯棌鐩綍锛坄.` 寮€澶达級
- 绌虹洰褰?涓嶅瓨鍦ㄧ洰褰曡繑鍥?`{}`
**SkillConfig 字段**:
**SkillConfig 瀛楁**锛?
| 字段 | 类型 | 说明 |
| 瀛楁 | 绫诲瀷 | 璇存槑 |
|------|------|------|
| name | string | 技能名称 |
| description | string | 描述 |
| instruction | string | SKILL.md 正文 |
| location | string | 相对路径(如 `skills/meeting_minutes`) |
| name | string | 鎶€鑳藉悕绉?|
| description | string | 鎻忚堪 |
| instruction | string | SKILL.md 姝f枃 |
| location | string | 鐩稿璺緞锛堝 `skills/meeting_minutes`锛?|
### 3.3 update_skills_json
**输入**:`skills_dir: Path`, `config_dir: Path`
**杈撳叆**锛歚skills_dir: Path`, `config_dir: Path`
**输出**:写入 `config_dir/skills.json`
**杈撳嚭**锛氬啓鍏?`config_dir/skills.json`
**JSON 结构**:
**JSON 缁撴瀯**锛?
```json
{
......@@ -69,7 +69,7 @@
"code": "alpha",
"name": "alpha",
"location": "skills/alpha",
"instruction": "技能 alpha 的说明"
"instruction": "鎶€鑳?alpha 鐨勮鏄?
}
}
}
......@@ -77,38 +77,38 @@
---
## 4. 测试场景
## 4. 娴嬭瘯鍦烘櫙
### 4.1 Frontmatter解析
### 4.1 Frontmatter瑙f瀽
| 序号 | 场景名称 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------|
| 1 | 解析有效frontmatter | meta含name/description, body含正文 |
| 2 | 无frontmatter | meta={}, body=原文 |
| 1 | 瑙f瀽鏈夋晥frontmatter | meta鍚玭ame/description, body鍚鏂?|
| 2 | 鏃爁rontmatter | meta={}, body=鍘熸枃 |
### 4.2 scan_skills
| 序号 | 场景名称 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------|
| 1 | 正常扫描2个技能 | 长度=2, 含meeting_minutes和support |
| 2 | 跳过无SKILL.md的目录 | 长度=1 |
| 3 | 跳过隐藏目录 | 长度=0 |
| 4 | 空目录 | 返回{} |
| 5 | 不存在的目录 | 返回{} |
| 1 | 姝e父鎵弿2涓妧鑳?| 闀垮害=2, 鍚玬eeting_minutes鍜宻upport |
| 2 | 璺宠繃鏃燬KILL.md鐨勭洰褰?| 闀垮害=1 |
| 3 | 璺宠繃闅愯棌鐩綍 | 闀垮害=0 |
| 4 | 绌虹洰褰?| 杩斿洖{} |
| 5 | 涓嶅瓨鍦ㄧ殑鐩綍 | 杩斿洖{} |
### 4.3 update_skills_json
| 序号 | 场景名称 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------|
| 1 | 全量扫描并写入 | skills.json存在, 含2个技能, location/code/name/instruction正确 |
| 1 | 鍏ㄩ噺鎵弿骞跺啓鍏?| skills.json瀛樺湪, 鍚?涓妧鑳? location/code/name/instruction姝g‘ |
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_skill_scanner.py`
娴嬭瘯鏂囦欢锛歚backend/tests/test_skill_scanner.py`
| 测试类 | 测试方法 | 对应场景 |
| 娴嬭瘯绫?| 娴嬭瘯鏂规硶 | 瀵瑰簲鍦烘櫙 |
|--------|----------|----------|
| TestParseFrontmatter | test_parses_valid_frontmatter | 4.1-1 |
| TestParseFrontmatter | test_handles_missing_frontmatter | 4.1-2 |
......@@ -118,3 +118,56 @@
| TestScanSkills | test_empty_skills_dir | 4.2-4 |
| TestScanSkills | test_nonexistent_dir | 4.2-5 |
| TestUpdateSkillsJson | test_full_scan_and_write | 4.3-1 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
# 接口测试文档 — skill
# 鎺ュ彛娴嬭瘯鏂囨。 鈥?skill
---
## 1. 模块概览
## 1. 妯″潡姒傝
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 模块名称 | skill |
| 模块说明 | Skill目录 — 列表查询 + 详情查询 + Redis缓存 |
| 路由前缀 | `/api/v1/skills` |
| 数据库表 | `skills` |
| 外部依赖 | SkillCache(内存缓存) |
| 妯″潡鍚嶇О | skill |
| 妯″潡璇存槑 | Skill鐩綍 鈥?鍒楄〃鏌ヨ + 璇︽儏鏌ヨ + Redis缂撳瓨 |
| 璺敱鍓嶇紑 | `/api/v1/skills` |
| 鏁版嵁搴撹〃 | `skills` |
| 澶栭儴渚濊禆 | SkillCache锛堝唴瀛樼紦瀛橈級 |
---
## 2. 接口列表
## 2. 鎺ュ彛鍒楄〃
| 序号 | 方法 | 路径 | 说明 |
| 搴忓彿 | 鏂规硶 | 璺緞 | 璇存槑 |
|------|------|------|------|
| 1 | GET | `/api/v1/skills` | 查询Skill列表 |
| 2 | GET | `/api/v1/skills/{skill_code}` | 查询Skill详情 |
| 1 | GET | `/api/v1/skills` | 鏌ヨSkill鍒楄〃 |
| 2 | GET | `/api/v1/skills/{skill_code}` | 鏌ヨSkill璇︽儏 |
---
## 3. 接口详细说明
## 3. 鎺ュ彛璇︾粏璇存槑
### 3.1 查询Skill列表
### 3.1 鏌ヨSkill鍒楄〃
**基本信息**
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/skills` |
| 说明 | 返回所有Skill列表,按priority升序,列表项不含doc_markdown |
| 鏂规硶 | GET |
| 璺緞 | `/api/v1/skills` |
| 璇存槑 | 杩斿洖鎵€鏈塖kill鍒楄〃锛屾寜priority鍗囧簭锛屽垪琛ㄩ」涓嶅惈doc_markdown |
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| list | array | Skill列表 |
| list[].skill_code | string | 技能编码 |
| list[].skill_name | string | 技能名称 |
| list[].description | string | 描述 |
| list | array | Skill鍒楄〃 |
| list[].skill_code | string | 鎶€鑳界紪鐮?|
| list[].skill_name | string | 鎶€鑳藉悕绉?|
| list[].description | string | 鎻忚堪 |
---
### 3.2 查询Skill详情
### 3.2 鏌ヨSkill璇︽儏
**基本信息**
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/skills/{skill_code}` |
| 说明 | 返回Skill详情,包含doc_markdown;支持缓存 |
| 鏂规硶 | GET |
| 璺緞 | `/api/v1/skills/{skill_code}` |
| 璇存槑 | 杩斿洖Skill璇︽儏锛屽寘鍚玠oc_markdown锛涙敮鎸佺紦瀛?|
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| skill_code | path | string | 是 | 技能编码 |
| skill_code | path | string | 鏄?| 鎶€鑳界紪鐮?|
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| skill_code | string | 技能编码 |
| skill_name | string | 技能名称 |
| description | string | 描述 |
| doc_markdown | string | Markdown格式文档 |
| skill_code | string | 鎶€鑳界紪鐮?|
| skill_name | string | 鎶€鑳藉悕绉?|
| description | string | 鎻忚堪 |
| doc_markdown | string | Markdown鏍煎紡鏂囨。 |
**错误码**
**閿欒鐮?*
| HTTP 状态码 | 触发条件 |
| HTTP 鐘舵€佺爜 | 瑙﹀彂鏉′欢 |
|-------------|----------|
| 404 | Skill不存在 |
| 404 | Skill涓嶅瓨鍦?|
---
## 4. 测试场景
## 4. 娴嬭瘯鍦烘櫙
### 4.1 Skill列表
### 4.1 Skill鍒楄〃
| 序号 | 场景名称 | 分类 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | 返回所有Skill | 正常 | list长度=2 |
| 2 | 列表项字段验证 | 正常 | 含skill_code/skill_name/description,不含doc_markdown |
| 3 | 空列表 | 边界 | list=[] |
| 4 | 按priority排序 | 正常 | 高优先级在前 |
| 1 | 杩斿洖鎵€鏈塖kill | 姝e父 | list闀垮害=2 |
| 2 | 鍒楄〃椤瑰瓧娈甸獙璇?| 姝e父 | 鍚玸kill_code/skill_name/description锛屼笉鍚玠oc_markdown |
| 3 | 绌哄垪琛?| 杈圭晫 | list=[] |
| 4 | 鎸塸riority鎺掑簭 | 姝e父 | 楂樹紭鍏堢骇鍦ㄥ墠 |
### 4.2 Skill详情
### 4.2 Skill璇︽儏
| 序号 | 场景名称 | 分类 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | 详情查询成功 | 正常 | 含doc_markdown |
| 2 | 不存在返回404 | 异常 | HTTP 404 |
| 3 | doc_markdown内容完整 | 正常 | markdown内容原样返回 |
| 1 | 璇︽儏鏌ヨ鎴愬姛 | 姝e父 | 鍚玠oc_markdown |
| 2 | 涓嶅瓨鍦ㄨ繑鍥?04 | 寮傚父 | HTTP 404 |
| 3 | doc_markdown鍐呭瀹屾暣 | 姝e父 | markdown鍐呭鍘熸牱杩斿洖 |
### 4.3 缓存行为
### 4.3 缂撳瓨琛屼负
| 序号 | 场景名称 | 分类 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | 缓存命中避免DB查询 | 正常 | 删除DB记录后仍返回缓存数据 |
| 2 | 缓存未命中查DB | 正常 | 返回DB最新数据 |
| 3 | 详情查询后缓存填充 | 正常 | 缓存中可读取到skill数据 |
| 1 | 缂撳瓨鍛戒腑閬垮厤DB鏌ヨ | 姝e父 | 鍒犻櫎DB璁板綍鍚庝粛杩斿洖缂撳瓨鏁版嵁 |
| 2 | 缂撳瓨鏈懡涓煡DB | 姝e父 | 杩斿洖DB鏈€鏂版暟鎹?|
| 3 | 璇︽儏鏌ヨ鍚庣紦瀛樺~鍏?| 姝e父 | 缂撳瓨涓彲璇诲彇鍒皊kill鏁版嵁 |
### 4.4 服务层
| 序号 | 场景名称 | 分类 | 预期结果 |
### 4.4 鏈嶅姟灞?
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | Service层列表查询 | 正常 | 返回skill_code正确的列表 |
| 2 | Service层详情查询 | 正常 | 含doc_markdown |
| 3 | Service层不存在 | 异常 | ValueError "不存在" |
| 1 | Service灞傚垪琛ㄦ煡璇?| 姝e父 | 杩斿洖skill_code姝g‘鐨勫垪琛?|
| 2 | Service灞傝鎯呮煡璇?| 姝e父 | 鍚玠oc_markdown |
| 3 | Service灞備笉瀛樺湪 | 寮傚父 | ValueError "涓嶅瓨鍦? |
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_skill_api.py`
娴嬭瘯鏂囦欢锛歚backend/tests/test_skill_api.py`
| 测试类 | 测试方法 | 对应场景 |
| 娴嬭瘯绫?| 娴嬭瘯鏂规硶 | 瀵瑰簲鍦烘櫙 |
|--------|----------|----------|
| TestListSkills | test_list_returns_all_skills | 4.1-1 |
| TestListSkills | test_list_item_fields | 4.1-2 |
......@@ -135,3 +134,56 @@
| 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 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
# 接口测试文档 — tool-manager
# 鎺ュ彛娴嬭瘯鏂囨。 鈥?tool-manager
---
## 1. 模块概览
## 1. 妯″潡姒傝
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 模块名称 | tool-manager |
| 模块说明 | 工具管理器 — 注册/调用工具,支持分组、激活/停用、OpenAI兼容Schema |
| 路由前缀 | 无(非HTTP接口,Service组件) |
| 数据库表 | 无 |
| 外部依赖 | 无 |
| 妯″潡鍚嶇О | tool-manager |
| 妯″潡璇存槑 | 宸ュ叿绠$悊鍣?鈥?娉ㄥ唽/璋冪敤宸ュ叿锛屾敮鎸佸垎缁勩€佹縺娲?鍋滅敤銆丱penAI鍏煎Schema |
| 璺敱鍓嶇紑 | 鏃狅紙闈濰TTP鎺ュ彛锛孲ervice缁勪欢锛?|
| 鏁版嵁搴撹〃 | 鏃?|
| 澶栭儴渚濊禆 | 鏃?|
---
## 2. 组件列表
## 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` | 工具组字典 |
| 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. 缁勪欢璇︾粏璇存槑
### 3.1 工具注册
### 3.1 宸ュ叿娉ㄥ唽
**方式一:函数调用**
**鏂瑰紡涓€锛氬嚱鏁拌皟鐢?*
```python
tm.register_tool(get_weather, name="custom", group="admin", description="自定义描述")
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
**瑙勫垯**锛?- `basic` 缁勯粯璁ゆ縺娲伙紝鍏朵粬缁勯粯璁ゆ湭婵€娲?- 鑷姩浠庡嚱鏁扮鍚嶇敓鎴?`input_schema`锛圤penAI function calling 鏍煎紡锛?- 鑷姩鎻愬彇 docstring 浣滀负 description
### 3.2 工具调用
**输入**:
### 3.2 宸ュ叿璋冪敤
**杈撳叆**锛?
```python
{"name": "add", "input": {"a": 1, "b": 2}}
```
**输出**:
- 成功:`{"result": 3}`
- 未注册:`{"error": "未注册..."}`
- 组未激活:`{"error": "未激活..."}`
- 执行异常:`{"error": "...boom..."}`
**杈撳嚭**锛?
- 鎴愬姛锛歚{"result": 3}`
- 鏈敞鍐岋細`{"error": "鏈敞鍐?.."}`
- 缁勬湭婵€娲伙細`{"error": "鏈縺娲?.."}`
- 鎵ц寮傚父锛歚{"error": "...boom..."}`
### 3.3 Schema生成
### 3.3 Schema鐢熸垚
**格式**:OpenAI function calling 兼容
**鏍煎紡**锛歄penAI function calling 鍏煎
```json
{
"type": "function",
"function": {
"name": "search",
"description": "搜索知识库",
"description": "鎼滅储鐭ヨ瘑搴?,
"parameters": {
"type": "object",
"properties": {"query": {"type": "string"}, "limit": {"type": "integer"}},
......@@ -85,56 +80,55 @@ def analyze_image(image_url: str) -> str:
}
```
**规则**:仅返回激活组(默认basic)的工具Schema
**瑙勫垯**锛氫粎杩斿洖婵€娲荤粍锛堥粯璁asic锛夌殑宸ュ叿Schema
### 3.4 分组管理
### 3.4 鍒嗙粍绠$悊
- `basic` 组默认存在且激活
- `reset_equipped_tools(basic=False, vision=True)` 切换激活组
- `basic` 缁勯粯璁ゅ瓨鍦ㄤ笖婵€娲?- `reset_equipped_tools(basic=False, vision=True)` 鍒囨崲婵€娲荤粍
---
## 4. 测试场景
## 4. 娴嬭瘯鍦烘櫙
### 4.1 工具注册
### 4.1 宸ュ叿娉ㄥ唽
| 序号 | 场景名称 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------|
| 1 | 函数注册 | 名称/description/group正确 |
| 2 | 自定义name/group/description | 覆盖默认值 |
| 3 | 装饰器注册 | group="vision"未激活, input_schema含参数 |
| 1 | 鍑芥暟娉ㄥ唽 | 鍚嶇О/description/group姝g‘ |
| 2 | 鑷畾涔塶ame/group/description | 瑕嗙洊榛樿鍊?|
| 3 | 瑁呴グ鍣ㄦ敞鍐?| group="vision"鏈縺娲? input_schema鍚弬鏁?|
### 4.2 工具调用
### 4.2 宸ュ叿璋冪敤
| 序号 | 场景名称 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------|
| 1 | 调用成功 | {"result": 3} |
| 2 | 工具未注册 | {"error": "未注册"} |
| 3 | 组未激活 | {"error": "未激活"} |
| 4 | 执行异常 | {"error": 含"boom"} |
| 1 | 璋冪敤鎴愬姛 | {"result": 3} |
| 2 | 宸ュ叿鏈敞鍐?| {"error": "鏈敞鍐?} |
| 3 | 缁勬湭婵€娲?| {"error": "鏈縺娲?} |
| 4 | 鎵ц寮傚父 | {"error": 鍚?boom"} |
### 4.3 Schema生成
### 4.3 Schema鐢熸垚
| 序号 | 场景名称 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------|
| 1 | 仅返回激活组 | 1个schema(basic组) |
| 2 | 空管理器 | [] |
| 3 | OpenAI兼容格式 | type/function/parameters结构正确 |
| 1 | 浠呰繑鍥炴縺娲荤粍 | 1涓猻chema(basic缁? |
| 2 | 绌虹鐞嗗櫒 | [] |
| 3 | OpenAI鍏煎鏍煎紡 | type/function/parameters缁撴瀯姝g‘ |
### 4.4 分组管理
### 4.4 鍒嗙粍绠$悊
| 序号 | 场景名称 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------|
| 1 | 切换激活组 | reset后vision激活,basic停用 |
| 2 | 默认组 | basic存在且激活 |
| 1 | 鍒囨崲婵€娲荤粍 | reset鍚巚ision婵€娲?basic鍋滅敤 |
| 2 | 榛樿缁?| basic瀛樺湪涓旀縺娲?|
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_tool_manager.py`
娴嬭瘯鏂囦欢锛歚backend/tests/test_tool_manager.py`
| 测试类 | 测试方法 | 对应场景 |
| 娴嬭瘯绫?| 娴嬭瘯鏂规硶 | 瀵瑰簲鍦烘櫙 |
|--------|----------|----------|
| TestToolManagerRegister | test_register_function | 4.1-1 |
| TestToolManagerRegister | test_register_with_custom_name_and_group | 4.1-2 |
......@@ -148,3 +142,56 @@ def analyze_image(image_url: str) -> str:
| TestToolManagerSchemas | test_schema_format_openai_compatible | 4.3-3 |
| TestToolManagerGroups | test_reset_equipped_tools | 4.4-1 |
| TestToolManagerGroups | test_default_groups | 4.4-2 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
# 接口测试文档 - wecom-sync
# 鎺ュ彛娴嬭瘯鏂囨。 - wecom-sync
---
## 1. 模块概览
## 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` |
| 妯″潡鍚嶇О | 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. 接口列表
## 2. 鎺ュ彛鍒楄〃
| 序号 | 方法 | 路径 | 说明 |
| 搴忓彿 | 鏂规硶 | 璺緞 | 璇存槑 |
|------|------|------|------|
| 1 | POST | `/api/v1/wecom-sync/run` | 手动触发同步 |
| 2 | GET | `/api/v1/wecom-sync/checkpoints` | 分页查询同步检查点 |
| 1 | POST | `/api/v1/wecom-sync/run` | 鎵嬪姩瑙﹀彂鍚屾 |
| 2 | GET | `/api/v1/wecom-sync/checkpoints` | 鍒嗛〉鏌ヨ鍚屾妫€鏌ョ偣 |
---
## 3. 接口详细说明
## 3. 鎺ュ彛璇︾粏璇存槑
### 3.1 手动触发同步
### 3.1 鎵嬪姩瑙﹀彂鍚屾
**基本信息**
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | POST |
| 路径 | `/api/v1/wecom-sync/run` |
| 说明 | 支持首次全量同步或后续增量同步 |
| 鏂规硶 | 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 |
| mode | body | string | 鏄?| `full` 鎴?`incremental` |
| bot_ids | body | string[] | 鍚?| 澧為噺妯″紡涓嬫寚瀹氭満鍣ㄤ汉鍒楄〃锛涗笉浼犳椂榛樿浣跨敤鏈湴宸插悓姝ユ満鍣ㄤ汉 |
| message_start_time | body | string | 鍚?| 娑堟伅鍚屾璧峰鏃堕棿锛孖SO 8601 |
| message_end_time | body | string | 鍚?| 娑堟伅鍚屾缁撴潫鏃堕棿锛孖SO 8601 |
**请求示例:全量同步**
**璇锋眰绀轰緥锛氬叏閲忓悓姝?*
```json
{
......@@ -54,7 +54,7 @@
}
```
**请求示例:增量同步**
**璇锋眰绀轰緥锛氬閲忓悓姝?*
```json
{
......@@ -64,20 +64,20 @@
}
```
**响应参数**
**鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 |
| 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------|
| 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 | 触发时间 |
| 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
{
......@@ -94,51 +94,51 @@
}
```
**错误码**
**閿欒鐮?*
| HTTP / Code | 场景 | 说明 |
| HTTP / Code | 鍦烘櫙 | 璇存槑 |
|-------------|------|------|
| 400 | 请求参数错误 | `mode` 非法或时间参数格式错误 |
| 503 | 外部 Business API 不可用 | 拉取外部数据失败 |
| 400 | 璇锋眰鍙傛暟閿欒 | `mode` 闈炴硶鎴栨椂闂村弬鏁版牸寮忛敊璇?|
| 503 | 澶栭儴 Business API 涓嶅彲鐢?| 鎷夊彇澶栭儴鏁版嵁澶辫触 |
---
### 3.2 查询同步检查点
### 3.2 鏌ヨ鍚屾妫€鏌ョ偣
**基本信息**
**鍩烘湰淇℃伅**
| 字段 | 值 |
| 瀛楁 | 鍊?|
|------|-----|
| 方法 | GET |
| 路径 | `/api/v1/wecom-sync/checkpoints` |
| 说明 | 分页查看机器人、联系人、群、消息各类同步检查点 |
| 鏂规硶 | GET |
| 璺緞 | `/api/v1/wecom-sync/checkpoints` |
| 璇存槑 | 鍒嗛〉鏌ョ湅鏈哄櫒浜恒€佽仈绯讳汉銆佺兢銆佹秷鎭悇绫诲悓姝ユ鏌ョ偣 |
**请求参数**
**璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 |
| 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------|
| page | query | integer | 否 | 页码,默认 1 |
| page_size | query | integer | 否 | 每页数量,默认 20,最大 100 |
| 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 | 最近完成时间 |
**成功响应示例**
| 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
{
......@@ -166,25 +166,78 @@
---
## 4. 测试场景
## 4. 娴嬭瘯鍦烘櫙
| 序号 | 场景名称 | 分类 | 预期结果 |
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------|
| 1 | 手动触发全量同步 | 正常 | 返回统一结构,`mode=full`,并返回各资源同步数量 |
| 2 | 手动触发增量同步且未传 bot_ids | 正常 | 自动读取本地机器人列表并执行增量消息同步 |
| 3 | 查询同步检查点分页列表 | 正常 | 返回分页结构,包含 `resource_type`、`scope_key`、`last_sync_time` 等字段 |
| 1 | 鎵嬪姩瑙﹀彂鍏ㄩ噺鍚屾 | 姝e父 | 杩斿洖缁熶竴缁撴瀯锛宍mode=full`锛屽苟杩斿洖鍚勮祫婧愬悓姝ユ暟閲?|
| 2 | 鎵嬪姩瑙﹀彂澧為噺鍚屾涓旀湭浼?bot_ids | 姝e父 | 鑷姩璇诲彇鏈湴鏈哄櫒浜哄垪琛ㄥ苟鎵ц澧為噺娑堟伅鍚屾 |
| 3 | 鏌ヨ鍚屾妫€鏌ョ偣鍒嗛〉鍒楄〃 | 姝e父 | 杩斿洖鍒嗛〉缁撴瀯锛屽寘鍚?`resource_type`銆乣scope_key`銆乣last_sync_time` 绛夊瓧娈?|
---
## 5. 对应测试代码
## 5. 瀵瑰簲娴嬭瘯浠g爜
测试文件:`backend/tests/test_wecom_sync_api.py`、`backend/tests/test_wecom_sync_service.py`
娴嬭瘯鏂囦欢锛歚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` | 分发失败不丢原始消息 |
| 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` | 鍒嗗彂澶辫触涓嶄涪鍘熷娑堟伅 |
---
## 附录A 字段说明
### A.1 通用响应字段
| 字段 | 类型 | 说明 |
|------|------|------|
| code | integer | 业务响应码。`200` 表示成功,`400` 表示请求参数错误,`401` 表示未授权,`403` 表示无权限,`404` 表示资源不存在,`409` 表示资源冲突,`500` 表示服务器内部错误。 |
| message | string | 响应说明。成功时固定为 `success`,失败时为具体错误原因。 |
| data | object/null | 实际业务数据。成功时返回对象或分页结构,失败时固定为 `null`。 |
### A.2 分页字段
如果接口是列表查询,则 `data` 一般使用分页结构:
| 字段 | 类型 | 说明 |
|------|------|------|
| total | integer | 总记录数。 |
| page | integer | 当前页码,默认从 `1` 开始。 |
| page_size | integer | 每页数量,默认 `20`,最大 `100`。 |
| list | array | 当前页数据列表。 |
### A.3 常见时间字段
| 字段类型 | 格式 | 说明 |
|----------|------|------|
| created_at | ISO 8601 string | 创建时间。 |
| updated_at | ISO 8601 string | 更新时间。 |
| deleted_at | ISO 8601 string | 删除时间,仅删除类接口出现。 |
| archived_at | ISO 8601 string | 归档时间,仅归档类接口出现。 |
| triggered_at | ISO 8601 string | 触发时间,仅任务或同步类接口出现。 |
### A.4 常见布尔与状态字段
| 字段 | 类型 | 说明 |
|------|------|------|
| success | boolean | 是否成功,通常用于删除、归档、状态切换等动作接口。 |
| status | string | 业务状态字段,具体取值以各接口正文说明为准,例如 `enable`、`disable`、`active`、`archived`、`failed`。 |
### A.5 ID 与编码字段
| 字段类型 | 说明 |
|----------|------|
| `*_id` | 业务主键或外部主键。不同模块含义不同,需结合接口正文说明理解。 |
| `*_code` | 业务编码字段,通常用于唯一标识某类对象,稳定性高于展示名称。 |
### A.6 说明约定
- 具体接口字段的业务含义,以各文档正文中的“请求参数”“响应参数”“示例响应”为准。
- 本附录用于统一解释所有文档里重复出现的通用字段,避免重复写相同说明。
- 如果某个接口没有分页能力,则不会返回 `total / page / page_size / list`。
CREATE TABLE IF NOT EXISTS ai_agent_users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
agent_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
CONSTRAINT fk_ai_agent_users_agent
FOREIGN KEY (agent_id) REFERENCES ai_agents(id) ON DELETE CASCADE,
CONSTRAINT uk_agent_user UNIQUE (agent_id, user_id)
);
CREATE INDEX IF NOT EXISTS idx_ai_agent_users_agent_id ON ai_agent_users(agent_id);
CREATE INDEX IF NOT EXISTS idx_ai_agent_users_user_id ON ai_agent_users(user_id);
CREATE UNIQUE INDEX IF NOT EXISTS uk_ai_agents_name_not_deleted
ON ai_agents(name)
WHERE is_deleted = 0;
CREATE UNIQUE INDEX IF NOT EXISTS uk_position_tags_name
ON position_tags(name);
CREATE TABLE IF NOT EXISTS position_tag_users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
position_tag_id INTEGER NOT NULL,
wecom_bot_id INTEGER NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
CONSTRAINT fk_position_tag_users_tag
FOREIGN KEY (position_tag_id) REFERENCES position_tags(id) ON DELETE CASCADE,
CONSTRAINT uk_position_tag_user UNIQUE (position_tag_id, wecom_bot_id)
);
CREATE INDEX IF NOT EXISTS idx_position_tag_users_tag_id ON position_tag_users(position_tag_id);
CREATE INDEX IF NOT EXISTS idx_position_tag_users_bot_id ON position_tag_users(wecom_bot_id);
-- Remove deprecated columns from qrcode_channels:
-- 1) position_code
-- 2) wechat_user_id
-- SQLite doesn't support DROP COLUMN safely in all deployed versions,
-- so rebuild table and migrate data.
PRAGMA foreign_keys=off;
BEGIN TRANSACTION;
CREATE TABLE qrcode_channels_new (
id INTEGER PRIMARY KEY,
qrcode_name VARCHAR(50),
position_name VARCHAR(100) NOT NULL DEFAULT '',
employee_id VARCHAR(100) NOT NULL,
employee_name VARCHAR(100) NOT NULL DEFAULT '',
channel_code VARCHAR(100) NOT NULL,
qrcode_url VARCHAR(500),
agent_ids JSON,
agent_names JSON,
remark VARCHAR(200),
welcome_message VARCHAR(500),
status VARCHAR(20) NOT NULL DEFAULT 'enable',
disable_reason VARCHAR(200),
created_by VARCHAR(64),
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uk_position_name UNIQUE (position_name),
CONSTRAINT uq_qrcode_channels_channel_code UNIQUE (channel_code)
);
INSERT INTO qrcode_channels_new (
id,
qrcode_name,
position_name,
employee_id,
employee_name,
channel_code,
qrcode_url,
agent_ids,
agent_names,
remark,
welcome_message,
status,
disable_reason,
created_by,
created_at,
updated_at
)
SELECT
id,
qrcode_name,
position_name,
employee_id,
employee_name,
channel_code,
qrcode_url,
agent_ids,
agent_names,
remark,
welcome_message,
status,
disable_reason,
created_by,
created_at,
updated_at
FROM qrcode_channels;
DROP TABLE qrcode_channels;
ALTER TABLE qrcode_channels_new RENAME TO qrcode_channels;
CREATE INDEX ix_qrcode_channels_id ON qrcode_channels (id);
CREATE INDEX ix_qrcode_channels_employee_id ON qrcode_channels (employee_id);
CREATE UNIQUE INDEX ix_qrcode_channels_channel_code ON qrcode_channels (channel_code);
COMMIT;
PRAGMA foreign_keys=on;
-- Enforce one qrcode per position_name.
-- Rebuild qrcode_channels to replace UNIQUE(position_name, employee_id)
-- with UNIQUE(position_name).
PRAGMA foreign_keys=off;
BEGIN TRANSACTION;
CREATE TABLE qrcode_channels_new (
id INTEGER PRIMARY KEY,
qrcode_name VARCHAR(50),
position_name VARCHAR(100) NOT NULL DEFAULT '',
employee_id VARCHAR(100) NOT NULL,
employee_name VARCHAR(100) NOT NULL DEFAULT '',
channel_code VARCHAR(100) NOT NULL,
qrcode_url VARCHAR(500),
agent_ids JSON,
agent_names JSON,
remark VARCHAR(200),
welcome_message VARCHAR(500),
status VARCHAR(20) NOT NULL DEFAULT 'enable',
disable_reason VARCHAR(200),
created_by VARCHAR(64),
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uk_position_name UNIQUE (position_name),
CONSTRAINT uq_qrcode_channels_channel_code UNIQUE (channel_code)
);
INSERT INTO qrcode_channels_new (
id,
qrcode_name,
position_name,
employee_id,
employee_name,
channel_code,
qrcode_url,
agent_ids,
agent_names,
remark,
welcome_message,
status,
disable_reason,
created_by,
created_at,
updated_at
)
SELECT
id,
qrcode_name,
position_name,
employee_id,
employee_name,
channel_code,
qrcode_url,
agent_ids,
agent_names,
remark,
welcome_message,
status,
disable_reason,
created_by,
created_at,
updated_at
FROM qrcode_channels;
DROP TABLE qrcode_channels;
ALTER TABLE qrcode_channels_new RENAME TO qrcode_channels;
CREATE INDEX ix_qrcode_channels_id ON qrcode_channels (id);
CREATE INDEX ix_qrcode_channels_employee_id ON qrcode_channels (employee_id);
CREATE UNIQUE INDEX ix_qrcode_channels_channel_code ON qrcode_channels (channel_code);
COMMIT;
PRAGMA foreign_keys=on;
-- Create relation tables:
-- 1) position <-> qrcode (one position at most one qrcode)
-- 2) qrcode <-> employee(bot) (one qrcode at most one bot, one bot at most one qrcode)
CREATE TABLE IF NOT EXISTS qrcode_position_bindings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
position_id INTEGER NOT NULL,
qrcode_id INTEGER NOT NULL UNIQUE,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uk_qrcode_position_binding_position UNIQUE (position_id),
FOREIGN KEY(position_id) REFERENCES position_tags(id) ON DELETE CASCADE,
FOREIGN KEY(qrcode_id) REFERENCES qrcode_channels(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS ix_qrcode_position_bindings_position_id ON qrcode_position_bindings(position_id);
CREATE INDEX IF NOT EXISTS ix_qrcode_position_bindings_qrcode_id ON qrcode_position_bindings(qrcode_id);
CREATE TABLE IF NOT EXISTS qrcode_employee_bindings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
qrcode_id INTEGER NOT NULL UNIQUE,
wecom_bot_id INTEGER NOT NULL UNIQUE,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uk_qrcode_employee_binding UNIQUE (qrcode_id, wecom_bot_id),
FOREIGN KEY(qrcode_id) REFERENCES qrcode_channels(id) ON DELETE CASCADE,
FOREIGN KEY(wecom_bot_id) REFERENCES wecom_bots(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS ix_qrcode_employee_bindings_qrcode_id ON qrcode_employee_bindings(qrcode_id);
CREATE INDEX IF NOT EXISTS ix_qrcode_employee_bindings_wecom_bot_id ON qrcode_employee_bindings(wecom_bot_id);
-- Flatten bindings into qrcode_channels:
-- 1) add position_id and wecom_bot_id columns
-- 2) migrate data from relation tables if present
-- 3) enforce one-to-one unique constraints on the two columns
-- 4) drop relation tables
PRAGMA foreign_keys=off;
BEGIN TRANSACTION;
ALTER TABLE qrcode_channels ADD COLUMN position_id INTEGER;
ALTER TABLE qrcode_channels ADD COLUMN wecom_bot_id INTEGER;
UPDATE qrcode_channels
SET position_id = (
SELECT pb.position_id
FROM qrcode_position_bindings pb
WHERE pb.qrcode_id = qrcode_channels.id
LIMIT 1
)
WHERE EXISTS (SELECT 1 FROM sqlite_master WHERE type='table' AND name='qrcode_position_bindings');
UPDATE qrcode_channels
SET wecom_bot_id = (
SELECT eb.wecom_bot_id
FROM qrcode_employee_bindings eb
WHERE eb.qrcode_id = qrcode_channels.id
LIMIT 1
)
WHERE EXISTS (SELECT 1 FROM sqlite_master WHERE type='table' AND name='qrcode_employee_bindings');
DROP TABLE IF EXISTS qrcode_position_bindings;
DROP TABLE IF EXISTS qrcode_employee_bindings;
CREATE UNIQUE INDEX IF NOT EXISTS uk_qrcode_position_id ON qrcode_channels(position_id);
CREATE UNIQUE INDEX IF NOT EXISTS uk_qrcode_wecom_bot_id ON qrcode_channels(wecom_bot_id);
COMMIT;
PRAGMA foreign_keys=on;
-- Add single managed user column to ai_agents.
-- managed_user_id references wecom_bots.id at business level.
ALTER TABLE ai_agents ADD COLUMN managed_user_id INTEGER;
CREATE INDEX IF NOT EXISTS ix_ai_agents_managed_user_id ON ai_agents(managed_user_id);
## Context
当前后端需要提供 Agent 的基础管理能力,包括创建、更新、删除、详情、列表与状态更新。实现基于 FastAPI + SQLAlchemy,创建接口需要由后端自动生成业务编码,详情接口需要聚合岗位、技能和会话统计。
当前后端已经提供 Agent 的基础管理能力,包括创建、更新、删除、详情、列表与状态更新。现在需要在 Agent 上增加“企业微信员工绑定”能力,用于表达某个 Agent 适用于哪些岗位下的具体员工,并且保持现有统一响应结构、分页结构与 Swagger 文档风格。
系统中暂时没有独立的员工主数据表,但已有 `qrcode_channels` 维护岗位与员工的映射关系,字段中包含岗位编码、岗位名称、企业微信员工标识和员工姓名,因此这张表最适合作为当前阶段的员工来源。
## Goals / Non-Goals
**Goals**
- 提供完整的 Agent CRUD 与状态管理接口
- 统一使用 `{code, message, data}` 响应结构
- 列表接口遵循统一分页格式
- 创建接口自动生成唯一 `code`
- Agent 详情接口返回完整展示数据
- 创建和更新 Agent 时支持传入 `user_ids`
- `user_ids` 必须严格校验为所选岗位下的员工
- 列表接口返回轻量的 `user_ids`
- 详情接口返回可展示的 `users`
- Swagger 和文档同步反映新增字段与约束
**Non-Goals**
- 当前阶段不实现 Agent 编辑并发锁定
- 当前阶段不扩展列表接口为重详情结构
- 当前阶段不让前端自定义 Agent 编码
- 当前阶段不引入独立员工主表
- 当前阶段不扩展 Agent 的消息发送或路由能力
- 当前阶段不改变前端交互流程,仅提供后端契约能力
## Decisions
### 1. 数据模型
- `ai_agents` 存储 Agent 主体信息:`name`、`code`、`description`、`status`、`is_deleted`、`version`
- `ai_agent_positions` 存储 Agent 与岗位标签的关联
- `ai_agent_skills` 存储 Agent 与技能的关联
- `ai_agents` 保存 Agent 主体信息:`name`、`code`、`description`、`status`、`is_deleted`、`version`
- `ai_agent_positions` 保存 Agent 与岗位标签的关联
- `ai_agent_skills` 保存 Agent 与技能的关联
- `ai_agent_users` 保存 Agent 与员工的关联:
- `agent_id`
- `user_id`
- `created_at`
- `user_id` 指向 `qrcode_channels.id`,不是企业微信原始字符串 ID
### 2. 自动编码策略
- 创建接口请求体不再接收 `code`
- 后端在创建时生成 `agent_<8位随机十六进制串>`
- 写入前查询现有未删除 Agent,若冲突则重试
### 2. 员工来源与校验策略
- `qrcode_channels` 作为当前阶段的员工来源表:
- `id`: 本地员工记录主键
- `position_code`: 员工所属岗位编码
- `employee_id`: 企业微信员工标识
- `employee_name`: 员工展示名
- 请求中的 `user_ids` 使用 `qrcode_channels.id`
- 创建或更新 Agent 时执行以下校验:
- 每个 `user_id` 必须存在
- 每个 `user_id` 对应的 `position_code` 必须映射到本次 `position_ids` 对应岗位的 `code`
- 任一校验失败时返回 `400`
### 3. 删除策略
- Agent 使用软删除
- 删除接口返回 `success` 和 `deleted_at`
### 3. 编码生成策略
- 创建接口不再接收请求体中的 `code`
- 后端自动生成 `agent_<8位随机后缀>`
- 写入前检查未删除 Agent 中是否重复,冲突则重试
### 4. 列表与详情分离
- 列表接口保持轻量,仅返回基础信息、岗位 ID 列表和技能编码列表
- 详情接口返回完整结构,用于详情页和 Swagger 调试
### 4. 列表与详情响应策略
- 列表接口保持轻量:
- 返回 `agent_id`、`name`、`code`、`position_ids`、`skill_codes`、`user_ids`、`created_at`
- 详情接口返回完整聚合结构:
- `positions`: `{id, name}`
- `skills`: `{skill_code, skill_name}`
- `users`: `{user_id, user_name}`
- `session_count`
### 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 主表
### 5. 删除策略
- Agent 使用软删除
- 删除接口返回:
- `success`
- `deleted_at`
## Risks / Trade-offs
- **并发更新可能被后写覆盖**
当前不做乐观锁拦截,后续如进入多人高频协作场景,再评估恢复版本校验或改为显式锁定机制。
- **员工数据依赖二维码渠道表**
当前没有独立员工主表,`qrcode_channels` 的数据完整性会直接影响 Agent 员工绑定能力。
- **详情接口查询更重**
通过保持列表接口轻量化,把额外聚合成本收敛在单条详情接口上。
- **岗位编码映射是间接关系**
`position_ids` 需要先查 `position_tags.code`,再和 `qrcode_channels.position_code` 比较,查询路径稍长,但能避免重复维护员工归属。
- **自动编码不可读性一般**
当前优先保证稳定唯一和实现简单,如后续需要更强业务语义,再评估引入前缀映射规则。
- **后续主数据迁移成本**
如果未来引入独立员工表,需要重新审视 `ai_agent_users.user_id` 的语义以及迁移策略。
## Why
允许管理员在后台管理 Agent 的生命周期,包括创建、编辑、删除、查询以及状态控制。这是 Agent 管理后台的核心功能,为后续的岗位关联和 Skill 配置提供基础支撑。
允许管理员在后台管理 Agent 的生命周期,包括创建、编辑、删除、查询以及状态控制。这是 Agent 管理后台的核心能力,为后续的岗位关联、Skill 配置以及企业微信员工绑定提供基础支撑。
## What Changes
- **新增 Agent 创建接口**: 支持配置名称、编码、岗位关联、Skill 关联及描述。
- **新增 Agent 编辑接口**: 支持修改名称、岗位、Skill 及状态(编码不可修改)。
- **新增 Agent 删除接口**: 实现软删除逻辑,并增加引用检查。
- **新增 Agent 列表查询**: 支持分页、关键词搜索、按岗位和状态筛选。
- **新增 Agent 详情查询**: 返回 Agent 的完整配置信息、关联岗位和 Skill。
- **新增 Agent 创建接口**: 支持配置名称、岗位关联、Skill 关联、企业微信员工绑定及描述。
- **新增 Agent 编辑接口**: 支持修改名称、岗位、Skill、员工及状态,编码仍不可修改。
- **新增 Agent 删除接口**: 实现软删除逻辑,并返回删除结果。
- **新增 Agent 列表查询**: 支持分页、关键字搜索、按岗位和状态筛选,并返回轻量员工 ID 列表。
- **新增 Agent 详情查询**: 返回 Agent 的完整配置信息、关联岗位、Skill、员工和会话统计。
- **新增 Agent 状态管理**: 支持一键启用或停用 Agent。
## Capabilities
### New Capabilities
- `agent-management`: 涵盖 Agent 的增删改查及状态管理全生命周期。
- `agent-management`: 覆盖 Agent 的增删改查、员工绑定及状态管理全生命周期。
### Modified Capabilities
<!-- 无 -->
......@@ -22,5 +22,6 @@
## Impact
- **API**: 新增 `/api/v1/agents` 及其相关子路径。
- **数据库**: 需要设计 `agents` 表,以及 `agent_positions` 和 `agent_skills` 中间表。
- **关联系统**: 影响路由分发层(状态同步)及会话管理系统(删除校验)。
- **数据库**: 需要在现有 `agents`、`agent_positions`、`agent_skills` 之外新增 `agent_users` 关联表。
- **关联系统**: 员工来源依赖已有 `qrcode_channels` 岗位员工映射数据。
- **测试覆盖**: 需要补充员工绑定成功、员工不存在、员工不属于已选岗位等场景。
......@@ -4,9 +4,10 @@
系统 SHALL 提供创建 Agent 的接口,并由后端自动生成唯一编码。
#### Scenario: 创建成功
- **WHEN** 请求提供合法的 `name`、`position_ids`、`skill_codes`、`description`、`status`
- **WHEN** 请求提供合法的 `name`、`position_ids`、`skill_codes`、`user_ids`、`description`、`status`
- **THEN** 系统创建 Agent 并返回统一成功响应
- **AND** `data.code` 由后端自动生成
- **AND** `data.user_ids` 返回已绑定员工 ID 列表
#### Scenario: 自动编码规则
- **WHEN** 系统创建 Agent
......@@ -14,17 +15,35 @@
- **AND** 后缀为随机字符串
- **AND** 最终写入前必须校验与现有未删除 Agent 编码不重复
#### Scenario: 创建时绑定岗位下员工
- **WHEN** 请求中的 `user_ids` 都存在
- **AND** 每个员工都属于 `position_ids` 指定岗位之一
- **THEN** 系统保存 Agent 与员工的绑定关系
#### Scenario: 创建时员工不存在
- **WHEN** 请求中的任意 `user_id` 不存在
- **THEN** 系统返回 400 错误响应
#### Scenario: 创建时员工不属于已选岗位
- **WHEN** 请求中的任意 `user_id` 不属于 `position_ids` 指定的岗位
- **THEN** 系统返回 400 错误响应
### Requirement: 更新 Agent
系统 SHALL 提供更新 Agent 的接口,用于修改名称、描述、状态、岗位关联和技能关联。
系统 SHALL 提供更新 Agent 的接口,用于修改名称、描述、状态、岗位关联、技能关联和员工关联。
#### Scenario: 更新成功
- **WHEN** 请求提供合法的 `name`、`position_ids`、`skill_codes`、`description`、`status`
- **WHEN** 请求提供合法的 `name`、`position_ids`、`skill_codes`、`user_ids`、`description`、`status`
- **THEN** 系统更新目标 Agent,并返回统一成功响应
- **AND** `data.user_ids` 返回最新绑定员工 ID 列表
#### Scenario: 更新不存在的 Agent
- **WHEN** 请求中的 `agent_id` 不存在或已软删除
- **THEN** 系统返回 404 错误响应
#### Scenario: 更新时重建员工绑定
- **WHEN** 请求传入新的 `user_ids`
- **THEN** 系统替换 Agent 原有的员工绑定关系
### Requirement: 删除 Agent
系统 SHALL 提供软删除 Agent 的接口。
......@@ -37,12 +56,16 @@
#### Scenario: 查询成功
- **WHEN** 请求中的 `agent_id` 存在
- **THEN** 系统返回统一成功响应,`data` 中包含 `agent_id`、`name`、`code`、`description`、`positions`、`skills`、`status`、`session_count`、`created_at`、`updated_at`
- **THEN** 系统返回统一成功响应,`data` 中包含 `agent_id`、`name`、`code`、`description`、`positions`、`skills`、`users`、`status`、`session_count`、`created_at`、`updated_at`
#### Scenario: 详情中的岗位和技能信息
- **WHEN** Agent 已关联岗位和技能
- **THEN** `positions` 返回 `{id, name}` 列表,`skills` 返回 `{skill_code, skill_name}` 列表
#### Scenario: 详情中的员工信息
- **WHEN** Agent 已关联员工
- **THEN** `users` 返回 `{user_id, user_name}` 列表
#### Scenario: 详情中的会话统计
- **WHEN** Agent 已关联会话
- **THEN** `session_count` 返回该 Agent 的全部会话总数
......@@ -58,6 +81,10 @@
- **WHEN** 请求提供 `keyword`、`position_id` 或 `status`
- **THEN** 系统按条件过滤返回结果
#### Scenario: 列表项返回员工 ID
- **WHEN** 系统返回 Agent 列表
- **THEN** 每个列表项包含 `user_ids`
### Requirement: 更新 Agent 状态
系统 SHALL 提供单独的 Agent 状态更新接口。
......
## 1. 数据库准备
- [x] 1.1 创建 `agents` 表迁移,包含 `is_deleted` 和 `version` 字段
- [x] 1.2 创建 `agent_positions` 和 `agent_skills` 关联表迁移
- [ ] 1.3 补充索引与约束校验
- [ ] 1.1 新增 `agent_users` 关联表迁移
- [ ] 1.2 为 `agent_users` 补充唯一约束与索引
## 2. 模型与 Schema
- [x] 2.1 实现 SQLAlchemy ORM:`Agent`、`AgentPosition`、`AgentSkill`
- [x] 2.2 实现创建/更新请求 Schema
- [x] 2.3 实现列表/详情响应 Schema
- [ ] 2.1 扩展 SQLAlchemy ORM:新增 `AgentUser`
- [ ] 2.2 扩展创建/更新请求 Schema,增加 `user_ids`
- [ ] 2.3 扩展列表响应 Schema,增加 `user_ids`
- [ ] 2.4 扩展详情响应 Schema,增加 `users`
- [ ] 2.5 更新 Swagger 字段描述与示例
## 3. 服务层
- [x] 3.1 实现 Agent 创建逻辑,创建时自动生成唯一 `code`
- [x] 3.2 实现 Agent 编辑逻辑,支持全量替换岗位与技能关联
- [x] 3.3 实现 Agent 软删除逻辑
- [x] 3.4 实现 Agent 列表查询逻辑,支持分页和条件筛选
- [x] 3.5 实现 Agent 状态更新逻辑
- [x] 3.6 实现 Agent 详情聚合逻辑,返回岗位名称、技能名称和全部会话总数
- [ ] 3.1 实现员工存在性校验
- [ ] 3.2 实现员工岗位归属校验
- [ ] 3.3 创建 Agent 时写入员工绑定关系
- [ ] 3.4 更新 Agent 时同步替换员工绑定关系
- [ ] 3.5 列表接口返回 `user_ids`
- [ ] 3.6 详情接口聚合 `users`
## 4. API 层
- [x] 4.1 挂载 `POST /api/v1/agents` 创建接口
- 请求参数:`name`、`description`、`position_ids`、`skill_codes`、`status`
- 响应中的 `code` 由后端自动生成
- [x] 4.2 挂载 `PUT /api/v1/agents/{agent_id}` 更新接口
- [x] 4.3 挂载 `DELETE /api/v1/agents/{agent_id}` 删除接口
- [x] 4.4 挂载 `GET /api/v1/agents` 列表接口
- [x] 4.5 挂载 `GET /api/v1/agents/{agent_id}` 详情接口
- 返回:`agent_id`、`name`、`code`、`description`、`positions`、`skills`、`status`、`session_count`、`created_at`、`updated_at`
- [x] 4.6 挂载 `PUT /api/v1/agents/{agent_id}/status` 状态接口
## 5. 测试
- [x] 5.1 创建接口测试
- [x] 5.2 更新接口测试
- [x] 5.3 删除接口测试
- [x] 5.4 列表接口测试
- [x] 5.5 详情接口测试
- [x] 5.6 状态接口测试
- [ ] 4.1 调整 `POST /api/v1/agents` 请求体,增加 `user_ids`
- [ ] 4.2 调整 `PUT /api/v1/agents/{agent_id}` 请求体,增加 `user_ids`
- [ ] 4.3 调整创建/更新/列表响应体,返回 `user_ids`
- [ ] 4.4 调整详情响应体,返回 `users`
## 5. 测试与文档
- [ ] 5.1 创建接口测试覆盖 `user_ids`
- [ ] 5.2 更新接口测试覆盖 `user_ids`
- [ ] 5.3 列表接口测试覆盖 `user_ids`
- [ ] 5.4 详情接口测试覆盖 `users`
- [ ] 5.5 增加员工不存在校验测试
- [ ] 5.6 增加员工不属于已选岗位校验测试
- [ ] 5.7 更新 wangxz 接口测试文档
......@@ -4,7 +4,10 @@ import pytest
from fastapi import HTTPException
from app.main import app
from app.model.agent import Agent, AgentStatus
from app.model.agent_group import QrcodeChannel
from app.model.position_tag import PositionTag
from app.model.wecom_sync import WeComBot
from tests.conftest import TestingSessionLocal
......@@ -23,6 +26,9 @@ class FakeWeComClient:
def clean_db():
db = TestingSessionLocal()
db.query(QrcodeChannel).delete()
db.query(Agent).delete()
db.query(WeComBot).delete()
db.query(PositionTag).delete()
db.commit()
db.close()
......@@ -30,12 +36,23 @@ def clean_db():
class TestPositionEmployees:
def test_position_employees_route_is_registered(self):
paths = {route.path for route in app.routes}
assert "/api/v1/agent-group/position/{position_code}/employees" in paths
def test_returns_active_position_employees(self):
def test_returns_position_employees_and_agent_mount_status(self):
from app.api.v1.endpoints.agent_group_helper import get_position_employees
db = TestingSessionLocal()
db.add(PositionTag(id=1, name="驻店销售岗", code="store_sales"))
db.add_all(
[
WeComBot(id=1, channel="wt_ww", bot_id="emp_12345", bot_code="wt_ww:emp_12345", bot_name="张三"),
WeComBot(id=2, channel="wt_ww", bot_id="emp_67890", bot_code="wt_ww:emp_67890", bot_name="李四"),
Agent(id=101, name="复盘 Agent", code="agent_101", status=AgentStatus.enable, managed_user_id=1),
]
)
db.commit()
db.close()
result = get_position_employees(
"store_sales",
TestingSessionLocal(),
......@@ -48,15 +65,13 @@ class TestPositionEmployees:
"employee_id": "emp_12345",
"employee_name": "张三",
"wechat_user_id": "zhangsan",
"department": "销售部",
"status": "在职",
},
{
"employee_id": "emp_67890",
"employee_name": "李四",
"wechat_user_id": "lisi",
"department": "销售部",
"status": "离职",
"status": "在职",
},
],
}
......@@ -66,15 +81,20 @@ class TestPositionEmployees:
data = result.model_dump()
assert data["position_name"] == "驻店销售岗"
assert data["employee_count"] == 1
assert data["employee_count"] == 2
assert data["employees"] == [
{
"employee_id": "emp_12345",
"employee_name": "张三",
"wechat_user_id": "zhangsan",
"department": "销售部",
"status": "在职",
}
"status": "已挂载Agent",
},
{
"employee_id": "emp_67890",
"employee_name": "李四",
"wechat_user_id": "lisi",
"status": "未挂载Agent",
},
]
def test_unknown_position_returns_404(self):
......@@ -82,26 +102,24 @@ class TestPositionEmployees:
with pytest.raises(HTTPException) as exc_info:
get_position_employees("missing", TestingSessionLocal(), FakeWeComClient())
assert exc_info.value.status_code == 404
def test_wecom_failure_returns_503(self):
from app.api.v1.endpoints.agent_group_helper import get_position_employees
with pytest.raises(HTTPException) as exc_info:
get_position_employees(
"store_sales",
TestingSessionLocal(),
FakeWeComClient(failures={"store_sales"}),
)
db = TestingSessionLocal()
db.add(PositionTag(id=1, name="驻店销售岗", code="store_sales"))
db.commit()
db.close()
with pytest.raises(HTTPException) as exc_info:
get_position_employees("store_sales", TestingSessionLocal(), FakeWeComClient(failures={"store_sales"}))
assert exc_info.value.status_code == 503
class TestEmployeeQrcodes:
def test_employee_qrcodes_route_is_registered(self):
paths = {route.path for route in app.routes}
assert "/api/v1/agent-group/employee/{employee_id}/qrcodes" in paths
def test_returns_employee_qrcodes(self):
......@@ -111,50 +129,20 @@ class TestEmployeeQrcodes:
db.add(
QrcodeChannel(
id=1,
position_id=1,
wecom_bot_id=1,
employee_id="emp_12345",
employee_name="张三",
position_name="驻店销售岗",
channel_code="zdxs_store_sales_emp_12345",
channel_code="store_sales",
status="enable",
created_at=datetime(2026, 5, 15, 10, 0, tzinfo=timezone.utc),
)
)
db.add(
QrcodeChannel(
id=2,
employee_id="emp_other",
employee_name="李四",
position_name="驻店销售岗",
channel_code="zdxs_store_sales_emp_other",
status="enable",
created_at=datetime(2026, 5, 16, 10, 0, tzinfo=timezone.utc),
)
)
db.commit()
db.close()
result = get_employee_qrcodes("emp_12345", TestingSessionLocal())
data = result.model_dump(mode="json")
assert data["employee_name"] == "张三"
assert data["qrcode_count"] == 1
assert data["qrcodes"] == [
{
"qrcode_id": 1,
"position_name": "驻店销售岗",
"channel_code": "zdxs_store_sales_emp_12345",
"status": "enable",
"created_at": "2026-05-15T10:00:00",
}
]
def test_returns_empty_qrcode_list_for_employee_without_qrcodes(self):
from app.api.v1.endpoints.agent_group_helper import get_employee_qrcodes
result = get_employee_qrcodes("emp_empty", TestingSessionLocal())
assert result.model_dump() == {
"employee_name": "",
"qrcode_count": 0,
"qrcodes": [],
}
......@@ -2,7 +2,8 @@ import pytest
from fastapi.testclient import TestClient
from app.main import app
from app.model.agent import Agent, AgentPosition, AgentSkill
from app.model.agent import Agent, AgentPosition, AgentSkill, AgentUser
from app.model.agent_group import QrcodeChannel
from app.model.position_tag import PositionTag
from app.model.session import Session
from app.model.skill import Skill
......@@ -16,7 +17,9 @@ def clean_db():
db = TestingSessionLocal()
db.query(Session).delete()
db.query(Skill).delete()
db.query(QrcodeChannel).delete()
db.query(PositionTag).delete()
db.query(AgentUser).delete()
db.query(AgentSkill).delete()
db.query(AgentPosition).delete()
db.query(Agent).delete()
......@@ -25,8 +28,50 @@ def clean_db():
yield
def seed_positions_and_users():
db = TestingSessionLocal()
db.add_all(
[
PositionTag(id=1, name="驻店销售岗", code="store_sales"),
PositionTag(id=2, name="客服岗", code="customer_service"),
PositionTag(id=3, name="招商主管", code="sales_manager"),
Skill(skill_code="query-metric", skill_name="指标查询"),
Skill(skill_code="query-detail", skill_name="明细查询"),
Skill(skill_code="attribution-analysis", skill_name="归因分析"),
QrcodeChannel(
id=1,
position_code="store_sales",
position_name="驻店销售岗",
employee_id="emp_001",
employee_name="张三",
channel_code="zdxs_store_sales_emp_001",
),
QrcodeChannel(
id=2,
position_code="customer_service",
position_name="客服岗",
employee_id="emp_002",
employee_name="李四",
channel_code="zdxs_customer_service_emp_002",
),
QrcodeChannel(
id=3,
position_code="sales_manager",
position_name="招商主管",
employee_id="emp_003",
employee_name="王五",
channel_code="zdxs_sales_manager_emp_003",
),
]
)
db.commit()
db.close()
class TestCreateAgent:
def test_create_agent_success(self):
seed_positions_and_users()
resp = client.post(
"/api/v1/agents",
json={
......@@ -34,6 +79,7 @@ class TestCreateAgent:
"description": "review desc",
"position_ids": [1],
"skill_codes": ["query-metric"],
"user_ids": [1],
"status": "enable",
},
)
......@@ -43,13 +89,15 @@ class TestCreateAgent:
assert payload["message"] == "success"
data = payload["data"]
assert data["name"] == "Review Agent"
assert data["code"].startswith("agent_")
assert "agent_id" in data
assert data["position_ids"] == [1]
assert data["skill_codes"] == ["query-metric"]
assert data["user_ids"] == [1]
assert "created_at" in data
def test_create_agent_generates_unique_code(self):
def test_create_agent_name_conflict(self):
seed_positions_and_users()
first_resp = client.post(
"/api/v1/agents",
json={
......@@ -57,30 +105,62 @@ class TestCreateAgent:
"description": "desc",
"position_ids": [1],
"skill_codes": ["query-metric"],
"user_ids": [1],
"status": "enable",
},
)
first_code = first_resp.json()["data"]["code"]
assert first_resp.status_code == 201
resp = client.post(
"/api/v1/agents",
json={
"name": "Agent Two",
"name": "Agent One",
"description": "desc",
"position_ids": [1],
"skill_codes": ["query-metric"],
"user_ids": [1],
"status": "enable",
},
)
assert resp.status_code == 201
payload = resp.json()
assert payload["code"] == 201
assert payload["data"]["code"].startswith("agent_")
assert payload["data"]["code"] != first_code
assert resp.status_code == 400
def test_create_agent_rejects_unknown_user(self):
seed_positions_and_users()
resp = client.post(
"/api/v1/agents",
json={
"name": "Invalid User Agent",
"description": "desc",
"position_ids": [1],
"skill_codes": ["query-metric"],
"user_ids": [999],
"status": "enable",
},
)
assert resp.status_code == 400
def test_create_agent_rejects_user_outside_positions(self):
seed_positions_and_users()
resp = client.post(
"/api/v1/agents",
json={
"name": "Invalid Position Agent",
"description": "desc",
"position_ids": [1],
"skill_codes": ["query-metric"],
"user_ids": [2],
"status": "enable",
},
)
assert resp.status_code == 400
class TestUpdateAgent:
def test_update_agent_success(self):
seed_positions_and_users()
create_resp = client.post(
"/api/v1/agents",
json={
......@@ -88,6 +168,7 @@ class TestUpdateAgent:
"description": "before update",
"position_ids": [1],
"skill_codes": ["query-metric"],
"user_ids": [1],
"status": "enable",
},
)
......@@ -101,6 +182,7 @@ class TestUpdateAgent:
"status": "enable",
"position_ids": [1, 2],
"skill_codes": ["query-metric", "query-detail"],
"user_ids": [1, 2],
},
)
assert resp.status_code == 200
......@@ -111,8 +193,11 @@ class TestUpdateAgent:
assert data["name"] == "Updated Agent"
assert data["position_ids"] == [1, 2]
assert sorted(data["skill_codes"]) == ["query-detail", "query-metric"]
assert data["user_ids"] == [1, 2]
def test_update_agent_without_version(self):
seed_positions_and_users()
create_resp = client.post(
"/api/v1/agents",
json={
......@@ -120,6 +205,7 @@ class TestUpdateAgent:
"description": "desc",
"position_ids": [1],
"skill_codes": ["query-metric"],
"user_ids": [1],
"status": "enable",
},
)
......@@ -133,6 +219,7 @@ class TestUpdateAgent:
"status": "enable",
"position_ids": [1],
"skill_codes": ["query-metric"],
"user_ids": [1],
},
)
assert resp.status_code == 200
......@@ -144,6 +231,8 @@ class TestUpdateAgent:
class TestDeleteAgent:
def test_delete_agent_success(self):
seed_positions_and_users()
create_resp = client.post(
"/api/v1/agents",
json={
......@@ -151,6 +240,7 @@ class TestDeleteAgent:
"description": "desc",
"position_ids": [1],
"skill_codes": ["query-metric"],
"user_ids": [1],
"status": "enable",
},
)
......@@ -170,17 +260,7 @@ class TestDeleteAgent:
class TestGetAgentDetail:
def test_get_agent_detail_success(self):
db = TestingSessionLocal()
db.add_all(
[
PositionTag(id=1, name="驻店销售岗", code="store_sales"),
PositionTag(id=3, name="客服岗", code="customer_service"),
Skill(skill_code="query-metric", skill_name="指标查询"),
Skill(skill_code="query-detail", skill_name="明细查询"),
]
)
db.commit()
db.close()
seed_positions_and_users()
create_resp = client.post(
"/api/v1/agents",
......@@ -189,6 +269,7 @@ class TestGetAgentDetail:
"description": "desc",
"position_ids": [1, 3],
"skill_codes": ["query-metric", "query-detail"],
"user_ids": [1, 3],
"status": "enable",
},
)
......@@ -224,24 +305,29 @@ class TestGetAgentDetail:
data = payload["data"]
assert data["agent_id"] == agent_id
assert data["name"] == "Detail Agent"
assert data["code"].startswith("agent_")
assert data["description"] == "desc"
assert data["status"] == "enable"
assert data["session_count"] == 2
assert data["positions"] == [
{"id": 1, "name": "驻店销售岗"},
{"id": 3, "name": "客服岗"},
{"id": 3, "name": "招商主管"},
]
assert data["skills"] == [
{"skill_code": "query-detail", "skill_name": "明细查询"},
{"skill_code": "query-metric", "skill_name": "指标查询"},
]
assert data["users"] == [
{"user_id": 1, "user_name": "张三"},
{"user_id": 3, "user_name": "王五"},
]
assert "created_at" in data
assert "updated_at" in data
class TestListAgents:
def test_list_agents_success(self):
seed_positions_and_users()
r1 = client.post(
"/api/v1/agents",
json={
......@@ -249,6 +335,7 @@ class TestListAgents:
"description": "desc1",
"position_ids": [1],
"skill_codes": ["query-metric"],
"user_ids": [1],
"status": "enable",
},
)
......@@ -260,6 +347,7 @@ class TestListAgents:
"description": "desc2",
"position_ids": [2],
"skill_codes": ["query-detail"],
"user_ids": [2],
"status": "enable",
},
)
......@@ -278,8 +366,11 @@ class TestListAgents:
assert "agent_id" in item
assert "position_ids" in item
assert "skill_codes" in item
assert "user_ids" in item
def test_list_agents_with_keyword(self):
seed_positions_and_users()
client.post(
"/api/v1/agents",
json={
......@@ -287,6 +378,7 @@ class TestListAgents:
"description": "desc",
"position_ids": [1],
"skill_codes": ["query-metric"],
"user_ids": [1],
"status": "enable",
},
)
......@@ -302,6 +394,8 @@ class TestListAgents:
class TestUpdateStatus:
def test_disable_agent(self):
seed_positions_and_users()
create_resp = client.post(
"/api/v1/agents",
json={
......@@ -309,6 +403,7 @@ class TestUpdateStatus:
"description": "desc",
"position_ids": [1],
"skill_codes": ["query-metric"],
"user_ids": [1],
"status": "enable",
},
)
......
......@@ -4,7 +4,8 @@ from fastapi.testclient import TestClient
from app.main import app
from app.model.agent import Agent, AgentPosition, AgentSkill, AgentStatus
from app.model.agent_group import QrcodeChannel
from app.model.position_tag import OfficialTab, PositionTag
from app.model.position_tag import OfficialTab, PositionTag, PositionTagUser
from app.model.wecom_sync import WeComBot
from tests.conftest import TestingSessionLocal
client = TestClient(app)
......@@ -17,6 +18,8 @@ def clean_db():
db.query(AgentPosition).delete()
db.query(Agent).delete()
db.query(QrcodeChannel).delete()
db.query(PositionTagUser).delete()
db.query(WeComBot).delete()
db.query(OfficialTab).delete()
db.query(PositionTag).delete()
db.commit()
......@@ -24,289 +27,179 @@ def clean_db():
yield
def _create_position_tag(name="销售岗", code="sales", description="销售岗位"):
def _seed_employees():
db = TestingSessionLocal()
db.add_all(
[
WeComBot(id=1, channel="wt_ww", bot_id="emp_001", bot_code="wt_ww:emp_001", bot_name="张三机器人"),
WeComBot(id=2, channel="wt_ww", bot_id="emp_002", bot_code="wt_ww:emp_002", bot_name="李四机器人"),
]
)
db.add_all(
[
QrcodeChannel(
id=1,
position_id=1001,
position_name="未分配",
wecom_bot_id=1,
employee_id="emp_001",
employee_name="张三",
channel_code="ch_001",
status="enable",
),
QrcodeChannel(
id=2,
position_id=1002,
position_name="未分配",
wecom_bot_id=2,
employee_id="emp_002",
employee_name="李四",
channel_code="ch_002",
status="enable",
),
]
)
db.commit()
db.close()
def _create_position_tag(name="销售岗", description="销售岗位", user_ids=None):
if user_ids is None:
user_ids = [1]
return client.post(
"/api/v1/position-tags",
json={"name": name, "code": code, "description": description},
json={"name": name, "description": description, "user_ids": user_ids},
)
class TestCreatePositionTag:
def test_create_success(self):
_seed_employees()
resp = _create_position_tag()
assert resp.status_code == 201
payload = resp.json()
assert payload["code"] == 201
assert payload["message"] == "success"
data = payload["data"]
data = resp.json()["data"]
assert data["name"] == "销售岗"
assert data["code"] == "sales"
assert data["description"] == "销售岗位"
assert "id" in data
assert "created_at" in data
assert data["user_ids"] == [1]
assert data["agents"] == []
def test_create_code_conflict_returns_409(self):
_create_position_tag(code="duplicate_code")
resp = _create_position_tag(name="重复岗位", code="duplicate_code")
def test_create_name_conflict_returns_409(self):
_seed_employees()
_create_position_tag(name="重复岗位")
resp = _create_position_tag(name="重复岗位")
assert resp.status_code == 409
payload = resp.json()
assert payload["code"] == 409
assert payload["data"] is None
def test_create_invalid_code_format(self):
resp = _create_position_tag(code="123invalid")
def test_create_requires_user_ids(self):
_seed_employees()
resp = client.post("/api/v1/position-tags", json={"name": "无员工岗位", "description": "x"})
assert resp.status_code == 400
def test_create_with_invalid_user_ids_returns_400(self):
_seed_employees()
resp = _create_position_tag(name="非法员工岗位", user_ids=[999])
assert resp.status_code == 400
payload = resp.json()
assert payload["code"] == 400
assert payload["data"] is None
def test_create_binds_users_to_position(self):
_seed_employees()
resp = _create_position_tag(name="驻店销售岗", user_ids=[1, 2])
assert resp.status_code == 201
db = TestingSessionLocal()
rows = (
db.query(PositionTagUser)
.filter(PositionTagUser.position_tag_id == resp.json()["data"]["id"])
.order_by(PositionTagUser.wecom_bot_id.asc())
.all()
)
db.close()
assert [row.wecom_bot_id for row in rows] == [1, 2]
class TestUpdatePositionTag:
def test_update_success(self):
create_resp = _create_position_tag()
def test_update_success_and_user_binding(self):
_seed_employees()
create_resp = _create_position_tag(user_ids=[1])
tag_id = create_resp.json()["data"]["id"]
resp = client.put(
f"/api/v1/position-tags/{tag_id}",
json={"name": "更新后岗位", "description": "更新后描述"},
json={"name": "更新后岗位", "description": "更新后描述", "user_ids": [2]},
)
assert resp.status_code == 200
payload = resp.json()
assert payload["code"] == 200
data = payload["data"]
data = resp.json()["data"]
assert data["name"] == "更新后岗位"
assert data["description"] == "更新后描述"
assert data["code"] == "sales"
assert data["user_ids"] == [2]
def test_update_name_conflict_returns_409(self):
_seed_employees()
first = _create_position_tag(name="岗位A", user_ids=[1])
second = _create_position_tag(name="岗位B", user_ids=[2])
second_id = second.json()["data"]["id"]
resp = client.put(
f"/api/v1/position-tags/{second_id}",
json={"name": first.json()["data"]["name"], "description": "冲突", "user_ids": [2]},
)
assert resp.status_code == 409
def test_update_nonexistent_returns_404(self):
_seed_employees()
resp = client.put(
"/api/v1/position-tags/99999",
json={"name": "不存在", "description": "不存在"},
json={"name": "不存在", "description": "不存在", "user_ids": [1]},
)
assert resp.status_code == 404
assert resp.json()["code"] == 404
class TestReferenceCheck:
def test_no_references_can_delete(self):
create_resp = _create_position_tag()
def test_update_invalid_user_ids_returns_400(self):
_seed_employees()
create_resp = _create_position_tag(user_ids=[1])
tag_id = create_resp.json()["data"]["id"]
resp = client.get(f"/api/v1/position-tags/{tag_id}/references")
assert resp.status_code == 200
data = resp.json()["data"]
assert data["can_delete"] is True
assert len(data["blocking_references"]) == 0
assert len(data["detachable_references"]) == 0
def test_blocking_reference_from_qrcode_channel(self):
create_resp = _create_position_tag(name="驻店销售岗", code="store_sales")
tag_id = create_resp.json()["data"]["id"]
db = TestingSessionLocal()
from datetime import datetime, timezone
db.add(
QrcodeChannel(
id=1,
employee_id="emp_001",
employee_name="张三",
position_name="驻店销售岗",
channel_code="ch_store_sales",
status="enable",
created_at=datetime(2026, 5, 15, 10, 0, tzinfo=timezone.utc),
)
resp = client.put(
f"/api/v1/position-tags/{tag_id}",
json={"name": "更新岗位", "description": "更新描述", "user_ids": [999]},
)
db.commit()
db.close()
resp = client.get(f"/api/v1/position-tags/{tag_id}/references")
assert resp.status_code == 200
data = resp.json()["data"]
assert data["can_delete"] is False
assert any(ref["type"] == "qrcode_channel" for ref in data["blocking_references"])
assert resp.status_code == 400
def test_blocking_reference_from_official_tab(self):
create_resp = _create_position_tag()
tag_id = create_resp.json()["data"]["id"]
db = TestingSessionLocal()
db.add(OfficialTab(id=1, tab_name="销售Tab", position_id=tag_id))
db.commit()
db.close()
resp = client.get(f"/api/v1/position-tags/{tag_id}/references")
assert resp.status_code == 200
data = resp.json()["data"]
assert data["can_delete"] is False
assert any(ref["type"] == "official_tab" for ref in data["blocking_references"])
def test_detachable_reference_from_agent(self):
create_resp = _create_position_tag()
class TestReferenceCheck:
def test_no_references_can_delete(self):
_seed_employees()
create_resp = _create_position_tag(user_ids=[1])
tag_id = create_resp.json()["data"]["id"]
db = TestingSessionLocal()
agent = Agent(id=1, name="测试Agent", code="test_agent", status=AgentStatus.enable)
db.add(agent)
db.flush()
db.add(AgentPosition(agent_id=agent.id, position_id=tag_id))
db.commit()
db.close()
resp = client.get(f"/api/v1/position-tags/{tag_id}/references")
assert resp.status_code == 200
data = resp.json()["data"]
assert data["can_delete"] is True
assert len(data["detachable_references"]) > 0
assert data["detachable_references"][0]["type"] == "agent"
def test_nonexistent_tag_returns_404(self):
resp = client.get("/api/v1/position-tags/99999/references")
assert resp.status_code == 404
assert resp.json()["code"] == 404
class TestDeletePositionTag:
def test_delete_no_references(self):
create_resp = _create_position_tag()
tag_id = create_resp.json()["data"]["id"]
resp = client.delete(f"/api/v1/position-tags/{tag_id}")
assert resp.status_code == 200
assert resp.json()["data"]["success"] is True
get_resp = client.get(f"/api/v1/position-tags/{tag_id}/references")
assert get_resp.status_code == 404
def test_delete_with_blocking_reference_returns_409(self):
create_resp = _create_position_tag()
tag_id = create_resp.json()["data"]["id"]
db = TestingSessionLocal()
db.add(OfficialTab(id=1, tab_name="关联Tab", position_id=tag_id))
db.commit()
db.close()
resp = client.delete(f"/api/v1/position-tags/{tag_id}")
assert resp.status_code == 409
assert resp.json()["code"] == 409
def test_delete_with_agent_reference_and_confirm(self):
create_resp = _create_position_tag()
tag_id = create_resp.json()["data"]["id"]
db = TestingSessionLocal()
agent = Agent(id=1, name="关联Agent", code="linked_agent", status=AgentStatus.enable)
db.add(agent)
db.flush()
db.add(AgentPosition(agent_id=agent.id, position_id=tag_id))
db.commit()
db.close()
resp = client.delete(f"/api/v1/position-tags/{tag_id}?confirm_detach_agents=true")
assert resp.status_code == 200
assert resp.json()["data"]["success"] is True
def test_delete_with_agent_reference_without_confirm_returns_409(self):
create_resp = _create_position_tag()
tag_id = create_resp.json()["data"]["id"]
db = TestingSessionLocal()
agent = Agent(id=1, name="关联Agent", code="linked_agent2", status=AgentStatus.enable)
db.add(agent)
db.flush()
db.add(AgentPosition(agent_id=agent.id, position_id=tag_id))
db.commit()
db.close()
resp = client.delete(f"/api/v1/position-tags/{tag_id}")
assert resp.status_code == 409
assert resp.json()["code"] == 409
def test_delete_nonexistent_returns_404(self):
resp = client.delete("/api/v1/position-tags/99999")
assert resp.status_code == 404
assert resp.json()["code"] == 404
class TestListPositionTags:
def test_list_success(self):
_create_position_tag(name="销售岗", code="sales")
_create_position_tag(name="客服岗", code="service")
_seed_employees()
_create_position_tag(name="销售岗", user_ids=[1])
_create_position_tag(name="客服岗", user_ids=[2])
resp = client.get("/api/v1/position-tags?page=1&page_size=20")
assert resp.status_code == 200
payload = resp.json()
assert payload["code"] == 200
data = payload["data"]
assert data["total"] >= 2
assert data["page"] == 1
assert data["page_size"] == 20
def test_list_with_keyword(self):
_create_position_tag(name="销售岗", code="sales")
_create_position_tag(name="客服岗", code="service")
resp = client.get("/api/v1/position-tags?keyword=销售")
assert resp.status_code == 200
data = resp.json()["data"]
assert data["total"] >= 1
assert any(tag["name"] == "销售岗" for tag in data["list"])
def test_list_keyword_matches_code(self):
_create_position_tag(name="销售岗", code="sales_keyword_test")
resp = client.get("/api/v1/position-tags?keyword=sales_keyword_test")
assert resp.status_code == 200
data = resp.json()["data"]
assert data["total"] >= 1
def test_list_empty(self):
resp = client.get("/api/v1/position-tags?page=1&page_size=20")
assert resp.status_code == 200
data = resp.json()["data"]
assert data["total"] == 0
assert data["page"] == 1
assert data["page_size"] == 20
assert data["list"] == []
assert data["total"] >= 2
assert all("user_ids" in row for row in data["list"])
assert all("agents" in row for row in data["list"])
class TestPositionTagAgentStatistics:
def test_statistics_success(self):
create_resp = _create_position_tag()
def test_list_includes_mounted_agents(self):
_seed_employees()
create_resp = _create_position_tag(name="复盘销售岗", user_ids=[1])
tag_id = create_resp.json()["data"]["id"]
db = TestingSessionLocal()
agent1 = Agent(id=10, name="启用Agent", code="active_agent", status=AgentStatus.enable)
agent2 = Agent(id=11, name="禁用Agent", code="disabled_agent", status=AgentStatus.disable)
db.add(agent1)
db.add(agent2)
agent = Agent(id=101, name="复盘 Agent", code="agent_101", status=AgentStatus.enable)
db.add(agent)
db.flush()
db.add(AgentPosition(agent_id=agent1.id, position_id=tag_id))
db.add(AgentPosition(agent_id=agent2.id, position_id=tag_id))
db.add(AgentPosition(agent_id=agent.id, position_id=tag_id))
db.commit()
db.close()
resp = client.get(f"/api/v1/position-tags/{tag_id}/agents/statistics")
assert resp.status_code == 200
data = resp.json()["data"]
assert data["position_id"] == tag_id
assert data["agent_count"] == 2
assert data["active_agent_count"] == 1
assert len(data["agents"]) == 2
def test_statistics_no_agents(self):
create_resp = _create_position_tag()
tag_id = create_resp.json()["data"]["id"]
resp = client.get(f"/api/v1/position-tags/{tag_id}/agents/statistics")
resp = client.get("/api/v1/position-tags?page=1&page_size=20")
assert resp.status_code == 200
data = resp.json()["data"]
assert data["agent_count"] == 0
assert data["active_agent_count"] == 0
assert data["agents"] == []
def test_statistics_nonexistent_tag_returns_404(self):
resp = client.get("/api/v1/position-tags/99999/agents/statistics")
assert resp.status_code == 404
assert resp.json()["code"] == 404
rows = resp.json()["data"]["list"]
target = next((row for row in rows if row["id"] == tag_id), None)
assert target is not None
assert any(item["id"] == 101 for item in target["agents"])
import pytest
from datetime import datetime, timezone
from app.infrastructure.file_parser import InMemoryOSSClient
from app.model.agent import Agent, AgentPosition, AgentSkill, AgentStatus
from app.model.agent_group import QrcodeChannel
from app.model.position_tag import PositionTag
from app.model.skill import Skill
from app.model.session import Session as DbSession
from app.model.analytics import ConversationLog, AnalyticsEvent, AnalyticsStatistic, PageView, ScanEvent, GroupJoinEvent
from app.model.position_tag import PositionTag, PositionTagUser
from app.model.wecom_sync import WeComBot
from app.schema.qrcode_channel import QrcodeCreateRequest, QrcodeExportRequest, QrcodeUpdateRequest
from app.service.agent_group_helper_service import InMemoryWeComClient
from app.service.qrcode_channel_service import QrcodeChannelService
from tests.conftest import TestingSessionLocal
@pytest.fixture
def db():
session = TestingSessionLocal()
session.query(GroupJoinEvent).delete()
session.query(ScanEvent).delete()
session.query(PageView).delete()
session.query(AnalyticsStatistic).delete()
session.query(AnalyticsEvent).delete()
session.query(ConversationLog).delete()
session.query(AgentSkill).delete()
session.query(AgentPosition).delete()
session.query(Agent).delete()
session.query(QrcodeChannel).delete()
session.query(PositionTagUser).delete()
session.query(WeComBot).delete()
session.query(PositionTag).delete()
session.query(DbSession).delete()
session.commit()
yield session
session.close()
@pytest.fixture
def wecom():
return InMemoryWeComClient()
@pytest.fixture
def oss():
return InMemoryOSSClient()
def _insert_position(db, name="驻店销售岗", code="store_sales"):
def _seed_position_with_bot(db, name="驻店销售岗", code="store_sales", bot_row_id=1, bot_id="emp_1001", bot_name="张三机器人"):
pos = PositionTag(name=name, code=code)
db.add(pos)
db.flush()
bot = WeComBot(id=bot_row_id, channel="wt_ww", bot_id=bot_id, bot_code=f"wt_ww:{bot_id}", bot_name=bot_name)
db.add(bot)
db.flush()
db.add(PositionTagUser(position_tag_id=pos.id, wecom_bot_id=bot.id))
db.commit()
db.refresh(pos)
return pos
return pos, bot
def _insert_agent(db, name="管家Agent", code="steward", status=AgentStatus.enable):
agent = Agent(name=name, code=code, status=status)
db.add(agent)
def _seed_agent(db, name="管家Agent", code="steward", status=AgentStatus.enable):
a = Agent(name=name, code=code, status=status)
db.add(a)
db.commit()
db.refresh(agent)
return agent
db.refresh(a)
return a
class TestCreateQrcode:
def test_create_success(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest
_insert_position(db)
_insert_agent(db)
svc = QrcodeChannelService(db, wecom)
req = QrcodeCreateRequest(
qrcode_name="驻店销售岗渠道活码",
position_code="store_sales",
employee_id="emp_12345",
employee_name="张三",
wechat_user_id="zhangsan",
remark="3月新活动渠道",
welcome_message="欢迎加入!",
)
result = svc.create(req)
class TestQrcodeChannel:
def test_create_success_with_applicant_bot(self, db):
pos, bot = _seed_position_with_bot(db)
_seed_agent(db)
svc = QrcodeChannelService(db, InMemoryWeComClient())
result = svc.create(QrcodeCreateRequest(qrcode_name="销售岗活码", position_name=pos.name, applicant_bot_id=bot.id))
assert result.qrcode_id > 0
assert result.channel_code == "zdxs_store_sales_emp_12345"
assert result.status == "enable"
assert "cdn.weixin.qq.com" in result.qrcode_url
def test_create_position_not_found(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest
svc = QrcodeChannelService(db, wecom)
req = QrcodeCreateRequest(
qrcode_name="test", position_code="nonexistent",
employee_id="emp_1", employee_name="test", wechat_user_id="wx_1",
)
with pytest.raises(ValueError, match="岗位不存在"):
svc.create(req)
def test_create_duplicate_returns_409(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest
_insert_position(db)
_insert_agent(db)
svc = QrcodeChannelService(db, wecom)
req = QrcodeCreateRequest(
qrcode_name="test", position_code="store_sales",
employee_id="emp_1", employee_name="张三", wechat_user_id="wx_1",
)
svc.create(req)
with pytest.raises(ValueError, match="已存在同岗位活码"):
svc.create(req)
def test_create_channel_code_format(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest
_insert_position(db, name="客服岗", code="cs")
_insert_agent(db)
svc = QrcodeChannelService(db, wecom)
req = QrcodeCreateRequest(
qrcode_name="客服岗活码", position_code="cs",
employee_id="emp_99", employee_name="李四", wechat_user_id="lisi",
)
result = svc.create(req)
assert result.channel_code == "zdxs_cs_emp_99"
def test_create_auto_includes_steward_and_position_agents(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest
pos = _insert_position(db)
steward = _insert_agent(db, name="管家Agent", code="steward")
metric = _insert_agent(db, name="指标Agent", code="metric-agent")
db.add(AgentPosition(agent_id=metric.id, position_id=pos.id))
assert result.position.position_name == pos.name
assert result.employee.employee_name == bot.bot_name
def test_create_conflict_when_position_has_qrcode(self, db):
pos, bot = _seed_position_with_bot(db)
_seed_agent(db)
svc = QrcodeChannelService(db, InMemoryWeComClient())
svc.create(QrcodeCreateRequest(qrcode_name="销售岗活码1", position_name=pos.name, applicant_bot_id=bot.id))
with pytest.raises(ValueError, match="岗位已存在活码"):
svc.create(QrcodeCreateRequest(qrcode_name="销售岗活码2", position_name=pos.name, applicant_bot_id=bot.id))
def test_create_error_when_applicant_not_in_position(self, db):
pos, _ = _seed_position_with_bot(db, bot_row_id=1, bot_id="emp_1")
other = WeComBot(id=2, channel="wt_ww", bot_id="emp_2", bot_code="wt_ww:emp_2", bot_name="李四机器人")
db.add(other)
db.commit()
svc = QrcodeChannelService(db, wecom)
req = QrcodeCreateRequest(
qrcode_name="test", position_code="store_sales",
employee_id="emp_1", employee_name="张三", wechat_user_id="wx_1",
)
result = svc.create(req)
assert steward.id in result.agent_ids
assert metric.id in result.agent_ids
class TestUpdateQrcode:
def test_update_success(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest, QrcodeUpdateRequest
_insert_position(db)
_insert_agent(db)
svc = QrcodeChannelService(db, wecom)
created = svc.create(QrcodeCreateRequest(
qrcode_name="原始名称", position_code="store_sales",
employee_id="emp_1", employee_name="张三", wechat_user_id="wx_1",
))
result = svc.update(created.qrcode_id, QrcodeUpdateRequest(
qrcode_name="更新后名称", remark="更新备注", welcome_message="新欢迎语",
))
assert result.success is True
def test_update_nonexistent(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeUpdateRequest
svc = QrcodeChannelService(db, wecom)
with pytest.raises(ValueError, match="不存在"):
svc.update(99999, QrcodeUpdateRequest(qrcode_name="test"))
class TestGetDetail:
def test_detail_success(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest
_insert_position(db)
_insert_agent(db)
svc = QrcodeChannelService(db, wecom)
created = svc.create(QrcodeCreateRequest(
qrcode_name="详情测试", position_code="store_sales",
employee_id="emp_1", employee_name="张三", wechat_user_id="wx_1",
welcome_message="你好",
))
detail = svc.get_detail(created.qrcode_id)
assert detail.qrcode_name == "详情测试"
assert detail.welcome_message == "你好"
assert detail.position_name == "驻店销售岗"
def test_detail_not_found(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
svc = QrcodeChannelService(db, wecom)
with pytest.raises(ValueError, match="不存在"):
svc.get_detail(99999)
class TestListQrcodes:
def test_list_with_employee_name_filter(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest
_insert_position(db)
_insert_agent(db)
svc = QrcodeChannelService(db, wecom)
svc.create(QrcodeCreateRequest(
qrcode_name="张三活码", position_code="store_sales",
employee_id="emp_1", employee_name="张三", wechat_user_id="wx_1",
))
svc.create(QrcodeCreateRequest(
qrcode_name="李四活码", position_code="store_sales",
employee_id="emp_2", employee_name="李四", wechat_user_id="wx_2",
))
result = svc.list_qrcodes(employee_name="张三")
assert result.total == 1
assert result.list[0].employee_name == "张三"
def test_list_by_status(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest
_insert_position(db)
_insert_agent(db)
svc = QrcodeChannelService(db, wecom)
svc.create(QrcodeCreateRequest(
qrcode_name="test", position_code="store_sales",
employee_id="emp_1", employee_name="张三", wechat_user_id="wx_1",
))
result = svc.list_qrcodes(status="enable")
assert result.total == 1
def test_list_keyword_search(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest
_insert_position(db)
_insert_agent(db)
svc = QrcodeChannelService(db, wecom)
svc.create(QrcodeCreateRequest(
qrcode_name="test", position_code="store_sales",
employee_id="emp_1", employee_name="张三", wechat_user_id="wx_1",
))
result = svc.list_qrcodes(keyword="zdxs_store_sales")
assert result.total == 1
def test_list_empty(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
svc = QrcodeChannelService(db, wecom)
result = svc.list_qrcodes()
assert result.total == 0
assert result.list == []
class TestExport:
def test_export_success(self, db, wecom, oss):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest, QrcodeExportRequest
_insert_position(db)
_insert_agent(db)
svc = QrcodeChannelService(db, wecom, oss)
svc.create(QrcodeCreateRequest(
qrcode_name="test", position_code="store_sales",
employee_id="emp_1", employee_name="张三", wechat_user_id="wx_1",
))
result = svc.export(QrcodeExportRequest())
assert result.total_count == 1
assert result.file_url is not None
class TestDisableEnable:
def test_disable_success(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest
_insert_position(db)
_insert_agent(db)
svc = QrcodeChannelService(db, wecom)
created = svc.create(QrcodeCreateRequest(
qrcode_name="test", position_code="store_sales",
employee_id="emp_1", employee_name="张三", wechat_user_id="wx_1",
))
result = svc.disable(created.qrcode_id, "活动结束")
assert result.success is True
assert result.previous_status == "enable"
detail = svc.get_detail(created.qrcode_id)
assert detail.status == "disable"
def test_enable_success(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest
_insert_position(db)
_insert_agent(db)
svc = QrcodeChannelService(db, wecom)
created = svc.create(QrcodeCreateRequest(
qrcode_name="test", position_code="store_sales",
employee_id="emp_1", employee_name="张三", wechat_user_id="wx_1",
))
svc.disable(created.qrcode_id, "临时停用")
result = svc.enable(created.qrcode_id)
assert result.success is True
assert result.previous_status == "disable"
def test_disable_not_found(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
svc = QrcodeChannelService(db, wecom)
with pytest.raises(ValueError, match="不存在"):
svc.disable(99999, "reason")
class TestBatchStatus:
def test_batch_disable(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest
_insert_position(db)
_insert_agent(db)
svc = QrcodeChannelService(db, wecom)
r1 = svc.create(QrcodeCreateRequest(
qrcode_name="test1", position_code="store_sales",
employee_id="emp_1", employee_name="张三", wechat_user_id="wx_1",
))
r2 = svc.create(QrcodeCreateRequest(
qrcode_name="test2", position_code="store_sales",
employee_id="emp_2", employee_name="李四", wechat_user_id="wx_2",
))
result = svc.batch_status([r1.qrcode_id, r2.qrcode_id], "disable", "批量停用")
assert result.success_count == 2
assert result.failed_count == 0
def test_batch_with_failures(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest
_insert_position(db)
_insert_agent(db)
svc = QrcodeChannelService(db, wecom)
r1 = svc.create(QrcodeCreateRequest(
qrcode_name="test1", position_code="store_sales",
employee_id="emp_1", employee_name="张三", wechat_user_id="wx_1",
))
result = svc.batch_status([r1.qrcode_id, 99999], "disable", "test")
assert result.success_count == 1
assert result.failed_count == 1
class TestIntegrationFlow:
def test_create_query_update_disable_enable(self, db, wecom):
from app.service.qrcode_channel_service import QrcodeChannelService
from app.schema.qrcode_channel import QrcodeCreateRequest, QrcodeUpdateRequest
_insert_position(db)
_insert_agent(db)
svc = QrcodeChannelService(db, wecom)
created = svc.create(QrcodeCreateRequest(
qrcode_name="初始名称", position_code="store_sales",
employee_id="emp_1", employee_name="张三", wechat_user_id="wx_1",
welcome_message="初始欢迎语",
))
assert created.status == "enable"
svc = QrcodeChannelService(db, InMemoryWeComClient())
with pytest.raises(ValueError, match="未绑定到该岗位"):
svc.create(QrcodeCreateRequest(qrcode_name="x", position_name=pos.name, applicant_bot_id=2))
def test_create_error_when_applicant_already_bound(self, db):
pos1, bot = _seed_position_with_bot(db, name="销售岗A", code="a")
pos2 = PositionTag(name="销售岗B", code="b")
db.add(pos2)
db.flush()
db.add(PositionTagUser(position_tag_id=pos2.id, wecom_bot_id=bot.id))
db.commit()
svc = QrcodeChannelService(db, InMemoryWeComClient())
_seed_agent(db)
svc.create(QrcodeCreateRequest(qrcode_name="A活码", position_name=pos1.name, applicant_bot_id=bot.id))
with pytest.raises(ValueError, match="员工已绑定活码"):
svc.create(QrcodeCreateRequest(qrcode_name="B活码", position_name=pos2.name, applicant_bot_id=bot.id))
def test_update_list_disable_enable_delete_export(self, db):
pos, bot = _seed_position_with_bot(db)
_seed_agent(db)
svc = QrcodeChannelService(db, InMemoryWeComClient(), InMemoryOSSClient())
created = svc.create(QrcodeCreateRequest(qrcode_name="原始", position_name=pos.name, applicant_bot_id=bot.id))
svc.update(created.qrcode_id, QrcodeUpdateRequest(qrcode_name="更新后", welcome_message="hi"))
detail = svc.get_detail(created.qrcode_id)
assert detail.qrcode_name == "初始名称"
svc.update(created.qrcode_id, QrcodeUpdateRequest(
qrcode_name="更新名称", remark="新备注", welcome_message="新欢迎语",
))
detail2 = svc.get_detail(created.qrcode_id)
assert detail2.qrcode_name == "更新名称"
assert detail2.welcome_message == "新欢迎语"
svc.disable(created.qrcode_id, "活动结束")
detail3 = svc.get_detail(created.qrcode_id)
assert detail3.status == "disable"
svc.enable(created.qrcode_id)
detail4 = svc.get_detail(created.qrcode_id)
assert detail4.status == "enable"
assert detail.qrcode_name == "更新后"
listed = svc.list_qrcodes()
assert listed.total == 1
row = listed.list[0]
assert row.position_id == pos.id
assert row.employee_id == bot.id
assert row.qrcode_name == "更新后"
assert isinstance(row.agents, list)
assert svc.disable(created.qrcode_id, "x").success is True
assert svc.enable(created.qrcode_id).success is True
assert svc.export(QrcodeExportRequest()).total_count >= 1
assert svc.delete(created.qrcode_id).success is True
......@@ -360,7 +360,6 @@
```json
{
"name": "驻店销售岗",
"code": "store_sales",
"description": "负责门店销售的岗位"
}
```
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!