Commit fd892279 by imwangxiaozhou

feat(wecom-customer-group): 调整企业微信群名规则并新增消息发送者自动推断逻辑

重构企业微信群名生成逻辑,将原有的基于客户名称+`-service`的格式改为基于职位名称+「服务群」的格式;新增消息发送状态自动推断方法,替代直接从参数获取bot_send的方式,优化业务判断准确性;新增无效群组状态过滤逻辑,解析客户联系ID时排除异常状态的群组;更新测试用例适配新的群名生成规则。
1 parent 7dfc5f45
......@@ -509,7 +509,7 @@ class WeComCustomerGroupOrchestrationService:
resolved_member_list = list(dict.fromkeys([item.contact_id.strip(), *member_bot_ids]))
biz_rela_no = f"biz-group-{int(_utcnow().timestamp() * 1000)}-{uuid4().hex[:6]}"
group_name = self._build_group_name(item.customer_name, item.contact_id)
group_name = self._build_group_name(item.position_name, item.contact_id)
logger.info(
format_job_log(
"机器人[%s]:我准备发起建群啦!!客户=%s(%s),群名=%s,群成员=%s"
......@@ -824,9 +824,9 @@ class WeComCustomerGroupOrchestrationService:
record.is_deleted = False
self.db.flush()
def _build_group_name(self, customer_name: str | None, customer_contact_id: str) -> str:
base_name = str(customer_name or "").strip() or customer_contact_id
return f"{base_name}-service"
def _build_group_name(self, position_name: str | None, customer_contact_id: str) -> str:
base_name = str(position_name or "").strip() or customer_contact_id
return f"{base_name}服务群"
def _resolve_position_member_bots(self, *, position_id: int) -> list[WeComNewCustomerItem.MemberBotItem]:
agents = (
......
......@@ -19,6 +19,8 @@ from app.model.wecom_sync import (
logger = logging.getLogger(__name__)
INVALID_GROUP_STATUSES = {"failed", "timeout", "invalid"}
def _utcnow() -> datetime:
return datetime.now(timezone.utc)
......@@ -404,7 +406,7 @@ class WeComSyncService:
record.sender_name = data.get("sender_name")
record.contact_id = data.get("contact_id")
record.session_title = data.get("session_title")
record.bot_send = bool(data.get("bot_send"))
record.bot_send = self._infer_message_bot_send(data)
record.payload = dict(data)
if not record.bot_send and record.dispatch_status is None:
record.dispatch_status = "pending"
......@@ -412,6 +414,57 @@ class WeComSyncService:
self.db.flush()
return record
def _infer_message_bot_send(self, data: dict[str, Any]) -> bool:
"""
本地判定消息是否为“机器人/非客户发送”。
规则:
- 仅当发送者为该群绑定的客户本人时,视为非机器人发送(bot_send=False,需要分发);
- 群内其他任何发送者一律视为机器人/非客户(bot_send=True,不分发);
- 若无法解析该消息所属的客户绑定信息,默认视为 bot_send=True(安全策略)。
"""
bot_id = str(data.get("bot_id") or "").strip()
contact_id = str(data.get("contact_id") or "").strip()
sender_id = str(data.get("sender_id") or "").strip()
if not bot_id or not contact_id or not sender_id:
logger.warning(
format_job_log(
"bot_send 判定缺少关键字段,默认视为 bot_send=True: bot_id=%s contact_id=%s sender_id=%s msg_id=%s"
% (bot_id or "-", contact_id or "-", sender_id or "-", str(data.get("msg_id") or "-"))
)
)
return True
customer_contact_id = self._resolve_customer_contact_id(bot_id=bot_id, group_contact_id=contact_id)
if not customer_contact_id:
logger.warning(
format_job_log(
"未找到群绑定客户信息,默认视为 bot_send=True: bot_id=%s contact_id=%s sender_id=%s msg_id=%s"
% (bot_id, contact_id, sender_id, str(data.get("msg_id") or "-"))
)
)
return True
# 只有客户本人发言才需要分发(bot_send=False)
return sender_id != customer_contact_id
def _resolve_customer_contact_id(self, *, bot_id: str, group_contact_id: str) -> str | None:
record = (
self.db.query(WeComCustomerGroup)
.filter(
WeComCustomerGroup.bot_id == bot_id,
WeComCustomerGroup.group_id == group_contact_id,
WeComCustomerGroup.is_deleted == False,
)
.order_by(WeComCustomerGroup.id.asc())
.first()
)
if record is None:
return None
if record.group_status in INVALID_GROUP_STATUSES:
return None
return str(record.customer_contact_id or "").strip() or None
def _dispatch_message_if_needed(self, message: WeComMessage) -> None:
if message.bot_send:
return
......
......@@ -699,7 +699,7 @@ def test_sync_customer_groups_invalidates_timeout_pending_request_before_recreat
assert rows[1].member_snapshot['member_list'] == ['cust_1', 'managed_1']
assert client.last_create_group_kwargs == {
'bot_code': 'wt_ww:bot_1',
'group_name': 'alice-service',
'group_name': 'store-sales服务群',
'member_list': ['cust_1', 'managed_1'],
'group_announcement': None,
'biz_rela_no': rows[1].biz_rela_no,
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!