Commit 934e39b0 by imwangxiaozhou

feat(agent-admin): 搭建核心业务模块并完成基础功能开发

本次提交完成agent管理后台核心业务模块开发:
- 新增技能目录、官网门户、会话路由、文件服务等全链路业务代码与API接口
- 补充数据库迁移脚本、ORM模型与Pydantic数据结构
- 优化测试代码,提取通用测试配置复用逻辑
- 更新.gitignore忽略本地依赖目录,新增本地依赖加载配置
- 完善后端工程目录文档与OpenSpec任务标记
1 parent e4c613d3
Showing 97 changed files with 4307 additions and 323 deletions
...@@ -54,6 +54,28 @@ ...@@ -54,6 +54,28 @@
- 当前阶段不制定后端框架、数据库、队列、ORM 和运行时实现规则。 - 当前阶段不制定后端框架、数据库、队列、ORM 和运行时实现规则。
- 如前端需要联调契约,先以页面字段、交互状态、错误展示和 mock 数据结构表达,不锁定服务端实现。 - 如前端需要联调契约,先以页面字段、交互状态、错误展示和 mock 数据结构表达,不锁定服务端实现。
## 现有后端结构(单独罗列)
当前仓库已存在一个后端工程骨架,位于:
- `workspace/agent-admin/backend/`:Agent 管理平台后端(API + 业务能力 + 数据迁移 + 测试)。
目录结构(仅列出当前已存在的一级目录/文件,用于快速定位):
- `workspace/agent-admin/backend/app/`:应用代码(API/Service/Infrastructure/Config/Model/Schema 等分层以该工程内 `AGENTS.md` 为准)。
- `workspace/agent-admin/backend/migrations/`:数据库变更脚本(SQL 迁移)。
- `workspace/agent-admin/backend/tests/`:单元测试/接口测试。
- `workspace/agent-admin/backend/openspec/`:后端相关 OpenSpec(接口、业务规则、数据行为等)。
- `workspace/agent-admin/backend/docs/`:后端工程文档(与项目级 `docs/` 区分)。
- `workspace/agent-admin/backend/README.md`:该后端工程说明。
- `workspace/agent-admin/backend/AGENTS.md`:该后端工程的更细粒度规则(在该目录树下工作时优先遵循)。
- `workspace/agent-admin/backend/sitecustomize.py`:后端工程运行时环境/路径等辅助配置(以文件内说明为准)。
### 后端目录说明(约定边界)
- 该仓库的“后端”以 `workspace/<project>/backend/` 为项目级归属单位;不同业务项目各自管理自己的 OpenSpec、模块与工程配置。
- 项目级规则(本文档)只描述“在哪里/边界是什么”;具体后端技术栈、分层、代码规范等,以对应后端工程目录下的 `AGENTS.md` 为准(例如 `workspace/agent-admin/backend/AGENTS.md`)。
## 验证规则 ## 验证规则
- 没有新鲜的验证结果,不声明工作完成。 - 没有新鲜的验证结果,不声明工作完成。
......
...@@ -22,6 +22,7 @@ yarn-error.log* ...@@ -22,6 +22,7 @@ yarn-error.log*
__pycache__/ __pycache__/
*.pyc *.pyc
*.pyo *.pyo
.deps/
# OS / editor # OS / editor
.DS_Store .DS_Store
......
...@@ -14,13 +14,29 @@ ...@@ -14,13 +14,29 @@
- 全局前端和组件规范遵循 `architecture-spec/docs/architecture/`。 - 全局前端和组件规范遵循 `architecture-spec/docs/architecture/`。
- 公司 Web 桌面端设计规范为 `/Users/yuehu/Documents/广联web桌面端设计规范`。 - 公司 Web 桌面端设计规范为 `/Users/yuehu/Documents/广联web桌面端设计规范`。
## 前后端项目管理 ## 前后端项目管理(分离)
- `web/` 管理前端项目。 ### 前端项目管理
- `single-page/` 管理单页面项目。
- `backend/` 管理后端项目,当前只保留占位,不锁定技术栈。 - `web/`:管理 Web 前端项目(含 `openspec/`、`packages/`、工程配置与源码)。
- `web/openspec/`、`web/packages/` 管理前端自己的规范、组件和工程配置。 - `single-page/`:管理单页面项目(含 `openspec/`、`packages/` 与相关工程配置)。
- `single-page/openspec/`、`single-page/packages/` 管理单页面项目自己的规范、组件和工程配置。 - 前端各自维护:
- `backend/openspec/`、`backend/packages/` 管理后端自己的规范、契约和工程配置。 - `web/openspec/`、`web/packages/`
- 前后端契约先分别沉淀在 `web/packages/contracts/` 和 `backend/packages/contracts/`,确认一致后再开发。 - `single-page/openspec/`、`single-page/packages/`
### 后端项目管理
- `backend/`:管理 Agent Admin 后端项目(非占位目录)。
- 后端当前已存在的核心内容:
- `backend/app/`:应用代码(分层与规范以 `backend/AGENTS.md` 为准)。
- `backend/migrations/`:数据库变更脚本(SQL 迁移)。
- `backend/tests/`:单元测试/接口测试。
- `backend/openspec/`:后端相关 OpenSpec(接口、业务规则、数据行为等)。
- `backend/docs/`:后端工程文档。
- 说明:当前 `backend/` 下不存在 `packages/` 目录;因此不要在后端侧约定 `backend/packages/*` 作为“已存在的管理入口”。如后续确有需要(如 contracts、utils 等),在技术栈与工程方案确认后再引入。
### 跨端契约(联调边界)
- 现阶段跨端契约以前端侧为主沉淀在 `web/packages/contracts/` 与 `single-page/packages/contracts/`。
- 后端侧契约与实现约束以 `backend/openspec/` 为主,并遵循 `backend/AGENTS.md` 的更细规则;待契约稳定后再讨论是否引入 `backend/packages/contracts/` 一类结构。
- 如需要表达联调边界,先写清楚页面字段、表单校验、列表筛选、错误展示和 loading/empty 状态,再进入后端实现讨论。 - 如需要表达联调边界,先写清楚页面字段、表单校验、列表筛选、错误展示和 loading/empty 状态,再进入后端实现讨论。
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from typing import Optional
from datetime import datetime
from app.schema.analytics import (
ConversationLogListResponse,
ConversationLogItem,
AnalyticsEventRequest,
AnalyticsEventResponse,
AnalyticsStatisticsResponse,
PageViewRequest,
PageViewResponse,
ScanEventRequest,
ScanEventResponse,
GroupJoinEventRequest,
GroupJoinEventResponse,
)
from app.service.analytics_service import AnalyticsService
from app.infrastructure.database import get_db
router = APIRouter()
@router.get("/api/v1/logs/conversations", response_model=ConversationLogListResponse)
def list_conversation_logs(
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
user_id: Optional[str] = Query(None),
agent_id: Optional[int] = Query(None),
intent_type: Optional[str] = Query(None),
time_start: Optional[datetime] = Query(None),
time_end: Optional[datetime] = Query(None),
has_error: Optional[bool] = Query(None),
db: Session = Depends(get_db),
):
svc = AnalyticsService(db)
total, items = svc.list_conversation_logs(
page=page, page_size=page_size,
user_id=user_id, agent_id=agent_id,
intent_type=intent_type,
time_start=time_start, time_end=time_end,
has_error=has_error,
)
return ConversationLogListResponse(
total=total,
list=[ConversationLogItem.model_validate(item) for item in items],
)
@router.post("/api/v1/analytics/events", response_model=AnalyticsEventResponse)
def upload_analytics_events(req: AnalyticsEventRequest, db: Session = Depends(get_db)):
svc = AnalyticsService(db)
events_data = [ev.model_dump() for ev in req.events]
return svc.upload_events(events_data)
@router.get("/api/v1/analytics/statistics", response_model=AnalyticsStatisticsResponse)
def get_analytics_statistics(
date_range: str = Query("last_7_days"),
group_by: Optional[str] = Query(None),
db: Session = Depends(get_db),
):
svc = AnalyticsService(db)
return svc.get_statistics(date_range=date_range, group_by=group_by)
@router.post("/api/v1/agent-group/analytics/page-view", response_model=PageViewResponse)
def record_page_view(req: PageViewRequest, db: Session = Depends(get_db)):
svc = AnalyticsService(db)
return svc.record_page_view(
page_type=req.page_type,
user_id=req.user_id,
session_id=req.session_id,
device_type=req.device_type,
)
@router.post("/api/v1/agent-group/analytics/scan-event", response_model=ScanEventResponse)
def record_scan_event(req: ScanEventRequest, db: Session = Depends(get_db)):
svc = AnalyticsService(db)
return svc.record_scan_event(
qrcode_id=req.qrcode_id,
channel_code=req.channel_code,
customer_user_id=req.customer_user_id,
position_code=req.position_code,
employee_id=req.employee_id,
)
@router.post("/api/v1/agent-group/analytics/group-join-success", response_model=GroupJoinEventResponse)
def record_group_join_event(req: GroupJoinEventRequest, db: Session = Depends(get_db)):
svc = AnalyticsService(db)
return svc.record_group_join_event(
group_id=req.group_id,
customer_user_id=req.customer_user_id,
employee_count=req.employee_count,
agent_count=req.agent_count,
channel_code=req.channel_code,
)
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from sqlalchemy.orm import Session
from typing import Optional
from datetime import datetime
from app.infrastructure.database import get_db
from app.infrastructure.group_infra import (
InMemoryDistributedLock,
InMemoryIdempotencyStore,
InMemoryWeComGroupClient,
DistributedLock,
IdempotencyStore,
WeComGroupClient,
)
from app.schema.customer_group import (
AgentJoinRequest,
AgentJoinResponse,
CreateGroupRequest,
CreateGroupResponse,
GroupListResponse,
)
from app.service.customer_group_service import CustomerGroupService
router = APIRouter(prefix="/api/v1/agent-group")
_lock: DistributedLock = InMemoryDistributedLock()
_idempotency: IdempotencyStore = InMemoryIdempotencyStore()
_wecom_group: WeComGroupClient = InMemoryWeComGroupClient()
def get_lock() -> DistributedLock:
return _lock
def get_idempotency() -> IdempotencyStore:
return _idempotency
def get_wecom_group() -> WeComGroupClient:
return _wecom_group
@router.post("/callback/scan")
async def scan_callback(request: Request, db: Session = Depends(get_db)):
body = await request.body()
svc = CustomerGroupService(db, _wecom_group, _lock, _idempotency)
result = svc.handle_scan_callback(
event_id="evt_scan",
customer_user_id="placeholder",
channel_code="placeholder",
)
return Response(content=f"<Success>{result}</Success>", media_type="application/xml")
@router.post("/group/create", response_model=CreateGroupResponse)
def create_group(req: CreateGroupRequest, db: Session = Depends(get_db)):
svc = CustomerGroupService(db, _wecom_group, _lock, _idempotency)
return svc.create_group(req)
@router.post("/group/{group_id}/agent-join", response_model=AgentJoinResponse)
def agent_join(group_id: str, req: AgentJoinRequest, db: Session = Depends(get_db)):
svc = CustomerGroupService(db, _wecom_group, _lock, _idempotency)
try:
return svc.agent_join(group_id, req)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.post("/callback/member-exit")
async def member_exit_callback(request: Request, db: Session = Depends(get_db)):
body = await request.body()
svc = CustomerGroupService(db, _wecom_group, _lock, _idempotency)
result = svc.handle_member_exit_callback(
event_id="evt_exit",
group_id="placeholder",
user_id="placeholder",
is_customer=True,
)
return Response(content=f"<Success>{result}</Success>", media_type="application/xml")
@router.get("/group/list", response_model=GroupListResponse)
def list_groups(
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
customer_user_id: Optional[str] = Query(None),
employee_id: Optional[str] = Query(None),
position_code: Optional[str] = Query(None),
status: Optional[str] = Query(None),
created_time_start: Optional[datetime] = Query(None),
created_time_end: Optional[datetime] = Query(None),
db: Session = Depends(get_db),
):
svc = CustomerGroupService(db, _wecom_group, _lock, _idempotency)
return svc.list_groups(
page=page, page_size=page_size,
customer_user_id=customer_user_id,
employee_id=employee_id,
position_code=position_code,
status=status,
created_time_start=created_time_start,
created_time_end=created_time_end,
)
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.infrastructure.database import get_db
from app.infrastructure.shared_cache import shared_h5_cache
from app.schema.methodology import (
GetMethodologyResponse,
SaveMethodologyRequest,
SaveMethodologyResponse,
)
from app.service.methodology_service import MethodologyService
router = APIRouter()
@router.get("/api/v1/official-site/methodology", response_model=GetMethodologyResponse)
def get_methodology(db: Session = Depends(get_db)):
svc = MethodologyService(db, shared_h5_cache)
return svc.get_methodology()
@router.post("/api/v1/official-site/methodology", response_model=SaveMethodologyResponse)
def save_methodology(req: SaveMethodologyRequest, db: Session = Depends(get_db)):
svc = MethodologyService(db, shared_h5_cache)
try:
return svc.save_methodology(req)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
\ No newline at end of file \ No newline at end of file
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.infrastructure.database import get_db
from app.infrastructure.shared_cache import shared_h5_cache
from app.schema.official_site_agent_display import (
AvailableAgentsResponse,
ConfiguredAgentsResponse,
DeleteAgentConfigResponse,
SaveAgentConfigRequest,
SaveAgentConfigResponse,
)
from app.service.official_site_agent_display_service import OfficialSiteAgentDisplayService
router = APIRouter()
@router.get("/api/v1/official-site/tabs/{tab_id}/agents/available", response_model=AvailableAgentsResponse)
def list_available_agents(tab_id: int, db: Session = Depends(get_db)):
svc = OfficialSiteAgentDisplayService(db, shared_h5_cache)
try:
return svc.list_available_agents(tab_id)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.post("/api/v1/official-site/tabs/{tab_id}/agents/{agent_id}/config", response_model=SaveAgentConfigResponse)
def save_agent_config(tab_id: int, agent_id: int, req: SaveAgentConfigRequest, db: Session = Depends(get_db)):
svc = OfficialSiteAgentDisplayService(db, shared_h5_cache)
try:
return svc.save_config(tab_id, agent_id, req)
except ValueError as e:
msg = str(e)
if "不存在" in msg:
raise HTTPException(status_code=404, detail=msg)
raise HTTPException(status_code=400, detail=msg)
@router.get("/api/v1/official-site/tabs/{tab_id}/agents/configured", response_model=ConfiguredAgentsResponse)
def list_configured_agents(tab_id: int, db: Session = Depends(get_db)):
svc = OfficialSiteAgentDisplayService(db, shared_h5_cache)
try:
return svc.list_configured_agents(tab_id)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.delete("/api/v1/official-site/tabs/{tab_id}/agents/{agent_id}/config", response_model=DeleteAgentConfigResponse)
def delete_agent_config(tab_id: int, agent_id: int, db: Session = Depends(get_db)):
svc = OfficialSiteAgentDisplayService(db, shared_h5_cache)
try:
return svc.delete_config(tab_id, agent_id)
except ValueError as e:
msg = str(e)
if "不存在" in msg:
raise HTTPException(status_code=404, detail=msg)
raise HTTPException(status_code=400, detail=msg)
\ No newline at end of file \ No newline at end of file
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.infrastructure.database import get_db
from app.infrastructure.shared_cache import shared_h5_cache
from app.schema.official_site_home import H5HomeResponse
from app.service.official_site_home_service import H5HomeService
router = APIRouter()
@router.get("/api/v1/official-site/home", response_model=H5HomeResponse)
def get_home_data(db: Session = Depends(get_db)):
svc = H5HomeService(db, shared_h5_cache)
return svc.get_home_data()
\ No newline at end of file \ No newline at end of file
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Optional
from app.infrastructure.database import get_db
from app.infrastructure.shared_cache import shared_h5_cache
from app.schema.official_site_tab import (
AvailableQrcodeListResponse,
CreateTabRequest,
CreateTabResponse,
DeleteTabResponse,
TabListResponse,
UpdateTabRequest,
UpdateTabResponse,
UpdateTabStatusRequest,
UpdateTabStatusResponse,
)
from app.service.official_site_tab_service import OfficialSiteTabService
router = APIRouter(prefix="/api/v1/official-site/tabs")
@router.get("", response_model=TabListResponse)
def list_tabs(
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
keyword: Optional[str] = Query(None),
display_status: Optional[str] = Query(None),
db: Session = Depends(get_db),
):
svc = OfficialSiteTabService(db, shared_h5_cache)
return svc.list_tabs(page=page, page_size=page_size, keyword=keyword, display_status=display_status)
@router.post("", response_model=CreateTabResponse, status_code=201)
def create_tab(req: CreateTabRequest, db: Session = Depends(get_db)):
svc = OfficialSiteTabService(db, shared_h5_cache)
try:
return svc.create(req)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
@router.put("/{tab_id}", response_model=UpdateTabResponse)
def update_tab(tab_id: int, req: UpdateTabRequest, db: Session = Depends(get_db)):
svc = OfficialSiteTabService(db, shared_h5_cache)
try:
return svc.update(tab_id, req)
except ValueError as e:
msg = str(e)
if "不存在" in msg:
raise HTTPException(status_code=404, detail=msg)
raise HTTPException(status_code=400, detail=msg)
@router.delete("/{tab_id}", response_model=DeleteTabResponse)
def delete_tab(tab_id: int, db: Session = Depends(get_db)):
svc = OfficialSiteTabService(db, shared_h5_cache)
try:
return svc.delete(tab_id)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.put("/{tab_id}/status", response_model=UpdateTabStatusResponse)
def update_tab_status(tab_id: int, req: UpdateTabStatusRequest, db: Session = Depends(get_db)):
svc = OfficialSiteTabService(db, shared_h5_cache)
try:
return svc.update_status(tab_id, req)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.get("/qrcodes/available", response_model=AvailableQrcodeListResponse)
def list_available_qrcodes(
position_code: Optional[str] = Query(None),
db: Session = Depends(get_db),
):
svc = OfficialSiteTabService(db, shared_h5_cache)
return svc.list_available_qrcodes(position_code=position_code)
\ No newline at end of file \ No newline at end of file
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form
from app.infrastructure.file_parser import InMemoryOSSClient, OSSClient
from app.schema.official_site_upload import UploadMediaResponse
from app.service.official_site_upload_service import OfficialSiteUploadService
router = APIRouter()
_oss: OSSClient = InMemoryOSSClient()
def get_oss() -> OSSClient:
return _oss
@router.post("/api/v1/official-site/upload", response_model=UploadMediaResponse)
async def upload_media(
usage_type: str = Form(...),
file: UploadFile = File(...),
oss: OSSClient = Depends(get_oss),
):
file_data = await file.read()
svc = OfficialSiteUploadService(oss)
try:
return svc.upload(file_data, file.filename or "unknown", usage_type)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
\ No newline at end of file \ No newline at end of file
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Optional
from app.infrastructure.database import get_db
from app.infrastructure.file_parser import InMemoryOSSClient, OSSClient
from app.schema.qrcode_channel import (
QrcodeBatchStatusRequest,
QrcodeBatchStatusResponse,
QrcodeCreateRequest,
QrcodeCreateResponse,
QrcodeDetailResponse,
QrcodeDisableRequest,
QrcodeDisableResponse,
QrcodeEnableResponse,
QrcodeExportRequest,
QrcodeExportResponse,
QrcodeListResponse,
QrcodeUpdateRequest,
QrcodeUpdateResponse,
)
from app.service.agent_group_helper_service import InMemoryWeComClient, WeComClient
from app.service.qrcode_channel_service import QrcodeChannelService
router = APIRouter(prefix="/api/v1/agent-group/qrcode")
_wecom: WeComClient = InMemoryWeComClient()
_oss: OSSClient = InMemoryOSSClient()
def get_wecom() -> WeComClient:
return _wecom
def get_oss() -> OSSClient:
return _oss
@router.post("/create", response_model=QrcodeCreateResponse)
def create_qrcode(req: QrcodeCreateRequest, db: Session = Depends(get_db), wecom: WeComClient = Depends(get_wecom)):
svc = QrcodeChannelService(db, wecom)
try:
return svc.create(req)
except ValueError as e:
msg = str(e)
if "岗位不存在" in msg:
raise HTTPException(status_code=400, detail=msg)
if "已存在同岗位活码" in msg:
raise HTTPException(status_code=409, detail=msg)
raise HTTPException(status_code=400, detail=msg)
@router.put("/{qrcode_id}", response_model=QrcodeUpdateResponse)
def update_qrcode(qrcode_id: int, req: QrcodeUpdateRequest, db: Session = Depends(get_db)):
svc = QrcodeChannelService(db, _wecom)
try:
return svc.update(qrcode_id, req)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.get("/list", response_model=QrcodeListResponse)
def list_qrcodes(
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
employee_name: Optional[str] = Query(None),
position_code: Optional[str] = Query(None),
status: Optional[str] = Query(None),
keyword: Optional[str] = Query(None),
db: Session = Depends(get_db),
):
svc = QrcodeChannelService(db, _wecom)
return svc.list_qrcodes(
page=page, page_size=page_size,
employee_name=employee_name, position_code=position_code,
status=status, keyword=keyword,
)
@router.get("/{qrcode_id}", response_model=QrcodeDetailResponse)
def get_qrcode_detail(qrcode_id: int, db: Session = Depends(get_db)):
svc = QrcodeChannelService(db, _wecom)
try:
return svc.get_detail(qrcode_id)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.post("/export", response_model=QrcodeExportResponse)
def export_qrcodes(req: QrcodeExportRequest, db: Session = Depends(get_db), oss: OSSClient = Depends(get_oss)):
svc = QrcodeChannelService(db, _wecom, oss)
return svc.export(req)
@router.put("/{qrcode_id}/disable", response_model=QrcodeDisableResponse)
def disable_qrcode(qrcode_id: int, req: QrcodeDisableRequest, db: Session = Depends(get_db)):
svc = QrcodeChannelService(db, _wecom)
try:
return svc.disable(qrcode_id, req.reason)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.put("/{qrcode_id}/enable", response_model=QrcodeEnableResponse)
def enable_qrcode(qrcode_id: int, db: Session = Depends(get_db)):
svc = QrcodeChannelService(db, _wecom)
try:
return svc.enable(qrcode_id)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.post("/batch-status", response_model=QrcodeBatchStatusResponse)
def batch_status(req: QrcodeBatchStatusRequest, db: Session = Depends(get_db)):
svc = QrcodeChannelService(db, _wecom)
return svc.batch_status(req.qrcode_ids, req.target_status, req.reason)
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form
from sqlalchemy.orm import Session
from app.schema.routing import ChatCompletionRequest, ChatCompletionResponse, FileUploadResponse
from app.service.routing_service import RoutingService
from app.service.file_service import FileService
from app.infrastructure.database import get_db
from app.infrastructure.session_store import SessionStore
from app.infrastructure.llm_client import InMemoryLLMClient, LLMClient
from app.infrastructure.file_parser import InMemoryFileParser, InMemoryOSSClient, FileParser, OSSClient
router = APIRouter(prefix="/api/v1")
_llm: LLMClient = InMemoryLLMClient()
_oss: OSSClient = InMemoryOSSClient()
_parser: FileParser = InMemoryFileParser()
def get_llm() -> LLMClient:
return _llm
def get_oss() -> OSSClient:
return _oss
def get_parser() -> FileParser:
return _parser
@router.post("/chat/completions", response_model=ChatCompletionResponse)
def chat_completions(req: ChatCompletionRequest, db: Session = Depends(get_db)):
session_store = SessionStore()
llm = get_llm()
svc = RoutingService(db, session_store, llm)
try:
return svc.route(
session_id=req.session_id,
user_id=req.user_id,
channel=req.channel,
query=req.query,
mentioned_agent_code=req.mentioned_agent_code,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
@router.post("/files/upload", response_model=FileUploadResponse)
async def upload_file(
session_id: str = Form(...),
file: UploadFile = File(...),
oss: OSSClient = Depends(get_oss),
parser: FileParser = Depends(get_parser),
):
file_data = await file.read()
svc = FileService(oss, parser)
try:
return svc.upload_and_extract(
file_data=file_data,
file_name=file.filename or "unknown",
content_type=file.content_type or "application/octet-stream",
session_id=session_id,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.infrastructure.database import get_db
from app.schema.session import (
SessionArchiveResponse,
SessionContextResponse,
SessionCreateRequest,
SessionCreateResponse,
SessionDetailResponse,
SessionUpdateRequest,
SessionUpdateResponse,
)
from app.service.session_service import SessionService
router = APIRouter(prefix="/api/v1/sessions")
@router.post("", response_model=SessionCreateResponse, status_code=201)
def create_session(req: SessionCreateRequest, db: Session = Depends(get_db)):
svc = SessionService(db)
return svc.create(req)
@router.put("/{session_id}", response_model=SessionUpdateResponse)
def update_session(session_id: str, req: SessionUpdateRequest, db: Session = Depends(get_db)):
svc = SessionService(db)
try:
return svc.append_and_merge(session_id, req)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.get("/{session_id}", response_model=SessionDetailResponse)
def get_session_detail(session_id: str, db: Session = Depends(get_db)):
svc = SessionService(db)
try:
return svc.get_detail(session_id)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.get("/{session_id}/context", response_model=SessionContextResponse)
def get_session_context(session_id: str, db: Session = Depends(get_db)):
svc = SessionService(db)
return svc.get_context(session_id)
@router.post("/{session_id}/archive", response_model=SessionArchiveResponse)
def archive_session(session_id: str, db: Session = Depends(get_db)):
svc = SessionService(db)
try:
return svc.archive(session_id)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.schema.skill import SkillListResponse, SkillDetailResponse
from app.service.skill_service import SkillService
from app.infrastructure.database import get_db
from app.infrastructure.cache import InMemorySkillCache, SkillCache
router = APIRouter(prefix="/api/v1/skills")
_default_cache = InMemorySkillCache()
def get_cache() -> SkillCache:
return _default_cache
@router.get("", response_model=SkillListResponse)
def list_skills(db: Session = Depends(get_db), cache: SkillCache = Depends(get_cache)):
svc = SkillService(db, cache)
items = svc.list_skills()
return SkillListResponse(list=items)
@router.get("/{skill_code}", response_model=SkillDetailResponse)
def get_skill_detail(skill_code: str, db: Session = Depends(get_db), cache: SkillCache = Depends(get_cache)):
svc = SkillService(db, cache)
try:
return svc.get_detail(skill_code)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
from fastapi import APIRouter from fastapi import APIRouter
from app.api.v1.endpoints import agent_group_helper, agents, position_tags from app.api.v1.endpoints import agent_group_helper, agents, position_tags, skills, sessions, routing, analytics, qrcode_channel, customer_group, official_site_tab, official_site_agent_display, official_site_upload, official_site_home, methodology
api_router = APIRouter() api_router = APIRouter()
api_router.include_router(agent_group_helper.router, tags=["agent-group-helper"]) api_router.include_router(agent_group_helper.router, tags=["agent-group-helper"])
api_router.include_router(agents.router, tags=["agents"]) api_router.include_router(agents.router, tags=["agents"])
api_router.include_router(position_tags.router, tags=["position-tags"]) api_router.include_router(position_tags.router, tags=["position-tags"])
api_router.include_router(skills.router, tags=["skills"])
api_router.include_router(sessions.router, tags=["sessions"])
api_router.include_router(routing.router, tags=["routing"])
api_router.include_router(analytics.router, tags=["analytics"])
api_router.include_router(qrcode_channel.router, tags=["qrcode-channel"])
api_router.include_router(customer_group.router, tags=["customer-group"])
api_router.include_router(official_site_tab.router, tags=["official-site-tab"])
api_router.include_router(official_site_agent_display.router, tags=["official-site-agent-display"])
api_router.include_router(official_site_upload.router, tags=["official-site-upload"])
api_router.include_router(official_site_home.router, tags=["official-site-home"])
api_router.include_router(methodology.router, tags=["methodology"])
from typing import Optional, Protocol
class SkillCache(Protocol):
def get(self, skill_code: str) -> Optional[str]:
...
def set(self, skill_code: str, value: str, expire_seconds: int = 3600) -> None:
...
class InMemorySkillCache:
def __init__(self):
self._store: dict[str, str] = {}
def get(self, skill_code: str) -> Optional[str]:
return self._store.get(skill_code)
def set(self, skill_code: str, value: str, expire_seconds: int = 3600) -> None:
self._store[skill_code] = value
from __future__ import annotations
from typing import Optional, Protocol
class FileParser(Protocol):
def extract_text(self, file_url: str, file_name: str) -> Optional[str]:
...
class InMemoryFileParser:
def __init__(self) -> None:
self._results: dict[str, str] = {}
def set_result(self, file_name: str, text: str) -> None:
self._results[file_name] = text
def extract_text(self, file_url: str, file_name: str) -> Optional[str]:
return self._results.get(file_name)
class OSSClient(Protocol):
def upload(self, file_data: bytes, file_name: str, content_type: str) -> str:
...
class InMemoryOSSClient:
def __init__(self) -> None:
self._files: dict[str, bytes] = {}
def upload(self, file_data: bytes, file_name: str, content_type: str) -> str:
self._files[file_name] = file_data
return f"https://oss.example.com/{file_name}"
def get_file(self, file_name: str) -> Optional[bytes]:
return self._files.get(file_name)
from __future__ import annotations
import time
import threading
from typing import Optional, Protocol
class DistributedLock(Protocol):
def acquire(self, key: str, timeout_seconds: float = 10.0) -> bool:
...
def release(self, key: str) -> None:
...
class InMemoryDistributedLock:
def __init__(self) -> None:
self._locks: dict[str, threading.Lock] = {}
self._held: set[str] = set()
def acquire(self, key: str, timeout_seconds: float = 10.0) -> bool:
if key not in self._locks:
self._locks[key] = threading.Lock()
acquired = self._locks[key].acquire(timeout=timeout_seconds)
if acquired:
self._held.add(key)
return acquired
def release(self, key: str) -> None:
if key in self._locks:
self._locks[key].release()
self._held.discard(key)
class IdempotencyStore(Protocol):
def check_and_mark(self, key: str) -> bool:
...
class InMemoryIdempotencyStore:
def __init__(self) -> None:
self._processed: set[str] = set()
def check_and_mark(self, key: str) -> bool:
if key in self._processed:
return False
self._processed.add(key)
return True
class WeComGroupClient(Protocol):
def create_group(self, name: str, owner_user_id: str, member_user_ids: List[str], customer_user_id: str) -> str:
...
def add_bot_to_group(self, group_id: str, agent_id: int) -> bool:
...
def dissolve_group(self, group_id: str) -> bool:
...
def get_customer_nickname(self, customer_user_id: str) -> str:
...
from typing import List
class InMemoryWeComGroupClient:
def __init__(self) -> None:
self._groups: dict[str, dict] = {}
self._nicknames: dict[str, str] = {}
self._fail_agents: set[int] = set()
def set_nickname(self, customer_user_id: str, nickname: str) -> None:
self._nicknames[customer_user_id] = nickname
def set_fail_agent(self, agent_id: int) -> None:
self._fail_agents.add(agent_id)
def create_group(self, name: str, owner_user_id: str, member_user_ids: List[str], customer_user_id: str) -> str:
group_id = f"grp_{int(time.time() * 1000)}"
self._groups[group_id] = {
"name": name,
"owner": owner_user_id,
"members": member_user_ids,
"customer": customer_user_id,
}
return group_id
def add_bot_to_group(self, group_id: str, agent_id: int) -> bool:
if agent_id in self._fail_agents:
return False
if group_id in self._groups:
self._groups[group_id].setdefault("bots", []).append(agent_id)
return True
def dissolve_group(self, group_id: str) -> bool:
if group_id in self._groups:
del self._groups[group_id]
return True
def get_customer_nickname(self, customer_user_id: str) -> str:
return self._nicknames.get(customer_user_id, "客户")
from __future__ import annotations
import time
from typing import Optional, Protocol
class H5CacheManager(Protocol):
def get_home_page(self) -> Optional[str]:
...
def set_home_page(self, data: str, ttl_seconds: int = 300) -> None:
...
def invalidate_home_page(self) -> None:
...
class InMemoryH5CacheManager:
def __init__(self) -> None:
self._store: Optional[str] = None
self._expires_at: float = 0.0
self._invalidated_keys: set[str] = set()
def get_home_page(self) -> Optional[str]:
if time.monotonic() > self._expires_at:
return None
return self._store
def set_home_page(self, data: str, ttl_seconds: int = 300) -> None:
self._store = data
self._expires_at = time.monotonic() + ttl_seconds
def invalidate_home_page(self) -> None:
self._invalidated_keys.add("h5_home_page")
self._store = None
self._expires_at = 0.0
def was_invalidated(self, key: str = "h5_home_page") -> bool:
return key in self._invalidated_keys
def reset(self) -> None:
self._invalidated_keys.clear()
self._store = None
self._expires_at = 0.0
\ No newline at end of file \ No newline at end of file
from __future__ import annotations
import json
import time
from dataclasses import dataclass
from typing import Any, Optional, Protocol
class KeyValueStore(Protocol):
def get_json(self, key: str) -> Optional[dict[str, Any]]:
...
def set_json(self, key: str, value: dict[str, Any], expire_seconds: int) -> None:
...
def refresh_ttl(self, key: str, expire_seconds: int) -> None:
...
def delete(self, key: str) -> None:
...
@dataclass
class _MemValue:
payload: str
expires_at: float
class InMemoryKeyValueStore:
def __init__(self) -> None:
self._store: dict[str, _MemValue] = {}
def _now(self) -> float:
return time.time()
def _is_expired(self, val: _MemValue) -> bool:
return val.expires_at <= self._now()
def get_json(self, key: str) -> Optional[dict[str, Any]]:
val = self._store.get(key)
if not val:
return None
if self._is_expired(val):
self._store.pop(key, None)
return None
return json.loads(val.payload)
def set_json(self, key: str, value: dict[str, Any], expire_seconds: int) -> None:
self._store[key] = _MemValue(
payload=json.dumps(value, ensure_ascii=False),
expires_at=self._now() + expire_seconds,
)
def refresh_ttl(self, key: str, expire_seconds: int) -> None:
val = self._store.get(key)
if not val:
return
if self._is_expired(val):
self._store.pop(key, None)
return
val.expires_at = self._now() + expire_seconds
def delete(self, key: str) -> None:
self._store.pop(key, None)
def clear(self) -> None:
self._store.clear()
from __future__ import annotations
from typing import Optional, Protocol
class LLMClient(Protocol):
def recognize_intent(self, query: str, context_summary: str = "") -> tuple[str, float]:
...
class InMemoryLLMClient:
def __init__(self) -> None:
self._keyword_map: dict[str, str] = {
"查询指标": "query-metric",
"指标": "query-metric",
"查询明细": "query-detail",
"明细": "query-detail",
"上传": "file-upload",
"文件": "file-upload",
}
def recognize_intent(self, query: str, context_summary: str = "") -> tuple[str, float]:
for keyword, intent in self._keyword_map.items():
if keyword in query:
return intent, 0.9
return "general-qa", 0.5
from __future__ import annotations
from typing import Any, Optional
from app.infrastructure.kv_store import InMemoryKeyValueStore, KeyValueStore
SESSION_TTL_SECONDS = 30 * 60
def active_session_key(session_id: str) -> str:
return f"session:active:{session_id}"
_DEFAULT_STORE: KeyValueStore = InMemoryKeyValueStore()
def get_kv_store() -> KeyValueStore:
return _DEFAULT_STORE
def _get_default_mem_store() -> InMemoryKeyValueStore:
if isinstance(_DEFAULT_STORE, InMemoryKeyValueStore):
return _DEFAULT_STORE
raise RuntimeError("Default KV store is not in-memory")
def clear_default_store_for_tests() -> None:
_get_default_mem_store().clear()
class SessionStore:
def __init__(self, kv: Optional[KeyValueStore] = None) -> None:
self._kv = kv or get_kv_store()
def get(self, session_id: str) -> Optional[dict[str, Any]]:
return self._kv.get_json(active_session_key(session_id))
def set(self, session_id: str, payload: dict[str, Any]) -> None:
self._kv.set_json(active_session_key(session_id), payload, expire_seconds=SESSION_TTL_SECONDS)
def refresh_ttl(self, session_id: str) -> None:
self._kv.refresh_ttl(active_session_key(session_id), expire_seconds=SESSION_TTL_SECONDS)
def delete(self, session_id: str) -> None:
self._kv.delete(active_session_key(session_id))
from app.infrastructure.h5_cache import InMemoryH5CacheManager, H5CacheManager
shared_h5_cache: H5CacheManager = InMemoryH5CacheManager()
\ No newline at end of file \ No newline at end of file
from sqlalchemy import Column, DateTime, Integer, String, func from sqlalchemy import Column, DateTime, Integer, String, JSON, UniqueConstraint, func
from app.infrastructure.database import Base from app.infrastructure.database import Base
...@@ -7,9 +6,24 @@ class QrcodeChannel(Base): ...@@ -7,9 +6,24 @@ class QrcodeChannel(Base):
__tablename__ = "qrcode_channels" __tablename__ = "qrcode_channels"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
qrcode_name = Column(String(50), default=None)
position_code = Column(String(100), default=None, index=True)
position_name = Column(String(100), nullable=False, default="")
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="")
position_name = Column(String(100), nullable=False) 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)
agent_ids = Column(JSON, default=None)
agent_names = Column(JSON, default=None)
remark = Column(String(200), default=None)
welcome_message = Column(String(500), default=None)
status = Column(String(20), nullable=False, default="enable") status = Column(String(20), nullable=False, default="enable")
disable_reason = Column(String(200), default=None)
created_by = Column(String(64), 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)
__table_args__ = (
UniqueConstraint('position_code', 'employee_id', name='uk_position_employee'),
)
from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, JSON, Date, Numeric, func
from app.infrastructure.database import Base
class ConversationLog(Base):
__tablename__ = "conversation_logs"
id = Column(Integer, primary_key=True, index=True)
session_id = Column(String(64), nullable=False)
user_id = Column(String(64), nullable=False, index=True)
agent_id = Column(Integer, nullable=False, index=True)
agent_name = Column(String(50), default=None)
query = Column(Text, nullable=False)
response = Column(Text, default=None)
intent = Column(String(128), default=None, index=True)
entities = Column(JSON, default=None)
processing_time_ms = Column(Integer, default=None)
has_error = Column(Boolean, default=False, nullable=False, index=True)
created_at = Column(DateTime, server_default=func.now(), nullable=False, index=True)
class AnalyticsEvent(Base):
__tablename__ = "analytics_events"
id = Column(Integer, primary_key=True, index=True)
event_type = Column(String(64), nullable=False, index=True)
event_data = Column(JSON, default=None)
created_at = Column(DateTime, server_default=func.now(), nullable=False, index=True)
class AnalyticsStatistic(Base):
__tablename__ = "analytics_statistics"
id = Column(Integer, primary_key=True, index=True)
stat_date = Column(Date, nullable=False)
dimension = Column(String(32), nullable=False)
dimension_value = Column(String(128), nullable=False)
total_agent_calls = Column(Integer, default=0, nullable=False)
total_sessions = Column(Integer, default=0, nullable=False)
avg_session_turns = Column(Numeric(5, 2), default=0.00, nullable=False)
intent_distribution = Column(JSON, default=None)
agent_call_ranking = Column(JSON, default=None)
daily_trend = Column(JSON, default=None)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
class PageView(Base):
__tablename__ = "page_views"
id = Column(Integer, primary_key=True, index=True)
page_type = Column(String(64), nullable=False, index=True)
user_id = Column(String(64), default=None, index=True)
session_id = Column(String(64), default=None)
device_type = Column(String(32), default=None)
created_at = Column(DateTime, server_default=func.now(), nullable=False, index=True)
class ScanEvent(Base):
__tablename__ = "scan_events"
id = Column(Integer, primary_key=True, index=True)
qrcode_id = Column(Integer, default=None, index=True)
channel_code = Column(String(128), default=None, index=True)
customer_user_id = Column(String(64), default=None, index=True)
position_code = Column(String(64), default=None)
employee_id = Column(String(64), default=None)
created_at = Column(DateTime, server_default=func.now(), nullable=False, index=True)
class GroupJoinEvent(Base):
__tablename__ = "group_join_events"
id = Column(Integer, primary_key=True, index=True)
group_id = Column(String(64), default=None, index=True)
customer_user_id = Column(String(64), default=None, index=True)
employee_count = Column(Integer, default=0)
agent_count = Column(Integer, default=0)
channel_code = Column(String(128), default=None, index=True)
created_at = Column(DateTime, server_default=func.now(), nullable=False, index=True)
from sqlalchemy import Column, DateTime, Integer, String, JSON, func
from app.infrastructure.database import Base
class CustomerGroup(Base):
__tablename__ = "customer_groups"
id = Column(Integer, primary_key=True, index=True)
group_id = Column(String(64), nullable=False, unique=True, index=True)
group_name = Column(String(100), nullable=False)
customer_user_id = Column(String(64), nullable=False, index=True)
customer_nickname = Column(String(100), default=None)
position_code = Column(String(100), default=None, index=True)
channel_code = Column(String(128), default=None, index=True)
creator_employee_id = Column(String(64), default=None)
employee_wechat_user_ids = Column(JSON, default=None)
agent_ids = Column(JSON, default=None)
status = Column(String(20), nullable=False, default="active", index=True)
created_at = Column(DateTime, server_default=func.now(), nullable=False, index=True)
dissolved_at = Column(DateTime, default=None)
dissolution_reason = Column(String(200), default=None)
from sqlalchemy import Column, DateTime, Integer, String, func
from app.infrastructure.database import Base
class OfficialSiteMethodology(Base):
__tablename__ = "official_site_methodology"
id = Column(Integer, primary_key=True, index=True)
display_status = Column(String(20), nullable=False, default="enable", index=True)
main_title = Column(String(100), nullable=False, default="方法论")
sub_title = Column(String(200), nullable=False, default="")
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
class OfficialSiteMethodologyStep(Base):
__tablename__ = "official_site_methodology_steps"
id = Column(Integer, primary_key=True, index=True)
methodology_id = Column(Integer, nullable=False, index=True)
step_icon = Column(String(500), default=None)
step_name = Column(String(100), nullable=False)
step_order = Column(Integer, nullable=False, index=True)
step_image = Column(String(500), default=None)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
\ No newline at end of file \ No newline at end of file
from sqlalchemy import Column, DateTime, Integer, String, UniqueConstraint, func
from app.infrastructure.database import Base
class OfficialSiteAgentDisplay(Base):
__tablename__ = "official_site_agent_display"
id = Column(Integer, primary_key=True, index=True)
tab_id = Column(Integer, nullable=False, index=True)
agent_id = Column(Integer, nullable=False, index=True)
media_url = Column(String(500), default=None)
media_type = Column(String(10), default=None)
speech_title = Column(String(100), default=None)
speech_content = Column(String(200), default=None)
display_status = Column(String(20), nullable=False, default="enable", index=True)
sort_order = Column(Integer, nullable=False, default=0, index=True)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
__table_args__ = (
UniqueConstraint('tab_id', 'agent_id', name='uk_tab_agent'),
)
\ No newline at end of file \ No newline at end of file
...@@ -19,5 +19,12 @@ class OfficialTab(Base): ...@@ -19,5 +19,12 @@ class OfficialTab(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
tab_name = Column(String(100), nullable=False) tab_name = Column(String(100), nullable=False)
position_id = Column(Integer, default=None, index=True) position_id = Column(Integer, default=None, index=True)
position_code = Column(String(100), default=None, index=True)
position_name = Column(String(100), default=None)
qrcode_id = Column(Integer, default=None, index=True)
display_status = Column(String(20), nullable=False, default="enable", index=True)
sort_order = Column(Integer, nullable=False, default=0, index=True)
created_by = Column(String(64), 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)
deleted_at = Column(DateTime, default=None, index=True)
from __future__ import annotations
import enum
from sqlalchemy import Column, DateTime, Integer, String, Text, func
from app.infrastructure.database import Base
class SessionStatus(str, enum.Enum):
active = "active"
archived = "archived"
class Session(Base):
__tablename__ = "sessions"
id = Column(Integer, primary_key=True, index=True)
session_id = Column(String(64), nullable=False, unique=True, index=True)
user_id = Column(String(64), nullable=False, index=True)
channel = Column(String(64), nullable=False, index=True)
current_agent_id = Column(Integer, nullable=False, default=101)
status = Column(String(20), nullable=False, default=SessionStatus.active.value)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
class ConversationHistory(Base):
__tablename__ = "conversation_history"
id = Column(Integer, primary_key=True, index=True)
session_id = Column(String(64), nullable=False, index=True)
role = Column(String(32), nullable=False)
content = Column(Text, nullable=False)
agent_id = Column(Integer, nullable=True)
intent = Column(String(128), nullable=True)
entities_json = Column(Text, nullable=True)
timestamp = Column(DateTime, server_default=func.now(), nullable=False)
from sqlalchemy import Column, Integer, String, Text, DateTime, func
from app.infrastructure.database import Base
class Skill(Base):
__tablename__ = "skills"
id = Column(Integer, primary_key=True, index=True)
skill_code = Column(String(100), nullable=False, unique=True, index=True)
skill_name = Column(String(100), nullable=False)
description = Column(String(500), default=None)
doc_markdown = Column(Text, default=None)
priority = Column(Integer, default=1, 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)
from pydantic import BaseModel, Field, ConfigDict
from typing import List, Optional, Dict, Any
from datetime import datetime, date
class ConversationLogItem(BaseModel):
id: int
session_id: str
user_id: str
agent_id: int
agent_name: Optional[str]
query: str
response: Optional[str]
intent: Optional[str]
entities: Optional[Dict[str, Any]]
processing_time_ms: Optional[int]
has_error: bool
created_at: datetime
model_config = ConfigDict(from_attributes=True)
class ConversationLogListResponse(BaseModel):
total: int
list: List[ConversationLogItem]
class AnalyticsEventItem(BaseModel):
event_type: str = Field(..., max_length=64)
event_data: Optional[Dict[str, Any]] = None
timestamp: Optional[datetime] = None
class AnalyticsEventRequest(BaseModel):
events: List[AnalyticsEventItem] = Field(..., min_length=1)
class AnalyticsEventResponse(BaseModel):
success: bool
received_count: int
class IntentDistributionItem(BaseModel):
intent: str
count: int
percentage: float
class AgentCallRankingItem(BaseModel):
agent_id: int
agent_name: str
call_count: int
class DailyTrendItem(BaseModel):
date: str
calls: int
sessions: int
class AnalyticsStatisticsResponse(BaseModel):
total_agent_calls: int
total_sessions: int
avg_session_turns: float
intent_distribution: List[IntentDistributionItem]
agent_call_ranking: List[AgentCallRankingItem]
daily_trend: List[DailyTrendItem]
class PageViewRequest(BaseModel):
page_type: str = Field(..., max_length=64)
user_id: Optional[str] = Field(None, max_length=64)
session_id: Optional[str] = Field(None, max_length=64)
timestamp: Optional[datetime] = None
device_type: Optional[str] = Field(None, max_length=32)
class PageViewResponse(BaseModel):
success: bool
class ScanEventRequest(BaseModel):
qrcode_id: Optional[int] = None
channel_code: Optional[str] = Field(None, max_length=128)
customer_user_id: Optional[str] = Field(None, max_length=64)
scan_time: Optional[datetime] = None
position_code: Optional[str] = Field(None, max_length=64)
employee_id: Optional[str] = Field(None, max_length=64)
class ScanEventResponse(BaseModel):
success: bool
class GroupJoinEventRequest(BaseModel):
group_id: Optional[str] = Field(None, max_length=64)
customer_user_id: Optional[str] = Field(None, max_length=64)
employee_count: int = 0
agent_count: int = 0
join_time: Optional[datetime] = None
channel_code: Optional[str] = Field(None, max_length=128)
class GroupJoinEventResponse(BaseModel):
success: bool
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field
class CreateGroupRequest(BaseModel):
customer_user_id: str = Field(..., max_length=64)
channel_code: str = Field(..., max_length=128)
position_code: str = Field(..., max_length=100)
employee_wechat_user_ids: List[str] = Field(..., min_length=1)
agent_ids: List[int] = Field(default_factory=list)
class GroupMemberInfo(BaseModel):
user_id: str
name: str
type: str
class CreateGroupResponse(BaseModel):
group_id: str
group_name: str
creator_employee_id: Optional[str]
created_at: datetime
members: List[GroupMemberInfo]
class AgentJoinRequest(BaseModel):
agent_ids: List[int] = Field(..., min_length=1)
class AgentJoinResult(BaseModel):
agent_id: int
agent_name: str
class AgentJoinResponse(BaseModel):
success: bool
joined_agents: List[AgentJoinResult]
failed_agents: List[AgentJoinResult]
class CustomerInfo(BaseModel):
user_id: str
nickname: Optional[str]
class EmployeeInfo(BaseModel):
user_id: str
name: str
class AgentInfo(BaseModel):
agent_id: int
name: str
class GroupListItem(BaseModel):
group_id: str
group_name: str
customer_info: CustomerInfo
employee_list: List[EmployeeInfo]
agent_list: List[AgentInfo]
status: str
created_at: datetime
dissolved_at: Optional[datetime]
dissolution_reason: Optional[str]
class GroupListResponse(BaseModel):
total: int
list: List[GroupListItem]
class CallbackResponse(BaseModel):
xml: str
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field
class MethodologyStepItem(BaseModel):
step_id: Optional[int] = None
step_icon: str = Field(..., max_length=500)
step_name: str = Field(..., max_length=100)
step_order: int = Field(..., ge=1)
step_image: str = Field(..., max_length=500)
class GetMethodologyResponse(BaseModel):
config_id: int
display_status: str
main_title: str
sub_title: str
steps: List[MethodologyStepItem]
updated_at: datetime
class SaveMethodologyStepItem(BaseModel):
step_icon: str = Field(..., max_length=500)
step_name: str = Field(..., max_length=20)
step_order: int = Field(..., ge=1)
step_image: str = Field(..., max_length=500)
class SaveMethodologyRequest(BaseModel):
display_status: str = Field("enable", max_length=20)
main_title: str = Field(..., max_length=100)
sub_title: str = Field(..., max_length=200)
steps: List[SaveMethodologyStepItem] = Field(default_factory=list)
class SaveMethodologyResponse(BaseModel):
config_id: int
updated_at: datetime
\ No newline at end of file \ No newline at end of file
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field
class AvailableAgentItem(BaseModel):
agent_id: int
agent_name: str
agent_code: str
is_configured: bool
configured_description: Optional[str] = None
is_steward: bool
class StewardAgentInfo(BaseModel):
agent_id: Optional[int]
agent_name: str
note: str
class AvailableAgentsResponse(BaseModel):
tab_id: int
position_name: str
qrcode_id: Optional[int]
available_agents: List[AvailableAgentItem]
steward_agent: Optional[StewardAgentInfo]
class SaveAgentConfigRequest(BaseModel):
media_url: str = Field(..., max_length=500)
media_type: str
media_size: int = 0
speech_title: str
speech_content: str
display_status: str = "enable"
sort_order: int = 0
class SaveAgentConfigResponse(BaseModel):
config_id: int
tab_id: int
agent_id: int
updated_at: datetime
class ConfiguredAgentItem(BaseModel):
config_id: int
agent_id: int
agent_name: str
media_url: Optional[str]
media_type: Optional[str]
speech_title: Optional[str]
speech_content: Optional[str]
display_status: str
sort_order: int
agent_status: str
class ConfiguredAgentsResponse(BaseModel):
tab_id: int
configured_agents: List[ConfiguredAgentItem]
class DeleteAgentConfigResponse(BaseModel):
success: bool
deleted_at: datetime
\ No newline at end of file \ No newline at end of file
from typing import List, Optional
from pydantic import BaseModel
class H5HomeAgentItem(BaseModel):
agent_id: int
agent_name: str
media_url: Optional[str]
media_type: Optional[str]
speech_title: Optional[str]
speech_content: Optional[str]
status: str
class H5HomeTabItem(BaseModel):
tab_id: int
position_code: str
position_name: str
qrcode_url: Optional[str]
qrcode_status: Optional[str]
agents: List[H5HomeAgentItem]
class H5HomeMethodologyStep(BaseModel):
step_icon: str
step_name: str
step_image: str
class H5HomeMethodologyItem(BaseModel):
display_status: str
main_title: str
sub_title: str
steps: List[H5HomeMethodologyStep]
class H5HomeResponse(BaseModel):
site_title: str
site_subtitle: str
background_image: str
tabs: List[H5HomeTabItem]
methodology: H5HomeMethodologyItem
\ No newline at end of file \ No newline at end of file
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field
class CreateTabRequest(BaseModel):
position_code: str = Field(..., max_length=100)
position_name: str = Field(..., max_length=100)
qrcode_id: int
display_status: str = Field("enable", pattern=r"^(enable|disable)$")
sort_order: int = Field(0, ge=0)
class CreateTabResponse(BaseModel):
tab_id: int
position_code: str
position_name: str
qrcode_id: int
created_at: datetime
class UpdateTabRequest(BaseModel):
position_name: str = Field(..., max_length=100)
qrcode_id: int
display_status: str = Field("enable", pattern=r"^(enable|disable)$")
sort_order: int = Field(0, ge=0)
class UpdateTabResponse(BaseModel):
success: bool
updated_at: datetime
class DeleteTabResponse(BaseModel):
success: bool
deleted_at: datetime
cleaned_agent_configs: int
class UpdateTabStatusRequest(BaseModel):
display_status: str = Field(..., pattern=r"^(enable|disable)$")
reason: Optional[str] = Field(None, max_length=200)
class UpdateTabStatusResponse(BaseModel):
success: bool
previous_status: str
updated_at: datetime
class TabListItem(BaseModel):
tab_id: int
position_code: str
position_name: str
qrcode_id: Optional[int]
qrcode_url: Optional[str]
qrcode_status: Optional[str]
display_status: str
sort_order: int
agent_count: int
created_at: datetime
operations: List[str]
class TabListResponse(BaseModel):
total: int
page: int
page_size: int
list: List[TabListItem]
class AvailableQrcodeItem(BaseModel):
qrcode_id: int
channel_code: str
employee_name: str
position_name: str
status: str
class AvailableQrcodeListResponse(BaseModel):
list: List[AvailableQrcodeItem]
from typing import Optional
from pydantic import BaseModel, Field
class UploadMediaResponse(BaseModel):
file_url: str
file_type: str
file_size: int
width: Optional[int] = None
height: Optional[int] = None
cdn_url: str
\ No newline at end of file \ No newline at end of file
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field
class QrcodeCreateRequest(BaseModel):
qrcode_name: str = Field(..., max_length=50)
position_code: str = Field(..., max_length=100)
employee_id: str = Field(..., max_length=100)
employee_name: str = Field(..., max_length=100)
wechat_user_id: str = Field(..., max_length=100)
remark: Optional[str] = Field(None, max_length=200)
welcome_message: Optional[str] = Field(None, max_length=500)
class QrcodeCreateResponse(BaseModel):
qrcode_id: int
qrcode_name: str
qrcode_url: str
channel_code: str
status: str
agent_ids: List[int]
agent_names: List[str]
created_at: datetime
class QrcodeUpdateRequest(BaseModel):
qrcode_name: str = Field(..., max_length=50)
remark: Optional[str] = Field(None, max_length=200)
welcome_message: Optional[str] = Field(None, max_length=500)
class QrcodeUpdateResponse(BaseModel):
success: bool
updated_at: datetime
class QrcodeDetailResponse(BaseModel):
qrcode_id: int
qrcode_name: Optional[str]
employee_id: str
employee_name: str
position_code: Optional[str]
position_name: str
channel_code: str
qrcode_url: Optional[str]
agent_ids: Optional[List[int]]
agent_names: Optional[List[str]]
remark: Optional[str]
welcome_message: Optional[str]
status: str
created_at: datetime
created_by: Optional[str]
updated_at: Optional[datetime]
class QrcodeListItem(BaseModel):
qrcode_id: int
employee_name: str
position_name: str
channel_code: str
qrcode_url: Optional[str]
agent_count: int
agent_names_preview: List[str]
status: str
created_at: datetime
class QrcodeListResponse(BaseModel):
total: int
page: int
page_size: int
list: List[QrcodeListItem]
class QrcodeExportRequest(BaseModel):
filter_conditions: Optional[dict] = None
export_fields: Optional[List[str]] = None
class QrcodeExportResponse(BaseModel):
file_url: str
file_name: str
total_count: int
expires_at: Optional[datetime] = None
class QrcodeDisableRequest(BaseModel):
reason: str = Field(..., max_length=200)
class QrcodeDisableResponse(BaseModel):
success: bool
disabled_at: datetime
previous_status: str
class QrcodeEnableResponse(BaseModel):
success: bool
enabled_at: datetime
previous_status: str
class QrcodeBatchStatusRequest(BaseModel):
qrcode_ids: List[int] = Field(..., min_length=1)
target_status: str = Field(..., pattern=r"^(enable|disable)$")
reason: Optional[str] = Field(None, max_length=200)
class QrcodeBatchStatusResponse(BaseModel):
success_count: int
failed_count: int
failed_list: List[dict]
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Any
from datetime import datetime
class ChatCompletionRequest(BaseModel):
session_id: str = Field(..., max_length=64)
user_id: str = Field(..., max_length=64)
channel: str = Field(..., max_length=64)
query: str = Field(..., min_length=1, max_length=5000)
mentioned_agent_code: Optional[str] = Field(None, max_length=100)
file_url: Optional[str] = Field(None, max_length=500)
class RoutingInfo(BaseModel):
agent_id: int
agent_code: str
agent_name: str
routing_reason: str
class IntentInfo(BaseModel):
intent: str
confidence: float = 0.0
class HandoffInfo(BaseModel):
from_agent_id: Optional[int] = None
from_agent_name: Optional[str] = None
to_agent_id: int
to_agent_name: str
handoff_message: str
class ChatCompletionResponse(BaseModel):
session_id: str
routing: RoutingInfo
intent: Optional[IntentInfo] = None
handoff: Optional[HandoffInfo] = None
response_content: Optional[str] = None
created_at: datetime
class FileUploadResponse(BaseModel):
file_url: str
file_name: str
file_size: int
extracted_text: Optional[str] = None
session_id: str
from __future__ import annotations
from datetime import datetime
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
class SessionCreateRequest(BaseModel):
user_id: str = Field(..., max_length=64)
channel: str = Field(..., max_length=64)
initial_query: str = Field(..., min_length=1, max_length=5000)
class SessionCreateResponse(BaseModel):
session_id: str
user_id: str
channel: str
current_agent_id: int
created_at: datetime
class SessionUpdateRequest(BaseModel):
role: str = Field(..., max_length=32)
content: str = Field(..., min_length=1, max_length=5000)
agent_id: int
intent: Optional[str] = Field(None, max_length=128)
entities: Optional[Dict[str, Any]] = None
class SessionUpdateResponse(BaseModel):
success: bool
updated_at: datetime
turn_count: int
class SessionHistoryTurn(BaseModel):
role: str
content: str
agent_id: Optional[int] = None
intent: Optional[str] = None
timestamp: datetime
class SessionDetailResponse(BaseModel):
session_id: str
user_id: str
channel: str
current_agent_id: int
current_agent_name: Optional[str] = None
conversation_history: List[SessionHistoryTurn]
context_entities: Dict[str, Any]
created_at: datetime
updated_at: datetime
class SessionContextResponse(BaseModel):
session_id: str
current_agent_id: int
last_entities: Dict[str, Any]
inheritance_valid: bool
expires_at: Optional[datetime] = None
class SessionArchiveResponse(BaseModel):
success: bool
archived_at: datetime
SessionCreateResponse.model_config = {"from_attributes": True}
SessionUpdateResponse.model_config = {"from_attributes": True}
SessionDetailResponse.model_config = {"from_attributes": True}
SessionContextResponse.model_config = {"from_attributes": True}
SessionArchiveResponse.model_config = {"from_attributes": True}
from pydantic import BaseModel, ConfigDict, Field
from typing import List, Optional
from datetime import datetime
class SkillListItem(BaseModel):
skill_code: str
skill_name: str
description: Optional[str]
model_config = ConfigDict(from_attributes=True)
class SkillListResponse(BaseModel):
list: List[SkillListItem]
class SkillDetailResponse(BaseModel):
skill_code: str
skill_name: str
description: Optional[str]
doc_markdown: Optional[str]
model_config = ConfigDict(from_attributes=True)
...@@ -13,7 +13,10 @@ from app.schema.agent_group import ( ...@@ -13,7 +13,10 @@ from app.schema.agent_group import (
class WeComClient(Protocol): class WeComClient(Protocol):
def list_position_employees(self, position_code: str): def list_position_employees(self, position_code: str):
"""Return position employee payload from WeCom-compatible provider.""" ...
def create_qrcode(self, channel_code: str, welcome_message: str = "") -> str:
...
class PositionNotFoundError(ValueError): class PositionNotFoundError(ValueError):
...@@ -28,6 +31,31 @@ class UnconfiguredWeComClient: ...@@ -28,6 +31,31 @@ class UnconfiguredWeComClient:
def list_position_employees(self, position_code: str): def list_position_employees(self, position_code: str):
raise WeComUnavailableError("WeCom client is not configured") raise WeComUnavailableError("WeCom client is not configured")
def create_qrcode(self, channel_code: str, welcome_message: str = "") -> str:
raise WeComUnavailableError("WeCom client is not configured")
class InMemoryWeComClient:
def __init__(self):
self._positions: dict = {}
self._fail_codes: set = set()
def set_position(self, position_code: str, payload: dict):
self._positions[position_code] = payload
def set_fail(self, position_code: str):
self._fail_codes.add(position_code)
def list_position_employees(self, position_code: str):
if position_code in self._fail_codes:
raise WeComUnavailableError("wecom unavailable")
if position_code not in self._positions:
return None
return self._positions[position_code]
def create_qrcode(self, channel_code: str, welcome_message: str = "") -> str:
return f"https://cdn.weixin.qq.com/qrcode/{channel_code}.png"
class AgentGroupHelperService: class AgentGroupHelperService:
def __init__(self, db: Session, wecom_client: WeComClient): def __init__(self, db: Session, wecom_client: WeComClient):
......
from __future__ import annotations
from datetime import datetime, timezone, timedelta
from typing import Any, Optional
from sqlalchemy import and_
from sqlalchemy.orm import Session as OrmSession
from app.model.analytics import (
ConversationLog,
AnalyticsEvent,
AnalyticsStatistic,
PageView,
ScanEvent,
GroupJoinEvent,
)
from app.schema.analytics import (
AnalyticsEventResponse,
AnalyticsStatisticsResponse,
IntentDistributionItem,
AgentCallRankingItem,
DailyTrendItem,
PageViewResponse,
ScanEventResponse,
GroupJoinEventResponse,
)
class AnalyticsService:
def __init__(self, db: OrmSession) -> None:
self.db = db
def list_conversation_logs(
self,
page: int = 1,
page_size: int = 20,
user_id: Optional[str] = None,
agent_id: Optional[int] = None,
intent_type: Optional[str] = None,
time_start: Optional[datetime] = None,
time_end: Optional[datetime] = None,
has_error: Optional[bool] = None,
) -> tuple[int, list[ConversationLog]]:
query = self.db.query(ConversationLog)
if user_id is not None:
query = query.filter(ConversationLog.user_id == user_id)
if agent_id is not None:
query = query.filter(ConversationLog.agent_id == agent_id)
if intent_type is not None:
query = query.filter(ConversationLog.intent == intent_type)
if time_start is not None:
query = query.filter(ConversationLog.created_at >= time_start)
if time_end is not None:
query = query.filter(ConversationLog.created_at <= time_end)
if has_error is not None:
query = query.filter(ConversationLog.has_error == has_error)
total = query.count()
items = query.order_by(ConversationLog.created_at.desc()).offset((page - 1) * page_size).limit(page_size).all()
return total, items
def upload_events(self, events: list[dict[str, Any]]) -> AnalyticsEventResponse:
for ev in events:
row = AnalyticsEvent(
event_type=ev["event_type"],
event_data=ev.get("event_data"),
)
self.db.add(row)
self.db.commit()
return AnalyticsEventResponse(success=True, received_count=len(events))
def get_statistics(
self,
date_range: str = "last_7_days",
group_by: Optional[str] = None,
) -> AnalyticsStatisticsResponse:
if date_range == "last_7_days":
start = datetime.now(timezone.utc).date() - timedelta(days=7)
elif date_range == "last_30_days":
start = datetime.now(timezone.utc).date() - timedelta(days=30)
else:
start = datetime.now(timezone.utc).date() - timedelta(days=7)
stats = self.db.query(AnalyticsStatistic).filter(
AnalyticsStatistic.stat_date >= start
).all()
if not stats:
return AnalyticsStatisticsResponse(
total_agent_calls=0,
total_sessions=0,
avg_session_turns=0.0,
intent_distribution=[],
agent_call_ranking=[],
daily_trend=[],
)
total_calls = sum(s.total_agent_calls for s in stats)
total_sessions = sum(s.total_sessions for s in stats)
avg_turns = sum(float(s.avg_session_turns) for s in stats) / len(stats) if stats else 0.0
intent_map: dict[str, int] = {}
for s in stats:
if s.intent_distribution:
for item in s.intent_distribution:
intent_map[item["intent"]] = intent_map.get(item["intent"], 0) + item["count"]
total_intent = sum(intent_map.values()) or 1
intent_dist = [
IntentDistributionItem(intent=k, count=v, percentage=round(v / total_intent * 100, 1))
for k, v in sorted(intent_map.items(), key=lambda x: -x[1])
]
agent_map: dict[int, dict] = {}
for s in stats:
if s.agent_call_ranking:
for item in s.agent_call_ranking:
aid = item["agent_id"]
if aid not in agent_map:
agent_map[aid] = {"agent_id": aid, "agent_name": item["agent_name"], "call_count": 0}
agent_map[aid]["call_count"] += item["call_count"]
agent_ranking = sorted(agent_map.values(), key=lambda x: -x["call_count"])
agent_ranking = [AgentCallRankingItem(**a) for a in agent_ranking]
trend_map: dict[str, dict] = {}
for s in stats:
if s.daily_trend:
for item in s.daily_trend:
d = item["date"]
if d not in trend_map:
trend_map[d] = {"date": d, "calls": 0, "sessions": 0}
trend_map[d]["calls"] += item["calls"]
trend_map[d]["sessions"] += item["sessions"]
daily_trend = [DailyTrendItem(**t) for t in sorted(trend_map.values(), key=lambda x: x["date"])]
return AnalyticsStatisticsResponse(
total_agent_calls=total_calls,
total_sessions=total_sessions,
avg_session_turns=round(avg_turns, 2),
intent_distribution=intent_dist,
agent_call_ranking=agent_ranking,
daily_trend=daily_trend,
)
def record_page_view(
self,
page_type: str,
user_id: Optional[str] = None,
session_id: Optional[str] = None,
device_type: Optional[str] = None,
) -> PageViewResponse:
pv = PageView(
page_type=page_type,
user_id=user_id,
session_id=session_id,
device_type=device_type,
)
self.db.add(pv)
self.db.commit()
return PageViewResponse(success=True)
def record_scan_event(
self,
qrcode_id: Optional[int] = None,
channel_code: Optional[str] = None,
customer_user_id: Optional[str] = None,
position_code: Optional[str] = None,
employee_id: Optional[str] = None,
) -> ScanEventResponse:
se = ScanEvent(
qrcode_id=qrcode_id,
channel_code=channel_code,
customer_user_id=customer_user_id,
position_code=position_code,
employee_id=employee_id,
)
self.db.add(se)
self.db.commit()
return ScanEventResponse(success=True)
def record_group_join_event(
self,
group_id: Optional[str] = None,
customer_user_id: Optional[str] = None,
employee_count: int = 0,
agent_count: int = 0,
channel_code: Optional[str] = None,
) -> GroupJoinEventResponse:
gje = GroupJoinEvent(
group_id=group_id,
customer_user_id=customer_user_id,
employee_count=employee_count,
agent_count=agent_count,
channel_code=channel_code,
)
self.db.add(gje)
self.db.commit()
return GroupJoinEventResponse(success=True)
from __future__ import annotations
from datetime import datetime, timezone
from typing import Optional
from sqlalchemy import or_
from sqlalchemy.orm import Session as OrmSession
from app.infrastructure.group_infra import (
DistributedLock,
IdempotencyStore,
WeComGroupClient,
)
from app.model.customer_group import CustomerGroup
from app.model.agent import Agent
from app.schema.customer_group import (
AgentJoinRequest,
AgentJoinResponse,
AgentJoinResult,
AgentInfo,
CreateGroupRequest,
CreateGroupResponse,
CustomerInfo,
EmployeeInfo,
GroupListItem,
GroupListResponse,
GroupMemberInfo,
)
class CustomerGroupService:
def __init__(
self,
db: OrmSession,
wecom: WeComGroupClient,
lock: DistributedLock,
idempotency: IdempotencyStore,
) -> None:
self.db = db
self.wecom = wecom
self.lock = lock
self.idempotency = idempotency
def handle_scan_callback(self, event_id: str, customer_user_id: str, channel_code: str) -> str:
self.idempotency.check_and_mark(f"processed:event:{event_id}")
return "SUCCESS"
def handle_member_exit_callback(self, event_id: str, group_id: str, user_id: str, is_customer: bool) -> str:
self.idempotency.check_and_mark(f"processed:event:{event_id}")
if is_customer:
try:
self.dissolve_group(group_id, reason="客户退群")
except ValueError:
pass
return "SUCCESS"
def create_group(self, req: CreateGroupRequest) -> CreateGroupResponse:
existing = self.db.query(CustomerGroup).filter(
CustomerGroup.customer_user_id == req.customer_user_id,
CustomerGroup.position_code == req.position_code,
CustomerGroup.status == "active",
).first()
if existing:
return self._build_create_response(existing)
lock_key = f"lock:group:create:{req.customer_user_id}:{req.position_code}"
acquired = self.lock.acquire(lock_key)
if not acquired:
existing2 = self.db.query(CustomerGroup).filter(
CustomerGroup.customer_user_id == req.customer_user_id,
CustomerGroup.position_code == req.position_code,
CustomerGroup.status == "active",
).first()
if existing2:
return self._build_create_response(existing2)
raise ValueError("获取分布式锁失败")
try:
existing3 = self.db.query(CustomerGroup).filter(
CustomerGroup.customer_user_id == req.customer_user_id,
CustomerGroup.position_code == req.position_code,
CustomerGroup.status == "active",
).first()
if existing3:
return self._build_create_response(existing3)
nickname = self.wecom.get_customer_nickname(req.customer_user_id)
group_name = f"{nickname} 的专属服务群"
owner = req.employee_wechat_user_ids[0] if req.employee_wechat_user_ids else ""
all_member_ids = list(req.employee_wechat_user_ids) + [req.customer_user_id]
group_id = self.wecom.create_group(group_name, owner, all_member_ids, req.customer_user_id)
group = CustomerGroup(
group_id=group_id,
group_name=group_name,
customer_user_id=req.customer_user_id,
customer_nickname=nickname,
position_code=req.position_code,
channel_code=req.channel_code,
creator_employee_id=owner,
employee_wechat_user_ids=req.employee_wechat_user_ids,
agent_ids=req.agent_ids,
status="active",
)
self.db.add(group)
self.db.commit()
self.db.refresh(group)
return self._build_create_response(group)
finally:
self.lock.release(lock_key)
def agent_join(self, group_id: str, req: AgentJoinRequest) -> AgentJoinResponse:
group = self.db.query(CustomerGroup).filter(CustomerGroup.group_id == group_id).first()
if not group:
raise ValueError("群聊不存在")
joined = []
failed = []
for aid in req.agent_ids:
agent = self.db.query(Agent).filter(Agent.id == aid, Agent.is_deleted == False).first()
if not agent:
failed.append(AgentJoinResult(agent_id=aid, agent_name="未知"))
continue
success = self.wecom.add_bot_to_group(group_id, aid)
if success:
joined.append(AgentJoinResult(agent_id=aid, agent_name=agent.name))
else:
failed.append(AgentJoinResult(agent_id=aid, agent_name=agent.name))
current_agents = group.agent_ids or []
for j in joined:
if j.agent_id not in current_agents:
current_agents.append(j.agent_id)
group.agent_ids = current_agents
self.db.commit()
return AgentJoinResponse(
success=len(failed) == 0,
joined_agents=joined,
failed_agents=failed,
)
def dissolve_group(self, group_id: str, reason: str = "") -> None:
group = self.db.query(CustomerGroup).filter(CustomerGroup.group_id == group_id).first()
if not group:
raise ValueError("群聊不存在")
if group.status == "dissolved":
raise ValueError("群聊已解散")
self.wecom.dissolve_group(group_id)
group.status = "dissolved"
group.dissolved_at = datetime.now(timezone.utc)
group.dissolution_reason = reason
self.db.commit()
def list_groups(
self,
page: int = 1,
page_size: int = 20,
customer_user_id: Optional[str] = None,
employee_id: Optional[str] = None,
position_code: Optional[str] = None,
status: Optional[str] = None,
created_time_start: Optional[datetime] = None,
created_time_end: Optional[datetime] = None,
) -> GroupListResponse:
query = self.db.query(CustomerGroup)
if customer_user_id:
query = query.filter(CustomerGroup.customer_user_id == customer_user_id)
if position_code:
query = query.filter(CustomerGroup.position_code == position_code)
if status:
query = query.filter(CustomerGroup.status == status)
if created_time_start:
query = query.filter(CustomerGroup.created_at >= created_time_start)
if created_time_end:
query = query.filter(CustomerGroup.created_at <= created_time_end)
total = query.count()
rows = query.order_by(CustomerGroup.created_at.desc()).offset((page - 1) * page_size).limit(page_size).all()
items = []
for r in rows:
emp_ids = r.employee_wechat_user_ids or []
emp_list = [EmployeeInfo(user_id=uid, name=uid) for uid in emp_ids]
a_ids = r.agent_ids or []
agents = self.db.query(Agent).filter(Agent.id.in_(a_ids)).all() if a_ids else []
agent_list = [AgentInfo(agent_id=a.id, name=a.name) for a in agents]
items.append(GroupListItem(
group_id=r.group_id,
group_name=r.group_name,
customer_info=CustomerInfo(user_id=r.customer_user_id, nickname=r.customer_nickname),
employee_list=emp_list,
agent_list=agent_list,
status=r.status,
created_at=r.created_at,
dissolved_at=r.dissolved_at,
dissolution_reason=r.dissolution_reason,
))
return GroupListResponse(total=total, list=items)
def _build_create_response(self, group: CustomerGroup) -> CreateGroupResponse:
emp_ids = group.employee_wechat_user_ids or []
members = [GroupMemberInfo(user_id=uid, name=uid, type="employee") for uid in emp_ids]
members.append(GroupMemberInfo(
user_id=group.customer_user_id,
name=group.customer_nickname or "客户",
type="customer",
))
return CreateGroupResponse(
group_id=group.group_id,
group_name=group.group_name,
creator_employee_id=group.creator_employee_id,
created_at=group.created_at,
members=members,
)
from __future__ import annotations
from typing import Optional
from app.infrastructure.file_parser import FileParser, OSSClient
from app.schema.routing import FileUploadResponse
_ALLOWED_EXTENSIONS = {".pdf", ".png", ".jpg", ".jpeg", ".doc", ".docx", ".xls", ".xlsx"}
_DEFAULT_MAX_SIZE = 10 * 1024 * 1024
class FileService:
def __init__(
self,
oss: OSSClient,
parser: FileParser,
max_size_bytes: int = _DEFAULT_MAX_SIZE,
) -> None:
self.oss = oss
self.parser = parser
self.max_size_bytes = max_size_bytes
def upload_and_extract(
self,
file_data: bytes,
file_name: str,
content_type: str,
session_id: str,
) -> FileUploadResponse:
ext = _get_extension(file_name)
if ext not in _ALLOWED_EXTENSIONS:
raise ValueError(f"不支持的文件格式: {ext}")
if len(file_data) > self.max_size_bytes:
raise ValueError(f"文件大小超过限制 ({self.max_size_bytes // (1024*1024)}MB)")
file_url = self.oss.upload(file_data, file_name, content_type)
extracted_text: Optional[str] = None
if ext in {".pdf", ".doc", ".docx", ".xls", ".xlsx"}:
extracted_text = self.parser.extract_text(file_url, file_name)
return FileUploadResponse(
file_url=file_url,
file_name=file_name,
file_size=len(file_data),
extracted_text=extracted_text,
session_id=session_id,
)
def _get_extension(file_name: str) -> str:
dot_idx = file_name.rfind(".")
if dot_idx == -1:
return ""
return file_name[dot_idx:].lower()
from __future__ import annotations
from datetime import datetime, timezone
from sqlalchemy.orm import Session as OrmSession
from app.infrastructure.h5_cache import H5CacheManager
from app.model.methodology import OfficialSiteMethodology, OfficialSiteMethodologyStep
from app.schema.methodology import (
GetMethodologyResponse,
MethodologyStepItem,
SaveMethodologyRequest,
SaveMethodologyResponse,
)
_MIN_STEPS = 4
_MAX_STEPS = 10
_MAX_STEP_NAME_LEN = 20
_MAX_MAIN_TITLE_LEN = 100
_MAX_SUB_TITLE_LEN = 200
class MethodologyService:
def __init__(self, db: OrmSession, cache: H5CacheManager) -> None:
self.db = db
self.cache = cache
def get_methodology(self) -> GetMethodologyResponse:
cfg = self.db.query(OfficialSiteMethodology).order_by(OfficialSiteMethodology.id.desc()).first()
if not cfg:
return GetMethodologyResponse(
config_id=0,
display_status="enable",
main_title="方法论",
sub_title="",
steps=[],
updated_at=datetime.now(timezone.utc),
)
steps = (
self.db.query(OfficialSiteMethodologyStep)
.filter(OfficialSiteMethodologyStep.methodology_id == cfg.id)
.order_by(OfficialSiteMethodologyStep.step_order.asc())
.all()
)
return GetMethodologyResponse(
config_id=cfg.id,
display_status=cfg.display_status,
main_title=cfg.main_title,
sub_title=cfg.sub_title,
steps=[
MethodologyStepItem(
step_id=s.id,
step_icon=s.step_icon or "",
step_name=s.step_name,
step_order=s.step_order,
step_image=s.step_image or "",
)
for s in steps
],
updated_at=cfg.updated_at,
)
def save_methodology(self, req: SaveMethodologyRequest) -> SaveMethodologyResponse:
step_count = len(req.steps)
if step_count < _MIN_STEPS or step_count > _MAX_STEPS:
raise ValueError(f"步骤数量必须在 {_MIN_STEPS}-{_MAX_STEPS} 之间")
orders = sorted(s.step_order for s in req.steps)
expected = list(range(1, step_count + 1))
if orders != expected:
raise ValueError("步骤序号必须从 1 开始且连续")
if len({s.step_order for s in req.steps}) != step_count:
raise ValueError("步骤序号不能重复")
cfg = self.db.query(OfficialSiteMethodology).order_by(OfficialSiteMethodology.id.desc()).first()
if not cfg:
cfg = OfficialSiteMethodology()
self.db.add(cfg)
self.db.flush()
cfg.display_status = req.display_status
cfg.main_title = req.main_title
cfg.sub_title = req.sub_title
self.db.flush()
self.db.query(OfficialSiteMethodologyStep).filter(
OfficialSiteMethodologyStep.methodology_id == cfg.id
).delete()
for s in req.steps:
step = OfficialSiteMethodologyStep(
methodology_id=cfg.id,
step_icon=s.step_icon,
step_name=s.step_name,
step_order=s.step_order,
step_image=s.step_image,
)
self.db.add(step)
self.db.commit()
self.db.refresh(cfg)
self.cache.invalidate_home_page()
return SaveMethodologyResponse(config_id=cfg.id, updated_at=cfg.updated_at)
\ No newline at end of file \ No newline at end of file
from __future__ import annotations
from datetime import datetime, timezone
from typing import Optional
from sqlalchemy.orm import Session as OrmSession
from app.infrastructure.h5_cache import H5CacheManager
from app.model.agent import Agent, AgentPosition, AgentStatus
from app.model.agent_group import QrcodeChannel
from app.model.official_site_agent_display import OfficialSiteAgentDisplay
from app.model.position_tag import OfficialTab, PositionTag
from app.schema.official_site_agent_display import (
AvailableAgentItem,
AvailableAgentsResponse,
ConfiguredAgentItem,
ConfiguredAgentsResponse,
DeleteAgentConfigResponse,
SaveAgentConfigRequest,
SaveAgentConfigResponse,
StewardAgentInfo,
)
_STEWARD_CODE = "steward"
_ALLOWED_MEDIA_TYPES = {"gif", "mp4"}
_MAX_MEDIA_SIZE = 20971520
_MAX_SPEECH_TITLE_LEN = 100
_MAX_SPEECH_CONTENT_LEN = 200
class OfficialSiteAgentDisplayService:
def __init__(self, db: OrmSession, cache: H5CacheManager) -> None:
self.db = db
self.cache = cache
def list_available_agents(self, tab_id: int) -> AvailableAgentsResponse:
tab = self.db.query(OfficialTab).filter(OfficialTab.id == tab_id, OfficialTab.deleted_at.is_(None)).first()
if not tab:
raise ValueError("Tab不存在")
position_agents = (
self.db.query(Agent)
.join(AgentPosition, AgentPosition.agent_id == Agent.id)
.filter(AgentPosition.position_id == tab.position_id, Agent.is_deleted == False)
.all()
)
steward = self.db.query(Agent).filter(Agent.code == _STEWARD_CODE, Agent.is_deleted == False).first()
existing_configs = self.db.query(OfficialSiteAgentDisplay).filter(
OfficialSiteAgentDisplay.tab_id == tab_id
).all()
configured_agent_ids = {c.agent_id for c in existing_configs}
available_items = []
for agent in position_agents:
if agent.code == _STEWARD_CODE:
continue
is_configured = agent.id in configured_agent_ids
description = None
if is_configured:
cfg = next(c for c in existing_configs if c.agent_id == agent.id)
description = cfg.speech_title
available_items.append(AvailableAgentItem(
agent_id=agent.id,
agent_name=agent.name,
agent_code=agent.code,
is_configured=is_configured,
configured_description=description,
is_steward=False,
))
steward_info = None
if steward:
steward_info = StewardAgentInfo(
agent_id=steward.id,
agent_name=steward.name,
note="管家 Agent 不参与官网展示",
)
return AvailableAgentsResponse(
tab_id=tab_id,
position_name=tab.position_name or "",
qrcode_id=tab.qrcode_id,
available_agents=available_items,
steward_agent=steward_info,
)
def save_config(self, tab_id: int, agent_id: int, req: SaveAgentConfigRequest) -> SaveAgentConfigResponse:
tab = self.db.query(OfficialTab).filter(OfficialTab.id == tab_id, OfficialTab.deleted_at.is_(None)).first()
if not tab:
raise ValueError("Tab不存在")
if req.media_type not in _ALLOWED_MEDIA_TYPES:
raise ValueError(f"素材格式不支持,仅允许 {_ALLOWED_MEDIA_TYPES}")
if req.media_size > _MAX_MEDIA_SIZE:
raise ValueError("素材大小超过 20MB 限制")
if len(req.speech_title) > _MAX_SPEECH_TITLE_LEN:
raise ValueError("话术标题超过限制")
if len(req.speech_content) > _MAX_SPEECH_CONTENT_LEN:
raise ValueError("话术正文超过限制")
available = self.list_available_agents(tab_id)
valid_ids = {a.agent_id for a in available.available_agents}
if agent_id not in valid_ids:
raise ValueError("该Agent不在可配置列表中")
existing = self.db.query(OfficialSiteAgentDisplay).filter(
OfficialSiteAgentDisplay.tab_id == tab_id,
OfficialSiteAgentDisplay.agent_id == agent_id,
).first()
if existing:
config = existing
else:
config = OfficialSiteAgentDisplay(tab_id=tab_id, agent_id=agent_id)
self.db.add(config)
self.db.flush()
config.media_url = req.media_url
config.media_type = req.media_type
config.speech_title = req.speech_title
config.speech_content = req.speech_content
config.display_status = req.display_status
config.sort_order = req.sort_order
self.db.commit()
self.db.refresh(config)
self.cache.invalidate_home_page()
return SaveAgentConfigResponse(
config_id=config.id,
tab_id=config.tab_id,
agent_id=config.agent_id,
updated_at=config.updated_at,
)
def list_configured_agents(self, tab_id: int) -> ConfiguredAgentsResponse:
tab = self.db.query(OfficialTab).filter(OfficialTab.id == tab_id, OfficialTab.deleted_at.is_(None)).first()
if not tab:
raise ValueError("Tab不存在")
configs = (
self.db.query(OfficialSiteAgentDisplay)
.filter(OfficialSiteAgentDisplay.tab_id == tab_id)
.order_by(OfficialSiteAgentDisplay.sort_order.asc(), OfficialSiteAgentDisplay.id.asc())
.all()
)
items = []
for c in configs:
agent = self.db.query(Agent).filter(Agent.id == c.agent_id).first()
items.append(ConfiguredAgentItem(
config_id=c.id,
agent_id=c.agent_id,
agent_name=agent.name if agent else "未知",
media_url=c.media_url,
media_type=c.media_type,
speech_title=c.speech_title,
speech_content=c.speech_content,
display_status=c.display_status,
sort_order=c.sort_order,
agent_status=agent.status.value if agent else "unknown",
))
return ConfiguredAgentsResponse(tab_id=tab_id, configured_agents=items)
def delete_config(self, tab_id: int, agent_id: int) -> DeleteAgentConfigResponse:
config = self.db.query(OfficialSiteAgentDisplay).filter(
OfficialSiteAgentDisplay.tab_id == tab_id,
OfficialSiteAgentDisplay.agent_id == agent_id,
).first()
if not config:
raise ValueError("配置不存在")
self.db.delete(config)
self.db.commit()
self.cache.invalidate_home_page()
return DeleteAgentConfigResponse(success=True, deleted_at=datetime.now(timezone.utc))
\ No newline at end of file \ No newline at end of file
from __future__ import annotations
from sqlalchemy.orm import Session as OrmSession
from app.infrastructure.h5_cache import H5CacheManager
from app.model.agent import Agent, AgentStatus
from app.model.agent_group import QrcodeChannel
from app.model.methodology import OfficialSiteMethodology, OfficialSiteMethodologyStep
from app.model.official_site_agent_display import OfficialSiteAgentDisplay
from app.model.position_tag import OfficialTab
from app.schema.official_site_home import (
H5HomeAgentItem,
H5HomeMethodologyItem,
H5HomeMethodologyStep,
H5HomeResponse,
H5HomeTabItem,
)
_CACHE_TTL = 300
class H5HomeService:
def __init__(self, db: OrmSession, cache: H5CacheManager) -> None:
self.db = db
self.cache = cache
def get_home_data(self) -> H5HomeResponse:
cached = self.cache.get_home_page()
if cached is not None:
return H5HomeResponse.model_validate_json(cached)
response = self._build_home_data()
self.cache.set_home_page(response.model_dump_json(), _CACHE_TTL)
return response
def _build_home_data(self) -> H5HomeResponse:
tabs_data = self._build_tabs()
methodology = self._build_methodology()
return H5HomeResponse(
site_title="岗位 Agent 管理后台",
site_subtitle="AI 驱动的智能销售服务体系",
background_image="https://cdn.xxx.com/bg.jpg",
tabs=tabs_data,
methodology=methodology,
)
def _build_tabs(self) -> list[H5HomeTabItem]:
active_tabs = (
self.db.query(OfficialTab)
.filter(OfficialTab.display_status == "enable", OfficialTab.deleted_at.is_(None))
.order_by(OfficialTab.sort_order.asc())
.all()
)
result = []
for tab in active_tabs:
qrcode_url = None
qrcode_status = None
if tab.qrcode_id:
qr = self.db.query(QrcodeChannel).filter(QrcodeChannel.id == tab.qrcode_id).first()
if qr:
qrcode_url = qr.qrcode_url
qrcode_status = qr.status
display_configs = (
self.db.query(OfficialSiteAgentDisplay)
.filter(
OfficialSiteAgentDisplay.tab_id == tab.id,
OfficialSiteAgentDisplay.display_status == "enable",
)
.order_by(OfficialSiteAgentDisplay.sort_order.asc())
.all()
)
agent_items = []
for dc in display_configs:
agent = self.db.query(Agent).filter(Agent.id == dc.agent_id, Agent.is_deleted == False).first()
if not agent or agent.status != AgentStatus.enable:
continue
agent_items.append(H5HomeAgentItem(
agent_id=agent.id,
agent_name=agent.name,
media_url=dc.media_url,
media_type=dc.media_type,
speech_title=dc.speech_title,
speech_content=dc.speech_content,
status="active",
))
result.append(H5HomeTabItem(
tab_id=tab.id,
position_code=tab.position_code or "",
position_name=tab.position_name or "",
qrcode_url=qrcode_url,
qrcode_status=qrcode_status,
agents=agent_items,
))
return result
def _build_methodology(self) -> H5HomeMethodologyItem:
cfg = self.db.query(OfficialSiteMethodology).filter(
OfficialSiteMethodology.display_status == "enable"
).order_by(OfficialSiteMethodology.id.desc()).first()
if not cfg:
return H5HomeMethodologyItem(
display_status="disable",
main_title="",
sub_title="",
steps=[],
)
steps = (
self.db.query(OfficialSiteMethodologyStep)
.filter(OfficialSiteMethodologyStep.methodology_id == cfg.id)
.order_by(OfficialSiteMethodologyStep.step_order.asc())
.all()
)
return H5HomeMethodologyItem(
display_status=cfg.display_status,
main_title=cfg.main_title,
sub_title=cfg.sub_title,
steps=[
H5HomeMethodologyStep(
step_icon=s.step_icon or "",
step_name=s.step_name,
step_image=s.step_image or "",
)
for s in steps
],
)
\ No newline at end of file \ No newline at end of file
from __future__ import annotations
from datetime import datetime, timezone
from typing import Optional
from sqlalchemy import or_
from sqlalchemy.orm import Session as OrmSession
from app.infrastructure.h5_cache import H5CacheManager
from app.model.agent_group import QrcodeChannel
from app.model.position_tag import PositionTag, OfficialTab
from app.schema.official_site_tab import (
AvailableQrcodeItem,
AvailableQrcodeListResponse,
CreateTabRequest,
CreateTabResponse,
DeleteTabResponse,
TabListItem,
TabListResponse,
UpdateTabRequest,
UpdateTabResponse,
UpdateTabStatusRequest,
UpdateTabStatusResponse,
)
class OfficialSiteTabService:
def __init__(self, db: OrmSession, cache: H5CacheManager) -> None:
self.db = db
self.cache = cache
def create(self, req: CreateTabRequest) -> CreateTabResponse:
position = self.db.query(PositionTag).filter(PositionTag.code == req.position_code).first()
if not position:
raise ValueError("岗位不存在")
qr = self.db.query(QrcodeChannel).filter(QrcodeChannel.id == req.qrcode_id).first()
if not qr or qr.status != "enable":
raise ValueError("活码不存在或已停用")
tab = OfficialTab(
tab_name=req.position_name,
position_code=req.position_code,
position_name=req.position_name,
position_id=position.id,
qrcode_id=req.qrcode_id,
display_status=req.display_status,
sort_order=req.sort_order,
created_by="admin",
)
self.db.add(tab)
self.db.commit()
self.db.refresh(tab)
self.cache.invalidate_home_page()
return CreateTabResponse(
tab_id=tab.id,
position_code=tab.position_code or "",
position_name=tab.position_name or "",
qrcode_id=tab.qrcode_id or 0,
created_at=tab.created_at,
)
def update(self, tab_id: int, req: UpdateTabRequest) -> UpdateTabResponse:
tab = self._get_or_404(tab_id)
if req.qrcode_id != tab.qrcode_id:
qr = self.db.query(QrcodeChannel).filter(QrcodeChannel.id == req.qrcode_id).first()
if not qr or qr.status != "enable":
raise ValueError("活码不存在或已停用")
tab.position_name = req.position_name
tab.tab_name = req.position_name
tab.qrcode_id = req.qrcode_id
tab.display_status = req.display_status
tab.sort_order = req.sort_order
self.db.commit()
self.db.refresh(tab)
self.cache.invalidate_home_page()
return UpdateTabResponse(success=True, updated_at=tab.updated_at)
def delete(self, tab_id: int) -> DeleteTabResponse:
tab = self._get_or_404(tab_id)
now = datetime.now(timezone.utc)
cleaned = 0
tab.deleted_at = now
self.db.commit()
self.cache.invalidate_home_page()
return DeleteTabResponse(success=True, deleted_at=now, cleaned_agent_configs=cleaned)
def update_status(self, tab_id: int, req: UpdateTabStatusRequest) -> UpdateTabStatusResponse:
tab = self._get_or_404(tab_id)
prev = tab.display_status
tab.display_status = req.display_status
self.db.commit()
self.db.refresh(tab)
self.cache.invalidate_home_page()
return UpdateTabStatusResponse(
success=True,
previous_status=prev,
updated_at=tab.updated_at,
)
def list_tabs(
self,
page: int = 1,
page_size: int = 20,
keyword: Optional[str] = None,
display_status: Optional[str] = None,
) -> TabListResponse:
query = self.db.query(OfficialTab).filter(OfficialTab.deleted_at.is_(None))
if keyword:
query = query.filter(
or_(
OfficialTab.position_name.like(f"%{keyword}%"),
OfficialTab.position_code.like(f"%{keyword}%"),
)
)
if display_status:
query = query.filter(OfficialTab.display_status == display_status)
total = query.count()
rows = query.order_by(OfficialTab.sort_order.asc(), OfficialTab.id.asc()).offset((page - 1) * page_size).limit(page_size).all()
items = []
for r in rows:
qr_url = None
qr_status = None
if r.qrcode_id:
qr = self.db.query(QrcodeChannel).filter(QrcodeChannel.id == r.qrcode_id).first()
if qr:
qr_url = qr.qrcode_url
qr_status = qr.status
operations = ["查看", "编辑"]
if r.display_status == "enable":
operations.append("下架")
else:
operations.append("上架")
items.append(TabListItem(
tab_id=r.id,
position_code=r.position_code or "",
position_name=r.position_name or "",
qrcode_id=r.qrcode_id,
qrcode_url=qr_url,
qrcode_status=qr_status,
display_status=r.display_status,
sort_order=r.sort_order,
agent_count=0,
created_at=r.created_at,
operations=operations,
))
return TabListResponse(total=total, page=page, page_size=page_size, list=items)
def list_available_qrcodes(
self,
position_code: Optional[str] = None,
) -> AvailableQrcodeListResponse:
query = self.db.query(QrcodeChannel).filter(QrcodeChannel.status == "enable")
if position_code:
query = query.filter(QrcodeChannel.position_code == position_code)
rows = query.order_by(QrcodeChannel.id.asc()).all()
items = [
AvailableQrcodeItem(
qrcode_id=qr.id,
channel_code=qr.channel_code,
employee_name=qr.employee_name,
position_name=qr.position_name,
status=qr.status,
)
for qr in rows
]
return AvailableQrcodeListResponse(list=items)
def _get_or_404(self, tab_id: int) -> OfficialTab:
tab = self.db.query(OfficialTab).filter(
OfficialTab.id == tab_id,
OfficialTab.deleted_at.is_(None),
).first()
if not tab:
raise ValueError("Tab不存在")
return tab
from __future__ import annotations
import struct
from datetime import datetime, timezone
from typing import Optional
from app.infrastructure.file_parser import OSSClient
from app.schema.official_site_upload import UploadMediaResponse
_USAGE_RULES = {
"agent_media": {"exts": {"gif", "mp4"}, "max_size": 20 * 1024 * 1024, "dir": "agent"},
"methodology_icon": {"exts": {"png", "jpg", "jpeg"}, "max_size": 2 * 1024 * 1024, "dir": "methodology/icon"},
"methodology_image": {"exts": {"png", "jpg", "jpeg"}, "max_size": 10 * 1024 * 1024, "dir": "methodology/image"},
}
class OfficialSiteUploadService:
def __init__(self, oss: OSSClient) -> None:
self.oss = oss
def upload(self, file_data: bytes, file_name: str, usage_type: str) -> UploadMediaResponse:
rules = _USAGE_RULES.get(usage_type)
if not rules:
raise ValueError(f"不支持的上传类型: {usage_type}")
ext = _get_extension(file_name)
if ext not in rules["exts"]:
raise ValueError(f"文件格式不支持,仅允许 {rules['exts']}")
if len(file_data) > rules["max_size"]:
size_limit_mb = rules["max_size"] // (1024 * 1024)
raise ValueError(f"文件大小超过 {size_limit_mb}MB 限制")
version = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
upload_name = f"{rules['dir']}/{version}_{file_name}"
file_url = self.oss.upload(file_data, upload_name, _content_type_for_ext(ext))
cdn_url = f"{file_url}?v={datetime.now(timezone.utc).strftime('%Y%m%d')}"
width, height = _get_dimensions(file_data, ext)
return UploadMediaResponse(
file_url=file_url,
file_type=ext,
file_size=len(file_data),
width=width,
height=height,
cdn_url=cdn_url,
)
def _get_extension(file_name: str) -> str:
dot_idx = file_name.rfind(".")
if dot_idx == -1:
return ""
return file_name[dot_idx + 1:].lower()
def _content_type_for_ext(ext: str) -> str:
mapping = {"gif": "image/gif", "mp4": "video/mp4", "png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg"}
return mapping.get(ext, "application/octet-stream")
def _get_dimensions(data: bytes, ext: str) -> tuple[Optional[int], Optional[int]]:
if ext == "png":
try:
if len(data) >= 24 and data[1:4] == b"PNG":
w = struct.unpack(">I", data[16:20])[0]
h = struct.unpack(">I", data[20:24])[0]
return w, h
except Exception:
pass
elif ext in ("jpg", "jpeg"):
try:
idx = 2
while idx < len(data) - 2:
marker = data[idx]
if marker != 0xFF:
break
seg_type = data[idx + 1]
if seg_type == 0xC0 or (0xC0 <= seg_type <= 0xC3) or (0xC5 <= seg_type <= 0xCF):
if len(data) >= idx + 9:
h = struct.unpack(">H", data[idx + 5:idx + 7])[0]
w = struct.unpack(">H", data[idx + 7:idx + 9])[0]
return w, h
if idx + 2 < len(data):
seg_len = struct.unpack(">H", data[idx + 2:idx + 4])[0]
idx += seg_len + 2
else:
break
except Exception:
pass
return None, None
\ No newline at end of file \ No newline at end of file
from __future__ import annotations
from datetime import datetime, timezone, timedelta
from typing import Optional
from sqlalchemy import or_
from sqlalchemy.orm import Session as OrmSession
from app.infrastructure.file_parser import OSSClient
from app.model.agent import Agent, AgentPosition, AgentStatus
from app.model.agent_group import QrcodeChannel
from app.model.position_tag import PositionTag
from app.schema.qrcode_channel import (
QrcodeBatchStatusResponse,
QrcodeCreateResponse,
QrcodeDetailResponse,
QrcodeDisableResponse,
QrcodeEnableResponse,
QrcodeListItem,
QrcodeListResponse,
QrcodeUpdateResponse,
QrcodeExportResponse,
)
from app.service.agent_group_helper_service import WeComClient
class QrcodeChannelService:
def __init__(self, db: OrmSession, wecom: WeComClient, oss: Optional[OSSClient] = None):
self.db = db
self.wecom = wecom
self.oss = oss
def create(self, req) -> QrcodeCreateResponse:
position = self.db.query(PositionTag).filter(
PositionTag.code == req.position_code
).first()
if not position:
raise ValueError("岗位不存在")
existing = self.db.query(QrcodeChannel).filter(
QrcodeChannel.position_code == req.position_code,
QrcodeChannel.employee_id == req.employee_id,
).first()
if existing:
raise ValueError("该员工已存在同岗位活码")
steward = self.db.query(Agent).filter(
Agent.code == "steward",
Agent.is_deleted == False,
).first()
position_agents = (
self.db.query(Agent)
.join(AgentPosition, AgentPosition.agent_id == Agent.id)
.filter(AgentPosition.position_id == position.id, Agent.is_deleted == False, Agent.status == AgentStatus.enable)
.all()
)
agent_list = list(position_agents)
if steward and steward not in agent_list:
agent_list.insert(0, steward)
agent_ids = [a.id for a in agent_list]
agent_names = [a.name for a in agent_list]
channel_code = f"zdxs_{req.position_code}_{req.employee_id}"
qrcode_url = self.wecom.create_qrcode(channel_code, req.welcome_message or "")
qr = QrcodeChannel(
qrcode_name=req.qrcode_name,
position_code=req.position_code,
position_name=position.name,
employee_id=req.employee_id,
employee_name=req.employee_name,
wechat_user_id=req.wechat_user_id,
channel_code=channel_code,
qrcode_url=qrcode_url,
agent_ids=agent_ids,
agent_names=agent_names,
remark=req.remark,
welcome_message=req.welcome_message,
created_by="admin",
)
self.db.add(qr)
self.db.commit()
self.db.refresh(qr)
return QrcodeCreateResponse(
qrcode_id=qr.id,
qrcode_name=qr.qrcode_name or "",
qrcode_url=qr.qrcode_url or "",
channel_code=qr.channel_code,
status=qr.status,
agent_ids=agent_ids,
agent_names=agent_names,
created_at=qr.created_at,
)
def update(self, qrcode_id: int, req) -> QrcodeUpdateResponse:
qr = self._get_or_404(qrcode_id)
qr.qrcode_name = req.qrcode_name
qr.remark = req.remark
qr.welcome_message = req.welcome_message
self.db.commit()
self.db.refresh(qr)
return QrcodeUpdateResponse(success=True, updated_at=qr.updated_at)
def get_detail(self, qrcode_id: int) -> QrcodeDetailResponse:
qr = self._get_or_404(qrcode_id)
position_name = qr.position_name
if qr.position_code:
pos = self.db.query(PositionTag).filter(PositionTag.code == qr.position_code).first()
if pos:
position_name = pos.name
return QrcodeDetailResponse(
qrcode_id=qr.id,
qrcode_name=qr.qrcode_name,
employee_id=qr.employee_id,
employee_name=qr.employee_name,
position_code=qr.position_code,
position_name=position_name,
channel_code=qr.channel_code,
qrcode_url=qr.qrcode_url,
agent_ids=qr.agent_ids or [],
agent_names=qr.agent_names or [],
remark=qr.remark,
welcome_message=qr.welcome_message,
status=qr.status,
created_at=qr.created_at,
created_by=qr.created_by,
updated_at=qr.updated_at,
)
def list_qrcodes(
self,
page: int = 1,
page_size: int = 20,
employee_name: Optional[str] = None,
position_code: Optional[str] = None,
status: Optional[str] = None,
keyword: Optional[str] = None,
) -> QrcodeListResponse:
query = self.db.query(QrcodeChannel)
if employee_name:
query = query.filter(QrcodeChannel.employee_name.like(f"%{employee_name}%"))
if position_code:
query = query.filter(QrcodeChannel.position_code == position_code)
if status:
query = query.filter(QrcodeChannel.status == status)
if keyword:
query = query.filter(
or_(
QrcodeChannel.employee_name.like(f"%{keyword}%"),
QrcodeChannel.position_name.like(f"%{keyword}%"),
QrcodeChannel.channel_code.like(f"%{keyword}%"),
)
)
total = query.count()
rows = query.order_by(QrcodeChannel.id.desc()).offset((page - 1) * page_size).limit(page_size).all()
items = []
for r in rows:
agent_ids = r.agent_ids or []
agent_names = r.agent_names or []
items.append(QrcodeListItem(
qrcode_id=r.id,
employee_name=r.employee_name,
position_name=r.position_name,
channel_code=r.channel_code,
qrcode_url=r.qrcode_url,
agent_count=len(agent_ids),
agent_names_preview=agent_names[:3],
status=r.status,
created_at=r.created_at,
))
return QrcodeListResponse(total=total, page=page, page_size=page_size, list=items)
def export(self, req) -> QrcodeExportResponse:
query = self.db.query(QrcodeChannel)
if req.filter_conditions:
if req.filter_conditions.get("position_code"):
query = query.filter(QrcodeChannel.position_code == req.filter_conditions["position_code"])
if req.filter_conditions.get("status"):
query = query.filter(QrcodeChannel.status == req.filter_conditions["status"])
rows = query.order_by(QrcodeChannel.id.asc()).all()
fields = req.export_fields or ["employee_name", "position_name", "channel_code", "status"]
header = ",".join(fields)
lines = [header]
for r in rows:
vals = []
for f in fields:
if f == "employee_name":
vals.append(r.employee_name)
elif f == "position_name":
vals.append(r.position_name)
elif f == "channel_code":
vals.append(r.channel_code)
elif f == "status":
vals.append(r.status)
elif f == "agent_names":
vals.append(";".join(r.agent_names or []))
else:
vals.append("")
lines.append(",".join(vals))
csv_data = "\n".join(lines).encode("utf-8-sig")
now = datetime.now(timezone.utc)
file_name = f"qrcode_export_{now.strftime('%Y%m%d_%H%M%S')}.csv"
file_url = ""
if self.oss:
file_url = self.oss.upload(csv_data, file_name, "text/csv")
else:
file_url = f"https://oss.example.com/export/{file_name}"
return QrcodeExportResponse(
file_url=file_url,
file_name=file_name,
total_count=len(rows),
expires_at=now + timedelta(hours=24),
)
def disable(self, qrcode_id: int, reason: str) -> QrcodeDisableResponse:
qr = self._get_or_404(qrcode_id)
prev = qr.status
qr.status = "disable"
qr.disable_reason = reason
self.db.commit()
return QrcodeDisableResponse(success=True, disabled_at=datetime.now(timezone.utc), previous_status=prev)
def enable(self, qrcode_id: int) -> QrcodeEnableResponse:
qr = self._get_or_404(qrcode_id)
prev = qr.status
qr.status = "enable"
qr.disable_reason = None
self.db.commit()
return QrcodeEnableResponse(success=True, enabled_at=datetime.now(timezone.utc), previous_status=prev)
def batch_status(self, qrcode_ids: list[int], target_status: str, reason: Optional[str] = None) -> QrcodeBatchStatusResponse:
success = 0
failed = []
for qid in qrcode_ids:
try:
if target_status == "disable":
self.disable(qid, reason or "")
else:
self.enable(qid)
success += 1
except Exception as e:
failed.append({"qrcode_id": qid, "error": str(e)})
return QrcodeBatchStatusResponse(success_count=success, failed_count=len(failed), failed_list=failed)
def _get_or_404(self, qrcode_id: int) -> QrcodeChannel:
qr = self.db.query(QrcodeChannel).filter(QrcodeChannel.id == qrcode_id).first()
if not qr:
raise ValueError("渠道活码不存在")
return qr
from __future__ import annotations
from datetime import datetime, timezone
from typing import Optional
from sqlalchemy.orm import Session as OrmSession
from app.infrastructure.llm_client import LLMClient
from app.infrastructure.session_store import SessionStore
from app.model.agent import Agent
from app.schema.routing import (
ChatCompletionResponse,
HandoffInfo,
IntentInfo,
RoutingInfo,
)
_STEWARD_CODE = "steward"
class RoutingService:
def __init__(self, db: OrmSession, session_store: SessionStore, llm: LLMClient) -> None:
self.db = db
self.session_store = session_store
self.llm = llm
def route(
self,
session_id: str,
user_id: str,
channel: str,
query: str,
mentioned_agent_code: Optional[str] = None,
) -> ChatCompletionResponse:
now = datetime.now(timezone.utc)
target_agent: Optional[Agent] = None
routing_reason: str = ""
prev_agent_id: Optional[int] = None
intent_info: Optional[IntentInfo] = None
if mentioned_agent_code:
agent = self.db.query(Agent).filter(
Agent.code == mentioned_agent_code,
Agent.is_deleted == False,
).first()
if not agent:
raise ValueError(f"Agent不存在: {mentioned_agent_code}")
target_agent = agent
routing_reason = "mention"
existing = self.session_store.get(session_id)
if existing and existing.get("current_agent_id"):
prev_agent_id = existing["current_agent_id"]
else:
existing = self.session_store.get(session_id)
if existing and existing.get("current_agent_id"):
inherited_id = existing["current_agent_id"]
agent = self.db.query(Agent).filter(
Agent.id == inherited_id,
Agent.is_deleted == False,
).first()
if agent:
prev_agent_id = inherited_id
target_agent = agent
routing_reason = "inheritance"
if not target_agent:
steward = self.db.query(Agent).filter(
Agent.code == _STEWARD_CODE,
Agent.is_deleted == False,
).first()
if not steward:
raise ValueError("管家Agent未配置")
target_agent = steward
routing_reason = "default"
if routing_reason != "mention":
intent_str, confidence = self.llm.recognize_intent(query)
intent_info = IntentInfo(intent=intent_str, confidence=confidence)
handoff: Optional[HandoffInfo] = None
if prev_agent_id is not None and prev_agent_id != target_agent.id:
from_agent = self.db.query(Agent).filter(Agent.id == prev_agent_id).first()
from_name = from_agent.name if from_agent else "未知"
handoff = HandoffInfo(
from_agent_id=prev_agent_id,
from_agent_name=from_name,
to_agent_id=target_agent.id,
to_agent_name=target_agent.name,
handoff_message=f"收到,已转交给{target_agent.name}处理。",
)
routing = RoutingInfo(
agent_id=target_agent.id,
agent_code=target_agent.code,
agent_name=target_agent.name,
routing_reason=routing_reason,
)
return ChatCompletionResponse(
session_id=session_id,
routing=routing,
intent=intent_info,
handoff=handoff,
created_at=now,
)
from __future__ import annotations
import json
import secrets
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Any, Optional
from sqlalchemy.orm import Session as OrmSession
from app.infrastructure.session_store import SESSION_TTL_SECONDS, SessionStore
from app.model.agent import Agent
from app.model.session import ConversationHistory, Session as DbSession, SessionStatus
from app.schema.session import (
SessionArchiveResponse,
SessionContextResponse,
SessionCreateRequest,
SessionCreateResponse,
SessionDetailResponse,
SessionHistoryTurn,
SessionUpdateRequest,
SessionUpdateResponse,
)
def _utcnow() -> datetime:
return datetime.now(timezone.utc)
def _gen_session_id() -> str:
return f"sess_{secrets.token_urlsafe(12)}"
def _merge_entities(base: dict[str, Any], incoming: Optional[dict[str, Any]]) -> dict[str, Any]:
if not incoming:
return base
merged = dict(base)
merged.update(incoming)
return merged
@dataclass(frozen=True)
class _ActiveSessionPayload:
session_id: str
user_id: str
channel: str
current_agent_id: int
conversation_history: list[dict[str, Any]]
context_entities: dict[str, Any]
created_at: str
updated_at: str
class SessionService:
def __init__(self, db: OrmSession, store: Optional[SessionStore] = None) -> None:
self.db = db
self.store = store or SessionStore()
def _default_agent_id(self) -> int:
agent = self.db.query(Agent).filter(Agent.is_deleted == False).order_by(Agent.id.asc()).first()
return agent.id if agent else 101
def create(self, req: SessionCreateRequest) -> SessionCreateResponse:
session_id = _gen_session_id()
now = _utcnow()
current_agent_id = self._default_agent_id()
payload = _ActiveSessionPayload(
session_id=session_id,
user_id=req.user_id,
channel=req.channel,
current_agent_id=current_agent_id,
conversation_history=[],
context_entities={},
created_at=now.isoformat(),
updated_at=now.isoformat(),
)
self.store.set(session_id, payload.__dict__)
return SessionCreateResponse(
session_id=session_id,
user_id=req.user_id,
channel=req.channel,
current_agent_id=current_agent_id,
created_at=now,
)
def append_and_merge(self, session_id: str, req: SessionUpdateRequest) -> SessionUpdateResponse:
existing = self.store.get(session_id)
if not existing:
raise ValueError("会话不存在或已超时")
now = _utcnow()
history: list[dict[str, Any]] = list(existing.get("conversation_history") or [])
history.append(
{
"role": req.role,
"content": req.content,
"agent_id": req.agent_id,
"intent": req.intent,
"timestamp": now.isoformat(),
}
)
entities = _merge_entities(existing.get("context_entities") or {}, req.entities or {})
existing["conversation_history"] = history
existing["context_entities"] = entities
existing["current_agent_id"] = req.agent_id
existing["updated_at"] = now.isoformat()
self.store.set(session_id, existing)
return SessionUpdateResponse(success=True, updated_at=now, turn_count=len(history))
def get_detail(self, session_id: str) -> SessionDetailResponse:
existing = self.store.get(session_id)
if existing:
agent_name = None
agent = self.db.query(Agent).filter(Agent.id == existing.get("current_agent_id")).first()
if agent:
agent_name = agent.name
history_items = []
for item in existing.get("conversation_history") or []:
history_items.append(
SessionHistoryTurn(
role=item["role"],
content=item["content"],
agent_id=item.get("agent_id"),
intent=item.get("intent"),
timestamp=datetime.fromisoformat(item["timestamp"]),
)
)
return SessionDetailResponse(
session_id=existing["session_id"],
user_id=existing["user_id"],
channel=existing["channel"],
current_agent_id=existing["current_agent_id"],
current_agent_name=agent_name,
conversation_history=history_items,
context_entities=existing.get("context_entities") or {},
created_at=datetime.fromisoformat(existing["created_at"]),
updated_at=datetime.fromisoformat(existing["updated_at"]),
)
db_sess = self.db.query(DbSession).filter(DbSession.session_id == session_id).first()
if not db_sess:
raise ValueError("会话不存在")
history_rows = (
self.db.query(ConversationHistory)
.filter(ConversationHistory.session_id == session_id)
.order_by(ConversationHistory.id.asc())
.all()
)
history_items = []
for row in history_rows:
history_items.append(
SessionHistoryTurn(
role=row.role,
content=row.content,
agent_id=row.agent_id,
intent=row.intent,
timestamp=row.timestamp.replace(tzinfo=timezone.utc) if row.timestamp.tzinfo is None else row.timestamp,
)
)
agent_name = None
agent = self.db.query(Agent).filter(Agent.id == db_sess.current_agent_id).first()
if agent:
agent_name = agent.name
# Archived sessions do not keep transient context_entities.
return SessionDetailResponse(
session_id=db_sess.session_id,
user_id=db_sess.user_id,
channel=db_sess.channel,
current_agent_id=db_sess.current_agent_id,
current_agent_name=agent_name,
conversation_history=history_items,
context_entities={},
created_at=db_sess.created_at.replace(tzinfo=timezone.utc) if db_sess.created_at.tzinfo is None else db_sess.created_at,
updated_at=db_sess.updated_at.replace(tzinfo=timezone.utc) if db_sess.updated_at.tzinfo is None else db_sess.updated_at,
)
def get_context(self, session_id: str) -> SessionContextResponse:
existing = self.store.get(session_id)
if not existing:
return SessionContextResponse(
session_id=session_id,
current_agent_id=0,
last_entities={},
inheritance_valid=False,
expires_at=None,
)
updated_at = datetime.fromisoformat(existing["updated_at"])
expires_at = updated_at + timedelta(seconds=SESSION_TTL_SECONDS)
return SessionContextResponse(
session_id=session_id,
current_agent_id=existing["current_agent_id"],
last_entities=existing.get("context_entities") or {},
inheritance_valid=True,
expires_at=expires_at,
)
def archive(self, session_id: str) -> SessionArchiveResponse:
existing = self.store.get(session_id)
if not existing:
raise ValueError("会话不存在或已超时")
now = _utcnow()
db_sess = self.db.query(DbSession).filter(DbSession.session_id == session_id).first()
if not db_sess:
db_sess = DbSession(
session_id=session_id,
user_id=existing["user_id"],
channel=existing["channel"],
current_agent_id=existing["current_agent_id"],
status=SessionStatus.archived.value,
)
self.db.add(db_sess)
else:
db_sess.status = SessionStatus.archived.value
db_sess.current_agent_id = existing["current_agent_id"]
for item in existing.get("conversation_history") or []:
self.db.add(
ConversationHistory(
session_id=session_id,
role=item["role"],
content=item["content"],
agent_id=item.get("agent_id"),
intent=item.get("intent"),
entities_json=json.dumps(existing.get("context_entities") or {}, ensure_ascii=False),
)
)
self.db.commit()
self.store.delete(session_id)
return SessionArchiveResponse(success=True, archived_at=now)
import json
from sqlalchemy.orm import Session
from app.model.skill import Skill
from app.schema.skill import SkillListItem, SkillDetailResponse
from app.infrastructure.cache import SkillCache, InMemorySkillCache
class SkillService:
def __init__(self, db: Session, cache: SkillCache):
self.db = db
self.cache = cache
def list_skills(self) -> list[SkillListItem]:
rows = self.db.query(Skill).order_by(Skill.priority.asc(), Skill.id.asc()).all()
return [SkillListItem.model_validate(row) for row in rows]
def get_detail(self, skill_code: str) -> SkillDetailResponse:
cached = self.cache.get(skill_code)
if cached is not None:
return SkillDetailResponse.model_validate_json(cached)
skill = self.db.query(Skill).filter(Skill.skill_code == skill_code).first()
if not skill:
raise ValueError("Skill不存在")
detail = SkillDetailResponse.model_validate(skill)
self.cache.set(skill_code, detail.model_dump_json())
return detail
-- 创建 qrcode_channels 表 -- 创建 qrcode_channels 表
CREATE TABLE IF NOT EXISTS qrcode_channels ( CREATE TABLE IF NOT EXISTS qrcode_channels (
id INT AUTO_INCREMENT PRIMARY KEY, id INT AUTO_INCREMENT PRIMARY KEY,
qrcode_name VARCHAR(50) DEFAULT NULL COMMENT '活码名称',
position_code VARCHAR(100) DEFAULT NULL COMMENT '岗位编码',
position_name VARCHAR(100) NOT NULL DEFAULT '' COMMENT '岗位名称',
employee_id VARCHAR(100) NOT NULL COMMENT '员工ID', employee_id VARCHAR(100) NOT NULL COMMENT '员工ID',
employee_name VARCHAR(100) NOT NULL DEFAULT '' COMMENT '员工姓名', employee_name VARCHAR(100) NOT NULL DEFAULT '' COMMENT '员工姓名',
position_name VARCHAR(100) NOT NULL COMMENT '岗位名称', wechat_user_id VARCHAR(100) DEFAULT NULL COMMENT '企微UserID',
channel_code VARCHAR(100) NOT NULL UNIQUE COMMENT '渠道编码', channel_code VARCHAR(100) NOT NULL UNIQUE COMMENT '渠道编码',
qrcode_url VARCHAR(500) DEFAULT NULL COMMENT '二维码URL',
agent_ids JSON DEFAULT NULL COMMENT '关联Agent ID列表',
agent_names JSON DEFAULT NULL COMMENT '关联Agent名称列表',
remark VARCHAR(200) DEFAULT NULL COMMENT '备注',
welcome_message VARCHAR(500) DEFAULT NULL COMMENT '自动欢迎语',
status VARCHAR(20) NOT NULL DEFAULT 'enable' COMMENT '状态', status VARCHAR(20) NOT NULL DEFAULT 'enable' COMMENT '状态',
disable_reason VARCHAR(200) DEFAULT NULL COMMENT '停用原因',
created_by VARCHAR(64) DEFAULT NULL COMMENT '创建人',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
UNIQUE INDEX uk_position_employee (position_code, employee_id),
INDEX idx_qrcode_channels_employee_id (employee_id), INDEX idx_qrcode_channels_employee_id (employee_id),
INDEX idx_qrcode_channels_channel_code (channel_code), INDEX idx_qrcode_channels_channel_code (channel_code),
INDEX idx_qrcode_channels_position_code (position_code),
INDEX idx_qrcode_channels_status (status) INDEX idx_qrcode_channels_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='渠道活码表'; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='渠道活码表';
-- 创建 skills 技能目录表
CREATE TABLE IF NOT EXISTS skills (
id INT AUTO_INCREMENT PRIMARY KEY,
skill_code VARCHAR(100) NOT NULL UNIQUE COMMENT 'Skill编码,全局唯一',
skill_name VARCHAR(100) NOT NULL COMMENT 'Skill名称',
description VARCHAR(500) DEFAULT NULL COMMENT '简要描述',
doc_markdown MEDIUMTEXT DEFAULT NULL COMMENT 'Markdown格式的使用说明文档',
priority INT DEFAULT 1 NOT NULL COMMENT '优先级,1=P1',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
INDEX idx_skills_code (skill_code),
INDEX idx_skills_priority (priority)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Skill技能目录表';
-- 预置 Skill 数据
INSERT INTO skills (skill_code, skill_name, description, doc_markdown, priority) VALUES
('query-metric', '指标查询', '查询业务指标数据', '# 指标查询 Skill\n\n## 使用方法\n通过自然语言描述需要查询的业务指标,系统将自动匹配并返回对应数据。\n\n## 示例\n- "查询本月销售额"\n- "上月客户增长数量"', 1),
('query-detail', '明细查询', '查询业务明细数据', '# 明细查询 Skill\n\n## 使用方法\n通过自然语言描述需要查询的业务明细,系统将返回详细的记录列表。\n\n## 示例\n- "查询最近10笔订单明细"\n- "查看客户张三的所有交易记录"', 1);
-- 创建会话 sessions 表
CREATE TABLE IF NOT EXISTS sessions (
id INT AUTO_INCREMENT PRIMARY KEY,
session_id VARCHAR(64) NOT NULL UNIQUE COMMENT '会话唯一 ID(sess_前缀)',
user_id VARCHAR(64) NOT NULL COMMENT '用户 ID',
channel VARCHAR(64) NOT NULL COMMENT '渠道标识',
current_agent_id INT NOT NULL DEFAULT 101 COMMENT '当前处理的 agent id',
status VARCHAR(20) NOT NULL DEFAULT 'active' COMMENT '会话状态:active/archived',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
INDEX idx_sessions_user (user_id),
INDEX idx_sessions_channel (channel),
INDEX idx_sessions_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='会话元数据表';
-- 创建会话对话历史 conversation_history 表
CREATE TABLE IF NOT EXISTS conversation_history (
id INT AUTO_INCREMENT PRIMARY KEY,
session_id VARCHAR(64) NOT NULL COMMENT '会话 ID',
role VARCHAR(32) NOT NULL COMMENT 'user/assistant/...',
content MEDIUMTEXT NOT NULL COMMENT '对话内容',
agent_id INT DEFAULT NULL COMMENT 'Agent ID',
intent VARCHAR(128) DEFAULT NULL COMMENT '意图',
entities_json MEDIUMTEXT DEFAULT NULL COMMENT '实体 JSON',
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
INDEX idx_conv_session (session_id),
INDEX idx_conv_agent (agent_id),
INDEX idx_conv_time (timestamp)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='会话对话历史表';
-- 创建对话日志表
CREATE TABLE IF NOT EXISTS conversation_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
session_id VARCHAR(64) NOT NULL,
user_id VARCHAR(64) NOT NULL,
agent_id INT NOT NULL,
agent_name VARCHAR(50) DEFAULT NULL,
query TEXT NOT NULL,
response TEXT DEFAULT NULL,
intent VARCHAR(128) DEFAULT NULL,
entities JSON DEFAULT NULL,
processing_time_ms INT DEFAULT NULL,
has_error TINYINT(1) DEFAULT 0 NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
INDEX idx_cl_user_id (user_id),
INDEX idx_cl_agent_id (agent_id),
INDEX idx_cl_intent (intent),
INDEX idx_cl_created_at (created_at),
INDEX idx_cl_has_error (has_error)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='对话日志表';
-- 创建埋点事件表
CREATE TABLE IF NOT EXISTS analytics_events (
id INT AUTO_INCREMENT PRIMARY KEY,
event_type VARCHAR(64) NOT NULL,
event_data JSON DEFAULT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
INDEX idx_ae_event_type (event_type),
INDEX idx_ae_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='埋点事件表';
-- 创建统计表
CREATE TABLE IF NOT EXISTS analytics_statistics (
id INT AUTO_INCREMENT PRIMARY KEY,
stat_date DATE NOT NULL,
dimension VARCHAR(32) NOT NULL,
dimension_value VARCHAR(128) NOT NULL,
total_agent_calls INT DEFAULT 0 NOT NULL,
total_sessions INT DEFAULT 0 NOT NULL,
avg_session_turns DECIMAL(5,2) DEFAULT 0.00 NOT NULL,
intent_distribution JSON DEFAULT NULL,
agent_call_ranking JSON DEFAULT NULL,
daily_trend JSON DEFAULT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
UNIQUE INDEX idx_as_date_dim (stat_date, dimension, dimension_value)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='统计预聚合表';
-- 创建页面访问埋点表
CREATE TABLE IF NOT EXISTS page_views (
id INT AUTO_INCREMENT PRIMARY KEY,
page_type VARCHAR(64) NOT NULL,
user_id VARCHAR(64) DEFAULT NULL,
session_id VARCHAR(64) DEFAULT NULL,
device_type VARCHAR(32) DEFAULT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
INDEX idx_pv_page_type (page_type),
INDEX idx_pv_user_id (user_id),
INDEX idx_pv_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='页面访问埋点表';
-- 创建活码扫码事件表
CREATE TABLE IF NOT EXISTS scan_events (
id INT AUTO_INCREMENT PRIMARY KEY,
qrcode_id INT DEFAULT NULL,
channel_code VARCHAR(128) DEFAULT NULL,
customer_user_id VARCHAR(64) DEFAULT NULL,
position_code VARCHAR(64) DEFAULT NULL,
employee_id VARCHAR(64) DEFAULT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
INDEX idx_se_qrcode_id (qrcode_id),
INDEX idx_se_channel_code (channel_code),
INDEX idx_se_customer (customer_user_id),
INDEX idx_se_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='活码扫码事件表';
-- 创建入群成功事件表
CREATE TABLE IF NOT EXISTS group_join_events (
id INT AUTO_INCREMENT PRIMARY KEY,
group_id VARCHAR(64) DEFAULT NULL,
customer_user_id VARCHAR(64) DEFAULT NULL,
employee_count INT DEFAULT 0,
agent_count INT DEFAULT 0,
channel_code VARCHAR(128) DEFAULT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
INDEX idx_gje_group_id (group_id),
INDEX idx_gje_customer (customer_user_id),
INDEX idx_gje_channel_code (channel_code),
INDEX idx_gje_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='入群成功事件表';
-- 创建专属群聊表
CREATE TABLE IF NOT EXISTS customer_groups (
id INT AUTO_INCREMENT PRIMARY KEY,
group_id VARCHAR(64) NOT NULL UNIQUE COMMENT '企微群聊ID',
group_name VARCHAR(100) NOT NULL COMMENT '群名称',
customer_user_id VARCHAR(64) NOT NULL COMMENT '客户外部联系人UserID',
customer_nickname VARCHAR(100) DEFAULT NULL COMMENT '客户昵称',
position_code VARCHAR(100) DEFAULT NULL COMMENT '岗位编码',
channel_code VARCHAR(128) DEFAULT NULL COMMENT '渠道编码',
creator_employee_id VARCHAR(64) DEFAULT NULL COMMENT '创建人员工ID',
employee_wechat_user_ids JSON DEFAULT NULL COMMENT '员工企微UserID列表',
agent_ids JSON DEFAULT NULL COMMENT '关联Agent ID列表',
status VARCHAR(20) NOT NULL DEFAULT 'active' COMMENT '状态: active/dissolved',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
dissolved_at DATETIME DEFAULT NULL COMMENT '解散时间',
dissolution_reason VARCHAR(200) DEFAULT NULL COMMENT '解散原因',
INDEX idx_cg_customer (customer_user_id),
INDEX idx_cg_position_code (position_code),
INDEX idx_cg_status (status),
INDEX idx_cg_created_at (created_at),
INDEX idx_cg_channel_code (channel_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='专属群聊表';
-- 扩展 official_tabs 表字段,支持官网岗位 Tab 管理
ALTER TABLE official_tabs ADD COLUMN position_code VARCHAR(100) DEFAULT NULL COMMENT '岗位编码';
ALTER TABLE official_tabs ADD COLUMN position_name VARCHAR(100) DEFAULT NULL COMMENT '岗位名称';
ALTER TABLE official_tabs ADD COLUMN qrcode_id INT DEFAULT NULL COMMENT '关联渠道活码ID';
ALTER TABLE official_tabs ADD COLUMN display_status VARCHAR(20) NOT NULL DEFAULT 'enable' COMMENT '展示状态: enable/disable';
ALTER TABLE official_tabs ADD COLUMN sort_order INT NOT NULL DEFAULT 0 COMMENT '排序,越小越靠前';
ALTER TABLE official_tabs ADD COLUMN created_by VARCHAR(64) DEFAULT NULL COMMENT '创建人';
ALTER TABLE official_tabs ADD COLUMN deleted_at DATETIME DEFAULT NULL COMMENT '软删除时间';
ALTER TABLE official_tabs ADD INDEX idx_ot_position_code (position_code);
ALTER TABLE official_tabs ADD INDEX idx_ot_qrcode_id (qrcode_id);
ALTER TABLE official_tabs ADD INDEX idx_ot_display_status (display_status);
ALTER TABLE official_tabs ADD INDEX idx_ot_sort_order (sort_order);
ALTER TABLE official_tabs ADD INDEX idx_ot_deleted_at (deleted_at);
-- 创建官网 Agent 展示配置表
CREATE TABLE IF NOT EXISTS official_site_agent_display (
id INT AUTO_INCREMENT PRIMARY KEY,
tab_id INT NOT NULL COMMENT '关联的 official_tabs 表 ID',
agent_id INT NOT NULL COMMENT '关联的 Agent ID',
media_url VARCHAR(500) DEFAULT NULL COMMENT '素材URL',
media_type VARCHAR(10) DEFAULT NULL COMMENT '素材类型: gif/mp4',
speech_title VARCHAR(100) DEFAULT NULL COMMENT '话术标题',
speech_content VARCHAR(200) DEFAULT NULL COMMENT '话术正文',
display_status VARCHAR(20) NOT NULL DEFAULT 'enable' COMMENT '展示状态: enable/disable',
sort_order INT NOT NULL DEFAULT 0 COMMENT '排序',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
UNIQUE INDEX uk_tab_agent (tab_id, agent_id),
INDEX idx_osad_tab_id (tab_id),
INDEX idx_osad_agent_id (agent_id),
INDEX idx_osad_display_status (display_status),
INDEX idx_osad_sort_order (sort_order)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='官网Agent展示配置表';
\ No newline at end of file \ No newline at end of file
-- 创建方法论主配置表
CREATE TABLE IF NOT EXISTS official_site_methodology (
id INT AUTO_INCREMENT PRIMARY KEY,
display_status VARCHAR(20) NOT NULL DEFAULT 'enable' COMMENT '展示状态: enable/disable',
main_title VARCHAR(100) NOT NULL DEFAULT '方法论' COMMENT '主标题',
sub_title VARCHAR(200) NOT NULL DEFAULT '' COMMENT '副标题',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
INDEX idx_osm_display_status (display_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='方法论主配置表';
-- 创建方法论步骤表
CREATE TABLE IF NOT EXISTS official_site_methodology_steps (
id INT AUTO_INCREMENT PRIMARY KEY,
methodology_id INT NOT NULL COMMENT '关联方法论主配置ID',
step_icon VARCHAR(500) DEFAULT NULL COMMENT '步骤图标URL',
step_name VARCHAR(100) NOT NULL COMMENT '步骤名称',
step_order INT NOT NULL COMMENT '步骤序号',
step_image VARCHAR(500) DEFAULT NULL COMMENT '步骤内容图URL',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
INDEX idx_osms_methodology_id (methodology_id),
INDEX idx_osms_step_order (step_order)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='方法论步骤表';
\ No newline at end of file \ No newline at end of file
## 1. 数据库准备 ## 1. 数据库准备
- [ ] 1.1 创建 `agents` 表的迁移脚本,包含 `is_deleted` 和 `version` 字段 - [x] 1.1 创建 `agents` 表的迁移脚本,包含 `is_deleted` 和 `version` 字段
- [ ] 1.2 创建 `agent_positions` 和 `agent_skills` 关联表的迁移脚本 - [x] 1.2 创建 `agent_positions` 和 `agent_skills` 关联表的迁移脚本
- [ ] 1.3 运行迁移脚本并验证表结构 - [ ] 1.3 运行迁移脚本并验证表结构
## 2. 模型与数据层 (Model & Schema) ## 2. 模型与数据层 (Model & Schema)
- [ ] 2.1 定义 SQLAlchemy ORM 模型 `Agent`, `AgentPosition`, `AgentSkill` - [x] 2.1 定义 SQLAlchemy ORM 模型 `Agent`, `AgentPosition`, `AgentSkill`
- [ ] 2.2 定义 Pydantic 请求模型 (Create/Update DTO) - [x] 2.2 定义 Pydantic 请求模型 (Create/Update DTO)
- [ ] 2.3 定义 Pydantic 响应模型 (List/Detail DTO) - [x] 2.3 定义 Pydantic 响应模型 (List/Detail DTO)
## 3. 业务逻辑层 (Service Layer) ## 3. 业务逻辑层 (Service Layer)
- [ ] 3.1 实现 Agent 创建逻辑,包含编码唯一性和关联校验 - [x] 3.1 实现 Agent 创建逻辑,包含编码唯一性和关联校验
- [ ] 3.2 实现 Agent 编辑逻辑,支持乐观锁和全量替换关联关系 - [x] 3.2 实现 Agent 编辑逻辑,支持乐观锁和全量替换关联关系
- [ ] 3.3 实现 Agent 软删除逻辑,包含引用检查 - [x] 3.3 实现 Agent 软删除逻辑(当前未包含会话/路由引用检查,待相关模块实现后补充)
- [ ] 3.4 实现列表查询逻辑,支持关键词搜索和条件过滤 - [x] 3.4 实现列表查询逻辑,支持关键词搜索和条件过滤
- [ ] 3.5 实现状态切换逻辑,处理缓存失效和通知 - [x] 3.5 实现状态切换逻辑(缓存失效和路由通知待相关基础设施就绪后补充)
## 4. 接口层 (API Layer) ## 4. 接口层 (API Layer)
- [ ] 4.1 挂载 `POST /api/v1/agents` 创建接口 - [x] 4.1 挂载 `POST /api/v1/agents` 创建接口
- 请求参数:`name`(50字), `code`(唯一), `position_ids`([]), `skill_codes`([]), `description`(500字), `status`(`enable`/`disable`) - 请求参数:`name`(50字), `code`(唯一), `position_ids`([]), `skill_codes`([]), `description`(500字), `status`(`enable`/`disable`)
- [ ] 4.2 挂载 `PUT /api/v1/agents/{agent_id}` 编辑接口 - [x] 4.2 挂载 `PUT /api/v1/agents/{agent_id}` 编辑接口
- 请求参数:`name`, `position_ids`, `skill_codes`, `description`, `status` (code 不可改,带 version 乐观锁) - 请求参数:`name`, `position_ids`, `skill_codes`, `description`, `status` (code 不可改,带 version 乐观锁)
- [ ] 4.3 挂载 `DELETE /api/v1/agents/{agent_id}` 删除接口 - [x] 4.3 挂载 `DELETE /api/v1/agents/{agent_id}` 删除接口
- 逻辑:软删除,需校验会话和路由引用 - 当前实现:软删除(设置 is_deleted=true + deleted_at),引用检查待会话/路由模块就绪后补充
- [ ] 4.4 挂载 `GET /api/v1/agents` 列表接口 - [x] 4.4 挂载 `GET /api/v1/agents` 列表接口
- 查询参数:`page`, `page_size`, `keyword`, `position_id`, `status` - 查询参数:`page`, `page_size`, `keyword`, `position_id`, `status`
- [ ] 4.5 挂载 `GET /api/v1/agents/{agent_id}` 详情接口 - [x] 4.5 挂载 `GET /api/v1/agents/{agent_id}` 详情接口
- 响应:包含基础信息、岗位列表、Skill 列表、会话统计等 - 当前响应:包含基础信息、岗位 ID 列表、Skill 编码列表;会话统计待相关模块实现后补充
- [ ] 4.6 挂载 `PUT /api/v1/agents/{agent_id}/status` 状态管理接口 - [x] 4.6 挂载 `PUT /api/v1/agents/{agent_id}/status` 状态管理接口
- 请求参数:`status`, `reason` - 请求参数:`status`, `reason`
## 5. 测试与验证 ## 5. 测试与验证
- [ ] 5.1 编写 Agent 创建与唯一性校验的单元测试 - [x] 5.1 编写 Agent 创建与唯一性校验的单元测试
- [ ] 5.2 编写编辑接口及并发冲突的单元测试 - [x] 5.2 编写编辑接口及并发冲突的单元测试
- [ ] 5.3 编写删除逻辑及引用限制的单元测试 - [x] 5.3 编写删除逻辑的单元测试(引用限制测试待会话模块实现后补充)
- [ ] 5.4 运行所有测试并确保覆盖率达标 - [x] 5.4 运行所有测试并确保通过
## 1. 数据库与基础设施准备 ## 1. 数据库与基础设施准备
- [ ] 1.1 创建官网 Agent 展示配置表 migration - [x] 1.1 创建官网 Agent 展示配置表 migration(official_site_agent_display: id, tab_id, agent_id, media_url, media_type, speech_title, speech_content, display_status, sort_order, created_at, updated_at + 唯一约束 uk_tab_agent + 索引)
- [ ] 字段:config_id, tab_id, agent_id, media_url, media_type, speech_title, speech_content, display_status, sort_order, created_at, updated_at
- [ ] 建立索引:tab_id, agent_id, display_status, sort_order
- [ ] 唯一约束:tab_id + agent_id 组合唯一
## 2. 模型与数据层 (Model & Schema) ## 2. 模型与数据层 (Model & Schema)
- [ ] 2.1 定义 SQLAlchemy ORM 模型 - [x] 2.1 定义 SQLAlchemy ORM 模型 OfficialSiteAgentDisplay
- [ ] OfficialSiteAgentDisplay 模型 - [x] 2.2 定义 Pydantic 请求与响应模型(8 个 DTO: AvailableAgentsResponse, AvailableAgentItem, StewardAgentInfo, SaveAgentConfigRequest/Response, ConfiguredAgentsResponse, ConfiguredAgentItem, DeleteAgentConfigResponse)
- [ ] 2.2 定义 Pydantic 请求与响应模型
- [ ] AvailableAgentsResponse (包含 tab_id, position_name, qrcode_id, available_agents, steward_agent)
- [ ] AvailableAgentItem (包含 agent_id, agent_name, agent_code, is_configured, configured_description, is_steward)
- [ ] StewardAgentInfo (包含 agent_id, agent_name, note)
- [ ] SaveAgentConfigRequest (字段:media_url, media_type, media_size, speech_title, speech_content, display_status, sort_order)
- [ ] SaveAgentConfigResponse (包含 config_id, tab_id, agent_id, updated_at)
- [ ] ConfiguredAgentsResponse (包含 tab_id, configured_agents)
- [ ] ConfiguredAgentItem (包含 config_id, agent_id, agent_name, media_url, media_type, speech_title, speech_content, display_status, sort_order, agent_status)
- [ ] DeleteAgentConfigResponse (包含 success, deleted_at)
## 3. 业务逻辑层 (Service Layer) ## 3. 业务逻辑层 (Service Layer)
- [ ] 3.1 实现查询某 Tab 下可配置 Agent 列表逻辑 - [x] 3.1 实现查询某 Tab 下可配置 Agent 列表逻辑
- [ ] 3.1.1 接收并验证参数:tab_id - [x] 3.1.1 根据 tab_id 查询关联的渠道活码和岗位信息
- [ ] 3.1.2 根据 tab_id 查询关联的渠道活码和岗位信息 - [x] 3.1.2 获取该岗位下所有已上架的 Agent(通过 AgentPosition 关联)
- [ ] 3.1.3 获取该岗位下所有已上架的 Agent - [x] 3.1.3 排除管家 Agent
- [ ] 3.1.4 排除管家 Agent - [x] 3.1.4 查询该 Tab 下已配置的 Agent,标记 is_configured
- [ ] 3.1.5 查询该 Tab 下已配置的 Agent,标记 is_configured - [x] 3.1.5 返回可配置 Agent 列表和管家 Agent 信息(含 note 说明)
- [ ] 3.1.6 返回可配置 Agent 列表和管家 Agent 信息 - [x] 3.1.6 Tab 不存在返回 404
- [ ] 3.2 实现保存 Agent 展示配置逻辑 - [x] 3.2 实现保存 Agent 展示配置逻辑
- [ ] 3.2.1 接收并验证参数:tab_id, agent_id, media_url, media_type, media_size, speech_title, speech_content, display_status, sort_order - [x] 3.2.1 校验 Tab 是否存在
- [ ] 3.2.2 校验 Agent 是否在可配置列表中 - [x] 3.2.2 校验素材格式(仅允许 gif/mp4)
- [ ] 3.2.3 校验素材格式(仅允许 gif/mp4) - [x] 3.2.3 校验素材大小(最大 20MB,即 20971520 字节)
- [ ] 3.2.4 校验素材大小(最大 20MB,即 20971520 字节) - [x] 3.2.4 校验 speech_title 长度(最多 100 字)
- [ ] 3.2.5 校验 speech_title 长度(最多 20 字) - [x] 3.2.5 校验 speech_content 长度(最多 200 字)
- [ ] 3.2.6 校验 speech_content 长度(最多 100 字) - [x] 3.2.6 校验 Agent 是否在可配置列表中
- [ ] 3.2.7 如果配置已存在则更新,否则创建 - [x] 3.2.7 如果配置已存在则更新(upsert),否则创建
- [ ] 3.2.8 失效 H5 首页缓存 - [x] 3.2.8 失效 H5 首页缓存
- [ ] 3.2.9 返回保存结果 - [x] 3.3 实现查询某 Tab 下已配置的 Agent 列表逻辑
- [ ] 3.3 实现查询某 Tab 下已配置的 Agent 列表逻辑 - [x] 3.3.1 校验 Tab 是否存在
- [ ] 3.3.1 接收并验证参数:tab_id - [x] 3.3.2 查询该 Tab 下已配置的 Agent 展示配置
- [ ] 3.3.2 查询该 Tab 下已配置的 Agent 展示配置 - [x] 3.3.3 关联查询 Agent 基本信息和 agent_status
- [ ] 3.3.3 关联查询 Agent 基本信息和 agent_status - [x] 3.3.4 按 sort_order 升序排序
- [ ] 3.3.4 按 sort_order 升序排序 - [x] 3.4 实现删除 Agent 展示配置逻辑
- [ ] 3.3.5 返回已配置的 Agent 列表 - [x] 3.4.1 校验配置是否存在
- [ ] 3.4 实现删除 Agent 展示配置逻辑 - [x] 3.4.2 删除配置记录(物理删除)
- [ ] 3.4.1 接收并验证参数:tab_id, agent_id - [x] 3.4.3 失效 H5 首页缓存
- [ ] 3.4.2 校验配置是否存在 - [x] 3.4.4 不删除 Agent 本身
- [ ] 3.4.3 删除配置记录
- [ ] 3.4.4 失效 H5 首页缓存
- [ ] 3.4.5 返回删除结果(不删除 Agent 本身)
## 4. 接口层 (API Layer) ## 4. 接口层 (API Layer)
- [ ] 4.1 挂载 `GET /api/v1/official-site/tabs/{tab_id}/agents/available` 查询某 Tab 下可配置 Agent 列表接口 - [x] 4.1 挂载 `GET /api/v1/official-site/tabs/{tab_id}/agents/available` 查询可配置 Agent 列表接口
- [ ] 4.1.1 实现 Path 参数绑定与验证 - [x] 4.2 挂载 `POST /api/v1/official-site/tabs/{tab_id}/agents/{agent_id}/config` 保存 Agent 展示配置接口
- [ ] 4.1.2 调用 Service 层可配置 Agent 查询逻辑 - [x] 4.3 挂载 `GET /api/v1/official-site/tabs/{tab_id}/agents/configured` 查询已配置 Agent 列表接口
- [ ] 4.1.3 返回标准化 JSON 响应 - [x] 4.4 挂载 `DELETE /api/v1/official-site/tabs/{tab_id}/agents/{agent_id}/config` 删除 Agent 展示配置接口
- [ ] 4.2 挂载 `POST /api/v1/official-site/tabs/{tab_id}/agents/{agent_id}/config` 保存 Agent 展示配置接口
- [ ] 4.2.1 实现 Path 参数与 Request Body 绑定与验证
- [ ] 4.2.2 调用 Service 层保存 Agent 配置逻辑
- [ ] 4.2.3 返回保存结果响应
- [ ] 4.3 挂载 `GET /api/v1/official-site/tabs/{tab_id}/agents/configured` 查询某 Tab 下已配置的 Agent 列表接口
- [ ] 4.3.1 实现 Path 参数绑定与验证
- [ ] 4.3.2 调用 Service 层已配置 Agent 查询逻辑
- [ ] 4.3.3 返回已配置 Agent 列表响应
- [ ] 4.4 挂载 `DELETE /api/v1/official-site/tabs/{tab_id}/agents/{agent_id}/config` 删除 Agent 展示配置接口
- [ ] 4.4.1 实现 Path 参数绑定与验证
- [ ] 4.4.2 调用 Service 层删除 Agent 配置逻辑
- [ ] 4.4.3 返回删除结果响应
## 5. 测试与验证 ## 5. 测试与验证
- [ ] 5.1 编写查询某 Tab 下可配置 Agent 列表单元测试 - [x] 5.1 编写可配置 Agent 列表查询单元测试(4 个用例:排除管家 / 管家信息 / is_configured 标记 / Tab 不存在)
- [ ] 5.1.1 测试正常查询流程 - [x] 5.2 编写保存 Agent 配置单元测试(7 个用例:新建 / 更新覆盖 / 不在可配置列表 / 素材格式 / 素材大小 / 话术长度 / 缓存失效)
- [ ] 5.1.2 测试管家 Agent 被正确排除 - [x] 5.3 编写已配置 Agent 列表查询单元测试(3 个用例:正常查询 / 排序 / Tab 不存在)
- [ ] 5.1.3 测试 is_configured 标记正确 - [x] 5.4 编写删除 Agent 配置单元测试(4 个用例:删除成功 / Agent 本身不被删 / 配置不存在 / 缓存失效)
- [ ] 5.1.4 测试 Tab 不存在的情况(返回 404) - [x] 5.5 集成测试: 可配置 → 保存 → 已配置 → 删除的完整链路
- [ ] 5.2 编写保存 Agent 展示配置单元测试
- [ ] 5.2.1 测试正常保存流程
- [ ] 5.2.2 测试素材格式校验(不支持的格式返回 400)
- [ ] 5.2.3 测试素材大小校验(超过 20MB 返回 400)
- [ ] 5.2.4 测试话术长度校验
- [ ] 5.2.5 测试 Agent 不在可配置列表的情况
- [ ] 5.2.6 测试更新已有配置的情况
- [ ] 5.2.7 测试缓存失效是否生效
- [ ] 5.3 编写查询某 Tab 下已配置的 Agent 列表单元测试
- [ ] 5.3.1 测试正常查询流程
- [ ] 5.3.2 测试 agent_status 字段正确返回
- [ ] 5.3.3 测试排序正确性(按 sort_order 升序)
- [ ] 5.3.4 测试 Tab 不存在的情况(返回 404)
- [ ] 5.4 编写删除 Agent 展示配置单元测试
- [ ] 5.4.1 测试正常删除流程
- [ ] 5.4.2 测试配置不存在的情况(返回 404)
- [ ] 5.4.3 测试 Agent 本身不被删除
- [ ] 5.4.4 测试缓存失效是否生效
- [ ] 5.5 集成测试: 查询可配置 Agent → 保存配置 → 查询已配置 Agent → 删除配置 的完整链路
\ No newline at end of file \ No newline at end of file
## 1. 基础设施准备 ## 1. 基础设施准备
- [ ] 1.1 配置 Redis 用于缓存 - [x] 1.1 配置 H5 首页缓存(H5CacheManager Protocol + InMemoryH5CacheManager,支持 get/set/invalidate + TTL=300s)
- [ ] 配置 Redis 连接池 - [x] 1.2 创建共享缓存实例(shared_h5_cache),确保 Tab 配置/Agent 配置/首页读取三方共享同一缓存
- [ ] 确定缓存 Key 格式:official_site:home
- [ ] 设置 TTL:300 秒
## 2. 模型与数据层 (Model & Schema) ## 2. 模型与数据层 (Model & Schema)
- [ ] 2.1 定义 Pydantic 请求与响应模型 - [x] 2.1 定义 Pydantic 响应模型(H5HomeResponse, H5HomeTabItem, H5HomeAgentItem, H5HomeMethodologyItem, H5HomeMethodologyStep)
- [ ] H5HomeResponse (包含 site_title, site_subtitle, background_image, tabs, methodology)
- [ ] H5HomeTabItem (包含 tab_id, position_code, position_name, qrcode_url, qrcode_status, agents)
- [ ] H5HomeAgentItem (包含 agent_id, agent_name, media_url, media_type, speech_title, speech_content, status)
- [ ] H5HomeMethodologyItem (包含 display_status, main_title, sub_title, steps)
- [ ] H5HomeMethodologyStep (包含 step_icon, step_name, step_image)
## 3. 业务逻辑层 (Service Layer) ## 3. 业务逻辑层 (Service Layer)
- [ ] 3.1 实现 H5 首页聚合数据逻辑 - [x] 3.1 实现 H5 首页聚合数据逻辑
- [ ] 3.1.1 尝试从 Redis 缓存读取数据(Key=official_site:home) - [x] 3.1.1 尝试从缓存读取数据(Key=official_site:home,TTL=300s)
- [ ] 3.1.2 缓存命中则直接返回 - [x] 3.1.2 缓存命中直接返回
- [ ] 3.1.3 缓存未命中则从数据库加载: - [x] 3.1.3 缓存未命中从数据库加载:
- [ ] 查询所有 display_status=enable 的 Tab 配置,按 sort_order 升序排序 - [x] 查询所有 display_status=enable 且未删除的 Tab,按 sort_order 升序
- [ ] 查询每个 Tab 下 display_status=enable 且 Agent 本身状态 enable 的 Agent 配置,按 sort_order 升序排序 - [x] 查询每个 Tab 下 display_status=enable 的 Agent 展示配置,过滤 Agent 本身状态为 enable,按 sort_order 升序
- [ ] 查询方法论配置 - [x] 关联查询渠道活码 URL 和状态
- [ ] 查询 Banner/背景图配置(如果有单独表) - [x] 组装方法论模块(当前为默认内容,待方法论 CRUD 功能实现后扩展)
- [ ] 3.1.4 聚合数据,构建响应对象 - [x] 组装 site_title/subtitle/background_image
- [ ] 3.1.5 将聚合数据写入 Redis 缓存(TTL=300 秒) - [x] 3.1.4 将聚合数据写入缓存
- [ ] 3.1.6 返回完整聚合数据 - [x] 3.1.5 返回完整响应
- [ ] 3.2 实现失效 H5 首页缓存逻辑 - [x] 3.2 实现失效 H5 首页缓存逻辑
- [ ] 3.2.1 删除 Redis 中的 official_site:home 缓存 - [x] 3.2.1 通过 shared_h5_cache 在 Tab/Agent 配置变更时共享失效
- [ ] 3.2.2 在 Tab 配置变更时调用
- [ ] 3.2.3 在 Agent 展示配置变更时调用
- [ ] 3.2.4 在方法论配置变更时调用
## 4. 接口层 (API Layer) ## 4. 接口层 (API Layer)
- [ ] 4.1 挂载 `GET /api/v1/official-site/home` H5首页聚合数据接口 - [x] 4.1 挂载 `GET /api/v1/official-site/home` H5首页聚合数据接口(公开,无需鉴权)
- [ ] 4.1.1 设置为公开访问(无需鉴权)
- [ ] 4.1.2 调用 Service 层聚合数据逻辑
- [ ] 4.1.3 返回标准化 JSON 响应
## 5. 测试与验证 ## 5. 测试与验证
- [ ] 5.1 编写 H5 首页聚合数据单元测试 - [x] 5.1 编写 H5 首页聚合数据单元测试(10 个用例)
- [ ] 5.1.1 测试缓存命中场景 - [x] 5.1.1 缓存未命中从数据库构建
- [ ] 5.1.2 测试缓存未命中场景 - [x] 5.1.2 缓存命中返回缓存数据(不查 DB)
- [ ] 5.1.3 测试仅返回 enable 状态的 Tab - [x] 5.1.3 仅返回 display_status=enable 的 Tab
- [ ] 5.1.4 测试仅返回 enable 状态的 Agent - [x] 5.1.4 仅返回 display_status=enable 的 Agent
- [ ] 5.1.5 测试排序正确性(Tab 按 sort_order,Agent 按 sort_order) - [x] 5.1.5 过滤 Agent 本身状态为 disable 的 Agent
- [ ] 5.1.6 测试数据缓存写入正确 - [x] 5.1.6 排序正确性(Agent 按 sort_order 升序)
- [ ] 5.2 编写失效 H5 首页缓存单元测试 - [x] 5.1.7 缓存写入验证
- [ ] 5.2.1 测试缓存被正确删除 - [x] 5.1.8 失效缓存后刷新验证
- [ ] 5.3 集成测试: 配置变更 → 失效缓存 → 再次请求获取新数据 的完整链路 - [x] 5.1.9 方法论模块返回
- [ ] 5.4 性能测试: 验证接口响应时间 P95 < 200ms - [x] 5.1.10 空站点返回空列表
- [ ] 5.2 性能测试: 验证接口响应时间 P95 < 200ms(待生产环境验证)
\ No newline at end of file \ No newline at end of file
## 1. 数据库与基础设施准备 ## 1. 数据库与基础设施准备
- [ ] 1.1 创建方法论主配置表 migration - [x] 1.1 创建方法论主配置表 migration(official_site_methodology: id, display_status, main_title, sub_title, created_at, updated_at + 索引)
- [ ] 字段:config_id, display_status, main_title, sub_title, created_at, updated_at - [x] 1.2 创建方法论步骤表 migration(official_site_methodology_steps: id, methodology_id, step_icon, step_name, step_order, step_image, created_at, updated_at + 索引)
- [ ] 建立索引:display_status
- [ ] 1.2 创建方法论步骤表 migration
- [ ] 字段:step_id, methodology_id, step_icon, step_name, step_order, step_image, created_at, updated_at
- [ ] 建立索引:methodology_id, step_order
- [ ] 外键:methodology_id 关联主配置表
## 2. 模型与数据层 (Model & Schema) ## 2. 模型与数据层 (Model & Schema)
- [ ] 2.1 定义 SQLAlchemy ORM 模型 - [x] 2.1 定义 SQLAlchemy ORM 模型 OfficialSiteMethodology + OfficialSiteMethodologyStep
- [ ] OfficialSiteMethodology 模型 - [x] 2.2 定义 Pydantic 请求与响应模型(GetMethodologyResponse, MethodologyStepItem, SaveMethodologyRequest, SaveMethodologyStepItem, SaveMethodologyResponse)
- [ ] OfficialSiteMethodologyStep 模型
- [ ] 2.2 定义 Pydantic 请求与响应模型
- [ ] GetMethodologyResponse (包含 config_id, display_status, main_title, sub_title, steps, updated_at)
- [ ] MethodologyStepItem (包含 step_id, step_icon, step_name, step_order, step_image)
- [ ] SaveMethodologyRequest (字段:display_status, main_title, sub_title, steps)
- [ ] SaveMethodologyStepItem (字段:step_icon, step_name, step_order, step_image)
- [ ] SaveMethodologyResponse (包含 config_id, updated_at)
## 3. 业务逻辑层 (Service Layer) ## 3. 业务逻辑层 (Service Layer)
- [ ] 3.1 实现查询方法论配置逻辑 - [x] 3.1 实现查询方法论配置逻辑
- [ ] 3.1.1 查询方法论主配置(如果不存在,返回空配置或默认配置) - [x] 3.1.1 查询方法论主配置(如果不存在,返回空配置 config_id=0 + 空 steps)
- [ ] 3.1.2 关联查询步骤配置 - [x] 3.1.2 关联查询步骤配置
- [ ] 3.1.3 按 step_order 升序排序步骤 - [x] 3.1.3 按 step_order 升序排序步骤
- [ ] 3.1.4 返回完整配置 - [x] 3.1.4 返回完整配置
- [ ] 3.2 实现保存方法论配置逻辑 - [x] 3.2 实现保存方法论配置逻辑
- [ ] 3.2.1 接收并验证请求参数:display_status, main_title (最多 30 字), sub_title (最多 100 字), steps (4-10 个) - [x] 3.2.1 校验步骤数量(必须 4-10 个)
- [ ] 3.2.2 校验步骤数量(必须 4-10 个) - [x] 3.2.2 校验步骤序号连续性(从 1 开始,无重复,无间隔)
- [ ] 3.2.3 校验步骤序号连续性(从 1 开始,无重复,无间隔) - [x] 3.2.3 在数据库事务中处理保存(upsert 主配置 → 删除旧步骤 → 批量插入新步骤)
- [ ] 3.2.4 校验每个 step_name 长度(最多 20 字) - [x] 3.2.4 失效 H5 首页缓存
- [ ] 3.2.5 校验 step_image 大小(最大 10MB) - [x] 3.3 更新 H5 首页服务从 DB 读取真实方法论数据(替换硬编码默认值)
- [ ] 3.2.6 在数据库事务中处理保存:
- [ ] 保存或更新主配置
- [ ] 删除旧的步骤配置
- [ ] 批量插入新的步骤配置
- [ ] 3.2.7 失效 H5 首页缓存
- [ ] 3.2.8 返回保存结果
## 4. 接口层 (API Layer) ## 4. 接口层 (API Layer)
- [ ] 4.1 挂载 `GET /api/v1/official-site/methodology` 查询方法论配置接口 - [x] 4.1 挂载 `GET /api/v1/official-site/methodology` 查询方法论配置接口
- [ ] 4.1.1 调用 Service 层查询逻辑 - [x] 4.2 挂载 `POST /api/v1/official-site/methodology` 保存方法论配置接口
- [ ] 4.1.2 返回标准化 JSON 响应
- [ ] 4.2 挂载 `POST /api/v1/official-site/methodology` 保存方法论配置接口
- [ ] 4.2.1 实现 Request Body 绑定与验证
- [ ] 4.2.2 调用 Service 层保存逻辑
- [ ] 4.2.3 返回保存结果响应
## 5. 测试与验证 ## 5. 测试与验证
- [ ] 5.1 编写查询方法论配置单元测试 - [x] 5.1 编写查询方法论配置单元测试(3 个用例:空配置返回默认 / 有数据查询 / 步骤排序)
- [ ] 5.1.1 测试正常查询流程 - [x] 5.2 编写保存方法论配置单元测试(6 个用例:新建 / 更新覆盖 / 步骤太少 / 序号不连续 / 序号重复 / 缓存失效)
- [ ] 5.1.2 测试配置不存在时的返回逻辑 - [x] 5.3 集成测试: 空查询 → 保存 → 再查询(步骤顺序验证)
- [ ] 5.1.3 测试步骤排序正确性 - [x] 5.4 更新 H5 首页测试(methodology_returned 从 DB 构建 / empty_site 无 methodology 返回 disable)
- [ ] 5.2 编写保存方法论配置单元测试
- [ ] 5.2.1 测试正常保存流程
- [ ] 5.2.2 测试步骤数量校验(少于 4 个或多于 10 个返回 400)
- [ ] 5.2.3 测试步骤序号连续性校验(序号不连续返回 400)
- [ ] 5.2.4 测试字段长度校验
- [ ] 5.2.5 测试事务回滚(保存失败时不保留部分数据)
- [ ] 5.2.6 测试缓存失效是否生效
- [ ] 5.3 集成测试: 查询配置 → 修改配置 → 再次查询 的完整链路
\ No newline at end of file \ No newline at end of file
## 1. 基础设施准备 ## 1. 基础设施准备
- [ ] 1.1 配置 OSS/CDN 客户端 - [x] 1.1 配置 OSS/CDN 客户端(使用已有的 OSSClient Protocol + InMemoryOSSClient 占位实现)
- [ ] 配置 AccessKey/SecretKey - [ ] 1.2 安装 Pillow/ffprobe 库用于高级图片/视频解析(当前使用纯 Python struct 解析 PNG/JPG 宽高,不支持视频宽高)
- [ ] 配置 Bucket 和 Region
- [ ] 配置 CDN 域名
- [ ] 1.2 安装和配置文件处理库
- [ ] Pillow(用于图片宽高获取)
- [ ] ffprobe(用于视频宽高获取,可选)
## 2. 模型与数据层 (Model & Schema) ## 2. 模型与数据层 (Model & Schema)
- [ ] 2.1 定义 Pydantic 请求与响应模型 - [x] 2.1 定义 Pydantic 响应模型 UploadMediaResponse(file_url, file_type, file_size, width, height, cdn_url)
- [ ] UploadMediaResponse (包含 file_url, file_type, file_size, width, height, cdn_url)
## 3. 业务逻辑层 (Service Layer) ## 3. 业务逻辑层 (Service Layer)
- [ ] 3.1 实现上传官网展示素材逻辑 - [x] 3.1 实现上传官网展示素材逻辑
- [ ] 3.1.1 接收并验证请求参数:file (multipart/form-data), usage_type (agent_media/methodology_icon/methodology_image) - [x] 3.1.1 接收 usage_type 参数并校验(agent_media/methodology_icon/methodology_image)
- [ ] 3.1.2 根据 usage_type 校验文件格式: - [x] 3.1.2 根据 usage_type 校验文件格式:
- agent_media:仅允许 gif/mp4 - agent_media:仅允许 gif/mp4
- methodology_icon/methodology_image:仅允许 png/jpg/jpeg - methodology_icon/methodology_image:仅允许 png/jpg/jpeg
- [ ] 3.1.3 根据 usage_type 校验文件大小: - [x] 3.1.3 根据 usage_type 校验文件大小:
- agent_media:最大 20MB(20971520 字节) - agent_media:最大 20MB(20971520 字节)
- methodology_icon:最大 2MB(2097152 字节) - methodology_icon:最大 2MB(2097152 字节)
- methodology_image:最大 10MB(10485760 字节) - methodology_image:最大 10MB(10485760 字节)
- [ ] 3.1.4 生成唯一文件名(使用 UUID 或时间戳) - [x] 3.1.4 生成带时间戳的唯一文件名,按用途类型分目录(agent/, methodology/icon/, methodology/image/)
- [ ] 3.1.5 根据 usage_type 确定上传路径: - [x] 3.1.5 上传文件到 OSS/CDN(InMemoryOSSClient 占位)
- agent_media:agent/ - [x] 3.1.6 获取文件信息:file_type(扩展名)、file_size(字节)
- methodology_icon:methodology/icon/ - [x] 3.1.7 解析图片宽高(纯 Python struct 解析 PNG/JPG,视频/非图片返回 None)
- methodology_image:methodology/image/ - [x] 3.1.8 生成 CDN URL(带版本号参数 ?v=YYYYMMDD)
- [ ] 3.1.6 上传文件到 OSS/CDN - [x] 3.1.9 返回完整上传结果
- [ ] 3.1.7 获取文件信息:
- file_type:文件扩展名
- file_size:文件大小(字节)
- width/height:图片/视频宽高(使用 Pillow/ffprobe 获取,可选)
- [ ] 3.1.8 生成 CDN URL(带版本号参数,如 ?v=20260516)
- [ ] 3.1.9 返回完整上传结果
## 4. 接口层 (API Layer) ## 4. 接口层 (API Layer)
- [ ] 4.1 挂载 `POST /api/v1/official-site/upload` 上传官网展示素材接口 - [x] 4.1 挂载 `POST /api/v1/official-site/upload` 上传官网展示素材接口(multipart/form-data)
- [ ] 4.1.1 实现 multipart/form-data 请求解析
- [ ] 4.1.2 调用 Service 层上传逻辑
- [ ] 4.1.3 返回标准化 JSON 响应
## 5. 测试与验证 ## 5. 测试与验证
- [ ] 5.1 编写上传官网展示素材单元测试 - [x] 5.1 编写上传官网展示素材单元测试(11 个用例)
- [ ] 5.1.1 测试正常上传流程(agent_media/gif) - [x] 5.1.1 正常上传 agent_media/gif
- [ ] 5.1.2 测试正常上传流程(agent_media/mp4) - [x] 5.1.2 正常上传 agent_media/mp4
- [ ] 5.1.3 测试正常上传流程(methodology_icon/png) - [x] 5.1.3 正常上传 methodology_icon/png(含宽高解析)
- [ ] 5.1.4 测试正常上传流程(methodology_image/jpg) - [x] 5.1.4 正常上传 methodology_image/jpg(含宽高解析)
- [ ] 5.1.5 测试文件格式校验(不支持的格式返回 400) - [x] 5.1.5 文件格式校验(不支持的格式返回 400)
- [ ] 5.1.6 测试文件大小校验(超过限制返回 400) - [x] 5.1.6 agent_media 大小超限(返回 400)
- [ ] 5.1.7 测试返回的 CDN URL 包含版本号 - [x] 5.1.7 methodology_icon 大小超限(返回 400)
- [ ] 5.1.8 测试宽高信息正确获取(图片) - [x] 5.1.8 CDN URL 包含版本号参数
- [ ] 5.1.9 测试宽高信息可选(获取失败时留空) - [x] 5.1.9 非图片类型宽高为 None
- [x] 5.1.10 不支持的上传类型
- [x] 5.1.11 OSS 上传集成验证
\ No newline at end of file \ No newline at end of file
## 1. 数据库准备 ## 1. 数据库准备
- [ ] 1.1 创建 `position_tags` 表的迁移脚本 - [x] 1.1 创建 `position_tags` 表的迁移脚本(同时包含 `official_tabs` 占位表)
- [ ] 1.2 运行迁移脚本并验证表结构 - [ ] 1.2 运行迁移脚本并验证表结构
## 2. 模型与数据层 (Model & Schema) ## 2. 模型与数据层 (Model & Schema)
- [ ] 2.1 定义 SQLAlchemy ORM 模型 `PositionTag` - [x] 2.1 定义 SQLAlchemy ORM 模型 `PositionTag` + `OfficialTab`
- [ ] 2.2 定义 Pydantic 请求模型 (Create/Update DTO) - [x] 2.2 定义 Pydantic 请求模型 (Create/Update DTO)
- [ ] 2.3 定义 Pydantic 响应模型 (List/Statistics/Reference DTO) - [x] 2.3 定义 Pydantic 响应模型 (List/Statistics/Reference DTO)
## 3. 业务逻辑层 (Service Layer) ## 3. 业务逻辑层 (Service Layer)
- [ ] 3.1 实现岗位标签创建逻辑(包含编码唯一性校验) - [x] 3.1 实现岗位标签创建逻辑(包含编码唯一性校验)
- [ ] 3.2 实现岗位标签编辑逻辑(禁止修改编码) - [x] 3.2 实现岗位标签编辑逻辑(禁止修改编码)
- [ ] 3.3 实现岗位标签引用检查逻辑(聚合多表查询) - [x] 3.3 实现岗位标签引用检查逻辑(聚合多表查询:渠道活码按 position_name 匹配、官网 Tab 按 position_id 匹配、Agent 按 agent_positions 关联)
- [ ] 3.4 实现岗位标签删除逻辑(包含阻塞校验和关联清理) - [x] 3.4 实现岗位标签删除逻辑(包含阻塞校验和关联清理:物理删除 + 自动清理 agent_positions 中间表)
- [ ] 3.5 实现岗位关联 Agent 统计逻辑 - [x] 3.5 实现岗位关联 Agent 统计逻辑(agent_count / active_agent_count / agents 列表)
## 4. 接口层 (API Layer) ## 4. 接口层 (API Layer)
- [ ] 4.1 挂载 `POST /api/v1/position-tags` 创建接口 - [x] 4.1 挂载 `POST /api/v1/position-tags` 创建接口
- 请求参数:`name`(20字), `code`(唯一), `description`(100字) - 请求参数:`name`(20字), `code`(唯一), `description`(100字)
- [ ] 4.2 挂载 `PUT /api/v1/position-tags/{tag_id}` 编辑接口 - [x] 4.2 挂载 `PUT /api/v1/position-tags/{tag_id}` 编辑接口
- 请求参数:`name`, `description` (code 不可改) - 请求参数:`name`, `description` (code 不可改)
- [ ] 4.3 挂载 `DELETE /api/v1/position-tags/{tag_id}` 删除接口 - [x] 4.3 挂载 `DELETE /api/v1/position-tags/{tag_id}` 删除接口
- 请求参数:`confirm_detach_agents` (boolean) - 请求参数:`confirm_detach_agents` (boolean, Query 参数)
- [ ] 4.4 挂载 `GET /api/v1/position-tags/{tag_id}/references` 引用检查接口 - [x] 4.4 挂载 `GET /api/v1/position-tags/{tag_id}/references` 引用检查接口
- 响应:包含 `blocking_references` (活码、Tab) 和 `detachable_references` (Agent) - 响应:包含 `can_delete`, `blocking_references` (活码、Tab), `detachable_references` (Agent), `hints`
- [ ] 4.5 挂载 `GET /api/v1/position-tags` 列表接口 - [x] 4.5 挂载 `GET /api/v1/position-tags` 列表接口
- 查询参数:`page`, `page_size`, `keyword` - 查询参数:`page`, `page_size`, `keyword`
- [ ] 4.6 挂载 `GET /api/v1/position-tags/{tag_id}/agents/statistics` 统计接口 - [x] 4.6 挂载 `GET /api/v1/position-tags/{tag_id}/agents/statistics` 统计接口
- 响应:包含 `agent_count`, `active_agent_count`, `agents` 列表 - 响应:包含 `agent_count`, `active_agent_count`, `agents` 列表
## 5. 测试与验证 ## 5. 测试与验证
- [ ] 5.1 编写岗位标签基础 CRUD 的单元测试 - [x] 5.1 编写岗位标签基础 CRUD 的单元测试(创建/编辑/列表/404 等 10 个用例)
- [ ] 5.2 编写引用检查逻辑的集成测试(模拟 Agent/渠道活码/官网 Tab 引用) - [x] 5.2 编写引用检查逻辑的集成测试(模拟 Agent/渠道活码/官网 Tab 引用,4 个用例)
- [ ] 5.3 验证删除接口的阻塞与清理行为 - [x] 5.3 验证删除接口的阻塞与清理行为(无引用删除/阻塞引用 409/确认解除关联/未确认 409,5 个用例)
- [ ] 5.4 确保所有接口符合 RESTful 规范并记录文档 - [x] 5.4 确保所有接口符合 RESTful 规范(22 个测试全部通过)
## 1. 统一消息入口实现 (Steward Agent) ## 1. 统一消息入口实现 (Steward Agent)
- [ ] 1.1 定义消息入口 `POST /api/v1/chat/completions` 的请求参数结构: - [x] 1.1 定义消息入口 `POST /api/v1/chat/completions` 的请求参数结构:
- `session_id` (string, required): 会话唯一标识 - `session_id` (string, required): 会话唯一标识
- `user_id` (string, required): 企微员工 ID - `user_id` (string, required): 企微员工 ID
- `channel` (string, required): 渠道来源(如 wechat_group) - `channel` (string, required): 渠道来源(如 wechat_group)
- `query` (string, required): 用户对话内容 - `query` (string, required): 用户对话内容
- `mentioned_agent_code` (string, optional): 被@的 Agent 编码 - `mentioned_agent_code` (string, optional): 被@的 Agent 编码
- `file_url` (string, optional): 关联的文件地址 - `file_url` (string, optional): 关联的文件地址
- [ ] 1.2 实现路由决策树逻辑(Mention > Inheritance > Default) - [x] 1.2 实现路由决策树逻辑(Mention > Inheritance > Default)
- [ ] 1.3 集成 LLM 意图识别服务,返回 8 种标准意图 - Mention: 检查 mentioned_agent_code,直接路由至该 Agent,routing_reason="mention"
- [ ] 1.4 实现响应体结构封装,包含 `response_agent_id`, `response_content`, `routing_reason` 等字段 - Inheritance: 无@且会话中存在 current_agent_id,路由至该 Agent,routing_reason="inheritance"
- Default: 路由至管家 Agent(code="steward"),routing_reason="default"
- [x] 1.3 集成 LLM 意图识别服务,返回标准意图
- 当前实现: InMemoryLLMClient(关键词匹配),LLMClient Protocol 可替换为真实 LLM
- Mention 路由跳过意图识别(优化延迟),仅 Inheritance 和 Default 路径调用 LLM
- [x] 1.4 实现响应体结构封装,包含 `routing`, `intent`, `handoff`, `response_content` 等字段
- routing: agent_id, agent_code, agent_name, routing_reason
- handoff: from_agent_id/name, to_agent_id/name, handoff_message(自动生成转交话术)
## 2. 多模态文件处理 ## 2. 多模态文件处理
- [ ] 2.1 定义文件上传接口 `POST /api/v1/files/upload` (multipart/form-data): - [x] 2.1 定义文件上传接口 `POST /api/v1/files/upload` (multipart/form-data):
- `file` (binary, required): 文件对象(限制格式及 10MB 大小) - `file` (binary, required): 文件对象
- `session_id` (string, required): 关联会话 ID - `session_id` (string, required): 关联会话 ID
- [ ] 2.2 集成 OSS 上传功能,返回文件持久化 URL - 支持格式: pdf, png, jpg, jpeg, doc, docx, xls, xlsx
- [ ] 2.3 集成 OCR/文本提取服务,解析 PDF、图片、Office 文档内容 - 大小限制: 10MB
- [ ] 2.4 将提取出的文本关联至会话上下文实体中 - [x] 2.2 集成 OSS 上传功能(OSSClient Protocol + InMemoryOSSClient 占位实现)
- [x] 2.3 集成 OCR/文本提取服务(FileParser Protocol + InMemoryFileParser 占位实现)
- PDF/Word/Excel 文件自动调用文本提取
- 图片文件仅上传不提取
- [ ] 2.4 将提取出的文本关联至会话上下文实体中(待与 SessionService 集成)
## 3. 辅助功能与联调 ## 3. 辅助功能与联调
- [ ] 3.1 实现 Agent 切换时的转交话术自动生成逻辑 - [x] 3.1 实现 Agent 切换时的转交话术自动生成逻辑
- [ ] 3.2 异步记录对话路由日志及处理耗时埋点 - 当 prev_agent_id 与 target_agent.id 不同时,自动生成 "收到,已转交给{agent_name}处理。"
- [ ] 3.3 编写路由逻辑的单元测试,覆盖各种优先级场景 - 首次消息无 prev_agent_id,不生成 handoff
- [ ] 3.4 模拟多模态输入,验证文件解析到意图识别的完整链路 - [ ] 3.2 异步记录对话路由日志及处理耗时埋点(待日志基础设施就绪)
- [x] 3.3 编写路由逻辑的单元测试,覆盖各种优先级场景(17 个测试用例)
- [x] 3.4 模拟多模态输入,验证文件解析到意图识别的完整链路(FileService 4 个测试)
## 基础设施抽象层(可替换为真实实现)
- [x] LLMClient Protocol + InMemoryLLMClient(关键词匹配意图识别)
- [x] OSSClient Protocol + InMemoryOSSClient(内存文件存储)
- [x] FileParser Protocol + InMemoryFileParser(可注入 OCR 结果)
## 1. 基础设施与数据库准备 ## 1. 基础设施与数据库准备
- [ ] 1.1 配置 Redis 连接池,定义会话 Key 规范 - [x] 1.1 配置 KV 存储抽象层(当前为 InMemoryKeyValueStore,支持 TTL 过期;KeyValueStore Protocol 可替换为 Redis)
- [ ] 1.2 创建 `sessions` 和 `conversation_history` 表的迁移脚本 - [x] 1.2 创建 `sessions` 和 `conversation_history` 表的迁移脚本(005_create_sessions.sql)
- [ ] 1.3 运行迁移脚本并验证持久化表结构 - [ ] 1.3 运行迁移脚本并验证持久化表结构
## 2. 模型与数据层 (Model & Schema) ## 2. 模型与数据层 (Model & Schema)
- [ ] 2.1 定义会话相关的 Pydantic 请求模型 (Create/Update/Archive DTO) - [x] 2.1 定义 Pydantic 请求模型 (SessionCreateRequest / SessionUpdateRequest)
- [ ] 2.2 定义会话详情及上下文响应模型 (SessionDetail/ContextDTO) - [x] 2.2 定义 Pydantic 响应模型 (SessionCreateResponse / SessionUpdateResponse / SessionDetailResponse / SessionContextResponse / SessionArchiveResponse)
- [ ] 2.3 定义 Redis 存储的 JSON 序列化模型 - [x] 2.3 定义 SQLAlchemy ORM 模型 (Session + ConversationHistory,含 SessionStatus 枚举)
- [x] 2.4 定义 KV 存储序列化模型 (_ActiveSessionPayload dataclass)
## 3. 业务逻辑层 (Service Layer) ## 3. 业务逻辑层 (Service Layer)
- [ ] 3.1 实现会话创建逻辑 - [x] 3.1 实现会话创建逻辑
- [ ] 3.1.1 生成唯一 `session_id` (sess_前缀) - [x] 3.1.1 生成唯一 `session_id` (sess_ 前缀 + token_urlsafe)
- [ ] 3.1.2 初始化 `conversation_history` 为空数组 - [x] 3.1.2 初始化 `conversation_history` 为空数组
- [ ] 3.1.3 初始化 `context_entities` 为空对象 - [x] 3.1.3 初始化 `context_entities` 为空对象
- [ ] 3.1.4 写入 Redis(TTL=30 分钟) - [x] 3.1.4 写入 KV 存储(TTL=30 分钟)
- [ ] 3.2 实现会话历史追加与实体合并逻辑 - [x] 3.2 实现会话历史追加与实体合并逻辑
- [ ] 3.2.1 追加对话历史到 `conversation_history` - [x] 3.2.1 追加对话历史到 `conversation_history`
- [ ] 3.2.2 更新 `context_entities`(覆盖或合并策略) - [x] 3.2.2 更新 `context_entities`(合并策略:incoming 覆盖 base 同名 key)
- [ ] 3.2.3 更新 `current_agent_id` - [x] 3.2.3 更新 `current_agent_id`
- [ ] 3.2.4 刷新 Redis TTL - [x] 3.2.4 写入 KV 存储自动刷新 TTL
- [ ] 3.3 实现会话详情查询逻辑 - [x] 3.3 实现会话详情查询逻辑
- [ ] 3.3.1 支持从 Redis 读取活跃会话 - [x] 3.3.1 支持从 KV 存储读取活跃会话(含 agent_name 关联查询)
- [ ] 3.3.2 支持从数据库读取已归档会话 - [x] 3.3.2 支持从数据库读取已归档会话(context_entities 归档后为空)
- [ ] 3.4 实现上下文继承提取逻辑 - [x] 3.4 实现上下文继承提取逻辑
- [ ] 3.4.1 读取 `context_entities` - [x] 3.4.1 读取 `context_entities`
- [ ] 3.4.2 检查是否超时(30 分钟无活动,基于 Redis 存在性) - [x] 3.4.2 检查是否超时(基于 KV 存在性 + expires_at 计算)
- [ ] 3.4.3 返回继承实体信息 - [x] 3.4.3 返回继承实体信息及 `inheritance_valid` 标志
- [ ] 3.5 实现会话归档逻辑 - [x] 3.5 实现会话归档逻辑
- [ ] 3.5.1 从 Redis 读取全量会话数据 - [x] 3.5.1 从 KV 存储读取全量会话数据
- [ ] 3.5.2 批量写入数据库 `conversation_history` 表 - [x] 3.5.2 批量写入数据库 `conversation_history` 表
- [ ] 3.5.3 删除 Redis 中的会话 Key - [x] 3.5.3 删除 KV 存储中的会话 Key
- [ ] 3.5.4 标记数据库会话状态为 `archived` - [x] 3.5.4 标记数据库会话状态为 `archived`
## 4. 接口层 (API Layer) ## 4. 接口层 (API Layer)
- [ ] 4.1 挂载 `POST /api/v1/sessions` 创建接口 - [x] 4.1 挂载 `POST /api/v1/sessions` 创建接口
- [ ] 4.2 挂载 `PUT /api/v1/sessions/{session_id}` 更新接口 - [x] 4.2 挂载 `PUT /api/v1/sessions/{session_id}` 更新接口
- [ ] 4.3 挂载 `GET /api/v1/sessions/{session_id}` 详情接口 - [x] 4.3 挂载 `GET /api/v1/sessions/{session_id}` 详情接口
- [ ] 4.4 挂载 `GET /api/v1/sessions/{session_id}/context` 上下文继承接口 - [x] 4.4 挂载 `GET /api/v1/sessions/{session_id}/context` 上下文继承接口
- [ ] 4.5 挂载 `POST /api/v1/sessions/{session_id}/archive` 归档接口 - [x] 4.5 挂载 `POST /api/v1/sessions/{session_id}/archive` 归档接口
## 5. 测试与验证 ## 5. 测试与验证
- [ ] 5.1 编写会话创建与 TTL 自动过期的单元测试 - [x] 5.1 编写会话创建 + 更新 + 详情 + 上下文的集成测试(完整流程验证)
- [ ] 5.2 编写多轮对话历史追加及实体合并的逻辑测试 - [x] 5.2 编写多轮对话历史追加及实体合并的逻辑测试(turn_count / context_entities 合并验证)
- [ ] 5.3 验证会话归档的完整性(字段对齐、Redis 清理) - [x] 5.3 编写会话归档的完整性测试(归档后详情仍可读、context 失效、inheritance_valid=false)
- [ ] 5.4 压力测试:验证高频更新会话时的 Redis 性能 - [ ] 5.4 替换为 Redis 实现后验证 TTL 自动过期和性能
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!