Commit 1eda8f97 by imwangxiaozhou

refactor(wecom-sync): 移除旧版企微群同步相关冗余代码

移除全部 WeComGroup 数据模型与关联的数据库表,删除群同步相关的客户端方法、服务逻辑与 API 响应字段。
简化新客户扫描逻辑,固定仅同步企微客户类型并移除多余的 contact_type 参数。
同步更新所有依赖的测试用例以适配代码变更。
1 parent 392bbb3e
......@@ -90,12 +90,12 @@ def run_wecom_job(req: WeComJobRunRequest, services=Depends(get_services)):
"/new-customers/scan",
response_model=ApiResponse[WeComNewCustomerListResponse],
summary="扫描可建群的新客户",
description="按承接机器人扫描新增客户候选列表。该接口只返回候选客户、岗位解析结果和可建群成员,不会真正发起建群,也不会写入正式客户群绑定表。可通过 contact_type 选择通讯录类型,例如 ww_customer、ww_group_external、ww_colleague。",
description="按承接机器人扫描新增客户候选列表。该接口只返回候选客户、岗位解析结果和可建群成员,不会真正发起建群,也不会写入正式客户群绑定表。当前固定只扫描企微客户 contact_type=ww_customer。",
)
def list_new_customers(req: WeComNewCustomersRequest, services=Depends(get_services)):
_, orchestration_service = services
try:
items = orchestration_service.scan_new_customers(bot_ids=req.bot_ids, contact_type=req.contact_type)
items = orchestration_service.scan_new_customers(bot_ids=req.bot_ids)
payload = WeComNewCustomerListResponse(
total=len(items),
list=items,
......
......@@ -40,7 +40,6 @@ def run_wecom_sync(req: WeComSyncRunRequest, svc: WeComSyncService = Depends(get
bot_ids = [item.bot_id for item in db.query(WeComBot).order_by(WeComBot.id.asc()).all()]
result = {
"bots": 0,
"groups": 0,
"messages": svc.sync_messages_incremental(
bot_ids=bot_ids,
start_time=req.message_start_time,
......@@ -50,7 +49,6 @@ def run_wecom_sync(req: WeComSyncRunRequest, svc: WeComSyncService = Depends(get
payload = WeComSyncRunResponse(
mode=req.mode,
bots=result["bots"],
groups=result["groups"],
messages=result["messages"],
triggered_at=datetime.now(timezone.utc),
)
......
......@@ -88,6 +88,14 @@ def ensure_runtime_schema(engine) -> None:
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 "wecom_job_configs" not in table_names:
conn.execute(
text(
......
......@@ -37,12 +37,6 @@ class HttpWeComSyncClient(WeComSyncClient):
{"bot_id": bot_id, "page": page, "page_size": page_size},
)
def list_groups(self, *, bot_id: str, page: int, page_size: int) -> dict[str, Any]:
return self._get(
"/api/v1/business/groups",
{"bot_id": bot_id, "page": page, "page_size": page_size},
)
def list_customers(
self,
*,
......
......@@ -4,7 +4,6 @@ from app.model.position_tag import PositionTag, OfficialTab, PositionTagUser
from app.model.wecom_sync import (
WeComBot,
WeComCustomerGroup,
WeComGroup,
WeComGroupCreateRequest,
WeComMessage,
WeComSyncCheckpoint,
......@@ -15,6 +14,6 @@ __all__ = [
"Agent", "AgentPosition", "AgentSkill", "AgentStatus",
"QrcodeChannel",
"PositionTag", "OfficialTab", "PositionTagUser",
"WeComBot", "WeComCustomerGroup", "WeComGroup", "WeComMessage", "WeComSyncCheckpoint",
"WeComBot", "WeComCustomerGroup", "WeComMessage", "WeComSyncCheckpoint",
"WeComGroupCreateRequest", "WeComJobConfig",
]
......@@ -27,28 +27,6 @@ class WeComBot(Base):
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
class WeComGroup(Base):
__tablename__ = "wecom_groups"
id = Column(Integer, primary_key=True, index=True)
bot_code = Column(String(191), nullable=False, index=True)
channel = Column(String(64), nullable=False)
bot_id = Column(String(128), nullable=False)
group_id = Column(String(191), nullable=False)
group_name = Column(String(255), nullable=False)
group_type = Column(String(64), nullable=True)
avatar_url = Column(String(500), nullable=True)
status = Column(String(64), nullable=True)
extra = Column(JSON, nullable=True)
last_active = Column(DateTime, nullable=True)
external_created_at = Column(DateTime, nullable=True)
external_updated_at = Column(DateTime, nullable=True)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
__table_args__ = (UniqueConstraint("bot_code", "group_id", name="uk_wecom_group_bot_group"),)
class WeComMessage(Base):
__tablename__ = "wecom_messages"
......
......@@ -16,7 +16,6 @@ class WeComSyncRunRequest(BaseModel):
class WeComSyncRunResponse(BaseModel):
mode: str = Field(..., description="本次执行的同步模式。", examples=["full"])
bots: int = Field(..., description="同步到的机器人数量。", examples=[1])
groups: int = Field(..., description="同步到的群数量。", examples=[8])
messages: int = Field(..., description="同步到的消息数量。", examples=[156])
triggered_at: datetime = Field(..., description="任务触发时间。", examples=["2026-05-21T16:30:00Z"])
......@@ -71,7 +70,6 @@ class WeComJobRunRequest(BaseModel):
class WeComNewCustomersRequest(BaseModel):
bot_ids: Optional[List[str]] = Field(default=None, description="待扫描的新客户所属 bot_id 列表;为空时扫描本地已同步的全部机器人。", examples=[["RBT001"]])
contact_type: Optional[str] = Field(default=None, description="通讯录类型筛选,例如 ww_customer、ww_group_external、ww_colleague;为空时不过滤。", examples=["ww_customer"])
class WeComGroupCreateRequestItem(BaseModel):
......
......@@ -32,6 +32,7 @@ from app.service.wecom_sync_service import WeComSyncClient, WeComSyncService
logger = logging.getLogger(__name__)
PENDING_REQUEST_TIMEOUT = timedelta(hours=1)
INVALID_GROUP_STATUSES = {"failed", "timeout", "invalid"}
WECOM_CUSTOMER_CONTACT_TYPE = "ww_customer"
def _utcnow() -> datetime:
......@@ -97,7 +98,7 @@ class WeComCustomerGroupOrchestrationService:
"created": created,
}
def scan_new_customers(self, *, bot_ids: Iterable[str] | None = None, contact_type: str | None = None) -> list[WeComNewCustomerItem]:
def scan_new_customers(self, *, bot_ids: Iterable[str] | None = None) -> list[WeComNewCustomerItem]:
resolved_bot_ids = list(bot_ids) if bot_ids else [
item.bot_id for item in self.db.query(WeComBot).order_by(WeComBot.id.asc()).all()
]
......@@ -105,7 +106,7 @@ class WeComCustomerGroupOrchestrationService:
items: list[WeComNewCustomerItem] = []
seen_contact_ids: set[str] = set()
for bot_id in resolved_bot_ids:
for item in self._scan_new_customers_for_bot(bot_id=bot_id, contact_type=contact_type):
for item in self._scan_new_customers_for_bot(bot_id=bot_id):
if item.contact_id in seen_contact_ids:
continue
seen_contact_ids.add(item.contact_id)
......@@ -173,7 +174,7 @@ class WeComCustomerGroupOrchestrationService:
def create_new_requests(self, *, bot_ids: Iterable[str] | None = None) -> int:
created = 0
for item in self.scan_new_customers(bot_ids=bot_ids, contact_type=None):
for item in self.scan_new_customers(bot_ids=bot_ids):
if not item.can_create_group:
continue
if self._has_valid_customer_group(item.contact_id):
......@@ -490,7 +491,7 @@ class WeComCustomerGroupOrchestrationService:
self.sync_service._upsert_group(resolved)
return True
def _scan_new_customers_for_bot(self, *, bot_id: str, contact_type: str | None = None) -> 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()
if bot is None:
raise ValueError(f"??? bot_id={bot_id} ??????????")
......@@ -503,6 +504,7 @@ class WeComCustomerGroupOrchestrationService:
if position is None:
raise ValueError(f"bot_id={bot_id} ????????????")
resolved_contact_type = WECOM_CUSTOMER_CONTACT_TYPE
candidates: list[WeComNewCustomerItem] = []
page = 1
while True:
......@@ -512,7 +514,7 @@ class WeComCustomerGroupOrchestrationService:
end_time=None,
page=page,
page_size=self.page_size,
contact_type=contact_type,
contact_type=resolved_contact_type,
)
items = payload.get("items") or []
if not items:
......@@ -713,7 +715,7 @@ class WeComCustomerGroupOrchestrationService:
end_time=None,
page=1,
page_size=self.page_size,
contact_type=None,
contact_type=WECOM_CUSTOMER_CONTACT_TYPE,
)
for item in payload.get("items") or []:
if str(item.get("contact_id") or "") == customer_contact_id:
......
......@@ -10,7 +10,6 @@ from sqlalchemy.orm import Session
from app.model.wecom_sync import (
WeComBot,
WeComCustomerGroup,
WeComGroup,
WeComJobConfig,
WeComMessage,
WeComSyncCheckpoint,
......@@ -54,9 +53,6 @@ class WeComSyncClient(Protocol):
def list_bots(self, *, page: int, page_size: int) -> dict[str, Any]:
...
def list_groups(self, *, bot_id: str, page: int, page_size: int) -> dict[str, Any]:
...
def list_customers(
self,
*,
......@@ -142,11 +138,14 @@ class WeComSyncService:
end_time: datetime | None,
) -> dict[str, int]:
bots = self.sync_bots_full()
resolved_bot_ids = [bot.bot_id for bot in self.db.query(WeComBot).all() if bot.bot_id]
resolved_bot_ids = [
bot.bot_id
for bot in self.db.query(WeComBot).filter(WeComBot.online == True).all()
if bot.bot_id
]
if bot_ids is not None:
allowed_bot_ids = {str(bot_id) for bot_id in bot_ids if str(bot_id).strip()}
resolved_bot_ids = [item for item in resolved_bot_ids if item in allowed_bot_ids]
groups = self.sync_groups_full(resolved_bot_ids)
messages = self.sync_messages_incremental(
bot_ids=resolved_bot_ids,
start_time=start_time,
......@@ -154,7 +153,6 @@ class WeComSyncService:
)
return {
"bots": bots,
"groups": groups,
"messages": messages,
}
......@@ -163,6 +161,8 @@ class WeComSyncService:
latest_time: datetime | None = None
latest_id: str | None = None
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):
continue
bot = self._upsert_bot(item)
count += 1
candidate_time = _parse_dt(item.get("updated_at")) or _parse_dt(item.get("created_at"))
......@@ -170,26 +170,6 @@ class WeComSyncService:
self._complete_checkpoint("bots", "global", latest_time, latest_id)
return count
def sync_groups_full(self, bot_ids: Iterable[str]) -> int:
total = 0
for bot_id in bot_ids:
latest_time: datetime | None = None
latest_id: str | None = None
bot_code = self._resolve_bot_code(None, bot_id)
for item in self._paginate(
lambda page, current_bot_id=bot_id: self.client.list_groups(
bot_id=current_bot_id,
page=page,
page_size=self.page_size,
)
):
group = self._upsert_group(item)
total += 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, group.group_id)
self._complete_checkpoint("groups", f"bot:{bot_code}", latest_time, latest_id)
return total
def sync_messages_incremental(
self,
*,
......@@ -241,30 +221,34 @@ class WeComSyncService:
bot_name or bot_id,
bot_id,
)
checkpoint = self._get_checkpoint("messages", f"bot:{bot_code}")
window = self._resolve_message_window(checkpoint, start_time, end_time)
latest_time = checkpoint.last_sync_time if checkpoint else None
latest_id = checkpoint.last_external_id if checkpoint else None
for item in self._paginate(
lambda page, current_bot_id=bot_id: self.client.list_messages(
bot_id=current_bot_id,
group_id=None,
start_time=window.start_time,
end_time=window.end_time,
page=page,
page_size=self.page_size,
order="asc",
)
):
msg_time = _parse_dt(item.get("msg_time"))
msg_id = str(item.get("msg_id") or "")
if self._is_message_already_consumed(checkpoint, msg_time, msg_id):
for group in bound_groups:
group_id = str(group.group_id or "").strip()
if not group_id:
continue
message = self._upsert_message(item)
total += 1
latest_time, latest_id = self._max_key(latest_time, latest_id, message.msg_time, message.msg_id)
self._complete_checkpoint("messages", f"bot:{bot_code}", latest_time, latest_id)
checkpoint = self._get_checkpoint("messages", f"group:{group_id}")
window = self._resolve_message_window(checkpoint, start_time, end_time)
latest_time = checkpoint.last_sync_time if checkpoint else None
latest_id = checkpoint.last_external_id if checkpoint else None
for item in self._paginate(
lambda page, current_bot_id=bot_id, current_group_id=group_id: self.client.list_messages(
bot_id=current_bot_id,
group_id=current_group_id,
start_time=window.start_time,
end_time=window.end_time,
page=page,
page_size=self.page_size,
order="asc",
)
):
msg_time = _parse_dt(item.get("msg_time"))
msg_id = str(item.get("msg_id") or "")
if self._is_message_already_consumed(checkpoint, msg_time, msg_id):
continue
message = self._upsert_message(item)
total += 1
latest_time, latest_id = self._max_key(latest_time, latest_id, message.msg_time, message.msg_id)
self._complete_checkpoint("messages", f"group:{group_id}", latest_time, latest_id)
return total
def dispatch_pending_messages(self, *, bot_ids: Iterable[str] | None = None) -> int:
......@@ -360,32 +344,6 @@ class WeComSyncService:
self.db.flush()
return record
def _upsert_group(self, data: dict[str, Any]) -> WeComGroup:
bot_code = self._resolve_bot_code(data.get("bot_code"), data.get("bot_id"), data.get("channel"))
group_id = str(data.get("group_id") or data.get("contact_id") or "")
record = (
self.db.query(WeComGroup)
.filter(WeComGroup.bot_code == bot_code, WeComGroup.group_id == group_id)
.first()
)
if record is None:
record = WeComGroup(bot_code=bot_code, channel=str(data.get("channel") or ""), bot_id=str(data.get("bot_id") or ""), group_id=group_id, group_name="")
self.db.add(record)
record.bot_code = bot_code
record.channel = str(data.get("channel") or record.channel)
record.bot_id = str(data.get("bot_id") or record.bot_id)
record.group_id = group_id
record.group_name = str(data.get("group_name") or data.get("contact_name") or data.get("display_name") or group_id)
record.group_type = data.get("group_type") or data.get("contact_type")
record.avatar_url = data.get("avatar_url")
record.status = data.get("status")
record.extra = data.get("extra")
record.last_active = _parse_dt(data.get("last_active"))
record.external_created_at = _parse_dt(data.get("created_at"))
record.external_updated_at = _parse_dt(data.get("updated_at"))
self.db.flush()
return record
def _upsert_message(self, data: dict[str, Any]) -> WeComMessage:
bot_code = self._resolve_bot_code(data.get("bot_code"), data.get("bot_id"), data.get("channel"))
msg_id = str(data.get("msg_id") or "")
......@@ -539,3 +497,6 @@ class WeComSyncService:
if isinstance(value, str):
return value.lower() in {"1", "true", "yes", "online", "enable"}
return bool(value)
def _is_online_bot(self, data: dict[str, Any]) -> bool:
return bool(self._to_bool_or_none(data.get("online")))
......@@ -25,7 +25,6 @@ from app.model.position_tag import PositionTag
from app.model.wecom_sync import (
WeComBot,
WeComCustomerGroup,
WeComGroup,
WeComGroupCreateRequest,
WeComMessage,
)
......@@ -60,9 +59,6 @@ class FakeClient:
def list_contacts(self, *, bot_id: str, page: int, page_size: int):
return {'items': [], 'meta': {'total': 0, 'page': 1, 'page_size': page_size}}
def list_groups(self, *, bot_id: str, page: int, page_size: int):
return {'items': [], 'meta': {'total': 0, 'page': 1, 'page_size': page_size}}
def list_customers(self, *, bot_id: str, start_time, end_time, page: int, page_size: int, contact_type=None, keyword=None):
self.last_list_customers_kwargs = {
'bot_id': bot_id,
......@@ -283,32 +279,6 @@ def test_list_new_customers_returns_candidates_without_writing_groups():
db.close()
def test_list_new_customers_passes_contact_type_to_customer_scan():
db = _setup_db()
_seed_group_context(db)
seen = {'contact_type': None}
class CandidateClient(FakeClient):
def list_customers(self, *, bot_id: str, start_time, end_time, page: int, page_size: int, contact_type=None):
seen['contact_type'] = contact_type
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'], contact_type='ww_customer'),
(sync_service, orchestration_service),
)
assert result['data']['total'] == 1
assert seen['contact_type'] == 'ww_customer'
db.close()
def test_list_new_customers_skips_customer_when_group_already_exists():
db = _setup_db()
bot, managed, _, _ = _seed_group_context(db)
......@@ -841,11 +811,6 @@ def test_get_group_create_request_status_returns_request_progress():
'contact_type': None,
'keyword': 'biz-group-001',
}
group = db.query(WeComGroup).filter(WeComGroup.bot_code == 'yc_ww:ABE6E30E3476E955853410C13E38C1065194F219CF554649F1C4F9C615435A82', WeComGroup.group_id == '4BD6DE10053F765A7F161DF36A6E0031901A2DDBF0758730A19ADA8F0B6DD9F8').first()
assert group is not None
assert group.group_name == '123444'
assert group.group_type == 'ww_group_external'
assert group.extra == {'biz_rela_no': 'biz-group-001', 'member_count': 0}
db.close()
......
......@@ -22,7 +22,7 @@ class FakeApiSyncService:
def sync_all_full(self, *, message_start_time, message_end_time):
self.full_called = True
return {"bots": 1, "groups": 3, "messages": 4}
return {"bots": 1, "messages": 4}
def sync_messages_incremental(self, *, bot_ids, start_time, end_time):
self.incremental_called = True
......
......@@ -10,7 +10,6 @@ from app.infrastructure.database import Base
from app.model.wecom_sync import (
WeComBot,
WeComCustomerGroup,
WeComGroup,
WeComMessage,
WeComSyncCheckpoint,
)
......@@ -30,15 +29,11 @@ def _dt(value: str) -> datetime:
@dataclass
class FakeWeComSyncClient(WeComSyncClient):
bots: list[dict[str, Any]] = field(default_factory=list)
groups_by_bot: dict[str, list[dict[str, Any]]] = field(default_factory=dict)
messages_by_bot: dict[str, list[dict[str, Any]]] = field(default_factory=dict)
def list_bots(self, *, page: int, page_size: int) -> dict[str, Any]:
return _paginate(self.bots, page, page_size)
def list_groups(self, *, bot_id: str, page: int, page_size: int) -> dict[str, Any]:
return _paginate(self.groups_by_bot.get(bot_id, []), page, page_size)
def list_messages(
self,
*,
......@@ -91,7 +86,6 @@ def db():
session.query(WeComSyncCheckpoint).delete()
session.query(WeComMessage).delete()
session.query(WeComCustomerGroup).delete()
session.query(WeComGroup).delete()
session.query(WeComBot).delete()
session.commit()
yield session
......@@ -114,6 +108,7 @@ def test_sync_wecom_bots_groups_messages_ignores_legacy_contact_payloads(db):
"bot_id": "RBT001",
"bot_code": "wt_ww:RBT001",
"bot_name": "销售机器人",
"online": 1,
}
],
)
......@@ -125,12 +120,12 @@ def test_sync_wecom_bots_groups_messages_ignores_legacy_contact_payloads(db):
end_time=_dt("2026-05-21T10:00:00Z"),
)
assert result == {"bots": 1, "groups": 0, "messages": 0}
assert result == {"bots": 1, "messages": 0}
checkpoints = db.query(WeComSyncCheckpoint).order_by(WeComSyncCheckpoint.resource_type.asc()).all()
assert [item.resource_type for item in checkpoints] == ["bots", "groups", "messages"]
assert [item.resource_type for item in checkpoints] == ["bots", "messages"]
def test_sync_wecom_bots_groups_messages_syncs_bots_groups_messages(db):
def test_sync_messages_incremental_only_persists_customer_group_messages(db):
client = FakeWeComSyncClient(
bots=[
{
......@@ -138,21 +133,52 @@ def test_sync_wecom_bots_groups_messages_syncs_bots_groups_messages(db):
"bot_id": "RBT001",
"bot_code": "wt_ww:RBT001",
"bot_name": "销售机器人",
"updated_at": "2026-05-21T09:00:00Z",
"online": 1,
}
],
groups_by_bot={
messages_by_bot={
"RBT001": [
{
"channel": "wt_ww",
"bot_id": "RBT001",
"msg_id": "msg_001",
"sender_id": "wm_001",
"sender_name": "张三",
"msg_content": "你好",
"msg_type": "text",
"msg_time": "2026-05-21T09:03:00Z",
"session_title": "销售服务群",
"contact_id": "wr_001",
"contact_name": "销售服务群",
"contact_type": "ww_group_external",
"updated_at": "2026-05-21T09:02:00Z",
"bot_send": 0,
}
]
},
)
service = WeComSyncService(db, client, RecordingDispatcher())
service.sync_bots_full()
synced = service.sync_messages_incremental(
bot_ids=["RBT001"],
start_time=_dt("2026-05-21T09:00:00Z"),
end_time=_dt("2026-05-21T10:00:00Z"),
)
assert synced == 0
assert db.query(WeComMessage).count() == 0
def test_sync_wecom_bots_groups_messages_syncs_bots_messages(db):
client = FakeWeComSyncClient(
bots=[
{
"channel": "wt_ww",
"bot_id": "RBT001",
"bot_code": "wt_ww:RBT001",
"bot_name": "销售机器人",
"online": 1,
"updated_at": "2026-05-21T09:00:00Z",
}
],
messages_by_bot={
"RBT001": [
{
......@@ -174,6 +200,21 @@ def test_sync_wecom_bots_groups_messages_syncs_bots_groups_messages(db):
)
dispatcher = RecordingDispatcher()
service = WeComSyncService(db, client, dispatcher)
db.add(
WeComCustomerGroup(
customer_contact_id="cust_001",
customer_name="张三",
bot_id="RBT001",
bot_code="wt_ww:RBT001",
group_id="wr_001",
group_name="销售服务群",
group_status="active",
group_create_request_id=1,
member_bot_ids=["managed_1"],
is_deleted=False,
)
)
db.commit()
result = service.sync_wecom_bots_groups_messages(
bot_ids=["RBT001"],
......@@ -181,9 +222,8 @@ def test_sync_wecom_bots_groups_messages_syncs_bots_groups_messages(db):
end_time=_dt("2026-05-21T10:00:00Z"),
)
assert result == {"bots": 1, "groups": 1, "messages": 1}
assert result == {"bots": 1, "messages": 1}
assert db.query(WeComBot).count() == 1
assert db.query(WeComGroup).count() == 1
assert db.query(WeComMessage).count() == 1
assert dispatcher.dispatched == ["msg_001"]
......@@ -202,19 +242,6 @@ def test_full_sync_persists_resources_and_dispatches_non_bot_messages(db):
"updated_at": "2026-05-21T09:00:00Z",
}
],
groups_by_bot={
"RBT001": [
{
"channel": "wt_ww",
"bot_id": "RBT001",
"contact_id": "wr_001",
"contact_name": "销售服务群",
"display_name": "销售服务群",
"contact_type": "ww_group_external",
"updated_at": "2026-05-21T09:02:00Z",
}
]
},
messages_by_bot={
"RBT001": [
{
......@@ -251,6 +278,21 @@ def test_full_sync_persists_resources_and_dispatches_non_bot_messages(db):
)
dispatcher = RecordingDispatcher()
service = WeComSyncService(db, client, dispatcher)
db.add(
WeComCustomerGroup(
customer_contact_id="cust_001",
customer_name="张三",
bot_id="RBT001",
bot_code="wt_ww:RBT001",
group_id="wr_001",
group_name="销售服务群",
group_status="active",
group_create_request_id=1,
member_bot_ids=["managed_1"],
is_deleted=False,
)
)
db.commit()
result = service.sync_all_full(
message_start_time=_dt("2026-05-21T09:00:00Z"),
......@@ -258,11 +300,9 @@ def test_full_sync_persists_resources_and_dispatches_non_bot_messages(db):
)
assert result["bots"] == 1
assert result["groups"] == 1
assert result["messages"] == 2
assert "contacts" not in result
assert db.query(WeComBot).count() == 1
assert db.query(WeComGroup).count() == 1
assert db.query(WeComMessage).count() == 2
assert dispatcher.dispatched == ["msg_001"]
......@@ -277,6 +317,34 @@ def test_full_sync_persists_resources_and_dispatches_non_bot_messages(db):
assert len(checkpoints) == 3
def test_sync_bots_full_skips_offline_bots(db):
client = FakeWeComSyncClient(
bots=[
{
"channel": "wt_ww",
"bot_id": "RBT001",
"bot_code": "wt_ww:RBT001",
"bot_name": "在线机器人",
"online": 1,
},
{
"channel": "wt_ww",
"bot_id": "RBT002",
"bot_code": "wt_ww:RBT002",
"bot_name": "离线机器人",
"online": 0,
},
]
)
service = WeComSyncService(db, client, RecordingDispatcher())
count = service.sync_bots_full()
assert count == 1
rows = db.query(WeComBot).order_by(WeComBot.bot_id.asc()).all()
assert [item.bot_id for item in rows] == ["RBT001"]
def test_incremental_sync_uses_time_and_msg_id_boundary_without_duplicates(db):
client = FakeWeComSyncClient(
bots=[
......@@ -285,6 +353,7 @@ def test_incremental_sync_uses_time_and_msg_id_boundary_without_duplicates(db):
"bot_id": "RBT001",
"bot_code": "wt_ww:RBT001",
"bot_name": "销售机器人",
"online": 1,
}
],
messages_by_bot={
......@@ -319,6 +388,21 @@ def test_incremental_sync_uses_time_and_msg_id_boundary_without_duplicates(db):
},
)
service = WeComSyncService(db, client, RecordingDispatcher())
db.add(
WeComCustomerGroup(
customer_contact_id="cust_001",
customer_name="张三",
bot_id="RBT001",
bot_code="wt_ww:RBT001",
group_id="wr_001",
group_name="销售服务群",
group_status="active",
group_create_request_id=1,
member_bot_ids=["managed_1"],
is_deleted=False,
)
)
db.commit()
service.sync_bots_full()
service.sync_messages_incremental(
......@@ -361,6 +445,7 @@ def test_dispatch_failure_marks_message_failed_without_losing_payload(db):
"bot_id": "RBT001",
"bot_code": "wt_ww:RBT001",
"bot_name": "销售机器人",
"online": 1,
}
],
messages_by_bot={
......@@ -384,6 +469,21 @@ def test_dispatch_failure_marks_message_failed_without_losing_payload(db):
)
dispatcher = RecordingDispatcher(fail_msg_ids={"msg_fail"})
service = WeComSyncService(db, client, dispatcher)
db.add(
WeComCustomerGroup(
customer_contact_id="cust_001",
customer_name="张三",
bot_id="RBT001",
bot_code="wt_ww:RBT001",
group_id="wr_001",
group_name="销售服务群",
group_status="active",
group_create_request_id=1,
member_bot_ids=["managed_1"],
is_deleted=False,
)
)
db.commit()
service.sync_bots_full()
service.sync_messages_incremental(
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!