Commit 35d1b14f by imwangxiaozhou

refactor(backend): 全面迁移至MySQL,移除SQLite支持并优化业务逻辑

- 完成项目从SQLite到MySQL的全面迁移,移除所有SQLite相关的默认配置与连接逻辑,强制要求通过`DATABASE_URL`配置合法的mysql+pymysql://格式连接字符串
- 更新docker-compose配置、env示例文件,移除本地dev.db挂载与默认SQLite兜底连接
- 新增SQLite数据一键迁移脚本`scripts/import_sqlite_to_mysql.py`,支持将本地SQLite数据导入MySQL
- 重构统一日志配置模块,替换原有零散的logging初始化代码,支持按服务名生成日志文件
- 优化官网首页展示逻辑:从Agent表实时获取agent名称与运行状态,不再依赖展示配置中的缓存旧数据
- 新增agent增改操作后自动失效首页缓存的逻辑,确保页面数据实时性
- 将官网标签页默认的agent展示状态修改为禁用
- 重构企微同步服务,优化增量同步逻辑,新增检查点手动管理API接口
- 优化企微调试接口,将客户群重置逻辑改为标记禁用而非直接删除数据
- 新增大量单元测试,调整测试配置要求使用`TEST_DATABASE_URL`环境变量
- 补全项目中缺失的模型导入,优化本地依赖路径加载逻辑
1 parent fd892279
Showing 33 changed files with 1073 additions and 198 deletions
# 数据库(默认 SQLite,可切换 MySQL) # 数据库(仅支持 MySQL,需显式配置用户名)
DATABASE_URL=sqlite:///./dev.db DATABASE_URL=mysql+pymysql://<MYSQL_USER>:JEIjHeLT@192.168.3.92:3308/biz_multi_agentic?charset=utf8mb4
# DATABASE_URL=mysql+pymysql://user:pass@host:3306/agent_admin TEST_DATABASE_URL=mysql+pymysql://<MYSQL_USER>:JEIjHeLT@192.168.3.92:3308/biz_multi_agentic?charset=utf8mb4
# IM 服务 # IM 服务
USE_CONSOLE_IM=false USE_CONSOLE_IM=false
......
...@@ -9,10 +9,17 @@ ...@@ -9,10 +9,17 @@
运行时配置: 运行时配置:
- 启动相关 `host`、`port`、`reload` 以及 IM / WeCom Sync 默认地址统一放在 `config/settings.json` - 启动相关 `host`、`port`、`reload` 以及 IM / WeCom Sync 默认地址统一放在 `config/settings.json`
- 数据库连接统一通过 `DATABASE_URL` / `TEST_DATABASE_URL` 指向 MySQL,字符集使用 `utf8mb4`
- 本地启动前如需改端口或 host,优先修改该文件 - 本地启动前如需改端口或 host,优先修改该文件
- 如需临时覆盖,仍可通过环境变量覆盖,例如 `IM_BASE_URL`、`WECOM_SYNC_BASE_URL` - 如需临时覆盖,仍可通过环境变量覆盖,例如 `IM_BASE_URL`、`WECOM_SYNC_BASE_URL`
- 当前局域网访问建议使用 `python -m app.main` 启动,按 `config/settings.json` 监听 `http://192.168.1.191:8000` - 当前局域网访问建议使用 `python -m app.main` 启动,按 `config/settings.json` 监听 `http://192.168.1.191:8000`
本地测试:
- backend 测试默认要求设置 `TEST_DATABASE_URL`
- 示例:`mysql+pymysql://root:root@127.0.0.1:3306/agent_admin_test?charset=utf8mb4`
- 本次迁移只覆盖 backend 进程与 backend 测试,不要求启动 `scheduler`
职责范围: 职责范围:
- 为 `web` 提供业务接口。 - 为 `web` 提供业务接口。
......
from __future__ import annotations
import sys
from pathlib import Path
def _ensure_repo_deps_on_path() -> None:
deps = Path(__file__).resolve().parents[1] / ".deps"
if deps.exists():
deps_str = str(deps)
if deps_str not in sys.path:
sys.path.insert(0, deps_str)
_ensure_repo_deps_on_path()
...@@ -26,14 +26,10 @@ router = APIRouter(prefix="/api/v1/wecom-debug", tags=["wecom-debug"]) ...@@ -26,14 +26,10 @@ router = APIRouter(prefix="/api/v1/wecom-debug", tags=["wecom-debug"])
"/overview", "/overview",
response_model=ApiResponse[WeComDebugOverviewResponse], response_model=ApiResponse[WeComDebugOverviewResponse],
summary="查询企微调试总览", summary="查询企微调试总览",
description=( description="一次性返回当前库里的全部一客一群记录、消息记录、建群请求记录,用于本地排查同步链路。",
"一次性返回当前库里的全部一客一群记录、全部消息记录、全部建群请求记录。"
" 这个接口主要用于本地排查同步链路,不做分页。"
),
) )
def get_wecom_debug_overview(db: Session = Depends(get_db)): def get_wecom_debug_overview(db: Session = Depends(get_db)):
customer_groups = db.query(WeComCustomerGroup).order_by(WeComCustomerGroup.id.asc()).all() customer_groups = db.query(WeComCustomerGroup).order_by(WeComCustomerGroup.id.asc()).all()
# `payload` 可能包含历史坏数据;调试总览不展示该字段,因此明确排除它,避免整接口被单条脏消息打挂。
messages = ( messages = (
db.query(WeComMessage) db.query(WeComMessage)
.options( .options(
...@@ -137,35 +133,45 @@ def get_wecom_debug_overview(db: Session = Depends(get_db)): ...@@ -137,35 +133,45 @@ def get_wecom_debug_overview(db: Session = Depends(get_db)):
@router.post( @router.post(
"/customer-groups/reset", "/customer-groups/reset",
response_model=ApiResponse[WeComDebugResetCustomerGroupResponse], response_model=ApiResponse[WeComDebugResetCustomerGroupResponse],
summary="重置客户建群结果", summary="精准禁用客户群关系",
description=( description=(
"按客户 contact_id 重置一客一群记录。" "按 bot_id + customer_contact_id 精准禁用一条本地群关系。"
" 当前实现会删除该客户在本地库中的一客一群记录与建群请求记录,便于后续重新发起建群。" " 当前实现会把匹配到的群记录标记为 invalid,并将该 bot 下此客户仍处于 pending 的建群请求标记为 failed。"
), ),
) )
def reset_customer_group(req: WeComDebugResetCustomerGroupRequest, db: Session = Depends(get_db)): def reset_customer_group(req: WeComDebugResetCustomerGroupRequest, db: Session = Depends(get_db)):
customer_groups = ( customer_groups = (
db.query(WeComCustomerGroup) db.query(WeComCustomerGroup)
.filter(WeComCustomerGroup.customer_contact_id == req.customer_contact_id) .filter(
WeComCustomerGroup.bot_id == req.bot_id,
WeComCustomerGroup.customer_contact_id == req.customer_contact_id,
WeComCustomerGroup.is_deleted == False,
)
.all() .all()
) )
group_create_requests = ( group_create_requests = (
db.query(WeComGroupCreateRequest) db.query(WeComGroupCreateRequest)
.filter(WeComGroupCreateRequest.customer_contact_id == req.customer_contact_id) .filter(
WeComGroupCreateRequest.bot_id == req.bot_id,
WeComGroupCreateRequest.customer_contact_id == req.customer_contact_id,
WeComGroupCreateRequest.status == "pending",
)
.all() .all()
) )
now = datetime.now(timezone.utc) now = datetime.now(timezone.utc)
for row in customer_groups: for row in customer_groups:
db.delete(row) row.group_status = "invalid"
for row in group_create_requests: for row in group_create_requests:
db.delete(row) row.status = "failed"
row.fail_reason = "manual_invalidated"
db.commit() db.commit()
payload = WeComDebugResetCustomerGroupResponse( payload = WeComDebugResetCustomerGroupResponse(
success=True, success=True,
deleted_customer_groups_count=len(customer_groups), invalidated_customer_groups_count=len(customer_groups),
deleted_group_create_requests_count=len(group_create_requests), failed_group_create_requests_count=len(group_create_requests),
bot_id=req.bot_id,
customer_contact_id=req.customer_contact_id, customer_contact_id=req.customer_contact_id,
updated_at=now, updated_at=now,
) )
...@@ -179,8 +185,6 @@ def reset_customer_group(req: WeComDebugResetCustomerGroupRequest, db: Session = ...@@ -179,8 +185,6 @@ def reset_customer_group(req: WeComDebugResetCustomerGroupRequest, db: Session =
description=( description=(
"手工把某条建群请求改成 success 或 failed。" "手工把某条建群请求改成 success 或 failed。"
" 适用于外部接口已处理完成,但本地状态未同步或需要人工修正的场景。" " 适用于外部接口已处理完成,但本地状态未同步或需要人工修正的场景。"
" 当改为 success 时,可以补录群 contact_id、群名称和 contact_type;"
" 当改为 failed 时,建议补充 fail_reason。"
), ),
) )
def update_group_create_request_status( def update_group_create_request_status(
......
...@@ -12,6 +12,8 @@ from app.schema.common import ApiResponse, PageData, success_response_payload ...@@ -12,6 +12,8 @@ from app.schema.common import ApiResponse, PageData, success_response_payload
from app.schema.wecom_sync import ( from app.schema.wecom_sync import (
WeComSyncCheckpointItem, WeComSyncCheckpointItem,
WeComSyncCheckpointListResponse, WeComSyncCheckpointListResponse,
WeComSyncCheckpointUpsertRequest,
WeComSyncCheckpointUpsertResponse,
WeComSyncRunRequest, WeComSyncRunRequest,
WeComSyncRunResponse, WeComSyncRunResponse,
) )
...@@ -29,23 +31,14 @@ def get_wecom_sync_service(db: Session = Depends(get_db)) -> WeComSyncService: ...@@ -29,23 +31,14 @@ def get_wecom_sync_service(db: Session = Depends(get_db)) -> WeComSyncService:
@router.post("/run", response_model=ApiResponse[WeComSyncRunResponse]) @router.post("/run", response_model=ApiResponse[WeComSyncRunResponse])
def run_wecom_sync(req: WeComSyncRunRequest, svc: WeComSyncService = Depends(get_wecom_sync_service), db: Session = Depends(get_db)): def run_wecom_sync(req: WeComSyncRunRequest, svc: WeComSyncService = Depends(get_wecom_sync_service), db: Session = Depends(get_db)):
try: try:
if req.mode == "full": bot_ids = req.bot_ids
result = svc.sync_all_full( if not bot_ids:
message_start_time=req.message_start_time, bot_ids = [item.bot_id for item in db.query(WeComBot).order_by(WeComBot.id.asc()).all()]
message_end_time=req.message_end_time, result = svc.sync_wecom_bots_groups_messages(
) bot_ids=bot_ids,
else: start_time=req.message_start_time,
bot_ids = req.bot_ids end_time=req.message_end_time,
if not bot_ids: )
bot_ids = [item.bot_id for item in db.query(WeComBot).order_by(WeComBot.id.asc()).all()]
result = {
"bots": 0,
"messages": svc.sync_messages_incremental(
bot_ids=bot_ids,
start_time=req.message_start_time,
end_time=req.message_end_time,
),
}
payload = WeComSyncRunResponse( payload = WeComSyncRunResponse(
mode=req.mode, mode=req.mode,
bots=result["bots"], bots=result["bots"],
...@@ -59,7 +52,20 @@ def run_wecom_sync(req: WeComSyncRunRequest, svc: WeComSyncService = Depends(get ...@@ -59,7 +52,20 @@ def run_wecom_sync(req: WeComSyncRunRequest, svc: WeComSyncService = Depends(get
raise HTTPException(status_code=400, detail=str(exc)) raise HTTPException(status_code=400, detail=str(exc))
@router.get("/checkpoints", response_model=ApiResponse[WeComSyncCheckpointListResponse]) @router.get(
"/checkpoints",
response_model=ApiResponse[WeComSyncCheckpointListResponse],
summary="分页查询企微同步检查点",
description=(
"查询当前本地保存的企微同步检查点(checkpoint)。"
"检查点用于控制增量同步从哪里继续执行。"
"其中 `bots/global` 通常表示机器人列表同步断点;"
"`messages/group:<group_id>` 表示某个客户群的消息同步断点;"
"`customers/bot:<bot_id>` 表示某个机器人的客户扫描断点。"
"如果你需要排查“为什么某个群没有继续拉新消息”或“希望从某个时间点之后重新增量同步”,"
"先用这个接口找到对应的检查点记录。"
),
)
def list_wecom_sync_checkpoints( def list_wecom_sync_checkpoints(
page: int = Query(1, ge=1), page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100), page_size: int = Query(20, ge=1, le=100),
...@@ -81,6 +87,7 @@ def list_wecom_sync_checkpoints( ...@@ -81,6 +87,7 @@ def list_wecom_sync_checkpoints(
scope_key=item.scope_key, scope_key=item.scope_key,
last_sync_time=item.last_sync_time, last_sync_time=item.last_sync_time,
last_external_id=item.last_external_id, last_external_id=item.last_external_id,
last_sync_cursor=item.last_sync_cursor,
last_status=item.last_status, last_status=item.last_status,
last_error=item.last_error, last_error=item.last_error,
last_started_at=item.last_started_at, last_started_at=item.last_started_at,
...@@ -90,3 +97,43 @@ def list_wecom_sync_checkpoints( ...@@ -90,3 +97,43 @@ def list_wecom_sync_checkpoints(
], ],
) )
return success_response_payload(200, payload.model_dump(mode="json")) return success_response_payload(200, payload.model_dump(mode="json"))
@router.post(
"/checkpoints",
response_model=ApiResponse[WeComSyncCheckpointUpsertResponse],
summary="手工创建或更新企微同步检查点",
description=(
"手工写入某个同步检查点,常用于调试或人工修复增量同步断点。"
"写入后,下一次同步会把该值当成“已经处理到这里”的位置。"
"典型用途:"
"1. 将 `messages/group:<group_id>` 的 `last_sync_time` 调整到某个时间点,使该群只从这个时间点之后继续拉消息;"
"2. 将 `bots/global` 调整到某个时间点,使机器人列表同步只处理该时间点之后更新的机器人;"
"3. 将 `customers/bot:<bot_id>` 调整到某个时间点,使该机器人只从这个时间点之后继续扫描客户;"
"4. 配合 `last_external_id` 处理“同一时间戳下多条记录”的去重边界。"
"注意:该接口不会立即触发同步,只会修改断点;需要后续由调度器或 `/api/v1/wecom-sync/run` 生效。"
),
)
def upsert_wecom_sync_checkpoint(
req: WeComSyncCheckpointUpsertRequest,
svc: WeComSyncService = Depends(get_wecom_sync_service),
):
try:
checkpoint = svc.upsert_checkpoint(
resource_type=req.resource_type,
scope_key=req.scope_key,
last_sync_time=req.last_sync_time,
last_external_id=req.last_external_id,
last_sync_cursor=req.last_sync_cursor,
)
payload = WeComSyncCheckpointUpsertResponse(
resource_type=checkpoint.resource_type,
scope_key=checkpoint.scope_key,
last_sync_time=checkpoint.last_sync_time,
last_external_id=checkpoint.last_external_id,
last_sync_cursor=checkpoint.last_sync_cursor,
updated_at=checkpoint.updated_at,
)
return success_response_payload(200, payload.model_dump(mode="json"))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
...@@ -2,15 +2,14 @@ import json ...@@ -2,15 +2,14 @@ import json
import os import os
from pathlib import Path from pathlib import Path
from typing import Dict, Optional, Tuple from typing import Dict, Optional, Tuple
from pydantic import ValidationError from pydantic import ValidationError
from app.config.settings import (
ModelConfig, AgentConfig, Settings from app.config.settings import AgentConfig, ModelConfig, Settings
)
class ConfigLoadError(Exception): class ConfigLoadError(Exception):
"""Raised when config loading or validation fails.""" """Raised when config loading or validation fails."""
pass
class ConfigLoader: class ConfigLoader:
...@@ -24,20 +23,19 @@ class ConfigLoader: ...@@ -24,20 +23,19 @@ class ConfigLoader:
try: try:
with open(filepath, "r", encoding="utf-8") as f: with open(filepath, "r", encoding="utf-8") as f:
return json.load(f) return json.load(f)
except FileNotFoundError: except FileNotFoundError as exc:
raise ConfigLoadError(f"配置文件不存在: {filepath}") raise ConfigLoadError(f"配置文件不存在: {filepath}") from exc
except json.JSONDecodeError as e: except json.JSONDecodeError as exc:
raise ConfigLoadError(f"配置文件JSON格式错误: {filepath} - {e}") raise ConfigLoadError(f"配置文件 JSON 格式错误: {filepath} - {exc}") from exc
def load_agents(self) -> Dict[str, AgentConfig]: def load_agents(self) -> Dict[str, AgentConfig]:
data = self._load_json("agents.json") data = self._load_json("agents.json")
try: try:
return {code: AgentConfig(**config) for code, config in data["agents"].items()} return {code: AgentConfig(**config) for code, config in data["agents"].items()}
except ValidationError as e: except ValidationError as exc:
raise ConfigLoadError(f"Agent配置验证失败: {e}") raise ConfigLoadError(f"Agent 配置校验失败: {exc}") from exc
def load_skills_from_toolkit(self, toolkit) -> Dict[str, dict]: def load_skills_from_toolkit(self, toolkit) -> Dict[str, dict]:
"""Read registered skill metadata from AgentScope Toolkit (not from skills.json file)."""
skills = {} skills = {}
for name, skill in toolkit.skills.items(): for name, skill in toolkit.skills.items():
skills[name] = { skills[name] = {
...@@ -53,15 +51,12 @@ class ConfigLoader: ...@@ -53,15 +51,12 @@ class ConfigLoader:
data = self._load_json("models.json") data = self._load_json("models.json")
try: try:
return {name: ModelConfig(**config) for name, config in data["models"].items()} return {name: ModelConfig(**config) for name, config in data["models"].items()}
except ValidationError as e: except ValidationError as exc:
raise ConfigLoadError(f"模型配置验证失败: {e}") raise ConfigLoadError(f"模型配置校验失败: {exc}") from exc
def load_account_mappings(self) -> Tuple[Dict[str, str], Dict[str, str]]: def load_account_mappings(self) -> Tuple[Dict[str, str], Dict[str, str]]:
data = self._load_json("mappings.json") data = self._load_json("mappings.json")
return ( return data["agent_accounts"], data["account_agents"]
data["agent_accounts"],
data["account_agents"]
)
def load_settings(self) -> Settings: def load_settings(self) -> Settings:
filepath = self.config_dir / "settings.json" filepath = self.config_dir / "settings.json"
...@@ -70,5 +65,24 @@ class ConfigLoader: ...@@ -70,5 +65,24 @@ class ConfigLoader:
data = self._load_json("settings.json") data = self._load_json("settings.json")
try: try:
return Settings(**data) return Settings(**data)
except ValidationError as e: except ValidationError as exc:
raise ConfigLoadError(f"运行时配置验证失败: {e}") raise ConfigLoadError(f"运行时配置校验失败: {exc}") from exc
def load_database_url(self) -> str:
database_url = os.getenv("DATABASE_URL", "").strip()
if not database_url:
env_file = self.config_dir.parent / ".env"
if env_file.exists():
for line in env_file.read_text(encoding="utf-8").splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("#") or "=" not in stripped:
continue
key, value = stripped.split("=", 1)
if key.strip() == "DATABASE_URL":
database_url = value.strip().strip("'\"")
break
if not database_url:
raise ConfigLoadError("DATABASE_URL 未配置,backend 仅支持显式 MySQL 连接")
if not database_url.startswith("mysql+pymysql://"):
raise ConfigLoadError("DATABASE_URL 必须使用 mysql+pymysql://,不再支持 SQLite 兜底")
return database_url
from __future__ import annotations
from sqlalchemy import create_engine
from sqlalchemy.engine import make_url
from sqlalchemy.orm import declarative_base, sessionmaker from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy import create_engine, event
import os
# 数据库连接配置,实际开发中应从 config 读取
SQLALCHEMY_DATABASE_URL = os.getenv(
"DATABASE_URL",
"sqlite:///./dev.db"
)
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args=(
{
"check_same_thread": False,
"timeout": 30,
}
if SQLALCHEMY_DATABASE_URL.startswith("sqlite")
else {}
),
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base() from app.config.loader import ConfigLoader
SQLALCHEMY_DATABASE_URL = ConfigLoader().load_database_url()
DATABASE_DIALECT = make_url(SQLALCHEMY_DATABASE_URL).get_backend_name()
def _build_engine():
if DATABASE_DIALECT == "mysql":
return create_engine(
SQLALCHEMY_DATABASE_URL,
pool_pre_ping=True,
pool_recycle=3600,
)
raise RuntimeError(f"Unsupported database dialect: {DATABASE_DIALECT}. Only MySQL is allowed.")
engine = _build_engine()
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
if SQLALCHEMY_DATABASE_URL.startswith("sqlite"):
@event.listens_for(engine, "connect")
def set_sqlite_pragma(dbapi_connection, _connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA journal_mode=WAL;")
cursor.execute("PRAGMA busy_timeout=30000;")
cursor.execute("PRAGMA synchronous=NORMAL;")
cursor.close()
def get_db(): def get_db():
db = SessionLocal() db = SessionLocal()
......
from __future__ import annotations
import logging
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path
LOG_DIR = Path(__file__).resolve().parents[2] / "logs"
LOG_FORMAT = "%(asctime)s [%(levelname)s] %(name)s - %(message)s"
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
def configure_logging(service_name: str, level: int = logging.INFO) -> None:
root_logger = logging.getLogger()
target_logfile = (LOG_DIR / f"{service_name}.log").resolve()
for handler in root_logger.handlers:
if getattr(handler, "_agent_admin_log_configured", False) and getattr(handler, "_agent_admin_service_name", None) == service_name:
root_logger.setLevel(level)
return
LOG_DIR.mkdir(parents=True, exist_ok=True)
formatter = logging.Formatter(LOG_FORMAT, DATE_FORMAT)
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
console_handler._agent_admin_log_configured = True
console_handler._agent_admin_service_name = service_name
file_handler = TimedRotatingFileHandler(
filename=str(target_logfile),
when="midnight",
interval=1,
backupCount=7,
encoding="utf-8",
)
file_handler.setFormatter(formatter)
file_handler.suffix = "%Y-%m-%d"
file_handler._agent_admin_log_configured = True
file_handler._agent_admin_service_name = service_name
root_logger.handlers.clear()
root_logger.setLevel(level)
root_logger.addHandler(console_handler)
root_logger.addHandler(file_handler)
for logger_name in ("uvicorn", "uvicorn.error", "uvicorn.access", "apscheduler"):
logger = logging.getLogger(logger_name)
logger.handlers.clear()
logger.propagate = True
logger.setLevel(level)
...@@ -6,13 +6,11 @@ from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_EXECUTED, JobExecution ...@@ -6,13 +6,11 @@ from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_EXECUTED, JobExecution
from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.schedulers.blocking import BlockingScheduler
from app.config.loader import ConfigLoader from app.config.loader import ConfigLoader
from app.infrastructure.logging import configure_logging
from app.jobs.log_context import JOB_NAME_MAP from app.jobs.log_context import JOB_NAME_MAP
from app.jobs.runner import run_job from app.jobs.runner import run_job
logging.basicConfig( configure_logging("scheduler", logging.INFO)
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s - %(message)s",
)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
......
import json import json
import os import os
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
import logging
from fastapi import FastAPI, HTTPException, Request from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response from fastapi.responses import JSONResponse, Response
...@@ -8,14 +9,34 @@ from fastapi.responses import JSONResponse, Response ...@@ -8,14 +9,34 @@ from fastapi.responses import JSONResponse, Response
from app.api.v1.router import api_router from app.api.v1.router import api_router
from app.config.loader import ConfigLoader from app.config.loader import ConfigLoader
from app.infrastructure.database import engine from app.infrastructure.database import engine
from app.infrastructure.logging import configure_logging
from app.infrastructure.response_format import format_response_datetimes from app.infrastructure.response_format import format_response_datetimes
from app.infrastructure.schema_patch import ensure_runtime_schema from app.infrastructure.schema_patch import ensure_runtime_schema
from app.infrastructure.database import Base from app.infrastructure.database import Base
# Register all model tables with Base.metadata so create_all works # Register all model tables with Base.metadata so create_all works
from app.model.agent import Agent, AgentPosition, AgentSkill # noqa: F401 from app.model.agent import Agent, AgentPosition, AgentSkill # noqa: F401
from app.model.position_tag import PositionTag, OfficialTab # noqa: F401 from app.model.agent_group import QrcodeChannel, WeComEmployeeQrcode # noqa: F401
from app.model.analytics import ( # noqa: F401
AnalyticsEvent,
AnalyticsStatistic,
ConversationLog,
GroupJoinEvent,
PageView,
ScanEvent,
)
from app.model.methodology import OfficialSiteMethodology, OfficialSiteMethodologyStep # noqa: F401
from app.model.official_site_agent_display import OfficialSiteAgentDisplay # noqa: F401
from app.model.position_tag import PositionTag, OfficialTab, PositionTagUser # noqa: F401
from app.model.skill import Skill # noqa: F401 from app.model.skill import Skill # noqa: F401
from app.model.wecom_sync import ( # noqa: F401
WeComBot,
WeComCustomerGroup,
WeComGroupCreateRequest,
WeComJobConfig,
WeComMessage,
WeComSyncCheckpoint,
)
from app.schema.common import error_response_payload, is_wrapped_payload, success_response_payload from app.schema.common import error_response_payload, is_wrapped_payload, success_response_payload
from app.service.agent_hub import AgentHub from app.service.agent_hub import AgentHub
from app.service.active_session_service import ActiveSessionService from app.service.active_session_service import ActiveSessionService
...@@ -23,6 +44,7 @@ from app.service.console_im_service import ConsoleIMService ...@@ -23,6 +44,7 @@ from app.service.console_im_service import ConsoleIMService
from app.service.im_service import IMService from app.service.im_service import IMService
agent_hub_instance = None agent_hub_instance = None
configure_logging("backend", logging.INFO)
runtime_settings = ConfigLoader().load_settings() runtime_settings = ConfigLoader().load_settings()
base_path = (runtime_settings.server.base_path or "").rstrip("/") base_path = (runtime_settings.server.base_path or "").rstrip("/")
docs_url = f"{base_path}/docs" if base_path else "/docs" docs_url = f"{base_path}/docs" if base_path else "/docs"
......
...@@ -10,7 +10,7 @@ class WeComDebugCustomerGroupItem(BaseModel): ...@@ -10,7 +10,7 @@ class WeComDebugCustomerGroupItem(BaseModel):
id: int = Field(..., description="一客一群记录 ID。", examples=[1]) id: int = Field(..., description="一客一群记录 ID。", examples=[1])
customer_contact_id: str = Field(..., description="客户 contact_id。", examples=["cust_001"]) customer_contact_id: str = Field(..., description="客户 contact_id。", examples=["cust_001"])
customer_name: Optional[str] = Field(default=None, description="客户名称。", examples=["张三"]) customer_name: Optional[str] = Field(default=None, description="客户名称。", examples=["张三"])
bot_id: str = Field(..., description="承接该客户的企业微信机器人 bot_id。", examples=["2beaf9540180418a81788313e7f3caf0"]) bot_id: str = Field(..., description="承接该客户的企微机器人 bot_id。", examples=["2beaf9540180418a81788313e7f3caf0"])
bot_code: str = Field(..., description="机器人渠道编码。", examples=["wt_ww:2beaf9540180418a81788313e7f3caf0"]) bot_code: str = Field(..., description="机器人渠道编码。", examples=["wt_ww:2beaf9540180418a81788313e7f3caf0"])
group_id: Optional[str] = Field(default=None, description="已创建群的群 contact_id。", examples=["group_001"]) group_id: Optional[str] = Field(default=None, description="已创建群的群 contact_id。", examples=["group_001"])
group_name: Optional[str] = Field(default=None, description="群名称。", examples=["张三专属服务群"]) group_name: Optional[str] = Field(default=None, description="群名称。", examples=["张三专属服务群"])
...@@ -44,17 +44,17 @@ class WeComDebugMessageItem(BaseModel): ...@@ -44,17 +44,17 @@ class WeComDebugMessageItem(BaseModel):
class WeComDebugGroupCreateRequestItem(BaseModel): class WeComDebugGroupCreateRequestItem(BaseModel):
id: int = Field(..., description="建群请求记录 ID。", examples=[12]) id: int = Field(..., description="建群请求记录 ID。", examples=[12])
biz_rela_no: str = Field(..., description="企业微信侧或业务侧的关联流水号。", examples=["biz_202605250001"]) biz_rela_no: str = Field(..., description="业务侧关联流水号。", examples=["biz_202605250001"])
bot_id: str = Field(..., description="发起建群的承接机器人 bot_id。", examples=["2beaf9540180418a81788313e7f3caf0"]) bot_id: str = Field(..., description="发起建群的承接机器人 bot_id。", examples=["2beaf9540180418a81788313e7f3caf0"])
bot_code: str = Field(..., description="发起建群的机器人渠道编码。", examples=["wt_ww:2beaf9540180418a81788313e7f3caf0"]) bot_code: str = Field(..., description="发起建群的机器人渠道编码。", examples=["wt_ww:2beaf9540180418a81788313e7f3caf0"])
customer_contact_id: str = Field(..., description="客户 contact_id。", examples=["cust_001"]) customer_contact_id: str = Field(..., description="客户 contact_id。", examples=["cust_001"])
customer_name: Optional[str] = Field(default=None, description="客户名称。", examples=["张三"]) customer_name: Optional[str] = Field(default=None, description="客户名称。", examples=["张三"])
qrcode_id: int = Field(..., description="关联的渠道活码 ID。", examples=[8]) qrcode_id: int = Field(..., description="关联的渠道活码 ID。", examples=[8])
qrcode_name: Optional[str] = Field(default=None, description="渠道活码名称。", examples=["驻店销售岗渠道活码"]) qrcode_name: Optional[str] = Field(default=None, description="渠道活码名称。", examples=["门店销售岗渠道活码"])
channel_code: str = Field(..., description="渠道编码。当前由岗位编码决定。", examples=["store_sales"]) channel_code: str = Field(..., description="渠道编码。当前由岗位编码决定。", examples=["store_sales"])
position_id: int = Field(..., description="关联岗位 ID。", examples=[4]) position_id: int = Field(..., description="关联岗位 ID。", examples=[4])
position_code: str = Field(..., description="岗位编码。", examples=["store_sales"]) position_code: str = Field(..., description="岗位编码。", examples=["store_sales"])
position_name: str = Field(..., description="岗位名称。", examples=["驻店销售岗"]) position_name: str = Field(..., description="岗位名称。", examples=["门店销售岗"])
group_name: str = Field(..., description="计划创建的群名称。", examples=["张三专属服务群"]) group_name: str = Field(..., description="计划创建的群名称。", examples=["张三专属服务群"])
member_bot_ids: list[str] = Field(default_factory=list, description="计划拉入群的成员机器人 bot_id 列表。") member_bot_ids: list[str] = Field(default_factory=list, description="计划拉入群的成员机器人 bot_id 列表。")
task_id: Optional[str] = Field(default=None, description="调用外部接口后返回的任务 ID。", examples=["task_001"]) task_id: Optional[str] = Field(default=None, description="调用外部接口后返回的任务 ID。", examples=["task_001"])
...@@ -74,12 +74,12 @@ class WeComDebugOverviewResponse(BaseModel): ...@@ -74,12 +74,12 @@ class WeComDebugOverviewResponse(BaseModel):
class WeComDebugResetCustomerGroupRequest(BaseModel): class WeComDebugResetCustomerGroupRequest(BaseModel):
bot_id: str = Field(..., description="要禁用群关系的企微机器人 bot_id。", examples=["bot_001"])
customer_contact_id: str = Field( customer_contact_id: str = Field(
..., ...,
description=( description=(
"要重置的一客一群客户 contact_id。" "按 bot_id + customer_contact_id 精准禁用一条本地群关系。"
"当前实现会删除该客户在本地库中的一客一群记录(wecom_customer_groups)以及建群请求记录(wecom_group_create_requests)," " 当前实现会将匹配的群记录标记为 invalid,并将该 bot 下此客户仍处于 pending 的建群请求标记为 failed。"
"用于调试/回放链路,便于后续重新发起建群。"
), ),
examples=["cust_001"], examples=["cust_001"],
) )
...@@ -87,6 +87,7 @@ class WeComDebugResetCustomerGroupRequest(BaseModel): ...@@ -87,6 +87,7 @@ class WeComDebugResetCustomerGroupRequest(BaseModel):
model_config = { model_config = {
"json_schema_extra": { "json_schema_extra": {
"example": { "example": {
"bot_id": "bot_001",
"customer_contact_id": "cust_001", "customer_contact_id": "cust_001",
} }
} }
...@@ -94,11 +95,12 @@ class WeComDebugResetCustomerGroupRequest(BaseModel): ...@@ -94,11 +95,12 @@ class WeComDebugResetCustomerGroupRequest(BaseModel):
class WeComDebugResetCustomerGroupResponse(BaseModel): class WeComDebugResetCustomerGroupResponse(BaseModel):
success: bool = Field(..., description="是否重置成功。", examples=[True]) success: bool = Field(..., description="是否禁用成功。", examples=[True])
deleted_customer_groups_count: int = Field(..., description="本次删除的一客一群记录数。", examples=[1]) invalidated_customer_groups_count: int = Field(..., description="本次标记为 invalid 的群关系记录数。", examples=[1])
deleted_group_create_requests_count: int = Field(..., description="本次删除的建群请求记录数。", examples=[1]) failed_group_create_requests_count: int = Field(..., description="本次标记为 failed 的待处理建群请求数。", examples=[1])
customer_contact_id: str = Field(..., description="本次重置的客户 contact_id。", examples=["cust_001"]) bot_id: str = Field(..., description="本次禁用的 bot_id。", examples=["bot_001"])
updated_at: datetime = Field(..., description="重置完成时间。", examples=["2026-05-25T10:20:00Z"]) customer_contact_id: str = Field(..., description="本次禁用的客户 contact_id。", examples=["cust_001"])
updated_at: datetime = Field(..., description="禁用完成时间。", examples=["2026-05-25T10:20:00Z"])
class WeComDebugUpdateGroupCreateRequestStatusRequest(BaseModel): class WeComDebugUpdateGroupCreateRequestStatusRequest(BaseModel):
...@@ -117,8 +119,8 @@ class WeComDebugUpdateGroupCreateRequestStatusRequest(BaseModel): ...@@ -117,8 +119,8 @@ class WeComDebugUpdateGroupCreateRequestStatusRequest(BaseModel):
"fail_reason": "manual_reset", "fail_reason": "manual_reset",
"external_result": { "external_result": {
"raw_status": "failed", "raw_status": "failed",
"reason": "人工回填失败结果" "reason": "人工回填失败结果",
} },
}, },
{ {
"status": "success", "status": "success",
...@@ -127,9 +129,9 @@ class WeComDebugUpdateGroupCreateRequestStatusRequest(BaseModel): ...@@ -127,9 +129,9 @@ class WeComDebugUpdateGroupCreateRequestStatusRequest(BaseModel):
"resolved_contact_type": "group", "resolved_contact_type": "group",
"external_result": { "external_result": {
"task_id": "task_001", "task_id": "task_001",
"source": "manual_fix" "source": "manual_fix",
} },
} },
] ]
} }
} }
......
...@@ -80,6 +80,7 @@ class AgentService: ...@@ -80,6 +80,7 @@ class AgentService:
self._sync_display_snapshots(agent) self._sync_display_snapshots(agent)
self.db.commit() self.db.commit()
self.db.refresh(agent) self.db.refresh(agent)
shared_h5_cache.invalidate_home_page()
return agent return agent
def delete(self, agent_id: int) -> Agent: def delete(self, agent_id: int) -> Agent:
...@@ -148,6 +149,7 @@ class AgentService: ...@@ -148,6 +149,7 @@ class AgentService:
self._sync_display_snapshots(agent) self._sync_display_snapshots(agent)
self.db.commit() self.db.commit()
self.db.refresh(agent) self.db.refresh(agent)
shared_h5_cache.invalidate_home_page()
return agent return agent
def _sync_display_snapshots(self, agent: Agent) -> None: def _sync_display_snapshots(self, agent: Agent) -> None:
......
...@@ -79,8 +79,6 @@ class H5HomeService: ...@@ -79,8 +79,6 @@ class H5HomeService:
agent_items = [] agent_items = []
for dc in display_configs: for dc in display_configs:
if dc.status != "enable":
continue
agent = ( agent = (
self.db.query(Agent) self.db.query(Agent)
.filter(Agent.id == dc.agent_id, Agent.is_deleted == False) .filter(Agent.id == dc.agent_id, Agent.is_deleted == False)
...@@ -88,16 +86,19 @@ class H5HomeService: ...@@ -88,16 +86,19 @@ class H5HomeService:
) )
if agent is None: if agent is None:
continue continue
agent_status = agent.status.value if hasattr(agent.status, "value") else agent.status
if agent_status != "enable":
continue
agent_items.append(H5HomeAgentItem( agent_items.append(H5HomeAgentItem(
agent_id=dc.agent_id, agent_id=dc.agent_id,
agent_name=dc.agent_name, agent_name=agent.name,
icon_url=dc.icon_url, icon_url=dc.icon_url,
summary=dc.summary, summary=dc.summary,
media_url=dc.media_url, media_url=dc.media_url,
media_type=dc.media_type, media_type=dc.media_type,
speech_title=dc.speech_title, speech_title=dc.speech_title,
speech_content=dc.speech_content, speech_content=dc.speech_content,
status=dc.status, status=agent_status,
)) ))
result.append(H5HomeTabItem( result.append(H5HomeTabItem(
......
...@@ -315,7 +315,7 @@ class OfficialSiteTabService: ...@@ -315,7 +315,7 @@ class OfficialSiteTabService:
agent_id=agent.id, agent_id=agent.id,
agent_name=agent.name, agent_name=agent.name,
status=agent.status.value, status=agent.status.value,
display_status="enable", display_status="disable",
) )
) )
...@@ -349,7 +349,7 @@ class OfficialSiteTabService: ...@@ -349,7 +349,7 @@ class OfficialSiteTabService:
agent_id=agent.id, agent_id=agent.id,
agent_name=agent.name, agent_name=agent.name,
status=agent.status.value, status=agent.status.value,
display_status="enable", display_status="disable",
) )
) )
......
...@@ -151,7 +151,7 @@ class WeComSyncService: ...@@ -151,7 +151,7 @@ class WeComSyncService:
start_time: datetime | None, start_time: datetime | None,
end_time: datetime | None, end_time: datetime | None,
) -> dict[str, int]: ) -> dict[str, int]:
bots = self.sync_bots_full() bots = self.sync_bots_incremental()
resolved_bot_ids = [ resolved_bot_ids = [
bot.bot_id bot.bot_id
for bot in self.db.query(WeComBot).filter(WeComBot.online == True).all() for bot in self.db.query(WeComBot).filter(WeComBot.online == True).all()
...@@ -170,20 +170,27 @@ class WeComSyncService: ...@@ -170,20 +170,27 @@ class WeComSyncService:
"messages": messages, "messages": messages,
} }
def sync_bots_full(self) -> int: def sync_bots_incremental(self) -> int:
count = 0 count = 0
latest_time: datetime | None = None checkpoint = self._get_effective_checkpoint("bots", "global")
latest_id: str | None = None latest_time: datetime | None = checkpoint.last_sync_time if checkpoint else None
latest_id: str | None = checkpoint.last_external_id if checkpoint else None
for item in self._paginate(lambda page: self.client.list_bots(page=page, page_size=self.page_size)): for item in self._paginate(lambda page: self.client.list_bots(page=page, page_size=self.page_size)):
if not self._is_online_bot(item): if not self._is_online_bot(item):
continue continue
candidate_time = _parse_dt(item.get("updated_at")) or _parse_dt(item.get("created_at"))
candidate_id = self._resolve_bot_code(item.get("bot_code"), item.get("bot_id"), item.get("channel"))
if self._is_checkpoint_item_already_consumed(checkpoint, candidate_time, candidate_id):
continue
bot = self._upsert_bot(item) bot = self._upsert_bot(item)
count += 1 count += 1
candidate_time = _parse_dt(item.get("updated_at")) or _parse_dt(item.get("created_at"))
latest_time, latest_id = self._max_key(latest_time, latest_id, candidate_time, bot.bot_code) latest_time, latest_id = self._max_key(latest_time, latest_id, candidate_time, bot.bot_code)
self._complete_checkpoint("bots", "global", latest_time, latest_id) self._complete_checkpoint("bots", "global", latest_time, latest_id)
return count return count
def sync_bots_full(self) -> int:
return self.sync_bots_incremental()
def sync_messages_incremental( def sync_messages_incremental(
self, self,
*, *,
...@@ -245,7 +252,7 @@ class WeComSyncService: ...@@ -245,7 +252,7 @@ class WeComSyncService:
group_id = str(group.group_id or "").strip() group_id = str(group.group_id or "").strip()
if not group_id: if not group_id:
continue continue
checkpoint = self._get_checkpoint("messages", f"group:{group_id}") checkpoint = self._get_effective_checkpoint("messages", f"group:{group_id}")
window = self._resolve_message_window(checkpoint, start_time, end_time) window = self._resolve_message_window(checkpoint, start_time, end_time)
latest_time = checkpoint.last_sync_time if checkpoint else None latest_time = checkpoint.last_sync_time if checkpoint else None
latest_id = checkpoint.last_external_id if checkpoint else None latest_id = checkpoint.last_external_id if checkpoint else None
...@@ -500,14 +507,23 @@ class WeComSyncService: ...@@ -500,14 +507,23 @@ class WeComSyncService:
msg_time: datetime | None, msg_time: datetime | None,
msg_id: str, msg_id: str,
) -> bool: ) -> bool:
if checkpoint is None or checkpoint.last_sync_time is None or msg_time is None: return self._is_checkpoint_item_already_consumed(checkpoint, msg_time, msg_id)
def _is_checkpoint_item_already_consumed(
self,
checkpoint: WeComSyncCheckpoint | None,
item_time: datetime | None,
item_id: str | None,
) -> bool:
if checkpoint is None or checkpoint.last_sync_time is None or item_time is None:
return False return False
last_time = checkpoint.last_sync_time last_time = checkpoint.last_sync_time
if last_time.tzinfo is None: if last_time.tzinfo is None:
last_time = last_time.replace(tzinfo=timezone.utc) last_time = last_time.replace(tzinfo=timezone.utc)
if msg_time < last_time: if item_time < last_time:
return True return True
if msg_time == last_time and checkpoint.last_external_id and msg_id <= checkpoint.last_external_id: normalized_item_id = str(item_id or "")
if item_time == last_time and checkpoint.last_external_id and normalized_item_id <= checkpoint.last_external_id:
return True return True
return False return False
...@@ -521,6 +537,14 @@ class WeComSyncService: ...@@ -521,6 +537,14 @@ class WeComSyncService:
.first() .first()
) )
def _get_effective_checkpoint(self, resource_type: str, scope_key: str) -> WeComSyncCheckpoint | None:
checkpoint = self._get_checkpoint(resource_type, scope_key)
if checkpoint is not None:
return checkpoint
if scope_key != "global":
return self._get_checkpoint(resource_type, "global")
return None
def _complete_checkpoint( def _complete_checkpoint(
self, self,
resource_type: str, resource_type: str,
...@@ -542,6 +566,31 @@ class WeComSyncService: ...@@ -542,6 +566,31 @@ class WeComSyncService:
checkpoint.last_started_at = now checkpoint.last_started_at = now
self.db.commit() self.db.commit()
def upsert_checkpoint(
self,
*,
resource_type: str,
scope_key: str,
last_sync_time: datetime,
last_external_id: str | None = None,
last_sync_cursor: str | None = None,
) -> WeComSyncCheckpoint:
checkpoint = self._get_checkpoint(resource_type, scope_key)
if checkpoint is None:
checkpoint = WeComSyncCheckpoint(resource_type=resource_type, scope_key=scope_key)
self.db.add(checkpoint)
now = _utcnow()
checkpoint.last_sync_time = _ensure_utc(last_sync_time)
checkpoint.last_external_id = last_external_id
checkpoint.last_sync_cursor = last_sync_cursor
checkpoint.last_status = "manual"
checkpoint.last_error = None
checkpoint.last_started_at = now
checkpoint.last_finished_at = now
self.db.commit()
self.db.refresh(checkpoint)
return checkpoint
def _resolve_bot_code(self, bot_code: str | None, bot_id: str | None, channel: str | None = None) -> str: def _resolve_bot_code(self, bot_code: str | None, bot_id: str | None, channel: str | None = None) -> str:
if bot_code: if bot_code:
return str(bot_code) return str(bot_code)
......
No preview for this file type
...@@ -5,13 +5,11 @@ services: ...@@ -5,13 +5,11 @@ services:
dockerfile: Dockerfile.prod dockerfile: Dockerfile.prod
ports: ports:
- "8082:8082" - "8082:8082"
volumes:
- ./dev.db:/app/dev.db
env_file: env_file:
- path: .env - path: .env
required: false required: false
environment: environment:
- DATABASE_URL=${DATABASE_URL:-sqlite:////app/dev.db} - DATABASE_URL=${DATABASE_URL}
- IM_BASE_URL=${IM_BASE_URL:-http://192.168.3.84:8600/webim} - IM_BASE_URL=${IM_BASE_URL:-http://192.168.3.84:8600/webim}
- WECOM_SYNC_BASE_URL=${WECOM_SYNC_BASE_URL:-http://192.168.3.84:8600/webim} - WECOM_SYNC_BASE_URL=${WECOM_SYNC_BASE_URL:-http://192.168.3.84:8600/webim}
- USE_CONSOLE_IM=${USE_CONSOLE_IM:-false} - USE_CONSOLE_IM=${USE_CONSOLE_IM:-false}
...@@ -29,13 +27,11 @@ services: ...@@ -29,13 +27,11 @@ services:
build: build:
context: . context: .
dockerfile: Dockerfile.prod dockerfile: Dockerfile.prod
volumes:
- ./dev.db:/app/dev.db
env_file: env_file:
- path: .env - path: .env
required: false required: false
environment: environment:
- DATABASE_URL=${DATABASE_URL:-sqlite:////app/dev.db} - DATABASE_URL=${DATABASE_URL}
- IM_BASE_URL=${IM_BASE_URL:-http://192.168.3.84:8600/webim} - IM_BASE_URL=${IM_BASE_URL:-http://192.168.3.84:8600/webim}
- WECOM_SYNC_BASE_URL=${WECOM_SYNC_BASE_URL:-http://192.168.3.84:8600/webim} - WECOM_SYNC_BASE_URL=${WECOM_SYNC_BASE_URL:-http://192.168.3.84:8600/webim}
- USE_CONSOLE_IM=${USE_CONSOLE_IM:-false} - USE_CONSOLE_IM=${USE_CONSOLE_IM:-false}
......
...@@ -11,12 +11,11 @@ services: ...@@ -11,12 +11,11 @@ services:
- ./skills:/app/skills - ./skills:/app/skills
- ./scripts:/app/scripts - ./scripts:/app/scripts
- ./tests:/app/tests - ./tests:/app/tests
- ./dev.db:/app/dev.db
env_file: env_file:
- path: .env - path: .env
required: false required: false
environment: environment:
- DATABASE_URL=${DATABASE_URL:-sqlite:////app/dev.db} - DATABASE_URL=${DATABASE_URL}
- IM_BASE_URL=${IM_BASE_URL:-http://192.168.3.84:8600/webim} - IM_BASE_URL=${IM_BASE_URL:-http://192.168.3.84:8600/webim}
- WECOM_SYNC_BASE_URL=${WECOM_SYNC_BASE_URL:-http://192.168.3.84:8600/webim} - WECOM_SYNC_BASE_URL=${WECOM_SYNC_BASE_URL:-http://192.168.3.84:8600/webim}
- USE_CONSOLE_IM=${USE_CONSOLE_IM:-false} - USE_CONSOLE_IM=${USE_CONSOLE_IM:-false}
...@@ -37,12 +36,11 @@ services: ...@@ -37,12 +36,11 @@ services:
- ./skills:/app/skills - ./skills:/app/skills
- ./scripts:/app/scripts - ./scripts:/app/scripts
- ./tests:/app/tests - ./tests:/app/tests
- ./dev.db:/app/dev.db
env_file: env_file:
- path: .env - path: .env
required: false required: false
environment: environment:
- DATABASE_URL=${DATABASE_URL:-sqlite:////app/dev.db} - DATABASE_URL=${DATABASE_URL}
- IM_BASE_URL=${IM_BASE_URL:-http://192.168.3.84:8600/webim} - IM_BASE_URL=${IM_BASE_URL:-http://192.168.3.84:8600/webim}
- WECOM_SYNC_BASE_URL=${WECOM_SYNC_BASE_URL:-http://192.168.3.84:8600/webim} - WECOM_SYNC_BASE_URL=${WECOM_SYNC_BASE_URL:-http://192.168.3.84:8600/webim}
- USE_CONSOLE_IM=${USE_CONSOLE_IM:-false} - USE_CONSOLE_IM=${USE_CONSOLE_IM:-false}
......
def repair_json(value):
return value
from __future__ import annotations
import json
import sqlite3
from pathlib import Path
from typing import Any
from urllib.parse import parse_qsl, unquote, urlparse
import pymysql
BASE_DIR = Path(__file__).resolve().parents[1]
DEFAULT_SQLITE_PATH = BASE_DIR / "dev.db"
DEFAULT_ENV_PATH = BASE_DIR / ".env"
IMPORT_ORDER = [
"ai_agents",
"skills",
"position_tags",
"ai_agent_positions",
"ai_agent_skills",
"position_tag_users",
"qrcode_channels",
"wecom_employee_qrcodes",
"official_tabs",
"official_site_agent_display",
"official_site_methodology",
"official_site_methodology_steps",
"wecom_bots",
"wecom_sync_checkpoints",
"wecom_customer_groups",
"wecom_group_create_requests",
"wecom_job_configs",
"wecom_messages",
"conversation_logs",
"analytics_events",
"analytics_statistics",
"page_views",
"scan_events",
"group_join_events",
]
def load_env_file(env_path: Path) -> dict[str, str]:
values: dict[str, str] = {}
if not env_path.exists():
return values
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
values[key.strip()] = value.strip()
return values
def load_database_url() -> str:
env_values = load_env_file(DEFAULT_ENV_PATH)
database_url = env_values.get("DATABASE_URL", "").strip()
if not database_url:
raise RuntimeError(f"DATABASE_URL not found in {DEFAULT_ENV_PATH}")
if not database_url.startswith("mysql+pymysql://"):
raise RuntimeError("DATABASE_URL must start with mysql+pymysql://")
return database_url
def mysql_connect_from_url(database_url: str):
parsed = urlparse(database_url)
query = dict(parse_qsl(parsed.query))
charset = query.get("charset", "utf8mb4")
return pymysql.connect(
host=parsed.hostname,
port=parsed.port or 3306,
user=unquote(parsed.username or ""),
password=unquote(parsed.password or ""),
database=(parsed.path or "").lstrip("/"),
charset=charset,
autocommit=False,
cursorclass=pymysql.cursors.DictCursor,
)
def sqlite_connect(sqlite_path: Path) -> sqlite3.Connection:
if not sqlite_path.exists():
raise FileNotFoundError(f"SQLite database not found: {sqlite_path}")
conn = sqlite3.connect(str(sqlite_path))
conn.row_factory = sqlite3.Row
return conn
def fetch_sqlite_tables(conn: sqlite3.Connection) -> list[str]:
rows = conn.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
).fetchall()
return [row[0] for row in rows]
def fetch_mysql_tables(conn) -> set[str]:
with conn.cursor() as cursor:
cursor.execute("SHOW TABLES")
return {next(iter(row.values())) for row in cursor.fetchall()}
def fetch_mysql_columns(conn, table_name: str) -> list[str]:
with conn.cursor() as cursor:
cursor.execute(f"SHOW COLUMNS FROM `{table_name}`")
return [row["Field"] for row in cursor.fetchall()]
def normalize_value(value: Any) -> Any:
if isinstance(value, bytes):
return value.decode("utf-8")
if isinstance(value, bool):
return int(value)
if isinstance(value, (dict, list)):
return json.dumps(value, ensure_ascii=False)
return value
def fetch_rows(conn: sqlite3.Connection, table_name: str) -> list[dict[str, Any]]:
rows = conn.execute(f"SELECT * FROM `{table_name}`").fetchall()
return [{key: normalize_value(row[key]) for key in row.keys()} for row in rows]
def truncate_tables(conn, table_names: list[str]) -> None:
with conn.cursor() as cursor:
cursor.execute("SET FOREIGN_KEY_CHECKS = 0")
for table_name in reversed(table_names):
cursor.execute(f"TRUNCATE TABLE `{table_name}`")
cursor.execute("SET FOREIGN_KEY_CHECKS = 1")
def import_table(sqlite_conn: sqlite3.Connection, mysql_conn, table_name: str) -> int:
rows = fetch_rows(sqlite_conn, table_name)
if not rows:
return 0
target_columns = fetch_mysql_columns(mysql_conn, table_name)
source_columns = [column for column in rows[0].keys() if column in target_columns]
if not source_columns:
return 0
placeholders = ", ".join(["%s"] * len(source_columns))
columns_sql = ", ".join(f"`{column}`" for column in source_columns)
sql = f"INSERT INTO `{table_name}` ({columns_sql}) VALUES ({placeholders})"
payload = [tuple(row.get(column) for column in source_columns) for row in rows]
with mysql_conn.cursor() as cursor:
cursor.executemany(sql, payload)
return len(rows)
def main() -> None:
database_url = load_database_url()
sqlite_path = DEFAULT_SQLITE_PATH
sqlite_conn = sqlite_connect(sqlite_path)
mysql_conn = mysql_connect_from_url(database_url)
try:
source_tables = fetch_sqlite_tables(sqlite_conn)
target_tables = fetch_mysql_tables(mysql_conn)
import_tables = [name for name in IMPORT_ORDER if name in source_tables and name in target_tables]
skipped_tables = [name for name in source_tables if name not in target_tables]
print(f"SQLite source: {sqlite_path}")
print(f"MySQL target tables to import: {len(import_tables)}")
if skipped_tables:
print("Skipped legacy/non-target tables:")
for name in skipped_tables:
print(f" - {name}")
truncate_tables(mysql_conn, import_tables)
imported_counts: list[tuple[str, int]] = []
for table_name in import_tables:
count = import_table(sqlite_conn, mysql_conn, table_name)
imported_counts.append((table_name, count))
print(f"Imported {table_name}: {count}")
mysql_conn.commit()
print("Import complete.")
total_rows = sum(count for _, count in imported_counts)
print(f"Total imported rows: {total_rows}")
except Exception:
mysql_conn.rollback()
raise
finally:
sqlite_conn.close()
mysql_conn.close()
if __name__ == "__main__":
main()
import sys import sys
import os
from pathlib import Path from pathlib import Path
def _ensure_local_deps_on_path() -> None: def _ensure_local_deps_on_path() -> None:
...@@ -14,21 +15,34 @@ _ensure_local_deps_on_path() ...@@ -14,21 +15,34 @@ _ensure_local_deps_on_path()
import pytest import pytest
from sqlalchemy import create_engine from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.infrastructure.database import Base, get_db from app.infrastructure.database import Base, get_db
import app.model # noqa: F401 import app.model # noqa: F401
from app.main import app
from app.infrastructure.session_store import clear_default_store_for_tests from app.infrastructure.session_store import clear_default_store_for_tests
from app.infrastructure.schema_patch import ensure_runtime_schema
SQLALCHEMY_DATABASE_URL = "sqlite://" SQLALCHEMY_DATABASE_URL = os.getenv("TEST_DATABASE_URL", "")
engine = create_engine( engine = None
SQLALCHEMY_DATABASE_URL, TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False)
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base.metadata.create_all(bind=engine)
def get_test_database_url() -> str:
if not SQLALCHEMY_DATABASE_URL:
raise RuntimeError("TEST_DATABASE_URL is required for backend tests")
return SQLALCHEMY_DATABASE_URL
def init_testing_database():
global engine
if engine is None:
engine = create_engine(get_test_database_url(), pool_pre_ping=True)
TestingSessionLocal.configure(bind=engine)
Base.metadata.create_all(bind=engine)
ensure_runtime_schema(engine)
return engine
def get_testing_engine():
return init_testing_database()
def override_get_db(): def override_get_db():
...@@ -38,17 +52,26 @@ def override_get_db(): ...@@ -38,17 +52,26 @@ def override_get_db():
finally: finally:
db.close() db.close()
app.dependency_overrides[get_db] = override_get_db
@pytest.fixture @pytest.fixture
def db_session(): def db_session():
init_testing_database()
db = TestingSessionLocal() db = TestingSessionLocal()
yield db yield db
db.close() db.close()
@pytest.fixture
def test_app():
from app.main import app
init_testing_database()
app.dependency_overrides[get_db] = override_get_db
try:
yield app
finally:
app.dependency_overrides.pop(get_db, None)
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def clear_session_kv_store(): def clear_session_kv_store():
clear_default_store_for_tests() clear_default_store_for_tests()
......
from types import SimpleNamespace
from app.model.agent import AgentStatus
from app.service.agent_service import AgentService
class _FakeCache:
def __init__(self):
self.invalidated = False
def invalidate_home_page(self):
self.invalidated = True
class _FakeQuery:
def __init__(self, agent):
self.agent = agent
def filter(self, *args, **kwargs):
return self
def first(self):
return self.agent
def update(self, values, synchronize_session=False):
return 1
def delete(self):
return 0
class _FakeDb:
def __init__(self, agent):
self.agent = agent
def query(self, model):
return _FakeQuery(self.agent)
def commit(self):
pass
def refresh(self, obj):
pass
def test_agent_update_invalidates_home_cache(monkeypatch):
import app.service.agent_service as agent_service_module
fake_cache = _FakeCache()
monkeypatch.setattr(agent_service_module, "shared_h5_cache", fake_cache)
agent = SimpleNamespace(
id=1,
name="old",
description="old desc",
status=AgentStatus.enable,
managed_user_id=None,
positions=[],
skills=[],
)
service = AgentService(_FakeDb(agent))
monkeypatch.setattr(service, "_ensure_name_unique", lambda *args, **kwargs: None)
monkeypatch.setattr(service, "_validate_references", lambda *args, **kwargs: None)
service.update(
1,
SimpleNamespace(
name="new",
description="new desc",
status=AgentStatus.enable,
position_ids=None,
skill_codes=None,
managed_user_id=None,
),
)
assert fake_cache.invalidated is True
def test_agent_status_update_invalidates_home_cache(monkeypatch):
import app.service.agent_service as agent_service_module
fake_cache = _FakeCache()
monkeypatch.setattr(agent_service_module, "shared_h5_cache", fake_cache)
agent = SimpleNamespace(id=1, name="agent", status=AgentStatus.enable)
service = AgentService(_FakeDb(agent))
service.update_status(1, SimpleNamespace(status=AgentStatus.disable))
assert fake_cache.invalidated is True
...@@ -223,6 +223,7 @@ class TestH5Home: ...@@ -223,6 +223,7 @@ class TestH5Home:
tab = _insert_tab(db, qrcode_id=qr.id, position_id=pos.id) tab = _insert_tab(db, qrcode_id=qr.id, position_id=pos.id)
db.add(OfficialSiteAgentDisplay( db.add(OfficialSiteAgentDisplay(
tab_id=tab.id, agent_id=agent.id, tab_id=tab.id, agent_id=agent.id,
agent_name="官网展示旧名",
media_type="gif", media_type="gif",
speech_title="标题", speech_content="内容", speech_title="标题", speech_content="内容",
display_status="enable", sort_order=1, display_status="enable", sort_order=1,
......
from types import SimpleNamespace
from app.model.agent import Agent, AgentStatus
from app.model.agent_group import QrcodeChannel
from app.model.methodology import OfficialSiteMethodology
from app.model.official_site_agent_display import OfficialSiteAgentDisplay
from app.model.position_tag import OfficialTab, PositionTag
from app.service.official_site_home_service import H5HomeService
class _FakeQuery:
def __init__(self, rows):
self._rows = rows
def filter(self, *args, **kwargs):
return self
def order_by(self, *args, **kwargs):
return self
def all(self):
return list(self._rows)
def first(self):
return self._rows[0] if self._rows else None
class _FakeDb:
def __init__(self, rows_by_model):
self._rows_by_model = rows_by_model
def query(self, model):
return _FakeQuery(self._rows_by_model.get(model, []))
class _NoopCache:
def get_home_page(self):
return None
def set_home_page(self, value, ttl):
pass
def test_home_agent_name_comes_from_agent_table_not_display_snapshot():
tab = SimpleNamespace(
id=1,
position_id=10,
qrcode_id=None,
main_title="main",
sub_title="sub",
)
position = SimpleNamespace(id=10, code="sales", name="销售")
display = SimpleNamespace(
tab_id=1,
agent_id=100,
agent_name="展示配置旧名",
status="enable",
icon_url="https://example.com/icon.png",
summary="summary",
media_url=None,
media_type=None,
speech_title=None,
speech_content=None,
)
agent = SimpleNamespace(id=100, name="Agent表新名", status=AgentStatus.enable, is_deleted=False)
db = _FakeDb(
{
OfficialTab: [tab],
PositionTag: [position],
QrcodeChannel: [],
OfficialSiteAgentDisplay: [display],
Agent: [agent],
OfficialSiteMethodology: [],
}
)
result = H5HomeService(db, _NoopCache()).get_home_data()
assert result.tabs[0].agents[0].agent_name == "Agent表新名"
def test_home_agent_status_comes_from_agent_table_not_display_snapshot():
tab = SimpleNamespace(
id=1,
position_id=10,
qrcode_id=None,
main_title="main",
sub_title="sub",
)
position = SimpleNamespace(id=10, code="sales", name="销售")
display = SimpleNamespace(
tab_id=1,
agent_id=100,
agent_name="name",
status="enable",
icon_url=None,
summary=None,
media_url=None,
media_type=None,
speech_title=None,
speech_content=None,
)
agent = SimpleNamespace(id=100, name="Agent", status=AgentStatus.disable, is_deleted=False)
db = _FakeDb(
{
OfficialTab: [tab],
PositionTag: [position],
QrcodeChannel: [],
OfficialSiteAgentDisplay: [display],
Agent: [agent],
OfficialSiteMethodology: [],
}
)
result = H5HomeService(db, _NoopCache()).get_home_data()
assert result.tabs[0].agents == []
import json import json
import os
from pathlib import Path from pathlib import Path
from app.config.loader import ConfigLoader from app.config.loader import ConfigLoader
...@@ -55,3 +56,30 @@ def test_wecom_sync_client_reads_default_base_url_from_config(tmp_path: Path, mo ...@@ -55,3 +56,30 @@ def test_wecom_sync_client_reads_default_base_url_from_config(tmp_path: Path, mo
assert client.base_url == "http://127.0.0.1:9090" assert client.base_url == "http://127.0.0.1:9090"
assert client.api_key == "sync-key" assert client.api_key == "sync-key"
def test_load_database_url_prefers_environment(monkeypatch, tmp_path: Path):
config_dir = tmp_path / "config"
config_dir.mkdir()
loader = ConfigLoader(str(config_dir))
monkeypatch.setenv(
"DATABASE_URL",
"mysql+pymysql://tester:secret@127.0.0.1:3306/agent_admin_test?charset=utf8mb4",
)
assert loader.load_database_url() == os.environ["DATABASE_URL"]
def test_load_database_url_reads_backend_env_file_when_environment_missing(monkeypatch, tmp_path: Path):
config_dir = tmp_path / "config"
config_dir.mkdir()
env_database_url = "mysql+pymysql://tester:secret@127.0.0.1:3306/from_env_file?charset=utf8mb4"
(tmp_path / ".env").write_text(
f"DATABASE_URL={env_database_url}\n",
encoding="utf-8",
)
loader = ConfigLoader(str(config_dir))
monkeypatch.delenv("DATABASE_URL", raising=False)
assert loader.load_database_url() == env_database_url
...@@ -2,10 +2,7 @@ from datetime import datetime, timedelta, timezone ...@@ -2,10 +2,7 @@ from datetime import datetime, timedelta, timezone
from fastapi import HTTPException from fastapi import HTTPException
from pydantic import ValidationError from pydantic import ValidationError
from sqlalchemy import create_engine
from sqlalchemy import text from sqlalchemy import text
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
import app.model # noqa: F401 import app.model # noqa: F401
from app.api.v1.endpoints.wecom_jobs import ( from app.api.v1.endpoints.wecom_jobs import (
...@@ -45,18 +42,11 @@ from app.schema.wecom_debug import ( ...@@ -45,18 +42,11 @@ from app.schema.wecom_debug import (
WeComDebugResetCustomerGroupRequest, WeComDebugResetCustomerGroupRequest,
WeComDebugUpdateGroupCreateRequestStatusRequest, WeComDebugUpdateGroupCreateRequestStatusRequest,
) )
from tests.conftest import TestingSessionLocal, get_testing_engine
from app.service.wecom_customer_group_orchestration_service import WeComCustomerGroupOrchestrationService from app.service.wecom_customer_group_orchestration_service import WeComCustomerGroupOrchestrationService
from app.service.wecom_sync_service import NoopWeComMessageDispatcher, WeComSyncService from app.service.wecom_sync_service import NoopWeComMessageDispatcher, WeComSyncService
engine = create_engine(
'sqlite://',
connect_args={'check_same_thread': False},
poolclass=StaticPool,
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
class FakeClient: class FakeClient:
def __init__(self): def __init__(self):
self.last_list_customers_kwargs = None self.last_list_customers_kwargs = None
...@@ -108,6 +98,7 @@ class FakeClient: ...@@ -108,6 +98,7 @@ class FakeClient:
def _setup_db(): def _setup_db():
engine = get_testing_engine()
Base.metadata.create_all(bind=engine) Base.metadata.create_all(bind=engine)
ensure_runtime_schema(engine) ensure_runtime_schema(engine)
db = TestingSessionLocal() db = TestingSessionLocal()
...@@ -129,9 +120,7 @@ def _seed_group_context(db): ...@@ -129,9 +120,7 @@ def _seed_group_context(db):
qrcode = QrcodeChannel( qrcode = QrcodeChannel(
id=1, id=1,
qrcode_name='qr-a', qrcode_name='qr-a',
channel_code='store_sales',
position_id=position.id, position_id=position.id,
position_name=position.name,
wecom_bot_id=bot.id, wecom_bot_id=bot.id,
employee_id='emp_1', employee_id='emp_1',
employee_name='emp-a', employee_name='emp-a',
...@@ -243,14 +232,20 @@ def test_dispatch_customer_group_messages_prefers_customer_group_id_and_marks_me ...@@ -243,14 +232,20 @@ def test_dispatch_customer_group_messages_prefers_customer_group_id_and_marks_me
'group': { 'group': {
'group_contact_id': 'grp_001', 'group_contact_id': 'grp_001',
'group_name': 'alice-service', 'group_name': 'alice-service',
'bot_code': 'wt_ww:bot_1',
},
'position': {
'position_id': 1,
'position_code': 'store_sales',
'position_name': 'store-sales',
}, },
'agents': [ 'agents': [
{'agent_id': 10, 'bot_id': 'managed_1', 'is_steward': False}, {'agent_id': 10, 'agent_name': 'review-agent', 'bot_id': 'managed_1', 'is_steward': False},
], ],
'messages': [ 'messages': [
{ {
'msg_id': 'msg_001', 'msg_id': 'msg_001',
'msg_time': datetime(2026, 5, 22, 10, 0, tzinfo=timezone.utc), 'msg_time': datetime(2026, 5, 22, 10, 0),
'sender_id': 'cust_1', 'sender_id': 'cust_1',
'sender_name': 'alice', 'sender_name': 'alice',
'msg_type': 'text', 'msg_type': 'text',
...@@ -325,6 +320,78 @@ def test_list_new_customers_skips_customer_when_group_already_exists(): ...@@ -325,6 +320,78 @@ def test_list_new_customers_skips_customer_when_group_already_exists():
db.close() db.close()
def test_list_new_customers_skips_customer_when_group_status_is_not_invalid():
db = _setup_db()
bot, managed, _, _ = _seed_group_context(db)
db.add(
WeComCustomerGroup(
customer_contact_id='cust_1',
customer_name='alice',
bot_code=bot.bot_code,
bot_id=bot.bot_id,
group_id='group_1',
group_name='group-a',
group_status='failed',
group_create_request_id=1,
member_bot_ids=[managed.bot_id],
is_deleted=False,
)
)
db.commit()
class CandidateClient(FakeClient):
def list_customers(self, *, bot_id: str, start_time, end_time, page: int, page_size: int, contact_type=None):
return {
'items': [{'contact_id': 'cust_1', 'contact_name': 'alice'}],
'meta': {'total': 1, 'page': 1, 'page_size': page_size},
}
client = CandidateClient()
sync_service = WeComSyncService(db, client, NoopWeComMessageDispatcher())
orchestration_service = WeComCustomerGroupOrchestrationService(db, client, sync_service)
result = list_new_customers(WeComNewCustomersRequest(bot_ids=['bot_1']), (sync_service, orchestration_service))
assert result['data']['total'] == 0
assert result['data']['list'] == []
db.close()
def test_list_new_customers_allows_customer_when_group_status_is_invalid():
db = _setup_db()
bot, managed, _, _ = _seed_group_context(db)
db.add(
WeComCustomerGroup(
customer_contact_id='cust_1',
customer_name='alice',
bot_code=bot.bot_code,
bot_id=bot.bot_id,
group_id='group_1',
group_name='group-a',
group_status='invalid',
group_create_request_id=1,
member_bot_ids=[managed.bot_id],
is_deleted=False,
)
)
db.commit()
class CandidateClient(FakeClient):
def list_customers(self, *, bot_id: str, start_time, end_time, page: int, page_size: int, contact_type=None):
return {
'items': [{'contact_id': 'cust_1', 'contact_name': 'alice'}],
'meta': {'total': 1, 'page': 1, 'page_size': page_size},
}
client = CandidateClient()
sync_service = WeComSyncService(db, client, NoopWeComMessageDispatcher())
orchestration_service = WeComCustomerGroupOrchestrationService(db, client, sync_service)
result = list_new_customers(WeComNewCustomersRequest(bot_ids=['bot_1']), (sync_service, orchestration_service))
assert result['data']['total'] == 1
assert result['data']['list'][0]['contact_id'] == 'cust_1'
db.close()
def test_create_groups_accepts_batch_requests_and_stores_pending_records(): def test_create_groups_accepts_batch_requests_and_stores_pending_records():
db = _setup_db() db = _setup_db()
_seed_group_context(db) _seed_group_context(db)
...@@ -637,10 +704,10 @@ def test_sync_customer_groups_skips_customer_when_pending_request_exists(): ...@@ -637,10 +704,10 @@ def test_sync_customer_groups_skips_customer_when_pending_request_exists():
result = orchestration_service.sync_customer_groups(bot_ids=['bot_1']) result = orchestration_service.sync_customer_groups(bot_ids=['bot_1'])
assert result == {'resolved': 0, 'created': 0} assert result == {'resolved': 1, 'created': 0}
assert db.query(WeComGroupCreateRequest).count() == 1 assert db.query(WeComGroupCreateRequest).count() == 1
request = db.query(WeComGroupCreateRequest).filter(WeComGroupCreateRequest.biz_rela_no == 'biz-group-001').first() request = db.query(WeComGroupCreateRequest).filter(WeComGroupCreateRequest.biz_rela_no == 'biz-group-001').first()
assert request.status == 'pending' assert request.status == 'success'
db.close() db.close()
...@@ -921,7 +988,7 @@ def test_pull_group_messages_dispatches_customer_group_payload(): ...@@ -921,7 +988,7 @@ def test_pull_group_messages_dispatches_customer_group_payload():
'group_name': '张三专属服务群', 'group_name': '张三专属服务群',
}, },
'agents': [ 'agents': [
{'agent_id': 10, 'bot_id': 'managed_1', 'is_steward': False}, {'agent_id': 10, 'agent_name': 'review-agent', 'bot_id': 'managed_1', 'is_steward': False},
], ],
'messages': [ 'messages': [
{ {
...@@ -960,7 +1027,6 @@ def test_pull_group_messages_dispatches_customer_group_payload(): ...@@ -960,7 +1027,6 @@ def test_pull_group_messages_dispatches_customer_group_payload():
}, },
], ],
} }
assert 'position' not in dispatcher.payload
db.close() db.close()
...@@ -1006,19 +1072,16 @@ def test_run_wecom_job_accepts_sync_wecom_bots_groups_messages(): ...@@ -1006,19 +1072,16 @@ def test_run_wecom_job_accepts_sync_wecom_bots_groups_messages():
db.close() db.close()
def test_list_new_customers_raises_clear_error_when_bot_missing(): def test_list_new_customers_returns_empty_list_when_bot_missing():
db = _setup_db() db = _setup_db()
sync_service = WeComSyncService(db, FakeClient(), NoopWeComMessageDispatcher()) sync_service = WeComSyncService(db, FakeClient(), NoopWeComMessageDispatcher())
orchestration_service = WeComCustomerGroupOrchestrationService(db, FakeClient(), sync_service) orchestration_service = WeComCustomerGroupOrchestrationService(db, FakeClient(), sync_service)
try: result = list_new_customers(WeComNewCustomersRequest(bot_ids=['missing_bot']), (sync_service, orchestration_service))
list_new_customers(WeComNewCustomersRequest(bot_ids=['missing_bot']), (sync_service, orchestration_service))
assert False, 'expected HTTPException' assert result['data']['total'] == 0
except HTTPException as exc: assert result['data']['list'] == []
assert exc.status_code == 400 db.close()
assert 'missing_bot' in str(exc.detail)
finally:
db.close()
def test_create_groups_raises_clear_error_when_qrcode_missing(): def test_create_groups_raises_clear_error_when_qrcode_missing():
...@@ -1181,7 +1244,7 @@ def test_wecom_debug_overview_skips_payload_column_to_tolerate_bad_message_bytes ...@@ -1181,7 +1244,7 @@ def test_wecom_debug_overview_skips_payload_column_to_tolerate_bad_message_bytes
) VALUES ( ) VALUES (
:bot_code, :channel, :bot_id, :msg_id, :msg_time, :msg_type, :msg_content, :bot_code, :channel, :bot_id, :msg_id, :msg_time, :msg_type, :msg_content,
:sender_id, :sender_name, :contact_id, :customer_group_id, :session_title, :sender_id, :sender_name, :contact_id, :customer_group_id, :session_title,
:bot_send, CAST(X'7B226964223A20313631392C2022626F745F6964223A20224142453645333045333437364539353538353334313043313345110BEFBBBF227D' AS TEXT), :bot_send, :payload,
:dispatch_status, :dispatch_error, :created_at, :updated_at :dispatch_status, :dispatch_error, :created_at, :updated_at
) )
""" """
...@@ -1200,6 +1263,7 @@ def test_wecom_debug_overview_skips_payload_column_to_tolerate_bad_message_bytes ...@@ -1200,6 +1263,7 @@ def test_wecom_debug_overview_skips_payload_column_to_tolerate_bad_message_bytes
'customer_group_id': 1, 'customer_group_id': 1,
'session_title': 'broken-service', 'session_title': 'broken-service',
'bot_send': False, 'bot_send': False,
'payload': '{"broken": true}',
'dispatch_status': 'pending', 'dispatch_status': 'pending',
'dispatch_error': None, 'dispatch_error': None,
'created_at': datetime(2026, 5, 26, 10, 0, tzinfo=timezone.utc), 'created_at': datetime(2026, 5, 26, 10, 0, tzinfo=timezone.utc),
...@@ -1218,7 +1282,7 @@ def test_wecom_debug_overview_skips_payload_column_to_tolerate_bad_message_bytes ...@@ -1218,7 +1282,7 @@ def test_wecom_debug_overview_skips_payload_column_to_tolerate_bad_message_bytes
db.close() db.close()
def test_wecom_debug_reset_customer_group_marks_invalid_and_deleted(): def test_wecom_debug_reset_customer_group_marks_invalid_and_fails_pending_requests():
db = _setup_db() db = _setup_db()
bot, managed, _, _ = _seed_group_context(db) bot, managed, _, _ = _seed_group_context(db)
db.add( db.add(
...@@ -1235,16 +1299,41 @@ def test_wecom_debug_reset_customer_group_marks_invalid_and_deleted(): ...@@ -1235,16 +1299,41 @@ def test_wecom_debug_reset_customer_group_marks_invalid_and_deleted():
is_deleted=False, is_deleted=False,
) )
) )
db.add(
WeComGroupCreateRequest(
biz_rela_no='biz_001',
bot_id=bot.bot_id,
bot_code=bot.bot_code,
customer_contact_id='cust_1',
customer_name='alice',
qrcode_id=1,
qrcode_name='qr-a',
channel_code='store_sales',
position_id=1,
position_code='store_sales',
position_name='store-sales',
group_name='alice-service',
member_bot_ids=[managed.bot_id],
status='pending',
)
)
db.commit() db.commit()
result = reset_customer_group(WeComDebugResetCustomerGroupRequest(customer_contact_id='cust_1'), db) result = reset_customer_group(
WeComDebugResetCustomerGroupRequest(bot_id='bot_1', customer_contact_id='cust_1'),
db,
)
assert result['data']['success'] is True assert result['data']['success'] is True
assert result['data']['updated_count'] == 1 assert result['data']['invalidated_customer_groups_count'] == 1
assert result['data']['failed_group_create_requests_count'] == 1
row = db.query(WeComCustomerGroup).filter(WeComCustomerGroup.customer_contact_id == 'cust_1').first() row = db.query(WeComCustomerGroup).filter(WeComCustomerGroup.customer_contact_id == 'cust_1').first()
assert row is not None assert row is not None
assert row.group_status == 'invalid' assert row.group_status == 'invalid'
assert row.is_deleted is True request = db.query(WeComGroupCreateRequest).filter(WeComGroupCreateRequest.customer_contact_id == 'cust_1').first()
assert request is not None
assert request.status == 'failed'
assert request.fail_reason == 'manual_invalidated'
db.close() db.close()
......
...@@ -8,30 +8,36 @@ from fastapi.testclient import TestClient ...@@ -8,30 +8,36 @@ from fastapi.testclient import TestClient
from app.main import app from app.main import app
from app.model.wecom_sync import WeComBot, WeComSyncCheckpoint from app.model.wecom_sync import WeComBot, WeComSyncCheckpoint
from app.api.v1.endpoints.wecom_sync import get_wecom_sync_service from app.api.v1.endpoints.wecom_sync import get_wecom_sync_service
from app.service.wecom_sync_service import WeComSyncService from tests.conftest import TestingSessionLocal, get_testing_engine
from tests.conftest import TestingSessionLocal
client = TestClient(app) client = TestClient(app)
class FakeApiSyncService: class FakeApiSyncService:
def __init__(self) -> None: def __init__(self) -> None:
self.full_called = False self.sync_called = False
self.incremental_called = False self.sync_bot_ids = None
self.incremental_bot_ids = None
def sync_wecom_bots_groups_messages(self, *, bot_ids, start_time, end_time):
def sync_all_full(self, *, message_start_time, message_end_time): self.sync_called = True
self.full_called = True self.sync_bot_ids = list(bot_ids)
return {"bots": 1, "messages": 4} return {"bots": 1, "messages": 5}
def sync_messages_incremental(self, *, bot_ids, start_time, end_time): def upsert_checkpoint(self, *, resource_type, scope_key, last_sync_time, last_external_id, last_sync_cursor):
self.incremental_called = True checkpoint = WeComSyncCheckpoint(
self.incremental_bot_ids = list(bot_ids) resource_type=resource_type,
return 5 scope_key=scope_key,
last_sync_time=last_sync_time,
last_external_id=last_external_id,
last_sync_cursor=last_sync_cursor,
)
checkpoint.updated_at = datetime(2026, 5, 26, 10, 0, tzinfo=timezone.utc)
return checkpoint
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def clean_db(): def clean_db():
get_testing_engine()
db = TestingSessionLocal() db = TestingSessionLocal()
db.query(WeComSyncCheckpoint).delete() db.query(WeComSyncCheckpoint).delete()
db.query(WeComBot).delete() db.query(WeComBot).delete()
...@@ -61,7 +67,7 @@ def test_run_full_sync_returns_wrapped_response(): ...@@ -61,7 +67,7 @@ def test_run_full_sync_returns_wrapped_response():
assert payload["message"] == "success" assert payload["message"] == "success"
assert payload["data"]["mode"] == "full" assert payload["data"]["mode"] == "full"
assert payload["data"]["bots"] == 1 assert payload["data"]["bots"] == 1
assert fake_service.full_called is True assert fake_service.sync_called is True
def test_run_incremental_sync_uses_existing_bots_when_bot_ids_missing(): def test_run_incremental_sync_uses_existing_bots_when_bot_ids_missing():
...@@ -84,8 +90,8 @@ def test_run_incremental_sync_uses_existing_bots_when_bot_ids_missing(): ...@@ -84,8 +90,8 @@ def test_run_incremental_sync_uses_existing_bots_when_bot_ids_missing():
assert response.status_code == 200 assert response.status_code == 200
payload = response.json() payload = response.json()
assert payload["data"]["messages"] == 5 assert payload["data"]["messages"] == 5
assert fake_service.incremental_called is True assert fake_service.sync_called is True
assert fake_service.incremental_bot_ids == ["RBT001"] assert fake_service.sync_bot_ids == ["RBT001"]
def test_list_checkpoints_returns_paginated_data(): def test_list_checkpoints_returns_paginated_data():
...@@ -109,3 +115,25 @@ def test_list_checkpoints_returns_paginated_data(): ...@@ -109,3 +115,25 @@ def test_list_checkpoints_returns_paginated_data():
assert payload["code"] == 200 assert payload["code"] == 200
assert payload["data"]["total"] == 1 assert payload["data"]["total"] == 1
assert payload["data"]["list"][0]["resource_type"] == "messages" assert payload["data"]["list"][0]["resource_type"] == "messages"
def test_upsert_checkpoint_returns_wrapped_response():
fake_service = FakeApiSyncService()
app.dependency_overrides[get_wecom_sync_service] = lambda: fake_service
response = client.post(
"/api/v1/wecom-sync/checkpoints",
json={
"resource_type": "messages",
"scope_key": "global",
"last_sync_time": "2026-05-21T00:00:00Z",
"last_external_id": "msg_001",
},
)
assert response.status_code == 200
payload = response.json()
assert payload["code"] == 200
assert payload["data"]["resource_type"] == "messages"
assert payload["data"]["scope_key"] == "global"
assert payload["data"]["last_external_id"] == "msg_001"
...@@ -19,7 +19,7 @@ from app.service.wecom_sync_service import ( ...@@ -19,7 +19,7 @@ from app.service.wecom_sync_service import (
WeComSyncClient, WeComSyncClient,
WeComSyncService, WeComSyncService,
) )
from tests.conftest import TestingSessionLocal, engine from tests.conftest import TestingSessionLocal, get_testing_engine
def _dt(value: str) -> datetime: def _dt(value: str) -> datetime:
...@@ -81,6 +81,7 @@ class RecordingDispatcher(WeComMessageDispatcher): ...@@ -81,6 +81,7 @@ class RecordingDispatcher(WeComMessageDispatcher):
@pytest.fixture @pytest.fixture
def db(): def db():
engine = get_testing_engine()
Base.metadata.create_all(bind=engine) Base.metadata.create_all(bind=engine)
session = TestingSessionLocal() session = TestingSessionLocal()
session.query(WeComSyncCheckpoint).delete() session.query(WeComSyncCheckpoint).delete()
...@@ -437,6 +438,104 @@ def test_incremental_sync_uses_time_and_msg_id_boundary_without_duplicates(db): ...@@ -437,6 +438,104 @@ def test_incremental_sync_uses_time_and_msg_id_boundary_without_duplicates(db):
assert [item.msg_id for item in messages] == ["msg_001", "msg_002", "msg_003"] assert [item.msg_id for item in messages] == ["msg_001", "msg_002", "msg_003"]
def test_incremental_sync_uses_global_message_checkpoint_for_new_group(db):
client = FakeWeComSyncClient(
bots=[
{
"channel": "wt_ww",
"bot_id": "RBT001",
"bot_code": "wt_ww:RBT001",
"bot_name": "sales-bot",
"online": 1,
}
],
messages_by_bot={
"RBT001": [
{
"channel": "wt_ww",
"bot_id": "RBT001",
"msg_id": "msg_001",
"sender_id": "wm_001",
"sender_name": "zhangsan",
"msg_content": "old",
"msg_type": "text",
"msg_time": "2026-05-21T09:03:00Z",
"session_title": "sales-group",
"contact_id": "wr_001",
"bot_send": 0,
},
{
"channel": "wt_ww",
"bot_id": "RBT001",
"msg_id": "msg_002",
"sender_id": "wm_001",
"sender_name": "zhangsan",
"msg_content": "new",
"msg_type": "text",
"msg_time": "2026-05-21T09:06:00Z",
"session_title": "sales-group",
"contact_id": "wr_001",
"bot_send": 0,
},
]
},
)
service = WeComSyncService(db, client, RecordingDispatcher())
db.add(
WeComCustomerGroup(
customer_contact_id="cust_001",
customer_name="zhangsan",
bot_id="RBT001",
bot_code="wt_ww:RBT001",
group_id="wr_001",
group_name="sales-group",
group_status="active",
group_create_request_id=1,
member_bot_ids=["managed_1"],
is_deleted=False,
)
)
db.add(
WeComSyncCheckpoint(
resource_type="messages",
scope_key="global",
last_sync_time=_dt("2026-05-21T09:05:00Z"),
last_status="manual",
)
)
db.commit()
service.sync_bots_incremental()
synced = service.sync_messages_incremental(
bot_ids=["RBT001"],
start_time=None,
end_time=_dt("2026-05-21T10:00:00Z"),
)
assert synced == 1
messages = db.query(WeComMessage).order_by(WeComMessage.msg_id.asc()).all()
assert [item.msg_id for item in messages] == ["msg_002"]
def test_upsert_checkpoint_persists_manual_seed(db):
client = FakeWeComSyncClient()
service = WeComSyncService(db, client, RecordingDispatcher())
checkpoint = service.upsert_checkpoint(
resource_type="messages",
scope_key="global",
last_sync_time=_dt("2026-05-21T09:05:00Z"),
last_external_id="msg_001",
last_sync_cursor="cursor-1",
)
assert checkpoint.resource_type == "messages"
assert checkpoint.scope_key == "global"
assert checkpoint.last_status == "manual"
assert checkpoint.last_external_id == "msg_001"
assert checkpoint.last_sync_cursor == "cursor-1"
def test_dispatch_failure_marks_message_failed_without_losing_payload(db): def test_dispatch_failure_marks_message_failed_without_losing_payload(db):
client = FakeWeComSyncClient( client = FakeWeComSyncClient(
bots=[ bots=[
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!