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 2545 additions and 570 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)
from __future__ import annotations from __future__ import annotations
from sqlalchemy import text from sqlalchemy import text
from sqlalchemy.engine import make_url
def _rebuild_official_site_agent_display_without_unique(conn) -> None: def _rebuild_official_site_agent_display_without_unique(conn) -> None:
...@@ -220,270 +221,268 @@ def _rebuild_official_tabs_without_redundant_position_fields(conn) -> None: ...@@ -220,270 +221,268 @@ def _rebuild_official_tabs_without_redundant_position_fields(conn) -> None:
conn.execute(text("PRAGMA foreign_keys=ON")) conn.execute(text("PRAGMA foreign_keys=ON"))
def ensure_runtime_schema(engine) -> None: def _column_names(conn, dialect: str, table_name: str) -> set[str]:
if not str(engine.url).startswith("sqlite"): if dialect == "sqlite":
return result = conn.execute(text(f"PRAGMA table_info({table_name})"))
return {row[1] for row in result}
with engine.begin() as conn: result = conn.execute(text(f"SHOW COLUMNS FROM {table_name}"))
table_names = { return {row[0] for row in result}
row[0]
for row in conn.execute(text("SELECT name FROM sqlite_master WHERE type='table'"))
}
if "wecom_customer_position_groups" in table_names:
conn.execute(text("DROP TABLE wecom_customer_position_groups"))
table_names.remove("wecom_customer_position_groups")
if "wecom_groups" in table_names:
conn.execute(text("DROP TABLE wecom_groups"))
table_names.remove("wecom_groups")
if "qrcode_channels" in table_names:
qrcode_columns = {
row[1]
for row in conn.execute(text("PRAGMA table_info(qrcode_channels)"))
}
if "position_name" in qrcode_columns or "channel_code" in qrcode_columns or "agent_names" in qrcode_columns:
_rebuild_qrcode_channels_without_redundant_position_fields(conn)
if "wecom_employee_qrcodes" not in table_names:
conn.execute(
text(
"""
CREATE TABLE wecom_employee_qrcodes (
id INTEGER PRIMARY KEY,
employee_id VARCHAR(100) NOT NULL UNIQUE,
qrcode_url VARCHAR(500) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
)
"""
)
)
conn.execute(
text(
"CREATE UNIQUE INDEX IF NOT EXISTS uk_wecom_employee_qrcodes_employee_id "
"ON wecom_employee_qrcodes(employee_id)"
)
)
if "wecom_job_configs" not in table_names:
conn.execute(
text(
"""
CREATE TABLE wecom_job_configs (
id INTEGER PRIMARY KEY,
job_key VARCHAR(64) NOT NULL UNIQUE,
enabled BOOLEAN NOT NULL DEFAULT 1,
last_run_at DATETIME,
last_status VARCHAR(32),
last_error TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
)
"""
)
)
if "wecom_group_create_requests" not in table_names: def _mysql_table_names(conn) -> set[str]:
conn.execute( result = conn.execute(text("SHOW TABLES"))
text( return {row[0] for row in result}
"""
CREATE TABLE wecom_group_create_requests (
id INTEGER PRIMARY KEY,
biz_rela_no VARCHAR(191) NOT NULL UNIQUE,
bot_id VARCHAR(128) NOT NULL,
bot_code VARCHAR(191) NOT NULL,
customer_contact_id VARCHAR(191) NOT NULL,
customer_name VARCHAR(255),
qrcode_id INTEGER NOT NULL,
qrcode_name VARCHAR(255),
channel_code VARCHAR(100) NOT NULL,
position_id INTEGER NOT NULL,
position_code VARCHAR(100) NOT NULL,
position_name VARCHAR(255) NOT NULL,
group_name VARCHAR(255) NOT NULL,
member_bot_ids JSON NOT NULL,
member_snapshot JSON,
request_payload JSON,
submit_result JSON,
task_id VARCHAR(191),
status VARCHAR(32) NOT NULL DEFAULT 'pending',
fail_reason TEXT,
resolved_group_contact_id VARCHAR(191),
resolved_group_name VARCHAR(255),
resolved_contact_type VARCHAR(64),
external_result JSON,
resolved_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
)
"""
)
)
conn.execute(text("CREATE INDEX idx_wgcr_status ON wecom_group_create_requests(status)"))
conn.execute(text("CREATE INDEX idx_wgcr_bot ON wecom_group_create_requests(bot_id)"))
conn.execute(text("CREATE INDEX idx_wgcr_customer ON wecom_group_create_requests(customer_contact_id)"))
conn.execute(text("CREATE INDEX idx_wgcr_task_id ON wecom_group_create_requests(task_id)"))
conn.execute(text("CREATE INDEX idx_wgcr_resolved_group ON wecom_group_create_requests(resolved_group_contact_id)"))
else:
group_create_columns = {
row[1]
for row in conn.execute(text("PRAGMA table_info(wecom_group_create_requests)"))
}
if "submit_result" not in group_create_columns:
conn.execute(
text("ALTER TABLE wecom_group_create_requests ADD COLUMN submit_result JSON")
)
if "wecom_customer_groups" not in table_names:
conn.execute(
text(
"""
CREATE TABLE wecom_customer_groups (
id INTEGER PRIMARY KEY,
customer_contact_id VARCHAR(191) NOT NULL UNIQUE,
customer_name VARCHAR(255),
bot_id VARCHAR(128) NOT NULL,
bot_code VARCHAR(191) NOT NULL,
group_id VARCHAR(191),
group_name VARCHAR(255),
group_status VARCHAR(32) NOT NULL DEFAULT 'pending',
group_create_request_id INTEGER,
member_bot_ids JSON NOT NULL,
is_deleted BOOLEAN NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
)
"""
)
)
conn.execute(text("CREATE INDEX ix_wecom_customer_groups_customer_contact_id ON wecom_customer_groups(customer_contact_id)"))
conn.execute(text("CREATE INDEX ix_wecom_customer_groups_bot_id ON wecom_customer_groups(bot_id)"))
conn.execute(text("CREATE INDEX ix_wecom_customer_groups_bot_code ON wecom_customer_groups(bot_code)"))
conn.execute(text("CREATE INDEX ix_wecom_customer_groups_group_id ON wecom_customer_groups(group_id)"))
conn.execute(text("CREATE INDEX ix_wecom_customer_groups_group_status ON wecom_customer_groups(group_status)"))
conn.execute(text("CREATE INDEX ix_wecom_customer_groups_group_create_request_id ON wecom_customer_groups(group_create_request_id)"))
conn.execute(text("CREATE INDEX ix_wecom_customer_groups_is_deleted ON wecom_customer_groups(is_deleted)"))
if "wecom_messages" in table_names:
wecom_message_columns = {
row[1]
for row in conn.execute(text("PRAGMA table_info(wecom_messages)"))
}
if "customer_group_id" not in wecom_message_columns:
conn.execute(
text("ALTER TABLE wecom_messages ADD COLUMN customer_group_id INTEGER")
)
conn.execute(
text(
"CREATE INDEX IF NOT EXISTS ix_wecom_messages_customer_group_id "
"ON wecom_messages(customer_group_id)"
)
)
if "official_tabs" in table_names:
official_tab_columns = {
row[1]
for row in conn.execute(text("PRAGMA table_info(official_tabs)"))
}
if "position_code" in official_tab_columns or "position_name" in official_tab_columns:
_rebuild_official_tabs_without_redundant_position_fields(conn)
official_tab_columns = {
row[1]
for row in conn.execute(text("PRAGMA table_info(official_tabs)"))
}
if "main_title" not in official_tab_columns:
conn.execute(
text("ALTER TABLE official_tabs ADD COLUMN main_title VARCHAR(200)")
)
if "sub_title" not in official_tab_columns:
conn.execute(
text("ALTER TABLE official_tabs ADD COLUMN sub_title VARCHAR(500)")
)
if "ai_agents" in table_names:
ai_agent_columns = {
row[1]
for row in conn.execute(text("PRAGMA table_info(ai_agents)"))
}
if "managed_user_id" not in ai_agent_columns:
conn.execute(
text("ALTER TABLE ai_agents ADD COLUMN managed_user_id INTEGER")
)
conn.execute(
text(
"CREATE INDEX IF NOT EXISTS ix_ai_agents_managed_user_id "
"ON ai_agents(managed_user_id)"
)
)
if "is_steward" not in ai_agent_columns:
conn.execute(
text(
"ALTER TABLE ai_agents ADD COLUMN is_steward "
"BOOLEAN NOT NULL DEFAULT 0"
)
)
if "official_site_agent_display" in table_names: def _ensure_mysql_runtime_schema(conn) -> None:
display_columns = { conn.execute(
row[1] text(
for row in conn.execute(text("PRAGMA table_info(official_site_agent_display)")) """
} CREATE TABLE IF NOT EXISTS wecom_employee_qrcodes (
display_table_sql = conn.execute( id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
text("SELECT sql FROM sqlite_master WHERE type='table' AND name='official_site_agent_display'") employee_id VARCHAR(100) NOT NULL UNIQUE,
).scalar() or "" qrcode_url VARCHAR(500) NOT NULL,
if "UNIQUE (tab_id, agent_id)" in display_table_sql or "UNIQUE(tab_id, agent_id)" in display_table_sql: created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
_rebuild_official_site_agent_display_without_unique(conn) updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
display_columns = { INDEX uk_wecom_employee_qrcodes_employee_id (employee_id)
row[1] )
for row in conn.execute(text("PRAGMA table_info(official_site_agent_display)")) """
} )
)
if "agent_name" not in display_columns:
conn.execute(
text("ALTER TABLE official_site_agent_display ADD COLUMN agent_name VARCHAR(50) NOT NULL DEFAULT ''")
)
if "status" not in display_columns: table_names = _mysql_table_names(conn)
conn.execute(
text("ALTER TABLE official_site_agent_display ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'enable'") if "wecom_messages" in table_names:
) columns = _column_names(conn, "mysql", "wecom_messages")
conn.execute( if "customer_group_id" not in columns:
text("CREATE INDEX IF NOT EXISTS idx_osad_status ON official_site_agent_display(status)") conn.execute(text("ALTER TABLE wecom_messages ADD COLUMN customer_group_id INTEGER NULL"))
conn.execute(text("CREATE INDEX ix_wecom_messages_customer_group_id ON wecom_messages(customer_group_id)"))
if "official_tabs" in table_names:
columns = _column_names(conn, "mysql", "official_tabs")
if "main_title" not in columns:
conn.execute(text("ALTER TABLE official_tabs ADD COLUMN main_title VARCHAR(200) NULL"))
if "sub_title" not in columns:
conn.execute(text("ALTER TABLE official_tabs ADD COLUMN sub_title VARCHAR(500) NULL"))
if "ai_agents" in table_names:
columns = _column_names(conn, "mysql", "ai_agents")
if "managed_user_id" not in columns:
conn.execute(text("ALTER TABLE ai_agents ADD COLUMN managed_user_id INTEGER NULL"))
conn.execute(text("CREATE INDEX ix_ai_agents_managed_user_id ON ai_agents(managed_user_id)"))
if "is_steward" not in columns:
conn.execute(text("ALTER TABLE ai_agents ADD COLUMN is_steward BOOLEAN NOT NULL DEFAULT 0"))
if "official_site_agent_display" in table_names:
columns = _column_names(conn, "mysql", "official_site_agent_display")
if "agent_name" not in columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN agent_name VARCHAR(50) NOT NULL DEFAULT ''"))
if "status" not in columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'enable'"))
if "summary" not in columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN summary VARCHAR(500) NULL"))
if "icon_url" not in columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN icon_url VARCHAR(500) NULL"))
if "media_url" not in columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN media_url VARCHAR(500) NULL"))
if "media_type" not in columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN media_type VARCHAR(10) NULL"))
if "speech_title" not in columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN speech_title VARCHAR(100) NULL"))
if "speech_content" not in columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN speech_content VARCHAR(200) NULL"))
def _ensure_sqlite_runtime_schema(conn) -> None:
table_names = {
row[0]
for row in conn.execute(text("SELECT name FROM sqlite_master WHERE type='table'"))
}
if "wecom_customer_position_groups" in table_names:
conn.execute(text("DROP TABLE wecom_customer_position_groups"))
table_names.remove("wecom_customer_position_groups")
if "wecom_groups" in table_names:
conn.execute(text("DROP TABLE wecom_groups"))
table_names.remove("wecom_groups")
if "qrcode_channels" in table_names:
qrcode_columns = _column_names(conn, "sqlite", "qrcode_channels")
if "position_name" in qrcode_columns or "channel_code" in qrcode_columns or "agent_names" in qrcode_columns:
_rebuild_qrcode_channels_without_redundant_position_fields(conn)
if "wecom_employee_qrcodes" not in table_names:
conn.execute(
text(
"""
CREATE TABLE wecom_employee_qrcodes (
id INTEGER PRIMARY KEY,
employee_id VARCHAR(100) NOT NULL UNIQUE,
qrcode_url VARCHAR(500) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
) )
"""
)
)
conn.execute(
text(
"CREATE UNIQUE INDEX IF NOT EXISTS uk_wecom_employee_qrcodes_employee_id "
"ON wecom_employee_qrcodes(employee_id)"
)
)
if "summary" not in display_columns: if "wecom_job_configs" not in table_names:
conn.execute( conn.execute(
text("ALTER TABLE official_site_agent_display ADD COLUMN summary VARCHAR(500)") text(
"""
CREATE TABLE wecom_job_configs (
id INTEGER PRIMARY KEY,
job_key VARCHAR(64) NOT NULL UNIQUE,
enabled BOOLEAN NOT NULL DEFAULT 1,
last_run_at DATETIME,
last_status VARCHAR(32),
last_error TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
) )
"""
)
)
if "icon_url" not in display_columns: if "wecom_group_create_requests" not in table_names:
conn.execute( conn.execute(
text("ALTER TABLE official_site_agent_display ADD COLUMN icon_url VARCHAR(500)") text(
"""
CREATE TABLE wecom_group_create_requests (
id INTEGER PRIMARY KEY,
biz_rela_no VARCHAR(191) NOT NULL UNIQUE,
bot_id VARCHAR(128) NOT NULL,
bot_code VARCHAR(191) NOT NULL,
customer_contact_id VARCHAR(191) NOT NULL,
customer_name VARCHAR(255),
qrcode_id INTEGER NOT NULL,
qrcode_name VARCHAR(255),
channel_code VARCHAR(100) NOT NULL,
position_id INTEGER NOT NULL,
position_code VARCHAR(100) NOT NULL,
position_name VARCHAR(255) NOT NULL,
group_name VARCHAR(255) NOT NULL,
member_bot_ids JSON NOT NULL,
member_snapshot JSON,
request_payload JSON,
submit_result JSON,
task_id VARCHAR(191),
status VARCHAR(32) NOT NULL DEFAULT 'pending',
fail_reason TEXT,
resolved_group_contact_id VARCHAR(191),
resolved_group_name VARCHAR(255),
resolved_contact_type VARCHAR(64),
external_result JSON,
resolved_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
) )
"""
if "media_url" not in display_columns: )
conn.execute( )
text("ALTER TABLE official_site_agent_display ADD COLUMN media_url VARCHAR(500)") conn.execute(text("CREATE INDEX idx_wgcr_status ON wecom_group_create_requests(status)"))
conn.execute(text("CREATE INDEX idx_wgcr_bot ON wecom_group_create_requests(bot_id)"))
conn.execute(text("CREATE INDEX idx_wgcr_customer ON wecom_group_create_requests(customer_contact_id)"))
conn.execute(text("CREATE INDEX idx_wgcr_task_id ON wecom_group_create_requests(task_id)"))
conn.execute(text("CREATE INDEX idx_wgcr_resolved_group ON wecom_group_create_requests(resolved_group_contact_id)"))
else:
group_create_columns = _column_names(conn, "sqlite", "wecom_group_create_requests")
if "submit_result" not in group_create_columns:
conn.execute(text("ALTER TABLE wecom_group_create_requests ADD COLUMN submit_result JSON"))
if "wecom_customer_groups" not in table_names:
conn.execute(
text(
"""
CREATE TABLE wecom_customer_groups (
id INTEGER PRIMARY KEY,
customer_contact_id VARCHAR(191) NOT NULL UNIQUE,
customer_name VARCHAR(255),
bot_id VARCHAR(128) NOT NULL,
bot_code VARCHAR(191) NOT NULL,
group_id VARCHAR(191),
group_name VARCHAR(255),
group_status VARCHAR(32) NOT NULL DEFAULT 'pending',
group_create_request_id INTEGER,
member_bot_ids JSON NOT NULL,
is_deleted BOOLEAN NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
) )
"""
)
)
conn.execute(text("CREATE INDEX ix_wecom_customer_groups_customer_contact_id ON wecom_customer_groups(customer_contact_id)"))
conn.execute(text("CREATE INDEX ix_wecom_customer_groups_bot_id ON wecom_customer_groups(bot_id)"))
conn.execute(text("CREATE INDEX ix_wecom_customer_groups_bot_code ON wecom_customer_groups(bot_code)"))
conn.execute(text("CREATE INDEX ix_wecom_customer_groups_group_id ON wecom_customer_groups(group_id)"))
conn.execute(text("CREATE INDEX ix_wecom_customer_groups_group_status ON wecom_customer_groups(group_status)"))
conn.execute(text("CREATE INDEX ix_wecom_customer_groups_group_create_request_id ON wecom_customer_groups(group_create_request_id)"))
conn.execute(text("CREATE INDEX ix_wecom_customer_groups_is_deleted ON wecom_customer_groups(is_deleted)"))
if "wecom_messages" in table_names:
wecom_message_columns = _column_names(conn, "sqlite", "wecom_messages")
if "customer_group_id" not in wecom_message_columns:
conn.execute(text("ALTER TABLE wecom_messages ADD COLUMN customer_group_id INTEGER"))
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_wecom_messages_customer_group_id ON wecom_messages(customer_group_id)"))
if "official_tabs" in table_names:
official_tab_columns = _column_names(conn, "sqlite", "official_tabs")
if "position_code" in official_tab_columns or "position_name" in official_tab_columns:
_rebuild_official_tabs_without_redundant_position_fields(conn)
official_tab_columns = _column_names(conn, "sqlite", "official_tabs")
if "main_title" not in official_tab_columns:
conn.execute(text("ALTER TABLE official_tabs ADD COLUMN main_title VARCHAR(200)"))
if "sub_title" not in official_tab_columns:
conn.execute(text("ALTER TABLE official_tabs ADD COLUMN sub_title VARCHAR(500)"))
if "ai_agents" in table_names:
ai_agent_columns = _column_names(conn, "sqlite", "ai_agents")
if "managed_user_id" not in ai_agent_columns:
conn.execute(text("ALTER TABLE ai_agents ADD COLUMN managed_user_id INTEGER"))
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_ai_agents_managed_user_id ON ai_agents(managed_user_id)"))
if "is_steward" not in ai_agent_columns:
conn.execute(text("ALTER TABLE ai_agents ADD COLUMN is_steward BOOLEAN NOT NULL DEFAULT 0"))
if "official_site_agent_display" in table_names:
display_columns = _column_names(conn, "sqlite", "official_site_agent_display")
display_table_sql = conn.execute(
text("SELECT sql FROM sqlite_master WHERE type='table' AND name='official_site_agent_display'")
).scalar() or ""
if "UNIQUE (tab_id, agent_id)" in display_table_sql or "UNIQUE(tab_id, agent_id)" in display_table_sql:
_rebuild_official_site_agent_display_without_unique(conn)
display_columns = _column_names(conn, "sqlite", "official_site_agent_display")
if "agent_name" not in display_columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN agent_name VARCHAR(50) NOT NULL DEFAULT ''"))
if "status" not in display_columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN status VARCHAR(20) NOT NULL DEFAULT 'enable'"))
conn.execute(text("CREATE INDEX IF NOT EXISTS idx_osad_status ON official_site_agent_display(status)"))
if "summary" not in display_columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN summary VARCHAR(500)"))
if "icon_url" not in display_columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN icon_url VARCHAR(500)"))
if "media_url" not in display_columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN media_url VARCHAR(500)"))
if "media_type" not in display_columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN media_type VARCHAR(10)"))
if "speech_title" not in display_columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN speech_title VARCHAR(100)"))
if "speech_content" not in display_columns:
conn.execute(text("ALTER TABLE official_site_agent_display ADD COLUMN speech_content VARCHAR(200)"))
if "media_type" not in display_columns:
conn.execute(
text("ALTER TABLE official_site_agent_display ADD COLUMN media_type VARCHAR(10)")
)
if "speech_title" not in display_columns: def ensure_runtime_schema(engine) -> None:
conn.execute( dialect = make_url(str(engine.url)).get_backend_name()
text("ALTER TABLE official_site_agent_display ADD COLUMN speech_title VARCHAR(100)") if dialect != "mysql":
) raise RuntimeError(f"Unsupported database dialect: {dialect}. Only MySQL is allowed.")
if "speech_content" not in display_columns: with engine.begin() as conn:
conn.execute( _ensure_mysql_runtime_schema(conn)
text("ALTER TABLE official_site_agent_display ADD COLUMN speech_content VARCHAR(200)")
)
...@@ -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",
} },
} },
] ]
} }
} }
......
...@@ -7,185 +7,287 @@ from pydantic import BaseModel, Field ...@@ -7,185 +7,287 @@ from pydantic import BaseModel, Field
class WeComSyncRunRequest(BaseModel): class WeComSyncRunRequest(BaseModel):
mode: str = Field(..., pattern="^(full|incremental)$", description="同步模式:full 为全量,incremental 为增量。", examples=["full"]) mode: str = Field(..., pattern="^(full|incremental)$")
bot_ids: Optional[List[str]] = Field(default=None, description="指定同步的 bot_id 列表;为空时按系统默认范围执行。", examples=[["RBT001"]]) bot_ids: Optional[List[str]] = None
message_start_time: Optional[datetime] = Field(default=None, description="消息同步开始时间。", examples=["2026-05-21T00:00:00Z"]) message_start_time: Optional[datetime] = None
message_end_time: Optional[datetime] = Field(default=None, description="消息同步结束时间。", examples=["2026-05-21T23:59:59Z"]) message_end_time: Optional[datetime] = None
class WeComSyncRunResponse(BaseModel): class WeComSyncRunResponse(BaseModel):
mode: str = Field(..., description="本次执行的同步模式。", examples=["full"]) mode: str
bots: int = Field(..., description="同步到的机器人数量。", examples=[1]) bots: int
messages: int = Field(..., description="同步到的消息数量。", examples=[156]) messages: int
triggered_at: datetime = Field(..., description="任务触发时间。", examples=["2026-05-21T16:30:00Z"]) triggered_at: datetime
class WeComSyncCheckpointItem(BaseModel): class WeComSyncCheckpointItem(BaseModel):
resource_type: str = Field(..., description="资源类型。", examples=["messages"]) resource_type: str = Field(
scope_key: str = Field(..., description="同步范围标识。", examples=["bot:wt_ww:RBT001"]) ...,
last_sync_time: Optional[datetime] = Field(default=None, description="最近一次同步时间。") description="检查点资源类型。`bots` 表示机器人列表同步进度,`messages` 表示群消息同步进度,`customers` 表示联系人/客户扫描进度。",
last_external_id: Optional[str] = Field(default=None, description="最近一次同步的外部 ID。") examples=["customers"],
last_status: Optional[str] = Field(default=None, description="最近一次同步状态。", examples=["success"]) )
last_error: Optional[str] = Field(default=None, description="最近一次同步错误信息。") scope_key: str = Field(
last_started_at: Optional[datetime] = Field(default=None, description="最近一次同步开始时间。") ...,
last_finished_at: Optional[datetime] = Field(default=None, description="最近一次同步结束时间。") description=(
"检查点作用域键。"
"`global` 一般用于机器人列表同步;"
"`group:<group_id>` 用于某个客户群的消息增量同步进度;"
"`bot:<bot_id>` 可用于某个机器人的客户扫描进度。"
),
examples=["bot:ABE6E30E3476E955853410C13E38C1065194F219CF554649F1C4F9C615435A82"],
)
last_sync_time: Optional[datetime] = Field(
default=None,
description="最近一次成功处理到的业务时间。下一次增量同步通常从这个时间点之后继续拉取。",
examples=["2026-05-26T09:30:00Z"],
)
last_external_id: Optional[str] = Field(
default=None,
description="当多条记录时间相同时,用于去重/断点续传的外部唯一 ID,例如消息 msg_id 或 bot_code。",
examples=["1425296440037376"],
)
last_sync_cursor: Optional[str] = Field(
default=None,
description="预留的游标字段。当前消息/机器人同步主流程未强依赖该值,可用于兼容未来按 cursor 拉取的外部接口。",
examples=["cursor_001"],
)
last_status: Optional[str] = Field(
default=None,
description="最近一次写入该检查点时记录的状态,例如 `success` 或 `manual`。",
examples=["success"],
)
last_error: Optional[str] = Field(
default=None,
description="最近一次同步失败时记录的错误信息。",
examples=["http 503"],
)
last_started_at: Optional[datetime] = Field(
default=None,
description="最近一次同步开始时间。",
examples=["2026-05-26T09:30:00Z"],
)
last_finished_at: Optional[datetime] = Field(
default=None,
description="最近一次同步完成时间。",
examples=["2026-05-26T09:30:10Z"],
)
class WeComSyncCheckpointListResponse(BaseModel): class WeComSyncCheckpointListResponse(BaseModel):
total: int = Field(..., description="总数。", examples=[4]) total: int = Field(..., description="总记录数。", examples=[3])
page: int = Field(..., description="页码。", examples=[1]) page: int = Field(..., description="当前页码,从 1 开始。", examples=[1])
page_size: int = Field(..., description="每页条数。", examples=[20]) page_size: int = Field(..., description="当前分页大小。", examples=[20])
list: List[WeComSyncCheckpointItem] = Field(..., description="同步检查点列表。") list: List[WeComSyncCheckpointItem] = Field(default_factory=list, description="检查点列表。")
class WeComJobRunRequest(BaseModel): class WeComSyncCheckpointUpsertRequest(BaseModel):
job_type: str = Field( resource_type: str = Field(
...,
pattern="^(bots|messages|customers)$",
description=(
"要修改的检查点资源类型。"
"`bots` 用于机器人列表同步;"
"`messages` 用于群消息同步;"
"`customers` 用于联系人/客户扫描。"
),
examples=["customers"],
)
scope_key: str = Field(
...,
description=(
"检查点作用域键。"
"机器人列表通常传 `global`;"
"群消息同步通常传 `group:<group_id>`。"
"客户扫描通常传 `bot:<bot_id>`。"
"如果你希望某个群从指定时间重新开始增量拉取,需要精确更新该群对应的 `group:<group_id>` 检查点。"
),
examples=["bot:ABE6E30E3476E955853410C13E38C1065194F219CF554649F1C4F9C615435A82"],
)
last_sync_time: datetime = Field(
..., ...,
pattern="^(sync_wecom_bots_groups_messages|sync_customer_groups|dispatch_customer_group_messages)$",
description=( description=(
"任务类型。" "手工设置的断点时间。"
"可选值:" "下一次增量同步会把它视为“已处理到这里”,只拉这个时间点之后的数据。"
"1. sync_wecom_bots_groups_messages:统一增量同步机器人、群、群消息。" "如果外部接口返回的数据包含与该时间相同的记录,还会结合 `last_external_id` 做去重。"
"2. sync_customer_groups:处理客户群编排,包括轮询 pending 请求和创建新请求。"
"3. dispatch_customer_group_messages:按 bot_id 扫描本地待处理群消息,并投递到下游分发链路。"
), ),
examples=["sync_wecom_bots_groups_messages"], examples=["2026-05-26T09:30:00Z"],
) )
bot_ids: Optional[List[str]] = Field( last_external_id: Optional[str] = Field(
default=None, default=None,
description=( description=(
"指定执行任务的 bot_id 列表。" "可选。与 `last_sync_time` 配合使用的外部唯一 ID。"
"为空时按各任务的默认范围执行。" "当多条记录拥有相同业务时间时,系统会用它避免重复消费同一条记录。"
"对于 sync_wecom_bots_groups_messages 和 sync_customer_groups,通常表示只处理这些承接机器人;"
"对于 dispatch_customer_group_messages,表示只分发这些机器人名下的本地待处理群消息。"
), ),
examples=[["RBT001"]], examples=["1425296440037376"],
)
last_sync_cursor: Optional[str] = Field(
default=None,
description="可选。预留游标字段,当前主流程通常可不填。",
examples=["cursor_001"],
) )
dry_run: bool = Field(
default=False, model_config = {
description="是否只做演练不真正执行。当前字段预留,现阶段新三类 job 默认按实际逻辑执行。", "json_schema_extra": {
examples=[False], "examples": [
{
"resource_type": "messages",
"scope_key": "group:2F9EA29F5F99A685E95104BFC5176A626CB77981F72E7003FD5FDB76BADF8AAD",
"last_sync_time": "2026-05-26T09:30:00Z",
"last_external_id": "1425296440037376",
},
{
"resource_type": "bots",
"scope_key": "global",
"last_sync_time": "2026-05-26T00:00:00Z",
"last_external_id": "yc_ww:ABE6E30E3476E955853410C13E38C1065194F219CF554649F1C4F9C615435A82",
},
{
"resource_type": "customers",
"scope_key": "bot:ABE6E30E3476E955853410C13E38C1065194F219CF554649F1C4F9C615435A82",
"last_sync_time": "2026-05-26T09:30:00Z",
"last_external_id": "762865B77C5D5473ED0BC7CBFD8DED2F5194F219CF554649F1C4F9C615435A82",
},
]
}
}
class WeComSyncCheckpointUpsertResponse(BaseModel):
resource_type: str = Field(..., description="检查点资源类型。", examples=["messages"])
scope_key: str = Field(..., description="检查点作用域键。", examples=["group:2F9EA29F5F99A685E95104BFC5176A626CB77981F72E7003FD5FDB76BADF8AAD"])
last_sync_time: datetime = Field(..., description="写入后的断点时间。", examples=["2026-05-26T09:30:00Z"])
last_external_id: Optional[str] = Field(default=None, description="写入后的外部唯一 ID。", examples=["1425296440037376"])
last_sync_cursor: Optional[str] = Field(default=None, description="写入后的游标值。", examples=["cursor_001"])
updated_at: datetime = Field(..., description="检查点记录更新时间。", examples=["2026-05-26T09:31:00Z"])
class WeComJobRunRequest(BaseModel):
job_type: str = Field(
...,
pattern="^(sync_wecom_bots_groups_messages|sync_customer_groups|dispatch_customer_group_messages)$",
) )
bot_ids: Optional[List[str]] = None
dry_run: bool = False
class WeComNewCustomersRequest(BaseModel): class WeComNewCustomersRequest(BaseModel):
bot_ids: Optional[List[str]] = Field(default=None, description="待扫描的新客户所属 bot_id 列表;为空时扫描本地已同步的全部机器人。", examples=[["RBT001"]]) bot_ids: Optional[List[str]] = None
class WeComGroupCreateRequestItem(BaseModel): class WeComGroupCreateRequestItem(BaseModel):
bot_code: str = Field(..., description="发起建群的机器人标识,格式与机器人接口保持一致,例如 yc_ww:<bot_id>。", examples=["yc_ww:ABE6E30E3476E955853410C13E38C1065194F219CF554649F1C4F9C615435A82"]) bot_code: str
group_name: str = Field(..., description="群名称,对应机器人接口的 group_name。", examples=["123"]) group_name: str
member_list: List[str] = Field(..., min_length=1, description="成员列表,对应机器人接口的 member_list。wt_ww 传显示名,yc_ww 传 contact_serial_no,yjy_ww 传 wxid。", examples=[["762865B77C5D5473ED0BC7CBFD8DED2F5194F219CF554649F1C4F9C615435A82", "78AF0EC2871502AFE12491C6798B0ADC5194F219CF554649F1C4F9C615435A82"]]) member_list: List[str] = Field(..., min_length=1)
group_announcement: Optional[str] = Field(default=None, description="群公告,对应机器人接口的 group_announcement。", examples=["1232132"]) group_announcement: Optional[str] = None
biz_rela_no: Optional[str] = Field(default=None, description="业务单号。若不传则系统自动生成唯一值。", examples=["biz-group-1779529725643"]) biz_rela_no: Optional[str] = None
class WeComGroupCreateBatchRequest(BaseModel): class WeComGroupCreateBatchRequest(BaseModel):
items: List[WeComGroupCreateRequestItem] = Field(..., description="批量建群请求项。一次可提交多个群。") items: List[WeComGroupCreateRequestItem]
class WeComJobRunResponse(BaseModel): class WeComJobRunResponse(BaseModel):
job_type: str = Field(..., description="任务类型。新三类 job 之一。", examples=["dispatch_customer_group_messages"]) job_type: str
processed_count: int = Field(..., description="处理数量。", examples=[10]) processed_count: int
triggered_at: datetime = Field(..., description="任务触发时间。", examples=["2026-05-22T10:00:00Z"]) triggered_at: datetime
class WeComGroupCreateBatchItemResult(BaseModel): class WeComGroupCreateBatchItemResult(BaseModel):
index: int = Field(..., description="对应请求 items 中的下标。", examples=[0]) index: int
status: str = Field(..., description="处理结果:accepted 表示已受理,failed 表示受理失败。", examples=["accepted"]) status: str
biz_rela_no: Optional[str] = Field(default=None, description="业务单号。") biz_rela_no: Optional[str] = None
task_id: Optional[str] = Field(default=None, description="机器人接口返回的任务 ID。") task_id: Optional[str] = None
submit_result: Optional[dict[str, Any]] = Field(default=None, description="机器人建群接口提交时返回的原始 data 内容。") submit_result: Optional[dict[str, Any]] = None
message: str = Field(..., description="结果说明。", examples=["accepted"]) message: str
class WeComGroupCreateBatchResponse(BaseModel): class WeComGroupCreateBatchResponse(BaseModel):
total: int = Field(..., description="请求总数。", examples=[2]) total: int
success_count: int = Field(..., description="受理成功数量。", examples=[1]) success_count: int
failed_count: int = Field(..., description="受理失败数量。", examples=[1]) failed_count: int
list: List[WeComGroupCreateBatchItemResult] = Field(..., description="逐条处理结果。") list: List[WeComGroupCreateBatchItemResult]
class WeComGroupCreateStatusQueryRequest(BaseModel): class WeComGroupCreateStatusQueryRequest(BaseModel):
biz_rela_nos: List[str] = Field(..., description="要查询的业务单号列表。", examples=[["ORDER-20260523-001", "ORDER-20260523-002"]]) biz_rela_nos: List[str]
class WeComGroupCreateStatusItem(BaseModel): class WeComGroupCreateStatusItem(BaseModel):
biz_rela_no: str = Field(..., description="业务单号。") biz_rela_no: str
status: str = Field(..., description="状态:pending、success、failed。", examples=["success"]) status: str
task_id: Optional[str] = Field(default=None, description="机器人任务 ID。") task_id: Optional[str] = None
bot_id: str = Field(..., description="本地识别到的 bot_id。") bot_id: str
customer_contact_id: str = Field(..., description="本地关联的客户 contact_id;若本次请求未携带客户上下文则为空字符串。") customer_contact_id: str
customer_name: Optional[str] = Field(default=None, description="客户名称。") customer_name: Optional[str] = None
group_name: str = Field(..., description="群名称。") group_name: str
resolved_group_contact_id: Optional[str] = Field(default=None, description="反查到的群 contact_id。") resolved_group_contact_id: Optional[str] = None
resolved_group_name: Optional[str] = Field(default=None, description="反查到的群名称。") resolved_group_name: Optional[str] = None
resolved_contact_type: Optional[str] = Field(default=None, description="反查到的群 contact_type。") resolved_contact_type: Optional[str] = None
fail_reason: Optional[str] = Field(default=None, description="失败原因。") fail_reason: Optional[str] = None
member_bot_ids: List[str] = Field(default_factory=list, description="兼容旧数据保留的成员 bot_id 列表。") member_bot_ids: List[str] = Field(default_factory=list)
submit_result: Optional[dict[str, Any]] = Field(default=None, description="发起建群时机器人接口返回的原始回执。") submit_result: Optional[dict[str, Any]] = None
external_result: Optional[dict[str, Any]] = Field(default=None, description="后续通过 customers 反查得到的最终外部结果。") external_result: Optional[dict[str, Any]] = None
created_at: datetime = Field(..., description="创建时间。") created_at: datetime
updated_at: datetime = Field(..., description="更新时间。") updated_at: datetime
class WeComGroupCreateStatusQueryResponse(BaseModel): class WeComGroupCreateStatusQueryResponse(BaseModel):
total: int = Field(..., description="结果数量。", examples=[1]) total: int
list: List[WeComGroupCreateStatusItem] = Field(..., description="建群状态列表。") list: List[WeComGroupCreateStatusItem]
class WeComGroupMessagePullRequest(BaseModel): class WeComGroupMessagePullRequest(BaseModel):
bot_id: str = Field(..., description="指定查询消息的机器人 bot_id。", examples=["ABE6E30E3476E955853410C13E38C1065194F219CF554649F1C4F9C615435A82"]) bot_id: str
group_id: str = Field(..., description="指定群的 contact_id。", examples=["4BD6DE10053F765A7F161DF36A6E0031901A2DDBF0758730A19ADA8F0B6DD9F8"]) group_id: str
start_time: datetime = Field(..., description="消息开始时间。", examples=["2026-05-22T00:00:00Z"]) start_time: datetime
end_time: Optional[datetime] = Field(default=None, description="消息结束时间;为空则不限制结束时间。", examples=["2026-05-22T23:59:59Z"]) end_time: Optional[datetime] = None
order: str = Field(default="asc", pattern="^(asc|desc)$", description="消息排序方式。", examples=["asc"]) order: str = Field(default="asc", pattern="^(asc|desc)$")
page: int = Field(default=1, ge=1, description="页码。", examples=[1]) page: int = Field(default=1, ge=1)
page_size: int = Field(default=20, ge=1, le=200, description="每页条数。", examples=[20]) page_size: int = Field(default=20, ge=1, le=200)
class WeComGroupMessagePullResponse(BaseModel): class WeComGroupMessagePullResponse(BaseModel):
pulled_count: int = Field(..., description="本次从机器人接口拉取到的消息数量。", examples=[2]) pulled_count: int
dispatched: bool = Field(..., description="是否已投递到下游空白接口。", examples=[True]) dispatched: bool
payload: dict[str, Any] = Field(..., description="投递到下游空白接口的完整 payload。") payload: dict[str, Any]
class WeComNewCustomerItem(BaseModel): class WeComNewCustomerItem(BaseModel):
class MemberBotItem(BaseModel): class MemberBotItem(BaseModel):
bot_id: str = Field(..., description="成员机器人 bot_id。", examples=["RBT001"]) bot_id: str
bot_name: str = Field(..., description="成员机器人名称。", examples=["机器人A"]) bot_name: str
bot_id: str = Field(..., description="承接机器人 bot_id。", examples=["RBT001"]) bot_id: str
contact_id: str = Field(..., description="客户 contact_id。", examples=["cust_001"]) contact_id: str
customer_name: str = Field(..., description="客户名称。", examples=["张三"]) customer_name: str
position_id: Optional[int] = Field(default=None, description="关联岗位 ID。") position_id: Optional[int] = None
position_name: Optional[str] = Field(default=None, description="关联岗位名称。") position_name: Optional[str] = None
already_bound: bool = Field(..., description="是否已绑定客户群。", examples=[False]) already_bound: bool
can_create_group: bool = Field(..., description="是否可直接建群。", examples=[True]) can_create_group: bool
skip_reason: Optional[str] = Field(default=None, description="不可建群时的原因,例如 already_bound、no_members。") skip_reason: Optional[str] = None
member_bots: List["WeComNewCustomerItem.MemberBotItem"] = Field(default_factory=list, description="岗位挂载的成员机器人列表。") member_bots: List["WeComNewCustomerItem.MemberBotItem"] = Field(default_factory=list)
class WeComNewCustomerListResponse(BaseModel): class WeComNewCustomerListResponse(BaseModel):
total: int = Field(..., description="总数。", examples=[1]) total: int
list: List[WeComNewCustomerItem] = Field(..., description="新客户候选列表。") list: List[WeComNewCustomerItem]
class WeComJobConfigItem(BaseModel): class WeComJobConfigItem(BaseModel):
job_key: str = Field(..., description="任务键。新三类 job 之一。", examples=["dispatch_customer_group_messages"]) job_key: str
enabled: bool = Field(..., description="是否启用。", examples=[True]) enabled: bool
last_run_at: Optional[datetime] = Field(default=None, description="最近运行时间。") last_run_at: Optional[datetime] = None
last_status: Optional[str] = Field(default=None, description="最近运行状态。", examples=["success"]) last_status: Optional[str] = None
last_error: Optional[str] = Field(default=None, description="最近运行错误。") last_error: Optional[str] = None
class WeComJobConfigListResponse(BaseModel): class WeComJobConfigListResponse(BaseModel):
total: int = Field(..., description="总数。", examples=[3]) total: int
list: List[WeComJobConfigItem] = Field(..., description="任务配置列表。") list: List[WeComJobConfigItem]
class WeComJobToggleResponse(BaseModel): class WeComJobToggleResponse(BaseModel):
success: bool = Field(..., description="是否操作成功。", examples=[True]) success: bool
job_key: str = Field(..., description="任务键。新三类 job 之一。", examples=["sync_customer_groups"]) job_key: str
enabled: bool = Field(..., description="操作后的启用状态。", examples=[False]) enabled: bool
updated_at: datetime = Field(..., description="更新时间。", examples=["2026-05-22T10:00:00Z"]) updated_at: datetime
...@@ -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",
) )
) )
......
...@@ -22,6 +22,7 @@ from app.model.wecom_sync import ( ...@@ -22,6 +22,7 @@ from app.model.wecom_sync import (
WeComCustomerGroup, WeComCustomerGroup,
WeComGroupCreateRequest, WeComGroupCreateRequest,
WeComMessage, WeComMessage,
WeComSyncCheckpoint,
) )
from app.schema.wecom_sync import ( from app.schema.wecom_sync import (
WeComGroupCreateBatchItemResult, WeComGroupCreateBatchItemResult,
...@@ -30,13 +31,17 @@ from app.schema.wecom_sync import ( ...@@ -30,13 +31,17 @@ from app.schema.wecom_sync import (
WeComGroupCreateRequestItem, WeComGroupCreateRequestItem,
WeComNewCustomerItem, WeComNewCustomerItem,
) )
from app.service.wecom_sync_service import WeComSyncClient, WeComSyncService from app.service.wecom_sync_service import WeComSyncClient, WeComSyncService, _parse_dt
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
PENDING_REQUEST_TIMEOUT = timedelta(hours=1) PENDING_REQUEST_TIMEOUT = timedelta(minutes=10)
INVALID_GROUP_STATUSES = {"failed", "timeout", "invalid"} INVALID_GROUP_STATUSES = {"failed", "timeout", "invalid"}
WECOM_CUSTOMER_CONTACT_TYPE = "ww_customer" WECOM_CUSTOMER_CONTACT_TYPE = "ww_customer"
GROUP_CREATE_TIMEOUT_WEBHOOK_URL = (
"https://qyapi.weixin.qq.com/cgi-bin/webhook/send"
"?key=d741ee77-b177-4f92-b478-e5357cadf990"
)
def _utcnow() -> datetime: def _utcnow() -> datetime:
...@@ -64,6 +69,27 @@ class NoopGroupMessageBatchDispatcher: ...@@ -64,6 +69,27 @@ class NoopGroupMessageBatchDispatcher:
return None return None
class WeComWebhookNotifier:
def __init__(self, webhook_url: str = GROUP_CREATE_TIMEOUT_WEBHOOK_URL, timeout_seconds: float = 10.0) -> None:
self.webhook_url = webhook_url
self.timeout_seconds = timeout_seconds
def send_text(self, content: str) -> None:
payload = {
"msgtype": "text",
"text": {
"content": content,
},
}
with httpx.Client(timeout=self.timeout_seconds) as client:
response = client.post(
self.webhook_url,
json=payload,
headers={"Content-Type": "application/json"},
)
response.raise_for_status()
class HttpChatCompletionsBatchDispatcher: class HttpChatCompletionsBatchDispatcher:
def __init__(self, base_url: str | None = None, timeout_seconds: float = 30.0) -> None: def __init__(self, base_url: str | None = None, timeout_seconds: float = 30.0) -> None:
settings = ConfigLoader().load_settings() settings = ConfigLoader().load_settings()
...@@ -158,12 +184,14 @@ class WeComCustomerGroupOrchestrationService: ...@@ -158,12 +184,14 @@ class WeComCustomerGroupOrchestrationService:
client: WeComSyncClient, client: WeComSyncClient,
sync_service: WeComSyncService, sync_service: WeComSyncService,
batch_dispatcher: Any | None = None, batch_dispatcher: Any | None = None,
webhook_notifier: WeComWebhookNotifier | None = None,
page_size: int = 100, page_size: int = 100,
) -> None: ) -> None:
self.db = db self.db = db
self.client = client self.client = client
self.sync_service = sync_service self.sync_service = sync_service
self.batch_dispatcher = batch_dispatcher or NoopGroupMessageBatchDispatcher() self.batch_dispatcher = batch_dispatcher or NoopGroupMessageBatchDispatcher()
self.webhook_notifier = webhook_notifier or WeComWebhookNotifier()
self.page_size = page_size self.page_size = page_size
def sync_customer_groups(self, *, bot_ids: Iterable[str] | None = None) -> dict[str, int]: def sync_customer_groups(self, *, bot_ids: Iterable[str] | None = None) -> dict[str, int]:
...@@ -246,6 +274,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -246,6 +274,7 @@ class WeComCustomerGroupOrchestrationService:
if self._is_pending_request_timed_out(request): if self._is_pending_request_timed_out(request):
request.status = "failed" request.status = "failed"
request.fail_reason = "timeout" request.fail_reason = "timeout"
self._notify_group_create_timeout(request)
processed += 1 processed += 1
continue continue
...@@ -262,12 +291,13 @@ class WeComCustomerGroupOrchestrationService: ...@@ -262,12 +291,13 @@ class WeComCustomerGroupOrchestrationService:
def create_new_requests(self, *, bot_ids: Iterable[str] | None = None) -> int: def create_new_requests(self, *, bot_ids: Iterable[str] | None = None) -> int:
created = 0 created = 0
for item in self.scan_new_customers(bot_ids=bot_ids): candidates = self._collect_group_create_candidates(bot_ids=bot_ids)
for item in candidates:
if not item.can_create_group: if not item.can_create_group:
continue continue
if self._has_valid_customer_group(item.contact_id): if not self._should_create_customer_group(bot_id=item.bot_id, customer_contact_id=item.contact_id):
continue continue
if self._has_pending_group_create_request(item.contact_id): if self._has_pending_group_create_request(bot_id=item.bot_id, customer_contact_id=item.contact_id):
continue continue
self._submit_group_create_request_for_customer(item) self._submit_group_create_request_for_customer(item)
created += 1 created += 1
...@@ -276,6 +306,26 @@ class WeComCustomerGroupOrchestrationService: ...@@ -276,6 +306,26 @@ class WeComCustomerGroupOrchestrationService:
self.db.commit() self.db.commit()
return created return created
def _collect_group_create_candidates(self, *, bot_ids: Iterable[str] | None = None) -> list[WeComNewCustomerItem]:
items: list[WeComNewCustomerItem] = []
seen: set[tuple[str, str]] = set()
for item in self._scan_invalid_customer_groups(bot_ids=bot_ids):
key = (item.bot_id, item.contact_id)
if key in seen:
continue
seen.add(key)
items.append(item)
for item in self.scan_new_customers(bot_ids=bot_ids):
key = (item.bot_id, item.contact_id)
if key in seen:
continue
seen.add(key)
items.append(item)
return items
def poll_pending_group_create_requests(self) -> int: def poll_pending_group_create_requests(self) -> int:
return self.resolve_pending_requests() return self.resolve_pending_requests()
...@@ -644,6 +694,27 @@ class WeComCustomerGroupOrchestrationService: ...@@ -644,6 +694,27 @@ class WeComCustomerGroupOrchestrationService:
) )
) )
def _notify_group_create_timeout(self, request: WeComGroupCreateRequest) -> None:
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == request.bot_id).first()
bot_name = str((bot.bot_name if bot and bot.bot_name else request.bot_id) or "")
customer_name = str(request.customer_name or "")
content = f"{bot_name} 拉取 {customer_name} 建群失败,请关注!!"
try:
self.webhook_notifier.send_text(content)
logger.info(
format_job_log(
"建群超时告警已发送: bot_id=%s customer_name=%s"
% (request.bot_id, customer_name)
)
)
except Exception:
logger.exception(
format_job_log(
"建群超时告警发送失败: bot_id=%s customer_name=%s"
% (request.bot_id, customer_name)
)
)
def _scan_new_customers_for_bot(self, *, bot_id: str) -> list[WeComNewCustomerItem]: def _scan_new_customers_for_bot(self, *, bot_id: str) -> list[WeComNewCustomerItem]:
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == bot_id).first() bot = self.db.query(WeComBot).filter(WeComBot.bot_id == bot_id).first()
if bot is None: if bot is None:
...@@ -662,11 +733,14 @@ class WeComCustomerGroupOrchestrationService: ...@@ -662,11 +733,14 @@ class WeComCustomerGroupOrchestrationService:
resolved_contact_type = WECOM_CUSTOMER_CONTACT_TYPE resolved_contact_type = WECOM_CUSTOMER_CONTACT_TYPE
candidates: list[WeComNewCustomerItem] = [] candidates: list[WeComNewCustomerItem] = []
checkpoint = self._get_customer_checkpoint(bot_id=bot.bot_id)
latest_time = checkpoint.last_sync_time if checkpoint else None
latest_id = checkpoint.last_external_id if checkpoint else None
page = 1 page = 1
while True: while True:
payload = self.client.list_customers( payload = self.client.list_customers(
bot_id=bot.bot_id, bot_id=bot.bot_id,
start_time=None, start_time=latest_time,
end_time=None, end_time=None,
page=page, page=page,
page_size=self.page_size, page_size=self.page_size,
...@@ -680,7 +754,11 @@ class WeComCustomerGroupOrchestrationService: ...@@ -680,7 +754,11 @@ class WeComCustomerGroupOrchestrationService:
contact_id = str(item.get("contact_id") or "") contact_id = str(item.get("contact_id") or "")
if not contact_id: if not contact_id:
continue continue
if self._has_valid_customer_group(contact_id): candidate_time = _parse_dt(item.get("updated_at")) or _parse_dt(item.get("created_at"))
if self.sync_service._is_checkpoint_item_already_consumed(checkpoint, candidate_time, contact_id):
continue
if not self._should_create_customer_group(bot_id=bot.bot_id, customer_contact_id=contact_id):
latest_time, latest_id = self.sync_service._max_key(latest_time, latest_id, candidate_time, contact_id)
continue continue
member_bots = self._resolve_position_member_bots(position_id=position.id) member_bots = self._resolve_position_member_bots(position_id=position.id)
customer_name = str(item.get("contact_name") or item.get("display_name") or "") customer_name = str(item.get("contact_name") or item.get("display_name") or "")
...@@ -713,6 +791,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -713,6 +791,7 @@ class WeComCustomerGroupOrchestrationService:
member_bots=member_bots, member_bots=member_bots,
) )
) )
latest_time, latest_id = self.sync_service._max_key(latest_time, latest_id, candidate_time, contact_id)
meta = payload.get("meta") or {} meta = payload.get("meta") or {}
total = meta.get("total") total = meta.get("total")
...@@ -721,8 +800,70 @@ class WeComCustomerGroupOrchestrationService: ...@@ -721,8 +800,70 @@ class WeComCustomerGroupOrchestrationService:
break break
page += 1 page += 1
self._complete_customer_checkpoint(bot_id=bot.bot_id, last_sync_time=latest_time, last_external_id=latest_id)
return candidates return candidates
def _scan_invalid_customer_groups(self, *, bot_ids: Iterable[str] | None = None) -> list[WeComNewCustomerItem]:
query = (
self.db.query(WeComCustomerGroup)
.filter(WeComCustomerGroup.group_status == "invalid")
.order_by(WeComCustomerGroup.id.asc())
)
resolved_bot_ids = [str(item).strip() for item in (bot_ids or []) if str(item).strip()]
if resolved_bot_ids:
query = query.filter(WeComCustomerGroup.bot_id.in_(resolved_bot_ids))
items: list[WeComNewCustomerItem] = []
seen: set[tuple[str, str]] = set()
for group in query.all():
bot_id = str(group.bot_id or "").strip()
contact_id = str(group.customer_contact_id or "").strip()
if not bot_id or not contact_id:
continue
key = (bot_id, contact_id)
if key in seen:
continue
seen.add(key)
bot, qrcode, position = self._resolve_bot_binding_context(bot_id)
if bot is None or qrcode is None or position is None:
continue
member_bots = self._resolve_position_member_bots(position_id=position.id)
customer_name = str(group.customer_name or "").strip()
can_create_group = bool(member_bots)
skip_reason = None if can_create_group else "no_members"
items.append(
WeComNewCustomerItem(
bot_id=bot.bot_id,
contact_id=contact_id,
customer_name=customer_name,
position_id=position.id,
position_name=position.name,
already_bound=False,
can_create_group=can_create_group,
skip_reason=skip_reason,
member_bots=member_bots,
)
)
return items
def _get_customer_checkpoint(self, *, bot_id: str) -> WeComSyncCheckpoint | None:
return self.sync_service._get_effective_checkpoint("customers", f"bot:{bot_id}")
def _complete_customer_checkpoint(
self,
*,
bot_id: str,
last_sync_time: datetime | None,
last_external_id: str | None,
) -> None:
self.sync_service._complete_checkpoint(
"customers",
f"bot:{bot_id}",
last_sync_time,
last_external_id,
)
def _resolve_bot_binding_context(self, bot_id: str) -> tuple[WeComBot | None, QrcodeChannel | None, PositionTag | None]: def _resolve_bot_binding_context(self, bot_id: str) -> tuple[WeComBot | None, QrcodeChannel | None, PositionTag | None]:
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == bot_id).first() bot = self.db.query(WeComBot).filter(WeComBot.bot_id == bot_id).first()
if bot is None: if bot is None:
...@@ -764,6 +905,24 @@ class WeComCustomerGroupOrchestrationService: ...@@ -764,6 +905,24 @@ class WeComCustomerGroupOrchestrationService:
return None return None
def _get_latest_customer_group(self, *, bot_id: str, customer_contact_id: str) -> WeComCustomerGroup | None:
return (
self.db.query(WeComCustomerGroup)
.filter(
WeComCustomerGroup.bot_id == bot_id,
WeComCustomerGroup.customer_contact_id == customer_contact_id,
WeComCustomerGroup.is_deleted == False,
)
.order_by(WeComCustomerGroup.id.desc())
.first()
)
def _should_create_customer_group(self, *, bot_id: str, customer_contact_id: str) -> bool:
record = self._get_latest_customer_group(bot_id=bot_id, customer_contact_id=customer_contact_id)
if record is None:
return True
return record.group_status == "invalid"
def _has_valid_customer_group(self, customer_contact_id: str) -> bool: def _has_valid_customer_group(self, customer_contact_id: str) -> bool:
record = ( record = (
self.db.query(WeComCustomerGroup) self.db.query(WeComCustomerGroup)
...@@ -778,10 +937,11 @@ class WeComCustomerGroupOrchestrationService: ...@@ -778,10 +937,11 @@ class WeComCustomerGroupOrchestrationService:
return False return False
return record.group_status not in INVALID_GROUP_STATUSES return record.group_status not in INVALID_GROUP_STATUSES
def _has_pending_group_create_request(self, customer_contact_id: str) -> bool: def _has_pending_group_create_request(self, *, bot_id: str, customer_contact_id: str) -> bool:
return ( return (
self.db.query(WeComGroupCreateRequest) self.db.query(WeComGroupCreateRequest)
.filter( .filter(
WeComGroupCreateRequest.bot_id == bot_id,
WeComGroupCreateRequest.customer_contact_id == customer_contact_id, WeComGroupCreateRequest.customer_contact_id == customer_contact_id,
WeComGroupCreateRequest.status == "pending", WeComGroupCreateRequest.status == "pending",
) )
......
...@@ -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
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
CREATE TABLE IF NOT EXISTS ai_agents (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
code VARCHAR(100) NOT NULL,
managed_user_id INTEGER NULL,
description VARCHAR(500) NULL,
status ENUM('enable','disable') NULL,
is_steward BOOLEAN NOT NULL DEFAULT 0,
version INTEGER NOT NULL DEFAULT 1,
is_deleted BOOLEAN NOT NULL DEFAULT 0,
deleted_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY ix_ai_agents_code (code),
KEY ix_ai_agents_id (id),
KEY ix_ai_agents_managed_user_id (managed_user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS skills (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
skill_code VARCHAR(100) NOT NULL,
skill_name VARCHAR(100) NOT NULL,
description VARCHAR(500) NULL,
doc_markdown TEXT NULL,
priority INTEGER NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY ix_skills_skill_code (skill_code),
KEY ix_skills_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS position_tags (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20) NOT NULL,
code VARCHAR(100) NOT NULL,
description VARCHAR(100) NULL,
user_ids JSON NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY ix_position_tags_code (code),
KEY ix_position_tags_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS ai_agent_positions (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
agent_id INTEGER NOT NULL,
position_id INTEGER NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uk_agent_position UNIQUE (agent_id, position_id),
CONSTRAINT fk_ai_agent_positions_agent FOREIGN KEY (agent_id) REFERENCES ai_agents (id) ON DELETE CASCADE,
KEY ix_ai_agent_positions_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS ai_agent_skills (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
agent_id INTEGER NOT NULL,
skill_code VARCHAR(100) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uk_agent_skill UNIQUE (agent_id, skill_code),
CONSTRAINT fk_ai_agent_skills_agent FOREIGN KEY (agent_id) REFERENCES ai_agents (id) ON DELETE CASCADE,
KEY ix_ai_agent_skills_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS position_tag_users (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
position_tag_id INTEGER NOT NULL,
wecom_bot_id INTEGER NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uk_position_tag_user UNIQUE (position_tag_id, wecom_bot_id),
CONSTRAINT fk_position_tag_users_position_tag FOREIGN KEY (position_tag_id) REFERENCES position_tags (id) ON DELETE CASCADE,
KEY ix_position_tag_users_id (id),
KEY ix_position_tag_users_position_tag_id (position_tag_id),
KEY ix_position_tag_users_wecom_bot_id (wecom_bot_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS qrcode_channels (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
qrcode_name VARCHAR(50) NULL,
position_id INTEGER NOT NULL,
wecom_bot_id INTEGER NOT NULL,
employee_id VARCHAR(100) NOT NULL,
employee_name VARCHAR(100) NOT NULL DEFAULT '',
qrcode_url VARCHAR(500) NULL,
agent_ids JSON NULL,
remark VARCHAR(200) NULL,
welcome_message VARCHAR(500) NULL,
status VARCHAR(20) NOT NULL DEFAULT 'enable',
disable_reason VARCHAR(200) NULL,
created_by VARCHAR(64) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CONSTRAINT uk_qrcode_position_id UNIQUE (position_id),
CONSTRAINT uk_qrcode_wecom_bot_id UNIQUE (wecom_bot_id),
KEY ix_qrcode_channels_id (id),
KEY ix_qrcode_channels_position_id (position_id),
KEY ix_qrcode_channels_wecom_bot_id (wecom_bot_id),
KEY ix_qrcode_channels_employee_id (employee_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS wecom_employee_qrcodes (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
employee_id VARCHAR(100) NOT NULL,
qrcode_url VARCHAR(500) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY ix_wecom_employee_qrcodes_employee_id (employee_id),
KEY uk_wecom_employee_qrcodes_employee_id (employee_id),
KEY ix_wecom_employee_qrcodes_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS official_tabs (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
tab_name VARCHAR(100) NOT NULL,
position_id INTEGER NULL,
qrcode_id INTEGER NULL,
display_status VARCHAR(20) NOT NULL DEFAULT 'enable',
sort_order INTEGER NOT NULL DEFAULT 0,
main_title VARCHAR(200) NULL,
sub_title VARCHAR(500) NULL,
created_by VARCHAR(64) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
KEY ix_official_tabs_id (id),
KEY ix_official_tabs_position_id (position_id),
KEY ix_official_tabs_qrcode_id (qrcode_id),
KEY ix_official_tabs_display_status (display_status),
KEY ix_official_tabs_sort_order (sort_order),
KEY ix_official_tabs_deleted_at (deleted_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS official_site_agent_display (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
tab_id INTEGER NOT NULL,
agent_id INTEGER NOT NULL,
agent_name VARCHAR(50) NOT NULL DEFAULT '',
status VARCHAR(20) NOT NULL DEFAULT 'enable',
summary VARCHAR(500) NULL,
icon_url VARCHAR(500) NULL,
media_url VARCHAR(500) NULL,
media_type VARCHAR(10) NULL,
speech_title VARCHAR(100) NULL,
speech_content VARCHAR(200) NULL,
display_status VARCHAR(20) NOT NULL DEFAULT 'enable',
sort_order INTEGER NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY ix_official_site_agent_display_id (id),
KEY ix_official_site_agent_display_tab_id (tab_id),
KEY ix_official_site_agent_display_agent_id (agent_id),
KEY ix_official_site_agent_display_status (status),
KEY ix_official_site_agent_display_display_status (display_status),
KEY ix_official_site_agent_display_sort_order (sort_order)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS official_site_methodology (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
display_status VARCHAR(20) NOT NULL DEFAULT 'enable',
main_title VARCHAR(100) NOT NULL,
sub_title VARCHAR(200) NOT NULL DEFAULT '',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY ix_official_site_methodology_id (id),
KEY ix_official_site_methodology_display_status (display_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS official_site_methodology_steps (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
methodology_id INTEGER NOT NULL,
step_icon VARCHAR(500) NULL,
step_name VARCHAR(100) NOT NULL,
step_order INTEGER NOT NULL,
step_image VARCHAR(500) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY ix_official_site_methodology_steps_id (id),
KEY ix_official_site_methodology_steps_methodology_id (methodology_id),
KEY ix_official_site_methodology_steps_step_order (step_order)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS wecom_bots (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
channel VARCHAR(64) NOT NULL,
bot_id VARCHAR(128) NOT NULL,
bot_code VARCHAR(191) NOT NULL,
bot_name VARCHAR(255) NOT NULL,
corp_name VARCHAR(255) NULL,
online BOOLEAN NULL,
status VARCHAR(64) NULL,
config JSON NULL,
queue_count INTEGER NULL,
pending_count INTEGER NULL,
last_active DATETIME NULL,
last_fail DATETIME NULL,
external_created_at DATETIME NULL,
external_updated_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY ix_wecom_bots_bot_code (bot_code),
KEY ix_wecom_bots_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS wecom_messages (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
bot_code VARCHAR(191) NOT NULL,
channel VARCHAR(64) NOT NULL,
bot_id VARCHAR(128) NOT NULL,
msg_id VARCHAR(191) NOT NULL,
msg_time DATETIME NOT NULL,
msg_type VARCHAR(64) NULL,
msg_content TEXT NULL,
sender_id VARCHAR(191) NULL,
sender_name VARCHAR(255) NULL,
contact_id VARCHAR(191) NULL,
customer_group_id INTEGER NULL,
session_title VARCHAR(255) NULL,
bot_send BOOLEAN NOT NULL DEFAULT 0,
payload JSON NOT NULL,
dispatch_status VARCHAR(32) NULL,
dispatch_error TEXT NULL,
dispatch_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CONSTRAINT uk_wecom_message_bot_msg UNIQUE (bot_code, msg_id),
KEY ix_wecom_messages_id (id),
KEY ix_wecom_messages_bot_code (bot_code),
KEY ix_wecom_messages_msg_time (msg_time),
KEY ix_wecom_messages_customer_group_id (customer_group_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS wecom_sync_checkpoints (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
resource_type VARCHAR(32) NOT NULL,
scope_key VARCHAR(191) NOT NULL,
last_sync_time DATETIME NULL,
last_external_id VARCHAR(191) NULL,
last_sync_cursor VARCHAR(191) NULL,
last_status VARCHAR(32) NULL,
last_error TEXT NULL,
last_started_at DATETIME NULL,
last_finished_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CONSTRAINT uk_wecom_sync_checkpoint_scope UNIQUE (resource_type, scope_key),
KEY ix_wecom_sync_checkpoints_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS wecom_customer_groups (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
customer_contact_id VARCHAR(191) NOT NULL,
customer_name VARCHAR(255) NULL,
bot_id VARCHAR(128) NOT NULL,
bot_code VARCHAR(191) NOT NULL,
group_id VARCHAR(191) NULL,
group_name VARCHAR(255) NULL,
group_status VARCHAR(32) NOT NULL DEFAULT 'pending',
group_create_request_id INTEGER NULL,
member_bot_ids JSON NOT NULL,
is_deleted BOOLEAN NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CONSTRAINT uk_wecom_customer_group_customer UNIQUE (customer_contact_id),
KEY ix_wecom_customer_groups_id (id),
KEY ix_wecom_customer_groups_customer_contact_id (customer_contact_id),
KEY ix_wecom_customer_groups_bot_id (bot_id),
KEY ix_wecom_customer_groups_bot_code (bot_code),
KEY ix_wecom_customer_groups_group_id (group_id),
KEY ix_wecom_customer_groups_group_status (group_status),
KEY ix_wecom_customer_groups_group_create_request_id (group_create_request_id),
KEY ix_wecom_customer_groups_is_deleted (is_deleted)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS wecom_group_create_requests (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
biz_rela_no VARCHAR(191) NOT NULL,
bot_id VARCHAR(128) NOT NULL,
bot_code VARCHAR(191) NOT NULL,
customer_contact_id VARCHAR(191) NOT NULL,
customer_name VARCHAR(255) NULL,
qrcode_id INTEGER NOT NULL,
qrcode_name VARCHAR(255) NULL,
channel_code VARCHAR(100) NOT NULL,
position_id INTEGER NOT NULL,
position_code VARCHAR(100) NOT NULL,
position_name VARCHAR(255) NOT NULL,
group_name VARCHAR(255) NOT NULL,
member_bot_ids JSON NOT NULL,
member_snapshot JSON NULL,
request_payload JSON NULL,
submit_result JSON NULL,
task_id VARCHAR(191) NULL,
status VARCHAR(32) NOT NULL DEFAULT 'pending',
fail_reason TEXT NULL,
resolved_group_contact_id VARCHAR(191) NULL,
resolved_group_name VARCHAR(255) NULL,
resolved_contact_type VARCHAR(64) NULL,
external_result JSON NULL,
resolved_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY ix_wecom_group_create_requests_biz_rela_no (biz_rela_no),
KEY ix_wecom_group_create_requests_id (id),
KEY ix_wecom_group_create_requests_bot_id (bot_id),
KEY ix_wecom_group_create_requests_bot_code (bot_code),
KEY ix_wecom_group_create_requests_customer_contact_id (customer_contact_id),
KEY ix_wecom_group_create_requests_qrcode_id (qrcode_id),
KEY ix_wecom_group_create_requests_channel_code (channel_code),
KEY ix_wecom_group_create_requests_position_id (position_id),
KEY ix_wecom_group_create_requests_position_code (position_code),
KEY ix_wecom_group_create_requests_status (status),
KEY ix_wecom_group_create_requests_task_id (task_id),
KEY ix_wecom_group_create_requests_resolved_group_contact_id (resolved_group_contact_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS wecom_job_configs (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
job_key VARCHAR(64) NOT NULL,
enabled BOOLEAN NOT NULL DEFAULT 1,
last_run_at DATETIME NULL,
last_status VARCHAR(32) NULL,
last_error TEXT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY ix_wecom_job_configs_job_key (job_key),
KEY ix_wecom_job_configs_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS conversation_logs (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
session_id VARCHAR(64) NOT NULL,
user_id VARCHAR(64) NOT NULL,
agent_id INTEGER NOT NULL,
agent_name VARCHAR(50) NULL,
query TEXT NOT NULL,
response TEXT NULL,
intent VARCHAR(128) NULL,
entities JSON NULL,
processing_time_ms INTEGER NULL,
has_error BOOLEAN NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
KEY ix_conversation_logs_id (id),
KEY ix_conversation_logs_user_id (user_id),
KEY ix_conversation_logs_agent_id (agent_id),
KEY ix_conversation_logs_intent (intent),
KEY ix_conversation_logs_has_error (has_error),
KEY ix_conversation_logs_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS analytics_events (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
event_type VARCHAR(64) NOT NULL,
event_data JSON NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
KEY ix_analytics_events_id (id),
KEY ix_analytics_events_event_type (event_type),
KEY ix_analytics_events_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS analytics_statistics (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
stat_date DATE NOT NULL,
dimension VARCHAR(32) NOT NULL,
dimension_value VARCHAR(128) NOT NULL,
total_agent_calls INTEGER NOT NULL DEFAULT 0,
total_sessions INTEGER NOT NULL DEFAULT 0,
avg_session_turns NUMERIC(5,2) NOT NULL DEFAULT 0.00,
intent_distribution JSON NULL,
agent_call_ranking JSON NULL,
daily_trend JSON NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY ix_analytics_statistics_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS page_views (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
page_type VARCHAR(64) NOT NULL,
user_id VARCHAR(64) NULL,
session_id VARCHAR(64) NULL,
device_type VARCHAR(32) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
KEY ix_page_views_id (id),
KEY ix_page_views_page_type (page_type),
KEY ix_page_views_user_id (user_id),
KEY ix_page_views_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS scan_events (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
qrcode_id INTEGER NULL,
channel_code VARCHAR(128) NULL,
customer_user_id VARCHAR(64) NULL,
position_code VARCHAR(64) NULL,
employee_id VARCHAR(64) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
KEY ix_scan_events_id (id),
KEY ix_scan_events_qrcode_id (qrcode_id),
KEY ix_scan_events_channel_code (channel_code),
KEY ix_scan_events_customer_user_id (customer_user_id),
KEY ix_scan_events_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS group_join_events (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
group_id VARCHAR(64) NULL,
customer_user_id VARCHAR(64) NULL,
employee_count INTEGER NULL,
agent_count INTEGER NULL,
channel_code VARCHAR(128) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
KEY ix_group_join_events_id (id),
KEY ix_group_join_events_group_id (group_id),
KEY ix_group_join_events_customer_user_id (customer_user_id),
KEY ix_group_join_events_channel_code (channel_code),
KEY ix_group_join_events_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
SET FOREIGN_KEY_CHECKS = 1;
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
CREATE TABLE IF NOT EXISTS ai_agents (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
code VARCHAR(100) NOT NULL,
managed_user_id INTEGER NULL,
description VARCHAR(500) NULL,
status ENUM('enable','disable') NULL,
is_steward BOOLEAN NOT NULL DEFAULT 0,
version INTEGER NOT NULL DEFAULT 1,
is_deleted BOOLEAN NOT NULL DEFAULT 0,
deleted_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY ix_ai_agents_code (code),
KEY ix_ai_agents_id (id),
KEY ix_ai_agents_managed_user_id (managed_user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS skills (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
skill_code VARCHAR(100) NOT NULL,
skill_name VARCHAR(100) NOT NULL,
description VARCHAR(500) NULL,
doc_markdown TEXT NULL,
priority INTEGER NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY ix_skills_skill_code (skill_code),
KEY ix_skills_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS position_tags (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20) NOT NULL,
code VARCHAR(100) NOT NULL,
description VARCHAR(100) NULL,
user_ids JSON NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY ix_position_tags_code (code),
KEY ix_position_tags_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS ai_agent_positions (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
agent_id INTEGER NOT NULL,
position_id INTEGER NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uk_agent_position UNIQUE (agent_id, position_id),
KEY ix_ai_agent_positions_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS ai_agent_skills (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
agent_id INTEGER NOT NULL,
skill_code VARCHAR(100) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uk_agent_skill UNIQUE (agent_id, skill_code),
KEY ix_ai_agent_skills_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS position_tag_users (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
position_tag_id INTEGER NOT NULL,
wecom_bot_id INTEGER NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uk_position_tag_user UNIQUE (position_tag_id, wecom_bot_id),
KEY ix_position_tag_users_id (id),
KEY ix_position_tag_users_position_tag_id (position_tag_id),
KEY ix_position_tag_users_wecom_bot_id (wecom_bot_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS qrcode_channels (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
qrcode_name VARCHAR(50) NULL,
position_id INTEGER NOT NULL,
wecom_bot_id INTEGER NOT NULL,
employee_id VARCHAR(100) NOT NULL,
employee_name VARCHAR(100) NOT NULL DEFAULT '',
qrcode_url VARCHAR(500) NULL,
agent_ids JSON NULL,
remark VARCHAR(200) NULL,
welcome_message VARCHAR(500) NULL,
status VARCHAR(20) NOT NULL DEFAULT 'enable',
disable_reason VARCHAR(200) NULL,
created_by VARCHAR(64) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CONSTRAINT uk_qrcode_position_id UNIQUE (position_id),
CONSTRAINT uk_qrcode_wecom_bot_id UNIQUE (wecom_bot_id),
KEY ix_qrcode_channels_id (id),
KEY ix_qrcode_channels_position_id (position_id),
KEY ix_qrcode_channels_wecom_bot_id (wecom_bot_id),
KEY ix_qrcode_channels_employee_id (employee_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS wecom_employee_qrcodes (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
employee_id VARCHAR(100) NOT NULL,
qrcode_url VARCHAR(500) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY ix_wecom_employee_qrcodes_employee_id (employee_id),
KEY uk_wecom_employee_qrcodes_employee_id (employee_id),
KEY ix_wecom_employee_qrcodes_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS official_tabs (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
tab_name VARCHAR(100) NOT NULL,
position_id INTEGER NULL,
qrcode_id INTEGER NULL,
display_status VARCHAR(20) NOT NULL DEFAULT 'enable',
sort_order INTEGER NOT NULL DEFAULT 0,
main_title VARCHAR(200) NULL,
sub_title VARCHAR(500) NULL,
created_by VARCHAR(64) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
KEY ix_official_tabs_id (id),
KEY ix_official_tabs_position_id (position_id),
KEY ix_official_tabs_qrcode_id (qrcode_id),
KEY ix_official_tabs_display_status (display_status),
KEY ix_official_tabs_sort_order (sort_order),
KEY ix_official_tabs_deleted_at (deleted_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS official_site_agent_display (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
tab_id INTEGER NOT NULL,
agent_id INTEGER NOT NULL,
agent_name VARCHAR(50) NOT NULL DEFAULT '',
status VARCHAR(20) NOT NULL DEFAULT 'enable',
summary VARCHAR(500) NULL,
icon_url VARCHAR(500) NULL,
media_url VARCHAR(500) NULL,
media_type VARCHAR(10) NULL,
speech_title VARCHAR(100) NULL,
speech_content VARCHAR(200) NULL,
display_status VARCHAR(20) NOT NULL DEFAULT 'enable',
sort_order INTEGER NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY ix_official_site_agent_display_id (id),
KEY ix_official_site_agent_display_tab_id (tab_id),
KEY ix_official_site_agent_display_agent_id (agent_id),
KEY ix_official_site_agent_display_status (status),
KEY ix_official_site_agent_display_display_status (display_status),
KEY ix_official_site_agent_display_sort_order (sort_order)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS official_site_methodology (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
display_status VARCHAR(20) NOT NULL DEFAULT 'enable',
main_title VARCHAR(100) NOT NULL,
sub_title VARCHAR(200) NOT NULL DEFAULT '',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY ix_official_site_methodology_id (id),
KEY ix_official_site_methodology_display_status (display_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS official_site_methodology_steps (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
methodology_id INTEGER NOT NULL,
step_icon VARCHAR(500) NULL,
step_name VARCHAR(100) NOT NULL,
step_order INTEGER NOT NULL,
step_image VARCHAR(500) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY ix_official_site_methodology_steps_id (id),
KEY ix_official_site_methodology_steps_methodology_id (methodology_id),
KEY ix_official_site_methodology_steps_step_order (step_order)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS wecom_bots (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
channel VARCHAR(64) NOT NULL,
bot_id VARCHAR(128) NOT NULL,
bot_code VARCHAR(191) NOT NULL,
bot_name VARCHAR(255) NOT NULL,
corp_name VARCHAR(255) NULL,
online BOOLEAN NULL,
status VARCHAR(64) NULL,
config JSON NULL,
queue_count INTEGER NULL,
pending_count INTEGER NULL,
last_active DATETIME NULL,
last_fail DATETIME NULL,
external_created_at DATETIME NULL,
external_updated_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY ix_wecom_bots_bot_code (bot_code),
KEY ix_wecom_bots_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS wecom_messages (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
bot_code VARCHAR(191) NOT NULL,
channel VARCHAR(64) NOT NULL,
bot_id VARCHAR(128) NOT NULL,
msg_id VARCHAR(191) NOT NULL,
msg_time DATETIME NOT NULL,
msg_type VARCHAR(64) NULL,
msg_content TEXT NULL,
sender_id VARCHAR(191) NULL,
sender_name VARCHAR(255) NULL,
contact_id VARCHAR(191) NULL,
customer_group_id INTEGER NULL,
session_title VARCHAR(255) NULL,
bot_send BOOLEAN NOT NULL DEFAULT 0,
payload JSON NOT NULL,
dispatch_status VARCHAR(32) NULL,
dispatch_error TEXT NULL,
dispatch_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CONSTRAINT uk_wecom_message_bot_msg UNIQUE (bot_code, msg_id),
KEY ix_wecom_messages_id (id),
KEY ix_wecom_messages_bot_code (bot_code),
KEY ix_wecom_messages_msg_time (msg_time),
KEY ix_wecom_messages_customer_group_id (customer_group_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS wecom_sync_checkpoints (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
resource_type VARCHAR(32) NOT NULL,
scope_key VARCHAR(191) NOT NULL,
last_sync_time DATETIME NULL,
last_external_id VARCHAR(191) NULL,
last_sync_cursor VARCHAR(191) NULL,
last_status VARCHAR(32) NULL,
last_error TEXT NULL,
last_started_at DATETIME NULL,
last_finished_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CONSTRAINT uk_wecom_sync_checkpoint_scope UNIQUE (resource_type, scope_key),
KEY ix_wecom_sync_checkpoints_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS wecom_customer_groups (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
customer_contact_id VARCHAR(191) NOT NULL,
customer_name VARCHAR(255) NULL,
bot_id VARCHAR(128) NOT NULL,
bot_code VARCHAR(191) NOT NULL,
group_id VARCHAR(191) NULL,
group_name VARCHAR(255) NULL,
group_status VARCHAR(32) NOT NULL DEFAULT 'pending',
group_create_request_id INTEGER NULL,
member_bot_ids JSON NOT NULL,
is_deleted BOOLEAN NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CONSTRAINT uk_wecom_customer_group_customer UNIQUE (customer_contact_id),
KEY ix_wecom_customer_groups_id (id),
KEY ix_wecom_customer_groups_customer_contact_id (customer_contact_id),
KEY ix_wecom_customer_groups_bot_id (bot_id),
KEY ix_wecom_customer_groups_bot_code (bot_code),
KEY ix_wecom_customer_groups_group_id (group_id),
KEY ix_wecom_customer_groups_group_status (group_status),
KEY ix_wecom_customer_groups_group_create_request_id (group_create_request_id),
KEY ix_wecom_customer_groups_is_deleted (is_deleted)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS wecom_group_create_requests (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
biz_rela_no VARCHAR(191) NOT NULL,
bot_id VARCHAR(128) NOT NULL,
bot_code VARCHAR(191) NOT NULL,
customer_contact_id VARCHAR(191) NOT NULL,
customer_name VARCHAR(255) NULL,
qrcode_id INTEGER NOT NULL,
qrcode_name VARCHAR(255) NULL,
channel_code VARCHAR(100) NOT NULL,
position_id INTEGER NOT NULL,
position_code VARCHAR(100) NOT NULL,
position_name VARCHAR(255) NOT NULL,
group_name VARCHAR(255) NOT NULL,
member_bot_ids JSON NOT NULL,
member_snapshot JSON NULL,
request_payload JSON NULL,
submit_result JSON NULL,
task_id VARCHAR(191) NULL,
status VARCHAR(32) NOT NULL DEFAULT 'pending',
fail_reason TEXT NULL,
resolved_group_contact_id VARCHAR(191) NULL,
resolved_group_name VARCHAR(255) NULL,
resolved_contact_type VARCHAR(64) NULL,
external_result JSON NULL,
resolved_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY ix_wecom_group_create_requests_biz_rela_no (biz_rela_no),
KEY ix_wecom_group_create_requests_id (id),
KEY ix_wecom_group_create_requests_bot_id (bot_id),
KEY ix_wecom_group_create_requests_bot_code (bot_code),
KEY ix_wecom_group_create_requests_customer_contact_id (customer_contact_id),
KEY ix_wecom_group_create_requests_qrcode_id (qrcode_id),
KEY ix_wecom_group_create_requests_channel_code (channel_code),
KEY ix_wecom_group_create_requests_position_id (position_id),
KEY ix_wecom_group_create_requests_position_code (position_code),
KEY ix_wecom_group_create_requests_status (status),
KEY ix_wecom_group_create_requests_task_id (task_id),
KEY ix_wecom_group_create_requests_resolved_group_contact_id (resolved_group_contact_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS wecom_job_configs (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
job_key VARCHAR(64) NOT NULL,
enabled BOOLEAN NOT NULL DEFAULT 1,
last_run_at DATETIME NULL,
last_status VARCHAR(32) NULL,
last_error TEXT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY ix_wecom_job_configs_job_key (job_key),
KEY ix_wecom_job_configs_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS conversation_logs (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
session_id VARCHAR(64) NOT NULL,
user_id VARCHAR(64) NOT NULL,
agent_id INTEGER NOT NULL,
agent_name VARCHAR(50) NULL,
query TEXT NOT NULL,
response TEXT NULL,
intent VARCHAR(128) NULL,
entities JSON NULL,
processing_time_ms INTEGER NULL,
has_error BOOLEAN NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
KEY ix_conversation_logs_id (id),
KEY ix_conversation_logs_user_id (user_id),
KEY ix_conversation_logs_agent_id (agent_id),
KEY ix_conversation_logs_intent (intent),
KEY ix_conversation_logs_has_error (has_error),
KEY ix_conversation_logs_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS analytics_events (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
event_type VARCHAR(64) NOT NULL,
event_data JSON NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
KEY ix_analytics_events_id (id),
KEY ix_analytics_events_event_type (event_type),
KEY ix_analytics_events_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS analytics_statistics (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
stat_date DATE NOT NULL,
dimension VARCHAR(32) NOT NULL,
dimension_value VARCHAR(128) NOT NULL,
total_agent_calls INTEGER NOT NULL DEFAULT 0,
total_sessions INTEGER NOT NULL DEFAULT 0,
avg_session_turns NUMERIC(5,2) NOT NULL DEFAULT 0.00,
intent_distribution JSON NULL,
agent_call_ranking JSON NULL,
daily_trend JSON NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY ix_analytics_statistics_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS page_views (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
page_type VARCHAR(64) NOT NULL,
user_id VARCHAR(64) NULL,
session_id VARCHAR(64) NULL,
device_type VARCHAR(32) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
KEY ix_page_views_id (id),
KEY ix_page_views_page_type (page_type),
KEY ix_page_views_user_id (user_id),
KEY ix_page_views_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS scan_events (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
qrcode_id INTEGER NULL,
channel_code VARCHAR(128) NULL,
customer_user_id VARCHAR(64) NULL,
position_code VARCHAR(64) NULL,
employee_id VARCHAR(64) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
KEY ix_scan_events_id (id),
KEY ix_scan_events_qrcode_id (qrcode_id),
KEY ix_scan_events_channel_code (channel_code),
KEY ix_scan_events_customer_user_id (customer_user_id),
KEY ix_scan_events_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS group_join_events (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
group_id VARCHAR(64) NULL,
customer_user_id VARCHAR(64) NULL,
employee_count INTEGER NULL,
agent_count INTEGER NULL,
channel_code VARCHAR(128) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
KEY ix_group_join_events_id (id),
KEY ix_group_join_events_group_id (group_id),
KEY ix_group_join_events_customer_user_id (customer_user_id),
KEY ix_group_join_events_channel_code (channel_code),
KEY ix_group_join_events_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
SET FOREIGN_KEY_CHECKS = 1;
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!