Commit 3d3f6a2d by imwangxiaozhou Committed by 胡悦

feat(wecom-customer-group): 新增配置项与建群限流,重构客户扫描逻辑

新增企微同步配置项customer_contact_type和max_group_creates_per_bot_per_job,并同步到Pydantic设置模型
重构新客户扫描逻辑,新增全量对比与预览模式,废弃旧的增量扫描与checkpoint逻辑
为建群请求添加单机器人每任务建群数量限制,基于配置项控制
将硬编码的客户联系类型改为从配置读取,新增deleted群组状态到无效状态集合
支持自动清理远端已不存在的本地客户数据
调整list_new_customers接口默认开启dry_run模式,避免意外写入数据
1 parent 3218ac85
...@@ -33,6 +33,8 @@ class IMSettings(BaseModel): ...@@ -33,6 +33,8 @@ class IMSettings(BaseModel):
class WeComSyncSettings(BaseModel): class WeComSyncSettings(BaseModel):
base_url: str = "http://192.168.3.84:8600/webim" base_url: str = "http://192.168.3.84:8600/webim"
api_key: str = "" api_key: str = ""
customer_contact_type: str = "ww_customer"
max_group_creates_per_bot_per_job: int = 2
class DownstreamChatSettings(BaseModel): class DownstreamChatSettings(BaseModel):
......
...@@ -37,7 +37,7 @@ from app.service.wecom_sync_service import WeComSyncClient, WeComSyncService, _p ...@@ -37,7 +37,7 @@ from app.service.wecom_sync_service import WeComSyncClient, WeComSyncService, _p
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
PENDING_REQUEST_TIMEOUT = timedelta(minutes=10) PENDING_REQUEST_TIMEOUT = timedelta(minutes=10)
INVALID_GROUP_STATUSES = {"failed", "timeout", "invalid"} INVALID_GROUP_STATUSES = {"failed", "timeout", "invalid", "deleted"}
WECOM_CUSTOMER_CONTACT_TYPE = "ww_customer" WECOM_CUSTOMER_CONTACT_TYPE = "ww_customer"
GROUP_CREATE_TIMEOUT_WEBHOOK_URL = ( GROUP_CREATE_TIMEOUT_WEBHOOK_URL = (
"https://qyapi.weixin.qq.com/cgi-bin/webhook/send" "https://qyapi.weixin.qq.com/cgi-bin/webhook/send"
...@@ -194,6 +194,9 @@ class WeComCustomerGroupOrchestrationService: ...@@ -194,6 +194,9 @@ class WeComCustomerGroupOrchestrationService:
self.batch_dispatcher = batch_dispatcher or NoopGroupMessageBatchDispatcher() self.batch_dispatcher = batch_dispatcher or NoopGroupMessageBatchDispatcher()
self.webhook_notifier = webhook_notifier or WeComWebhookNotifier() self.webhook_notifier = webhook_notifier or WeComWebhookNotifier()
self.page_size = page_size self.page_size = page_size
settings = ConfigLoader().load_settings()
self._customer_contact_type = settings.wecom_sync.customer_contact_type
self._max_creates_per_bot = settings.wecom_sync.max_group_creates_per_bot_per_job
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]:
resolved = self.resolve_pending_requests(bot_ids=bot_ids) resolved = self.resolve_pending_requests(bot_ids=bot_ids)
...@@ -203,7 +206,10 @@ class WeComCustomerGroupOrchestrationService: ...@@ -203,7 +206,10 @@ class WeComCustomerGroupOrchestrationService:
"created": created, "created": created,
} }
def scan_new_customers(self, *, bot_ids: Iterable[str] | None = None) -> list[WeComNewCustomerItem]: def scan_new_customers(self, *, bot_ids: Iterable[str] | None = None, dry_run: bool = False) -> list[WeComNewCustomerItem]:
if not dry_run:
return self.scan_customers_full_compare(bot_ids=bot_ids)
if bot_ids: if bot_ids:
resolved_bot_ids = [str(item).strip() for item in bot_ids if str(item).strip()] resolved_bot_ids = [str(item).strip() for item in bot_ids if str(item).strip()]
else: else:
...@@ -222,13 +228,228 @@ class WeComCustomerGroupOrchestrationService: ...@@ -222,13 +228,228 @@ 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): for item in self._preview_bot_customers_full(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)
items.append(item) items.append(item)
return items return items
def scan_customers_full_compare(self, *, bot_ids: Iterable[str] | None = None) -> list[WeComNewCustomerItem]:
if bot_ids:
resolved_bot_ids = [str(item).strip() for item in bot_ids if str(item).strip()]
else:
resolved_bot_ids = [
bot.bot_id
for bot in (
self.db.query(WeComBot)
.join(QrcodeChannel, QrcodeChannel.wecom_bot_id == WeComBot.id)
.filter(WeComBot.bot_id.isnot(None))
.order_by(WeComBot.id.asc())
.all()
)
if bot.bot_id
]
new_customers: list[WeComNewCustomerItem] = []
seen_contact_ids: set[str] = set()
for bot_id in resolved_bot_ids:
for item in self._sync_bot_customers_full(bot_id=bot_id):
if item.contact_id in seen_contact_ids:
continue
seen_contact_ids.add(item.contact_id)
new_customers.append(item)
return new_customers
def _preview_bot_customers_full(self, bot_id: str) -> list[WeComNewCustomerItem]:
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == bot_id).first()
if bot is None:
return []
qrcode = self.db.query(QrcodeChannel).filter(QrcodeChannel.wecom_bot_id == bot.id).first()
if qrcode is None:
return []
position = self.db.query(PositionTag).filter(PositionTag.id == qrcode.position_id).first()
if position is None:
return []
remote_set: dict[str, dict] = {}
page = 1
while True:
payload = self.client.list_customers(
bot_id=bot.bot_id,
start_time=None,
end_time=None,
page=page,
page_size=self.page_size,
contact_type=self._customer_contact_type,
)
items = payload.get("items") or []
for item in items:
cid = str(item.get("contact_id") or "")
if cid:
remote_set[cid] = item
if not items:
break
meta = payload.get("meta") or {}
total = meta.get("total")
page_size = meta.get("page_size") or self.page_size
if total is not None and page * page_size >= total:
break
page += 1
local_records = (
self.db.query(WeComCustomerGroup)
.filter(
WeComCustomerGroup.bot_id == bot_id,
WeComCustomerGroup.is_deleted == False,
)
.all()
)
local_set = {r.customer_contact_id: r for r in local_records}
member_bots = self._resolve_position_member_bots(position_id=position.id)
can_create_group = bool(member_bots)
skip_reason = None if can_create_group else "no_members"
items: list[WeComNewCustomerItem] = []
for cid, item in remote_set.items():
if cid in local_set:
continue
customer_name = str(item.get("contact_name") or item.get("display_name") or "")
items.append(
WeComNewCustomerItem(
bot_id=bot.bot_id,
contact_id=cid,
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 _sync_bot_customers_full(self, bot_id: str) -> list[WeComNewCustomerItem]:
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == bot_id).first()
if bot is None:
logger.warning(format_job_log("跳过全量客户对比:bot_id=%s 不存在" % bot_id))
return []
qrcode = self.db.query(QrcodeChannel).filter(QrcodeChannel.wecom_bot_id == bot.id).first()
if qrcode is None:
logger.info(format_job_log("跳过全量客户对比:bot_id=%s 未绑定渠道活码" % bot_id))
return []
position = self.db.query(PositionTag).filter(PositionTag.id == qrcode.position_id).first()
if position is None:
logger.warning(format_job_log("跳过全量客户对比:bot_id=%s 绑定的渠道活码缺少岗位" % bot_id))
return []
remote_set: dict[str, dict] = {}
page = 1
while True:
payload = self.client.list_customers(
bot_id=bot.bot_id,
start_time=None,
end_time=None,
page=page,
page_size=self.page_size,
contact_type=self._customer_contact_type,
)
items = payload.get("items") or []
for item in items:
cid = str(item.get("contact_id") or "")
if cid:
remote_set[cid] = item
if not items:
break
meta = payload.get("meta") or {}
total = meta.get("total")
page_size = meta.get("page_size") or self.page_size
if total is not None and page * page_size >= total:
break
page += 1
local_records = (
self.db.query(WeComCustomerGroup)
.filter(
WeComCustomerGroup.bot_id == bot_id,
WeComCustomerGroup.is_deleted == False,
)
.all()
)
local_set = {r.customer_contact_id: r for r in local_records}
new_customers: list[WeComNewCustomerItem] = []
member_bots = self._resolve_position_member_bots(position_id=position.id)
can_create_group = bool(member_bots)
for cid, item in remote_set.items():
if cid in local_set:
record = local_set[cid]
customer_name = str(item.get("contact_name") or item.get("display_name") or "")
if record.customer_name != customer_name:
record.customer_name = customer_name
continue
customer_name = str(item.get("contact_name") or item.get("display_name") or "")
new_record = WeComCustomerGroup(
customer_contact_id=cid,
customer_name=customer_name,
bot_id=bot.bot_id,
bot_code=bot.bot_code,
group_name=None,
group_status="pending",
member_bot_ids=[m.bot_id for m in member_bots],
is_deleted=False,
)
self.db.add(new_record)
self.db.flush()
logger.info(
format_job_log(
"全量对比发现新客户:机器人[%s] 发现客户[%s](contact_id=%s)"
% (bot.bot_name or bot.bot_id, customer_name or "-", cid)
)
)
new_customers.append(
WeComNewCustomerItem(
bot_id=bot.bot_id,
contact_id=cid,
customer_name=customer_name,
position_id=position.id,
position_name=position.name,
already_bound=False,
can_create_group=can_create_group,
skip_reason=None if can_create_group else "no_members",
member_bots=member_bots,
)
)
for cid, record in local_set.items():
if cid not in remote_set:
record.is_deleted = True
record.group_status = "deleted"
logger.info(
format_job_log(
"全量对比剔除客户:机器人[%s] 客户[%s](contact_id=%s) 已不存在远端,标记为 deleted"
% (bot.bot_name or bot.bot_id, record.customer_name or "-", cid)
)
)
if remote_set or local_set:
self.db.flush()
return new_customers
def _resolved_contact_type(self) -> str:
return self._customer_contact_type
def _get_max_creates_per_bot(self) -> int:
return self._max_creates_per_bot
def submit_group_create_requests(self, *, items: list[WeComGroupCreateRequestItem]) -> list[WeComGroupCreateBatchItemResult]: def submit_group_create_requests(self, *, items: list[WeComGroupCreateRequestItem]) -> list[WeComGroupCreateBatchItemResult]:
results: list[WeComGroupCreateBatchItemResult] = [] results: list[WeComGroupCreateBatchItemResult] = []
dirty = False dirty = False
...@@ -295,14 +516,30 @@ class WeComCustomerGroupOrchestrationService: ...@@ -295,14 +516,30 @@ 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
candidates = self._collect_group_create_candidates(bot_ids=bot_ids) candidates = self._collect_group_create_candidates(bot_ids=bot_ids)
bot_groups: dict[str, list[WeComNewCustomerItem]] = defaultdict(list)
for item in candidates: for item in candidates:
bot_groups[item.bot_id].append(item)
for bot_id, items in bot_groups.items():
pending_count = 0
for item in items:
if not item.can_create_group: if not item.can_create_group:
continue continue
if pending_count >= self._max_creates_per_bot:
logger.info(
format_job_log(
"跳过建群:机器人[%s] 本次已达到上限 %s 个,跳过剩余客户"
% (bot_id, self._max_creates_per_bot)
)
)
break
if not self._should_create_customer_group(bot_id=item.bot_id, customer_contact_id=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(bot_id=item.bot_id, customer_contact_id=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)
pending_count += 1
created += 1 created += 1
if created: if created:
...@@ -720,6 +957,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -720,6 +957,7 @@ class WeComCustomerGroupOrchestrationService:
) )
def _scan_new_customers_for_bot(self, *, bot_id: str) -> list[WeComNewCustomerItem]: def _scan_new_customers_for_bot(self, *, bot_id: str) -> list[WeComNewCustomerItem]:
"""已废弃,由 _sync_bot_customers_full 替代。保留仅用于兼容历史调用。"""
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:
logger.warning(format_job_log("跳过新客户扫描:bot_id=%s 不存在" % bot_id)) logger.warning(format_job_log("跳过新客户扫描:bot_id=%s 不存在" % bot_id))
...@@ -852,6 +1090,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -852,6 +1090,7 @@ class WeComCustomerGroupOrchestrationService:
return items return items
def _get_customer_checkpoint(self, *, bot_id: str) -> WeComSyncCheckpoint | None: def _get_customer_checkpoint(self, *, bot_id: str) -> WeComSyncCheckpoint | None:
"""已废弃,由 scan_customers_full_compare 替代,不再需要 checkpoint。"""
return self.sync_service._get_effective_checkpoint("customers", f"bot:{bot_id}") return self.sync_service._get_effective_checkpoint("customers", f"bot:{bot_id}")
def _complete_customer_checkpoint( def _complete_customer_checkpoint(
...@@ -861,6 +1100,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -861,6 +1100,7 @@ class WeComCustomerGroupOrchestrationService:
last_sync_time: datetime | None, last_sync_time: datetime | None,
last_external_id: str | None, last_external_id: str | None,
) -> None: ) -> None:
"""已废弃,由 scan_customers_full_compare 替代,不再需要 checkpoint。"""
self.sync_service._complete_checkpoint( self.sync_service._complete_checkpoint(
"customers", "customers",
f"bot:{bot_id}", f"bot:{bot_id}",
...@@ -1074,7 +1314,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -1074,7 +1314,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=WECOM_CUSTOMER_CONTACT_TYPE, contact_type=self._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:
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!