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 1765 additions and 785 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 ...@@ -2,8 +2,8 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.infrastructure.database import get_db from app.infrastructure.database import get_db
from app.schema.common import ApiResponse from app.schema.common import ApiResponse, success_response_payload
from app.schema.agent_group import EmployeeQrcodesResponse, PositionEmployeesResponse from app.schema.agent_group import EmployeeMountsResponse, EmployeeQrcodesResponse, PositionEmployeesResponse
from app.service.agent_group_helper_service import ( from app.service.agent_group_helper_service import (
AgentGroupHelperService, AgentGroupHelperService,
PositionNotFoundError, PositionNotFoundError,
...@@ -29,7 +29,10 @@ def get_position_employees( ...@@ -29,7 +29,10 @@ def get_position_employees(
): ):
svc = AgentGroupHelperService(db, wecom_client) svc = AgentGroupHelperService(db, wecom_client)
try: 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: except PositionNotFoundError as exc:
raise HTTPException(status_code=404, detail=str(exc)) raise HTTPException(status_code=404, detail=str(exc))
except WeComUnavailableError as exc: except WeComUnavailableError as exc:
...@@ -45,4 +48,21 @@ def get_employee_qrcodes( ...@@ -45,4 +48,21 @@ def get_employee_qrcodes(
db: Session = Depends(get_db), db: Session = Depends(get_db),
): ):
svc = AgentGroupHelperService(db, get_wecom_client()) 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 ...@@ -4,6 +4,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.infrastructure.database import get_db from app.infrastructure.database import get_db
from app.model.agent import AgentStatus
from app.schema.agent import ( from app.schema.agent import (
AgentCreate, AgentCreate,
AgentDetailResponse, AgentDetailResponse,
...@@ -16,7 +17,6 @@ from app.schema.common import ( ...@@ -16,7 +17,6 @@ from app.schema.common import (
ApiResponse, ApiResponse,
DeleteSuccessData, DeleteSuccessData,
StatusSuccessData, StatusSuccessData,
SuccessFlagData,
success_response_payload, success_response_payload,
) )
from app.service.agent_service import AgentService from app.service.agent_service import AgentService
...@@ -28,9 +28,10 @@ def _to_response(agent) -> AgentResponse: ...@@ -28,9 +28,10 @@ def _to_response(agent) -> AgentResponse:
return AgentResponse( return AgentResponse(
agent_id=agent.id, agent_id=agent.id,
name=agent.name, name=agent.name,
code=agent.code,
position_ids=sorted(ap.position_id for ap in agent.positions), position_ids=sorted(ap.position_id for ap in agent.positions),
skill_codes=sorted(sk.skill_code for sk in agent.skills), 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, created_at=agent.created_at,
) )
...@@ -53,9 +54,9 @@ def update_agent(agent_id: int, req: AgentUpdate, db: Session = Depends(get_db)) ...@@ -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")) return success_response_payload(200, _to_response(agent).model_dump(mode="json"))
except ValueError as e: except ValueError as e:
msg = str(e) msg = str(e)
if "不存在" in msg: if msg == "Agent不存在":
raise HTTPException(status_code=404, detail=msg) 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]) @router.delete("/{agent_id}", response_model=ApiResponse[DeleteSuccessData])
...@@ -86,11 +87,11 @@ def get_agent_detail(agent_id: int, db: Session = Depends(get_db)): ...@@ -86,11 +87,11 @@ def get_agent_detail(agent_id: int, db: Session = Depends(get_db)):
@router.get("", response_model=ApiResponse[AgentListResponse]) @router.get("", response_model=ApiResponse[AgentListResponse])
def list_agents( def list_agents(
page: int = Query(1, ge=1), page: int = Query(1, ge=1, description="页码,默认 1。"),
page_size: int = Query(20, ge=1, le=100), page_size: int = Query(20, ge=1, le=100, description="每页数量,默认 20,最大 100。"),
keyword: Optional[str] = Query(None), keyword: Optional[str] = Query(None, description="按 Agent 名称或编码模糊搜索。"),
position_id: Optional[int] = Query(None), position_id: Optional[int] = Query(None, description="按岗位 ID 筛选。"),
status: Optional[str] = Query(None), status: Optional[str] = Query(None, description="按 Agent 状态筛选。"),
db: Session = Depends(get_db), db: Session = Depends(get_db),
): ):
svc = AgentService(db) svc = AgentService(db)
...@@ -123,3 +124,31 @@ def update_agent_status(agent_id: int, req: AgentStatusUpdate, db: Session = Dep ...@@ -123,3 +124,31 @@ def update_agent_status(agent_id: int, req: AgentStatusUpdate, db: Session = Dep
) )
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=404, detail=str(e)) raise HTTPException(status_code=404, detail=str(e))
@router.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 ...@@ -3,7 +3,7 @@ from sqlalchemy.orm import Session
from app.infrastructure.database import get_db from app.infrastructure.database import get_db
from app.infrastructure.shared_cache import shared_h5_cache from app.infrastructure.shared_cache import shared_h5_cache
from app.schema.common import ApiResponse from app.schema.common import ApiResponse, success_response_payload
from app.schema.official_site_home import H5HomeResponse from app.schema.official_site_home import H5HomeResponse
from app.service.official_site_home_service import H5HomeService from app.service.official_site_home_service import H5HomeService
...@@ -13,4 +13,4 @@ router = APIRouter() ...@@ -13,4 +13,4 @@ router = APIRouter()
@router.get("/api/v1/official-site/home", response_model=ApiResponse[H5HomeResponse]) @router.get("/api/v1/official-site/home", response_model=ApiResponse[H5HomeResponse])
def get_home_data(db: Session = Depends(get_db)): def get_home_data(db: Session = Depends(get_db)):
svc = H5HomeService(db, shared_h5_cache) svc = H5HomeService(db, shared_h5_cache)
return svc.get_home_data() return success_response_payload(200, svc.get_home_data().model_dump(mode="json"))
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import Optional
from app.infrastructure.database import get_db
from app.schema.common import ApiResponse, SuccessFlagData, success_response_payload
from app.schema.position_tag import ( from app.schema.position_tag import (
PositionTagAgentStatistics,
PositionTagCreate, PositionTagCreate,
PositionTagUpdate, PositionTagListItem,
PositionTagResponse,
PositionTagListResponse, PositionTagListResponse,
PositionTagResponse,
PositionTagUpdate,
PositionTagUpdateResponse,
ReferenceCheckResponse, ReferenceCheckResponse,
PositionTagAgentStatistics,
) )
from app.schema.common import ApiResponse, SuccessFlagData, success_response_payload
from app.service.position_tag_service import PositionTagService from app.service.position_tag_service import PositionTagService
from app.infrastructure.database import get_db
router = APIRouter(prefix="/api/v1/position-tags") 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) @router.post("", response_model=ApiResponse[PositionTagResponse], status_code=201)
def create_position_tag(req: PositionTagCreate, db: Session = Depends(get_db)): def create_position_tag(req: PositionTagCreate, db: Session = Depends(get_db)):
svc = PositionTagService(db) svc = PositionTagService(db)
try: try:
tag = svc.create(req) tag = svc.create(req)
return success_response_payload( return success_response_payload(201, _to_position_tag_response(tag).model_dump(mode="json"))
201,
PositionTagResponse.model_validate(tag).model_dump(mode="json"),
)
except ValueError as e: except ValueError as e:
msg = str(e) msg = str(e)
if "编码已存在" in msg: if msg == "岗位标签名称已存在":
raise HTTPException(status_code=409, detail=msg) raise HTTPException(status_code=409, detail=msg)
raise HTTPException(status_code=400, 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)): def update_position_tag(tag_id: int, req: PositionTagUpdate, db: Session = Depends(get_db)):
svc = PositionTagService(db) svc = PositionTagService(db)
try: try:
tag = svc.update(tag_id, req) tag = svc.update(tag_id, req)
return success_response_payload( return success_response_payload(
200, 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: 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]) @router.get("/{tag_id}/references", response_model=ApiResponse[ReferenceCheckResponse])
...@@ -69,11 +85,13 @@ def delete_position_tag( ...@@ -69,11 +85,13 @@ def delete_position_tag(
return success_response_payload(200, {"success": True}) return success_response_payload(200, {"success": True})
except ValueError as e: except ValueError as e:
msg = str(e) msg = str(e)
if "阻塞性引用" in msg: if 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) 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]) @router.get("", response_model=ApiResponse[PositionTagListResponse])
...@@ -89,9 +107,17 @@ def list_position_tags( ...@@ -89,9 +107,17 @@ def list_position_tags(
200, 200,
PositionTagListResponse( PositionTagListResponse(
total=total, total=total,
page=page, list=[
page_size=page_size, PositionTagListItem(
list=[PositionTagResponse.model_validate(item) for item in items], 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"), ).model_dump(mode="json"),
) )
......
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import Optional
from app.infrastructure.database import get_db from app.infrastructure.database import get_db
from app.infrastructure.file_parser import InMemoryOSSClient, OSSClient from app.infrastructure.file_parser import InMemoryOSSClient, OSSClient
...@@ -9,6 +10,7 @@ from app.schema.qrcode_channel import ( ...@@ -9,6 +10,7 @@ from app.schema.qrcode_channel import (
QrcodeBatchStatusResponse, QrcodeBatchStatusResponse,
QrcodeCreateRequest, QrcodeCreateRequest,
QrcodeCreateResponse, QrcodeCreateResponse,
QrcodeDeleteResponse,
QrcodeDetailResponse, QrcodeDetailResponse,
QrcodeDisableRequest, QrcodeDisableRequest,
QrcodeDisableResponse, QrcodeDisableResponse,
...@@ -43,10 +45,16 @@ def create_qrcode(req: QrcodeCreateRequest, db: Session = Depends(get_db), wecom ...@@ -43,10 +45,16 @@ def create_qrcode(req: QrcodeCreateRequest, db: Session = Depends(get_db), wecom
return svc.create(req) return svc.create(req)
except ValueError as e: except ValueError as e:
msg = str(e) msg = str(e)
if "岗位不存在" in msg: if msg == "岗位不存在":
raise HTTPException(status_code=400, detail=msg) raise HTTPException(status_code=400, detail=msg)
if "已存在同岗位活码" in msg: if msg == "该岗位已存在活码":
raise HTTPException(status_code=409, detail=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) raise HTTPException(status_code=400, detail=msg)
...@@ -63,18 +71,12 @@ def update_qrcode(qrcode_id: int, req: QrcodeUpdateRequest, db: Session = Depend ...@@ -63,18 +71,12 @@ def update_qrcode(qrcode_id: int, req: QrcodeUpdateRequest, db: Session = Depend
def list_qrcodes( def list_qrcodes(
page: int = Query(1, ge=1), page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100), page_size: int = Query(20, ge=1, le=100),
employee_name: Optional[str] = Query(None),
position_code: Optional[str] = Query(None),
status: Optional[str] = Query(None), status: Optional[str] = Query(None),
keyword: Optional[str] = Query(None), keyword: Optional[str] = Query(None),
db: Session = Depends(get_db), db: Session = Depends(get_db),
): ):
svc = QrcodeChannelService(db, _wecom) svc = QrcodeChannelService(db, _wecom)
return svc.list_qrcodes( return svc.list_qrcodes(page=page, page_size=page_size, status=status, keyword=keyword)
page=page, page_size=page_size,
employee_name=employee_name, position_code=position_code,
status=status, keyword=keyword,
)
@router.get("/{qrcode_id}", response_model=QrcodeDetailResponse) @router.get("/{qrcode_id}", response_model=QrcodeDetailResponse)
...@@ -114,3 +116,12 @@ def enable_qrcode(qrcode_id: int, db: Session = Depends(get_db)): ...@@ -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)): def batch_status(req: QrcodeBatchStatusRequest, db: Session = Depends(get_db)):
svc = QrcodeChannelService(db, _wecom) svc = QrcodeChannelService(db, _wecom)
return svc.batch_status(req.qrcode_ids, req.target_status, req.reason) 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 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.session import Session, SessionStatus
from app.model.wecom_sync import WeComBot, WeComContact, WeComGroup, WeComMessage, WeComSyncCheckpoint from app.model.wecom_sync import WeComBot, WeComContact, WeComGroup, WeComMessage, WeComSyncCheckpoint
__all__ = [ __all__ = [
"Agent", "AgentPosition", "AgentSkill", "AgentStatus", "Agent", "AgentPosition", "AgentSkill", "AgentStatus",
"QrcodeChannel",
"PositionTag", "OfficialTab", "PositionTagUser",
"Session", "SessionStatus", "Session", "SessionStatus",
"WeComBot", "WeComContact", "WeComGroup", "WeComMessage", "WeComSyncCheckpoint", "WeComBot", "WeComContact", "WeComGroup", "WeComMessage", "WeComSyncCheckpoint",
] ]
...@@ -15,6 +15,7 @@ class Agent(Base): ...@@ -15,6 +15,7 @@ class Agent(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
name = Column(String(50), nullable=False) name = Column(String(50), nullable=False)
code = Column(String(100), nullable=False, unique=True, index=True) code = Column(String(100), nullable=False, unique=True, index=True)
managed_user_id = Column(Integer, nullable=True, index=True)
description = Column(String(500)) description = Column(String(500))
status = Column(Enum(AgentStatus), default=AgentStatus.enable) status = Column(Enum(AgentStatus), default=AgentStatus.enable)
version = Column(Integer, default=1, nullable=False) version = Column(Integer, default=1, nullable=False)
...@@ -51,3 +52,4 @@ class AgentSkill(Base): ...@@ -51,3 +52,4 @@ class AgentSkill(Base):
agent = relationship("Agent", back_populates="skills") agent = relationship("Agent", back_populates="skills")
__table_args__ = (UniqueConstraint('agent_id', 'skill_code', name='uk_agent_skill'),) __table_args__ = (UniqueConstraint('agent_id', 'skill_code', name='uk_agent_skill'),)
...@@ -7,11 +7,11 @@ class QrcodeChannel(Base): ...@@ -7,11 +7,11 @@ class QrcodeChannel(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
qrcode_name = Column(String(50), default=None) 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="") 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_id = Column(String(100), nullable=False, index=True)
employee_name = Column(String(100), nullable=False, default="") 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) channel_code = Column(String(100), nullable=False, unique=True, index=True)
qrcode_url = Column(String(500), default=None) qrcode_url = Column(String(500), default=None)
agent_ids = Column(JSON, default=None) agent_ids = Column(JSON, default=None)
...@@ -25,5 +25,6 @@ class QrcodeChannel(Base): ...@@ -25,5 +25,6 @@ class QrcodeChannel(Base):
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False) updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
__table_args__ = ( __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 from app.infrastructure.database import Base
...@@ -9,8 +10,10 @@ class PositionTag(Base): ...@@ -9,8 +10,10 @@ class PositionTag(Base):
name = Column(String(20), nullable=False) name = Column(String(20), nullable=False)
code = Column(String(100), nullable=False, unique=True, index=True) code = Column(String(100), nullable=False, unique=True, index=True)
description = Column(String(100), default=None) description = Column(String(100), default=None)
user_ids = Column(JSON, default=None)
created_at = Column(DateTime, server_default=func.now(), nullable=False) created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=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): class OfficialTab(Base):
...@@ -28,3 +31,18 @@ class OfficialTab(Base): ...@@ -28,3 +31,18 @@ class OfficialTab(Base):
created_at = Column(DateTime, server_default=func.now(), nullable=False) created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=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) 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 datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field
from app.model.agent import AgentStatus from app.model.agent import AgentStatus
class AgentBase(BaseModel): class AgentBase(BaseModel):
name: str = Field(..., max_length=50) name: str = Field(..., max_length=50, description="Agent 名称。", examples=["复盘 Agent"])
description: Optional[str] = Field(None, max_length=500) description: Optional[str] = Field(
status: AgentStatus = AgentStatus.enable None,
max_length=500,
description="Agent 描述信息。",
examples=["智能复盘助手,帮助销售进行每日复盘"],
)
status: AgentStatus = Field(
default=AgentStatus.enable,
description="Agent 状态,可选 `enable` 或 `disable`。",
examples=["enable"],
)
class AgentCreate(AgentBase): class AgentCreate(AgentBase):
position_ids: List[int] position_ids: List[int] = Field(..., description="关联岗位 ID 列表。", examples=[[1, 3]])
skill_codes: List[str] 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): class AgentUpdate(AgentBase):
position_ids: Optional[List[int]] = None position_ids: Optional[List[int]] = Field(default=None, description="更新后的岗位 ID 列表。", examples=[[1, 2]])
skill_codes: Optional[List[str]] = None 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): class AgentStatusUpdate(BaseModel):
status: AgentStatus status: AgentStatus = Field(..., description="目标状态。", examples=["disable"])
reason: Optional[str] = None reason: Optional[str] = Field(default=None, description="状态变更原因。", examples=["manual disable"])
class AgentPositionItem(BaseModel): class AgentPositionItem(BaseModel):
id: int id: int = Field(..., description="岗位 ID。", examples=[1])
name: str name: str = Field(..., description="岗位名称。", examples=["驻店销售岗"])
class AgentSkillItem(BaseModel): class AgentSkillItem(BaseModel):
skill_code: str skill_code: str = Field(..., description="技能编码。", examples=["query-metric"])
skill_name: str 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): class AgentResponse(BaseModel):
agent_id: int agent_id: int = Field(..., description="Agent ID。", examples=[101])
name: str name: str = Field(..., description="Agent 名称。", examples=["复盘 Agent"])
code: str position_ids: List[int] = Field(..., description="岗位 ID 列表。", examples=[[1, 3]])
position_ids: List[int] skill_codes: List[str] = Field(..., description="技能编码列表。", examples=[["query-metric"]])
skill_codes: List[str] managed_user_id: Optional[int] = Field(default=None, description="托管员工 ID。", examples=[5])
created_at: datetime status: AgentStatus = Field(..., description="Agent 状态。", examples=["enable"])
created_at: datetime = Field(..., description="创建时间。", examples=["2026-05-21T10:00:00Z"])
class AgentDetailResponse(BaseModel): class AgentDetailResponse(BaseModel):
agent_id: int agent_id: int = Field(..., description="Agent ID。", examples=[101])
name: str name: str = Field(..., description="Agent 名称。", examples=["复盘 Agent"])
code: str description: Optional[str] = Field(default=None, description="Agent 描述信息。", examples=["智能复盘助手"])
description: Optional[str] positions: List[AgentPositionItem] = Field(..., description="关联岗位列表。")
positions: List[AgentPositionItem] skills: List[AgentSkillItem] = Field(..., description="关联技能列表。")
skills: List[AgentSkillItem] managed_user: Optional[AgentUserItem] = Field(default=None, description="托管员工。")
status: AgentStatus status: AgentStatus = Field(..., description="Agent 状态。", examples=["enable"])
session_count: int created_at: datetime = Field(..., description="创建时间。", examples=["2026-05-10T09:00:00Z"])
created_at: datetime updated_at: datetime = Field(..., description="更新时间。", examples=["2026-05-15T10:00:00Z"])
updated_at: datetime
class AgentListResponse(BaseModel): class AgentListResponse(BaseModel):
total: int total: int = Field(..., description="总记录数。", examples=[2])
page: int page: int = Field(..., description="当前页码。", examples=[1])
page_size: int page_size: int = Field(..., description="每页数量。", examples=[20])
list: List[AgentResponse] list: List[AgentResponse] = Field(..., description="Agent 列表。")
...@@ -8,7 +8,6 @@ class EmployeeInfo(BaseModel): ...@@ -8,7 +8,6 @@ class EmployeeInfo(BaseModel):
employee_id: str employee_id: str
employee_name: str employee_name: str
wechat_user_id: str wechat_user_id: str
department: str
status: str status: str
...@@ -30,3 +29,33 @@ class EmployeeQrcodesResponse(BaseModel): ...@@ -30,3 +29,33 @@ class EmployeeQrcodesResponse(BaseModel):
employee_name: str employee_name: str
qrcode_count: int qrcode_count: int
qrcodes: List[EmployeeQrcode] 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 ...@@ -2,42 +2,42 @@ from __future__ import annotations
from typing import Generic, List, TypeVar from typing import Generic, List, TypeVar
from pydantic import BaseModel from pydantic import BaseModel, Field
T = TypeVar("T") T = TypeVar("T")
class ApiResponse(BaseModel, Generic[T]): class ApiResponse(BaseModel, Generic[T]):
code: int code: int = Field(..., description="业务响应码。通常 200 表示成功,其余值表示业务或请求错误。", examples=[200])
message: str message: str = Field(..., description="响应说明。成功时固定为 success,失败时返回具体错误原因。", examples=["success"])
data: T data: T = Field(..., description="实际业务数据。成功时为对象或分页结构。")
class ErrorResponse(BaseModel): class ErrorResponse(BaseModel):
code: int code: int = Field(..., description="业务响应码。", examples=[400])
message: str message: str = Field(..., description="错误说明。", examples=["参数校验失败:employee_id 不能为空"])
data: None = None data: None = Field(default=None, description="错误响应固定为 null。")
class PageData(BaseModel, Generic[T]): class PageData(BaseModel, Generic[T]):
total: int total: int = Field(..., description="总记录数。", examples=[156])
page: int page: int = Field(..., description="当前页码,从 1 开始。", examples=[1])
page_size: int page_size: int = Field(..., description="每页数量。默认 20,最大 100。", examples=[20])
list: List[T] list: List[T] = Field(..., description="当前页数据列表。")
class SuccessFlagData(BaseModel): class SuccessFlagData(BaseModel):
success: bool success: bool = Field(..., description="操作是否成功。", examples=[True])
class DeleteSuccessData(BaseModel): class DeleteSuccessData(BaseModel):
success: bool success: bool = Field(..., description="删除操作是否成功。", examples=[True])
deleted_at: str deleted_at: str = Field(..., description="删除时间,ISO 8601 格式。", examples=["2026-05-15T14:30:00Z"])
class StatusSuccessData(BaseModel): class StatusSuccessData(BaseModel):
success: bool success: bool = Field(..., description="状态更新是否成功。", examples=[True])
status: str status: str = Field(..., description="更新后的状态值。", examples=["disable"])
def success_response_payload(status_code: int, data): def success_response_payload(status_code: int, data):
......
...@@ -17,9 +17,11 @@ class CreateTabResponse(BaseModel): ...@@ -17,9 +17,11 @@ class CreateTabResponse(BaseModel):
position_name: str position_name: str
qrcode_id: int qrcode_id: int
created_at: datetime created_at: datetime
updated_at: datetime
class UpdateTabRequest(BaseModel): class UpdateTabRequest(BaseModel):
position_code: str = Field(..., max_length=100)
position_name: str = Field(..., max_length=100) position_name: str = Field(..., max_length=100)
qrcode_id: int qrcode_id: int
display_status: str = Field("enable", pattern=r"^(enable|disable)$") display_status: str = Field("enable", pattern=r"^(enable|disable)$")
...@@ -59,6 +61,7 @@ class TabListItem(BaseModel): ...@@ -59,6 +61,7 @@ class TabListItem(BaseModel):
sort_order: int sort_order: int
agent_count: int agent_count: int
created_at: datetime created_at: datetime
updated_at: Optional[datetime] = None
operations: List[str] operations: List[str]
......
from pydantic import BaseModel, ConfigDict, Field
from typing import List, Optional
from datetime import datetime from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field
class PositionTagCreate(BaseModel): class PositionTagCreate(BaseModel):
name: str = Field(..., max_length=20) 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) description: Optional[str] = Field(None, max_length=100)
...@@ -15,21 +15,30 @@ class PositionTagUpdate(BaseModel): ...@@ -15,21 +15,30 @@ class PositionTagUpdate(BaseModel):
class PositionTagResponse(BaseModel): class PositionTagResponse(BaseModel):
id: int tag_id: int
name: str name: str
code: str code: str
description: Optional[str]
created_at: datetime created_at: datetime
updated_at: datetime updated_at: datetime
model_config = ConfigDict(from_attributes=True)
class PositionTagListResponse(BaseModel): class PositionTagListResponse(BaseModel):
total: int total: int
page: int list: List["PositionTagListItem"]
page_size: int
list: List[PositionTagResponse]
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): class BlockingReference(BaseModel):
...@@ -54,7 +63,6 @@ class ReferenceCheckResponse(BaseModel): ...@@ -54,7 +63,6 @@ class ReferenceCheckResponse(BaseModel):
class AgentBrief(BaseModel): class AgentBrief(BaseModel):
id: int id: int
name: str name: str
code: str
status: str status: str
......
from datetime import datetime from datetime import datetime
from typing import List, Optional from typing import List, Optional
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
class QrcodeCreateRequest(BaseModel): class QrcodeCreateRequest(BaseModel):
qrcode_name: str = Field(..., max_length=50) qrcode_name: str = Field(..., max_length=50)
position_code: str = Field(..., max_length=100) position_code: str = Field(..., max_length=100)
employee_id: str = Field(..., max_length=100) employee_id: str = Field(..., max_length=128, description="承接员工ID,对应企微员工标识(映射到 wecom_bots.bot_id)")
employee_name: str = Field(..., max_length=100) wechat_user_id: str = Field(..., max_length=128, description="承接员工微信ID,与 employee_id 指向同一个员工")
wechat_user_id: str = Field(..., max_length=100)
remark: Optional[str] = Field(None, max_length=200) remark: Optional[str] = Field(None, max_length=200)
welcome_message: Optional[str] = Field(None, max_length=500) welcome_message: Optional[str] = Field(None, max_length=500)
...@@ -40,12 +40,11 @@ class QrcodeDetailResponse(BaseModel): ...@@ -40,12 +40,11 @@ class QrcodeDetailResponse(BaseModel):
qrcode_name: Optional[str] qrcode_name: Optional[str]
employee_id: str employee_id: str
employee_name: str employee_name: str
position_code: Optional[str]
position_name: str position_name: str
channel_code: str channel_code: str
qrcode_url: Optional[str] qrcode_url: Optional[str]
agent_ids: Optional[List[int]] agent_ids: List[int]
agent_names: Optional[List[str]] agent_names: List[str]
remark: Optional[str] remark: Optional[str]
welcome_message: Optional[str] welcome_message: Optional[str]
status: str status: str
...@@ -64,6 +63,7 @@ class QrcodeListItem(BaseModel): ...@@ -64,6 +63,7 @@ class QrcodeListItem(BaseModel):
agent_names_preview: List[str] agent_names_preview: List[str]
status: str status: str
created_at: datetime created_at: datetime
operations: List[str]
class QrcodeListResponse(BaseModel): class QrcodeListResponse(BaseModel):
...@@ -111,3 +111,8 @@ class QrcodeBatchStatusResponse(BaseModel): ...@@ -111,3 +111,8 @@ class QrcodeBatchStatusResponse(BaseModel):
success_count: int success_count: int
failed_count: int failed_count: int
failed_list: List[dict] failed_list: List[dict]
class QrcodeDeleteResponse(BaseModel):
success: bool
deleted_at: datetime
...@@ -7,64 +7,64 @@ from pydantic import BaseModel, Field ...@@ -7,64 +7,64 @@ from pydantic import BaseModel, Field
class SessionCreateRequest(BaseModel): class SessionCreateRequest(BaseModel):
user_id: str = Field(..., max_length=64) user_id: str = Field(..., max_length=64, description="用户 ID。", examples=["emp_12345"])
channel: str = Field(..., max_length=64) channel: str = Field(..., max_length=64, description="会话渠道。", examples=["wechat_group"])
initial_query: str = Field(..., min_length=1, max_length=5000) initial_query: str = Field(..., min_length=1, max_length=5000, description="用户发起会话的首条问题。", examples=["query A"])
class SessionCreateResponse(BaseModel): class SessionCreateResponse(BaseModel):
session_id: str session_id: str = Field(..., description="会话 ID。", examples=["sess_abc123xyz"])
user_id: str user_id: str = Field(..., description="用户 ID。", examples=["emp_12345"])
channel: str channel: str = Field(..., description="会话渠道。", examples=["wechat_group"])
current_agent_id: int current_agent_id: int = Field(..., description="当前接入的 Agent ID。", examples=[101])
created_at: datetime created_at: datetime = Field(..., description="创建时间。", examples=["2026-05-15T10:00:00Z"])
class SessionUpdateRequest(BaseModel): class SessionUpdateRequest(BaseModel):
role: str = Field(..., max_length=32) role: str = Field(..., max_length=32, description="当前消息角色,例如 user 或 assistant。", examples=["user"])
content: str = Field(..., min_length=1, max_length=5000) content: str = Field(..., min_length=1, max_length=5000, description="本轮消息内容。", examples=["继续查昨天的数据"])
agent_id: int agent_id: int = Field(..., description="当前处理消息的 Agent ID。", examples=[101])
intent: Optional[str] = Field(None, max_length=128) intent: Optional[str] = Field(None, max_length=128, description="识别出的意图编码。", examples=["query-metric"])
entities: Optional[Dict[str, Any]] = None entities: Optional[Dict[str, Any]] = Field(default=None, description="本轮抽取出的实体对象。", examples=[{"merchant_id": "store_A", "metric": "sales"}])
class SessionUpdateResponse(BaseModel): class SessionUpdateResponse(BaseModel):
success: bool success: bool = Field(..., description="更新是否成功。", examples=[True])
updated_at: datetime updated_at: datetime = Field(..., description="更新时间。", examples=["2026-05-15T10:05:00Z"])
turn_count: int turn_count: int = Field(..., description="当前会话轮次数。", examples=[5])
class SessionHistoryTurn(BaseModel): class SessionHistoryTurn(BaseModel):
role: str role: str = Field(..., description="消息角色。", examples=["user"])
content: str content: str = Field(..., description="消息内容。", examples=["A 店 3 月销量是多少?"])
agent_id: Optional[int] = None agent_id: Optional[int] = Field(default=None, description="处理该轮消息的 Agent ID。", examples=[101])
intent: Optional[str] = None intent: Optional[str] = Field(default=None, description="该轮消息识别出的意图。", examples=["query-metric"])
timestamp: datetime timestamp: datetime = Field(..., description="消息时间。", examples=["2026-05-15T10:00:00Z"])
class SessionDetailResponse(BaseModel): class SessionDetailResponse(BaseModel):
session_id: str session_id: str = Field(..., description="会话 ID。", examples=["sess_abc123xyz"])
user_id: str user_id: str = Field(..., description="用户 ID。", examples=["emp_12345"])
channel: str channel: str = Field(..., description="会话渠道。", examples=["wechat_group"])
current_agent_id: int current_agent_id: int = Field(..., description="当前 Agent ID。", examples=[101])
current_agent_name: Optional[str] = None current_agent_name: Optional[str] = Field(default=None, description="当前 Agent 名称。", examples=["澄清 Agent"])
conversation_history: List[SessionHistoryTurn] conversation_history: List[SessionHistoryTurn] = Field(..., description="会话历史。")
context_entities: Dict[str, Any] context_entities: Dict[str, Any] = Field(..., description="当前上下文实体集合。", examples=[{"merchant_id": "store_A", "metric": "sales"}])
created_at: datetime created_at: datetime = Field(..., description="创建时间。", examples=["2026-05-15T10:00:00Z"])
updated_at: datetime updated_at: datetime = Field(..., description="更新时间。", examples=["2026-05-15T10:05:00Z"])
class SessionContextResponse(BaseModel): class SessionContextResponse(BaseModel):
session_id: str session_id: str = Field(..., description="会话 ID。", examples=["sess_abc123xyz"])
current_agent_id: int current_agent_id: int = Field(..., description="当前 Agent ID。", examples=[101])
last_entities: Dict[str, Any] last_entities: Dict[str, Any] = Field(..., description="最近一轮可继承的实体对象。", examples=[{"merchant_id": "store_A", "metric": "sales"}])
inheritance_valid: bool inheritance_valid: bool = Field(..., description="当前上下文是否仍可继承。", examples=[True])
expires_at: Optional[datetime] = None expires_at: Optional[datetime] = Field(default=None, description="上下文过期时间。", examples=["2026-05-15T10:30:00Z"])
class SessionArchiveResponse(BaseModel): class SessionArchiveResponse(BaseModel):
success: bool success: bool = Field(..., description="归档是否成功。", examples=[True])
archived_at: datetime archived_at: datetime = Field(..., description="归档时间。", examples=["2026-05-15T10:35:00Z"])
SessionCreateResponse.model_config = {"from_attributes": True} SessionCreateResponse.model_config = {"from_attributes": True}
......
...@@ -7,34 +7,51 @@ from pydantic import BaseModel, Field ...@@ -7,34 +7,51 @@ from pydantic import BaseModel, Field
class WeComSyncRunRequest(BaseModel): class WeComSyncRunRequest(BaseModel):
mode: str = Field(..., pattern="^(full|incremental)$") mode: str = Field(
bot_ids: Optional[List[str]] = None ...,
message_start_time: Optional[datetime] = None pattern="^(full|incremental)$",
message_end_time: Optional[datetime] = None 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): class WeComSyncRunResponse(BaseModel):
mode: str mode: str = Field(..., description="本次执行模式。", examples=["full"])
bots: int bots: int = Field(..., description="本次同步处理的机器人记录数。", examples=[1])
contacts: int contacts: int = Field(..., description="本次同步处理的联系人记录数。", examples=[12])
groups: int groups: int = Field(..., description="本次同步处理的群记录数。", examples=[8])
messages: int messages: int = Field(..., description="本次同步处理的消息记录数。", examples=[156])
triggered_at: datetime triggered_at: datetime = Field(..., description="本次同步触发时间,ISO 8601 格式。", examples=["2026-05-21T16:30:00Z"])
class WeComSyncCheckpointItem(BaseModel): class WeComSyncCheckpointItem(BaseModel):
resource_type: str resource_type: str = Field(..., description="资源类型。可取 bots、contacts、groups、messages。", examples=["messages"])
scope_key: str scope_key: str = Field(..., description="同步范围键。global 表示全局资源,bot:xxx 表示某个机器人范围。", examples=["bot:wt_ww:RBT001"])
last_sync_time: Optional[datetime] last_sync_time: Optional[datetime] = Field(default=None, description="最近一次成功同步到的时间点。", examples=["2026-05-21T09:03:00Z"])
last_external_id: Optional[str] last_external_id: Optional[str] = Field(default=None, description="最近一次成功同步到的外部主键。消息通常对应 msg_id。", examples=["msg_003"])
last_status: Optional[str] last_status: Optional[str] = Field(default=None, description="最近一次同步状态。通常为 success 或 failed。", examples=["success"])
last_error: Optional[str] last_error: Optional[str] = Field(default=None, description="最近一次同步失败时的错误信息。", examples=[None])
last_started_at: Optional[datetime] last_started_at: Optional[datetime] = Field(default=None, description="最近一次同步启动时间。", examples=["2026-05-21T16:29:58Z"])
last_finished_at: Optional[datetime] last_finished_at: Optional[datetime] = Field(default=None, description="最近一次同步完成时间。", examples=["2026-05-21T16:30:00Z"])
class WeComSyncCheckpointListResponse(BaseModel): class WeComSyncCheckpointListResponse(BaseModel):
total: int total: int = Field(..., description="检查点总数。", examples=[4])
page: int page: int = Field(..., description="当前页码,从 1 开始。", examples=[1])
page_size: int page_size: int = Field(..., description="每页数量。", examples=[20])
list: List[WeComSyncCheckpointItem] list: List[WeComSyncCheckpointItem] = Field(..., description="同步检查点列表。")
...@@ -2,9 +2,16 @@ from typing import Protocol ...@@ -2,9 +2,16 @@ from typing import Protocol
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.model.agent import Agent
from app.model.agent_group import QrcodeChannel 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 ( from app.schema.agent_group import (
EmployeeInfo, EmployeeInfo,
EmployeeMountedAgent,
EmployeeMountedQrcode,
EmployeeMountSummary,
EmployeeMountsResponse,
EmployeeQrcode, EmployeeQrcode,
EmployeeQrcodesResponse, EmployeeQrcodesResponse,
PositionEmployeesResponse, PositionEmployeesResponse,
...@@ -66,25 +73,78 @@ class AgentGroupHelperService: ...@@ -66,25 +73,78 @@ class AgentGroupHelperService:
if not position_code.strip(): if not position_code.strip():
raise PositionNotFoundError("岗位不存在") raise PositionNotFoundError("岗位不存在")
position = self.db.query(PositionTag).filter(PositionTag.code == position_code).first()
if not position:
raise PositionNotFoundError("岗位不存在")
try: try:
payload = self.wecom_client.list_position_employees(position_code) payload = self.wecom_client.list_position_employees(position_code)
except WeComUnavailableError: except WeComUnavailableError:
raise payload = None
except Exception as exc: except Exception as exc:
raise WeComUnavailableError("企微员工列表暂不可用") from exc raise WeComUnavailableError("企微员工列表暂不可用") from exc
if payload is None: 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,
)
)
active_employees = [ return PositionEmployeesResponse(
EmployeeInfo(**employee) position_name=position.name or payload.get("position_name", ""),
for employee in payload.get("employees", []) employee_count=len(employees),
if employee.get("status") == "在职" employees=employees,
)
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( return PositionEmployeesResponse(
position_name=payload.get("position_name", ""), position_name=position.name or "",
employee_count=len(active_employees), employee_count=len(employees),
employees=active_employees, employees=employees,
) )
def list_employee_qrcodes(self, employee_id: str) -> EmployeeQrcodesResponse: def list_employee_qrcodes(self, employee_id: str) -> EmployeeQrcodesResponse:
...@@ -111,3 +171,54 @@ class AgentGroupHelperService: ...@@ -111,3 +171,54 @@ class AgentGroupHelperService:
qrcode_count=len(qrcodes), qrcode_count=len(qrcodes),
qrcodes=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)
...@@ -13,8 +13,6 @@ from app.schema.methodology import ( ...@@ -13,8 +13,6 @@ from app.schema.methodology import (
SaveMethodologyResponse, SaveMethodologyResponse,
) )
_MIN_STEPS = 4
_MAX_STEPS = 10
_MAX_STEP_NAME_LEN = 20 _MAX_STEP_NAME_LEN = 20
_MAX_MAIN_TITLE_LEN = 100 _MAX_MAIN_TITLE_LEN = 100
_MAX_SUB_TITLE_LEN = 200 _MAX_SUB_TITLE_LEN = 200
...@@ -64,9 +62,6 @@ class MethodologyService: ...@@ -64,9 +62,6 @@ class MethodologyService:
def save_methodology(self, req: SaveMethodologyRequest) -> SaveMethodologyResponse: def save_methodology(self, req: SaveMethodologyRequest) -> SaveMethodologyResponse:
step_count = len(req.steps) 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) orders = sorted(s.step_order for s in req.steps)
expected = list(range(1, step_count + 1)) expected = list(range(1, step_count + 1))
if orders != expected: if orders != expected:
......
...@@ -7,6 +7,7 @@ from sqlalchemy import or_ ...@@ -7,6 +7,7 @@ from sqlalchemy import or_
from sqlalchemy.orm import Session as OrmSession from sqlalchemy.orm import Session as OrmSession
from app.infrastructure.h5_cache import H5CacheManager from app.infrastructure.h5_cache import H5CacheManager
from app.model.agent import Agent, AgentPosition
from app.model.agent_group import QrcodeChannel from app.model.agent_group import QrcodeChannel
from app.model.position_tag import PositionTag, OfficialTab from app.model.position_tag import PositionTag, OfficialTab
from app.schema.official_site_tab import ( from app.schema.official_site_tab import (
...@@ -30,6 +31,7 @@ class OfficialSiteTabService: ...@@ -30,6 +31,7 @@ class OfficialSiteTabService:
self.cache = cache self.cache = cache
def create(self, req: CreateTabRequest) -> CreateTabResponse: def create(self, req: CreateTabRequest) -> CreateTabResponse:
now = datetime.now(timezone.utc)
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: if not position:
raise ValueError("岗位不存在") raise ValueError("岗位不存在")
...@@ -47,6 +49,8 @@ class OfficialSiteTabService: ...@@ -47,6 +49,8 @@ class OfficialSiteTabService:
display_status=req.display_status, display_status=req.display_status,
sort_order=req.sort_order, sort_order=req.sort_order,
created_by="admin", created_by="admin",
created_at=now,
updated_at=now,
) )
self.db.add(tab) self.db.add(tab)
self.db.commit() self.db.commit()
...@@ -60,6 +64,7 @@ class OfficialSiteTabService: ...@@ -60,6 +64,7 @@ class OfficialSiteTabService:
position_name=tab.position_name or "", position_name=tab.position_name or "",
qrcode_id=tab.qrcode_id or 0, qrcode_id=tab.qrcode_id or 0,
created_at=tab.created_at, created_at=tab.created_at,
updated_at=tab.updated_at,
) )
def update(self, tab_id: int, req: UpdateTabRequest) -> UpdateTabResponse: def update(self, tab_id: int, req: UpdateTabRequest) -> UpdateTabResponse:
...@@ -159,6 +164,7 @@ class OfficialSiteTabService: ...@@ -159,6 +164,7 @@ class OfficialSiteTabService:
sort_order=r.sort_order, sort_order=r.sort_order,
agent_count=0, agent_count=0,
created_at=r.created_at, created_at=r.created_at,
updated_at=r.updated_at,
operations=operations, operations=operations,
)) ))
...@@ -170,7 +176,9 @@ class OfficialSiteTabService: ...@@ -170,7 +176,9 @@ class OfficialSiteTabService:
) -> AvailableQrcodeListResponse: ) -> AvailableQrcodeListResponse:
query = self.db.query(QrcodeChannel).filter(QrcodeChannel.status == "enable") query = self.db.query(QrcodeChannel).filter(QrcodeChannel.status == "enable")
if position_code: 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() rows = query.order_by(QrcodeChannel.id.asc()).all()
items = [ items = [
......
from sqlalchemy.orm import Session import re
from sqlalchemy import or_ import secrets
from typing import Optional 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 import Agent, AgentPosition, AgentStatus
from app.model.agent_group import QrcodeChannel from app.model.agent_group import QrcodeChannel
from app.model.position_tag import OfficialTab, PositionTag
from app.schema.position_tag import ( from app.schema.position_tag import (
PositionTagCreate, AgentBrief,
PositionTagUpdate,
ReferenceCheckResponse,
BlockingReference, BlockingReference,
DetachableReference, DetachableReference,
PositionTagAgentStatistics, PositionTagAgentStatistics,
AgentBrief, PositionTagCreate,
PositionTagUpdate,
ReferenceCheckResponse,
) )
...@@ -20,16 +23,15 @@ class PositionTagService: ...@@ -20,16 +23,15 @@ class PositionTagService:
self.db = db self.db = db
def create(self, data: PositionTagCreate) -> PositionTag: def create(self, data: PositionTagCreate) -> PositionTag:
existing = self.db.query(PositionTag).filter( existing = self.db.query(PositionTag).filter(PositionTag.name == data.name).first()
PositionTag.code == data.code
).first()
if existing: if existing:
raise ValueError("岗位标签编码已存在") raise ValueError("岗位标签名称已存在")
tag = PositionTag( tag = PositionTag(
name=data.name, name=data.name,
code=data.code, code=self._generate_position_code(data.name),
description=data.description, description=data.description,
user_ids=[],
) )
self.db.add(tag) self.db.add(tag)
self.db.commit() self.db.commit()
...@@ -38,8 +40,19 @@ class PositionTagService: ...@@ -38,8 +40,19 @@ class PositionTagService:
def update(self, tag_id: int, data: PositionTagUpdate) -> PositionTag: def update(self, tag_id: int, data: PositionTagUpdate) -> PositionTag:
tag = self._get_tag_or_404(tag_id) 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.name = data.name
tag.description = data.description tag.description = data.description
tag.user_ids = self.resolve_tag_user_ids(tag)
self.db.commit() self.db.commit()
self.db.refresh(tag) self.db.refresh(tag)
return tag return tag
...@@ -51,44 +64,25 @@ class PositionTagService: ...@@ -51,44 +64,25 @@ class PositionTagService:
detachable = [] detachable = []
hints = [] hints = []
qrcode_refs = self.db.query(QrcodeChannel).filter( qrcode_refs = self.db.query(QrcodeChannel).filter(QrcodeChannel.position_name == tag.name).all()
QrcodeChannel.position_name == tag.name
).all()
for qr in qrcode_refs: for qr in qrcode_refs:
blocking.append(BlockingReference( blocking.append(BlockingReference(type="qrcode_channel", id=qr.id, name=qr.channel_code))
type="qrcode_channel",
id=qr.id, tab_refs = self.db.query(OfficialTab).filter(OfficialTab.position_id == tag_id).all()
name=qr.channel_code,
))
tab_refs = self.db.query(OfficialTab).filter(
OfficialTab.position_id == tag_id
).all()
for tab in tab_refs: for tab in tab_refs:
blocking.append(BlockingReference( blocking.append(BlockingReference(type="official_tab", id=tab.id, name=tab.tab_name))
type="official_tab",
id=tab.id, agent_positions = self.db.query(AgentPosition).filter(AgentPosition.position_id == tag_id).all()
name=tab.tab_name,
))
agent_positions = self.db.query(AgentPosition).filter(
AgentPosition.position_id == tag_id
).all()
for ap in agent_positions: for ap in agent_positions:
agent = self.db.query(Agent).filter(Agent.id == ap.agent_id).first() agent = self.db.query(Agent).filter(Agent.id == ap.agent_id).first()
if agent: if agent:
detachable.append(DetachableReference( detachable.append(DetachableReference(type="agent", id=agent.id, name=agent.name))
type="agent",
id=agent.id,
name=agent.name,
))
can_delete = len(blocking) == 0 can_delete = len(blocking) == 0
if blocking: if blocking:
hints.append("该岗位标签存在阻塞性引用,无法删除") hints.append("该岗位标签存在阻塞性引用,无法删除")
if detachable: if detachable:
hints.append("该岗位标签被 Agent 引用,删除将解除与 Agent 的关联") hints.append("该岗位标签被 Agent 引用,删除将解除相关 Agent 的岗位关联")
return ReferenceCheckResponse( return ReferenceCheckResponse(
can_delete=can_delete, can_delete=can_delete,
...@@ -98,7 +92,7 @@ class PositionTagService: ...@@ -98,7 +92,7 @@ class PositionTagService:
) )
def delete(self, tag_id: int, confirm_detach_agents: bool = False) -> None: 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) ref_check = self.check_references(tag_id)
if ref_check.blocking_references: if ref_check.blocking_references:
...@@ -107,56 +101,62 @@ class PositionTagService: ...@@ -107,56 +101,62 @@ class PositionTagService:
if ref_check.detachable_references: if ref_check.detachable_references:
if not confirm_detach_agents: if not confirm_detach_agents:
raise ValueError("该岗位标签被 Agent 引用,需确认解除关联后删除") raise ValueError("该岗位标签被 Agent 引用,需确认解除关联后删除")
self.db.query(AgentPosition).filter( self.db.query(AgentPosition).filter(AgentPosition.position_id == tag_id).delete()
AgentPosition.position_id == tag_id
).delete()
tag = self._get_tag_or_404(tag_id)
self.db.delete(tag) self.db.delete(tag)
self.db.commit() self.db.commit()
def list_tags( def list_tags(self, page: int = 1, page_size: int = 20, keyword: Optional[str] = None):
self,
page: int = 1,
page_size: int = 20,
keyword: Optional[str] = None,
):
query = self.db.query(PositionTag) query = self.db.query(PositionTag)
if keyword: if keyword:
query = query.filter( query = query.filter(PositionTag.name.like(f"%{keyword}%"))
or_(
PositionTag.name.like(f"%{keyword}%"),
PositionTag.code.like(f"%{keyword}%"),
)
)
total = query.count() total = query.count()
items = query.offset((page - 1) * page_size).limit(page_size).all() items = query.offset((page - 1) * page_size).limit(page_size).all()
return total, items 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: def get_agent_statistics(self, tag_id: int) -> PositionTagAgentStatistics:
self._get_tag_or_404(tag_id) 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] 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 [] 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) active_count = sum(1 for a in agents if a.status == AgentStatus.enable)
return PositionTagAgentStatistics( return PositionTagAgentStatistics(
position_id=tag_id, position_id=tag_id,
agent_count=len(agents), agent_count=len(agents),
active_agent_count=active_count, active_agent_count=active_count,
agents=[ agents=[AgentBrief(id=a.id, name=a.name, status=a.status.value) for a in agents],
AgentBrief(id=a.id, name=a.name, code=a.code, 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: def _get_tag_or_404(self, tag_id: int) -> PositionTag:
tag = self.db.query(PositionTag).filter(PositionTag.id == tag_id).first() tag = self.db.query(PositionTag).filter(PositionTag.id == tag_id).first()
if not tag: if not tag:
......
Binary files a/workspace/agent-admin/backend/dev.db-wal and b/workspace/agent-admin/backend/dev.db-wal differ Binary files a/workspace/agent-admin/backend/dev.db-wal and b/workspace/agent-admin/backend/dev.db-wal differ
# 后端接口测试文档: agents # 后端接口测试文档: agents
## 1. 模块说明 ## 1. 模块概览
| 项 | 值 | | 项 | 值 |
|------|-----| |------|-----|
| 模块名 | agents | | 模块名 | agents |
| 基础路径 | `/api/v1/agents` | | 基础路径 | `/api/v1/agents` |
| 说明 | Agent 基础管理,包含创建、更新、删除、详情、列表和状态更新 | | 模块说明 | Agent 管理接口,支持创建、更新、删除、列表、详情、状态切换,以及岗位下企业微信员工绑定。 |
## 2. 通用响应规范 ## 2. 通用响应结构
成功响应: 成功响应:
...@@ -25,7 +25,7 @@ ...@@ -25,7 +25,7 @@
```json ```json
{ {
"code": 400, "code": 400,
"message": "错误信息", "message": "参数校验失败",
"data": null "data": null
} }
``` ```
...@@ -51,16 +51,17 @@ ...@@ -51,16 +51,17 @@
- 方法: `POST` - 方法: `POST`
- 路径: `/api/v1/agents` - 路径: `/api/v1/agents`
- 说明: 请求体不再传 `code`,由后端自动生成 `agent_` 前缀唯一编码 - 说明: 创建时按 `name` 判重。`user_ids` 为员工记录 ID,取值来自 `qrcode_channels.id`,且必须属于所选岗位。响应中不再返回 `code` 字段。
请求体: 请求示例:
```json ```json
{ {
"name": "复盘 Agent", "name": "复盘 Agent",
"description": "智能复盘助手", "description": "智能复盘助手,帮助销售进行每日复盘",
"position_ids": [1], "position_ids": [1, 3],
"skill_codes": ["query-metric"], "skill_codes": ["query-metric", "query-detail", "attribution-analysis"],
"user_ids": [1, 5],
"status": "enable" "status": "enable"
} }
``` ```
...@@ -74,28 +75,40 @@ ...@@ -74,28 +75,40 @@
"data": { "data": {
"agent_id": 101, "agent_id": 101,
"name": "复盘 Agent", "name": "复盘 Agent",
"code": "agent_a7k29xqp", "position_ids": [1, 3],
"position_ids": [1], "skill_codes": ["attribution-analysis", "query-detail", "query-metric"],
"skill_codes": ["query-metric"], "user_ids": [1, 5],
"created_at": "2026-05-15T10:30:00Z" "created_at": "2026-05-21T10:30:00Z"
} }
} }
``` ```
失败示例:
```json
{
"code": 400,
"message": "Agent名称已存在",
"data": null
}
```
### 3.2 更新 Agent ### 3.2 更新 Agent
- 方法: `PUT` - 方法: `PUT`
- 路径: `/api/v1/agents/{agent_id}` - 路径: `/api/v1/agents/{agent_id}`
- 说明: 更新时如果改名,也会按 `name` 判重。响应中不返回 `code` 字段。
请求体: 请求示例:
```json ```json
{ {
"name": "更新后 Agent", "name": "复盘 Agent",
"description": "更新后的描述", "description": "更新后的描述",
"status": "enable", "status": "enable",
"position_ids": [1, 2], "position_ids": [1, 2],
"skill_codes": ["query-metric", "query-detail"] "skill_codes": ["query-metric", "query-detail"],
"user_ids": [1, 2]
} }
``` ```
...@@ -107,11 +120,11 @@ ...@@ -107,11 +120,11 @@
"message": "success", "message": "success",
"data": { "data": {
"agent_id": 101, "agent_id": 101,
"name": "更新后 Agent", "name": "复盘 Agent",
"code": "agent_a7k29xqp",
"position_ids": [1, 2], "position_ids": [1, 2],
"skill_codes": ["query-detail", "query-metric"], "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 @@ ...@@ -138,6 +151,7 @@
- 方法: `GET` - 方法: `GET`
- 路径: `/api/v1/agents/{agent_id}` - 路径: `/api/v1/agents/{agent_id}`
- 说明: 详情响应不返回 `code` 字段。
成功响应示例: 成功响应示例:
...@@ -148,7 +162,6 @@ ...@@ -148,7 +162,6 @@
"data": { "data": {
"agent_id": 101, "agent_id": 101,
"name": "复盘 Agent", "name": "复盘 Agent",
"code": "agent_a7k29xqp",
"description": "智能复盘助手", "description": "智能复盘助手",
"positions": [ "positions": [
{"id": 1, "name": "驻店销售岗"}, {"id": 1, "name": "驻店销售岗"},
...@@ -159,6 +172,10 @@ ...@@ -159,6 +172,10 @@
{"skill_code": "query-detail", "skill_name": "明细查询"}, {"skill_code": "query-detail", "skill_name": "明细查询"},
{"skill_code": "attribution-analysis", "skill_name": "归因分析"} {"skill_code": "attribution-analysis", "skill_name": "归因分析"}
], ],
"users": [
{"user_id": 1, "user_name": "张三"},
{"user_id": 5, "user_name": "李四"}
],
"status": "enable", "status": "enable",
"session_count": 156, "session_count": 156,
"created_at": "2026-05-10T09:00:00Z", "created_at": "2026-05-10T09:00:00Z",
...@@ -177,6 +194,7 @@ ...@@ -177,6 +194,7 @@
- `keyword` - `keyword`
- `position_id` - `position_id`
- `status` - `status`
- 说明: `keyword` 只按 `name` 模糊搜索,不再按 `code` 搜索。列表响应不返回 `code` 字段。
成功响应示例: 成功响应示例:
...@@ -192,17 +210,17 @@ ...@@ -192,17 +210,17 @@
{ {
"agent_id": 1, "agent_id": 1,
"name": "Agent1", "name": "Agent1",
"code": "agent_1abc23de",
"position_ids": [1], "position_ids": [1],
"skill_codes": ["query-metric"], "skill_codes": ["query-metric"],
"user_ids": [1],
"created_at": "2026-05-21T10:00:00" "created_at": "2026-05-21T10:00:00"
}, },
{ {
"agent_id": 2, "agent_id": 2,
"name": "Agent2", "name": "Agent2",
"code": "agent_9f0c12ab",
"position_ids": [2], "position_ids": [2],
"skill_codes": ["query-detail"], "skill_codes": ["query-detail"],
"user_ids": [2],
"created_at": "2026-05-21T10:01:00" "created_at": "2026-05-21T10:01:00"
} }
] ]
...@@ -215,12 +233,12 @@ ...@@ -215,12 +233,12 @@
- 方法: `PUT` - 方法: `PUT`
- 路径: `/api/v1/agents/{agent_id}/status` - 路径: `/api/v1/agents/{agent_id}/status`
请求体: 请求示例:
```json ```json
{ {
"status": "disable", "status": "disable",
"reason": "手动禁用" "reason": "manual disable"
} }
``` ```
...@@ -239,12 +257,14 @@ ...@@ -239,12 +257,14 @@
## 4. 测试覆盖 ## 4. 测试覆盖
文档对应测试文件: `backend/tests/test_agents_api.py` 对应测试文件: `backend/tests/test_agents_api.py`
| 测试类 | 测试方法 | | 测试类 | 测试用例 |
|------|------| |------|------|
| `TestCreateAgent` | `test_create_agent_success` | | `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_success` |
| `TestUpdateAgent` | `test_update_agent_without_version` | | `TestUpdateAgent` | `test_update_agent_without_version` |
| `TestDeleteAgent` | `test_delete_agent_success` | | `TestDeleteAgent` | `test_delete_agent_success` |
...@@ -252,3 +272,38 @@ ...@@ -252,3 +272,38 @@
| `TestListAgents` | `test_list_agents_success` | | `TestListAgents` | `test_list_agents_success` |
| `TestListAgents` | `test_list_agents_with_keyword` | | `TestListAgents` | `test_list_agents_with_keyword` |
| `TestUpdateStatus` | `test_disable_agent` | | `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 关联会话数量。 |
# 接口测试文档 — official-site-home # 鎺ュ彛娴嬭瘯鏂囨。 鈥?official-site-home
--- ---
## 1. 模块概览 ## 1. 妯″潡姒傝
| 字段 | 值 | | 瀛楁 | 鍊?|
|------|-----| |------|-----|
| 模块名称 | official-site-home | | 妯″潡鍚嶇О | official-site-home |
| 模块说明 | H5首页聚合接口 — 一次返回Tab+Agent+方法论+缓存 | | 妯″潡璇存槑 | H5棣栭〉鑱氬悎鎺ュ彛 鈥?涓€娆¤繑鍥濼ab+Agent+鏂规硶璁?缂撳瓨 |
| 路由前缀 | `/api/v1/official-site/home` | | 璺敱鍓嶇紑 | `/api/v1/official-site/home` |
| 数据库表 | `official_tabs`, `official_site_agent_display`, `official_site_methodology` 等 | | 鏁版嵁搴撹〃 | `official_tabs`, `official_site_agent_display`, `official_site_methodology` 绛?|
| 外部依赖 | H5CacheManager(TTL缓存) | | 澶栭儴渚濊禆 | 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 | | 鏂规硶 | GET |
| 路径 | `/api/v1/official-site/home` | | 璺緞 | `/api/v1/official-site/home` |
| 说明 | 聚合Tab、Agent展示、方法论数据,支持缓存(TTL=300s) | | 璇存槑 | 鑱氬悎Tab銆丄gent灞曠ず銆佹柟娉曡鏁版嵁锛屾敮鎸佺紦瀛?TTL=300s) |
**响应参数** **鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 | | 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------| |----------|------|------|
| site_title | string | 站点标题 | | site_title | string | 绔欑偣鏍囬 |
| site_subtitle | string | 站点副标题 | | site_subtitle | string | 绔欑偣鍓爣棰?|
| background_image | string | 背景图 | | background_image | string | 鑳屾櫙鍥?|
| tabs | array | Tab列表 | | tabs | array | Tab鍒楄〃 |
| tabs[].tab_id | integer | Tab ID | | tabs[].tab_id | integer | Tab ID |
| tabs[].position_code | string | 岗位编码 | | tabs[].position_code | string | 宀椾綅缂栫爜 |
| tabs[].position_name | string | 岗位名称 | | tabs[].position_name | string | 宀椾綅鍚嶇О |
| tabs[].qrcode_url | string | 活码URL | | tabs[].qrcode_url | string | 娲荤爜URL |
| tabs[].agents | array | Agent列表 | | tabs[].agents | array | Agent鍒楄〃 |
| tabs[].agents[].agent_id | integer | Agent ID | | tabs[].agents[].agent_id | integer | Agent ID |
| tabs[].agents[].agent_name | string | Agent名称 | | tabs[].agents[].agent_name | string | Agent鍚嶇О |
| tabs[].agents[].media_url | string | 素材URL | | tabs[].agents[].media_url | string | 绱犳潗URL |
| tabs[].agents[].speech_title | string | 话术标题 | | tabs[].agents[].speech_title | string | 璇濇湳鏍囬 |
| tabs[].agents[].speech_content | string | 话术正文 | | tabs[].agents[].speech_content | string | 璇濇湳姝f枃 |
| methodology | object | 方法论 | | methodology | object | 鏂规硶璁?|
| methodology.display_status | string | enable/disable | | methodology.display_status | string | enable/disable |
| methodology.main_title | string | 主标题 | | methodology.main_title | string | 涓绘爣棰?|
| methodology.sub_title | string | 副标题 | | methodology.sub_title | string | 鍓爣棰?|
| methodology.steps | array | 步骤列表 | | 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条 | | 1 | 缂撳瓨鏈懡涓粠DB鏋勫缓 | 姝e父 | site_title闈炵┖锛宼abs鏈?鏉★紝agents鏈?鏉?|
| 2 | 缓存命中返回缓存数据 | 正常 | DB修改后仍返回旧数据 | | 2 | 缂撳瓨鍛戒腑杩斿洖缂撳瓨鏁版嵁 | 姝e父 | DB淇敼鍚庝粛杩斿洖鏃ф暟鎹?|
| 3 | disable的Tab不返回 | 正常 | tabs长度=0 | | 3 | disable鐨凾ab涓嶈繑鍥?| 姝e父 | tabs闀垮害=0 |
| 4 | disable的Agent配置不返回 | 正常 | tabs有1条但agents为空 | | 4 | disable鐨凙gent閰嶇疆涓嶈繑鍥?| 姝e父 | tabs鏈?鏉′絾agents涓虹┖ |
| 5 | Agent本身disable不返回 | 正常 | agents为空 | | 5 | Agent鏈韩disable涓嶈繑鍥?| 姝e父 | agents涓虹┖ |
| 6 | sort_order排序 | 正常 | sort_order小的Agent在前 | | 6 | sort_order鎺掑簭 | 姝e父 | sort_order灏忕殑Agent鍦ㄥ墠 |
| 7 | 缓存未命中时写入 | 正常 | cache.get_home_page()非空 | | 7 | 缂撳瓨鏈懡涓椂鍐欏叆 | 姝e父 | cache.get_home_page()闈炵┖ |
| 8 | 缓存失效后刷新 | 正常 | 修改Agent名后invalidate再查,返回新名称 | | 8 | 缂撳瓨澶辨晥鍚庡埛鏂?| 姝e父 | 淇敼Agent鍚嶅悗invalidate鍐嶆煡锛岃繑鍥炴柊鍚嶇О |
| 9 | 方法论数据返回 | 正常 | methodology.display_status="enable", steps=2 | | 9 | 鏂规硶璁烘暟鎹繑鍥?| 姝e父 | methodology.display_status="enable", steps=2 |
| 10 | 空站点 | 边界 | tabs=[], methodology.display_status="disable" | | 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_miss_builds_from_db | 1 |
| test_cache_hit_returns_cached_data | 2 | | test_cache_hit_returns_cached_data | 2 |
...@@ -95,3 +95,56 @@ ...@@ -95,3 +95,56 @@
| test_cache_invalidate_then_refresh | 8 | | test_cache_invalidate_then_refresh | 8 |
| test_methodology_returned | 9 | | test_methodology_returned | 9 |
| test_empty_site | 10 | | 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-upload # 鎺ュ彛娴嬭瘯鏂囨。 鈥?official-site-upload
--- ---
## 1. 模块概览 ## 1. 妯″潡姒傝
| 字段 | 值 | | 瀛楁 | 鍊?|
|------|-----| |------|-----|
| 模块名称 | official-site-upload | | 妯″潡鍚嶇О | official-site-upload |
| 模块说明 | 官网素材上传 — 格式/大小校验 + OSS存储 + 图片宽高解析 + CDN URL | | 妯″潡璇存槑 | 瀹樼綉绱犳潗涓婁紶 鈥?鏍煎紡/澶у皬鏍¢獙 + OSS瀛樺偍 + 鍥剧墖瀹介珮瑙f瀽 + CDN URL |
| 路由前缀 | `/api/v1/official-site/upload` | | 璺敱鍓嶇紑 | `/api/v1/official-site/upload` |
| 数据库表 | 无 | | 鏁版嵁搴撹〃 | 鏃?|
| 外部依赖 | OSSClient(对象存储) | | 澶栭儴渚濊禆 | OSSClient锛堝璞″瓨鍌級 |
--- ---
## 2. 接口列表 ## 2. 鎺ュ彛鍒楄〃
| 序号 | 方法 | 路径 | 说明 | | 搴忓彿 | 鏂规硶 | 璺緞 | 璇存槑 |
|------|------|------|------| |------|------|------|------|
| 1 | POST | `/api/v1/official-site/upload` | 上传素材文件 | | 1 | POST | `/api/v1/official-site/upload` | 涓婁紶绱犳潗鏂囦欢 |
--- ---
## 3. 接口详细说明 ## 3. 鎺ュ彛璇︾粏璇存槑
### 3.1 上传素材文件 ### 3.1 涓婁紶绱犳潗鏂囦欢
**基本信息** **鍩烘湰淇℃伅**
| 字段 | 值 | | 瀛楁 | 鍊?|
|------|-----| |------|-----|
| 方法 | POST | | 鏂规硶 | POST |
| 路径 | `/api/v1/official-site/upload` | | 璺緞 | `/api/v1/official-site/upload` |
| 说明 | 上传Agent素材或方法论图片,支持 gif/mp4/png/jpg | | 璇存槑 | 涓婁紶Agent绱犳潗鎴栨柟娉曡鍥剧墖锛屾敮鎸?gif/mp4/png/jpg |
| Content-Type | multipart/form-data | | Content-Type | multipart/form-data |
**请求参数** **璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 | | 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------| |--------|------|------|------|------|
| usage_type | form | string | 是 | 用途类型:agent_media / methodology_icon / methodology_image | | usage_type | form | string | 鏄?| 鐢ㄩ€旂被鍨嬶細agent_media / methodology_icon / methodology_image |
| file | form | file | 是 | 上传文件 | | file | form | file | 鏄?| 涓婁紶鏂囦欢 |
**usage_type 对应校验规则** **usage_type 瀵瑰簲鏍¢獙瑙勫垯**
| usage_type | 允许格式 | 大小限制 | 解析宽高 | | usage_type | 鍏佽鏍煎紡 | 澶у皬闄愬埗 | 瑙f瀽瀹介珮 |
|------------|----------|----------|----------| |------------|----------|----------|----------|
| agent_media | gif, mp4 | 20MB | 否 | | agent_media | gif, mp4 | 20MB | 鍚?|
| methodology_icon | png, jpg | 2MB | 是 | | methodology_icon | png, jpg | 2MB | 鏄?|
| methodology_image | png, jpg | 2MB | 是 | | methodology_image | png, jpg | 2MB | 鏄?|
**响应参数** **鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 | | 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------| |----------|------|------|
| file_url | string | OSS存储路径 | | file_url | string | OSS瀛樺偍璺緞 |
| file_type | string | 文件格式(gif/mp4/png/jpg) | | file_type | string | 鏂囦欢鏍煎紡(gif/mp4/png/jpg) |
| file_size | integer | 文件大小(bytes) | | file_size | integer | 鏂囦欢澶у皬(bytes) |
| width | integer | 图片宽度,非图片为null | | width | integer | 鍥剧墖瀹藉害锛岄潪鍥剧墖涓簄ull |
| height | integer | 图片高度,非图片为null | | height | integer | 鍥剧墖楂樺害锛岄潪鍥剧墖涓簄ull |
| cdn_url | string | CDN访问URL,含版本号 `?v=2026` | | cdn_url | string | CDN璁块棶URL锛屽惈鐗堟湰鍙?`?v=2026` |
**成功响应示例** **鎴愬姛鍝嶅簲绀轰緥**
```json ```json
{ {
...@@ -74,37 +74,37 @@ ...@@ -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=" | | 1 | Agent绱犳潗gif涓婁紶 | 姝e父 | file_type="gif", file_url鍚?agent/", cdn_url鍚??v=" |
| 2 | Agent素材mp4上传 | 正常 | file_type="mp4", width/height为null | | 2 | Agent绱犳潗mp4涓婁紶 | 姝e父 | file_type="mp4", width/height涓簄ull |
| 3 | 方法论图标png上传 | 正常 | file_type="png", file_url含"methodology/icon/", width=200, height=200 | | 3 | 鏂规硶璁哄浘鏍噋ng涓婁紶 | 姝e父 | file_type="png", file_url鍚?methodology/icon/", width=200, height=200 |
| 4 | 方法论图片jpg上传 | 正常 | file_type="jpg", file_url含"methodology/image/", width=800, height=600 | | 4 | 鏂规硶璁哄浘鐗噅pg涓婁紶 | 姝e父 | file_type="jpg", file_url鍚?methodology/image/", width=800, height=600 |
| 5 | 格式不支持(pdf) | 异常 | ValueError "格式" | | 5 | 鏍煎紡涓嶆敮鎸?pdf) | 寮傚父 | ValueError "鏍煎紡" |
| 6 | Agent素材超20MB | 异常 | ValueError "20MB" | | 6 | Agent绱犳潗瓒?0MB | 寮傚父 | ValueError "20MB" |
| 7 | 方法论图标超2MB | 异常 | ValueError "2MB" | | 7 | 鏂规硶璁哄浘鏍囪秴2MB | 寮傚父 | ValueError "2MB" |
| 8 | CDN URL含版本号 | 正常 | cdn_url含"?v=2026" | | 8 | CDN URL鍚増鏈彿 | 姝e父 | cdn_url鍚??v=2026" |
| 9 | 非图片无宽高 | 正常 | mp4的width/height为null | | 9 | 闈炲浘鐗囨棤瀹介珮 | 姝e父 | mp4鐨剋idth/height涓簄ull |
| 10 | 无效usage_type | 异常 | ValueError "类型" | | 10 | 鏃犳晥usage_type | 寮傚父 | ValueError "绫诲瀷" |
| 11 | OSS集成验证 | 正常 | 通过OSS客户端可读取已上传文件 | | 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_gif_success | 1 |
| test_agent_media_mp4_success | 2 | | test_agent_media_mp4_success | 2 |
...@@ -117,3 +117,56 @@ ...@@ -117,3 +117,56 @@
| test_width_height_optional_for_non_image | 9 | | test_width_height_optional_for_non_image | 9 |
| test_invalid_usage_type | 10 | | test_invalid_usage_type | 10 |
| test_oss_upload_integration | 11 | | 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`。
# 接口测试文档 — sessions # 鎺ュ彛娴嬭瘯鏂囨。 鈥?sessions
--- ---
## 1. 模块概览 ## 1. 妯″潡姒傝
| 字段 | 值 | | 瀛楁 | 鍊?|
|------|-----| |------|-----|
| 模块名称 | sessions | | 妯″潡鍚嶇О | sessions |
| 模块说明 | 会话管理 — 创建、追加入档、查询详情、上下文继承、归档 | | 妯″潡璇存槑 | 浼氳瘽绠$悊 鈥?鍒涘缓銆佽拷鍔犲叆妗c€佹煡璇㈣鎯呫€佷笂涓嬫枃缁ф壙銆佸綊妗?|
| 路由前缀 | `/api/v1/sessions` | | 璺敱鍓嶇紑 | `/api/v1/sessions` |
| 数据库表 | `sessions`, `conversation_history` | | 鏁版嵁搴撹〃 | `sessions`, `conversation_history` |
| 外部依赖 | 无 | | 澶栭儴渚濊禆 | 鏃?|
--- ---
## 2. 接口列表 ## 2. 鎺ュ彛鍒楄〃
| 序号 | 方法 | 路径 | 说明 | | 搴忓彿 | 鏂规硶 | 璺緞 | 璇存槑 |
|------|------|------|------| |------|------|------|------|
| 1 | POST | `/api/v1/sessions` | 创建会话 | | 1 | POST | `/api/v1/sessions` | 鍒涘缓浼氳瘽 |
| 2 | PUT | `/api/v1/sessions/{session_id}` | 追加对话并合并实体 | | 2 | PUT | `/api/v1/sessions/{session_id}` | 杩藉姞瀵硅瘽骞跺悎骞跺疄浣?|
| 3 | GET | `/api/v1/sessions/{session_id}` | 查询会话详情 | | 3 | GET | `/api/v1/sessions/{session_id}` | 鏌ヨ浼氳瘽璇︽儏 |
| 4 | GET | `/api/v1/sessions/{session_id}/context` | 查询会话上下文 | | 4 | GET | `/api/v1/sessions/{session_id}/context` | 鏌ヨ浼氳瘽涓婁笅鏂?|
| 5 | POST | `/api/v1/sessions/{session_id}/archive` | 归档会话 | | 5 | POST | `/api/v1/sessions/{session_id}/archive` | 褰掓。浼氳瘽 |
--- ---
## 3. 接口详细说明 ## 3. 鎺ュ彛璇︾粏璇存槑
### 3.1 创建会话 ### 3.1 鍒涘缓浼氳瘽
**请求参数** **璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 | | 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------| |--------|------|------|------|------|
| user_id | body | string | 是 | 用户ID,最长64 | | user_id | body | string | 鏄?| 鐢ㄦ埛ID锛屾渶闀?4 |
| channel | body | string | 是 | 渠道,最长64 | | channel | body | string | 鏄?| 娓犻亾锛屾渶闀?4 |
| initial_query | body | string | 是 | 初始问题,1~5000字符 | | initial_query | body | string | 鏄?| 鍒濆闂锛?~5000瀛楃 |
**响应参数** **鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 | | 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------| |----------|------|------|
| session_id | string | 会话ID | | session_id | string | 浼氳瘽ID |
| user_id | string | 用户ID | | user_id | string | 鐢ㄦ埛ID |
| channel | string | 渠道 | | channel | string | 娓犻亾 |
| current_agent_id | integer | 当前Agent ID | | current_agent_id | integer | 褰撳墠Agent ID |
| created_at | string | 创建时间 | | created_at | string | 鍒涘缓鏃堕棿 |
--- ---
### 3.2 追加对话 ### 3.2 杩藉姞瀵硅瘽
**请求参数** **璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 | | 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------| |--------|------|------|------|------|
| session_id | path | string | 是 | 会话ID | | session_id | path | string | 鏄?| 浼氳瘽ID |
| role | body | string | 是 | 角色,最长32 | | role | body | string | 鏄?| 瑙掕壊锛屾渶闀?2 |
| content | body | string | 是 | 内容,1~5000字符 | | content | body | string | 鏄?| 鍐呭锛?~5000瀛楃 |
| agent_id | body | integer | 是 | Agent ID | | agent_id | body | integer | 鏄?| Agent ID |
| intent | body | string | 否 | 意图 | | intent | body | string | 鍚?| 鎰忓浘 |
| entities | body | object | 否 | 实体JSON | | entities | body | object | 鍚?| 瀹炰綋JSON |
**响应参数** **鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 | | 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------| |----------|------|------|
| success | boolean | 是否成功 | | success | boolean | 鏄惁鎴愬姛 |
| updated_at | string | 更新时间 | | updated_at | string | 鏇存柊鏃堕棿 |
| turn_count | integer | 当前轮次 | | turn_count | integer | 褰撳墠杞 |
--- ---
### 3.3 查询会话详情 ### 3.3 鏌ヨ浼氳瘽璇︽儏
**响应参数** **鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 | | 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------| |----------|------|------|
| session_id | string | 会话ID | | session_id | string | 浼氳瘽ID |
| user_id | string | 用户ID | | user_id | string | 鐢ㄦ埛ID |
| channel | string | 渠道 | | channel | string | 娓犻亾 |
| current_agent_id | integer | 当前Agent ID | | current_agent_id | integer | 褰撳墠Agent ID |
| current_agent_name | string | Agent名称 | | current_agent_name | string | Agent鍚嶇О |
| conversation_history | array | 对话历史 | | conversation_history | array | 瀵硅瘽鍘嗗彶 |
| conversation_history[].role | string | 角色 | | conversation_history[].role | string | 瑙掕壊 |
| conversation_history[].content | string | 内容 | | conversation_history[].content | string | 鍐呭 |
| conversation_history[].agent_id | integer | Agent ID | | conversation_history[].agent_id | integer | Agent ID |
| conversation_history[].intent | string | 意图 | | conversation_history[].intent | string | 鎰忓浘 |
| context_entities | object | 合并后的实体 | | context_entities | object | 鍚堝苟鍚庣殑瀹炰綋 |
--- ---
### 3.4 查询会话上下文 ### 3.4 鏌ヨ浼氳瘽涓婁笅鏂?
**鍝嶅簲鍙傛暟**
**响应参数** | 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
| 字段路径 | 类型 | 说明 |
|----------|------|------| |----------|------|------|
| session_id | string | 会话ID | | session_id | string | 浼氳瘽ID |
| current_agent_id | integer | 当前Agent ID | | current_agent_id | integer | 褰撳墠Agent ID |
| last_entities | object | 最近实体 | | last_entities | object | 鏈€杩戝疄浣?|
| inheritance_valid | boolean | 继承是否有效 | | inheritance_valid | boolean | 缁ф壙鏄惁鏈夋晥 |
| expires_at | string | 过期时间 | | expires_at | string | 杩囨湡鏃堕棿 |
--- ---
### 3.5 归档会话 ### 3.5 褰掓。浼氳瘽
**响应参数** **鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 | | 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------| |----------|------|------|
| success | boolean | 是否成功 | | success | boolean | 鏄惁鎴愬姛 |
| archived_at | string | 归档时间 | | archived_at | string | 褰掓。鏃堕棿 |
--- ---
## 4. 测试场景 ## 4. 娴嬭瘯鍦烘櫙
| 序号 | 场景名称 | 分类 | 预期结果 | | 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------| |------|----------|------|----------|
| 1 | 创建→追加→详情→上下文 | 正常 | 创建201, 追加success+turn_count=1, 详情含history+entities, 上下文inheritance_valid=True | | 1 | 鍒涘缓鈫掕拷鍔犫啋璇︽儏鈫掍笂涓嬫枃 | 姝e父 | 鍒涘缓201, 杩藉姞success+turn_count=1, 璇︽儏鍚玥istory+entities, 涓婁笅鏂噄nheritance_valid=True |
| 2 | 归档会话 | 正常 | success=True, 归档后详情仍可读, 上下文inheritance_valid=False | | 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_create_update_get_and_context | 1 |
| TestSessionsApi | test_archive_session | 2 | | 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-scanner |
| 模块说明 | Skill目录扫描器 — 从文件系统SKILL.md读取技能配置并生成skills.json | | 妯″潡璇存槑 | Skill鐩綍鎵弿鍣?鈥?浠庢枃浠剁郴缁烻KILL.md璇诲彇鎶€鑳介厤缃苟鐢熸垚skills.json |
| 路由前缀 | 无(非HTTP接口,工具类) | | 璺敱鍓嶇紑 | 鏃狅紙闈濰TTP鎺ュ彛锛屽伐鍏风被锛?|
| 数据库表 | 无 | | 鏁版嵁搴撹〃 | 鏃?|
| 外部依赖 | 文件系统 | | 澶栭儴渚濊禆 | 鏂囦欢绯荤粺 |
--- ---
## 2. 组件列表 ## 2. 缁勪欢鍒楄〃
| 序号 | 函数/方法 | 说明 | | 搴忓彿 | 鍑芥暟/鏂规硶 | 璇存槑 |
|------|-----------|------| |------|-----------|------|
| 1 | `_parse_frontmatter(content)` | 解析SKILL.md的YAML frontmatter | | 1 | `_parse_frontmatter(content)` | 瑙f瀽SKILL.md鐨刌AML frontmatter |
| 2 | `scan_skills(skills_dir)` | 扫描目录下所有SKILL.md,返回技能字典 | | 2 | `scan_skills(skills_dir)` | 鎵弿鐩綍涓嬫墍鏈塖KILL.md锛岃繑鍥炴妧鑳藉瓧鍏?|
| 3 | `update_skills_json(skills_dir, config_dir)` | 全量扫描并写入config/skills.json | | 3 | `update_skills_json(skills_dir, config_dir)` | 鍏ㄩ噺鎵弿骞跺啓鍏onfig/skills.json |
--- ---
## 3. 组件详细说明 ## 3. 缁勪欢璇︾粏璇存槑
### 3.1 _parse_frontmatter ### 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 ### 3.2 scan_skills
**输入**:`skills_dir: Path` — 技能根目录 **杈撳叆**锛歚skills_dir: Path` 鈥?鎶€鑳芥牴鐩綍
**输出**:`dict[str, SkillConfig]` — 技能编码到配置的映射 **杈撳嚭**锛歚dict[str, SkillConfig]` 鈥?鎶€鑳界紪鐮佸埌閰嶇疆鐨勬槧灏?
**过滤规则**: **杩囨护瑙勫垯**锛?
- 跳过无 SKILL.md 的子目录 - 璺宠繃鏃?SKILL.md 鐨勫瓙鐩綍
- 跳过隐藏目录(`.` 开头) - 璺宠繃闅愯棌鐩綍锛坄.` 寮€澶达級
- 空目录/不存在目录返回 `{}` - 绌虹洰褰?涓嶅瓨鍦ㄧ洰褰曡繑鍥?`{}`
**SkillConfig 字段**: **SkillConfig 瀛楁**锛?
| 字段 | 类型 | 说明 | | 瀛楁 | 绫诲瀷 | 璇存槑 |
|------|------|------| |------|------|------|
| name | string | 技能名称 | | name | string | 鎶€鑳藉悕绉?|
| description | string | 描述 | | description | string | 鎻忚堪 |
| instruction | string | SKILL.md 正文 | | instruction | string | SKILL.md 姝f枃 |
| location | string | 相对路径(如 `skills/meeting_minutes`) | | location | string | 鐩稿璺緞锛堝 `skills/meeting_minutes`锛?|
### 3.3 update_skills_json ### 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 ```json
{ {
...@@ -69,7 +69,7 @@ ...@@ -69,7 +69,7 @@
"code": "alpha", "code": "alpha",
"name": "alpha", "name": "alpha",
"location": "skills/alpha", "location": "skills/alpha",
"instruction": "技能 alpha 的说明" "instruction": "鎶€鑳?alpha 鐨勮鏄?
} }
} }
} }
...@@ -77,38 +77,38 @@ ...@@ -77,38 +77,38 @@
--- ---
## 4. 测试场景 ## 4. 娴嬭瘯鍦烘櫙
### 4.1 Frontmatter解析 ### 4.1 Frontmatter瑙f瀽
| 序号 | 场景名称 | 预期结果 | | 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------| |------|----------|----------|
| 1 | 解析有效frontmatter | meta含name/description, body含正文 | | 1 | 瑙f瀽鏈夋晥frontmatter | meta鍚玭ame/description, body鍚鏂?|
| 2 | 无frontmatter | meta={}, body=原文 | | 2 | 鏃爁rontmatter | meta={}, body=鍘熸枃 |
### 4.2 scan_skills ### 4.2 scan_skills
| 序号 | 场景名称 | 预期结果 | | 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------| |------|----------|----------|
| 1 | 正常扫描2个技能 | 长度=2, 含meeting_minutes和support | | 1 | 姝e父鎵弿2涓妧鑳?| 闀垮害=2, 鍚玬eeting_minutes鍜宻upport |
| 2 | 跳过无SKILL.md的目录 | 长度=1 | | 2 | 璺宠繃鏃燬KILL.md鐨勭洰褰?| 闀垮害=1 |
| 3 | 跳过隐藏目录 | 长度=0 | | 3 | 璺宠繃闅愯棌鐩綍 | 闀垮害=0 |
| 4 | 空目录 | 返回{} | | 4 | 绌虹洰褰?| 杩斿洖{} |
| 5 | 不存在的目录 | 返回{} | | 5 | 涓嶅瓨鍦ㄧ殑鐩綍 | 杩斿洖{} |
### 4.3 update_skills_json ### 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_parses_valid_frontmatter | 4.1-1 |
| TestParseFrontmatter | test_handles_missing_frontmatter | 4.1-2 | | TestParseFrontmatter | test_handles_missing_frontmatter | 4.1-2 |
...@@ -118,3 +118,56 @@ ...@@ -118,3 +118,56 @@
| TestScanSkills | test_empty_skills_dir | 4.2-4 | | TestScanSkills | test_empty_skills_dir | 4.2-4 |
| TestScanSkills | test_nonexistent_dir | 4.2-5 | | TestScanSkills | test_nonexistent_dir | 4.2-5 |
| TestUpdateSkillsJson | test_full_scan_and_write | 4.3-1 | | 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 |
| 模块说明 | Skill目录 — 列表查询 + 详情查询 + Redis缓存 | | 妯″潡璇存槑 | Skill鐩綍 鈥?鍒楄〃鏌ヨ + 璇︽儏鏌ヨ + Redis缂撳瓨 |
| 路由前缀 | `/api/v1/skills` | | 璺敱鍓嶇紑 | `/api/v1/skills` |
| 数据库表 | `skills` | | 鏁版嵁搴撹〃 | `skills` |
| 外部依赖 | SkillCache(内存缓存) | | 澶栭儴渚濊禆 | SkillCache锛堝唴瀛樼紦瀛橈級 |
--- ---
## 2. 接口列表 ## 2. 鎺ュ彛鍒楄〃
| 序号 | 方法 | 路径 | 说明 | | 搴忓彿 | 鏂规硶 | 璺緞 | 璇存槑 |
|------|------|------|------| |------|------|------|------|
| 1 | GET | `/api/v1/skills` | 查询Skill列表 | | 1 | GET | `/api/v1/skills` | 鏌ヨSkill鍒楄〃 |
| 2 | GET | `/api/v1/skills/{skill_code}` | 查询Skill详情 | | 2 | GET | `/api/v1/skills/{skill_code}` | 鏌ヨSkill璇︽儏 |
--- ---
## 3. 接口详细说明 ## 3. 鎺ュ彛璇︾粏璇存槑
### 3.1 查询Skill列表 ### 3.1 鏌ヨSkill鍒楄〃
**基本信息** **鍩烘湰淇℃伅**
| 字段 | 值 | | 瀛楁 | 鍊?|
|------|-----| |------|-----|
| 方法 | GET | | 鏂规硶 | GET |
| 路径 | `/api/v1/skills` | | 璺緞 | `/api/v1/skills` |
| 说明 | 返回所有Skill列表,按priority升序,列表项不含doc_markdown | | 璇存槑 | 杩斿洖鎵€鏈塖kill鍒楄〃锛屾寜priority鍗囧簭锛屽垪琛ㄩ」涓嶅惈doc_markdown |
**响应参数** **鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 | | 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------| |----------|------|------|
| list | array | Skill列表 | | list | array | Skill鍒楄〃 |
| list[].skill_code | string | 技能编码 | | list[].skill_code | string | 鎶€鑳界紪鐮?|
| list[].skill_name | string | 技能名称 | | list[].skill_name | string | 鎶€鑳藉悕绉?|
| list[].description | string | 描述 | | list[].description | string | 鎻忚堪 |
--- ---
### 3.2 查询Skill详情 ### 3.2 鏌ヨSkill璇︽儏
**基本信息** **鍩烘湰淇℃伅**
| 字段 | 值 | | 瀛楁 | 鍊?|
|------|-----| |------|-----|
| 方法 | GET | | 鏂规硶 | GET |
| 路径 | `/api/v1/skills/{skill_code}` | | 璺緞 | `/api/v1/skills/{skill_code}` |
| 说明 | 返回Skill详情,包含doc_markdown;支持缓存 | | 璇存槑 | 杩斿洖Skill璇︽儏锛屽寘鍚玠oc_markdown锛涙敮鎸佺紦瀛?|
**请求参数** **璇锋眰鍙傛暟**
| 参数名 | 位置 | 类型 | 必填 | 说明 | | 鍙傛暟鍚?| 浣嶇疆 | 绫诲瀷 | 蹇呭~ | 璇存槑 |
|--------|------|------|------|------| |--------|------|------|------|------|
| skill_code | path | string | 是 | 技能编码 | | skill_code | path | string | 鏄?| 鎶€鑳界紪鐮?|
**响应参数** **鍝嶅簲鍙傛暟**
| 字段路径 | 类型 | 说明 | | 瀛楁璺緞 | 绫诲瀷 | 璇存槑 |
|----------|------|------| |----------|------|------|
| skill_code | string | 技能编码 | | skill_code | string | 鎶€鑳界紪鐮?|
| skill_name | string | 技能名称 | | skill_name | string | 鎶€鑳藉悕绉?|
| description | string | 描述 | | description | string | 鎻忚堪 |
| doc_markdown | string | Markdown格式文档 | | doc_markdown | string | Markdown鏍煎紡鏂囨。 |
**错误码** **閿欒鐮?*
| HTTP 状态码 | 触发条件 | | HTTP 鐘舵€佺爜 | 瑙﹀彂鏉′欢 |
|-------------|----------| |-------------|----------|
| 404 | Skill不存在 | | 404 | Skill涓嶅瓨鍦?|
--- ---
## 4. 测试场景 ## 4. 娴嬭瘯鍦烘櫙
### 4.1 Skill列表 ### 4.1 Skill鍒楄〃
| 序号 | 场景名称 | 分类 | 预期结果 | | 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------| |------|----------|------|----------|
| 1 | 返回所有Skill | 正常 | list长度=2 | | 1 | 杩斿洖鎵€鏈塖kill | 姝e父 | list闀垮害=2 |
| 2 | 列表项字段验证 | 正常 | 含skill_code/skill_name/description,不含doc_markdown | | 2 | 鍒楄〃椤瑰瓧娈甸獙璇?| 姝e父 | 鍚玸kill_code/skill_name/description锛屼笉鍚玠oc_markdown |
| 3 | 空列表 | 边界 | list=[] | | 3 | 绌哄垪琛?| 杈圭晫 | list=[] |
| 4 | 按priority排序 | 正常 | 高优先级在前 | | 4 | 鎸塸riority鎺掑簭 | 姝e父 | 楂樹紭鍏堢骇鍦ㄥ墠 |
### 4.2 Skill详情 ### 4.2 Skill璇︽儏
| 序号 | 场景名称 | 分类 | 预期结果 | | 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------| |------|----------|------|----------|
| 1 | 详情查询成功 | 正常 | 含doc_markdown | | 1 | 璇︽儏鏌ヨ鎴愬姛 | 姝e父 | 鍚玠oc_markdown |
| 2 | 不存在返回404 | 异常 | HTTP 404 | | 2 | 涓嶅瓨鍦ㄨ繑鍥?04 | 寮傚父 | HTTP 404 |
| 3 | doc_markdown内容完整 | 正常 | markdown内容原样返回 | | 3 | doc_markdown鍐呭瀹屾暣 | 姝e父 | markdown鍐呭鍘熸牱杩斿洖 |
### 4.3 缓存行为 ### 4.3 缂撳瓨琛屼负
| 序号 | 场景名称 | 分类 | 预期结果 | | 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
|------|----------|------|----------| |------|----------|------|----------|
| 1 | 缓存命中避免DB查询 | 正常 | 删除DB记录后仍返回缓存数据 | | 1 | 缂撳瓨鍛戒腑閬垮厤DB鏌ヨ | 姝e父 | 鍒犻櫎DB璁板綍鍚庝粛杩斿洖缂撳瓨鏁版嵁 |
| 2 | 缓存未命中查DB | 正常 | 返回DB最新数据 | | 2 | 缂撳瓨鏈懡涓煡DB | 姝e父 | 杩斿洖DB鏈€鏂版暟鎹?|
| 3 | 详情查询后缓存填充 | 正常 | 缓存中可读取到skill数据 | | 3 | 璇︽儏鏌ヨ鍚庣紦瀛樺~鍏?| 姝e父 | 缂撳瓨涓彲璇诲彇鍒皊kill鏁版嵁 |
### 4.4 服务层 ### 4.4 鏈嶅姟灞?
| 搴忓彿 | 鍦烘櫙鍚嶇О | 鍒嗙被 | 棰勬湡缁撴灉 |
| 序号 | 场景名称 | 分类 | 预期结果 |
|------|----------|------|----------| |------|----------|------|----------|
| 1 | Service层列表查询 | 正常 | 返回skill_code正确的列表 | | 1 | Service灞傚垪琛ㄦ煡璇?| 姝e父 | 杩斿洖skill_code姝g‘鐨勫垪琛?|
| 2 | Service层详情查询 | 正常 | 含doc_markdown | | 2 | Service灞傝鎯呮煡璇?| 姝e父 | 鍚玠oc_markdown |
| 3 | Service层不存在 | 异常 | ValueError "不存在" | | 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_returns_all_skills | 4.1-1 |
| TestListSkills | test_list_item_fields | 4.1-2 | | TestListSkills | test_list_item_fields | 4.1-2 |
...@@ -135,3 +134,56 @@ ...@@ -135,3 +134,56 @@
| TestServiceLayer | test_list_skills_service | 4.4-1 | | TestServiceLayer | test_list_skills_service | 4.4-1 |
| TestServiceLayer | test_get_detail_service | 4.4-2 | | TestServiceLayer | test_get_detail_service | 4.4-2 |
| TestServiceLayer | test_get_detail_service_not_found | 4.4-3 | | 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 | | 妯″潡鍚嶇О | tool-manager |
| 模块说明 | 工具管理器 — 注册/调用工具,支持分组、激活/停用、OpenAI兼容Schema | | 妯″潡璇存槑 | 宸ュ叿绠$悊鍣?鈥?娉ㄥ唽/璋冪敤宸ュ叿锛屾敮鎸佸垎缁勩€佹縺娲?鍋滅敤銆丱penAI鍏煎Schema |
| 路由前缀 | 无(非HTTP接口,Service组件) | | 璺敱鍓嶇紑 | 鏃狅紙闈濰TTP鎺ュ彛锛孲ervice缁勪欢锛?|
| 数据库表 | 无 | | 鏁版嵁搴撹〃 | 鏃?|
| 外部依赖 | 无 | | 澶栭儴渚濊禆 | 鏃?|
--- ---
## 2. 组件列表 ## 2. 缁勪欢鍒楄〃
| 序号 | 方法 | 说明 | | 搴忓彿 | 鏂规硶 | 璇存槑 |
|------|------|------| |------|------|------|
| 1 | `register_tool(func, name, group, description)` | 注册工具函数 | | 1 | `register_tool(func, name, group, description)` | 娉ㄥ唽宸ュ叿鍑芥暟 |
| 2 | `register(group)` | 装饰器方式注册 | | 2 | `register(group)` | 瑁呴グ鍣ㄦ柟寮忔敞鍐?|
| 3 | `call_tool({"name": ..., "input": ...})` | 调用工具 | | 3 | `call_tool({"name": ..., "input": ...})` | 璋冪敤宸ュ叿 |
| 4 | `get_tool_schemas()` | 获取激活工具的OpenAI兼容Schema | | 4 | `get_tool_schemas()` | 鑾峰彇婵€娲诲伐鍏风殑OpenAI鍏煎Schema |
| 5 | `reset_equipped_tools(**groups)` | 重置工具组激活状态 | | 5 | `reset_equipped_tools(**groups)` | 閲嶇疆宸ュ叿缁勬縺娲荤姸鎬?|
| 6 | `groups` | 工具组字典 | | 6 | `groups` | 宸ュ叿缁勫瓧鍏?|
--- ---
## 3. 组件详细说明 ## 3. 缁勪欢璇︾粏璇存槑
### 3.1 工具注册 ### 3.1 宸ュ叿娉ㄥ唽
**方式一:函数调用** **鏂瑰紡涓€锛氬嚱鏁拌皟鐢?*
```python ```python
tm.register_tool(get_weather, name="custom", group="admin", description="自定义描述") tm.register_tool(get_weather, name="custom", group="admin", description="鑷畾涔夋弿杩?)
``` ```
**方式二:装饰器** **鏂瑰紡浜岋細瑁呴グ鍣?*
```python ```python
@tm.register(group="vision") @tm.register(group="vision")
def analyze_image(image_url: str) -> str: def analyze_image(image_url: str) -> str:
"""分析图片内容""" """鍒嗘瀽鍥剧墖鍐呭"""
... ...
``` ```
**规则**: **瑙勫垯**锛?- `basic` 缁勯粯璁ゆ縺娲伙紝鍏朵粬缁勯粯璁ゆ湭婵€娲?- 鑷姩浠庡嚱鏁扮鍚嶇敓鎴?`input_schema`锛圤penAI function calling 鏍煎紡锛?- 鑷姩鎻愬彇 docstring 浣滀负 description
- `basic` 组默认激活,其他组默认未激活
- 自动从函数签名生成 `input_schema`(OpenAI function calling 格式)
- 自动提取 docstring 作为 description
### 3.2 工具调用 ### 3.2 宸ュ叿璋冪敤
**输入**:
**杈撳叆**锛?
```python ```python
{"name": "add", "input": {"a": 1, "b": 2}} {"name": "add", "input": {"a": 1, "b": 2}}
``` ```
**输出**: **杈撳嚭**锛?
- 鎴愬姛锛歚{"result": 3}`
- 成功:`{"result": 3}` - 鏈敞鍐岋細`{"error": "鏈敞鍐?.."}`
- 未注册:`{"error": "未注册..."}` - 缁勬湭婵€娲伙細`{"error": "鏈縺娲?.."}`
- 组未激活:`{"error": "未激活..."}` - 鎵ц寮傚父锛歚{"error": "...boom..."}`
- 执行异常:`{"error": "...boom..."}`
### 3.3 Schema生成 ### 3.3 Schema鐢熸垚
**格式**:OpenAI function calling 兼容 **鏍煎紡**锛歄penAI function calling 鍏煎
```json ```json
{ {
"type": "function", "type": "function",
"function": { "function": {
"name": "search", "name": "search",
"description": "搜索知识库", "description": "鎼滅储鐭ヨ瘑搴?,
"parameters": { "parameters": {
"type": "object", "type": "object",
"properties": {"query": {"type": "string"}, "limit": {"type": "integer"}}, "properties": {"query": {"type": "string"}, "limit": {"type": "integer"}},
...@@ -85,56 +80,55 @@ def analyze_image(image_url: str) -> str: ...@@ -85,56 +80,55 @@ def analyze_image(image_url: str) -> str:
} }
``` ```
**规则**:仅返回激活组(默认basic)的工具Schema **瑙勫垯**锛氫粎杩斿洖婵€娲荤粍锛堥粯璁asic锛夌殑宸ュ叿Schema
### 3.4 分组管理 ### 3.4 鍒嗙粍绠$悊
- `basic` 组默认存在且激活 - `basic` 缁勯粯璁ゅ瓨鍦ㄤ笖婵€娲?- `reset_equipped_tools(basic=False, vision=True)` 鍒囨崲婵€娲荤粍
- `reset_equipped_tools(basic=False, vision=True)` 切换激活组
--- ---
## 4. 测试场景 ## 4. 娴嬭瘯鍦烘櫙
### 4.1 工具注册 ### 4.1 宸ュ叿娉ㄥ唽
| 序号 | 场景名称 | 预期结果 | | 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------| |------|----------|----------|
| 1 | 函数注册 | 名称/description/group正确 | | 1 | 鍑芥暟娉ㄥ唽 | 鍚嶇О/description/group姝g‘ |
| 2 | 自定义name/group/description | 覆盖默认值 | | 2 | 鑷畾涔塶ame/group/description | 瑕嗙洊榛樿鍊?|
| 3 | 装饰器注册 | group="vision"未激活, input_schema含参数 | | 3 | 瑁呴グ鍣ㄦ敞鍐?| group="vision"鏈縺娲? input_schema鍚弬鏁?|
### 4.2 工具调用 ### 4.2 宸ュ叿璋冪敤
| 序号 | 场景名称 | 预期结果 | | 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------| |------|----------|----------|
| 1 | 调用成功 | {"result": 3} | | 1 | 璋冪敤鎴愬姛 | {"result": 3} |
| 2 | 工具未注册 | {"error": "未注册"} | | 2 | 宸ュ叿鏈敞鍐?| {"error": "鏈敞鍐?} |
| 3 | 组未激活 | {"error": "未激活"} | | 3 | 缁勬湭婵€娲?| {"error": "鏈縺娲?} |
| 4 | 执行异常 | {"error": 含"boom"} | | 4 | 鎵ц寮傚父 | {"error": 鍚?boom"} |
### 4.3 Schema生成 ### 4.3 Schema鐢熸垚
| 序号 | 场景名称 | 预期结果 | | 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------| |------|----------|----------|
| 1 | 仅返回激活组 | 1个schema(basic组) | | 1 | 浠呰繑鍥炴縺娲荤粍 | 1涓猻chema(basic缁? |
| 2 | 空管理器 | [] | | 2 | 绌虹鐞嗗櫒 | [] |
| 3 | OpenAI兼容格式 | type/function/parameters结构正确 | | 3 | OpenAI鍏煎鏍煎紡 | type/function/parameters缁撴瀯姝g‘ |
### 4.4 分组管理 ### 4.4 鍒嗙粍绠$悊
| 序号 | 场景名称 | 预期结果 | | 搴忓彿 | 鍦烘櫙鍚嶇О | 棰勬湡缁撴灉 |
|------|----------|----------| |------|----------|----------|
| 1 | 切换激活组 | reset后vision激活,basic停用 | | 1 | 鍒囨崲婵€娲荤粍 | reset鍚巚ision婵€娲?basic鍋滅敤 |
| 2 | 默认组 | 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_function | 4.1-1 |
| TestToolManagerRegister | test_register_with_custom_name_and_group | 4.1-2 | | TestToolManagerRegister | test_register_with_custom_name_and_group | 4.1-2 |
...@@ -148,3 +142,56 @@ def analyze_image(image_url: str) -> str: ...@@ -148,3 +142,56 @@ def analyze_image(image_url: str) -> str:
| TestToolManagerSchemas | test_schema_format_openai_compatible | 4.3-3 | | TestToolManagerSchemas | test_schema_format_openai_compatible | 4.3-3 |
| TestToolManagerGroups | test_reset_equipped_tools | 4.4-1 | | TestToolManagerGroups | test_reset_equipped_tools | 4.4-1 |
| TestToolManagerGroups | test_default_groups | 4.4-2 | | 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`。
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 ## Context
当前后端需要提供 Agent 的基础管理能力,包括创建、更新、删除、详情、列表与状态更新。实现基于 FastAPI + SQLAlchemy,创建接口需要由后端自动生成业务编码,详情接口需要聚合岗位、技能和会话统计。 当前后端已经提供 Agent 的基础管理能力,包括创建、更新、删除、详情、列表与状态更新。现在需要在 Agent 上增加“企业微信员工绑定”能力,用于表达某个 Agent 适用于哪些岗位下的具体员工,并且保持现有统一响应结构、分页结构与 Swagger 文档风格。
系统中暂时没有独立的员工主数据表,但已有 `qrcode_channels` 维护岗位与员工的映射关系,字段中包含岗位编码、岗位名称、企业微信员工标识和员工姓名,因此这张表最适合作为当前阶段的员工来源。
## Goals / Non-Goals ## Goals / Non-Goals
**Goals** **Goals**
- 提供完整的 Agent CRUD 与状态管理接口 - 创建和更新 Agent 时支持传入 `user_ids`
- 统一使用 `{code, message, data}` 响应结构 - `user_ids` 必须严格校验为所选岗位下的员工
- 列表接口遵循统一分页格式 - 列表接口返回轻量的 `user_ids`
- 创建接口自动生成唯一 `code` - 详情接口返回可展示的 `users`
- Agent 详情接口返回完整展示数据 - Swagger 和文档同步反映新增字段与约束
**Non-Goals** **Non-Goals**
- 当前阶段不实现 Agent 编辑并发锁定 - 当前阶段不引入独立员工主表
- 当前阶段不扩展列表接口为重详情结构 - 当前阶段不扩展 Agent 的消息发送或路由能力
- 当前阶段不让前端自定义 Agent 编码 - 当前阶段不改变前端交互流程,仅提供后端契约能力
## Decisions ## Decisions
### 1. 数据模型 ### 1. 数据模型
- `ai_agents` 存储 Agent 主体信息:`name`、`code`、`description`、`status`、`is_deleted`、`version` - `ai_agents` 保存 Agent 主体信息:`name`、`code`、`description`、`status`、`is_deleted`、`version`
- `ai_agent_positions` 存储 Agent 与岗位标签的关联 - `ai_agent_positions` 保存 Agent 与岗位标签的关联
- `ai_agent_skills` 存储 Agent 与技能的关联 - `ai_agent_skills` 保存 Agent 与技能的关联
- `ai_agent_users` 保存 Agent 与员工的关联:
- `agent_id`
- `user_id`
- `created_at`
- `user_id` 指向 `qrcode_channels.id`,不是企业微信原始字符串 ID
### 2. 自动编码策略 ### 2. 员工来源与校验策略
- 创建接口请求体不再接收 `code` - `qrcode_channels` 作为当前阶段的员工来源表:
- 后端在创建时生成 `agent_<8位随机十六进制串>` - `id`: 本地员工记录主键
- 写入前查询现有未删除 Agent,若冲突则重试 - `position_code`: 员工所属岗位编码
- `employee_id`: 企业微信员工标识
- `employee_name`: 员工展示名
- 请求中的 `user_ids` 使用 `qrcode_channels.id`
- 创建或更新 Agent 时执行以下校验:
- 每个 `user_id` 必须存在
- 每个 `user_id` 对应的 `position_code` 必须映射到本次 `position_ids` 对应岗位的 `code`
- 任一校验失败时返回 `400`
### 3. 删除策略 ### 3. 编码生成策略
- Agent 使用软删除 - 创建接口不再接收请求体中的 `code`
- 删除接口返回 `success` 和 `deleted_at` - 后端自动生成 `agent_<8位随机后缀>`
- 写入前检查未删除 Agent 中是否重复,冲突则重试
### 4. 列表与详情分离 ### 4. 列表与详情响应策略
- 列表接口保持轻量,仅返回基础信息、岗位 ID 列表和技能编码列表 - 列表接口保持轻量:
- 详情接口返回完整结构,用于详情页和 Swagger 调试 - 返回 `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. 详情聚合策略 ### 5. 删除策略
- `positions` 从 `position_tags` 表补齐 `{id, name}` - Agent 使用软删除
- `skills` 从 `skills` 表补齐 `{skill_code, skill_name}` - 删除接口返回:
- `session_count` 统计 `sessions.current_agent_id = agent_id` 的全部会话数 - `success`
- `status`、`description`、`created_at`、`updated_at` 直接来自 Agent 主表 - `deleted_at`
## Risks / Trade-offs ## Risks / Trade-offs
- **并发更新可能被后写覆盖** - **员工数据依赖二维码渠道表**
当前不做乐观锁拦截,后续如进入多人高频协作场景,再评估恢复版本校验或改为显式锁定机制。 当前没有独立员工主表,`qrcode_channels` 的数据完整性会直接影响 Agent 员工绑定能力。
- **详情接口查询更重** - **岗位编码映射是间接关系**
通过保持列表接口轻量化,把额外聚合成本收敛在单条详情接口上。 `position_ids` 需要先查 `position_tags.code`,再和 `qrcode_channels.position_code` 比较,查询路径稍长,但能避免重复维护员工归属。
- **自动编码不可读性一般** - **后续主数据迁移成本**
当前优先保证稳定唯一和实现简单,如后续需要更强业务语义,再评估引入前缀映射规则。 如果未来引入独立员工表,需要重新审视 `ai_agent_users.user_id` 的语义以及迁移策略。
## Why ## Why
允许管理员在后台管理 Agent 的生命周期,包括创建、编辑、删除、查询以及状态控制。这是 Agent 管理后台的核心功能,为后续的岗位关联和 Skill 配置提供基础支撑。 允许管理员在后台管理 Agent 的生命周期,包括创建、编辑、删除、查询以及状态控制。这是 Agent 管理后台的核心能力,为后续的岗位关联、Skill 配置以及企业微信员工绑定提供基础支撑。
## What Changes ## What Changes
- **新增 Agent 创建接口**: 支持配置名称、编码、岗位关联、Skill 关联及描述。 - **新增 Agent 创建接口**: 支持配置名称、岗位关联、Skill 关联、企业微信员工绑定及描述。
- **新增 Agent 编辑接口**: 支持修改名称、岗位、Skill 及状态(编码不可修改)。 - **新增 Agent 编辑接口**: 支持修改名称、岗位、Skill、员工及状态,编码仍不可修改。
- **新增 Agent 删除接口**: 实现软删除逻辑,并增加引用检查。 - **新增 Agent 删除接口**: 实现软删除逻辑,并返回删除结果。
- **新增 Agent 列表查询**: 支持分页、关键词搜索、按岗位和状态筛选。 - **新增 Agent 列表查询**: 支持分页、关键字搜索、按岗位和状态筛选,并返回轻量员工 ID 列表。
- **新增 Agent 详情查询**: 返回 Agent 的完整配置信息、关联岗位和 Skill。 - **新增 Agent 详情查询**: 返回 Agent 的完整配置信息、关联岗位、Skill、员工和会话统计。
- **新增 Agent 状态管理**: 支持一键启用或停用 Agent。 - **新增 Agent 状态管理**: 支持一键启用或停用 Agent。
## Capabilities ## Capabilities
### New Capabilities ### New Capabilities
- `agent-management`: 涵盖 Agent 的增删改查及状态管理全生命周期。 - `agent-management`: 覆盖 Agent 的增删改查、员工绑定及状态管理全生命周期。
### Modified Capabilities ### Modified Capabilities
<!-- 无 --> <!-- 无 -->
...@@ -22,5 +22,6 @@ ...@@ -22,5 +22,6 @@
## Impact ## Impact
- **API**: 新增 `/api/v1/agents` 及其相关子路径。 - **API**: 新增 `/api/v1/agents` 及其相关子路径。
- **数据库**: 需要设计 `agents` 表,以及 `agent_positions` 和 `agent_skills` 中间表。 - **数据库**: 需要在现有 `agents`、`agent_positions`、`agent_skills` 之外新增 `agent_users` 关联表。
- **关联系统**: 影响路由分发层(状态同步)及会话管理系统(删除校验)。 - **关联系统**: 员工来源依赖已有 `qrcode_channels` 岗位员工映射数据。
- **测试覆盖**: 需要补充员工绑定成功、员工不存在、员工不属于已选岗位等场景。
...@@ -4,9 +4,10 @@ ...@@ -4,9 +4,10 @@
系统 SHALL 提供创建 Agent 的接口,并由后端自动生成唯一编码。 系统 SHALL 提供创建 Agent 的接口,并由后端自动生成唯一编码。
#### Scenario: 创建成功 #### Scenario: 创建成功
- **WHEN** 请求提供合法的 `name`、`position_ids`、`skill_codes`、`description`、`status` - **WHEN** 请求提供合法的 `name`、`position_ids`、`skill_codes`、`user_ids`、`description`、`status`
- **THEN** 系统创建 Agent 并返回统一成功响应 - **THEN** 系统创建 Agent 并返回统一成功响应
- **AND** `data.code` 由后端自动生成 - **AND** `data.code` 由后端自动生成
- **AND** `data.user_ids` 返回已绑定员工 ID 列表
#### Scenario: 自动编码规则 #### Scenario: 自动编码规则
- **WHEN** 系统创建 Agent - **WHEN** 系统创建 Agent
...@@ -14,17 +15,35 @@ ...@@ -14,17 +15,35 @@
- **AND** 后缀为随机字符串 - **AND** 后缀为随机字符串
- **AND** 最终写入前必须校验与现有未删除 Agent 编码不重复 - **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 ### Requirement: 更新 Agent
系统 SHALL 提供更新 Agent 的接口,用于修改名称、描述、状态、岗位关联和技能关联。 系统 SHALL 提供更新 Agent 的接口,用于修改名称、描述、状态、岗位关联、技能关联和员工关联。
#### Scenario: 更新成功 #### Scenario: 更新成功
- **WHEN** 请求提供合法的 `name`、`position_ids`、`skill_codes`、`description`、`status` - **WHEN** 请求提供合法的 `name`、`position_ids`、`skill_codes`、`user_ids`、`description`、`status`
- **THEN** 系统更新目标 Agent,并返回统一成功响应 - **THEN** 系统更新目标 Agent,并返回统一成功响应
- **AND** `data.user_ids` 返回最新绑定员工 ID 列表
#### Scenario: 更新不存在的 Agent #### Scenario: 更新不存在的 Agent
- **WHEN** 请求中的 `agent_id` 不存在或已软删除 - **WHEN** 请求中的 `agent_id` 不存在或已软删除
- **THEN** 系统返回 404 错误响应 - **THEN** 系统返回 404 错误响应
#### Scenario: 更新时重建员工绑定
- **WHEN** 请求传入新的 `user_ids`
- **THEN** 系统替换 Agent 原有的员工绑定关系
### Requirement: 删除 Agent ### Requirement: 删除 Agent
系统 SHALL 提供软删除 Agent 的接口。 系统 SHALL 提供软删除 Agent 的接口。
...@@ -37,12 +56,16 @@ ...@@ -37,12 +56,16 @@
#### Scenario: 查询成功 #### Scenario: 查询成功
- **WHEN** 请求中的 `agent_id` 存在 - **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: 详情中的岗位和技能信息 #### Scenario: 详情中的岗位和技能信息
- **WHEN** Agent 已关联岗位和技能 - **WHEN** Agent 已关联岗位和技能
- **THEN** `positions` 返回 `{id, name}` 列表,`skills` 返回 `{skill_code, skill_name}` 列表 - **THEN** `positions` 返回 `{id, name}` 列表,`skills` 返回 `{skill_code, skill_name}` 列表
#### Scenario: 详情中的员工信息
- **WHEN** Agent 已关联员工
- **THEN** `users` 返回 `{user_id, user_name}` 列表
#### Scenario: 详情中的会话统计 #### Scenario: 详情中的会话统计
- **WHEN** Agent 已关联会话 - **WHEN** Agent 已关联会话
- **THEN** `session_count` 返回该 Agent 的全部会话总数 - **THEN** `session_count` 返回该 Agent 的全部会话总数
...@@ -58,6 +81,10 @@ ...@@ -58,6 +81,10 @@
- **WHEN** 请求提供 `keyword`、`position_id` 或 `status` - **WHEN** 请求提供 `keyword`、`position_id` 或 `status`
- **THEN** 系统按条件过滤返回结果 - **THEN** 系统按条件过滤返回结果
#### Scenario: 列表项返回员工 ID
- **WHEN** 系统返回 Agent 列表
- **THEN** 每个列表项包含 `user_ids`
### Requirement: 更新 Agent 状态 ### Requirement: 更新 Agent 状态
系统 SHALL 提供单独的 Agent 状态更新接口。 系统 SHALL 提供单独的 Agent 状态更新接口。
......
## 1. 数据库准备 ## 1. 数据库准备
- [x] 1.1 创建 `agents` 表迁移,包含 `is_deleted` 和 `version` 字段 - [ ] 1.1 新增 `agent_users` 关联表迁移
- [x] 1.2 创建 `agent_positions` 和 `agent_skills` 关联表迁移 - [ ] 1.2 为 `agent_users` 补充唯一约束与索引
- [ ] 1.3 补充索引与约束校验
## 2. 模型与 Schema ## 2. 模型与 Schema
- [x] 2.1 实现 SQLAlchemy ORM:`Agent`、`AgentPosition`、`AgentSkill` - [ ] 2.1 扩展 SQLAlchemy ORM:新增 `AgentUser`
- [x] 2.2 实现创建/更新请求 Schema - [ ] 2.2 扩展创建/更新请求 Schema,增加 `user_ids`
- [x] 2.3 实现列表/详情响应 Schema - [ ] 2.3 扩展列表响应 Schema,增加 `user_ids`
- [ ] 2.4 扩展详情响应 Schema,增加 `users`
- [ ] 2.5 更新 Swagger 字段描述与示例
## 3. 服务层 ## 3. 服务层
- [x] 3.1 实现 Agent 创建逻辑,创建时自动生成唯一 `code` - [ ] 3.1 实现员工存在性校验
- [x] 3.2 实现 Agent 编辑逻辑,支持全量替换岗位与技能关联 - [ ] 3.2 实现员工岗位归属校验
- [x] 3.3 实现 Agent 软删除逻辑 - [ ] 3.3 创建 Agent 时写入员工绑定关系
- [x] 3.4 实现 Agent 列表查询逻辑,支持分页和条件筛选 - [ ] 3.4 更新 Agent 时同步替换员工绑定关系
- [x] 3.5 实现 Agent 状态更新逻辑 - [ ] 3.5 列表接口返回 `user_ids`
- [x] 3.6 实现 Agent 详情聚合逻辑,返回岗位名称、技能名称和全部会话总数 - [ ] 3.6 详情接口聚合 `users`
## 4. API 层 ## 4. API 层
- [x] 4.1 挂载 `POST /api/v1/agents` 创建接口 - [ ] 4.1 调整 `POST /api/v1/agents` 请求体,增加 `user_ids`
- 请求参数:`name`、`description`、`position_ids`、`skill_codes`、`status` - [ ] 4.2 调整 `PUT /api/v1/agents/{agent_id}` 请求体,增加 `user_ids`
- 响应中的 `code` 由后端自动生成 - [ ] 4.3 调整创建/更新/列表响应体,返回 `user_ids`
- [x] 4.2 挂载 `PUT /api/v1/agents/{agent_id}` 更新接口 - [ ] 4.4 调整详情响应体,返回 `users`
- [x] 4.3 挂载 `DELETE /api/v1/agents/{agent_id}` 删除接口
- [x] 4.4 挂载 `GET /api/v1/agents` 列表接口 ## 5. 测试与文档
- [x] 4.5 挂载 `GET /api/v1/agents/{agent_id}` 详情接口
- 返回:`agent_id`、`name`、`code`、`description`、`positions`、`skills`、`status`、`session_count`、`created_at`、`updated_at` - [ ] 5.1 创建接口测试覆盖 `user_ids`
- [x] 4.6 挂载 `PUT /api/v1/agents/{agent_id}/status` 状态接口 - [ ] 5.2 更新接口测试覆盖 `user_ids`
- [ ] 5.3 列表接口测试覆盖 `user_ids`
## 5. 测试 - [ ] 5.4 详情接口测试覆盖 `users`
- [ ] 5.5 增加员工不存在校验测试
- [x] 5.1 创建接口测试 - [ ] 5.6 增加员工不属于已选岗位校验测试
- [x] 5.2 更新接口测试 - [ ] 5.7 更新 wangxz 接口测试文档
- [x] 5.3 删除接口测试
- [x] 5.4 列表接口测试
- [x] 5.5 详情接口测试
- [x] 5.6 状态接口测试
...@@ -4,7 +4,10 @@ import pytest ...@@ -4,7 +4,10 @@ import pytest
from fastapi import HTTPException from fastapi import HTTPException
from app.main import app from app.main import app
from app.model.agent import Agent, AgentStatus
from app.model.agent_group import QrcodeChannel 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 from tests.conftest import TestingSessionLocal
...@@ -23,6 +26,9 @@ class FakeWeComClient: ...@@ -23,6 +26,9 @@ class FakeWeComClient:
def clean_db(): def clean_db():
db = TestingSessionLocal() db = TestingSessionLocal()
db.query(QrcodeChannel).delete() db.query(QrcodeChannel).delete()
db.query(Agent).delete()
db.query(WeComBot).delete()
db.query(PositionTag).delete()
db.commit() db.commit()
db.close() db.close()
...@@ -30,12 +36,23 @@ def clean_db(): ...@@ -30,12 +36,23 @@ def clean_db():
class TestPositionEmployees: class TestPositionEmployees:
def test_position_employees_route_is_registered(self): def test_position_employees_route_is_registered(self):
paths = {route.path for route in app.routes} paths = {route.path for route in app.routes}
assert "/api/v1/agent-group/position/{position_code}/employees" in paths 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 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( result = get_position_employees(
"store_sales", "store_sales",
TestingSessionLocal(), TestingSessionLocal(),
...@@ -48,15 +65,13 @@ class TestPositionEmployees: ...@@ -48,15 +65,13 @@ class TestPositionEmployees:
"employee_id": "emp_12345", "employee_id": "emp_12345",
"employee_name": "张三", "employee_name": "张三",
"wechat_user_id": "zhangsan", "wechat_user_id": "zhangsan",
"department": "销售部",
"status": "在职", "status": "在职",
}, },
{ {
"employee_id": "emp_67890", "employee_id": "emp_67890",
"employee_name": "李四", "employee_name": "李四",
"wechat_user_id": "lisi", "wechat_user_id": "lisi",
"department": "销售部", "status": "在职",
"status": "离职",
}, },
], ],
} }
...@@ -66,15 +81,20 @@ class TestPositionEmployees: ...@@ -66,15 +81,20 @@ class TestPositionEmployees:
data = result.model_dump() data = result.model_dump()
assert data["position_name"] == "驻店销售岗" assert data["position_name"] == "驻店销售岗"
assert data["employee_count"] == 1 assert data["employee_count"] == 2
assert data["employees"] == [ assert data["employees"] == [
{ {
"employee_id": "emp_12345", "employee_id": "emp_12345",
"employee_name": "张三", "employee_name": "张三",
"wechat_user_id": "zhangsan", "wechat_user_id": "zhangsan",
"department": "销售部", "status": "已挂载Agent",
"status": "在职", },
} {
"employee_id": "emp_67890",
"employee_name": "李四",
"wechat_user_id": "lisi",
"status": "未挂载Agent",
},
] ]
def test_unknown_position_returns_404(self): def test_unknown_position_returns_404(self):
...@@ -82,26 +102,24 @@ class TestPositionEmployees: ...@@ -82,26 +102,24 @@ class TestPositionEmployees:
with pytest.raises(HTTPException) as exc_info: with pytest.raises(HTTPException) as exc_info:
get_position_employees("missing", TestingSessionLocal(), FakeWeComClient()) get_position_employees("missing", TestingSessionLocal(), FakeWeComClient())
assert exc_info.value.status_code == 404 assert exc_info.value.status_code == 404
def test_wecom_failure_returns_503(self): def test_wecom_failure_returns_503(self):
from app.api.v1.endpoints.agent_group_helper import get_position_employees from app.api.v1.endpoints.agent_group_helper import get_position_employees
with pytest.raises(HTTPException) as exc_info: db = TestingSessionLocal()
get_position_employees( db.add(PositionTag(id=1, name="驻店销售岗", code="store_sales"))
"store_sales", db.commit()
TestingSessionLocal(), db.close()
FakeWeComClient(failures={"store_sales"}),
)
with pytest.raises(HTTPException) as exc_info:
get_position_employees("store_sales", TestingSessionLocal(), FakeWeComClient(failures={"store_sales"}))
assert exc_info.value.status_code == 503 assert exc_info.value.status_code == 503
class TestEmployeeQrcodes: class TestEmployeeQrcodes:
def test_employee_qrcodes_route_is_registered(self): def test_employee_qrcodes_route_is_registered(self):
paths = {route.path for route in app.routes} paths = {route.path for route in app.routes}
assert "/api/v1/agent-group/employee/{employee_id}/qrcodes" in paths assert "/api/v1/agent-group/employee/{employee_id}/qrcodes" in paths
def test_returns_employee_qrcodes(self): def test_returns_employee_qrcodes(self):
...@@ -111,50 +129,20 @@ class TestEmployeeQrcodes: ...@@ -111,50 +129,20 @@ class TestEmployeeQrcodes:
db.add( db.add(
QrcodeChannel( QrcodeChannel(
id=1, id=1,
position_id=1,
wecom_bot_id=1,
employee_id="emp_12345", employee_id="emp_12345",
employee_name="张三", employee_name="张三",
position_name="驻店销售岗", position_name="驻店销售岗",
channel_code="zdxs_store_sales_emp_12345", channel_code="store_sales",
status="enable", status="enable",
created_at=datetime(2026, 5, 15, 10, 0, tzinfo=timezone.utc), 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.commit()
db.close() db.close()
result = get_employee_qrcodes("emp_12345", TestingSessionLocal()) result = get_employee_qrcodes("emp_12345", TestingSessionLocal())
data = result.model_dump(mode="json") data = result.model_dump(mode="json")
assert data["employee_name"] == "张三" assert data["employee_name"] == "张三"
assert data["qrcode_count"] == 1 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": [],
}
...@@ -360,7 +360,6 @@ ...@@ -360,7 +360,6 @@
```json ```json
{ {
"name": "驻店销售岗", "name": "驻店销售岗",
"code": "store_sales",
"description": "负责门店销售的岗位" "description": "负责门店销售的岗位"
} }
``` ```
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!