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)): ...@@ -90,12 +90,12 @@ def run_wecom_job(req: WeComJobRunRequest, services=Depends(get_services)):
"/new-customers/scan", "/new-customers/scan",
response_model=ApiResponse[WeComNewCustomerListResponse], response_model=ApiResponse[WeComNewCustomerListResponse],
summary="扫描可建群的新客户", 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)): def list_new_customers(req: WeComNewCustomersRequest, services=Depends(get_services)):
_, orchestration_service = services _, orchestration_service = services
try: 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( payload = WeComNewCustomerListResponse(
total=len(items), total=len(items),
list=items, list=items,
......
...@@ -40,7 +40,6 @@ def run_wecom_sync(req: WeComSyncRunRequest, svc: WeComSyncService = Depends(get ...@@ -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()] bot_ids = [item.bot_id for item in db.query(WeComBot).order_by(WeComBot.id.asc()).all()]
result = { result = {
"bots": 0, "bots": 0,
"groups": 0,
"messages": svc.sync_messages_incremental( "messages": svc.sync_messages_incremental(
bot_ids=bot_ids, bot_ids=bot_ids,
start_time=req.message_start_time, start_time=req.message_start_time,
...@@ -50,7 +49,6 @@ def run_wecom_sync(req: WeComSyncRunRequest, svc: WeComSyncService = Depends(get ...@@ -50,7 +49,6 @@ def run_wecom_sync(req: WeComSyncRunRequest, svc: WeComSyncService = Depends(get
payload = WeComSyncRunResponse( payload = WeComSyncRunResponse(
mode=req.mode, mode=req.mode,
bots=result["bots"], bots=result["bots"],
groups=result["groups"],
messages=result["messages"], messages=result["messages"],
triggered_at=datetime.now(timezone.utc), triggered_at=datetime.now(timezone.utc),
) )
......
...@@ -88,6 +88,14 @@ def ensure_runtime_schema(engine) -> None: ...@@ -88,6 +88,14 @@ def ensure_runtime_schema(engine) -> None:
for row in conn.execute(text("SELECT name FROM sqlite_master WHERE type='table'")) 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: if "wecom_job_configs" not in table_names:
conn.execute( conn.execute(
text( text(
......
...@@ -37,12 +37,6 @@ class HttpWeComSyncClient(WeComSyncClient): ...@@ -37,12 +37,6 @@ class HttpWeComSyncClient(WeComSyncClient):
{"bot_id": bot_id, "page": page, "page_size": page_size}, {"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( def list_customers(
self, self,
*, *,
......
...@@ -4,7 +4,6 @@ from app.model.position_tag import PositionTag, OfficialTab, PositionTagUser ...@@ -4,7 +4,6 @@ from app.model.position_tag import PositionTag, OfficialTab, PositionTagUser
from app.model.wecom_sync import ( from app.model.wecom_sync import (
WeComBot, WeComBot,
WeComCustomerGroup, WeComCustomerGroup,
WeComGroup,
WeComGroupCreateRequest, WeComGroupCreateRequest,
WeComMessage, WeComMessage,
WeComSyncCheckpoint, WeComSyncCheckpoint,
...@@ -15,6 +14,6 @@ __all__ = [ ...@@ -15,6 +14,6 @@ __all__ = [
"Agent", "AgentPosition", "AgentSkill", "AgentStatus", "Agent", "AgentPosition", "AgentSkill", "AgentStatus",
"QrcodeChannel", "QrcodeChannel",
"PositionTag", "OfficialTab", "PositionTagUser", "PositionTag", "OfficialTab", "PositionTagUser",
"WeComBot", "WeComCustomerGroup", "WeComGroup", "WeComMessage", "WeComSyncCheckpoint", "WeComBot", "WeComCustomerGroup", "WeComMessage", "WeComSyncCheckpoint",
"WeComGroupCreateRequest", "WeComJobConfig", "WeComGroupCreateRequest", "WeComJobConfig",
] ]
...@@ -27,28 +27,6 @@ class WeComBot(Base): ...@@ -27,28 +27,6 @@ class WeComBot(Base):
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False) updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
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): class WeComMessage(Base):
__tablename__ = "wecom_messages" __tablename__ = "wecom_messages"
......
...@@ -16,7 +16,6 @@ class WeComSyncRunRequest(BaseModel): ...@@ -16,7 +16,6 @@ class WeComSyncRunRequest(BaseModel):
class WeComSyncRunResponse(BaseModel): class WeComSyncRunResponse(BaseModel):
mode: str = Field(..., description="本次执行的同步模式。", examples=["full"]) mode: str = Field(..., description="本次执行的同步模式。", examples=["full"])
bots: int = Field(..., description="同步到的机器人数量。", examples=[1]) bots: int = Field(..., description="同步到的机器人数量。", examples=[1])
groups: int = Field(..., description="同步到的群数量。", examples=[8])
messages: int = Field(..., description="同步到的消息数量。", examples=[156]) messages: int = Field(..., description="同步到的消息数量。", examples=[156])
triggered_at: datetime = Field(..., description="任务触发时间。", examples=["2026-05-21T16:30:00Z"]) triggered_at: datetime = Field(..., description="任务触发时间。", examples=["2026-05-21T16:30:00Z"])
...@@ -71,7 +70,6 @@ class WeComJobRunRequest(BaseModel): ...@@ -71,7 +70,6 @@ class WeComJobRunRequest(BaseModel):
class WeComNewCustomersRequest(BaseModel): class WeComNewCustomersRequest(BaseModel):
bot_ids: Optional[List[str]] = Field(default=None, description="待扫描的新客户所属 bot_id 列表;为空时扫描本地已同步的全部机器人。", examples=[["RBT001"]]) 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): class WeComGroupCreateRequestItem(BaseModel):
......
...@@ -32,6 +32,7 @@ from app.service.wecom_sync_service import WeComSyncClient, WeComSyncService ...@@ -32,6 +32,7 @@ from app.service.wecom_sync_service import WeComSyncClient, WeComSyncService
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
PENDING_REQUEST_TIMEOUT = timedelta(hours=1) PENDING_REQUEST_TIMEOUT = timedelta(hours=1)
INVALID_GROUP_STATUSES = {"failed", "timeout", "invalid"} INVALID_GROUP_STATUSES = {"failed", "timeout", "invalid"}
WECOM_CUSTOMER_CONTACT_TYPE = "ww_customer"
def _utcnow() -> datetime: def _utcnow() -> datetime:
...@@ -97,7 +98,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -97,7 +98,7 @@ class WeComCustomerGroupOrchestrationService:
"created": created, "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 [ 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() item.bot_id for item in self.db.query(WeComBot).order_by(WeComBot.id.asc()).all()
] ]
...@@ -105,7 +106,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -105,7 +106,7 @@ class WeComCustomerGroupOrchestrationService:
items: list[WeComNewCustomerItem] = [] items: list[WeComNewCustomerItem] = []
seen_contact_ids: set[str] = set() seen_contact_ids: set[str] = set()
for bot_id in resolved_bot_ids: 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: if item.contact_id in seen_contact_ids:
continue continue
seen_contact_ids.add(item.contact_id) seen_contact_ids.add(item.contact_id)
...@@ -173,7 +174,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -173,7 +174,7 @@ 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, contact_type=None): for item in self.scan_new_customers(bot_ids=bot_ids):
if not item.can_create_group: if not item.can_create_group:
continue continue
if self._has_valid_customer_group(item.contact_id): if self._has_valid_customer_group(item.contact_id):
...@@ -490,7 +491,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -490,7 +491,7 @@ class WeComCustomerGroupOrchestrationService:
self.sync_service._upsert_group(resolved) self.sync_service._upsert_group(resolved)
return True 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() bot = self.db.query(WeComBot).filter(WeComBot.bot_id == bot_id).first()
if bot is None: if bot is None:
raise ValueError(f"??? bot_id={bot_id} ??????????") raise ValueError(f"??? bot_id={bot_id} ??????????")
...@@ -503,6 +504,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -503,6 +504,7 @@ class WeComCustomerGroupOrchestrationService:
if position is None: if position is None:
raise ValueError(f"bot_id={bot_id} ????????????") raise ValueError(f"bot_id={bot_id} ????????????")
resolved_contact_type = WECOM_CUSTOMER_CONTACT_TYPE
candidates: list[WeComNewCustomerItem] = [] candidates: list[WeComNewCustomerItem] = []
page = 1 page = 1
while True: while True:
...@@ -512,7 +514,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -512,7 +514,7 @@ class WeComCustomerGroupOrchestrationService:
end_time=None, end_time=None,
page=page, page=page,
page_size=self.page_size, page_size=self.page_size,
contact_type=contact_type, contact_type=resolved_contact_type,
) )
items = payload.get("items") or [] items = payload.get("items") or []
if not items: if not items:
...@@ -713,7 +715,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -713,7 +715,7 @@ class WeComCustomerGroupOrchestrationService:
end_time=None, end_time=None,
page=1, page=1,
page_size=self.page_size, page_size=self.page_size,
contact_type=None, contact_type=WECOM_CUSTOMER_CONTACT_TYPE,
) )
for item in payload.get("items") or []: for item in payload.get("items") or []:
if str(item.get("contact_id") or "") == customer_contact_id: if str(item.get("contact_id") or "") == customer_contact_id:
......
...@@ -10,7 +10,6 @@ from sqlalchemy.orm import Session ...@@ -10,7 +10,6 @@ from sqlalchemy.orm import Session
from app.model.wecom_sync import ( from app.model.wecom_sync import (
WeComBot, WeComBot,
WeComCustomerGroup, WeComCustomerGroup,
WeComGroup,
WeComJobConfig, WeComJobConfig,
WeComMessage, WeComMessage,
WeComSyncCheckpoint, WeComSyncCheckpoint,
...@@ -54,9 +53,6 @@ class WeComSyncClient(Protocol): ...@@ -54,9 +53,6 @@ class WeComSyncClient(Protocol):
def list_bots(self, *, page: int, page_size: int) -> dict[str, Any]: 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( def list_customers(
self, self,
*, *,
...@@ -142,11 +138,14 @@ class WeComSyncService: ...@@ -142,11 +138,14 @@ class WeComSyncService:
end_time: datetime | None, end_time: datetime | None,
) -> dict[str, int]: ) -> dict[str, int]:
bots = self.sync_bots_full() 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: if bot_ids is not None:
allowed_bot_ids = {str(bot_id) for bot_id in bot_ids if str(bot_id).strip()} 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] 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( messages = self.sync_messages_incremental(
bot_ids=resolved_bot_ids, bot_ids=resolved_bot_ids,
start_time=start_time, start_time=start_time,
...@@ -154,7 +153,6 @@ class WeComSyncService: ...@@ -154,7 +153,6 @@ class WeComSyncService:
) )
return { return {
"bots": bots, "bots": bots,
"groups": groups,
"messages": messages, "messages": messages,
} }
...@@ -163,6 +161,8 @@ class WeComSyncService: ...@@ -163,6 +161,8 @@ class WeComSyncService:
latest_time: datetime | None = None latest_time: datetime | None = None
latest_id: str | 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)): 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) bot = self._upsert_bot(item)
count += 1 count += 1
candidate_time = _parse_dt(item.get("updated_at")) or _parse_dt(item.get("created_at")) candidate_time = _parse_dt(item.get("updated_at")) or _parse_dt(item.get("created_at"))
...@@ -170,26 +170,6 @@ class WeComSyncService: ...@@ -170,26 +170,6 @@ class WeComSyncService:
self._complete_checkpoint("bots", "global", latest_time, latest_id) self._complete_checkpoint("bots", "global", latest_time, latest_id)
return count 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( def sync_messages_incremental(
self, self,
*, *,
...@@ -241,30 +221,34 @@ class WeComSyncService: ...@@ -241,30 +221,34 @@ class WeComSyncService:
bot_name or bot_id, bot_name or bot_id,
bot_id, bot_id,
) )
checkpoint = self._get_checkpoint("messages", f"bot:{bot_code}") for group in bound_groups:
window = self._resolve_message_window(checkpoint, start_time, end_time) group_id = str(group.group_id or "").strip()
latest_time = checkpoint.last_sync_time if checkpoint else None if not group_id:
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):
continue continue
message = self._upsert_message(item) checkpoint = self._get_checkpoint("messages", f"group:{group_id}")
total += 1 window = self._resolve_message_window(checkpoint, start_time, end_time)
latest_time, latest_id = self._max_key(latest_time, latest_id, message.msg_time, message.msg_id) latest_time = checkpoint.last_sync_time if checkpoint else None
self._complete_checkpoint("messages", f"bot:{bot_code}", latest_time, latest_id) 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 return total
def dispatch_pending_messages(self, *, bot_ids: Iterable[str] | None = None) -> int: def dispatch_pending_messages(self, *, bot_ids: Iterable[str] | None = None) -> int:
...@@ -360,32 +344,6 @@ class WeComSyncService: ...@@ -360,32 +344,6 @@ class WeComSyncService:
self.db.flush() self.db.flush()
return record 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: 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")) 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 "") msg_id = str(data.get("msg_id") or "")
...@@ -539,3 +497,6 @@ class WeComSyncService: ...@@ -539,3 +497,6 @@ class WeComSyncService:
if isinstance(value, str): if isinstance(value, str):
return value.lower() in {"1", "true", "yes", "online", "enable"} return value.lower() in {"1", "true", "yes", "online", "enable"}
return bool(value) 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 ...@@ -25,7 +25,6 @@ from app.model.position_tag import PositionTag
from app.model.wecom_sync import ( from app.model.wecom_sync import (
WeComBot, WeComBot,
WeComCustomerGroup, WeComCustomerGroup,
WeComGroup,
WeComGroupCreateRequest, WeComGroupCreateRequest,
WeComMessage, WeComMessage,
) )
...@@ -60,9 +59,6 @@ class FakeClient: ...@@ -60,9 +59,6 @@ class FakeClient:
def list_contacts(self, *, bot_id: str, page: int, page_size: int): def list_contacts(self, *, bot_id: str, page: int, page_size: int):
return {'items': [], 'meta': {'total': 0, 'page': 1, 'page_size': page_size}} 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): 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 = { self.last_list_customers_kwargs = {
'bot_id': bot_id, 'bot_id': bot_id,
...@@ -283,32 +279,6 @@ def test_list_new_customers_returns_candidates_without_writing_groups(): ...@@ -283,32 +279,6 @@ def test_list_new_customers_returns_candidates_without_writing_groups():
db.close() 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(): def test_list_new_customers_skips_customer_when_group_already_exists():
db = _setup_db() db = _setup_db()
bot, managed, _, _ = _seed_group_context(db) bot, managed, _, _ = _seed_group_context(db)
...@@ -841,11 +811,6 @@ def test_get_group_create_request_status_returns_request_progress(): ...@@ -841,11 +811,6 @@ def test_get_group_create_request_status_returns_request_progress():
'contact_type': None, 'contact_type': None,
'keyword': 'biz-group-001', '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() db.close()
......
...@@ -22,7 +22,7 @@ class FakeApiSyncService: ...@@ -22,7 +22,7 @@ class FakeApiSyncService:
def sync_all_full(self, *, message_start_time, message_end_time): def sync_all_full(self, *, message_start_time, message_end_time):
self.full_called = True 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): def sync_messages_incremental(self, *, bot_ids, start_time, end_time):
self.incremental_called = True self.incremental_called = True
......
...@@ -10,7 +10,6 @@ from app.infrastructure.database import Base ...@@ -10,7 +10,6 @@ from app.infrastructure.database import Base
from app.model.wecom_sync import ( from app.model.wecom_sync import (
WeComBot, WeComBot,
WeComCustomerGroup, WeComCustomerGroup,
WeComGroup,
WeComMessage, WeComMessage,
WeComSyncCheckpoint, WeComSyncCheckpoint,
) )
...@@ -30,15 +29,11 @@ def _dt(value: str) -> datetime: ...@@ -30,15 +29,11 @@ def _dt(value: str) -> datetime:
@dataclass @dataclass
class FakeWeComSyncClient(WeComSyncClient): class FakeWeComSyncClient(WeComSyncClient):
bots: list[dict[str, Any]] = field(default_factory=list) 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) 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]: def list_bots(self, *, page: int, page_size: int) -> dict[str, Any]:
return _paginate(self.bots, page, page_size) 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( def list_messages(
self, self,
*, *,
...@@ -91,7 +86,6 @@ def db(): ...@@ -91,7 +86,6 @@ def db():
session.query(WeComSyncCheckpoint).delete() session.query(WeComSyncCheckpoint).delete()
session.query(WeComMessage).delete() session.query(WeComMessage).delete()
session.query(WeComCustomerGroup).delete() session.query(WeComCustomerGroup).delete()
session.query(WeComGroup).delete()
session.query(WeComBot).delete() session.query(WeComBot).delete()
session.commit() session.commit()
yield session yield session
...@@ -114,6 +108,7 @@ def test_sync_wecom_bots_groups_messages_ignores_legacy_contact_payloads(db): ...@@ -114,6 +108,7 @@ def test_sync_wecom_bots_groups_messages_ignores_legacy_contact_payloads(db):
"bot_id": "RBT001", "bot_id": "RBT001",
"bot_code": "wt_ww:RBT001", "bot_code": "wt_ww:RBT001",
"bot_name": "销售机器人", "bot_name": "销售机器人",
"online": 1,
} }
], ],
) )
...@@ -125,12 +120,12 @@ def test_sync_wecom_bots_groups_messages_ignores_legacy_contact_payloads(db): ...@@ -125,12 +120,12 @@ def test_sync_wecom_bots_groups_messages_ignores_legacy_contact_payloads(db):
end_time=_dt("2026-05-21T10:00:00Z"), 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() 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( client = FakeWeComSyncClient(
bots=[ bots=[
{ {
...@@ -138,21 +133,52 @@ def test_sync_wecom_bots_groups_messages_syncs_bots_groups_messages(db): ...@@ -138,21 +133,52 @@ def test_sync_wecom_bots_groups_messages_syncs_bots_groups_messages(db):
"bot_id": "RBT001", "bot_id": "RBT001",
"bot_code": "wt_ww:RBT001", "bot_code": "wt_ww:RBT001",
"bot_name": "销售机器人", "bot_name": "销售机器人",
"updated_at": "2026-05-21T09:00:00Z", "online": 1,
} }
], ],
groups_by_bot={ messages_by_bot={
"RBT001": [ "RBT001": [
{ {
"channel": "wt_ww", "channel": "wt_ww",
"bot_id": "RBT001", "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_id": "wr_001",
"contact_name": "销售服务群", "bot_send": 0,
"contact_type": "ww_group_external",
"updated_at": "2026-05-21T09:02:00Z",
} }
] ]
}, },
)
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={ messages_by_bot={
"RBT001": [ "RBT001": [
{ {
...@@ -174,6 +200,21 @@ def test_sync_wecom_bots_groups_messages_syncs_bots_groups_messages(db): ...@@ -174,6 +200,21 @@ def test_sync_wecom_bots_groups_messages_syncs_bots_groups_messages(db):
) )
dispatcher = RecordingDispatcher() dispatcher = RecordingDispatcher()
service = WeComSyncService(db, client, dispatcher) 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( result = service.sync_wecom_bots_groups_messages(
bot_ids=["RBT001"], bot_ids=["RBT001"],
...@@ -181,9 +222,8 @@ def test_sync_wecom_bots_groups_messages_syncs_bots_groups_messages(db): ...@@ -181,9 +222,8 @@ def test_sync_wecom_bots_groups_messages_syncs_bots_groups_messages(db):
end_time=_dt("2026-05-21T10:00:00Z"), 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(WeComBot).count() == 1
assert db.query(WeComGroup).count() == 1
assert db.query(WeComMessage).count() == 1 assert db.query(WeComMessage).count() == 1
assert dispatcher.dispatched == ["msg_001"] assert dispatcher.dispatched == ["msg_001"]
...@@ -202,19 +242,6 @@ def test_full_sync_persists_resources_and_dispatches_non_bot_messages(db): ...@@ -202,19 +242,6 @@ def test_full_sync_persists_resources_and_dispatches_non_bot_messages(db):
"updated_at": "2026-05-21T09:00:00Z", "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={ messages_by_bot={
"RBT001": [ "RBT001": [
{ {
...@@ -251,6 +278,21 @@ def test_full_sync_persists_resources_and_dispatches_non_bot_messages(db): ...@@ -251,6 +278,21 @@ def test_full_sync_persists_resources_and_dispatches_non_bot_messages(db):
) )
dispatcher = RecordingDispatcher() dispatcher = RecordingDispatcher()
service = WeComSyncService(db, client, dispatcher) 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( result = service.sync_all_full(
message_start_time=_dt("2026-05-21T09:00:00Z"), 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): ...@@ -258,11 +300,9 @@ def test_full_sync_persists_resources_and_dispatches_non_bot_messages(db):
) )
assert result["bots"] == 1 assert result["bots"] == 1
assert result["groups"] == 1
assert result["messages"] == 2 assert result["messages"] == 2
assert "contacts" not in result assert "contacts" not in result
assert db.query(WeComBot).count() == 1 assert db.query(WeComBot).count() == 1
assert db.query(WeComGroup).count() == 1
assert db.query(WeComMessage).count() == 2 assert db.query(WeComMessage).count() == 2
assert dispatcher.dispatched == ["msg_001"] assert dispatcher.dispatched == ["msg_001"]
...@@ -277,6 +317,34 @@ def test_full_sync_persists_resources_and_dispatches_non_bot_messages(db): ...@@ -277,6 +317,34 @@ def test_full_sync_persists_resources_and_dispatches_non_bot_messages(db):
assert len(checkpoints) == 3 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): def test_incremental_sync_uses_time_and_msg_id_boundary_without_duplicates(db):
client = FakeWeComSyncClient( client = FakeWeComSyncClient(
bots=[ bots=[
...@@ -285,6 +353,7 @@ def test_incremental_sync_uses_time_and_msg_id_boundary_without_duplicates(db): ...@@ -285,6 +353,7 @@ def test_incremental_sync_uses_time_and_msg_id_boundary_without_duplicates(db):
"bot_id": "RBT001", "bot_id": "RBT001",
"bot_code": "wt_ww:RBT001", "bot_code": "wt_ww:RBT001",
"bot_name": "销售机器人", "bot_name": "销售机器人",
"online": 1,
} }
], ],
messages_by_bot={ messages_by_bot={
...@@ -319,6 +388,21 @@ def test_incremental_sync_uses_time_and_msg_id_boundary_without_duplicates(db): ...@@ -319,6 +388,21 @@ def test_incremental_sync_uses_time_and_msg_id_boundary_without_duplicates(db):
}, },
) )
service = WeComSyncService(db, client, RecordingDispatcher()) 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_bots_full()
service.sync_messages_incremental( service.sync_messages_incremental(
...@@ -361,6 +445,7 @@ def test_dispatch_failure_marks_message_failed_without_losing_payload(db): ...@@ -361,6 +445,7 @@ def test_dispatch_failure_marks_message_failed_without_losing_payload(db):
"bot_id": "RBT001", "bot_id": "RBT001",
"bot_code": "wt_ww:RBT001", "bot_code": "wt_ww:RBT001",
"bot_name": "销售机器人", "bot_name": "销售机器人",
"online": 1,
} }
], ],
messages_by_bot={ messages_by_bot={
...@@ -384,6 +469,21 @@ def test_dispatch_failure_marks_message_failed_without_losing_payload(db): ...@@ -384,6 +469,21 @@ def test_dispatch_failure_marks_message_failed_without_losing_payload(db):
) )
dispatcher = RecordingDispatcher(fail_msg_ids={"msg_fail"}) dispatcher = RecordingDispatcher(fail_msg_ids={"msg_fail"})
service = WeComSyncService(db, client, dispatcher) 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_bots_full()
service.sync_messages_incremental( 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!